]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - fs/ext4/extents.c
ext4: Add checks to validate extent entries.
[mirror_ubuntu-artful-kernel.git] / fs / ext4 / extents.c
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
4 *
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public Licens
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
21 */
22
23 /*
24 * Extents support for EXT4
25 *
26 * TODO:
27 * - ext4*_error() should be used in some situations
28 * - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29 * - smart tree reduction
30 */
31
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/jbd2.h>
36 #include <linux/highuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/quotaops.h>
39 #include <linux/string.h>
40 #include <linux/slab.h>
41 #include <linux/falloc.h>
42 #include <asm/uaccess.h>
43 #include <linux/fiemap.h>
44 #include "ext4_jbd2.h"
45 #include "ext4_extents.h"
46
47
48 /*
49 * ext_pblock:
50 * combine low and high parts of physical block number into ext4_fsblk_t
51 */
52 static ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
53 {
54 ext4_fsblk_t block;
55
56 block = le32_to_cpu(ex->ee_start_lo);
57 block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
58 return block;
59 }
60
61 /*
62 * idx_pblock:
63 * combine low and high parts of a leaf physical block number into ext4_fsblk_t
64 */
65 ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
66 {
67 ext4_fsblk_t block;
68
69 block = le32_to_cpu(ix->ei_leaf_lo);
70 block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
71 return block;
72 }
73
74 /*
75 * ext4_ext_store_pblock:
76 * stores a large physical block number into an extent struct,
77 * breaking it into parts
78 */
79 void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
80 {
81 ex->ee_start_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
82 ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
83 }
84
85 /*
86 * ext4_idx_store_pblock:
87 * stores a large physical block number into an index struct,
88 * breaking it into parts
89 */
90 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
91 {
92 ix->ei_leaf_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
93 ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
94 }
95
96 static int ext4_ext_journal_restart(handle_t *handle, int needed)
97 {
98 int err;
99
100 if (!ext4_handle_valid(handle))
101 return 0;
102 if (handle->h_buffer_credits > needed)
103 return 0;
104 err = ext4_journal_extend(handle, needed);
105 if (err <= 0)
106 return err;
107 return ext4_journal_restart(handle, needed);
108 }
109
110 /*
111 * could return:
112 * - EROFS
113 * - ENOMEM
114 */
115 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
116 struct ext4_ext_path *path)
117 {
118 if (path->p_bh) {
119 /* path points to block */
120 return ext4_journal_get_write_access(handle, path->p_bh);
121 }
122 /* path points to leaf/index in inode body */
123 /* we use in-core data, no need to protect them */
124 return 0;
125 }
126
127 /*
128 * could return:
129 * - EROFS
130 * - ENOMEM
131 * - EIO
132 */
133 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
134 struct ext4_ext_path *path)
135 {
136 int err;
137 if (path->p_bh) {
138 /* path points to block */
139 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
140 } else {
141 /* path points to leaf/index in inode body */
142 err = ext4_mark_inode_dirty(handle, inode);
143 }
144 return err;
145 }
146
147 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
148 struct ext4_ext_path *path,
149 ext4_lblk_t block)
150 {
151 struct ext4_inode_info *ei = EXT4_I(inode);
152 ext4_fsblk_t bg_start;
153 ext4_fsblk_t last_block;
154 ext4_grpblk_t colour;
155 ext4_group_t block_group;
156 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
157 int depth;
158
159 if (path) {
160 struct ext4_extent *ex;
161 depth = path->p_depth;
162
163 /* try to predict block placement */
164 ex = path[depth].p_ext;
165 if (ex)
166 return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
167
168 /* it looks like index is empty;
169 * try to find starting block from index itself */
170 if (path[depth].p_bh)
171 return path[depth].p_bh->b_blocknr;
172 }
173
174 /* OK. use inode's group */
175 block_group = ei->i_block_group;
176 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
177 /*
178 * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
179 * block groups per flexgroup, reserve the first block
180 * group for directories and special files. Regular
181 * files will start at the second block group. This
182 * tends to speed up directory access and improves
183 * fsck times.
184 */
185 block_group &= ~(flex_size-1);
186 if (S_ISREG(inode->i_mode))
187 block_group++;
188 }
189 bg_start = (block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
190 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
191 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
192
193 /*
194 * If we are doing delayed allocation, we don't need take
195 * colour into account.
196 */
197 if (test_opt(inode->i_sb, DELALLOC))
198 return bg_start;
199
200 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
201 colour = (current->pid % 16) *
202 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
203 else
204 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
205 return bg_start + colour + block;
206 }
207
208 /*
209 * Allocation for a meta data block
210 */
211 static ext4_fsblk_t
212 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
213 struct ext4_ext_path *path,
214 struct ext4_extent *ex, int *err)
215 {
216 ext4_fsblk_t goal, newblock;
217
218 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
219 newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
220 return newblock;
221 }
222
223 static int ext4_ext_space_block(struct inode *inode)
224 {
225 int size;
226
227 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
228 / sizeof(struct ext4_extent);
229 #ifdef AGGRESSIVE_TEST
230 if (size > 6)
231 size = 6;
232 #endif
233 return size;
234 }
235
236 static int ext4_ext_space_block_idx(struct inode *inode)
237 {
238 int size;
239
240 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
241 / sizeof(struct ext4_extent_idx);
242 #ifdef AGGRESSIVE_TEST
243 if (size > 5)
244 size = 5;
245 #endif
246 return size;
247 }
248
249 static int ext4_ext_space_root(struct inode *inode)
250 {
251 int size;
252
253 size = sizeof(EXT4_I(inode)->i_data);
254 size -= sizeof(struct ext4_extent_header);
255 size /= sizeof(struct ext4_extent);
256 #ifdef AGGRESSIVE_TEST
257 if (size > 3)
258 size = 3;
259 #endif
260 return size;
261 }
262
263 static int ext4_ext_space_root_idx(struct inode *inode)
264 {
265 int size;
266
267 size = sizeof(EXT4_I(inode)->i_data);
268 size -= sizeof(struct ext4_extent_header);
269 size /= sizeof(struct ext4_extent_idx);
270 #ifdef AGGRESSIVE_TEST
271 if (size > 4)
272 size = 4;
273 #endif
274 return size;
275 }
276
277 /*
278 * Calculate the number of metadata blocks needed
279 * to allocate @blocks
280 * Worse case is one block per extent
281 */
282 int ext4_ext_calc_metadata_amount(struct inode *inode, int blocks)
283 {
284 int lcap, icap, rcap, leafs, idxs, num;
285 int newextents = blocks;
286
287 rcap = ext4_ext_space_root_idx(inode);
288 lcap = ext4_ext_space_block(inode);
289 icap = ext4_ext_space_block_idx(inode);
290
291 /* number of new leaf blocks needed */
292 num = leafs = (newextents + lcap - 1) / lcap;
293
294 /*
295 * Worse case, we need separate index block(s)
296 * to link all new leaf blocks
297 */
298 idxs = (leafs + icap - 1) / icap;
299 do {
300 num += idxs;
301 idxs = (idxs + icap - 1) / icap;
302 } while (idxs > rcap);
303
304 return num;
305 }
306
307 static int
308 ext4_ext_max_entries(struct inode *inode, int depth)
309 {
310 int max;
311
312 if (depth == ext_depth(inode)) {
313 if (depth == 0)
314 max = ext4_ext_space_root(inode);
315 else
316 max = ext4_ext_space_root_idx(inode);
317 } else {
318 if (depth == 0)
319 max = ext4_ext_space_block(inode);
320 else
321 max = ext4_ext_space_block_idx(inode);
322 }
323
324 return max;
325 }
326
327 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
328 {
329 ext4_fsblk_t block = ext_pblock(ext);
330 int len = ext4_ext_get_actual_len(ext);
331 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
332 if (unlikely(block < le32_to_cpu(es->s_first_data_block) ||
333 ((block + len) > ext4_blocks_count(es))))
334 return 0;
335 else
336 return 1;
337 }
338
339 static int ext4_valid_extent_idx(struct inode *inode,
340 struct ext4_extent_idx *ext_idx)
341 {
342 ext4_fsblk_t block = idx_pblock(ext_idx);
343 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
344 if (unlikely(block < le32_to_cpu(es->s_first_data_block) ||
345 (block > ext4_blocks_count(es))))
346 return 0;
347 else
348 return 1;
349 }
350
351 static int ext4_valid_extent_entries(struct inode *inode,
352 struct ext4_extent_header *eh,
353 int depth)
354 {
355 struct ext4_extent *ext;
356 struct ext4_extent_idx *ext_idx;
357 unsigned short entries;
358 if (eh->eh_entries == 0)
359 return 1;
360
361 entries = le16_to_cpu(eh->eh_entries);
362
363 if (depth == 0) {
364 /* leaf entries */
365 ext = EXT_FIRST_EXTENT(eh);
366 while (entries) {
367 if (!ext4_valid_extent(inode, ext))
368 return 0;
369 ext++;
370 entries--;
371 }
372 } else {
373 ext_idx = EXT_FIRST_INDEX(eh);
374 while (entries) {
375 if (!ext4_valid_extent_idx(inode, ext_idx))
376 return 0;
377 ext_idx++;
378 entries--;
379 }
380 }
381 return 1;
382 }
383
384 static int __ext4_ext_check(const char *function, struct inode *inode,
385 struct ext4_extent_header *eh,
386 int depth)
387 {
388 const char *error_msg;
389 int max = 0;
390
391 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
392 error_msg = "invalid magic";
393 goto corrupted;
394 }
395 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
396 error_msg = "unexpected eh_depth";
397 goto corrupted;
398 }
399 if (unlikely(eh->eh_max == 0)) {
400 error_msg = "invalid eh_max";
401 goto corrupted;
402 }
403 max = ext4_ext_max_entries(inode, depth);
404 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
405 error_msg = "too large eh_max";
406 goto corrupted;
407 }
408 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
409 error_msg = "invalid eh_entries";
410 goto corrupted;
411 }
412 if (!ext4_valid_extent_entries(inode, eh, depth)) {
413 error_msg = "invalid extent entries";
414 goto corrupted;
415 }
416 return 0;
417
418 corrupted:
419 ext4_error(inode->i_sb, function,
420 "bad header/extent in inode #%lu: %s - magic %x, "
421 "entries %u, max %u(%u), depth %u(%u)",
422 inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
423 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
424 max, le16_to_cpu(eh->eh_depth), depth);
425
426 return -EIO;
427 }
428
429 #define ext4_ext_check(inode, eh, depth) \
430 __ext4_ext_check(__func__, inode, eh, depth)
431
432 #ifdef EXT_DEBUG
433 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
434 {
435 int k, l = path->p_depth;
436
437 ext_debug("path:");
438 for (k = 0; k <= l; k++, path++) {
439 if (path->p_idx) {
440 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
441 idx_pblock(path->p_idx));
442 } else if (path->p_ext) {
443 ext_debug(" %d:%d:%llu ",
444 le32_to_cpu(path->p_ext->ee_block),
445 ext4_ext_get_actual_len(path->p_ext),
446 ext_pblock(path->p_ext));
447 } else
448 ext_debug(" []");
449 }
450 ext_debug("\n");
451 }
452
453 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
454 {
455 int depth = ext_depth(inode);
456 struct ext4_extent_header *eh;
457 struct ext4_extent *ex;
458 int i;
459
460 if (!path)
461 return;
462
463 eh = path[depth].p_hdr;
464 ex = EXT_FIRST_EXTENT(eh);
465
466 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
467 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
468 ext4_ext_get_actual_len(ex), ext_pblock(ex));
469 }
470 ext_debug("\n");
471 }
472 #else
473 #define ext4_ext_show_path(inode, path)
474 #define ext4_ext_show_leaf(inode, path)
475 #endif
476
477 void ext4_ext_drop_refs(struct ext4_ext_path *path)
478 {
479 int depth = path->p_depth;
480 int i;
481
482 for (i = 0; i <= depth; i++, path++)
483 if (path->p_bh) {
484 brelse(path->p_bh);
485 path->p_bh = NULL;
486 }
487 }
488
489 /*
490 * ext4_ext_binsearch_idx:
491 * binary search for the closest index of the given block
492 * the header must be checked before calling this
493 */
494 static void
495 ext4_ext_binsearch_idx(struct inode *inode,
496 struct ext4_ext_path *path, ext4_lblk_t block)
497 {
498 struct ext4_extent_header *eh = path->p_hdr;
499 struct ext4_extent_idx *r, *l, *m;
500
501
502 ext_debug("binsearch for %u(idx): ", block);
503
504 l = EXT_FIRST_INDEX(eh) + 1;
505 r = EXT_LAST_INDEX(eh);
506 while (l <= r) {
507 m = l + (r - l) / 2;
508 if (block < le32_to_cpu(m->ei_block))
509 r = m - 1;
510 else
511 l = m + 1;
512 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
513 m, le32_to_cpu(m->ei_block),
514 r, le32_to_cpu(r->ei_block));
515 }
516
517 path->p_idx = l - 1;
518 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
519 idx_pblock(path->p_idx));
520
521 #ifdef CHECK_BINSEARCH
522 {
523 struct ext4_extent_idx *chix, *ix;
524 int k;
525
526 chix = ix = EXT_FIRST_INDEX(eh);
527 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
528 if (k != 0 &&
529 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
530 printk(KERN_DEBUG "k=%d, ix=0x%p, "
531 "first=0x%p\n", k,
532 ix, EXT_FIRST_INDEX(eh));
533 printk(KERN_DEBUG "%u <= %u\n",
534 le32_to_cpu(ix->ei_block),
535 le32_to_cpu(ix[-1].ei_block));
536 }
537 BUG_ON(k && le32_to_cpu(ix->ei_block)
538 <= le32_to_cpu(ix[-1].ei_block));
539 if (block < le32_to_cpu(ix->ei_block))
540 break;
541 chix = ix;
542 }
543 BUG_ON(chix != path->p_idx);
544 }
545 #endif
546
547 }
548
549 /*
550 * ext4_ext_binsearch:
551 * binary search for closest extent of the given block
552 * the header must be checked before calling this
553 */
554 static void
555 ext4_ext_binsearch(struct inode *inode,
556 struct ext4_ext_path *path, ext4_lblk_t block)
557 {
558 struct ext4_extent_header *eh = path->p_hdr;
559 struct ext4_extent *r, *l, *m;
560
561 if (eh->eh_entries == 0) {
562 /*
563 * this leaf is empty:
564 * we get such a leaf in split/add case
565 */
566 return;
567 }
568
569 ext_debug("binsearch for %u: ", block);
570
571 l = EXT_FIRST_EXTENT(eh) + 1;
572 r = EXT_LAST_EXTENT(eh);
573
574 while (l <= r) {
575 m = l + (r - l) / 2;
576 if (block < le32_to_cpu(m->ee_block))
577 r = m - 1;
578 else
579 l = m + 1;
580 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
581 m, le32_to_cpu(m->ee_block),
582 r, le32_to_cpu(r->ee_block));
583 }
584
585 path->p_ext = l - 1;
586 ext_debug(" -> %d:%llu:%d ",
587 le32_to_cpu(path->p_ext->ee_block),
588 ext_pblock(path->p_ext),
589 ext4_ext_get_actual_len(path->p_ext));
590
591 #ifdef CHECK_BINSEARCH
592 {
593 struct ext4_extent *chex, *ex;
594 int k;
595
596 chex = ex = EXT_FIRST_EXTENT(eh);
597 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
598 BUG_ON(k && le32_to_cpu(ex->ee_block)
599 <= le32_to_cpu(ex[-1].ee_block));
600 if (block < le32_to_cpu(ex->ee_block))
601 break;
602 chex = ex;
603 }
604 BUG_ON(chex != path->p_ext);
605 }
606 #endif
607
608 }
609
610 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
611 {
612 struct ext4_extent_header *eh;
613
614 eh = ext_inode_hdr(inode);
615 eh->eh_depth = 0;
616 eh->eh_entries = 0;
617 eh->eh_magic = EXT4_EXT_MAGIC;
618 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
619 ext4_mark_inode_dirty(handle, inode);
620 ext4_ext_invalidate_cache(inode);
621 return 0;
622 }
623
624 struct ext4_ext_path *
625 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
626 struct ext4_ext_path *path)
627 {
628 struct ext4_extent_header *eh;
629 struct buffer_head *bh;
630 short int depth, i, ppos = 0, alloc = 0;
631
632 eh = ext_inode_hdr(inode);
633 depth = ext_depth(inode);
634 if (ext4_ext_check(inode, eh, depth))
635 return ERR_PTR(-EIO);
636
637
638 /* account possible depth increase */
639 if (!path) {
640 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
641 GFP_NOFS);
642 if (!path)
643 return ERR_PTR(-ENOMEM);
644 alloc = 1;
645 }
646 path[0].p_hdr = eh;
647 path[0].p_bh = NULL;
648
649 i = depth;
650 /* walk through the tree */
651 while (i) {
652 ext_debug("depth %d: num %d, max %d\n",
653 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
654
655 ext4_ext_binsearch_idx(inode, path + ppos, block);
656 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
657 path[ppos].p_depth = i;
658 path[ppos].p_ext = NULL;
659
660 bh = sb_bread(inode->i_sb, path[ppos].p_block);
661 if (!bh)
662 goto err;
663
664 eh = ext_block_hdr(bh);
665 ppos++;
666 BUG_ON(ppos > depth);
667 path[ppos].p_bh = bh;
668 path[ppos].p_hdr = eh;
669 i--;
670
671 if (ext4_ext_check(inode, eh, i))
672 goto err;
673 }
674
675 path[ppos].p_depth = i;
676 path[ppos].p_ext = NULL;
677 path[ppos].p_idx = NULL;
678
679 /* find extent */
680 ext4_ext_binsearch(inode, path + ppos, block);
681 /* if not an empty leaf */
682 if (path[ppos].p_ext)
683 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
684
685 ext4_ext_show_path(inode, path);
686
687 return path;
688
689 err:
690 ext4_ext_drop_refs(path);
691 if (alloc)
692 kfree(path);
693 return ERR_PTR(-EIO);
694 }
695
696 /*
697 * ext4_ext_insert_index:
698 * insert new index [@logical;@ptr] into the block at @curp;
699 * check where to insert: before @curp or after @curp
700 */
701 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
702 struct ext4_ext_path *curp,
703 int logical, ext4_fsblk_t ptr)
704 {
705 struct ext4_extent_idx *ix;
706 int len, err;
707
708 err = ext4_ext_get_access(handle, inode, curp);
709 if (err)
710 return err;
711
712 BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
713 len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
714 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
715 /* insert after */
716 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
717 len = (len - 1) * sizeof(struct ext4_extent_idx);
718 len = len < 0 ? 0 : len;
719 ext_debug("insert new index %d after: %llu. "
720 "move %d from 0x%p to 0x%p\n",
721 logical, ptr, len,
722 (curp->p_idx + 1), (curp->p_idx + 2));
723 memmove(curp->p_idx + 2, curp->p_idx + 1, len);
724 }
725 ix = curp->p_idx + 1;
726 } else {
727 /* insert before */
728 len = len * sizeof(struct ext4_extent_idx);
729 len = len < 0 ? 0 : len;
730 ext_debug("insert new index %d before: %llu. "
731 "move %d from 0x%p to 0x%p\n",
732 logical, ptr, len,
733 curp->p_idx, (curp->p_idx + 1));
734 memmove(curp->p_idx + 1, curp->p_idx, len);
735 ix = curp->p_idx;
736 }
737
738 ix->ei_block = cpu_to_le32(logical);
739 ext4_idx_store_pblock(ix, ptr);
740 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
741
742 BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
743 > le16_to_cpu(curp->p_hdr->eh_max));
744 BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
745
746 err = ext4_ext_dirty(handle, inode, curp);
747 ext4_std_error(inode->i_sb, err);
748
749 return err;
750 }
751
752 /*
753 * ext4_ext_split:
754 * inserts new subtree into the path, using free index entry
755 * at depth @at:
756 * - allocates all needed blocks (new leaf and all intermediate index blocks)
757 * - makes decision where to split
758 * - moves remaining extents and index entries (right to the split point)
759 * into the newly allocated blocks
760 * - initializes subtree
761 */
762 static int ext4_ext_split(handle_t *handle, struct inode *inode,
763 struct ext4_ext_path *path,
764 struct ext4_extent *newext, int at)
765 {
766 struct buffer_head *bh = NULL;
767 int depth = ext_depth(inode);
768 struct ext4_extent_header *neh;
769 struct ext4_extent_idx *fidx;
770 struct ext4_extent *ex;
771 int i = at, k, m, a;
772 ext4_fsblk_t newblock, oldblock;
773 __le32 border;
774 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
775 int err = 0;
776
777 /* make decision: where to split? */
778 /* FIXME: now decision is simplest: at current extent */
779
780 /* if current leaf will be split, then we should use
781 * border from split point */
782 BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
783 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
784 border = path[depth].p_ext[1].ee_block;
785 ext_debug("leaf will be split."
786 " next leaf starts at %d\n",
787 le32_to_cpu(border));
788 } else {
789 border = newext->ee_block;
790 ext_debug("leaf will be added."
791 " next leaf starts at %d\n",
792 le32_to_cpu(border));
793 }
794
795 /*
796 * If error occurs, then we break processing
797 * and mark filesystem read-only. index won't
798 * be inserted and tree will be in consistent
799 * state. Next mount will repair buffers too.
800 */
801
802 /*
803 * Get array to track all allocated blocks.
804 * We need this to handle errors and free blocks
805 * upon them.
806 */
807 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
808 if (!ablocks)
809 return -ENOMEM;
810
811 /* allocate all needed blocks */
812 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
813 for (a = 0; a < depth - at; a++) {
814 newblock = ext4_ext_new_meta_block(handle, inode, path,
815 newext, &err);
816 if (newblock == 0)
817 goto cleanup;
818 ablocks[a] = newblock;
819 }
820
821 /* initialize new leaf */
822 newblock = ablocks[--a];
823 BUG_ON(newblock == 0);
824 bh = sb_getblk(inode->i_sb, newblock);
825 if (!bh) {
826 err = -EIO;
827 goto cleanup;
828 }
829 lock_buffer(bh);
830
831 err = ext4_journal_get_create_access(handle, bh);
832 if (err)
833 goto cleanup;
834
835 neh = ext_block_hdr(bh);
836 neh->eh_entries = 0;
837 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
838 neh->eh_magic = EXT4_EXT_MAGIC;
839 neh->eh_depth = 0;
840 ex = EXT_FIRST_EXTENT(neh);
841
842 /* move remainder of path[depth] to the new leaf */
843 BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
844 /* start copy from next extent */
845 /* TODO: we could do it by single memmove */
846 m = 0;
847 path[depth].p_ext++;
848 while (path[depth].p_ext <=
849 EXT_MAX_EXTENT(path[depth].p_hdr)) {
850 ext_debug("move %d:%llu:%d in new leaf %llu\n",
851 le32_to_cpu(path[depth].p_ext->ee_block),
852 ext_pblock(path[depth].p_ext),
853 ext4_ext_get_actual_len(path[depth].p_ext),
854 newblock);
855 /*memmove(ex++, path[depth].p_ext++,
856 sizeof(struct ext4_extent));
857 neh->eh_entries++;*/
858 path[depth].p_ext++;
859 m++;
860 }
861 if (m) {
862 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
863 le16_add_cpu(&neh->eh_entries, m);
864 }
865
866 set_buffer_uptodate(bh);
867 unlock_buffer(bh);
868
869 err = ext4_handle_dirty_metadata(handle, inode, bh);
870 if (err)
871 goto cleanup;
872 brelse(bh);
873 bh = NULL;
874
875 /* correct old leaf */
876 if (m) {
877 err = ext4_ext_get_access(handle, inode, path + depth);
878 if (err)
879 goto cleanup;
880 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
881 err = ext4_ext_dirty(handle, inode, path + depth);
882 if (err)
883 goto cleanup;
884
885 }
886
887 /* create intermediate indexes */
888 k = depth - at - 1;
889 BUG_ON(k < 0);
890 if (k)
891 ext_debug("create %d intermediate indices\n", k);
892 /* insert new index into current index block */
893 /* current depth stored in i var */
894 i = depth - 1;
895 while (k--) {
896 oldblock = newblock;
897 newblock = ablocks[--a];
898 bh = sb_getblk(inode->i_sb, newblock);
899 if (!bh) {
900 err = -EIO;
901 goto cleanup;
902 }
903 lock_buffer(bh);
904
905 err = ext4_journal_get_create_access(handle, bh);
906 if (err)
907 goto cleanup;
908
909 neh = ext_block_hdr(bh);
910 neh->eh_entries = cpu_to_le16(1);
911 neh->eh_magic = EXT4_EXT_MAGIC;
912 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
913 neh->eh_depth = cpu_to_le16(depth - i);
914 fidx = EXT_FIRST_INDEX(neh);
915 fidx->ei_block = border;
916 ext4_idx_store_pblock(fidx, oldblock);
917
918 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
919 i, newblock, le32_to_cpu(border), oldblock);
920 /* copy indexes */
921 m = 0;
922 path[i].p_idx++;
923
924 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
925 EXT_MAX_INDEX(path[i].p_hdr));
926 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
927 EXT_LAST_INDEX(path[i].p_hdr));
928 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
929 ext_debug("%d: move %d:%llu in new index %llu\n", i,
930 le32_to_cpu(path[i].p_idx->ei_block),
931 idx_pblock(path[i].p_idx),
932 newblock);
933 /*memmove(++fidx, path[i].p_idx++,
934 sizeof(struct ext4_extent_idx));
935 neh->eh_entries++;
936 BUG_ON(neh->eh_entries > neh->eh_max);*/
937 path[i].p_idx++;
938 m++;
939 }
940 if (m) {
941 memmove(++fidx, path[i].p_idx - m,
942 sizeof(struct ext4_extent_idx) * m);
943 le16_add_cpu(&neh->eh_entries, m);
944 }
945 set_buffer_uptodate(bh);
946 unlock_buffer(bh);
947
948 err = ext4_handle_dirty_metadata(handle, inode, bh);
949 if (err)
950 goto cleanup;
951 brelse(bh);
952 bh = NULL;
953
954 /* correct old index */
955 if (m) {
956 err = ext4_ext_get_access(handle, inode, path + i);
957 if (err)
958 goto cleanup;
959 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
960 err = ext4_ext_dirty(handle, inode, path + i);
961 if (err)
962 goto cleanup;
963 }
964
965 i--;
966 }
967
968 /* insert new index */
969 err = ext4_ext_insert_index(handle, inode, path + at,
970 le32_to_cpu(border), newblock);
971
972 cleanup:
973 if (bh) {
974 if (buffer_locked(bh))
975 unlock_buffer(bh);
976 brelse(bh);
977 }
978
979 if (err) {
980 /* free all allocated blocks in error case */
981 for (i = 0; i < depth; i++) {
982 if (!ablocks[i])
983 continue;
984 ext4_free_blocks(handle, inode, ablocks[i], 1, 1);
985 }
986 }
987 kfree(ablocks);
988
989 return err;
990 }
991
992 /*
993 * ext4_ext_grow_indepth:
994 * implements tree growing procedure:
995 * - allocates new block
996 * - moves top-level data (index block or leaf) into the new block
997 * - initializes new top-level, creating index that points to the
998 * just created block
999 */
1000 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1001 struct ext4_ext_path *path,
1002 struct ext4_extent *newext)
1003 {
1004 struct ext4_ext_path *curp = path;
1005 struct ext4_extent_header *neh;
1006 struct ext4_extent_idx *fidx;
1007 struct buffer_head *bh;
1008 ext4_fsblk_t newblock;
1009 int err = 0;
1010
1011 newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
1012 if (newblock == 0)
1013 return err;
1014
1015 bh = sb_getblk(inode->i_sb, newblock);
1016 if (!bh) {
1017 err = -EIO;
1018 ext4_std_error(inode->i_sb, err);
1019 return err;
1020 }
1021 lock_buffer(bh);
1022
1023 err = ext4_journal_get_create_access(handle, bh);
1024 if (err) {
1025 unlock_buffer(bh);
1026 goto out;
1027 }
1028
1029 /* move top-level index/leaf into new block */
1030 memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1031
1032 /* set size of new block */
1033 neh = ext_block_hdr(bh);
1034 /* old root could have indexes or leaves
1035 * so calculate e_max right way */
1036 if (ext_depth(inode))
1037 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
1038 else
1039 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
1040 neh->eh_magic = EXT4_EXT_MAGIC;
1041 set_buffer_uptodate(bh);
1042 unlock_buffer(bh);
1043
1044 err = ext4_handle_dirty_metadata(handle, inode, bh);
1045 if (err)
1046 goto out;
1047
1048 /* create index in new top-level index: num,max,pointer */
1049 err = ext4_ext_get_access(handle, inode, curp);
1050 if (err)
1051 goto out;
1052
1053 curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
1054 curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
1055 curp->p_hdr->eh_entries = cpu_to_le16(1);
1056 curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1057
1058 if (path[0].p_hdr->eh_depth)
1059 curp->p_idx->ei_block =
1060 EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1061 else
1062 curp->p_idx->ei_block =
1063 EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1064 ext4_idx_store_pblock(curp->p_idx, newblock);
1065
1066 neh = ext_inode_hdr(inode);
1067 fidx = EXT_FIRST_INDEX(neh);
1068 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1069 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1070 le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
1071
1072 neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1073 err = ext4_ext_dirty(handle, inode, curp);
1074 out:
1075 brelse(bh);
1076
1077 return err;
1078 }
1079
1080 /*
1081 * ext4_ext_create_new_leaf:
1082 * finds empty index and adds new leaf.
1083 * if no free index is found, then it requests in-depth growing.
1084 */
1085 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1086 struct ext4_ext_path *path,
1087 struct ext4_extent *newext)
1088 {
1089 struct ext4_ext_path *curp;
1090 int depth, i, err = 0;
1091
1092 repeat:
1093 i = depth = ext_depth(inode);
1094
1095 /* walk up to the tree and look for free index entry */
1096 curp = path + depth;
1097 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1098 i--;
1099 curp--;
1100 }
1101
1102 /* we use already allocated block for index block,
1103 * so subsequent data blocks should be contiguous */
1104 if (EXT_HAS_FREE_INDEX(curp)) {
1105 /* if we found index with free entry, then use that
1106 * entry: create all needed subtree and add new leaf */
1107 err = ext4_ext_split(handle, inode, path, newext, i);
1108 if (err)
1109 goto out;
1110
1111 /* refill path */
1112 ext4_ext_drop_refs(path);
1113 path = ext4_ext_find_extent(inode,
1114 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1115 path);
1116 if (IS_ERR(path))
1117 err = PTR_ERR(path);
1118 } else {
1119 /* tree is full, time to grow in depth */
1120 err = ext4_ext_grow_indepth(handle, inode, path, newext);
1121 if (err)
1122 goto out;
1123
1124 /* refill path */
1125 ext4_ext_drop_refs(path);
1126 path = ext4_ext_find_extent(inode,
1127 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1128 path);
1129 if (IS_ERR(path)) {
1130 err = PTR_ERR(path);
1131 goto out;
1132 }
1133
1134 /*
1135 * only first (depth 0 -> 1) produces free space;
1136 * in all other cases we have to split the grown tree
1137 */
1138 depth = ext_depth(inode);
1139 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1140 /* now we need to split */
1141 goto repeat;
1142 }
1143 }
1144
1145 out:
1146 return err;
1147 }
1148
1149 /*
1150 * search the closest allocated block to the left for *logical
1151 * and returns it at @logical + it's physical address at @phys
1152 * if *logical is the smallest allocated block, the function
1153 * returns 0 at @phys
1154 * return value contains 0 (success) or error code
1155 */
1156 int
1157 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1158 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1159 {
1160 struct ext4_extent_idx *ix;
1161 struct ext4_extent *ex;
1162 int depth, ee_len;
1163
1164 BUG_ON(path == NULL);
1165 depth = path->p_depth;
1166 *phys = 0;
1167
1168 if (depth == 0 && path->p_ext == NULL)
1169 return 0;
1170
1171 /* usually extent in the path covers blocks smaller
1172 * then *logical, but it can be that extent is the
1173 * first one in the file */
1174
1175 ex = path[depth].p_ext;
1176 ee_len = ext4_ext_get_actual_len(ex);
1177 if (*logical < le32_to_cpu(ex->ee_block)) {
1178 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1179 while (--depth >= 0) {
1180 ix = path[depth].p_idx;
1181 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1182 }
1183 return 0;
1184 }
1185
1186 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1187
1188 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1189 *phys = ext_pblock(ex) + ee_len - 1;
1190 return 0;
1191 }
1192
1193 /*
1194 * search the closest allocated block to the right for *logical
1195 * and returns it at @logical + it's physical address at @phys
1196 * if *logical is the smallest allocated block, the function
1197 * returns 0 at @phys
1198 * return value contains 0 (success) or error code
1199 */
1200 int
1201 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1202 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1203 {
1204 struct buffer_head *bh = NULL;
1205 struct ext4_extent_header *eh;
1206 struct ext4_extent_idx *ix;
1207 struct ext4_extent *ex;
1208 ext4_fsblk_t block;
1209 int depth; /* Note, NOT eh_depth; depth from top of tree */
1210 int ee_len;
1211
1212 BUG_ON(path == NULL);
1213 depth = path->p_depth;
1214 *phys = 0;
1215
1216 if (depth == 0 && path->p_ext == NULL)
1217 return 0;
1218
1219 /* usually extent in the path covers blocks smaller
1220 * then *logical, but it can be that extent is the
1221 * first one in the file */
1222
1223 ex = path[depth].p_ext;
1224 ee_len = ext4_ext_get_actual_len(ex);
1225 if (*logical < le32_to_cpu(ex->ee_block)) {
1226 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1227 while (--depth >= 0) {
1228 ix = path[depth].p_idx;
1229 BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1230 }
1231 *logical = le32_to_cpu(ex->ee_block);
1232 *phys = ext_pblock(ex);
1233 return 0;
1234 }
1235
1236 BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1237
1238 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1239 /* next allocated block in this leaf */
1240 ex++;
1241 *logical = le32_to_cpu(ex->ee_block);
1242 *phys = ext_pblock(ex);
1243 return 0;
1244 }
1245
1246 /* go up and search for index to the right */
1247 while (--depth >= 0) {
1248 ix = path[depth].p_idx;
1249 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1250 goto got_index;
1251 }
1252
1253 /* we've gone up to the root and found no index to the right */
1254 return 0;
1255
1256 got_index:
1257 /* we've found index to the right, let's
1258 * follow it and find the closest allocated
1259 * block to the right */
1260 ix++;
1261 block = idx_pblock(ix);
1262 while (++depth < path->p_depth) {
1263 bh = sb_bread(inode->i_sb, block);
1264 if (bh == NULL)
1265 return -EIO;
1266 eh = ext_block_hdr(bh);
1267 /* subtract from p_depth to get proper eh_depth */
1268 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1269 put_bh(bh);
1270 return -EIO;
1271 }
1272 ix = EXT_FIRST_INDEX(eh);
1273 block = idx_pblock(ix);
1274 put_bh(bh);
1275 }
1276
1277 bh = sb_bread(inode->i_sb, block);
1278 if (bh == NULL)
1279 return -EIO;
1280 eh = ext_block_hdr(bh);
1281 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1282 put_bh(bh);
1283 return -EIO;
1284 }
1285 ex = EXT_FIRST_EXTENT(eh);
1286 *logical = le32_to_cpu(ex->ee_block);
1287 *phys = ext_pblock(ex);
1288 put_bh(bh);
1289 return 0;
1290 }
1291
1292 /*
1293 * ext4_ext_next_allocated_block:
1294 * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1295 * NOTE: it considers block number from index entry as
1296 * allocated block. Thus, index entries have to be consistent
1297 * with leaves.
1298 */
1299 static ext4_lblk_t
1300 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1301 {
1302 int depth;
1303
1304 BUG_ON(path == NULL);
1305 depth = path->p_depth;
1306
1307 if (depth == 0 && path->p_ext == NULL)
1308 return EXT_MAX_BLOCK;
1309
1310 while (depth >= 0) {
1311 if (depth == path->p_depth) {
1312 /* leaf */
1313 if (path[depth].p_ext !=
1314 EXT_LAST_EXTENT(path[depth].p_hdr))
1315 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1316 } else {
1317 /* index */
1318 if (path[depth].p_idx !=
1319 EXT_LAST_INDEX(path[depth].p_hdr))
1320 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1321 }
1322 depth--;
1323 }
1324
1325 return EXT_MAX_BLOCK;
1326 }
1327
1328 /*
1329 * ext4_ext_next_leaf_block:
1330 * returns first allocated block from next leaf or EXT_MAX_BLOCK
1331 */
1332 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1333 struct ext4_ext_path *path)
1334 {
1335 int depth;
1336
1337 BUG_ON(path == NULL);
1338 depth = path->p_depth;
1339
1340 /* zero-tree has no leaf blocks at all */
1341 if (depth == 0)
1342 return EXT_MAX_BLOCK;
1343
1344 /* go to index block */
1345 depth--;
1346
1347 while (depth >= 0) {
1348 if (path[depth].p_idx !=
1349 EXT_LAST_INDEX(path[depth].p_hdr))
1350 return (ext4_lblk_t)
1351 le32_to_cpu(path[depth].p_idx[1].ei_block);
1352 depth--;
1353 }
1354
1355 return EXT_MAX_BLOCK;
1356 }
1357
1358 /*
1359 * ext4_ext_correct_indexes:
1360 * if leaf gets modified and modified extent is first in the leaf,
1361 * then we have to correct all indexes above.
1362 * TODO: do we need to correct tree in all cases?
1363 */
1364 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1365 struct ext4_ext_path *path)
1366 {
1367 struct ext4_extent_header *eh;
1368 int depth = ext_depth(inode);
1369 struct ext4_extent *ex;
1370 __le32 border;
1371 int k, err = 0;
1372
1373 eh = path[depth].p_hdr;
1374 ex = path[depth].p_ext;
1375 BUG_ON(ex == NULL);
1376 BUG_ON(eh == NULL);
1377
1378 if (depth == 0) {
1379 /* there is no tree at all */
1380 return 0;
1381 }
1382
1383 if (ex != EXT_FIRST_EXTENT(eh)) {
1384 /* we correct tree if first leaf got modified only */
1385 return 0;
1386 }
1387
1388 /*
1389 * TODO: we need correction if border is smaller than current one
1390 */
1391 k = depth - 1;
1392 border = path[depth].p_ext->ee_block;
1393 err = ext4_ext_get_access(handle, inode, path + k);
1394 if (err)
1395 return err;
1396 path[k].p_idx->ei_block = border;
1397 err = ext4_ext_dirty(handle, inode, path + k);
1398 if (err)
1399 return err;
1400
1401 while (k--) {
1402 /* change all left-side indexes */
1403 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1404 break;
1405 err = ext4_ext_get_access(handle, inode, path + k);
1406 if (err)
1407 break;
1408 path[k].p_idx->ei_block = border;
1409 err = ext4_ext_dirty(handle, inode, path + k);
1410 if (err)
1411 break;
1412 }
1413
1414 return err;
1415 }
1416
1417 static int
1418 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1419 struct ext4_extent *ex2)
1420 {
1421 unsigned short ext1_ee_len, ext2_ee_len, max_len;
1422
1423 /*
1424 * Make sure that either both extents are uninitialized, or
1425 * both are _not_.
1426 */
1427 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1428 return 0;
1429
1430 if (ext4_ext_is_uninitialized(ex1))
1431 max_len = EXT_UNINIT_MAX_LEN;
1432 else
1433 max_len = EXT_INIT_MAX_LEN;
1434
1435 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1436 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1437
1438 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1439 le32_to_cpu(ex2->ee_block))
1440 return 0;
1441
1442 /*
1443 * To allow future support for preallocated extents to be added
1444 * as an RO_COMPAT feature, refuse to merge to extents if
1445 * this can result in the top bit of ee_len being set.
1446 */
1447 if (ext1_ee_len + ext2_ee_len > max_len)
1448 return 0;
1449 #ifdef AGGRESSIVE_TEST
1450 if (ext1_ee_len >= 4)
1451 return 0;
1452 #endif
1453
1454 if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1455 return 1;
1456 return 0;
1457 }
1458
1459 /*
1460 * This function tries to merge the "ex" extent to the next extent in the tree.
1461 * It always tries to merge towards right. If you want to merge towards
1462 * left, pass "ex - 1" as argument instead of "ex".
1463 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1464 * 1 if they got merged.
1465 */
1466 int ext4_ext_try_to_merge(struct inode *inode,
1467 struct ext4_ext_path *path,
1468 struct ext4_extent *ex)
1469 {
1470 struct ext4_extent_header *eh;
1471 unsigned int depth, len;
1472 int merge_done = 0;
1473 int uninitialized = 0;
1474
1475 depth = ext_depth(inode);
1476 BUG_ON(path[depth].p_hdr == NULL);
1477 eh = path[depth].p_hdr;
1478
1479 while (ex < EXT_LAST_EXTENT(eh)) {
1480 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1481 break;
1482 /* merge with next extent! */
1483 if (ext4_ext_is_uninitialized(ex))
1484 uninitialized = 1;
1485 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1486 + ext4_ext_get_actual_len(ex + 1));
1487 if (uninitialized)
1488 ext4_ext_mark_uninitialized(ex);
1489
1490 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1491 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1492 * sizeof(struct ext4_extent);
1493 memmove(ex + 1, ex + 2, len);
1494 }
1495 le16_add_cpu(&eh->eh_entries, -1);
1496 merge_done = 1;
1497 WARN_ON(eh->eh_entries == 0);
1498 if (!eh->eh_entries)
1499 ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1500 "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1501 }
1502
1503 return merge_done;
1504 }
1505
1506 /*
1507 * check if a portion of the "newext" extent overlaps with an
1508 * existing extent.
1509 *
1510 * If there is an overlap discovered, it updates the length of the newext
1511 * such that there will be no overlap, and then returns 1.
1512 * If there is no overlap found, it returns 0.
1513 */
1514 unsigned int ext4_ext_check_overlap(struct inode *inode,
1515 struct ext4_extent *newext,
1516 struct ext4_ext_path *path)
1517 {
1518 ext4_lblk_t b1, b2;
1519 unsigned int depth, len1;
1520 unsigned int ret = 0;
1521
1522 b1 = le32_to_cpu(newext->ee_block);
1523 len1 = ext4_ext_get_actual_len(newext);
1524 depth = ext_depth(inode);
1525 if (!path[depth].p_ext)
1526 goto out;
1527 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1528
1529 /*
1530 * get the next allocated block if the extent in the path
1531 * is before the requested block(s)
1532 */
1533 if (b2 < b1) {
1534 b2 = ext4_ext_next_allocated_block(path);
1535 if (b2 == EXT_MAX_BLOCK)
1536 goto out;
1537 }
1538
1539 /* check for wrap through zero on extent logical start block*/
1540 if (b1 + len1 < b1) {
1541 len1 = EXT_MAX_BLOCK - b1;
1542 newext->ee_len = cpu_to_le16(len1);
1543 ret = 1;
1544 }
1545
1546 /* check for overlap */
1547 if (b1 + len1 > b2) {
1548 newext->ee_len = cpu_to_le16(b2 - b1);
1549 ret = 1;
1550 }
1551 out:
1552 return ret;
1553 }
1554
1555 /*
1556 * ext4_ext_insert_extent:
1557 * tries to merge requsted extent into the existing extent or
1558 * inserts requested extent as new one into the tree,
1559 * creating new leaf in the no-space case.
1560 */
1561 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1562 struct ext4_ext_path *path,
1563 struct ext4_extent *newext)
1564 {
1565 struct ext4_extent_header *eh;
1566 struct ext4_extent *ex, *fex;
1567 struct ext4_extent *nearex; /* nearest extent */
1568 struct ext4_ext_path *npath = NULL;
1569 int depth, len, err;
1570 ext4_lblk_t next;
1571 unsigned uninitialized = 0;
1572
1573 BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1574 depth = ext_depth(inode);
1575 ex = path[depth].p_ext;
1576 BUG_ON(path[depth].p_hdr == NULL);
1577
1578 /* try to insert block into found extent and return */
1579 if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1580 ext_debug("append %d block to %d:%d (from %llu)\n",
1581 ext4_ext_get_actual_len(newext),
1582 le32_to_cpu(ex->ee_block),
1583 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1584 err = ext4_ext_get_access(handle, inode, path + depth);
1585 if (err)
1586 return err;
1587
1588 /*
1589 * ext4_can_extents_be_merged should have checked that either
1590 * both extents are uninitialized, or both aren't. Thus we
1591 * need to check only one of them here.
1592 */
1593 if (ext4_ext_is_uninitialized(ex))
1594 uninitialized = 1;
1595 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1596 + ext4_ext_get_actual_len(newext));
1597 if (uninitialized)
1598 ext4_ext_mark_uninitialized(ex);
1599 eh = path[depth].p_hdr;
1600 nearex = ex;
1601 goto merge;
1602 }
1603
1604 repeat:
1605 depth = ext_depth(inode);
1606 eh = path[depth].p_hdr;
1607 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1608 goto has_space;
1609
1610 /* probably next leaf has space for us? */
1611 fex = EXT_LAST_EXTENT(eh);
1612 next = ext4_ext_next_leaf_block(inode, path);
1613 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1614 && next != EXT_MAX_BLOCK) {
1615 ext_debug("next leaf block - %d\n", next);
1616 BUG_ON(npath != NULL);
1617 npath = ext4_ext_find_extent(inode, next, NULL);
1618 if (IS_ERR(npath))
1619 return PTR_ERR(npath);
1620 BUG_ON(npath->p_depth != path->p_depth);
1621 eh = npath[depth].p_hdr;
1622 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1623 ext_debug("next leaf isnt full(%d)\n",
1624 le16_to_cpu(eh->eh_entries));
1625 path = npath;
1626 goto repeat;
1627 }
1628 ext_debug("next leaf has no free space(%d,%d)\n",
1629 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1630 }
1631
1632 /*
1633 * There is no free space in the found leaf.
1634 * We're gonna add a new leaf in the tree.
1635 */
1636 err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1637 if (err)
1638 goto cleanup;
1639 depth = ext_depth(inode);
1640 eh = path[depth].p_hdr;
1641
1642 has_space:
1643 nearex = path[depth].p_ext;
1644
1645 err = ext4_ext_get_access(handle, inode, path + depth);
1646 if (err)
1647 goto cleanup;
1648
1649 if (!nearex) {
1650 /* there is no extent in this leaf, create first one */
1651 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1652 le32_to_cpu(newext->ee_block),
1653 ext_pblock(newext),
1654 ext4_ext_get_actual_len(newext));
1655 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1656 } else if (le32_to_cpu(newext->ee_block)
1657 > le32_to_cpu(nearex->ee_block)) {
1658 /* BUG_ON(newext->ee_block == nearex->ee_block); */
1659 if (nearex != EXT_LAST_EXTENT(eh)) {
1660 len = EXT_MAX_EXTENT(eh) - nearex;
1661 len = (len - 1) * sizeof(struct ext4_extent);
1662 len = len < 0 ? 0 : len;
1663 ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1664 "move %d from 0x%p to 0x%p\n",
1665 le32_to_cpu(newext->ee_block),
1666 ext_pblock(newext),
1667 ext4_ext_get_actual_len(newext),
1668 nearex, len, nearex + 1, nearex + 2);
1669 memmove(nearex + 2, nearex + 1, len);
1670 }
1671 path[depth].p_ext = nearex + 1;
1672 } else {
1673 BUG_ON(newext->ee_block == nearex->ee_block);
1674 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1675 len = len < 0 ? 0 : len;
1676 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1677 "move %d from 0x%p to 0x%p\n",
1678 le32_to_cpu(newext->ee_block),
1679 ext_pblock(newext),
1680 ext4_ext_get_actual_len(newext),
1681 nearex, len, nearex + 1, nearex + 2);
1682 memmove(nearex + 1, nearex, len);
1683 path[depth].p_ext = nearex;
1684 }
1685
1686 le16_add_cpu(&eh->eh_entries, 1);
1687 nearex = path[depth].p_ext;
1688 nearex->ee_block = newext->ee_block;
1689 ext4_ext_store_pblock(nearex, ext_pblock(newext));
1690 nearex->ee_len = newext->ee_len;
1691
1692 merge:
1693 /* try to merge extents to the right */
1694 ext4_ext_try_to_merge(inode, path, nearex);
1695
1696 /* try to merge extents to the left */
1697
1698 /* time to correct all indexes above */
1699 err = ext4_ext_correct_indexes(handle, inode, path);
1700 if (err)
1701 goto cleanup;
1702
1703 err = ext4_ext_dirty(handle, inode, path + depth);
1704
1705 cleanup:
1706 if (npath) {
1707 ext4_ext_drop_refs(npath);
1708 kfree(npath);
1709 }
1710 ext4_ext_invalidate_cache(inode);
1711 return err;
1712 }
1713
1714 int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1715 ext4_lblk_t num, ext_prepare_callback func,
1716 void *cbdata)
1717 {
1718 struct ext4_ext_path *path = NULL;
1719 struct ext4_ext_cache cbex;
1720 struct ext4_extent *ex;
1721 ext4_lblk_t next, start = 0, end = 0;
1722 ext4_lblk_t last = block + num;
1723 int depth, exists, err = 0;
1724
1725 BUG_ON(func == NULL);
1726 BUG_ON(inode == NULL);
1727
1728 while (block < last && block != EXT_MAX_BLOCK) {
1729 num = last - block;
1730 /* find extent for this block */
1731 path = ext4_ext_find_extent(inode, block, path);
1732 if (IS_ERR(path)) {
1733 err = PTR_ERR(path);
1734 path = NULL;
1735 break;
1736 }
1737
1738 depth = ext_depth(inode);
1739 BUG_ON(path[depth].p_hdr == NULL);
1740 ex = path[depth].p_ext;
1741 next = ext4_ext_next_allocated_block(path);
1742
1743 exists = 0;
1744 if (!ex) {
1745 /* there is no extent yet, so try to allocate
1746 * all requested space */
1747 start = block;
1748 end = block + num;
1749 } else if (le32_to_cpu(ex->ee_block) > block) {
1750 /* need to allocate space before found extent */
1751 start = block;
1752 end = le32_to_cpu(ex->ee_block);
1753 if (block + num < end)
1754 end = block + num;
1755 } else if (block >= le32_to_cpu(ex->ee_block)
1756 + ext4_ext_get_actual_len(ex)) {
1757 /* need to allocate space after found extent */
1758 start = block;
1759 end = block + num;
1760 if (end >= next)
1761 end = next;
1762 } else if (block >= le32_to_cpu(ex->ee_block)) {
1763 /*
1764 * some part of requested space is covered
1765 * by found extent
1766 */
1767 start = block;
1768 end = le32_to_cpu(ex->ee_block)
1769 + ext4_ext_get_actual_len(ex);
1770 if (block + num < end)
1771 end = block + num;
1772 exists = 1;
1773 } else {
1774 BUG();
1775 }
1776 BUG_ON(end <= start);
1777
1778 if (!exists) {
1779 cbex.ec_block = start;
1780 cbex.ec_len = end - start;
1781 cbex.ec_start = 0;
1782 cbex.ec_type = EXT4_EXT_CACHE_GAP;
1783 } else {
1784 cbex.ec_block = le32_to_cpu(ex->ee_block);
1785 cbex.ec_len = ext4_ext_get_actual_len(ex);
1786 cbex.ec_start = ext_pblock(ex);
1787 cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1788 }
1789
1790 BUG_ON(cbex.ec_len == 0);
1791 err = func(inode, path, &cbex, ex, cbdata);
1792 ext4_ext_drop_refs(path);
1793
1794 if (err < 0)
1795 break;
1796
1797 if (err == EXT_REPEAT)
1798 continue;
1799 else if (err == EXT_BREAK) {
1800 err = 0;
1801 break;
1802 }
1803
1804 if (ext_depth(inode) != depth) {
1805 /* depth was changed. we have to realloc path */
1806 kfree(path);
1807 path = NULL;
1808 }
1809
1810 block = cbex.ec_block + cbex.ec_len;
1811 }
1812
1813 if (path) {
1814 ext4_ext_drop_refs(path);
1815 kfree(path);
1816 }
1817
1818 return err;
1819 }
1820
1821 static void
1822 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1823 __u32 len, ext4_fsblk_t start, int type)
1824 {
1825 struct ext4_ext_cache *cex;
1826 BUG_ON(len == 0);
1827 cex = &EXT4_I(inode)->i_cached_extent;
1828 cex->ec_type = type;
1829 cex->ec_block = block;
1830 cex->ec_len = len;
1831 cex->ec_start = start;
1832 }
1833
1834 /*
1835 * ext4_ext_put_gap_in_cache:
1836 * calculate boundaries of the gap that the requested block fits into
1837 * and cache this gap
1838 */
1839 static void
1840 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1841 ext4_lblk_t block)
1842 {
1843 int depth = ext_depth(inode);
1844 unsigned long len;
1845 ext4_lblk_t lblock;
1846 struct ext4_extent *ex;
1847
1848 ex = path[depth].p_ext;
1849 if (ex == NULL) {
1850 /* there is no extent yet, so gap is [0;-] */
1851 lblock = 0;
1852 len = EXT_MAX_BLOCK;
1853 ext_debug("cache gap(whole file):");
1854 } else if (block < le32_to_cpu(ex->ee_block)) {
1855 lblock = block;
1856 len = le32_to_cpu(ex->ee_block) - block;
1857 ext_debug("cache gap(before): %u [%u:%u]",
1858 block,
1859 le32_to_cpu(ex->ee_block),
1860 ext4_ext_get_actual_len(ex));
1861 } else if (block >= le32_to_cpu(ex->ee_block)
1862 + ext4_ext_get_actual_len(ex)) {
1863 ext4_lblk_t next;
1864 lblock = le32_to_cpu(ex->ee_block)
1865 + ext4_ext_get_actual_len(ex);
1866
1867 next = ext4_ext_next_allocated_block(path);
1868 ext_debug("cache gap(after): [%u:%u] %u",
1869 le32_to_cpu(ex->ee_block),
1870 ext4_ext_get_actual_len(ex),
1871 block);
1872 BUG_ON(next == lblock);
1873 len = next - lblock;
1874 } else {
1875 lblock = len = 0;
1876 BUG();
1877 }
1878
1879 ext_debug(" -> %u:%lu\n", lblock, len);
1880 ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1881 }
1882
1883 static int
1884 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
1885 struct ext4_extent *ex)
1886 {
1887 struct ext4_ext_cache *cex;
1888
1889 cex = &EXT4_I(inode)->i_cached_extent;
1890
1891 /* has cache valid data? */
1892 if (cex->ec_type == EXT4_EXT_CACHE_NO)
1893 return EXT4_EXT_CACHE_NO;
1894
1895 BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1896 cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1897 if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1898 ex->ee_block = cpu_to_le32(cex->ec_block);
1899 ext4_ext_store_pblock(ex, cex->ec_start);
1900 ex->ee_len = cpu_to_le16(cex->ec_len);
1901 ext_debug("%u cached by %u:%u:%llu\n",
1902 block,
1903 cex->ec_block, cex->ec_len, cex->ec_start);
1904 return cex->ec_type;
1905 }
1906
1907 /* not in cache */
1908 return EXT4_EXT_CACHE_NO;
1909 }
1910
1911 /*
1912 * ext4_ext_rm_idx:
1913 * removes index from the index block.
1914 * It's used in truncate case only, thus all requests are for
1915 * last index in the block only.
1916 */
1917 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1918 struct ext4_ext_path *path)
1919 {
1920 struct buffer_head *bh;
1921 int err;
1922 ext4_fsblk_t leaf;
1923
1924 /* free index block */
1925 path--;
1926 leaf = idx_pblock(path->p_idx);
1927 BUG_ON(path->p_hdr->eh_entries == 0);
1928 err = ext4_ext_get_access(handle, inode, path);
1929 if (err)
1930 return err;
1931 le16_add_cpu(&path->p_hdr->eh_entries, -1);
1932 err = ext4_ext_dirty(handle, inode, path);
1933 if (err)
1934 return err;
1935 ext_debug("index is empty, remove it, free block %llu\n", leaf);
1936 bh = sb_find_get_block(inode->i_sb, leaf);
1937 ext4_forget(handle, 1, inode, bh, leaf);
1938 ext4_free_blocks(handle, inode, leaf, 1, 1);
1939 return err;
1940 }
1941
1942 /*
1943 * ext4_ext_calc_credits_for_single_extent:
1944 * This routine returns max. credits that needed to insert an extent
1945 * to the extent tree.
1946 * When pass the actual path, the caller should calculate credits
1947 * under i_data_sem.
1948 */
1949 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
1950 struct ext4_ext_path *path)
1951 {
1952 if (path) {
1953 int depth = ext_depth(inode);
1954 int ret = 0;
1955
1956 /* probably there is space in leaf? */
1957 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1958 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
1959
1960 /*
1961 * There are some space in the leaf tree, no
1962 * need to account for leaf block credit
1963 *
1964 * bitmaps and block group descriptor blocks
1965 * and other metadat blocks still need to be
1966 * accounted.
1967 */
1968 /* 1 bitmap, 1 block group descriptor */
1969 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
1970 }
1971 }
1972
1973 return ext4_chunk_trans_blocks(inode, nrblocks);
1974 }
1975
1976 /*
1977 * How many index/leaf blocks need to change/allocate to modify nrblocks?
1978 *
1979 * if nrblocks are fit in a single extent (chunk flag is 1), then
1980 * in the worse case, each tree level index/leaf need to be changed
1981 * if the tree split due to insert a new extent, then the old tree
1982 * index/leaf need to be updated too
1983 *
1984 * If the nrblocks are discontiguous, they could cause
1985 * the whole tree split more than once, but this is really rare.
1986 */
1987 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
1988 {
1989 int index;
1990 int depth = ext_depth(inode);
1991
1992 if (chunk)
1993 index = depth * 2;
1994 else
1995 index = depth * 3;
1996
1997 return index;
1998 }
1999
2000 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2001 struct ext4_extent *ex,
2002 ext4_lblk_t from, ext4_lblk_t to)
2003 {
2004 struct buffer_head *bh;
2005 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2006 int i, metadata = 0;
2007
2008 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2009 metadata = 1;
2010 #ifdef EXTENTS_STATS
2011 {
2012 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2013 spin_lock(&sbi->s_ext_stats_lock);
2014 sbi->s_ext_blocks += ee_len;
2015 sbi->s_ext_extents++;
2016 if (ee_len < sbi->s_ext_min)
2017 sbi->s_ext_min = ee_len;
2018 if (ee_len > sbi->s_ext_max)
2019 sbi->s_ext_max = ee_len;
2020 if (ext_depth(inode) > sbi->s_depth_max)
2021 sbi->s_depth_max = ext_depth(inode);
2022 spin_unlock(&sbi->s_ext_stats_lock);
2023 }
2024 #endif
2025 if (from >= le32_to_cpu(ex->ee_block)
2026 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2027 /* tail removal */
2028 ext4_lblk_t num;
2029 ext4_fsblk_t start;
2030
2031 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2032 start = ext_pblock(ex) + ee_len - num;
2033 ext_debug("free last %u blocks starting %llu\n", num, start);
2034 for (i = 0; i < num; i++) {
2035 bh = sb_find_get_block(inode->i_sb, start + i);
2036 ext4_forget(handle, 0, inode, bh, start + i);
2037 }
2038 ext4_free_blocks(handle, inode, start, num, metadata);
2039 } else if (from == le32_to_cpu(ex->ee_block)
2040 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2041 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
2042 from, to, le32_to_cpu(ex->ee_block), ee_len);
2043 } else {
2044 printk(KERN_INFO "strange request: removal(2) "
2045 "%u-%u from %u:%u\n",
2046 from, to, le32_to_cpu(ex->ee_block), ee_len);
2047 }
2048 return 0;
2049 }
2050
2051 static int
2052 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2053 struct ext4_ext_path *path, ext4_lblk_t start)
2054 {
2055 int err = 0, correct_index = 0;
2056 int depth = ext_depth(inode), credits;
2057 struct ext4_extent_header *eh;
2058 ext4_lblk_t a, b, block;
2059 unsigned num;
2060 ext4_lblk_t ex_ee_block;
2061 unsigned short ex_ee_len;
2062 unsigned uninitialized = 0;
2063 struct ext4_extent *ex;
2064
2065 /* the header must be checked already in ext4_ext_remove_space() */
2066 ext_debug("truncate since %u in leaf\n", start);
2067 if (!path[depth].p_hdr)
2068 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2069 eh = path[depth].p_hdr;
2070 BUG_ON(eh == NULL);
2071
2072 /* find where to start removing */
2073 ex = EXT_LAST_EXTENT(eh);
2074
2075 ex_ee_block = le32_to_cpu(ex->ee_block);
2076 if (ext4_ext_is_uninitialized(ex))
2077 uninitialized = 1;
2078 ex_ee_len = ext4_ext_get_actual_len(ex);
2079
2080 while (ex >= EXT_FIRST_EXTENT(eh) &&
2081 ex_ee_block + ex_ee_len > start) {
2082 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
2083 path[depth].p_ext = ex;
2084
2085 a = ex_ee_block > start ? ex_ee_block : start;
2086 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2087 ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2088
2089 ext_debug(" border %u:%u\n", a, b);
2090
2091 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2092 block = 0;
2093 num = 0;
2094 BUG();
2095 } else if (a != ex_ee_block) {
2096 /* remove tail of the extent */
2097 block = ex_ee_block;
2098 num = a - block;
2099 } else if (b != ex_ee_block + ex_ee_len - 1) {
2100 /* remove head of the extent */
2101 block = a;
2102 num = b - a;
2103 /* there is no "make a hole" API yet */
2104 BUG();
2105 } else {
2106 /* remove whole extent: excellent! */
2107 block = ex_ee_block;
2108 num = 0;
2109 BUG_ON(a != ex_ee_block);
2110 BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2111 }
2112
2113 /*
2114 * 3 for leaf, sb, and inode plus 2 (bmap and group
2115 * descriptor) for each block group; assume two block
2116 * groups plus ex_ee_len/blocks_per_block_group for
2117 * the worst case
2118 */
2119 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2120 if (ex == EXT_FIRST_EXTENT(eh)) {
2121 correct_index = 1;
2122 credits += (ext_depth(inode)) + 1;
2123 }
2124 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2125
2126 err = ext4_ext_journal_restart(handle, credits);
2127 if (err)
2128 goto out;
2129
2130 err = ext4_ext_get_access(handle, inode, path + depth);
2131 if (err)
2132 goto out;
2133
2134 err = ext4_remove_blocks(handle, inode, ex, a, b);
2135 if (err)
2136 goto out;
2137
2138 if (num == 0) {
2139 /* this extent is removed; mark slot entirely unused */
2140 ext4_ext_store_pblock(ex, 0);
2141 le16_add_cpu(&eh->eh_entries, -1);
2142 }
2143
2144 ex->ee_block = cpu_to_le32(block);
2145 ex->ee_len = cpu_to_le16(num);
2146 /*
2147 * Do not mark uninitialized if all the blocks in the
2148 * extent have been removed.
2149 */
2150 if (uninitialized && num)
2151 ext4_ext_mark_uninitialized(ex);
2152
2153 err = ext4_ext_dirty(handle, inode, path + depth);
2154 if (err)
2155 goto out;
2156
2157 ext_debug("new extent: %u:%u:%llu\n", block, num,
2158 ext_pblock(ex));
2159 ex--;
2160 ex_ee_block = le32_to_cpu(ex->ee_block);
2161 ex_ee_len = ext4_ext_get_actual_len(ex);
2162 }
2163
2164 if (correct_index && eh->eh_entries)
2165 err = ext4_ext_correct_indexes(handle, inode, path);
2166
2167 /* if this leaf is free, then we should
2168 * remove it from index block above */
2169 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2170 err = ext4_ext_rm_idx(handle, inode, path + depth);
2171
2172 out:
2173 return err;
2174 }
2175
2176 /*
2177 * ext4_ext_more_to_rm:
2178 * returns 1 if current index has to be freed (even partial)
2179 */
2180 static int
2181 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2182 {
2183 BUG_ON(path->p_idx == NULL);
2184
2185 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2186 return 0;
2187
2188 /*
2189 * if truncate on deeper level happened, it wasn't partial,
2190 * so we have to consider current index for truncation
2191 */
2192 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2193 return 0;
2194 return 1;
2195 }
2196
2197 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2198 {
2199 struct super_block *sb = inode->i_sb;
2200 int depth = ext_depth(inode);
2201 struct ext4_ext_path *path;
2202 handle_t *handle;
2203 int i = 0, err = 0;
2204
2205 ext_debug("truncate since %u\n", start);
2206
2207 /* probably first extent we're gonna free will be last in block */
2208 handle = ext4_journal_start(inode, depth + 1);
2209 if (IS_ERR(handle))
2210 return PTR_ERR(handle);
2211
2212 ext4_ext_invalidate_cache(inode);
2213
2214 /*
2215 * We start scanning from right side, freeing all the blocks
2216 * after i_size and walking into the tree depth-wise.
2217 */
2218 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2219 if (path == NULL) {
2220 ext4_journal_stop(handle);
2221 return -ENOMEM;
2222 }
2223 path[0].p_hdr = ext_inode_hdr(inode);
2224 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2225 err = -EIO;
2226 goto out;
2227 }
2228 path[0].p_depth = depth;
2229
2230 while (i >= 0 && err == 0) {
2231 if (i == depth) {
2232 /* this is leaf block */
2233 err = ext4_ext_rm_leaf(handle, inode, path, start);
2234 /* root level has p_bh == NULL, brelse() eats this */
2235 brelse(path[i].p_bh);
2236 path[i].p_bh = NULL;
2237 i--;
2238 continue;
2239 }
2240
2241 /* this is index block */
2242 if (!path[i].p_hdr) {
2243 ext_debug("initialize header\n");
2244 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2245 }
2246
2247 if (!path[i].p_idx) {
2248 /* this level hasn't been touched yet */
2249 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2250 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2251 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2252 path[i].p_hdr,
2253 le16_to_cpu(path[i].p_hdr->eh_entries));
2254 } else {
2255 /* we were already here, see at next index */
2256 path[i].p_idx--;
2257 }
2258
2259 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2260 i, EXT_FIRST_INDEX(path[i].p_hdr),
2261 path[i].p_idx);
2262 if (ext4_ext_more_to_rm(path + i)) {
2263 struct buffer_head *bh;
2264 /* go to the next level */
2265 ext_debug("move to level %d (block %llu)\n",
2266 i + 1, idx_pblock(path[i].p_idx));
2267 memset(path + i + 1, 0, sizeof(*path));
2268 bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2269 if (!bh) {
2270 /* should we reset i_size? */
2271 err = -EIO;
2272 break;
2273 }
2274 if (WARN_ON(i + 1 > depth)) {
2275 err = -EIO;
2276 break;
2277 }
2278 if (ext4_ext_check(inode, ext_block_hdr(bh),
2279 depth - i - 1)) {
2280 err = -EIO;
2281 break;
2282 }
2283 path[i + 1].p_bh = bh;
2284
2285 /* save actual number of indexes since this
2286 * number is changed at the next iteration */
2287 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2288 i++;
2289 } else {
2290 /* we finished processing this index, go up */
2291 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2292 /* index is empty, remove it;
2293 * handle must be already prepared by the
2294 * truncatei_leaf() */
2295 err = ext4_ext_rm_idx(handle, inode, path + i);
2296 }
2297 /* root level has p_bh == NULL, brelse() eats this */
2298 brelse(path[i].p_bh);
2299 path[i].p_bh = NULL;
2300 i--;
2301 ext_debug("return to level %d\n", i);
2302 }
2303 }
2304
2305 /* TODO: flexible tree reduction should be here */
2306 if (path->p_hdr->eh_entries == 0) {
2307 /*
2308 * truncate to zero freed all the tree,
2309 * so we need to correct eh_depth
2310 */
2311 err = ext4_ext_get_access(handle, inode, path);
2312 if (err == 0) {
2313 ext_inode_hdr(inode)->eh_depth = 0;
2314 ext_inode_hdr(inode)->eh_max =
2315 cpu_to_le16(ext4_ext_space_root(inode));
2316 err = ext4_ext_dirty(handle, inode, path);
2317 }
2318 }
2319 out:
2320 ext4_ext_drop_refs(path);
2321 kfree(path);
2322 ext4_journal_stop(handle);
2323
2324 return err;
2325 }
2326
2327 /*
2328 * called at mount time
2329 */
2330 void ext4_ext_init(struct super_block *sb)
2331 {
2332 /*
2333 * possible initialization would be here
2334 */
2335
2336 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2337 printk(KERN_INFO "EXT4-fs: file extents enabled");
2338 #ifdef AGGRESSIVE_TEST
2339 printk(", aggressive tests");
2340 #endif
2341 #ifdef CHECK_BINSEARCH
2342 printk(", check binsearch");
2343 #endif
2344 #ifdef EXTENTS_STATS
2345 printk(", stats");
2346 #endif
2347 printk("\n");
2348 #ifdef EXTENTS_STATS
2349 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2350 EXT4_SB(sb)->s_ext_min = 1 << 30;
2351 EXT4_SB(sb)->s_ext_max = 0;
2352 #endif
2353 }
2354 }
2355
2356 /*
2357 * called at umount time
2358 */
2359 void ext4_ext_release(struct super_block *sb)
2360 {
2361 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2362 return;
2363
2364 #ifdef EXTENTS_STATS
2365 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2366 struct ext4_sb_info *sbi = EXT4_SB(sb);
2367 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2368 sbi->s_ext_blocks, sbi->s_ext_extents,
2369 sbi->s_ext_blocks / sbi->s_ext_extents);
2370 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2371 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2372 }
2373 #endif
2374 }
2375
2376 static void bi_complete(struct bio *bio, int error)
2377 {
2378 complete((struct completion *)bio->bi_private);
2379 }
2380
2381 /* FIXME!! we need to try to merge to left or right after zero-out */
2382 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2383 {
2384 int ret = -EIO;
2385 struct bio *bio;
2386 int blkbits, blocksize;
2387 sector_t ee_pblock;
2388 struct completion event;
2389 unsigned int ee_len, len, done, offset;
2390
2391
2392 blkbits = inode->i_blkbits;
2393 blocksize = inode->i_sb->s_blocksize;
2394 ee_len = ext4_ext_get_actual_len(ex);
2395 ee_pblock = ext_pblock(ex);
2396
2397 /* convert ee_pblock to 512 byte sectors */
2398 ee_pblock = ee_pblock << (blkbits - 9);
2399
2400 while (ee_len > 0) {
2401
2402 if (ee_len > BIO_MAX_PAGES)
2403 len = BIO_MAX_PAGES;
2404 else
2405 len = ee_len;
2406
2407 bio = bio_alloc(GFP_NOIO, len);
2408 if (!bio)
2409 return -ENOMEM;
2410 bio->bi_sector = ee_pblock;
2411 bio->bi_bdev = inode->i_sb->s_bdev;
2412
2413 done = 0;
2414 offset = 0;
2415 while (done < len) {
2416 ret = bio_add_page(bio, ZERO_PAGE(0),
2417 blocksize, offset);
2418 if (ret != blocksize) {
2419 /*
2420 * We can't add any more pages because of
2421 * hardware limitations. Start a new bio.
2422 */
2423 break;
2424 }
2425 done++;
2426 offset += blocksize;
2427 if (offset >= PAGE_CACHE_SIZE)
2428 offset = 0;
2429 }
2430
2431 init_completion(&event);
2432 bio->bi_private = &event;
2433 bio->bi_end_io = bi_complete;
2434 submit_bio(WRITE, bio);
2435 wait_for_completion(&event);
2436
2437 if (test_bit(BIO_UPTODATE, &bio->bi_flags))
2438 ret = 0;
2439 else {
2440 ret = -EIO;
2441 break;
2442 }
2443 bio_put(bio);
2444 ee_len -= done;
2445 ee_pblock += done << (blkbits - 9);
2446 }
2447 return ret;
2448 }
2449
2450 #define EXT4_EXT_ZERO_LEN 7
2451
2452 /*
2453 * This function is called by ext4_ext_get_blocks() if someone tries to write
2454 * to an uninitialized extent. It may result in splitting the uninitialized
2455 * extent into multiple extents (upto three - one initialized and two
2456 * uninitialized).
2457 * There are three possibilities:
2458 * a> There is no split required: Entire extent should be initialized
2459 * b> Splits in two extents: Write is happening at either end of the extent
2460 * c> Splits in three extents: Somone is writing in middle of the extent
2461 */
2462 static int ext4_ext_convert_to_initialized(handle_t *handle,
2463 struct inode *inode,
2464 struct ext4_ext_path *path,
2465 ext4_lblk_t iblock,
2466 unsigned int max_blocks)
2467 {
2468 struct ext4_extent *ex, newex, orig_ex;
2469 struct ext4_extent *ex1 = NULL;
2470 struct ext4_extent *ex2 = NULL;
2471 struct ext4_extent *ex3 = NULL;
2472 struct ext4_extent_header *eh;
2473 ext4_lblk_t ee_block;
2474 unsigned int allocated, ee_len, depth;
2475 ext4_fsblk_t newblock;
2476 int err = 0;
2477 int ret = 0;
2478
2479 depth = ext_depth(inode);
2480 eh = path[depth].p_hdr;
2481 ex = path[depth].p_ext;
2482 ee_block = le32_to_cpu(ex->ee_block);
2483 ee_len = ext4_ext_get_actual_len(ex);
2484 allocated = ee_len - (iblock - ee_block);
2485 newblock = iblock - ee_block + ext_pblock(ex);
2486 ex2 = ex;
2487 orig_ex.ee_block = ex->ee_block;
2488 orig_ex.ee_len = cpu_to_le16(ee_len);
2489 ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2490
2491 err = ext4_ext_get_access(handle, inode, path + depth);
2492 if (err)
2493 goto out;
2494 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2495 if (ee_len <= 2*EXT4_EXT_ZERO_LEN) {
2496 err = ext4_ext_zeroout(inode, &orig_ex);
2497 if (err)
2498 goto fix_extent_len;
2499 /* update the extent length and mark as initialized */
2500 ex->ee_block = orig_ex.ee_block;
2501 ex->ee_len = orig_ex.ee_len;
2502 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2503 ext4_ext_dirty(handle, inode, path + depth);
2504 /* zeroed the full extent */
2505 return allocated;
2506 }
2507
2508 /* ex1: ee_block to iblock - 1 : uninitialized */
2509 if (iblock > ee_block) {
2510 ex1 = ex;
2511 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2512 ext4_ext_mark_uninitialized(ex1);
2513 ex2 = &newex;
2514 }
2515 /*
2516 * for sanity, update the length of the ex2 extent before
2517 * we insert ex3, if ex1 is NULL. This is to avoid temporary
2518 * overlap of blocks.
2519 */
2520 if (!ex1 && allocated > max_blocks)
2521 ex2->ee_len = cpu_to_le16(max_blocks);
2522 /* ex3: to ee_block + ee_len : uninitialised */
2523 if (allocated > max_blocks) {
2524 unsigned int newdepth;
2525 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2526 if (allocated <= EXT4_EXT_ZERO_LEN) {
2527 /*
2528 * iblock == ee_block is handled by the zerouout
2529 * at the beginning.
2530 * Mark first half uninitialized.
2531 * Mark second half initialized and zero out the
2532 * initialized extent
2533 */
2534 ex->ee_block = orig_ex.ee_block;
2535 ex->ee_len = cpu_to_le16(ee_len - allocated);
2536 ext4_ext_mark_uninitialized(ex);
2537 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2538 ext4_ext_dirty(handle, inode, path + depth);
2539
2540 ex3 = &newex;
2541 ex3->ee_block = cpu_to_le32(iblock);
2542 ext4_ext_store_pblock(ex3, newblock);
2543 ex3->ee_len = cpu_to_le16(allocated);
2544 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2545 if (err == -ENOSPC) {
2546 err = ext4_ext_zeroout(inode, &orig_ex);
2547 if (err)
2548 goto fix_extent_len;
2549 ex->ee_block = orig_ex.ee_block;
2550 ex->ee_len = orig_ex.ee_len;
2551 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2552 ext4_ext_dirty(handle, inode, path + depth);
2553 /* blocks available from iblock */
2554 return allocated;
2555
2556 } else if (err)
2557 goto fix_extent_len;
2558
2559 /*
2560 * We need to zero out the second half because
2561 * an fallocate request can update file size and
2562 * converting the second half to initialized extent
2563 * implies that we can leak some junk data to user
2564 * space.
2565 */
2566 err = ext4_ext_zeroout(inode, ex3);
2567 if (err) {
2568 /*
2569 * We should actually mark the
2570 * second half as uninit and return error
2571 * Insert would have changed the extent
2572 */
2573 depth = ext_depth(inode);
2574 ext4_ext_drop_refs(path);
2575 path = ext4_ext_find_extent(inode,
2576 iblock, path);
2577 if (IS_ERR(path)) {
2578 err = PTR_ERR(path);
2579 return err;
2580 }
2581 /* get the second half extent details */
2582 ex = path[depth].p_ext;
2583 err = ext4_ext_get_access(handle, inode,
2584 path + depth);
2585 if (err)
2586 return err;
2587 ext4_ext_mark_uninitialized(ex);
2588 ext4_ext_dirty(handle, inode, path + depth);
2589 return err;
2590 }
2591
2592 /* zeroed the second half */
2593 return allocated;
2594 }
2595 ex3 = &newex;
2596 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2597 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2598 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2599 ext4_ext_mark_uninitialized(ex3);
2600 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2601 if (err == -ENOSPC) {
2602 err = ext4_ext_zeroout(inode, &orig_ex);
2603 if (err)
2604 goto fix_extent_len;
2605 /* update the extent length and mark as initialized */
2606 ex->ee_block = orig_ex.ee_block;
2607 ex->ee_len = orig_ex.ee_len;
2608 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2609 ext4_ext_dirty(handle, inode, path + depth);
2610 /* zeroed the full extent */
2611 /* blocks available from iblock */
2612 return allocated;
2613
2614 } else if (err)
2615 goto fix_extent_len;
2616 /*
2617 * The depth, and hence eh & ex might change
2618 * as part of the insert above.
2619 */
2620 newdepth = ext_depth(inode);
2621 /*
2622 * update the extent length after successful insert of the
2623 * split extent
2624 */
2625 orig_ex.ee_len = cpu_to_le16(ee_len -
2626 ext4_ext_get_actual_len(ex3));
2627 depth = newdepth;
2628 ext4_ext_drop_refs(path);
2629 path = ext4_ext_find_extent(inode, iblock, path);
2630 if (IS_ERR(path)) {
2631 err = PTR_ERR(path);
2632 goto out;
2633 }
2634 eh = path[depth].p_hdr;
2635 ex = path[depth].p_ext;
2636 if (ex2 != &newex)
2637 ex2 = ex;
2638
2639 err = ext4_ext_get_access(handle, inode, path + depth);
2640 if (err)
2641 goto out;
2642
2643 allocated = max_blocks;
2644
2645 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2646 * to insert a extent in the middle zerout directly
2647 * otherwise give the extent a chance to merge to left
2648 */
2649 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2650 iblock != ee_block) {
2651 err = ext4_ext_zeroout(inode, &orig_ex);
2652 if (err)
2653 goto fix_extent_len;
2654 /* update the extent length and mark as initialized */
2655 ex->ee_block = orig_ex.ee_block;
2656 ex->ee_len = orig_ex.ee_len;
2657 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2658 ext4_ext_dirty(handle, inode, path + depth);
2659 /* zero out the first half */
2660 /* blocks available from iblock */
2661 return allocated;
2662 }
2663 }
2664 /*
2665 * If there was a change of depth as part of the
2666 * insertion of ex3 above, we need to update the length
2667 * of the ex1 extent again here
2668 */
2669 if (ex1 && ex1 != ex) {
2670 ex1 = ex;
2671 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2672 ext4_ext_mark_uninitialized(ex1);
2673 ex2 = &newex;
2674 }
2675 /* ex2: iblock to iblock + maxblocks-1 : initialised */
2676 ex2->ee_block = cpu_to_le32(iblock);
2677 ext4_ext_store_pblock(ex2, newblock);
2678 ex2->ee_len = cpu_to_le16(allocated);
2679 if (ex2 != ex)
2680 goto insert;
2681 /*
2682 * New (initialized) extent starts from the first block
2683 * in the current extent. i.e., ex2 == ex
2684 * We have to see if it can be merged with the extent
2685 * on the left.
2686 */
2687 if (ex2 > EXT_FIRST_EXTENT(eh)) {
2688 /*
2689 * To merge left, pass "ex2 - 1" to try_to_merge(),
2690 * since it merges towards right _only_.
2691 */
2692 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2693 if (ret) {
2694 err = ext4_ext_correct_indexes(handle, inode, path);
2695 if (err)
2696 goto out;
2697 depth = ext_depth(inode);
2698 ex2--;
2699 }
2700 }
2701 /*
2702 * Try to Merge towards right. This might be required
2703 * only when the whole extent is being written to.
2704 * i.e. ex2 == ex and ex3 == NULL.
2705 */
2706 if (!ex3) {
2707 ret = ext4_ext_try_to_merge(inode, path, ex2);
2708 if (ret) {
2709 err = ext4_ext_correct_indexes(handle, inode, path);
2710 if (err)
2711 goto out;
2712 }
2713 }
2714 /* Mark modified extent as dirty */
2715 err = ext4_ext_dirty(handle, inode, path + depth);
2716 goto out;
2717 insert:
2718 err = ext4_ext_insert_extent(handle, inode, path, &newex);
2719 if (err == -ENOSPC) {
2720 err = ext4_ext_zeroout(inode, &orig_ex);
2721 if (err)
2722 goto fix_extent_len;
2723 /* update the extent length and mark as initialized */
2724 ex->ee_block = orig_ex.ee_block;
2725 ex->ee_len = orig_ex.ee_len;
2726 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2727 ext4_ext_dirty(handle, inode, path + depth);
2728 /* zero out the first half */
2729 return allocated;
2730 } else if (err)
2731 goto fix_extent_len;
2732 out:
2733 return err ? err : allocated;
2734
2735 fix_extent_len:
2736 ex->ee_block = orig_ex.ee_block;
2737 ex->ee_len = orig_ex.ee_len;
2738 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2739 ext4_ext_mark_uninitialized(ex);
2740 ext4_ext_dirty(handle, inode, path + depth);
2741 return err;
2742 }
2743
2744 /*
2745 * Block allocation/map/preallocation routine for extents based files
2746 *
2747 *
2748 * Need to be called with
2749 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
2750 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
2751 *
2752 * return > 0, number of of blocks already mapped/allocated
2753 * if create == 0 and these are pre-allocated blocks
2754 * buffer head is unmapped
2755 * otherwise blocks are mapped
2756 *
2757 * return = 0, if plain look up failed (blocks have not been allocated)
2758 * buffer head is unmapped
2759 *
2760 * return < 0, error case.
2761 */
2762 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
2763 ext4_lblk_t iblock,
2764 unsigned int max_blocks, struct buffer_head *bh_result,
2765 int create, int extend_disksize)
2766 {
2767 struct ext4_ext_path *path = NULL;
2768 struct ext4_extent_header *eh;
2769 struct ext4_extent newex, *ex;
2770 ext4_fsblk_t newblock;
2771 int err = 0, depth, ret, cache_type;
2772 unsigned int allocated = 0;
2773 struct ext4_allocation_request ar;
2774 loff_t disksize;
2775
2776 __clear_bit(BH_New, &bh_result->b_state);
2777 ext_debug("blocks %u/%u requested for inode %u\n",
2778 iblock, max_blocks, inode->i_ino);
2779
2780 /* check in cache */
2781 cache_type = ext4_ext_in_cache(inode, iblock, &newex);
2782 if (cache_type) {
2783 if (cache_type == EXT4_EXT_CACHE_GAP) {
2784 if (!create) {
2785 /*
2786 * block isn't allocated yet and
2787 * user doesn't want to allocate it
2788 */
2789 goto out2;
2790 }
2791 /* we should allocate requested block */
2792 } else if (cache_type == EXT4_EXT_CACHE_EXTENT) {
2793 /* block is already allocated */
2794 newblock = iblock
2795 - le32_to_cpu(newex.ee_block)
2796 + ext_pblock(&newex);
2797 /* number of remaining blocks in the extent */
2798 allocated = ext4_ext_get_actual_len(&newex) -
2799 (iblock - le32_to_cpu(newex.ee_block));
2800 goto out;
2801 } else {
2802 BUG();
2803 }
2804 }
2805
2806 /* find extent for this block */
2807 path = ext4_ext_find_extent(inode, iblock, NULL);
2808 if (IS_ERR(path)) {
2809 err = PTR_ERR(path);
2810 path = NULL;
2811 goto out2;
2812 }
2813
2814 depth = ext_depth(inode);
2815
2816 /*
2817 * consistent leaf must not be empty;
2818 * this situation is possible, though, _during_ tree modification;
2819 * this is why assert can't be put in ext4_ext_find_extent()
2820 */
2821 BUG_ON(path[depth].p_ext == NULL && depth != 0);
2822 eh = path[depth].p_hdr;
2823
2824 ex = path[depth].p_ext;
2825 if (ex) {
2826 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
2827 ext4_fsblk_t ee_start = ext_pblock(ex);
2828 unsigned short ee_len;
2829
2830 /*
2831 * Uninitialized extents are treated as holes, except that
2832 * we split out initialized portions during a write.
2833 */
2834 ee_len = ext4_ext_get_actual_len(ex);
2835 /* if found extent covers block, simply return it */
2836 if (iblock >= ee_block && iblock < ee_block + ee_len) {
2837 newblock = iblock - ee_block + ee_start;
2838 /* number of remaining blocks in the extent */
2839 allocated = ee_len - (iblock - ee_block);
2840 ext_debug("%u fit into %lu:%d -> %llu\n", iblock,
2841 ee_block, ee_len, newblock);
2842
2843 /* Do not put uninitialized extent in the cache */
2844 if (!ext4_ext_is_uninitialized(ex)) {
2845 ext4_ext_put_in_cache(inode, ee_block,
2846 ee_len, ee_start,
2847 EXT4_EXT_CACHE_EXTENT);
2848 goto out;
2849 }
2850 if (create == EXT4_CREATE_UNINITIALIZED_EXT)
2851 goto out;
2852 if (!create) {
2853 /*
2854 * We have blocks reserved already. We
2855 * return allocated blocks so that delalloc
2856 * won't do block reservation for us. But
2857 * the buffer head will be unmapped so that
2858 * a read from the block returns 0s.
2859 */
2860 if (allocated > max_blocks)
2861 allocated = max_blocks;
2862 set_buffer_unwritten(bh_result);
2863 goto out2;
2864 }
2865
2866 ret = ext4_ext_convert_to_initialized(handle, inode,
2867 path, iblock,
2868 max_blocks);
2869 if (ret <= 0) {
2870 err = ret;
2871 goto out2;
2872 } else
2873 allocated = ret;
2874 goto outnew;
2875 }
2876 }
2877
2878 /*
2879 * requested block isn't allocated yet;
2880 * we couldn't try to create block if create flag is zero
2881 */
2882 if (!create) {
2883 /*
2884 * put just found gap into cache to speed up
2885 * subsequent requests
2886 */
2887 ext4_ext_put_gap_in_cache(inode, path, iblock);
2888 goto out2;
2889 }
2890 /*
2891 * Okay, we need to do block allocation.
2892 */
2893
2894 /* find neighbour allocated blocks */
2895 ar.lleft = iblock;
2896 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
2897 if (err)
2898 goto out2;
2899 ar.lright = iblock;
2900 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
2901 if (err)
2902 goto out2;
2903
2904 /*
2905 * See if request is beyond maximum number of blocks we can have in
2906 * a single extent. For an initialized extent this limit is
2907 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
2908 * EXT_UNINIT_MAX_LEN.
2909 */
2910 if (max_blocks > EXT_INIT_MAX_LEN &&
2911 create != EXT4_CREATE_UNINITIALIZED_EXT)
2912 max_blocks = EXT_INIT_MAX_LEN;
2913 else if (max_blocks > EXT_UNINIT_MAX_LEN &&
2914 create == EXT4_CREATE_UNINITIALIZED_EXT)
2915 max_blocks = EXT_UNINIT_MAX_LEN;
2916
2917 /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
2918 newex.ee_block = cpu_to_le32(iblock);
2919 newex.ee_len = cpu_to_le16(max_blocks);
2920 err = ext4_ext_check_overlap(inode, &newex, path);
2921 if (err)
2922 allocated = ext4_ext_get_actual_len(&newex);
2923 else
2924 allocated = max_blocks;
2925
2926 /* allocate new block */
2927 ar.inode = inode;
2928 ar.goal = ext4_ext_find_goal(inode, path, iblock);
2929 ar.logical = iblock;
2930 ar.len = allocated;
2931 if (S_ISREG(inode->i_mode))
2932 ar.flags = EXT4_MB_HINT_DATA;
2933 else
2934 /* disable in-core preallocation for non-regular files */
2935 ar.flags = 0;
2936 newblock = ext4_mb_new_blocks(handle, &ar, &err);
2937 if (!newblock)
2938 goto out2;
2939 ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2940 ar.goal, newblock, allocated);
2941
2942 /* try to insert new extent into found leaf and return */
2943 ext4_ext_store_pblock(&newex, newblock);
2944 newex.ee_len = cpu_to_le16(ar.len);
2945 if (create == EXT4_CREATE_UNINITIALIZED_EXT) /* Mark uninitialized */
2946 ext4_ext_mark_uninitialized(&newex);
2947 err = ext4_ext_insert_extent(handle, inode, path, &newex);
2948 if (err) {
2949 /* free data blocks we just allocated */
2950 /* not a good idea to call discard here directly,
2951 * but otherwise we'd need to call it every free() */
2952 ext4_discard_preallocations(inode);
2953 ext4_free_blocks(handle, inode, ext_pblock(&newex),
2954 ext4_ext_get_actual_len(&newex), 0);
2955 goto out2;
2956 }
2957
2958 /* previous routine could use block we allocated */
2959 newblock = ext_pblock(&newex);
2960 allocated = ext4_ext_get_actual_len(&newex);
2961 outnew:
2962 if (extend_disksize) {
2963 disksize = ((loff_t) iblock + ar.len) << inode->i_blkbits;
2964 if (disksize > i_size_read(inode))
2965 disksize = i_size_read(inode);
2966 if (disksize > EXT4_I(inode)->i_disksize)
2967 EXT4_I(inode)->i_disksize = disksize;
2968 }
2969
2970 set_buffer_new(bh_result);
2971
2972 /* Cache only when it is _not_ an uninitialized extent */
2973 if (create != EXT4_CREATE_UNINITIALIZED_EXT)
2974 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2975 EXT4_EXT_CACHE_EXTENT);
2976 out:
2977 if (allocated > max_blocks)
2978 allocated = max_blocks;
2979 ext4_ext_show_leaf(inode, path);
2980 set_buffer_mapped(bh_result);
2981 bh_result->b_bdev = inode->i_sb->s_bdev;
2982 bh_result->b_blocknr = newblock;
2983 out2:
2984 if (path) {
2985 ext4_ext_drop_refs(path);
2986 kfree(path);
2987 }
2988 return err ? err : allocated;
2989 }
2990
2991 void ext4_ext_truncate(struct inode *inode)
2992 {
2993 struct address_space *mapping = inode->i_mapping;
2994 struct super_block *sb = inode->i_sb;
2995 ext4_lblk_t last_block;
2996 handle_t *handle;
2997 int err = 0;
2998
2999 /*
3000 * probably first extent we're gonna free will be last in block
3001 */
3002 err = ext4_writepage_trans_blocks(inode);
3003 handle = ext4_journal_start(inode, err);
3004 if (IS_ERR(handle))
3005 return;
3006
3007 if (inode->i_size & (sb->s_blocksize - 1))
3008 ext4_block_truncate_page(handle, mapping, inode->i_size);
3009
3010 if (ext4_orphan_add(handle, inode))
3011 goto out_stop;
3012
3013 down_write(&EXT4_I(inode)->i_data_sem);
3014 ext4_ext_invalidate_cache(inode);
3015
3016 ext4_discard_preallocations(inode);
3017
3018 /*
3019 * TODO: optimization is possible here.
3020 * Probably we need not scan at all,
3021 * because page truncation is enough.
3022 */
3023
3024 /* we have to know where to truncate from in crash case */
3025 EXT4_I(inode)->i_disksize = inode->i_size;
3026 ext4_mark_inode_dirty(handle, inode);
3027
3028 last_block = (inode->i_size + sb->s_blocksize - 1)
3029 >> EXT4_BLOCK_SIZE_BITS(sb);
3030 err = ext4_ext_remove_space(inode, last_block);
3031
3032 /* In a multi-transaction truncate, we only make the final
3033 * transaction synchronous.
3034 */
3035 if (IS_SYNC(inode))
3036 ext4_handle_sync(handle);
3037
3038 out_stop:
3039 up_write(&EXT4_I(inode)->i_data_sem);
3040 /*
3041 * If this was a simple ftruncate() and the file will remain alive,
3042 * then we need to clear up the orphan record which we created above.
3043 * However, if this was a real unlink then we were called by
3044 * ext4_delete_inode(), and we allow that function to clean up the
3045 * orphan info for us.
3046 */
3047 if (inode->i_nlink)
3048 ext4_orphan_del(handle, inode);
3049
3050 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3051 ext4_mark_inode_dirty(handle, inode);
3052 ext4_journal_stop(handle);
3053 }
3054
3055 static void ext4_falloc_update_inode(struct inode *inode,
3056 int mode, loff_t new_size, int update_ctime)
3057 {
3058 struct timespec now;
3059
3060 if (update_ctime) {
3061 now = current_fs_time(inode->i_sb);
3062 if (!timespec_equal(&inode->i_ctime, &now))
3063 inode->i_ctime = now;
3064 }
3065 /*
3066 * Update only when preallocation was requested beyond
3067 * the file size.
3068 */
3069 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3070 if (new_size > i_size_read(inode))
3071 i_size_write(inode, new_size);
3072 if (new_size > EXT4_I(inode)->i_disksize)
3073 ext4_update_i_disksize(inode, new_size);
3074 }
3075
3076 }
3077
3078 /*
3079 * preallocate space for a file. This implements ext4's fallocate inode
3080 * operation, which gets called from sys_fallocate system call.
3081 * For block-mapped files, posix_fallocate should fall back to the method
3082 * of writing zeroes to the required new blocks (the same behavior which is
3083 * expected for file systems which do not support fallocate() system call).
3084 */
3085 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
3086 {
3087 handle_t *handle;
3088 ext4_lblk_t block;
3089 loff_t new_size;
3090 unsigned int max_blocks;
3091 int ret = 0;
3092 int ret2 = 0;
3093 int retries = 0;
3094 struct buffer_head map_bh;
3095 unsigned int credits, blkbits = inode->i_blkbits;
3096
3097 /*
3098 * currently supporting (pre)allocate mode for extent-based
3099 * files _only_
3100 */
3101 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3102 return -EOPNOTSUPP;
3103
3104 /* preallocation to directories is currently not supported */
3105 if (S_ISDIR(inode->i_mode))
3106 return -ENODEV;
3107
3108 block = offset >> blkbits;
3109 /*
3110 * We can't just convert len to max_blocks because
3111 * If blocksize = 4096 offset = 3072 and len = 2048
3112 */
3113 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3114 - block;
3115 /*
3116 * credits to insert 1 extent into extent tree
3117 */
3118 credits = ext4_chunk_trans_blocks(inode, max_blocks);
3119 mutex_lock(&inode->i_mutex);
3120 retry:
3121 while (ret >= 0 && ret < max_blocks) {
3122 block = block + ret;
3123 max_blocks = max_blocks - ret;
3124 handle = ext4_journal_start(inode, credits);
3125 if (IS_ERR(handle)) {
3126 ret = PTR_ERR(handle);
3127 break;
3128 }
3129 ret = ext4_get_blocks_wrap(handle, inode, block,
3130 max_blocks, &map_bh,
3131 EXT4_CREATE_UNINITIALIZED_EXT, 0, 0);
3132 if (ret <= 0) {
3133 #ifdef EXT4FS_DEBUG
3134 WARN_ON(ret <= 0);
3135 printk(KERN_ERR "%s: ext4_ext_get_blocks "
3136 "returned error inode#%lu, block=%u, "
3137 "max_blocks=%u", __func__,
3138 inode->i_ino, block, max_blocks);
3139 #endif
3140 ext4_mark_inode_dirty(handle, inode);
3141 ret2 = ext4_journal_stop(handle);
3142 break;
3143 }
3144 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3145 blkbits) >> blkbits))
3146 new_size = offset + len;
3147 else
3148 new_size = (block + ret) << blkbits;
3149
3150 ext4_falloc_update_inode(inode, mode, new_size,
3151 buffer_new(&map_bh));
3152 ext4_mark_inode_dirty(handle, inode);
3153 ret2 = ext4_journal_stop(handle);
3154 if (ret2)
3155 break;
3156 }
3157 if (ret == -ENOSPC &&
3158 ext4_should_retry_alloc(inode->i_sb, &retries)) {
3159 ret = 0;
3160 goto retry;
3161 }
3162 mutex_unlock(&inode->i_mutex);
3163 return ret > 0 ? ret2 : ret;
3164 }
3165
3166 /*
3167 * Callback function called for each extent to gather FIEMAP information.
3168 */
3169 static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
3170 struct ext4_ext_cache *newex, struct ext4_extent *ex,
3171 void *data)
3172 {
3173 struct fiemap_extent_info *fieinfo = data;
3174 unsigned long blksize_bits = inode->i_sb->s_blocksize_bits;
3175 __u64 logical;
3176 __u64 physical;
3177 __u64 length;
3178 __u32 flags = 0;
3179 int error;
3180
3181 logical = (__u64)newex->ec_block << blksize_bits;
3182
3183 if (newex->ec_type == EXT4_EXT_CACHE_GAP) {
3184 pgoff_t offset;
3185 struct page *page;
3186 struct buffer_head *bh = NULL;
3187
3188 offset = logical >> PAGE_SHIFT;
3189 page = find_get_page(inode->i_mapping, offset);
3190 if (!page || !page_has_buffers(page))
3191 return EXT_CONTINUE;
3192
3193 bh = page_buffers(page);
3194
3195 if (!bh)
3196 return EXT_CONTINUE;
3197
3198 if (buffer_delay(bh)) {
3199 flags |= FIEMAP_EXTENT_DELALLOC;
3200 page_cache_release(page);
3201 } else {
3202 page_cache_release(page);
3203 return EXT_CONTINUE;
3204 }
3205 }
3206
3207 physical = (__u64)newex->ec_start << blksize_bits;
3208 length = (__u64)newex->ec_len << blksize_bits;
3209
3210 if (ex && ext4_ext_is_uninitialized(ex))
3211 flags |= FIEMAP_EXTENT_UNWRITTEN;
3212
3213 /*
3214 * If this extent reaches EXT_MAX_BLOCK, it must be last.
3215 *
3216 * Or if ext4_ext_next_allocated_block is EXT_MAX_BLOCK,
3217 * this also indicates no more allocated blocks.
3218 *
3219 * XXX this might miss a single-block extent at EXT_MAX_BLOCK
3220 */
3221 if (logical + length - 1 == EXT_MAX_BLOCK ||
3222 ext4_ext_next_allocated_block(path) == EXT_MAX_BLOCK)
3223 flags |= FIEMAP_EXTENT_LAST;
3224
3225 error = fiemap_fill_next_extent(fieinfo, logical, physical,
3226 length, flags);
3227 if (error < 0)
3228 return error;
3229 if (error == 1)
3230 return EXT_BREAK;
3231
3232 return EXT_CONTINUE;
3233 }
3234
3235 /* fiemap flags we can handle specified here */
3236 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
3237
3238 static int ext4_xattr_fiemap(struct inode *inode,
3239 struct fiemap_extent_info *fieinfo)
3240 {
3241 __u64 physical = 0;
3242 __u64 length;
3243 __u32 flags = FIEMAP_EXTENT_LAST;
3244 int blockbits = inode->i_sb->s_blocksize_bits;
3245 int error = 0;
3246
3247 /* in-inode? */
3248 if (EXT4_I(inode)->i_state & EXT4_STATE_XATTR) {
3249 struct ext4_iloc iloc;
3250 int offset; /* offset of xattr in inode */
3251
3252 error = ext4_get_inode_loc(inode, &iloc);
3253 if (error)
3254 return error;
3255 physical = iloc.bh->b_blocknr << blockbits;
3256 offset = EXT4_GOOD_OLD_INODE_SIZE +
3257 EXT4_I(inode)->i_extra_isize;
3258 physical += offset;
3259 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
3260 flags |= FIEMAP_EXTENT_DATA_INLINE;
3261 } else { /* external block */
3262 physical = EXT4_I(inode)->i_file_acl << blockbits;
3263 length = inode->i_sb->s_blocksize;
3264 }
3265
3266 if (physical)
3267 error = fiemap_fill_next_extent(fieinfo, 0, physical,
3268 length, flags);
3269 return (error < 0 ? error : 0);
3270 }
3271
3272 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3273 __u64 start, __u64 len)
3274 {
3275 ext4_lblk_t start_blk;
3276 ext4_lblk_t len_blks;
3277 int error = 0;
3278
3279 /* fallback to generic here if not in extents fmt */
3280 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
3281 return generic_block_fiemap(inode, fieinfo, start, len,
3282 ext4_get_block);
3283
3284 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
3285 return -EBADR;
3286
3287 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
3288 error = ext4_xattr_fiemap(inode, fieinfo);
3289 } else {
3290 start_blk = start >> inode->i_sb->s_blocksize_bits;
3291 len_blks = len >> inode->i_sb->s_blocksize_bits;
3292
3293 /*
3294 * Walk the extent tree gathering extent information.
3295 * ext4_ext_fiemap_cb will push extents back to user.
3296 */
3297 down_write(&EXT4_I(inode)->i_data_sem);
3298 error = ext4_ext_walk_space(inode, start_blk, len_blks,
3299 ext4_ext_fiemap_cb, fieinfo);
3300 up_write(&EXT4_I(inode)->i_data_sem);
3301 }
3302
3303 return error;
3304 }
3305