]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - fs/ext4/extents.c
Linux 3.4-rc5
[mirror_ubuntu-artful-kernel.git] / fs / ext4 / extents.c
CommitLineData
a86c6181
AT
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
a86c6181
AT
32#include <linux/fs.h>
33#include <linux/time.h>
cd02ff0b 34#include <linux/jbd2.h>
a86c6181
AT
35#include <linux/highuid.h>
36#include <linux/pagemap.h>
37#include <linux/quotaops.h>
38#include <linux/string.h>
39#include <linux/slab.h>
a2df2a63 40#include <linux/falloc.h>
a86c6181 41#include <asm/uaccess.h>
6873fa0d 42#include <linux/fiemap.h>
3dcf5451 43#include "ext4_jbd2.h"
a86c6181 44
0562e0ba
JZ
45#include <trace/events/ext4.h>
46
5f95d21f
LC
47/*
48 * used by extent splitting.
49 */
50#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
51 due to ENOSPC */
52#define EXT4_EXT_MARK_UNINIT1 0x2 /* mark first half uninitialized */
53#define EXT4_EXT_MARK_UNINIT2 0x4 /* mark second half uninitialized */
54
d583fb87
AH
55static int ext4_split_extent(handle_t *handle,
56 struct inode *inode,
57 struct ext4_ext_path *path,
58 struct ext4_map_blocks *map,
59 int split_flag,
60 int flags);
61
5f95d21f
LC
62static int ext4_split_extent_at(handle_t *handle,
63 struct inode *inode,
64 struct ext4_ext_path *path,
65 ext4_lblk_t split,
66 int split_flag,
67 int flags);
68
487caeef
JK
69static int ext4_ext_truncate_extend_restart(handle_t *handle,
70 struct inode *inode,
71 int needed)
a86c6181
AT
72{
73 int err;
74
0390131b
FM
75 if (!ext4_handle_valid(handle))
76 return 0;
a86c6181 77 if (handle->h_buffer_credits > needed)
9102e4fa
SF
78 return 0;
79 err = ext4_journal_extend(handle, needed);
0123c939 80 if (err <= 0)
9102e4fa 81 return err;
487caeef 82 err = ext4_truncate_restart_trans(handle, inode, needed);
0617b83f
DM
83 if (err == 0)
84 err = -EAGAIN;
487caeef
JK
85
86 return err;
a86c6181
AT
87}
88
89/*
90 * could return:
91 * - EROFS
92 * - ENOMEM
93 */
94static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
95 struct ext4_ext_path *path)
96{
97 if (path->p_bh) {
98 /* path points to block */
99 return ext4_journal_get_write_access(handle, path->p_bh);
100 }
101 /* path points to leaf/index in inode body */
102 /* we use in-core data, no need to protect them */
103 return 0;
104}
105
106/*
107 * could return:
108 * - EROFS
109 * - ENOMEM
110 * - EIO
111 */
9ea7a0df
TT
112#define ext4_ext_dirty(handle, inode, path) \
113 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
114static int __ext4_ext_dirty(const char *where, unsigned int line,
115 handle_t *handle, struct inode *inode,
116 struct ext4_ext_path *path)
a86c6181
AT
117{
118 int err;
119 if (path->p_bh) {
120 /* path points to block */
9ea7a0df
TT
121 err = __ext4_handle_dirty_metadata(where, line, handle,
122 inode, path->p_bh);
a86c6181
AT
123 } else {
124 /* path points to leaf/index in inode body */
125 err = ext4_mark_inode_dirty(handle, inode);
126 }
127 return err;
128}
129
f65e6fba 130static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
a86c6181 131 struct ext4_ext_path *path,
725d26d3 132 ext4_lblk_t block)
a86c6181 133{
a86c6181 134 if (path) {
81fdbb4a 135 int depth = path->p_depth;
a86c6181 136 struct ext4_extent *ex;
a86c6181 137
ad4fb9ca
KM
138 /*
139 * Try to predict block placement assuming that we are
140 * filling in a file which will eventually be
141 * non-sparse --- i.e., in the case of libbfd writing
142 * an ELF object sections out-of-order but in a way
143 * the eventually results in a contiguous object or
144 * executable file, or some database extending a table
145 * space file. However, this is actually somewhat
146 * non-ideal if we are writing a sparse file such as
147 * qemu or KVM writing a raw image file that is going
148 * to stay fairly sparse, since it will end up
149 * fragmenting the file system's free space. Maybe we
150 * should have some hueristics or some way to allow
151 * userspace to pass a hint to file system,
b8d6568a 152 * especially if the latter case turns out to be
ad4fb9ca
KM
153 * common.
154 */
7e028976 155 ex = path[depth].p_ext;
ad4fb9ca
KM
156 if (ex) {
157 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
158 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
159
160 if (block > ext_block)
161 return ext_pblk + (block - ext_block);
162 else
163 return ext_pblk - (ext_block - block);
164 }
a86c6181 165
d0d856e8
RD
166 /* it looks like index is empty;
167 * try to find starting block from index itself */
a86c6181
AT
168 if (path[depth].p_bh)
169 return path[depth].p_bh->b_blocknr;
170 }
171
172 /* OK. use inode's group */
f86186b4 173 return ext4_inode_to_goal_block(inode);
a86c6181
AT
174}
175
654b4908
AK
176/*
177 * Allocation for a meta data block
178 */
f65e6fba 179static ext4_fsblk_t
654b4908 180ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
a86c6181 181 struct ext4_ext_path *path,
55f020db 182 struct ext4_extent *ex, int *err, unsigned int flags)
a86c6181 183{
f65e6fba 184 ext4_fsblk_t goal, newblock;
a86c6181
AT
185
186 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
55f020db
AH
187 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
188 NULL, err);
a86c6181
AT
189 return newblock;
190}
191
55ad63bf 192static inline int ext4_ext_space_block(struct inode *inode, int check)
a86c6181
AT
193{
194 int size;
195
196 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
197 / sizeof(struct ext4_extent);
bbf2f9fb 198#ifdef AGGRESSIVE_TEST
02dc62fb
YY
199 if (!check && size > 6)
200 size = 6;
a86c6181
AT
201#endif
202 return size;
203}
204
55ad63bf 205static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
a86c6181
AT
206{
207 int size;
208
209 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
210 / sizeof(struct ext4_extent_idx);
bbf2f9fb 211#ifdef AGGRESSIVE_TEST
02dc62fb
YY
212 if (!check && size > 5)
213 size = 5;
a86c6181
AT
214#endif
215 return size;
216}
217
55ad63bf 218static inline int ext4_ext_space_root(struct inode *inode, int check)
a86c6181
AT
219{
220 int size;
221
222 size = sizeof(EXT4_I(inode)->i_data);
223 size -= sizeof(struct ext4_extent_header);
224 size /= sizeof(struct ext4_extent);
bbf2f9fb 225#ifdef AGGRESSIVE_TEST
02dc62fb
YY
226 if (!check && size > 3)
227 size = 3;
a86c6181
AT
228#endif
229 return size;
230}
231
55ad63bf 232static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
a86c6181
AT
233{
234 int size;
235
236 size = sizeof(EXT4_I(inode)->i_data);
237 size -= sizeof(struct ext4_extent_header);
238 size /= sizeof(struct ext4_extent_idx);
bbf2f9fb 239#ifdef AGGRESSIVE_TEST
02dc62fb
YY
240 if (!check && size > 4)
241 size = 4;
a86c6181
AT
242#endif
243 return size;
244}
245
d2a17637
MC
246/*
247 * Calculate the number of metadata blocks needed
248 * to allocate @blocks
249 * Worse case is one block per extent
250 */
01f49d0b 251int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
d2a17637 252{
9d0be502 253 struct ext4_inode_info *ei = EXT4_I(inode);
81fdbb4a 254 int idxs;
d2a17637 255
9d0be502
TT
256 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
257 / sizeof(struct ext4_extent_idx));
d2a17637
MC
258
259 /*
9d0be502
TT
260 * If the new delayed allocation block is contiguous with the
261 * previous da block, it can share index blocks with the
262 * previous block, so we only need to allocate a new index
263 * block every idxs leaf blocks. At ldxs**2 blocks, we need
264 * an additional index block, and at ldxs**3 blocks, yet
265 * another index blocks.
d2a17637 266 */
9d0be502
TT
267 if (ei->i_da_metadata_calc_len &&
268 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
81fdbb4a
YY
269 int num = 0;
270
9d0be502
TT
271 if ((ei->i_da_metadata_calc_len % idxs) == 0)
272 num++;
273 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
274 num++;
275 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
276 num++;
277 ei->i_da_metadata_calc_len = 0;
278 } else
279 ei->i_da_metadata_calc_len++;
280 ei->i_da_metadata_calc_last_lblock++;
281 return num;
282 }
d2a17637 283
9d0be502
TT
284 /*
285 * In the worst case we need a new set of index blocks at
286 * every level of the inode's extent tree.
287 */
288 ei->i_da_metadata_calc_len = 1;
289 ei->i_da_metadata_calc_last_lblock = lblock;
290 return ext_depth(inode) + 1;
d2a17637
MC
291}
292
c29c0ae7
AT
293static int
294ext4_ext_max_entries(struct inode *inode, int depth)
295{
296 int max;
297
298 if (depth == ext_depth(inode)) {
299 if (depth == 0)
55ad63bf 300 max = ext4_ext_space_root(inode, 1);
c29c0ae7 301 else
55ad63bf 302 max = ext4_ext_space_root_idx(inode, 1);
c29c0ae7
AT
303 } else {
304 if (depth == 0)
55ad63bf 305 max = ext4_ext_space_block(inode, 1);
c29c0ae7 306 else
55ad63bf 307 max = ext4_ext_space_block_idx(inode, 1);
c29c0ae7
AT
308 }
309
310 return max;
311}
312
56b19868
AK
313static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
314{
bf89d16f 315 ext4_fsblk_t block = ext4_ext_pblock(ext);
56b19868 316 int len = ext4_ext_get_actual_len(ext);
e84a26ce 317
31d4f3a2
TT
318 if (len == 0)
319 return 0;
6fd058f7 320 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
56b19868
AK
321}
322
323static int ext4_valid_extent_idx(struct inode *inode,
324 struct ext4_extent_idx *ext_idx)
325{
bf89d16f 326 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
e84a26ce 327
6fd058f7 328 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
56b19868
AK
329}
330
331static int ext4_valid_extent_entries(struct inode *inode,
332 struct ext4_extent_header *eh,
333 int depth)
334{
56b19868
AK
335 unsigned short entries;
336 if (eh->eh_entries == 0)
337 return 1;
338
339 entries = le16_to_cpu(eh->eh_entries);
340
341 if (depth == 0) {
342 /* leaf entries */
81fdbb4a 343 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
56b19868
AK
344 while (entries) {
345 if (!ext4_valid_extent(inode, ext))
346 return 0;
347 ext++;
348 entries--;
349 }
350 } else {
81fdbb4a 351 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
56b19868
AK
352 while (entries) {
353 if (!ext4_valid_extent_idx(inode, ext_idx))
354 return 0;
355 ext_idx++;
356 entries--;
357 }
358 }
359 return 1;
360}
361
c398eda0
TT
362static int __ext4_ext_check(const char *function, unsigned int line,
363 struct inode *inode, struct ext4_extent_header *eh,
364 int depth)
c29c0ae7
AT
365{
366 const char *error_msg;
367 int max = 0;
368
369 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
370 error_msg = "invalid magic";
371 goto corrupted;
372 }
373 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
374 error_msg = "unexpected eh_depth";
375 goto corrupted;
376 }
377 if (unlikely(eh->eh_max == 0)) {
378 error_msg = "invalid eh_max";
379 goto corrupted;
380 }
381 max = ext4_ext_max_entries(inode, depth);
382 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
383 error_msg = "too large eh_max";
384 goto corrupted;
385 }
386 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
387 error_msg = "invalid eh_entries";
388 goto corrupted;
389 }
56b19868
AK
390 if (!ext4_valid_extent_entries(inode, eh, depth)) {
391 error_msg = "invalid extent entries";
392 goto corrupted;
393 }
c29c0ae7
AT
394 return 0;
395
396corrupted:
c398eda0 397 ext4_error_inode(inode, function, line, 0,
24676da4 398 "bad header/extent: %s - magic %x, "
c29c0ae7 399 "entries %u, max %u(%u), depth %u(%u)",
24676da4 400 error_msg, le16_to_cpu(eh->eh_magic),
c29c0ae7
AT
401 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
402 max, le16_to_cpu(eh->eh_depth), depth);
403
404 return -EIO;
405}
406
56b19868 407#define ext4_ext_check(inode, eh, depth) \
c398eda0 408 __ext4_ext_check(__func__, __LINE__, inode, eh, depth)
c29c0ae7 409
7a262f7c
AK
410int ext4_ext_check_inode(struct inode *inode)
411{
412 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
413}
414
a86c6181
AT
415#ifdef EXT_DEBUG
416static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
417{
418 int k, l = path->p_depth;
419
420 ext_debug("path:");
421 for (k = 0; k <= l; k++, path++) {
422 if (path->p_idx) {
2ae02107 423 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
bf89d16f 424 ext4_idx_pblock(path->p_idx));
a86c6181 425 } else if (path->p_ext) {
553f9008 426 ext_debug(" %d:[%d]%d:%llu ",
a86c6181 427 le32_to_cpu(path->p_ext->ee_block),
553f9008 428 ext4_ext_is_uninitialized(path->p_ext),
a2df2a63 429 ext4_ext_get_actual_len(path->p_ext),
bf89d16f 430 ext4_ext_pblock(path->p_ext));
a86c6181
AT
431 } else
432 ext_debug(" []");
433 }
434 ext_debug("\n");
435}
436
437static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
438{
439 int depth = ext_depth(inode);
440 struct ext4_extent_header *eh;
441 struct ext4_extent *ex;
442 int i;
443
444 if (!path)
445 return;
446
447 eh = path[depth].p_hdr;
448 ex = EXT_FIRST_EXTENT(eh);
449
553f9008
M
450 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
451
a86c6181 452 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
553f9008
M
453 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
454 ext4_ext_is_uninitialized(ex),
bf89d16f 455 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
a86c6181
AT
456 }
457 ext_debug("\n");
458}
1b16da77
YY
459
460static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
461 ext4_fsblk_t newblock, int level)
462{
463 int depth = ext_depth(inode);
464 struct ext4_extent *ex;
465
466 if (depth != level) {
467 struct ext4_extent_idx *idx;
468 idx = path[level].p_idx;
469 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
470 ext_debug("%d: move %d:%llu in new index %llu\n", level,
471 le32_to_cpu(idx->ei_block),
472 ext4_idx_pblock(idx),
473 newblock);
474 idx++;
475 }
476
477 return;
478 }
479
480 ex = path[depth].p_ext;
481 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
482 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
483 le32_to_cpu(ex->ee_block),
484 ext4_ext_pblock(ex),
485 ext4_ext_is_uninitialized(ex),
486 ext4_ext_get_actual_len(ex),
487 newblock);
488 ex++;
489 }
490}
491
a86c6181 492#else
af5bc92d
TT
493#define ext4_ext_show_path(inode, path)
494#define ext4_ext_show_leaf(inode, path)
1b16da77 495#define ext4_ext_show_move(inode, path, newblock, level)
a86c6181
AT
496#endif
497
b35905c1 498void ext4_ext_drop_refs(struct ext4_ext_path *path)
a86c6181
AT
499{
500 int depth = path->p_depth;
501 int i;
502
503 for (i = 0; i <= depth; i++, path++)
504 if (path->p_bh) {
505 brelse(path->p_bh);
506 path->p_bh = NULL;
507 }
508}
509
510/*
d0d856e8
RD
511 * ext4_ext_binsearch_idx:
512 * binary search for the closest index of the given block
c29c0ae7 513 * the header must be checked before calling this
a86c6181
AT
514 */
515static void
725d26d3
AK
516ext4_ext_binsearch_idx(struct inode *inode,
517 struct ext4_ext_path *path, ext4_lblk_t block)
a86c6181
AT
518{
519 struct ext4_extent_header *eh = path->p_hdr;
520 struct ext4_extent_idx *r, *l, *m;
521
a86c6181 522
bba90743 523 ext_debug("binsearch for %u(idx): ", block);
a86c6181
AT
524
525 l = EXT_FIRST_INDEX(eh) + 1;
e9f410b1 526 r = EXT_LAST_INDEX(eh);
a86c6181
AT
527 while (l <= r) {
528 m = l + (r - l) / 2;
529 if (block < le32_to_cpu(m->ei_block))
530 r = m - 1;
531 else
532 l = m + 1;
26d535ed
DM
533 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
534 m, le32_to_cpu(m->ei_block),
535 r, le32_to_cpu(r->ei_block));
a86c6181
AT
536 }
537
538 path->p_idx = l - 1;
f65e6fba 539 ext_debug(" -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
bf89d16f 540 ext4_idx_pblock(path->p_idx));
a86c6181
AT
541
542#ifdef CHECK_BINSEARCH
543 {
544 struct ext4_extent_idx *chix, *ix;
545 int k;
546
547 chix = ix = EXT_FIRST_INDEX(eh);
548 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
549 if (k != 0 &&
550 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
4776004f
TT
551 printk(KERN_DEBUG "k=%d, ix=0x%p, "
552 "first=0x%p\n", k,
553 ix, EXT_FIRST_INDEX(eh));
554 printk(KERN_DEBUG "%u <= %u\n",
a86c6181
AT
555 le32_to_cpu(ix->ei_block),
556 le32_to_cpu(ix[-1].ei_block));
557 }
558 BUG_ON(k && le32_to_cpu(ix->ei_block)
8c55e204 559 <= le32_to_cpu(ix[-1].ei_block));
a86c6181
AT
560 if (block < le32_to_cpu(ix->ei_block))
561 break;
562 chix = ix;
563 }
564 BUG_ON(chix != path->p_idx);
565 }
566#endif
567
568}
569
570/*
d0d856e8
RD
571 * ext4_ext_binsearch:
572 * binary search for closest extent of the given block
c29c0ae7 573 * the header must be checked before calling this
a86c6181
AT
574 */
575static void
725d26d3
AK
576ext4_ext_binsearch(struct inode *inode,
577 struct ext4_ext_path *path, ext4_lblk_t block)
a86c6181
AT
578{
579 struct ext4_extent_header *eh = path->p_hdr;
580 struct ext4_extent *r, *l, *m;
581
a86c6181
AT
582 if (eh->eh_entries == 0) {
583 /*
d0d856e8
RD
584 * this leaf is empty:
585 * we get such a leaf in split/add case
a86c6181
AT
586 */
587 return;
588 }
589
bba90743 590 ext_debug("binsearch for %u: ", block);
a86c6181
AT
591
592 l = EXT_FIRST_EXTENT(eh) + 1;
e9f410b1 593 r = EXT_LAST_EXTENT(eh);
a86c6181
AT
594
595 while (l <= r) {
596 m = l + (r - l) / 2;
597 if (block < le32_to_cpu(m->ee_block))
598 r = m - 1;
599 else
600 l = m + 1;
26d535ed
DM
601 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
602 m, le32_to_cpu(m->ee_block),
603 r, le32_to_cpu(r->ee_block));
a86c6181
AT
604 }
605
606 path->p_ext = l - 1;
553f9008 607 ext_debug(" -> %d:%llu:[%d]%d ",
8c55e204 608 le32_to_cpu(path->p_ext->ee_block),
bf89d16f 609 ext4_ext_pblock(path->p_ext),
553f9008 610 ext4_ext_is_uninitialized(path->p_ext),
a2df2a63 611 ext4_ext_get_actual_len(path->p_ext));
a86c6181
AT
612
613#ifdef CHECK_BINSEARCH
614 {
615 struct ext4_extent *chex, *ex;
616 int k;
617
618 chex = ex = EXT_FIRST_EXTENT(eh);
619 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
620 BUG_ON(k && le32_to_cpu(ex->ee_block)
8c55e204 621 <= le32_to_cpu(ex[-1].ee_block));
a86c6181
AT
622 if (block < le32_to_cpu(ex->ee_block))
623 break;
624 chex = ex;
625 }
626 BUG_ON(chex != path->p_ext);
627 }
628#endif
629
630}
631
632int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
633{
634 struct ext4_extent_header *eh;
635
636 eh = ext_inode_hdr(inode);
637 eh->eh_depth = 0;
638 eh->eh_entries = 0;
639 eh->eh_magic = EXT4_EXT_MAGIC;
55ad63bf 640 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
a86c6181
AT
641 ext4_mark_inode_dirty(handle, inode);
642 ext4_ext_invalidate_cache(inode);
643 return 0;
644}
645
646struct ext4_ext_path *
725d26d3
AK
647ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
648 struct ext4_ext_path *path)
a86c6181
AT
649{
650 struct ext4_extent_header *eh;
651 struct buffer_head *bh;
652 short int depth, i, ppos = 0, alloc = 0;
653
654 eh = ext_inode_hdr(inode);
c29c0ae7 655 depth = ext_depth(inode);
a86c6181
AT
656
657 /* account possible depth increase */
658 if (!path) {
5d4958f9 659 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
a86c6181
AT
660 GFP_NOFS);
661 if (!path)
662 return ERR_PTR(-ENOMEM);
663 alloc = 1;
664 }
a86c6181 665 path[0].p_hdr = eh;
1973adcb 666 path[0].p_bh = NULL;
a86c6181 667
c29c0ae7 668 i = depth;
a86c6181
AT
669 /* walk through the tree */
670 while (i) {
7a262f7c
AK
671 int need_to_validate = 0;
672
a86c6181
AT
673 ext_debug("depth %d: num %d, max %d\n",
674 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
c29c0ae7 675
a86c6181 676 ext4_ext_binsearch_idx(inode, path + ppos, block);
bf89d16f 677 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
a86c6181
AT
678 path[ppos].p_depth = i;
679 path[ppos].p_ext = NULL;
680
7a262f7c
AK
681 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
682 if (unlikely(!bh))
a86c6181 683 goto err;
7a262f7c 684 if (!bh_uptodate_or_lock(bh)) {
0562e0ba
JZ
685 trace_ext4_ext_load_extent(inode, block,
686 path[ppos].p_block);
7a262f7c
AK
687 if (bh_submit_read(bh) < 0) {
688 put_bh(bh);
689 goto err;
690 }
691 /* validate the extent entries */
692 need_to_validate = 1;
693 }
a86c6181
AT
694 eh = ext_block_hdr(bh);
695 ppos++;
273df556
FM
696 if (unlikely(ppos > depth)) {
697 put_bh(bh);
698 EXT4_ERROR_INODE(inode,
699 "ppos %d > depth %d", ppos, depth);
700 goto err;
701 }
a86c6181
AT
702 path[ppos].p_bh = bh;
703 path[ppos].p_hdr = eh;
704 i--;
705
7a262f7c 706 if (need_to_validate && ext4_ext_check(inode, eh, i))
a86c6181
AT
707 goto err;
708 }
709
710 path[ppos].p_depth = i;
a86c6181
AT
711 path[ppos].p_ext = NULL;
712 path[ppos].p_idx = NULL;
713
a86c6181
AT
714 /* find extent */
715 ext4_ext_binsearch(inode, path + ppos, block);
1973adcb
SF
716 /* if not an empty leaf */
717 if (path[ppos].p_ext)
bf89d16f 718 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
a86c6181
AT
719
720 ext4_ext_show_path(inode, path);
721
722 return path;
723
724err:
725 ext4_ext_drop_refs(path);
726 if (alloc)
727 kfree(path);
728 return ERR_PTR(-EIO);
729}
730
731/*
d0d856e8
RD
732 * ext4_ext_insert_index:
733 * insert new index [@logical;@ptr] into the block at @curp;
734 * check where to insert: before @curp or after @curp
a86c6181 735 */
1f109d5a
TT
736static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
737 struct ext4_ext_path *curp,
738 int logical, ext4_fsblk_t ptr)
a86c6181
AT
739{
740 struct ext4_extent_idx *ix;
741 int len, err;
742
7e028976
AM
743 err = ext4_ext_get_access(handle, inode, curp);
744 if (err)
a86c6181
AT
745 return err;
746
273df556
FM
747 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
748 EXT4_ERROR_INODE(inode,
749 "logical %d == ei_block %d!",
750 logical, le32_to_cpu(curp->p_idx->ei_block));
751 return -EIO;
752 }
d4620315
RD
753
754 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
755 >= le16_to_cpu(curp->p_hdr->eh_max))) {
756 EXT4_ERROR_INODE(inode,
757 "eh_entries %d >= eh_max %d!",
758 le16_to_cpu(curp->p_hdr->eh_entries),
759 le16_to_cpu(curp->p_hdr->eh_max));
760 return -EIO;
761 }
762
a86c6181
AT
763 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
764 /* insert after */
80e675f9 765 ext_debug("insert new index %d after: %llu\n", logical, ptr);
a86c6181
AT
766 ix = curp->p_idx + 1;
767 } else {
768 /* insert before */
80e675f9 769 ext_debug("insert new index %d before: %llu\n", logical, ptr);
a86c6181
AT
770 ix = curp->p_idx;
771 }
772
80e675f9
EG
773 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
774 BUG_ON(len < 0);
775 if (len > 0) {
776 ext_debug("insert new index %d: "
777 "move %d indices from 0x%p to 0x%p\n",
778 logical, len, ix, ix + 1);
779 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
780 }
781
f472e026
TM
782 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
783 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
784 return -EIO;
785 }
786
a86c6181 787 ix->ei_block = cpu_to_le32(logical);
f65e6fba 788 ext4_idx_store_pblock(ix, ptr);
e8546d06 789 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
a86c6181 790
273df556
FM
791 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
792 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
793 return -EIO;
794 }
a86c6181
AT
795
796 err = ext4_ext_dirty(handle, inode, curp);
797 ext4_std_error(inode->i_sb, err);
798
799 return err;
800}
801
802/*
d0d856e8
RD
803 * ext4_ext_split:
804 * inserts new subtree into the path, using free index entry
805 * at depth @at:
806 * - allocates all needed blocks (new leaf and all intermediate index blocks)
807 * - makes decision where to split
808 * - moves remaining extents and index entries (right to the split point)
809 * into the newly allocated blocks
810 * - initializes subtree
a86c6181
AT
811 */
812static int ext4_ext_split(handle_t *handle, struct inode *inode,
55f020db
AH
813 unsigned int flags,
814 struct ext4_ext_path *path,
815 struct ext4_extent *newext, int at)
a86c6181
AT
816{
817 struct buffer_head *bh = NULL;
818 int depth = ext_depth(inode);
819 struct ext4_extent_header *neh;
820 struct ext4_extent_idx *fidx;
a86c6181 821 int i = at, k, m, a;
f65e6fba 822 ext4_fsblk_t newblock, oldblock;
a86c6181 823 __le32 border;
f65e6fba 824 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
a86c6181
AT
825 int err = 0;
826
827 /* make decision: where to split? */
d0d856e8 828 /* FIXME: now decision is simplest: at current extent */
a86c6181 829
d0d856e8 830 /* if current leaf will be split, then we should use
a86c6181 831 * border from split point */
273df556
FM
832 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
833 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
834 return -EIO;
835 }
a86c6181
AT
836 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
837 border = path[depth].p_ext[1].ee_block;
d0d856e8 838 ext_debug("leaf will be split."
a86c6181 839 " next leaf starts at %d\n",
8c55e204 840 le32_to_cpu(border));
a86c6181
AT
841 } else {
842 border = newext->ee_block;
843 ext_debug("leaf will be added."
844 " next leaf starts at %d\n",
8c55e204 845 le32_to_cpu(border));
a86c6181
AT
846 }
847
848 /*
d0d856e8
RD
849 * If error occurs, then we break processing
850 * and mark filesystem read-only. index won't
a86c6181 851 * be inserted and tree will be in consistent
d0d856e8 852 * state. Next mount will repair buffers too.
a86c6181
AT
853 */
854
855 /*
d0d856e8
RD
856 * Get array to track all allocated blocks.
857 * We need this to handle errors and free blocks
858 * upon them.
a86c6181 859 */
5d4958f9 860 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
a86c6181
AT
861 if (!ablocks)
862 return -ENOMEM;
a86c6181
AT
863
864 /* allocate all needed blocks */
865 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
866 for (a = 0; a < depth - at; a++) {
654b4908 867 newblock = ext4_ext_new_meta_block(handle, inode, path,
55f020db 868 newext, &err, flags);
a86c6181
AT
869 if (newblock == 0)
870 goto cleanup;
871 ablocks[a] = newblock;
872 }
873
874 /* initialize new leaf */
875 newblock = ablocks[--a];
273df556
FM
876 if (unlikely(newblock == 0)) {
877 EXT4_ERROR_INODE(inode, "newblock == 0!");
878 err = -EIO;
879 goto cleanup;
880 }
a86c6181
AT
881 bh = sb_getblk(inode->i_sb, newblock);
882 if (!bh) {
883 err = -EIO;
884 goto cleanup;
885 }
886 lock_buffer(bh);
887
7e028976
AM
888 err = ext4_journal_get_create_access(handle, bh);
889 if (err)
a86c6181
AT
890 goto cleanup;
891
892 neh = ext_block_hdr(bh);
893 neh->eh_entries = 0;
55ad63bf 894 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
a86c6181
AT
895 neh->eh_magic = EXT4_EXT_MAGIC;
896 neh->eh_depth = 0;
a86c6181 897
d0d856e8 898 /* move remainder of path[depth] to the new leaf */
273df556
FM
899 if (unlikely(path[depth].p_hdr->eh_entries !=
900 path[depth].p_hdr->eh_max)) {
901 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
902 path[depth].p_hdr->eh_entries,
903 path[depth].p_hdr->eh_max);
904 err = -EIO;
905 goto cleanup;
906 }
a86c6181 907 /* start copy from next extent */
1b16da77
YY
908 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
909 ext4_ext_show_move(inode, path, newblock, depth);
a86c6181 910 if (m) {
1b16da77
YY
911 struct ext4_extent *ex;
912 ex = EXT_FIRST_EXTENT(neh);
913 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
e8546d06 914 le16_add_cpu(&neh->eh_entries, m);
a86c6181
AT
915 }
916
917 set_buffer_uptodate(bh);
918 unlock_buffer(bh);
919
0390131b 920 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 921 if (err)
a86c6181
AT
922 goto cleanup;
923 brelse(bh);
924 bh = NULL;
925
926 /* correct old leaf */
927 if (m) {
7e028976
AM
928 err = ext4_ext_get_access(handle, inode, path + depth);
929 if (err)
a86c6181 930 goto cleanup;
e8546d06 931 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
7e028976
AM
932 err = ext4_ext_dirty(handle, inode, path + depth);
933 if (err)
a86c6181
AT
934 goto cleanup;
935
936 }
937
938 /* create intermediate indexes */
939 k = depth - at - 1;
273df556
FM
940 if (unlikely(k < 0)) {
941 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
942 err = -EIO;
943 goto cleanup;
944 }
a86c6181
AT
945 if (k)
946 ext_debug("create %d intermediate indices\n", k);
947 /* insert new index into current index block */
948 /* current depth stored in i var */
949 i = depth - 1;
950 while (k--) {
951 oldblock = newblock;
952 newblock = ablocks[--a];
bba90743 953 bh = sb_getblk(inode->i_sb, newblock);
a86c6181
AT
954 if (!bh) {
955 err = -EIO;
956 goto cleanup;
957 }
958 lock_buffer(bh);
959
7e028976
AM
960 err = ext4_journal_get_create_access(handle, bh);
961 if (err)
a86c6181
AT
962 goto cleanup;
963
964 neh = ext_block_hdr(bh);
965 neh->eh_entries = cpu_to_le16(1);
966 neh->eh_magic = EXT4_EXT_MAGIC;
55ad63bf 967 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
a86c6181
AT
968 neh->eh_depth = cpu_to_le16(depth - i);
969 fidx = EXT_FIRST_INDEX(neh);
970 fidx->ei_block = border;
f65e6fba 971 ext4_idx_store_pblock(fidx, oldblock);
a86c6181 972
bba90743
ES
973 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
974 i, newblock, le32_to_cpu(border), oldblock);
a86c6181 975
1b16da77 976 /* move remainder of path[i] to the new index block */
273df556
FM
977 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
978 EXT_LAST_INDEX(path[i].p_hdr))) {
979 EXT4_ERROR_INODE(inode,
980 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
981 le32_to_cpu(path[i].p_ext->ee_block));
982 err = -EIO;
983 goto cleanup;
984 }
1b16da77
YY
985 /* start copy indexes */
986 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
987 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
988 EXT_MAX_INDEX(path[i].p_hdr));
989 ext4_ext_show_move(inode, path, newblock, i);
a86c6181 990 if (m) {
1b16da77 991 memmove(++fidx, path[i].p_idx,
a86c6181 992 sizeof(struct ext4_extent_idx) * m);
e8546d06 993 le16_add_cpu(&neh->eh_entries, m);
a86c6181
AT
994 }
995 set_buffer_uptodate(bh);
996 unlock_buffer(bh);
997
0390131b 998 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 999 if (err)
a86c6181
AT
1000 goto cleanup;
1001 brelse(bh);
1002 bh = NULL;
1003
1004 /* correct old index */
1005 if (m) {
1006 err = ext4_ext_get_access(handle, inode, path + i);
1007 if (err)
1008 goto cleanup;
e8546d06 1009 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
a86c6181
AT
1010 err = ext4_ext_dirty(handle, inode, path + i);
1011 if (err)
1012 goto cleanup;
1013 }
1014
1015 i--;
1016 }
1017
1018 /* insert new index */
a86c6181
AT
1019 err = ext4_ext_insert_index(handle, inode, path + at,
1020 le32_to_cpu(border), newblock);
1021
1022cleanup:
1023 if (bh) {
1024 if (buffer_locked(bh))
1025 unlock_buffer(bh);
1026 brelse(bh);
1027 }
1028
1029 if (err) {
1030 /* free all allocated blocks in error case */
1031 for (i = 0; i < depth; i++) {
1032 if (!ablocks[i])
1033 continue;
7dc57615 1034 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
e6362609 1035 EXT4_FREE_BLOCKS_METADATA);
a86c6181
AT
1036 }
1037 }
1038 kfree(ablocks);
1039
1040 return err;
1041}
1042
1043/*
d0d856e8
RD
1044 * ext4_ext_grow_indepth:
1045 * implements tree growing procedure:
1046 * - allocates new block
1047 * - moves top-level data (index block or leaf) into the new block
1048 * - initializes new top-level, creating index that points to the
1049 * just created block
a86c6181
AT
1050 */
1051static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
55f020db 1052 unsigned int flags,
55f020db 1053 struct ext4_extent *newext)
a86c6181 1054{
a86c6181 1055 struct ext4_extent_header *neh;
a86c6181 1056 struct buffer_head *bh;
f65e6fba 1057 ext4_fsblk_t newblock;
a86c6181
AT
1058 int err = 0;
1059
1939dd84 1060 newblock = ext4_ext_new_meta_block(handle, inode, NULL,
55f020db 1061 newext, &err, flags);
a86c6181
AT
1062 if (newblock == 0)
1063 return err;
1064
1065 bh = sb_getblk(inode->i_sb, newblock);
1066 if (!bh) {
1067 err = -EIO;
1068 ext4_std_error(inode->i_sb, err);
1069 return err;
1070 }
1071 lock_buffer(bh);
1072
7e028976
AM
1073 err = ext4_journal_get_create_access(handle, bh);
1074 if (err) {
a86c6181
AT
1075 unlock_buffer(bh);
1076 goto out;
1077 }
1078
1079 /* move top-level index/leaf into new block */
1939dd84
DM
1080 memmove(bh->b_data, EXT4_I(inode)->i_data,
1081 sizeof(EXT4_I(inode)->i_data));
a86c6181
AT
1082
1083 /* set size of new block */
1084 neh = ext_block_hdr(bh);
1085 /* old root could have indexes or leaves
1086 * so calculate e_max right way */
1087 if (ext_depth(inode))
55ad63bf 1088 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
a86c6181 1089 else
55ad63bf 1090 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
a86c6181
AT
1091 neh->eh_magic = EXT4_EXT_MAGIC;
1092 set_buffer_uptodate(bh);
1093 unlock_buffer(bh);
1094
0390131b 1095 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 1096 if (err)
a86c6181
AT
1097 goto out;
1098
1939dd84 1099 /* Update top-level index: num,max,pointer */
a86c6181 1100 neh = ext_inode_hdr(inode);
1939dd84
DM
1101 neh->eh_entries = cpu_to_le16(1);
1102 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1103 if (neh->eh_depth == 0) {
1104 /* Root extent block becomes index block */
1105 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1106 EXT_FIRST_INDEX(neh)->ei_block =
1107 EXT_FIRST_EXTENT(neh)->ee_block;
1108 }
2ae02107 1109 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
a86c6181 1110 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
5a0790c2 1111 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
bf89d16f 1112 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
a86c6181 1113
b4611abf 1114 neh->eh_depth = cpu_to_le16(le16_to_cpu(neh->eh_depth) + 1);
1939dd84 1115 ext4_mark_inode_dirty(handle, inode);
a86c6181
AT
1116out:
1117 brelse(bh);
1118
1119 return err;
1120}
1121
1122/*
d0d856e8
RD
1123 * ext4_ext_create_new_leaf:
1124 * finds empty index and adds new leaf.
1125 * if no free index is found, then it requests in-depth growing.
a86c6181
AT
1126 */
1127static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
55f020db
AH
1128 unsigned int flags,
1129 struct ext4_ext_path *path,
1130 struct ext4_extent *newext)
a86c6181
AT
1131{
1132 struct ext4_ext_path *curp;
1133 int depth, i, err = 0;
1134
1135repeat:
1136 i = depth = ext_depth(inode);
1137
1138 /* walk up to the tree and look for free index entry */
1139 curp = path + depth;
1140 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1141 i--;
1142 curp--;
1143 }
1144
d0d856e8
RD
1145 /* we use already allocated block for index block,
1146 * so subsequent data blocks should be contiguous */
a86c6181
AT
1147 if (EXT_HAS_FREE_INDEX(curp)) {
1148 /* if we found index with free entry, then use that
1149 * entry: create all needed subtree and add new leaf */
55f020db 1150 err = ext4_ext_split(handle, inode, flags, path, newext, i);
787e0981
SF
1151 if (err)
1152 goto out;
a86c6181
AT
1153
1154 /* refill path */
1155 ext4_ext_drop_refs(path);
1156 path = ext4_ext_find_extent(inode,
725d26d3
AK
1157 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1158 path);
a86c6181
AT
1159 if (IS_ERR(path))
1160 err = PTR_ERR(path);
1161 } else {
1162 /* tree is full, time to grow in depth */
1939dd84 1163 err = ext4_ext_grow_indepth(handle, inode, flags, newext);
a86c6181
AT
1164 if (err)
1165 goto out;
1166
1167 /* refill path */
1168 ext4_ext_drop_refs(path);
1169 path = ext4_ext_find_extent(inode,
725d26d3
AK
1170 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1171 path);
a86c6181
AT
1172 if (IS_ERR(path)) {
1173 err = PTR_ERR(path);
1174 goto out;
1175 }
1176
1177 /*
d0d856e8
RD
1178 * only first (depth 0 -> 1) produces free space;
1179 * in all other cases we have to split the grown tree
a86c6181
AT
1180 */
1181 depth = ext_depth(inode);
1182 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
d0d856e8 1183 /* now we need to split */
a86c6181
AT
1184 goto repeat;
1185 }
1186 }
1187
1188out:
1189 return err;
1190}
1191
1988b51e
AT
1192/*
1193 * search the closest allocated block to the left for *logical
1194 * and returns it at @logical + it's physical address at @phys
1195 * if *logical is the smallest allocated block, the function
1196 * returns 0 at @phys
1197 * return value contains 0 (success) or error code
1198 */
1f109d5a
TT
1199static int ext4_ext_search_left(struct inode *inode,
1200 struct ext4_ext_path *path,
1201 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1988b51e
AT
1202{
1203 struct ext4_extent_idx *ix;
1204 struct ext4_extent *ex;
b939e376 1205 int depth, ee_len;
1988b51e 1206
273df556
FM
1207 if (unlikely(path == NULL)) {
1208 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1209 return -EIO;
1210 }
1988b51e
AT
1211 depth = path->p_depth;
1212 *phys = 0;
1213
1214 if (depth == 0 && path->p_ext == NULL)
1215 return 0;
1216
1217 /* usually extent in the path covers blocks smaller
1218 * then *logical, but it can be that extent is the
1219 * first one in the file */
1220
1221 ex = path[depth].p_ext;
b939e376 1222 ee_len = ext4_ext_get_actual_len(ex);
1988b51e 1223 if (*logical < le32_to_cpu(ex->ee_block)) {
273df556
FM
1224 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1225 EXT4_ERROR_INODE(inode,
1226 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1227 *logical, le32_to_cpu(ex->ee_block));
1228 return -EIO;
1229 }
1988b51e
AT
1230 while (--depth >= 0) {
1231 ix = path[depth].p_idx;
273df556
FM
1232 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1233 EXT4_ERROR_INODE(inode,
1234 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
6ee3b212 1235 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
273df556 1236 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
6ee3b212 1237 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
273df556
FM
1238 depth);
1239 return -EIO;
1240 }
1988b51e
AT
1241 }
1242 return 0;
1243 }
1244
273df556
FM
1245 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1246 EXT4_ERROR_INODE(inode,
1247 "logical %d < ee_block %d + ee_len %d!",
1248 *logical, le32_to_cpu(ex->ee_block), ee_len);
1249 return -EIO;
1250 }
1988b51e 1251
b939e376 1252 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
bf89d16f 1253 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1988b51e
AT
1254 return 0;
1255}
1256
1257/*
1258 * search the closest allocated block to the right for *logical
1259 * and returns it at @logical + it's physical address at @phys
df3ab170 1260 * if *logical is the largest allocated block, the function
1988b51e
AT
1261 * returns 0 at @phys
1262 * return value contains 0 (success) or error code
1263 */
1f109d5a
TT
1264static int ext4_ext_search_right(struct inode *inode,
1265 struct ext4_ext_path *path,
4d33b1ef
TT
1266 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1267 struct ext4_extent **ret_ex)
1988b51e
AT
1268{
1269 struct buffer_head *bh = NULL;
1270 struct ext4_extent_header *eh;
1271 struct ext4_extent_idx *ix;
1272 struct ext4_extent *ex;
1273 ext4_fsblk_t block;
395a87bf
ES
1274 int depth; /* Note, NOT eh_depth; depth from top of tree */
1275 int ee_len;
1988b51e 1276
273df556
FM
1277 if (unlikely(path == NULL)) {
1278 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1279 return -EIO;
1280 }
1988b51e
AT
1281 depth = path->p_depth;
1282 *phys = 0;
1283
1284 if (depth == 0 && path->p_ext == NULL)
1285 return 0;
1286
1287 /* usually extent in the path covers blocks smaller
1288 * then *logical, but it can be that extent is the
1289 * first one in the file */
1290
1291 ex = path[depth].p_ext;
b939e376 1292 ee_len = ext4_ext_get_actual_len(ex);
1988b51e 1293 if (*logical < le32_to_cpu(ex->ee_block)) {
273df556
FM
1294 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1295 EXT4_ERROR_INODE(inode,
1296 "first_extent(path[%d].p_hdr) != ex",
1297 depth);
1298 return -EIO;
1299 }
1988b51e
AT
1300 while (--depth >= 0) {
1301 ix = path[depth].p_idx;
273df556
FM
1302 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1303 EXT4_ERROR_INODE(inode,
1304 "ix != EXT_FIRST_INDEX *logical %d!",
1305 *logical);
1306 return -EIO;
1307 }
1988b51e 1308 }
4d33b1ef 1309 goto found_extent;
1988b51e
AT
1310 }
1311
273df556
FM
1312 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1313 EXT4_ERROR_INODE(inode,
1314 "logical %d < ee_block %d + ee_len %d!",
1315 *logical, le32_to_cpu(ex->ee_block), ee_len);
1316 return -EIO;
1317 }
1988b51e
AT
1318
1319 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1320 /* next allocated block in this leaf */
1321 ex++;
4d33b1ef 1322 goto found_extent;
1988b51e
AT
1323 }
1324
1325 /* go up and search for index to the right */
1326 while (--depth >= 0) {
1327 ix = path[depth].p_idx;
1328 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
25f1ee3a 1329 goto got_index;
1988b51e
AT
1330 }
1331
25f1ee3a
WF
1332 /* we've gone up to the root and found no index to the right */
1333 return 0;
1988b51e 1334
25f1ee3a 1335got_index:
1988b51e
AT
1336 /* we've found index to the right, let's
1337 * follow it and find the closest allocated
1338 * block to the right */
1339 ix++;
bf89d16f 1340 block = ext4_idx_pblock(ix);
1988b51e
AT
1341 while (++depth < path->p_depth) {
1342 bh = sb_bread(inode->i_sb, block);
1343 if (bh == NULL)
1344 return -EIO;
1345 eh = ext_block_hdr(bh);
395a87bf 1346 /* subtract from p_depth to get proper eh_depth */
56b19868 1347 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1988b51e
AT
1348 put_bh(bh);
1349 return -EIO;
1350 }
1351 ix = EXT_FIRST_INDEX(eh);
bf89d16f 1352 block = ext4_idx_pblock(ix);
1988b51e
AT
1353 put_bh(bh);
1354 }
1355
1356 bh = sb_bread(inode->i_sb, block);
1357 if (bh == NULL)
1358 return -EIO;
1359 eh = ext_block_hdr(bh);
56b19868 1360 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1988b51e
AT
1361 put_bh(bh);
1362 return -EIO;
1363 }
1364 ex = EXT_FIRST_EXTENT(eh);
4d33b1ef 1365found_extent:
1988b51e 1366 *logical = le32_to_cpu(ex->ee_block);
bf89d16f 1367 *phys = ext4_ext_pblock(ex);
4d33b1ef
TT
1368 *ret_ex = ex;
1369 if (bh)
1370 put_bh(bh);
1988b51e 1371 return 0;
1988b51e
AT
1372}
1373
a86c6181 1374/*
d0d856e8 1375 * ext4_ext_next_allocated_block:
f17722f9 1376 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
d0d856e8
RD
1377 * NOTE: it considers block number from index entry as
1378 * allocated block. Thus, index entries have to be consistent
1379 * with leaves.
a86c6181 1380 */
725d26d3 1381static ext4_lblk_t
a86c6181
AT
1382ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1383{
1384 int depth;
1385
1386 BUG_ON(path == NULL);
1387 depth = path->p_depth;
1388
1389 if (depth == 0 && path->p_ext == NULL)
f17722f9 1390 return EXT_MAX_BLOCKS;
a86c6181
AT
1391
1392 while (depth >= 0) {
1393 if (depth == path->p_depth) {
1394 /* leaf */
6f8ff537
CW
1395 if (path[depth].p_ext &&
1396 path[depth].p_ext !=
a86c6181
AT
1397 EXT_LAST_EXTENT(path[depth].p_hdr))
1398 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1399 } else {
1400 /* index */
1401 if (path[depth].p_idx !=
1402 EXT_LAST_INDEX(path[depth].p_hdr))
1403 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1404 }
1405 depth--;
1406 }
1407
f17722f9 1408 return EXT_MAX_BLOCKS;
a86c6181
AT
1409}
1410
1411/*
d0d856e8 1412 * ext4_ext_next_leaf_block:
f17722f9 1413 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
a86c6181 1414 */
5718789d 1415static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
a86c6181
AT
1416{
1417 int depth;
1418
1419 BUG_ON(path == NULL);
1420 depth = path->p_depth;
1421
1422 /* zero-tree has no leaf blocks at all */
1423 if (depth == 0)
f17722f9 1424 return EXT_MAX_BLOCKS;
a86c6181
AT
1425
1426 /* go to index block */
1427 depth--;
1428
1429 while (depth >= 0) {
1430 if (path[depth].p_idx !=
1431 EXT_LAST_INDEX(path[depth].p_hdr))
725d26d3
AK
1432 return (ext4_lblk_t)
1433 le32_to_cpu(path[depth].p_idx[1].ei_block);
a86c6181
AT
1434 depth--;
1435 }
1436
f17722f9 1437 return EXT_MAX_BLOCKS;
a86c6181
AT
1438}
1439
1440/*
d0d856e8
RD
1441 * ext4_ext_correct_indexes:
1442 * if leaf gets modified and modified extent is first in the leaf,
1443 * then we have to correct all indexes above.
a86c6181
AT
1444 * TODO: do we need to correct tree in all cases?
1445 */
1d03ec98 1446static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
a86c6181
AT
1447 struct ext4_ext_path *path)
1448{
1449 struct ext4_extent_header *eh;
1450 int depth = ext_depth(inode);
1451 struct ext4_extent *ex;
1452 __le32 border;
1453 int k, err = 0;
1454
1455 eh = path[depth].p_hdr;
1456 ex = path[depth].p_ext;
273df556
FM
1457
1458 if (unlikely(ex == NULL || eh == NULL)) {
1459 EXT4_ERROR_INODE(inode,
1460 "ex %p == NULL or eh %p == NULL", ex, eh);
1461 return -EIO;
1462 }
a86c6181
AT
1463
1464 if (depth == 0) {
1465 /* there is no tree at all */
1466 return 0;
1467 }
1468
1469 if (ex != EXT_FIRST_EXTENT(eh)) {
1470 /* we correct tree if first leaf got modified only */
1471 return 0;
1472 }
1473
1474 /*
d0d856e8 1475 * TODO: we need correction if border is smaller than current one
a86c6181
AT
1476 */
1477 k = depth - 1;
1478 border = path[depth].p_ext->ee_block;
7e028976
AM
1479 err = ext4_ext_get_access(handle, inode, path + k);
1480 if (err)
a86c6181
AT
1481 return err;
1482 path[k].p_idx->ei_block = border;
7e028976
AM
1483 err = ext4_ext_dirty(handle, inode, path + k);
1484 if (err)
a86c6181
AT
1485 return err;
1486
1487 while (k--) {
1488 /* change all left-side indexes */
1489 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1490 break;
7e028976
AM
1491 err = ext4_ext_get_access(handle, inode, path + k);
1492 if (err)
a86c6181
AT
1493 break;
1494 path[k].p_idx->ei_block = border;
7e028976
AM
1495 err = ext4_ext_dirty(handle, inode, path + k);
1496 if (err)
a86c6181
AT
1497 break;
1498 }
1499
1500 return err;
1501}
1502
748de673 1503int
a86c6181
AT
1504ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1505 struct ext4_extent *ex2)
1506{
749269fa 1507 unsigned short ext1_ee_len, ext2_ee_len, max_len;
a2df2a63
AA
1508
1509 /*
1510 * Make sure that either both extents are uninitialized, or
1511 * both are _not_.
1512 */
1513 if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1514 return 0;
1515
749269fa
AA
1516 if (ext4_ext_is_uninitialized(ex1))
1517 max_len = EXT_UNINIT_MAX_LEN;
1518 else
1519 max_len = EXT_INIT_MAX_LEN;
1520
a2df2a63
AA
1521 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1522 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1523
1524 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
63f57933 1525 le32_to_cpu(ex2->ee_block))
a86c6181
AT
1526 return 0;
1527
471d4011
SB
1528 /*
1529 * To allow future support for preallocated extents to be added
1530 * as an RO_COMPAT feature, refuse to merge to extents if
d0d856e8 1531 * this can result in the top bit of ee_len being set.
471d4011 1532 */
749269fa 1533 if (ext1_ee_len + ext2_ee_len > max_len)
471d4011 1534 return 0;
bbf2f9fb 1535#ifdef AGGRESSIVE_TEST
b939e376 1536 if (ext1_ee_len >= 4)
a86c6181
AT
1537 return 0;
1538#endif
1539
bf89d16f 1540 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
a86c6181
AT
1541 return 1;
1542 return 0;
1543}
1544
56055d3a
AA
1545/*
1546 * This function tries to merge the "ex" extent to the next extent in the tree.
1547 * It always tries to merge towards right. If you want to merge towards
1548 * left, pass "ex - 1" as argument instead of "ex".
1549 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1550 * 1 if they got merged.
1551 */
197217a5 1552static int ext4_ext_try_to_merge_right(struct inode *inode,
1f109d5a
TT
1553 struct ext4_ext_path *path,
1554 struct ext4_extent *ex)
56055d3a
AA
1555{
1556 struct ext4_extent_header *eh;
1557 unsigned int depth, len;
1558 int merge_done = 0;
1559 int uninitialized = 0;
1560
1561 depth = ext_depth(inode);
1562 BUG_ON(path[depth].p_hdr == NULL);
1563 eh = path[depth].p_hdr;
1564
1565 while (ex < EXT_LAST_EXTENT(eh)) {
1566 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1567 break;
1568 /* merge with next extent! */
1569 if (ext4_ext_is_uninitialized(ex))
1570 uninitialized = 1;
1571 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1572 + ext4_ext_get_actual_len(ex + 1));
1573 if (uninitialized)
1574 ext4_ext_mark_uninitialized(ex);
1575
1576 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1577 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1578 * sizeof(struct ext4_extent);
1579 memmove(ex + 1, ex + 2, len);
1580 }
e8546d06 1581 le16_add_cpu(&eh->eh_entries, -1);
56055d3a
AA
1582 merge_done = 1;
1583 WARN_ON(eh->eh_entries == 0);
1584 if (!eh->eh_entries)
24676da4 1585 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
56055d3a
AA
1586 }
1587
1588 return merge_done;
1589}
1590
197217a5
YY
1591/*
1592 * This function tries to merge the @ex extent to neighbours in the tree.
1593 * return 1 if merge left else 0.
1594 */
1595static int ext4_ext_try_to_merge(struct inode *inode,
1596 struct ext4_ext_path *path,
1597 struct ext4_extent *ex) {
1598 struct ext4_extent_header *eh;
1599 unsigned int depth;
1600 int merge_done = 0;
1601 int ret = 0;
1602
1603 depth = ext_depth(inode);
1604 BUG_ON(path[depth].p_hdr == NULL);
1605 eh = path[depth].p_hdr;
1606
1607 if (ex > EXT_FIRST_EXTENT(eh))
1608 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1609
1610 if (!merge_done)
1611 ret = ext4_ext_try_to_merge_right(inode, path, ex);
1612
1613 return ret;
1614}
1615
25d14f98
AA
1616/*
1617 * check if a portion of the "newext" extent overlaps with an
1618 * existing extent.
1619 *
1620 * If there is an overlap discovered, it updates the length of the newext
1621 * such that there will be no overlap, and then returns 1.
1622 * If there is no overlap found, it returns 0.
1623 */
4d33b1ef
TT
1624static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1625 struct inode *inode,
1f109d5a
TT
1626 struct ext4_extent *newext,
1627 struct ext4_ext_path *path)
25d14f98 1628{
725d26d3 1629 ext4_lblk_t b1, b2;
25d14f98
AA
1630 unsigned int depth, len1;
1631 unsigned int ret = 0;
1632
1633 b1 = le32_to_cpu(newext->ee_block);
a2df2a63 1634 len1 = ext4_ext_get_actual_len(newext);
25d14f98
AA
1635 depth = ext_depth(inode);
1636 if (!path[depth].p_ext)
1637 goto out;
1638 b2 = le32_to_cpu(path[depth].p_ext->ee_block);
4d33b1ef 1639 b2 &= ~(sbi->s_cluster_ratio - 1);
25d14f98
AA
1640
1641 /*
1642 * get the next allocated block if the extent in the path
2b2d6d01 1643 * is before the requested block(s)
25d14f98
AA
1644 */
1645 if (b2 < b1) {
1646 b2 = ext4_ext_next_allocated_block(path);
f17722f9 1647 if (b2 == EXT_MAX_BLOCKS)
25d14f98 1648 goto out;
4d33b1ef 1649 b2 &= ~(sbi->s_cluster_ratio - 1);
25d14f98
AA
1650 }
1651
725d26d3 1652 /* check for wrap through zero on extent logical start block*/
25d14f98 1653 if (b1 + len1 < b1) {
f17722f9 1654 len1 = EXT_MAX_BLOCKS - b1;
25d14f98
AA
1655 newext->ee_len = cpu_to_le16(len1);
1656 ret = 1;
1657 }
1658
1659 /* check for overlap */
1660 if (b1 + len1 > b2) {
1661 newext->ee_len = cpu_to_le16(b2 - b1);
1662 ret = 1;
1663 }
1664out:
1665 return ret;
1666}
1667
a86c6181 1668/*
d0d856e8
RD
1669 * ext4_ext_insert_extent:
1670 * tries to merge requsted extent into the existing extent or
1671 * inserts requested extent as new one into the tree,
1672 * creating new leaf in the no-space case.
a86c6181
AT
1673 */
1674int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1675 struct ext4_ext_path *path,
0031462b 1676 struct ext4_extent *newext, int flag)
a86c6181 1677{
af5bc92d 1678 struct ext4_extent_header *eh;
a86c6181
AT
1679 struct ext4_extent *ex, *fex;
1680 struct ext4_extent *nearex; /* nearest extent */
1681 struct ext4_ext_path *npath = NULL;
725d26d3
AK
1682 int depth, len, err;
1683 ext4_lblk_t next;
a2df2a63 1684 unsigned uninitialized = 0;
55f020db 1685 int flags = 0;
a86c6181 1686
273df556
FM
1687 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1688 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1689 return -EIO;
1690 }
a86c6181
AT
1691 depth = ext_depth(inode);
1692 ex = path[depth].p_ext;
273df556
FM
1693 if (unlikely(path[depth].p_hdr == NULL)) {
1694 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1695 return -EIO;
1696 }
a86c6181
AT
1697
1698 /* try to insert block into found extent and return */
744692dc 1699 if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
0031462b 1700 && ext4_can_extents_be_merged(inode, ex, newext)) {
32de6756 1701 ext_debug("append [%d]%d block to %u:[%d]%d (from %llu)\n",
bf89d16f
TT
1702 ext4_ext_is_uninitialized(newext),
1703 ext4_ext_get_actual_len(newext),
1704 le32_to_cpu(ex->ee_block),
1705 ext4_ext_is_uninitialized(ex),
1706 ext4_ext_get_actual_len(ex),
1707 ext4_ext_pblock(ex));
7e028976
AM
1708 err = ext4_ext_get_access(handle, inode, path + depth);
1709 if (err)
a86c6181 1710 return err;
a2df2a63
AA
1711
1712 /*
1713 * ext4_can_extents_be_merged should have checked that either
1714 * both extents are uninitialized, or both aren't. Thus we
1715 * need to check only one of them here.
1716 */
1717 if (ext4_ext_is_uninitialized(ex))
1718 uninitialized = 1;
1719 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1720 + ext4_ext_get_actual_len(newext));
1721 if (uninitialized)
1722 ext4_ext_mark_uninitialized(ex);
a86c6181
AT
1723 eh = path[depth].p_hdr;
1724 nearex = ex;
1725 goto merge;
1726 }
1727
a86c6181
AT
1728 depth = ext_depth(inode);
1729 eh = path[depth].p_hdr;
1730 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1731 goto has_space;
1732
1733 /* probably next leaf has space for us? */
1734 fex = EXT_LAST_EXTENT(eh);
598dbdf2
RD
1735 next = EXT_MAX_BLOCKS;
1736 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
5718789d 1737 next = ext4_ext_next_leaf_block(path);
598dbdf2 1738 if (next != EXT_MAX_BLOCKS) {
32de6756 1739 ext_debug("next leaf block - %u\n", next);
a86c6181
AT
1740 BUG_ON(npath != NULL);
1741 npath = ext4_ext_find_extent(inode, next, NULL);
1742 if (IS_ERR(npath))
1743 return PTR_ERR(npath);
1744 BUG_ON(npath->p_depth != path->p_depth);
1745 eh = npath[depth].p_hdr;
1746 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
25985edc 1747 ext_debug("next leaf isn't full(%d)\n",
a86c6181
AT
1748 le16_to_cpu(eh->eh_entries));
1749 path = npath;
ffb505ff 1750 goto has_space;
a86c6181
AT
1751 }
1752 ext_debug("next leaf has no free space(%d,%d)\n",
1753 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1754 }
1755
1756 /*
d0d856e8
RD
1757 * There is no free space in the found leaf.
1758 * We're gonna add a new leaf in the tree.
a86c6181 1759 */
55f020db
AH
1760 if (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)
1761 flags = EXT4_MB_USE_ROOT_BLOCKS;
1762 err = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);
a86c6181
AT
1763 if (err)
1764 goto cleanup;
1765 depth = ext_depth(inode);
1766 eh = path[depth].p_hdr;
1767
1768has_space:
1769 nearex = path[depth].p_ext;
1770
7e028976
AM
1771 err = ext4_ext_get_access(handle, inode, path + depth);
1772 if (err)
a86c6181
AT
1773 goto cleanup;
1774
1775 if (!nearex) {
1776 /* there is no extent in this leaf, create first one */
32de6756 1777 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
8c55e204 1778 le32_to_cpu(newext->ee_block),
bf89d16f 1779 ext4_ext_pblock(newext),
553f9008 1780 ext4_ext_is_uninitialized(newext),
a2df2a63 1781 ext4_ext_get_actual_len(newext));
80e675f9
EG
1782 nearex = EXT_FIRST_EXTENT(eh);
1783 } else {
1784 if (le32_to_cpu(newext->ee_block)
8c55e204 1785 > le32_to_cpu(nearex->ee_block)) {
80e675f9 1786 /* Insert after */
32de6756
YY
1787 ext_debug("insert %u:%llu:[%d]%d before: "
1788 "nearest %p\n",
80e675f9
EG
1789 le32_to_cpu(newext->ee_block),
1790 ext4_ext_pblock(newext),
1791 ext4_ext_is_uninitialized(newext),
1792 ext4_ext_get_actual_len(newext),
1793 nearex);
1794 nearex++;
1795 } else {
1796 /* Insert before */
1797 BUG_ON(newext->ee_block == nearex->ee_block);
32de6756
YY
1798 ext_debug("insert %u:%llu:[%d]%d after: "
1799 "nearest %p\n",
8c55e204 1800 le32_to_cpu(newext->ee_block),
bf89d16f 1801 ext4_ext_pblock(newext),
553f9008 1802 ext4_ext_is_uninitialized(newext),
a2df2a63 1803 ext4_ext_get_actual_len(newext),
80e675f9
EG
1804 nearex);
1805 }
1806 len = EXT_LAST_EXTENT(eh) - nearex + 1;
1807 if (len > 0) {
32de6756 1808 ext_debug("insert %u:%llu:[%d]%d: "
80e675f9
EG
1809 "move %d extents from 0x%p to 0x%p\n",
1810 le32_to_cpu(newext->ee_block),
1811 ext4_ext_pblock(newext),
1812 ext4_ext_is_uninitialized(newext),
1813 ext4_ext_get_actual_len(newext),
1814 len, nearex, nearex + 1);
1815 memmove(nearex + 1, nearex,
1816 len * sizeof(struct ext4_extent));
a86c6181 1817 }
a86c6181
AT
1818 }
1819
e8546d06 1820 le16_add_cpu(&eh->eh_entries, 1);
80e675f9 1821 path[depth].p_ext = nearex;
a86c6181 1822 nearex->ee_block = newext->ee_block;
bf89d16f 1823 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
a86c6181 1824 nearex->ee_len = newext->ee_len;
a86c6181
AT
1825
1826merge:
1827 /* try to merge extents to the right */
744692dc 1828 if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
0031462b 1829 ext4_ext_try_to_merge(inode, path, nearex);
a86c6181
AT
1830
1831 /* try to merge extents to the left */
1832
1833 /* time to correct all indexes above */
1834 err = ext4_ext_correct_indexes(handle, inode, path);
1835 if (err)
1836 goto cleanup;
1837
1838 err = ext4_ext_dirty(handle, inode, path + depth);
1839
1840cleanup:
1841 if (npath) {
1842 ext4_ext_drop_refs(npath);
1843 kfree(npath);
1844 }
a86c6181
AT
1845 ext4_ext_invalidate_cache(inode);
1846 return err;
1847}
1848
1f109d5a
TT
1849static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1850 ext4_lblk_t num, ext_prepare_callback func,
1851 void *cbdata)
6873fa0d
ES
1852{
1853 struct ext4_ext_path *path = NULL;
1854 struct ext4_ext_cache cbex;
1855 struct ext4_extent *ex;
1856 ext4_lblk_t next, start = 0, end = 0;
1857 ext4_lblk_t last = block + num;
1858 int depth, exists, err = 0;
1859
1860 BUG_ON(func == NULL);
1861 BUG_ON(inode == NULL);
1862
f17722f9 1863 while (block < last && block != EXT_MAX_BLOCKS) {
6873fa0d
ES
1864 num = last - block;
1865 /* find extent for this block */
fab3a549 1866 down_read(&EXT4_I(inode)->i_data_sem);
6873fa0d 1867 path = ext4_ext_find_extent(inode, block, path);
fab3a549 1868 up_read(&EXT4_I(inode)->i_data_sem);
6873fa0d
ES
1869 if (IS_ERR(path)) {
1870 err = PTR_ERR(path);
1871 path = NULL;
1872 break;
1873 }
1874
1875 depth = ext_depth(inode);
273df556
FM
1876 if (unlikely(path[depth].p_hdr == NULL)) {
1877 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1878 err = -EIO;
1879 break;
1880 }
6873fa0d
ES
1881 ex = path[depth].p_ext;
1882 next = ext4_ext_next_allocated_block(path);
1883
1884 exists = 0;
1885 if (!ex) {
1886 /* there is no extent yet, so try to allocate
1887 * all requested space */
1888 start = block;
1889 end = block + num;
1890 } else if (le32_to_cpu(ex->ee_block) > block) {
1891 /* need to allocate space before found extent */
1892 start = block;
1893 end = le32_to_cpu(ex->ee_block);
1894 if (block + num < end)
1895 end = block + num;
1896 } else if (block >= le32_to_cpu(ex->ee_block)
1897 + ext4_ext_get_actual_len(ex)) {
1898 /* need to allocate space after found extent */
1899 start = block;
1900 end = block + num;
1901 if (end >= next)
1902 end = next;
1903 } else if (block >= le32_to_cpu(ex->ee_block)) {
1904 /*
1905 * some part of requested space is covered
1906 * by found extent
1907 */
1908 start = block;
1909 end = le32_to_cpu(ex->ee_block)
1910 + ext4_ext_get_actual_len(ex);
1911 if (block + num < end)
1912 end = block + num;
1913 exists = 1;
1914 } else {
1915 BUG();
1916 }
1917 BUG_ON(end <= start);
1918
1919 if (!exists) {
1920 cbex.ec_block = start;
1921 cbex.ec_len = end - start;
1922 cbex.ec_start = 0;
6873fa0d
ES
1923 } else {
1924 cbex.ec_block = le32_to_cpu(ex->ee_block);
1925 cbex.ec_len = ext4_ext_get_actual_len(ex);
bf89d16f 1926 cbex.ec_start = ext4_ext_pblock(ex);
6873fa0d
ES
1927 }
1928
273df556
FM
1929 if (unlikely(cbex.ec_len == 0)) {
1930 EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1931 err = -EIO;
1932 break;
1933 }
c03f8aa9 1934 err = func(inode, next, &cbex, ex, cbdata);
6873fa0d
ES
1935 ext4_ext_drop_refs(path);
1936
1937 if (err < 0)
1938 break;
1939
1940 if (err == EXT_REPEAT)
1941 continue;
1942 else if (err == EXT_BREAK) {
1943 err = 0;
1944 break;
1945 }
1946
1947 if (ext_depth(inode) != depth) {
1948 /* depth was changed. we have to realloc path */
1949 kfree(path);
1950 path = NULL;
1951 }
1952
1953 block = cbex.ec_block + cbex.ec_len;
1954 }
1955
1956 if (path) {
1957 ext4_ext_drop_refs(path);
1958 kfree(path);
1959 }
1960
1961 return err;
1962}
1963
09b88252 1964static void
725d26d3 1965ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
b05e6ae5 1966 __u32 len, ext4_fsblk_t start)
a86c6181
AT
1967{
1968 struct ext4_ext_cache *cex;
1969 BUG_ON(len == 0);
2ec0ae3a 1970 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
d8990240 1971 trace_ext4_ext_put_in_cache(inode, block, len, start);
a86c6181 1972 cex = &EXT4_I(inode)->i_cached_extent;
a86c6181
AT
1973 cex->ec_block = block;
1974 cex->ec_len = len;
1975 cex->ec_start = start;
2ec0ae3a 1976 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
a86c6181
AT
1977}
1978
1979/*
d0d856e8
RD
1980 * ext4_ext_put_gap_in_cache:
1981 * calculate boundaries of the gap that the requested block fits into
a86c6181
AT
1982 * and cache this gap
1983 */
09b88252 1984static void
a86c6181 1985ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
725d26d3 1986 ext4_lblk_t block)
a86c6181
AT
1987{
1988 int depth = ext_depth(inode);
725d26d3
AK
1989 unsigned long len;
1990 ext4_lblk_t lblock;
a86c6181
AT
1991 struct ext4_extent *ex;
1992
1993 ex = path[depth].p_ext;
1994 if (ex == NULL) {
1995 /* there is no extent yet, so gap is [0;-] */
1996 lblock = 0;
f17722f9 1997 len = EXT_MAX_BLOCKS;
a86c6181
AT
1998 ext_debug("cache gap(whole file):");
1999 } else if (block < le32_to_cpu(ex->ee_block)) {
2000 lblock = block;
2001 len = le32_to_cpu(ex->ee_block) - block;
bba90743
ES
2002 ext_debug("cache gap(before): %u [%u:%u]",
2003 block,
2004 le32_to_cpu(ex->ee_block),
2005 ext4_ext_get_actual_len(ex));
a86c6181 2006 } else if (block >= le32_to_cpu(ex->ee_block)
a2df2a63 2007 + ext4_ext_get_actual_len(ex)) {
725d26d3 2008 ext4_lblk_t next;
8c55e204 2009 lblock = le32_to_cpu(ex->ee_block)
a2df2a63 2010 + ext4_ext_get_actual_len(ex);
725d26d3
AK
2011
2012 next = ext4_ext_next_allocated_block(path);
bba90743
ES
2013 ext_debug("cache gap(after): [%u:%u] %u",
2014 le32_to_cpu(ex->ee_block),
2015 ext4_ext_get_actual_len(ex),
2016 block);
725d26d3
AK
2017 BUG_ON(next == lblock);
2018 len = next - lblock;
a86c6181
AT
2019 } else {
2020 lblock = len = 0;
2021 BUG();
2022 }
2023
bba90743 2024 ext_debug(" -> %u:%lu\n", lblock, len);
b05e6ae5 2025 ext4_ext_put_in_cache(inode, lblock, len, 0);
a86c6181
AT
2026}
2027
b05e6ae5 2028/*
b7ca1e8e 2029 * ext4_ext_check_cache()
a4bb6b64
AH
2030 * Checks to see if the given block is in the cache.
2031 * If it is, the cached extent is stored in the given
2032 * cache extent pointer. If the cached extent is a hole,
2033 * this routine should be used instead of
2034 * ext4_ext_in_cache if the calling function needs to
2035 * know the size of the hole.
2036 *
2037 * @inode: The files inode
2038 * @block: The block to look for in the cache
2039 * @ex: Pointer where the cached extent will be stored
2040 * if it contains block
2041 *
b05e6ae5
TT
2042 * Return 0 if cache is invalid; 1 if the cache is valid
2043 */
a4bb6b64
AH
2044static int ext4_ext_check_cache(struct inode *inode, ext4_lblk_t block,
2045 struct ext4_ext_cache *ex){
a86c6181 2046 struct ext4_ext_cache *cex;
77f4135f 2047 struct ext4_sb_info *sbi;
b05e6ae5 2048 int ret = 0;
a86c6181 2049
60e6679e 2050 /*
2ec0ae3a
TT
2051 * We borrow i_block_reservation_lock to protect i_cached_extent
2052 */
2053 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
a86c6181 2054 cex = &EXT4_I(inode)->i_cached_extent;
77f4135f 2055 sbi = EXT4_SB(inode->i_sb);
a86c6181
AT
2056
2057 /* has cache valid data? */
b05e6ae5 2058 if (cex->ec_len == 0)
2ec0ae3a 2059 goto errout;
a86c6181 2060
731eb1a0 2061 if (in_range(block, cex->ec_block, cex->ec_len)) {
a4bb6b64 2062 memcpy(ex, cex, sizeof(struct ext4_ext_cache));
bba90743
ES
2063 ext_debug("%u cached by %u:%u:%llu\n",
2064 block,
2065 cex->ec_block, cex->ec_len, cex->ec_start);
b05e6ae5 2066 ret = 1;
a86c6181 2067 }
2ec0ae3a 2068errout:
d8990240 2069 trace_ext4_ext_in_cache(inode, block, ret);
2ec0ae3a
TT
2070 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2071 return ret;
a86c6181
AT
2072}
2073
a4bb6b64
AH
2074/*
2075 * ext4_ext_in_cache()
2076 * Checks to see if the given block is in the cache.
2077 * If it is, the cached extent is stored in the given
2078 * extent pointer.
2079 *
2080 * @inode: The files inode
2081 * @block: The block to look for in the cache
2082 * @ex: Pointer where the cached extent will be stored
2083 * if it contains block
2084 *
2085 * Return 0 if cache is invalid; 1 if the cache is valid
2086 */
2087static int
2088ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2089 struct ext4_extent *ex)
2090{
2091 struct ext4_ext_cache cex;
2092 int ret = 0;
2093
2094 if (ext4_ext_check_cache(inode, block, &cex)) {
2095 ex->ee_block = cpu_to_le32(cex.ec_block);
2096 ext4_ext_store_pblock(ex, cex.ec_start);
2097 ex->ee_len = cpu_to_le16(cex.ec_len);
2098 ret = 1;
2099 }
2100
2101 return ret;
2102}
2103
2104
a86c6181 2105/*
d0d856e8
RD
2106 * ext4_ext_rm_idx:
2107 * removes index from the index block.
a86c6181 2108 */
1d03ec98 2109static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
a86c6181
AT
2110 struct ext4_ext_path *path)
2111{
a86c6181 2112 int err;
f65e6fba 2113 ext4_fsblk_t leaf;
a86c6181
AT
2114
2115 /* free index block */
2116 path--;
bf89d16f 2117 leaf = ext4_idx_pblock(path->p_idx);
273df556
FM
2118 if (unlikely(path->p_hdr->eh_entries == 0)) {
2119 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2120 return -EIO;
2121 }
7e028976
AM
2122 err = ext4_ext_get_access(handle, inode, path);
2123 if (err)
a86c6181 2124 return err;
0e1147b0
RD
2125
2126 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2127 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2128 len *= sizeof(struct ext4_extent_idx);
2129 memmove(path->p_idx, path->p_idx + 1, len);
2130 }
2131
e8546d06 2132 le16_add_cpu(&path->p_hdr->eh_entries, -1);
7e028976
AM
2133 err = ext4_ext_dirty(handle, inode, path);
2134 if (err)
a86c6181 2135 return err;
2ae02107 2136 ext_debug("index is empty, remove it, free block %llu\n", leaf);
d8990240
AK
2137 trace_ext4_ext_rm_idx(inode, leaf);
2138
7dc57615 2139 ext4_free_blocks(handle, inode, NULL, leaf, 1,
e6362609 2140 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
a86c6181
AT
2141 return err;
2142}
2143
2144/*
ee12b630
MC
2145 * ext4_ext_calc_credits_for_single_extent:
2146 * This routine returns max. credits that needed to insert an extent
2147 * to the extent tree.
2148 * When pass the actual path, the caller should calculate credits
2149 * under i_data_sem.
a86c6181 2150 */
525f4ed8 2151int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
a86c6181
AT
2152 struct ext4_ext_path *path)
2153{
a86c6181 2154 if (path) {
ee12b630 2155 int depth = ext_depth(inode);
f3bd1f3f 2156 int ret = 0;
ee12b630 2157
a86c6181 2158 /* probably there is space in leaf? */
a86c6181 2159 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
ee12b630 2160 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
a86c6181 2161
ee12b630
MC
2162 /*
2163 * There are some space in the leaf tree, no
2164 * need to account for leaf block credit
2165 *
2166 * bitmaps and block group descriptor blocks
df3ab170 2167 * and other metadata blocks still need to be
ee12b630
MC
2168 * accounted.
2169 */
525f4ed8 2170 /* 1 bitmap, 1 block group descriptor */
ee12b630 2171 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
5887e98b 2172 return ret;
ee12b630
MC
2173 }
2174 }
a86c6181 2175
525f4ed8 2176 return ext4_chunk_trans_blocks(inode, nrblocks);
ee12b630 2177}
a86c6181 2178
ee12b630
MC
2179/*
2180 * How many index/leaf blocks need to change/allocate to modify nrblocks?
2181 *
2182 * if nrblocks are fit in a single extent (chunk flag is 1), then
2183 * in the worse case, each tree level index/leaf need to be changed
2184 * if the tree split due to insert a new extent, then the old tree
2185 * index/leaf need to be updated too
2186 *
2187 * If the nrblocks are discontiguous, they could cause
2188 * the whole tree split more than once, but this is really rare.
2189 */
525f4ed8 2190int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
ee12b630
MC
2191{
2192 int index;
2193 int depth = ext_depth(inode);
a86c6181 2194
ee12b630
MC
2195 if (chunk)
2196 index = depth * 2;
2197 else
2198 index = depth * 3;
a86c6181 2199
ee12b630 2200 return index;
a86c6181
AT
2201}
2202
2203static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
0aa06000
TT
2204 struct ext4_extent *ex,
2205 ext4_fsblk_t *partial_cluster,
2206 ext4_lblk_t from, ext4_lblk_t to)
a86c6181 2207{
0aa06000 2208 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a2df2a63 2209 unsigned short ee_len = ext4_ext_get_actual_len(ex);
0aa06000 2210 ext4_fsblk_t pblk;
e6362609 2211 int flags = EXT4_FREE_BLOCKS_FORGET;
a86c6181 2212
c9de560d 2213 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
e6362609 2214 flags |= EXT4_FREE_BLOCKS_METADATA;
0aa06000
TT
2215 /*
2216 * For bigalloc file systems, we never free a partial cluster
2217 * at the beginning of the extent. Instead, we make a note
2218 * that we tried freeing the cluster, and check to see if we
2219 * need to free it on a subsequent call to ext4_remove_blocks,
2220 * or at the end of the ext4_truncate() operation.
2221 */
2222 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2223
d8990240 2224 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
0aa06000
TT
2225 /*
2226 * If we have a partial cluster, and it's different from the
2227 * cluster of the last block, we need to explicitly free the
2228 * partial cluster here.
2229 */
2230 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2231 if (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {
2232 ext4_free_blocks(handle, inode, NULL,
2233 EXT4_C2B(sbi, *partial_cluster),
2234 sbi->s_cluster_ratio, flags);
2235 *partial_cluster = 0;
2236 }
2237
a86c6181
AT
2238#ifdef EXTENTS_STATS
2239 {
2240 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a86c6181
AT
2241 spin_lock(&sbi->s_ext_stats_lock);
2242 sbi->s_ext_blocks += ee_len;
2243 sbi->s_ext_extents++;
2244 if (ee_len < sbi->s_ext_min)
2245 sbi->s_ext_min = ee_len;
2246 if (ee_len > sbi->s_ext_max)
2247 sbi->s_ext_max = ee_len;
2248 if (ext_depth(inode) > sbi->s_depth_max)
2249 sbi->s_depth_max = ext_depth(inode);
2250 spin_unlock(&sbi->s_ext_stats_lock);
2251 }
2252#endif
2253 if (from >= le32_to_cpu(ex->ee_block)
a2df2a63 2254 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
a86c6181 2255 /* tail removal */
725d26d3 2256 ext4_lblk_t num;
725d26d3 2257
a2df2a63 2258 num = le32_to_cpu(ex->ee_block) + ee_len - from;
0aa06000
TT
2259 pblk = ext4_ext_pblock(ex) + ee_len - num;
2260 ext_debug("free last %u blocks starting %llu\n", num, pblk);
2261 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2262 /*
2263 * If the block range to be freed didn't start at the
2264 * beginning of a cluster, and we removed the entire
2265 * extent, save the partial cluster here, since we
2266 * might need to delete if we determine that the
2267 * truncate operation has removed all of the blocks in
2268 * the cluster.
2269 */
2270 if (pblk & (sbi->s_cluster_ratio - 1) &&
2271 (ee_len == num))
2272 *partial_cluster = EXT4_B2C(sbi, pblk);
2273 else
2274 *partial_cluster = 0;
a86c6181 2275 } else if (from == le32_to_cpu(ex->ee_block)
a2df2a63 2276 && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
d583fb87
AH
2277 /* head removal */
2278 ext4_lblk_t num;
2279 ext4_fsblk_t start;
2280
2281 num = to - from;
2282 start = ext4_ext_pblock(ex);
2283
2284 ext_debug("free first %u blocks starting %llu\n", num, start);
ee90d57e 2285 ext4_free_blocks(handle, inode, NULL, start, num, flags);
d583fb87 2286
a86c6181 2287 } else {
725d26d3
AK
2288 printk(KERN_INFO "strange request: removal(2) "
2289 "%u-%u from %u:%u\n",
2290 from, to, le32_to_cpu(ex->ee_block), ee_len);
a86c6181
AT
2291 }
2292 return 0;
2293}
2294
d583fb87
AH
2295
2296/*
2297 * ext4_ext_rm_leaf() Removes the extents associated with the
2298 * blocks appearing between "start" and "end", and splits the extents
2299 * if "start" and "end" appear in the same extent
2300 *
2301 * @handle: The journal handle
2302 * @inode: The files inode
2303 * @path: The path to the leaf
2304 * @start: The first block to remove
2305 * @end: The last block to remove
2306 */
a86c6181
AT
2307static int
2308ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
0aa06000
TT
2309 struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,
2310 ext4_lblk_t start, ext4_lblk_t end)
a86c6181 2311{
0aa06000 2312 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a86c6181
AT
2313 int err = 0, correct_index = 0;
2314 int depth = ext_depth(inode), credits;
2315 struct ext4_extent_header *eh;
750c9c47 2316 ext4_lblk_t a, b;
725d26d3
AK
2317 unsigned num;
2318 ext4_lblk_t ex_ee_block;
a86c6181 2319 unsigned short ex_ee_len;
a2df2a63 2320 unsigned uninitialized = 0;
a86c6181
AT
2321 struct ext4_extent *ex;
2322
c29c0ae7 2323 /* the header must be checked already in ext4_ext_remove_space() */
5f95d21f 2324 ext_debug("truncate since %u in leaf to %u\n", start, end);
a86c6181
AT
2325 if (!path[depth].p_hdr)
2326 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2327 eh = path[depth].p_hdr;
273df556
FM
2328 if (unlikely(path[depth].p_hdr == NULL)) {
2329 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2330 return -EIO;
2331 }
a86c6181
AT
2332 /* find where to start removing */
2333 ex = EXT_LAST_EXTENT(eh);
2334
2335 ex_ee_block = le32_to_cpu(ex->ee_block);
a2df2a63 2336 ex_ee_len = ext4_ext_get_actual_len(ex);
a86c6181 2337
d8990240
AK
2338 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2339
a86c6181
AT
2340 while (ex >= EXT_FIRST_EXTENT(eh) &&
2341 ex_ee_block + ex_ee_len > start) {
a41f2071
AK
2342
2343 if (ext4_ext_is_uninitialized(ex))
2344 uninitialized = 1;
2345 else
2346 uninitialized = 0;
2347
553f9008
M
2348 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2349 uninitialized, ex_ee_len);
a86c6181
AT
2350 path[depth].p_ext = ex;
2351
2352 a = ex_ee_block > start ? ex_ee_block : start;
d583fb87
AH
2353 b = ex_ee_block+ex_ee_len - 1 < end ?
2354 ex_ee_block+ex_ee_len - 1 : end;
a86c6181
AT
2355
2356 ext_debug(" border %u:%u\n", a, b);
2357
d583fb87 2358 /* If this extent is beyond the end of the hole, skip it */
5f95d21f 2359 if (end < ex_ee_block) {
d583fb87
AH
2360 ex--;
2361 ex_ee_block = le32_to_cpu(ex->ee_block);
2362 ex_ee_len = ext4_ext_get_actual_len(ex);
2363 continue;
750c9c47 2364 } else if (b != ex_ee_block + ex_ee_len - 1) {
dc1841d6
LC
2365 EXT4_ERROR_INODE(inode,
2366 "can not handle truncate %u:%u "
2367 "on extent %u:%u",
2368 start, end, ex_ee_block,
2369 ex_ee_block + ex_ee_len - 1);
750c9c47
DM
2370 err = -EIO;
2371 goto out;
a86c6181
AT
2372 } else if (a != ex_ee_block) {
2373 /* remove tail of the extent */
750c9c47 2374 num = a - ex_ee_block;
a86c6181
AT
2375 } else {
2376 /* remove whole extent: excellent! */
a86c6181 2377 num = 0;
a86c6181 2378 }
34071da7
TT
2379 /*
2380 * 3 for leaf, sb, and inode plus 2 (bmap and group
2381 * descriptor) for each block group; assume two block
2382 * groups plus ex_ee_len/blocks_per_block_group for
2383 * the worst case
2384 */
2385 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
a86c6181
AT
2386 if (ex == EXT_FIRST_EXTENT(eh)) {
2387 correct_index = 1;
2388 credits += (ext_depth(inode)) + 1;
2389 }
5aca07eb 2390 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
a86c6181 2391
487caeef 2392 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
9102e4fa 2393 if (err)
a86c6181 2394 goto out;
a86c6181
AT
2395
2396 err = ext4_ext_get_access(handle, inode, path + depth);
2397 if (err)
2398 goto out;
2399
0aa06000
TT
2400 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2401 a, b);
a86c6181
AT
2402 if (err)
2403 goto out;
2404
750c9c47 2405 if (num == 0)
d0d856e8 2406 /* this extent is removed; mark slot entirely unused */
f65e6fba 2407 ext4_ext_store_pblock(ex, 0);
a86c6181 2408
a86c6181 2409 ex->ee_len = cpu_to_le16(num);
749269fa
AA
2410 /*
2411 * Do not mark uninitialized if all the blocks in the
2412 * extent have been removed.
2413 */
2414 if (uninitialized && num)
a2df2a63 2415 ext4_ext_mark_uninitialized(ex);
d583fb87
AH
2416 /*
2417 * If the extent was completely released,
2418 * we need to remove it from the leaf
2419 */
2420 if (num == 0) {
f17722f9 2421 if (end != EXT_MAX_BLOCKS - 1) {
d583fb87
AH
2422 /*
2423 * For hole punching, we need to scoot all the
2424 * extents up when an extent is removed so that
2425 * we dont have blank extents in the middle
2426 */
2427 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2428 sizeof(struct ext4_extent));
2429
2430 /* Now get rid of the one at the end */
2431 memset(EXT_LAST_EXTENT(eh), 0,
2432 sizeof(struct ext4_extent));
2433 }
2434 le16_add_cpu(&eh->eh_entries, -1);
0aa06000
TT
2435 } else
2436 *partial_cluster = 0;
d583fb87 2437
750c9c47
DM
2438 err = ext4_ext_dirty(handle, inode, path + depth);
2439 if (err)
2440 goto out;
2441
bf52c6f7 2442 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
bf89d16f 2443 ext4_ext_pblock(ex));
a86c6181
AT
2444 ex--;
2445 ex_ee_block = le32_to_cpu(ex->ee_block);
a2df2a63 2446 ex_ee_len = ext4_ext_get_actual_len(ex);
a86c6181
AT
2447 }
2448
2449 if (correct_index && eh->eh_entries)
2450 err = ext4_ext_correct_indexes(handle, inode, path);
2451
0aa06000
TT
2452 /*
2453 * If there is still a entry in the leaf node, check to see if
2454 * it references the partial cluster. This is the only place
2455 * where it could; if it doesn't, we can free the cluster.
2456 */
2457 if (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&
2458 (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=
2459 *partial_cluster)) {
2460 int flags = EXT4_FREE_BLOCKS_FORGET;
2461
2462 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2463 flags |= EXT4_FREE_BLOCKS_METADATA;
2464
2465 ext4_free_blocks(handle, inode, NULL,
2466 EXT4_C2B(sbi, *partial_cluster),
2467 sbi->s_cluster_ratio, flags);
2468 *partial_cluster = 0;
2469 }
2470
a86c6181
AT
2471 /* if this leaf is free, then we should
2472 * remove it from index block above */
2473 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2474 err = ext4_ext_rm_idx(handle, inode, path + depth);
2475
2476out:
2477 return err;
2478}
2479
2480/*
d0d856e8
RD
2481 * ext4_ext_more_to_rm:
2482 * returns 1 if current index has to be freed (even partial)
a86c6181 2483 */
09b88252 2484static int
a86c6181
AT
2485ext4_ext_more_to_rm(struct ext4_ext_path *path)
2486{
2487 BUG_ON(path->p_idx == NULL);
2488
2489 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2490 return 0;
2491
2492 /*
d0d856e8 2493 * if truncate on deeper level happened, it wasn't partial,
a86c6181
AT
2494 * so we have to consider current index for truncation
2495 */
2496 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2497 return 0;
2498 return 1;
2499}
2500
5f95d21f
LC
2501static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2502 ext4_lblk_t end)
a86c6181
AT
2503{
2504 struct super_block *sb = inode->i_sb;
2505 int depth = ext_depth(inode);
2506 struct ext4_ext_path *path;
0aa06000 2507 ext4_fsblk_t partial_cluster = 0;
a86c6181 2508 handle_t *handle;
0617b83f 2509 int i, err;
a86c6181 2510
5f95d21f 2511 ext_debug("truncate since %u to %u\n", start, end);
a86c6181
AT
2512
2513 /* probably first extent we're gonna free will be last in block */
2514 handle = ext4_journal_start(inode, depth + 1);
2515 if (IS_ERR(handle))
2516 return PTR_ERR(handle);
2517
0617b83f 2518again:
a86c6181
AT
2519 ext4_ext_invalidate_cache(inode);
2520
d8990240
AK
2521 trace_ext4_ext_remove_space(inode, start, depth);
2522
5f95d21f
LC
2523 /*
2524 * Check if we are removing extents inside the extent tree. If that
2525 * is the case, we are going to punch a hole inside the extent tree
2526 * so we have to check whether we need to split the extent covering
2527 * the last block to remove so we can easily remove the part of it
2528 * in ext4_ext_rm_leaf().
2529 */
2530 if (end < EXT_MAX_BLOCKS - 1) {
2531 struct ext4_extent *ex;
2532 ext4_lblk_t ee_block;
2533
2534 /* find extent for this block */
2535 path = ext4_ext_find_extent(inode, end, NULL);
2536 if (IS_ERR(path)) {
2537 ext4_journal_stop(handle);
2538 return PTR_ERR(path);
2539 }
2540 depth = ext_depth(inode);
2541 ex = path[depth].p_ext;
2542 if (!ex)
2543 goto cont;
2544
2545 ee_block = le32_to_cpu(ex->ee_block);
2546
2547 /*
2548 * See if the last block is inside the extent, if so split
2549 * the extent at 'end' block so we can easily remove the
2550 * tail of the first part of the split extent in
2551 * ext4_ext_rm_leaf().
2552 */
2553 if (end >= ee_block &&
2554 end < ee_block + ext4_ext_get_actual_len(ex) - 1) {
2555 int split_flag = 0;
2556
2557 if (ext4_ext_is_uninitialized(ex))
2558 split_flag = EXT4_EXT_MARK_UNINIT1 |
2559 EXT4_EXT_MARK_UNINIT2;
2560
2561 /*
2562 * Split the extent in two so that 'end' is the last
2563 * block in the first new extent
2564 */
2565 err = ext4_split_extent_at(handle, inode, path,
2566 end + 1, split_flag,
2567 EXT4_GET_BLOCKS_PRE_IO |
2568 EXT4_GET_BLOCKS_PUNCH_OUT_EXT);
2569
2570 if (err < 0)
2571 goto out;
2572 }
2573 ext4_ext_drop_refs(path);
2574 kfree(path);
2575 }
2576cont:
2577
a86c6181 2578 /*
d0d856e8
RD
2579 * We start scanning from right side, freeing all the blocks
2580 * after i_size and walking into the tree depth-wise.
a86c6181 2581 */
0617b83f 2582 depth = ext_depth(inode);
216553c4 2583 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
a86c6181
AT
2584 if (path == NULL) {
2585 ext4_journal_stop(handle);
2586 return -ENOMEM;
2587 }
0617b83f 2588 path[0].p_depth = depth;
a86c6181 2589 path[0].p_hdr = ext_inode_hdr(inode);
5f95d21f 2590
56b19868 2591 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
a86c6181
AT
2592 err = -EIO;
2593 goto out;
2594 }
0617b83f 2595 i = err = 0;
a86c6181
AT
2596
2597 while (i >= 0 && err == 0) {
2598 if (i == depth) {
2599 /* this is leaf block */
d583fb87 2600 err = ext4_ext_rm_leaf(handle, inode, path,
0aa06000 2601 &partial_cluster, start,
5f95d21f 2602 end);
d0d856e8 2603 /* root level has p_bh == NULL, brelse() eats this */
a86c6181
AT
2604 brelse(path[i].p_bh);
2605 path[i].p_bh = NULL;
2606 i--;
2607 continue;
2608 }
2609
2610 /* this is index block */
2611 if (!path[i].p_hdr) {
2612 ext_debug("initialize header\n");
2613 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
a86c6181
AT
2614 }
2615
a86c6181 2616 if (!path[i].p_idx) {
d0d856e8 2617 /* this level hasn't been touched yet */
a86c6181
AT
2618 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2619 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2620 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2621 path[i].p_hdr,
2622 le16_to_cpu(path[i].p_hdr->eh_entries));
2623 } else {
d0d856e8 2624 /* we were already here, see at next index */
a86c6181
AT
2625 path[i].p_idx--;
2626 }
2627
2628 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2629 i, EXT_FIRST_INDEX(path[i].p_hdr),
2630 path[i].p_idx);
2631 if (ext4_ext_more_to_rm(path + i)) {
c29c0ae7 2632 struct buffer_head *bh;
a86c6181 2633 /* go to the next level */
2ae02107 2634 ext_debug("move to level %d (block %llu)\n",
bf89d16f 2635 i + 1, ext4_idx_pblock(path[i].p_idx));
a86c6181 2636 memset(path + i + 1, 0, sizeof(*path));
bf89d16f 2637 bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
c29c0ae7 2638 if (!bh) {
a86c6181
AT
2639 /* should we reset i_size? */
2640 err = -EIO;
2641 break;
2642 }
c29c0ae7
AT
2643 if (WARN_ON(i + 1 > depth)) {
2644 err = -EIO;
2645 break;
2646 }
56b19868 2647 if (ext4_ext_check(inode, ext_block_hdr(bh),
c29c0ae7
AT
2648 depth - i - 1)) {
2649 err = -EIO;
2650 break;
2651 }
2652 path[i + 1].p_bh = bh;
a86c6181 2653
d0d856e8
RD
2654 /* save actual number of indexes since this
2655 * number is changed at the next iteration */
a86c6181
AT
2656 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2657 i++;
2658 } else {
d0d856e8 2659 /* we finished processing this index, go up */
a86c6181 2660 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
d0d856e8 2661 /* index is empty, remove it;
a86c6181
AT
2662 * handle must be already prepared by the
2663 * truncatei_leaf() */
2664 err = ext4_ext_rm_idx(handle, inode, path + i);
2665 }
d0d856e8 2666 /* root level has p_bh == NULL, brelse() eats this */
a86c6181
AT
2667 brelse(path[i].p_bh);
2668 path[i].p_bh = NULL;
2669 i--;
2670 ext_debug("return to level %d\n", i);
2671 }
2672 }
2673
d8990240
AK
2674 trace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,
2675 path->p_hdr->eh_entries);
2676
7b415bf6
AK
2677 /* If we still have something in the partial cluster and we have removed
2678 * even the first extent, then we should free the blocks in the partial
2679 * cluster as well. */
2680 if (partial_cluster && path->p_hdr->eh_entries == 0) {
2681 int flags = EXT4_FREE_BLOCKS_FORGET;
2682
2683 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2684 flags |= EXT4_FREE_BLOCKS_METADATA;
2685
2686 ext4_free_blocks(handle, inode, NULL,
2687 EXT4_C2B(EXT4_SB(sb), partial_cluster),
2688 EXT4_SB(sb)->s_cluster_ratio, flags);
2689 partial_cluster = 0;
2690 }
2691
a86c6181
AT
2692 /* TODO: flexible tree reduction should be here */
2693 if (path->p_hdr->eh_entries == 0) {
2694 /*
d0d856e8
RD
2695 * truncate to zero freed all the tree,
2696 * so we need to correct eh_depth
a86c6181
AT
2697 */
2698 err = ext4_ext_get_access(handle, inode, path);
2699 if (err == 0) {
2700 ext_inode_hdr(inode)->eh_depth = 0;
2701 ext_inode_hdr(inode)->eh_max =
55ad63bf 2702 cpu_to_le16(ext4_ext_space_root(inode, 0));
a86c6181
AT
2703 err = ext4_ext_dirty(handle, inode, path);
2704 }
2705 }
2706out:
a86c6181
AT
2707 ext4_ext_drop_refs(path);
2708 kfree(path);
0617b83f
DM
2709 if (err == -EAGAIN)
2710 goto again;
a86c6181
AT
2711 ext4_journal_stop(handle);
2712
2713 return err;
2714}
2715
2716/*
2717 * called at mount time
2718 */
2719void ext4_ext_init(struct super_block *sb)
2720{
2721 /*
2722 * possible initialization would be here
2723 */
2724
83982b6f 2725 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
90576c0b 2726#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
92b97816 2727 printk(KERN_INFO "EXT4-fs: file extents enabled"
bbf2f9fb 2728#ifdef AGGRESSIVE_TEST
92b97816 2729 ", aggressive tests"
a86c6181
AT
2730#endif
2731#ifdef CHECK_BINSEARCH
92b97816 2732 ", check binsearch"
a86c6181
AT
2733#endif
2734#ifdef EXTENTS_STATS
92b97816 2735 ", stats"
a86c6181 2736#endif
92b97816 2737 "\n");
90576c0b 2738#endif
a86c6181
AT
2739#ifdef EXTENTS_STATS
2740 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2741 EXT4_SB(sb)->s_ext_min = 1 << 30;
2742 EXT4_SB(sb)->s_ext_max = 0;
2743#endif
2744 }
2745}
2746
2747/*
2748 * called at umount time
2749 */
2750void ext4_ext_release(struct super_block *sb)
2751{
83982b6f 2752 if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
a86c6181
AT
2753 return;
2754
2755#ifdef EXTENTS_STATS
2756 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2757 struct ext4_sb_info *sbi = EXT4_SB(sb);
2758 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2759 sbi->s_ext_blocks, sbi->s_ext_extents,
2760 sbi->s_ext_blocks / sbi->s_ext_extents);
2761 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2762 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2763 }
2764#endif
2765}
2766
093a088b
AK
2767/* FIXME!! we need to try to merge to left or right after zero-out */
2768static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2769{
2407518d
LC
2770 ext4_fsblk_t ee_pblock;
2771 unsigned int ee_len;
b720303d 2772 int ret;
093a088b 2773
093a088b 2774 ee_len = ext4_ext_get_actual_len(ex);
bf89d16f 2775 ee_pblock = ext4_ext_pblock(ex);
b720303d 2776
a107e5a3 2777 ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
2407518d
LC
2778 if (ret > 0)
2779 ret = 0;
093a088b 2780
2407518d 2781 return ret;
093a088b
AK
2782}
2783
47ea3bb5
YY
2784/*
2785 * ext4_split_extent_at() splits an extent at given block.
2786 *
2787 * @handle: the journal handle
2788 * @inode: the file inode
2789 * @path: the path to the extent
2790 * @split: the logical block where the extent is splitted.
2791 * @split_flags: indicates if the extent could be zeroout if split fails, and
2792 * the states(init or uninit) of new extents.
2793 * @flags: flags used to insert new extent to extent tree.
2794 *
2795 *
2796 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
2797 * of which are deterimined by split_flag.
2798 *
2799 * There are two cases:
2800 * a> the extent are splitted into two extent.
2801 * b> split is not needed, and just mark the extent.
2802 *
2803 * return 0 on success.
2804 */
2805static int ext4_split_extent_at(handle_t *handle,
2806 struct inode *inode,
2807 struct ext4_ext_path *path,
2808 ext4_lblk_t split,
2809 int split_flag,
2810 int flags)
2811{
2812 ext4_fsblk_t newblock;
2813 ext4_lblk_t ee_block;
2814 struct ext4_extent *ex, newex, orig_ex;
2815 struct ext4_extent *ex2 = NULL;
2816 unsigned int ee_len, depth;
2817 int err = 0;
2818
2819 ext_debug("ext4_split_extents_at: inode %lu, logical"
2820 "block %llu\n", inode->i_ino, (unsigned long long)split);
2821
2822 ext4_ext_show_leaf(inode, path);
2823
2824 depth = ext_depth(inode);
2825 ex = path[depth].p_ext;
2826 ee_block = le32_to_cpu(ex->ee_block);
2827 ee_len = ext4_ext_get_actual_len(ex);
2828 newblock = split - ee_block + ext4_ext_pblock(ex);
2829
2830 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
2831
2832 err = ext4_ext_get_access(handle, inode, path + depth);
2833 if (err)
2834 goto out;
2835
2836 if (split == ee_block) {
2837 /*
2838 * case b: block @split is the block that the extent begins with
2839 * then we just change the state of the extent, and splitting
2840 * is not needed.
2841 */
2842 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2843 ext4_ext_mark_uninitialized(ex);
2844 else
2845 ext4_ext_mark_initialized(ex);
2846
2847 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
2848 ext4_ext_try_to_merge(inode, path, ex);
2849
2850 err = ext4_ext_dirty(handle, inode, path + depth);
2851 goto out;
2852 }
2853
2854 /* case a */
2855 memcpy(&orig_ex, ex, sizeof(orig_ex));
2856 ex->ee_len = cpu_to_le16(split - ee_block);
2857 if (split_flag & EXT4_EXT_MARK_UNINIT1)
2858 ext4_ext_mark_uninitialized(ex);
2859
2860 /*
2861 * path may lead to new leaf, not to original leaf any more
2862 * after ext4_ext_insert_extent() returns,
2863 */
2864 err = ext4_ext_dirty(handle, inode, path + depth);
2865 if (err)
2866 goto fix_extent_len;
2867
2868 ex2 = &newex;
2869 ex2->ee_block = cpu_to_le32(split);
2870 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
2871 ext4_ext_store_pblock(ex2, newblock);
2872 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2873 ext4_ext_mark_uninitialized(ex2);
2874
2875 err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
2876 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2877 err = ext4_ext_zeroout(inode, &orig_ex);
2878 if (err)
2879 goto fix_extent_len;
2880 /* update the extent length and mark as initialized */
af1584f5 2881 ex->ee_len = cpu_to_le16(ee_len);
47ea3bb5
YY
2882 ext4_ext_try_to_merge(inode, path, ex);
2883 err = ext4_ext_dirty(handle, inode, path + depth);
2884 goto out;
2885 } else if (err)
2886 goto fix_extent_len;
2887
2888out:
2889 ext4_ext_show_leaf(inode, path);
2890 return err;
2891
2892fix_extent_len:
2893 ex->ee_len = orig_ex.ee_len;
2894 ext4_ext_dirty(handle, inode, path + depth);
2895 return err;
2896}
2897
2898/*
2899 * ext4_split_extents() splits an extent and mark extent which is covered
2900 * by @map as split_flags indicates
2901 *
2902 * It may result in splitting the extent into multiple extents (upto three)
2903 * There are three possibilities:
2904 * a> There is no split required
2905 * b> Splits in two extents: Split is happening at either end of the extent
2906 * c> Splits in three extents: Somone is splitting in middle of the extent
2907 *
2908 */
2909static int ext4_split_extent(handle_t *handle,
2910 struct inode *inode,
2911 struct ext4_ext_path *path,
2912 struct ext4_map_blocks *map,
2913 int split_flag,
2914 int flags)
2915{
2916 ext4_lblk_t ee_block;
2917 struct ext4_extent *ex;
2918 unsigned int ee_len, depth;
2919 int err = 0;
2920 int uninitialized;
2921 int split_flag1, flags1;
2922
2923 depth = ext_depth(inode);
2924 ex = path[depth].p_ext;
2925 ee_block = le32_to_cpu(ex->ee_block);
2926 ee_len = ext4_ext_get_actual_len(ex);
2927 uninitialized = ext4_ext_is_uninitialized(ex);
2928
2929 if (map->m_lblk + map->m_len < ee_block + ee_len) {
2930 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2931 EXT4_EXT_MAY_ZEROOUT : 0;
2932 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
2933 if (uninitialized)
2934 split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
2935 EXT4_EXT_MARK_UNINIT2;
2936 err = ext4_split_extent_at(handle, inode, path,
2937 map->m_lblk + map->m_len, split_flag1, flags1);
93917411
YY
2938 if (err)
2939 goto out;
47ea3bb5
YY
2940 }
2941
2942 ext4_ext_drop_refs(path);
2943 path = ext4_ext_find_extent(inode, map->m_lblk, path);
2944 if (IS_ERR(path))
2945 return PTR_ERR(path);
2946
2947 if (map->m_lblk >= ee_block) {
2948 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2949 EXT4_EXT_MAY_ZEROOUT : 0;
2950 if (uninitialized)
2951 split_flag1 |= EXT4_EXT_MARK_UNINIT1;
2952 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2953 split_flag1 |= EXT4_EXT_MARK_UNINIT2;
2954 err = ext4_split_extent_at(handle, inode, path,
2955 map->m_lblk, split_flag1, flags);
2956 if (err)
2957 goto out;
2958 }
2959
2960 ext4_ext_show_leaf(inode, path);
2961out:
2962 return err ? err : map->m_len;
2963}
2964
3977c965 2965#define EXT4_EXT_ZERO_LEN 7
56055d3a 2966/*
e35fd660 2967 * This function is called by ext4_ext_map_blocks() if someone tries to write
56055d3a 2968 * to an uninitialized extent. It may result in splitting the uninitialized
25985edc 2969 * extent into multiple extents (up to three - one initialized and two
56055d3a
AA
2970 * uninitialized).
2971 * There are three possibilities:
2972 * a> There is no split required: Entire extent should be initialized
2973 * b> Splits in two extents: Write is happening at either end of the extent
2974 * c> Splits in three extents: Somone is writing in middle of the extent
6f91bc5f
EG
2975 *
2976 * Pre-conditions:
2977 * - The extent pointed to by 'path' is uninitialized.
2978 * - The extent pointed to by 'path' contains a superset
2979 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
2980 *
2981 * Post-conditions on success:
2982 * - the returned value is the number of blocks beyond map->l_lblk
2983 * that are allocated and initialized.
2984 * It is guaranteed to be >= map->m_len.
56055d3a 2985 */
725d26d3 2986static int ext4_ext_convert_to_initialized(handle_t *handle,
e35fd660
TT
2987 struct inode *inode,
2988 struct ext4_map_blocks *map,
2989 struct ext4_ext_path *path)
56055d3a 2990{
6f91bc5f 2991 struct ext4_extent_header *eh;
667eff35
YY
2992 struct ext4_map_blocks split_map;
2993 struct ext4_extent zero_ex;
2994 struct ext4_extent *ex;
21ca087a 2995 ext4_lblk_t ee_block, eof_block;
f85b287a
DC
2996 unsigned int ee_len, depth;
2997 int allocated;
56055d3a 2998 int err = 0;
667eff35 2999 int split_flag = 0;
21ca087a
DM
3000
3001 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3002 "block %llu, max_blocks %u\n", inode->i_ino,
e35fd660 3003 (unsigned long long)map->m_lblk, map->m_len);
21ca087a
DM
3004
3005 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3006 inode->i_sb->s_blocksize_bits;
e35fd660
TT
3007 if (eof_block < map->m_lblk + map->m_len)
3008 eof_block = map->m_lblk + map->m_len;
56055d3a
AA
3009
3010 depth = ext_depth(inode);
6f91bc5f 3011 eh = path[depth].p_hdr;
56055d3a
AA
3012 ex = path[depth].p_ext;
3013 ee_block = le32_to_cpu(ex->ee_block);
3014 ee_len = ext4_ext_get_actual_len(ex);
e35fd660 3015 allocated = ee_len - (map->m_lblk - ee_block);
56055d3a 3016
6f91bc5f
EG
3017 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3018
3019 /* Pre-conditions */
3020 BUG_ON(!ext4_ext_is_uninitialized(ex));
3021 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
6f91bc5f
EG
3022
3023 /*
3024 * Attempt to transfer newly initialized blocks from the currently
3025 * uninitialized extent to its left neighbor. This is much cheaper
3026 * than an insertion followed by a merge as those involve costly
3027 * memmove() calls. This is the common case in steady state for
3028 * workloads doing fallocate(FALLOC_FL_KEEP_SIZE) followed by append
3029 * writes.
3030 *
3031 * Limitations of the current logic:
3032 * - L1: we only deal with writes at the start of the extent.
3033 * The approach could be extended to writes at the end
3034 * of the extent but this scenario was deemed less common.
3035 * - L2: we do not deal with writes covering the whole extent.
3036 * This would require removing the extent if the transfer
3037 * is possible.
3038 * - L3: we only attempt to merge with an extent stored in the
3039 * same extent tree node.
3040 */
3041 if ((map->m_lblk == ee_block) && /*L1*/
3042 (map->m_len < ee_len) && /*L2*/
3043 (ex > EXT_FIRST_EXTENT(eh))) { /*L3*/
3044 struct ext4_extent *prev_ex;
3045 ext4_lblk_t prev_lblk;
3046 ext4_fsblk_t prev_pblk, ee_pblk;
3047 unsigned int prev_len, write_len;
3048
3049 prev_ex = ex - 1;
3050 prev_lblk = le32_to_cpu(prev_ex->ee_block);
3051 prev_len = ext4_ext_get_actual_len(prev_ex);
3052 prev_pblk = ext4_ext_pblock(prev_ex);
3053 ee_pblk = ext4_ext_pblock(ex);
3054 write_len = map->m_len;
3055
3056 /*
3057 * A transfer of blocks from 'ex' to 'prev_ex' is allowed
3058 * upon those conditions:
3059 * - C1: prev_ex is initialized,
3060 * - C2: prev_ex is logically abutting ex,
3061 * - C3: prev_ex is physically abutting ex,
3062 * - C4: prev_ex can receive the additional blocks without
3063 * overflowing the (initialized) length limit.
3064 */
3065 if ((!ext4_ext_is_uninitialized(prev_ex)) && /*C1*/
3066 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3067 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3068 (prev_len < (EXT_INIT_MAX_LEN - write_len))) { /*C4*/
3069 err = ext4_ext_get_access(handle, inode, path + depth);
3070 if (err)
3071 goto out;
3072
3073 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3074 map, ex, prev_ex);
3075
3076 /* Shift the start of ex by 'write_len' blocks */
3077 ex->ee_block = cpu_to_le32(ee_block + write_len);
3078 ext4_ext_store_pblock(ex, ee_pblk + write_len);
3079 ex->ee_len = cpu_to_le16(ee_len - write_len);
3080 ext4_ext_mark_uninitialized(ex); /* Restore the flag */
3081
3082 /* Extend prev_ex by 'write_len' blocks */
3083 prev_ex->ee_len = cpu_to_le16(prev_len + write_len);
3084
3085 /* Mark the block containing both extents as dirty */
3086 ext4_ext_dirty(handle, inode, path + depth);
3087
3088 /* Update path to point to the right extent */
3089 path[depth].p_ext = prev_ex;
3090
3091 /* Result: number of initialized blocks past m_lblk */
3092 allocated = write_len;
3093 goto out;
3094 }
3095 }
3096
667eff35 3097 WARN_ON(map->m_lblk < ee_block);
21ca087a
DM
3098 /*
3099 * It is safe to convert extent to initialized via explicit
3100 * zeroout only if extent is fully insde i_size or new_size.
3101 */
667eff35 3102 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
21ca087a 3103
3977c965 3104 /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
667eff35
YY
3105 if (ee_len <= 2*EXT4_EXT_ZERO_LEN &&
3106 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3107 err = ext4_ext_zeroout(inode, ex);
3977c965 3108 if (err)
d03856bd 3109 goto out;
d03856bd
AK
3110
3111 err = ext4_ext_get_access(handle, inode, path + depth);
3112 if (err)
3113 goto out;
667eff35
YY
3114 ext4_ext_mark_initialized(ex);
3115 ext4_ext_try_to_merge(inode, path, ex);
3116 err = ext4_ext_dirty(handle, inode, path + depth);
3117 goto out;
56055d3a 3118 }
667eff35 3119
56055d3a 3120 /*
667eff35
YY
3121 * four cases:
3122 * 1. split the extent into three extents.
3123 * 2. split the extent into two extents, zeroout the first half.
3124 * 3. split the extent into two extents, zeroout the second half.
3125 * 4. split the extent into two extents with out zeroout.
56055d3a 3126 */
667eff35
YY
3127 split_map.m_lblk = map->m_lblk;
3128 split_map.m_len = map->m_len;
3129
3130 if (allocated > map->m_len) {
3131 if (allocated <= EXT4_EXT_ZERO_LEN &&
3132 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3133 /* case 3 */
3134 zero_ex.ee_block =
9b940f8e
AH
3135 cpu_to_le32(map->m_lblk);
3136 zero_ex.ee_len = cpu_to_le16(allocated);
667eff35
YY
3137 ext4_ext_store_pblock(&zero_ex,
3138 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3139 err = ext4_ext_zeroout(inode, &zero_ex);
56055d3a
AA
3140 if (err)
3141 goto out;
667eff35
YY
3142 split_map.m_lblk = map->m_lblk;
3143 split_map.m_len = allocated;
3144 } else if ((map->m_lblk - ee_block + map->m_len <
3145 EXT4_EXT_ZERO_LEN) &&
3146 (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3147 /* case 2 */
3148 if (map->m_lblk != ee_block) {
3149 zero_ex.ee_block = ex->ee_block;
3150 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3151 ee_block);
3152 ext4_ext_store_pblock(&zero_ex,
3153 ext4_ext_pblock(ex));
3154 err = ext4_ext_zeroout(inode, &zero_ex);
3155 if (err)
3156 goto out;
3157 }
3158
667eff35 3159 split_map.m_lblk = ee_block;
9b940f8e
AH
3160 split_map.m_len = map->m_lblk - ee_block + map->m_len;
3161 allocated = map->m_len;
56055d3a
AA
3162 }
3163 }
667eff35
YY
3164
3165 allocated = ext4_split_extent(handle, inode, path,
3166 &split_map, split_flag, 0);
3167 if (allocated < 0)
3168 err = allocated;
3169
56055d3a
AA
3170out:
3171 return err ? err : allocated;
3172}
3173
0031462b 3174/*
e35fd660 3175 * This function is called by ext4_ext_map_blocks() from
0031462b
MC
3176 * ext4_get_blocks_dio_write() when DIO to write
3177 * to an uninitialized extent.
3178 *
fd018fe8 3179 * Writing to an uninitialized extent may result in splitting the uninitialized
b595076a 3180 * extent into multiple /initialized uninitialized extents (up to three)
0031462b
MC
3181 * There are three possibilities:
3182 * a> There is no split required: Entire extent should be uninitialized
3183 * b> Splits in two extents: Write is happening at either end of the extent
3184 * c> Splits in three extents: Somone is writing in middle of the extent
3185 *
3186 * One of more index blocks maybe needed if the extent tree grow after
b595076a 3187 * the uninitialized extent split. To prevent ENOSPC occur at the IO
0031462b 3188 * complete, we need to split the uninitialized extent before DIO submit
421f91d2 3189 * the IO. The uninitialized extent called at this time will be split
0031462b
MC
3190 * into three uninitialized extent(at most). After IO complete, the part
3191 * being filled will be convert to initialized by the end_io callback function
3192 * via ext4_convert_unwritten_extents().
ba230c3f
M
3193 *
3194 * Returns the size of uninitialized extent to be written on success.
0031462b
MC
3195 */
3196static int ext4_split_unwritten_extents(handle_t *handle,
3197 struct inode *inode,
e35fd660 3198 struct ext4_map_blocks *map,
0031462b 3199 struct ext4_ext_path *path,
0031462b
MC
3200 int flags)
3201{
667eff35
YY
3202 ext4_lblk_t eof_block;
3203 ext4_lblk_t ee_block;
3204 struct ext4_extent *ex;
3205 unsigned int ee_len;
3206 int split_flag = 0, depth;
21ca087a
DM
3207
3208 ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
3209 "block %llu, max_blocks %u\n", inode->i_ino,
e35fd660 3210 (unsigned long long)map->m_lblk, map->m_len);
21ca087a
DM
3211
3212 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3213 inode->i_sb->s_blocksize_bits;
e35fd660
TT
3214 if (eof_block < map->m_lblk + map->m_len)
3215 eof_block = map->m_lblk + map->m_len;
21ca087a
DM
3216 /*
3217 * It is safe to convert extent to initialized via explicit
3218 * zeroout only if extent is fully insde i_size or new_size.
3219 */
667eff35
YY
3220 depth = ext_depth(inode);
3221 ex = path[depth].p_ext;
3222 ee_block = le32_to_cpu(ex->ee_block);
3223 ee_len = ext4_ext_get_actual_len(ex);
0031462b 3224
667eff35
YY
3225 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3226 split_flag |= EXT4_EXT_MARK_UNINIT2;
0031462b 3227
667eff35
YY
3228 flags |= EXT4_GET_BLOCKS_PRE_IO;
3229 return ext4_split_extent(handle, inode, path, map, split_flag, flags);
0031462b 3230}
197217a5 3231
c7064ef1 3232static int ext4_convert_unwritten_extents_endio(handle_t *handle,
0031462b
MC
3233 struct inode *inode,
3234 struct ext4_ext_path *path)
3235{
3236 struct ext4_extent *ex;
0031462b
MC
3237 int depth;
3238 int err = 0;
0031462b
MC
3239
3240 depth = ext_depth(inode);
0031462b
MC
3241 ex = path[depth].p_ext;
3242
197217a5
YY
3243 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3244 "block %llu, max_blocks %u\n", inode->i_ino,
3245 (unsigned long long)le32_to_cpu(ex->ee_block),
3246 ext4_ext_get_actual_len(ex));
3247
0031462b
MC
3248 err = ext4_ext_get_access(handle, inode, path + depth);
3249 if (err)
3250 goto out;
3251 /* first mark the extent as initialized */
3252 ext4_ext_mark_initialized(ex);
3253
197217a5
YY
3254 /* note: ext4_ext_correct_indexes() isn't needed here because
3255 * borders are not changed
0031462b 3256 */
197217a5
YY
3257 ext4_ext_try_to_merge(inode, path, ex);
3258
0031462b
MC
3259 /* Mark modified extent as dirty */
3260 err = ext4_ext_dirty(handle, inode, path + depth);
3261out:
3262 ext4_ext_show_leaf(inode, path);
3263 return err;
3264}
3265
515f41c3
AK
3266static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3267 sector_t block, int count)
3268{
3269 int i;
3270 for (i = 0; i < count; i++)
3271 unmap_underlying_metadata(bdev, block + i);
3272}
3273
58590b06
TT
3274/*
3275 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3276 */
3277static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
d002ebf1 3278 ext4_lblk_t lblk,
58590b06
TT
3279 struct ext4_ext_path *path,
3280 unsigned int len)
3281{
3282 int i, depth;
3283 struct ext4_extent_header *eh;
65922cb5 3284 struct ext4_extent *last_ex;
58590b06
TT
3285
3286 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3287 return 0;
3288
3289 depth = ext_depth(inode);
3290 eh = path[depth].p_hdr;
58590b06 3291
afcff5d8
LC
3292 /*
3293 * We're going to remove EOFBLOCKS_FL entirely in future so we
3294 * do not care for this case anymore. Simply remove the flag
3295 * if there are no extents.
3296 */
3297 if (unlikely(!eh->eh_entries))
3298 goto out;
58590b06
TT
3299 last_ex = EXT_LAST_EXTENT(eh);
3300 /*
3301 * We should clear the EOFBLOCKS_FL flag if we are writing the
3302 * last block in the last extent in the file. We test this by
3303 * first checking to see if the caller to
3304 * ext4_ext_get_blocks() was interested in the last block (or
3305 * a block beyond the last block) in the current extent. If
3306 * this turns out to be false, we can bail out from this
3307 * function immediately.
3308 */
d002ebf1 3309 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
58590b06
TT
3310 ext4_ext_get_actual_len(last_ex))
3311 return 0;
3312 /*
3313 * If the caller does appear to be planning to write at or
3314 * beyond the end of the current extent, we then test to see
3315 * if the current extent is the last extent in the file, by
3316 * checking to make sure it was reached via the rightmost node
3317 * at each level of the tree.
3318 */
3319 for (i = depth-1; i >= 0; i--)
3320 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3321 return 0;
afcff5d8 3322out:
58590b06
TT
3323 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3324 return ext4_mark_inode_dirty(handle, inode);
3325}
3326
7b415bf6
AK
3327/**
3328 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3329 *
3330 * Goes through the buffer heads in the range [lblk_start, lblk_end] and returns
3331 * whether there are any buffers marked for delayed allocation. It returns '1'
3332 * on the first delalloc'ed buffer head found. If no buffer head in the given
3333 * range is marked for delalloc, it returns 0.
3334 * lblk_start should always be <= lblk_end.
3335 * search_hint_reverse is to indicate that searching in reverse from lblk_end to
3336 * lblk_start might be more efficient (i.e., we will likely hit the delalloc'ed
3337 * block sooner). This is useful when blocks are truncated sequentially from
3338 * lblk_start towards lblk_end.
3339 */
3340static int ext4_find_delalloc_range(struct inode *inode,
3341 ext4_lblk_t lblk_start,
3342 ext4_lblk_t lblk_end,
3343 int search_hint_reverse)
3344{
3345 struct address_space *mapping = inode->i_mapping;
3346 struct buffer_head *head, *bh = NULL;
3347 struct page *page;
3348 ext4_lblk_t i, pg_lblk;
3349 pgoff_t index;
3350
8c48f7e8
RD
3351 if (!test_opt(inode->i_sb, DELALLOC))
3352 return 0;
3353
7b415bf6
AK
3354 /* reverse search wont work if fs block size is less than page size */
3355 if (inode->i_blkbits < PAGE_CACHE_SHIFT)
3356 search_hint_reverse = 0;
3357
3358 if (search_hint_reverse)
3359 i = lblk_end;
3360 else
3361 i = lblk_start;
3362
3363 index = i >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
3364
3365 while ((i >= lblk_start) && (i <= lblk_end)) {
3366 page = find_get_page(mapping, index);
5356f261 3367 if (!page)
7b415bf6
AK
3368 goto nextpage;
3369
7b415bf6
AK
3370 if (!page_has_buffers(page))
3371 goto nextpage;
3372
3373 head = page_buffers(page);
3374 if (!head)
3375 goto nextpage;
3376
3377 bh = head;
3378 pg_lblk = index << (PAGE_CACHE_SHIFT -
3379 inode->i_blkbits);
3380 do {
3381 if (unlikely(pg_lblk < lblk_start)) {
3382 /*
3383 * This is possible when fs block size is less
3384 * than page size and our cluster starts/ends in
3385 * middle of the page. So we need to skip the
3386 * initial few blocks till we reach the 'lblk'
3387 */
3388 pg_lblk++;
3389 continue;
3390 }
3391
5356f261
AK
3392 /* Check if the buffer is delayed allocated and that it
3393 * is not yet mapped. (when da-buffers are mapped during
3394 * their writeout, their da_mapped bit is set.)
3395 */
3396 if (buffer_delay(bh) && !buffer_da_mapped(bh)) {
7b415bf6 3397 page_cache_release(page);
d8990240
AK
3398 trace_ext4_find_delalloc_range(inode,
3399 lblk_start, lblk_end,
3400 search_hint_reverse,
3401 1, i);
7b415bf6
AK
3402 return 1;
3403 }
3404 if (search_hint_reverse)
3405 i--;
3406 else
3407 i++;
3408 } while ((i >= lblk_start) && (i <= lblk_end) &&
3409 ((bh = bh->b_this_page) != head));
3410nextpage:
3411 if (page)
3412 page_cache_release(page);
3413 /*
3414 * Move to next page. 'i' will be the first lblk in the next
3415 * page.
3416 */
3417 if (search_hint_reverse)
3418 index--;
3419 else
3420 index++;
3421 i = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
3422 }
3423
d8990240
AK
3424 trace_ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3425 search_hint_reverse, 0, 0);
7b415bf6
AK
3426 return 0;
3427}
3428
3429int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk,
3430 int search_hint_reverse)
3431{
3432 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3433 ext4_lblk_t lblk_start, lblk_end;
3434 lblk_start = lblk & (~(sbi->s_cluster_ratio - 1));
3435 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3436
3437 return ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3438 search_hint_reverse);
3439}
3440
3441/**
3442 * Determines how many complete clusters (out of those specified by the 'map')
3443 * are under delalloc and were reserved quota for.
3444 * This function is called when we are writing out the blocks that were
3445 * originally written with their allocation delayed, but then the space was
3446 * allocated using fallocate() before the delayed allocation could be resolved.
3447 * The cases to look for are:
3448 * ('=' indicated delayed allocated blocks
3449 * '-' indicates non-delayed allocated blocks)
3450 * (a) partial clusters towards beginning and/or end outside of allocated range
3451 * are not delalloc'ed.
3452 * Ex:
3453 * |----c---=|====c====|====c====|===-c----|
3454 * |++++++ allocated ++++++|
3455 * ==> 4 complete clusters in above example
3456 *
3457 * (b) partial cluster (outside of allocated range) towards either end is
3458 * marked for delayed allocation. In this case, we will exclude that
3459 * cluster.
3460 * Ex:
3461 * |----====c========|========c========|
3462 * |++++++ allocated ++++++|
3463 * ==> 1 complete clusters in above example
3464 *
3465 * Ex:
3466 * |================c================|
3467 * |++++++ allocated ++++++|
3468 * ==> 0 complete clusters in above example
3469 *
3470 * The ext4_da_update_reserve_space will be called only if we
3471 * determine here that there were some "entire" clusters that span
3472 * this 'allocated' range.
3473 * In the non-bigalloc case, this function will just end up returning num_blks
3474 * without ever calling ext4_find_delalloc_range.
3475 */
3476static unsigned int
3477get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3478 unsigned int num_blks)
3479{
3480 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3481 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3482 ext4_lblk_t lblk_from, lblk_to, c_offset;
3483 unsigned int allocated_clusters = 0;
3484
3485 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3486 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3487
3488 /* max possible clusters for this allocation */
3489 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3490
d8990240
AK
3491 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3492
7b415bf6
AK
3493 /* Check towards left side */
3494 c_offset = lblk_start & (sbi->s_cluster_ratio - 1);
3495 if (c_offset) {
3496 lblk_from = lblk_start & (~(sbi->s_cluster_ratio - 1));
3497 lblk_to = lblk_from + c_offset - 1;
3498
3499 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3500 allocated_clusters--;
3501 }
3502
3503 /* Now check towards right. */
3504 c_offset = (lblk_start + num_blks) & (sbi->s_cluster_ratio - 1);
3505 if (allocated_clusters && c_offset) {
3506 lblk_from = lblk_start + num_blks;
3507 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3508
3509 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3510 allocated_clusters--;
3511 }
3512
3513 return allocated_clusters;
3514}
3515
0031462b
MC
3516static int
3517ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
e35fd660 3518 struct ext4_map_blocks *map,
0031462b 3519 struct ext4_ext_path *path, int flags,
e35fd660 3520 unsigned int allocated, ext4_fsblk_t newblock)
0031462b
MC
3521{
3522 int ret = 0;
3523 int err = 0;
8d5d02e6 3524 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
0031462b 3525
88635ca2
ZL
3526 ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical "
3527 "block %llu, max_blocks %u, flags %x, allocated %u\n",
e35fd660 3528 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
0031462b
MC
3529 flags, allocated);
3530 ext4_ext_show_leaf(inode, path);
3531
d8990240
AK
3532 trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
3533 newblock);
3534
c7064ef1 3535 /* get_block() before submit the IO, split the extent */
744692dc 3536 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
e35fd660
TT
3537 ret = ext4_split_unwritten_extents(handle, inode, map,
3538 path, flags);
5f524950
M
3539 /*
3540 * Flag the inode(non aio case) or end_io struct (aio case)
25985edc 3541 * that this IO needs to conversion to written when IO is
5f524950
M
3542 * completed
3543 */
0edeb71d
TM
3544 if (io)
3545 ext4_set_io_unwritten_flag(inode, io);
3546 else
19f5fb7a 3547 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
744692dc 3548 if (ext4_should_dioread_nolock(inode))
e35fd660 3549 map->m_flags |= EXT4_MAP_UNINIT;
0031462b
MC
3550 goto out;
3551 }
c7064ef1 3552 /* IO end_io complete, convert the filled extent to written */
744692dc 3553 if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
c7064ef1 3554 ret = ext4_convert_unwritten_extents_endio(handle, inode,
0031462b 3555 path);
58590b06 3556 if (ret >= 0) {
b436b9be 3557 ext4_update_inode_fsync_trans(handle, inode, 1);
d002ebf1
ES
3558 err = check_eofblocks_fl(handle, inode, map->m_lblk,
3559 path, map->m_len);
58590b06
TT
3560 } else
3561 err = ret;
0031462b
MC
3562 goto out2;
3563 }
3564 /* buffered IO case */
3565 /*
3566 * repeat fallocate creation request
3567 * we already have an unwritten extent
3568 */
3569 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3570 goto map_out;
3571
3572 /* buffered READ or buffered write_begin() lookup */
3573 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3574 /*
3575 * We have blocks reserved already. We
3576 * return allocated blocks so that delalloc
3577 * won't do block reservation for us. But
3578 * the buffer head will be unmapped so that
3579 * a read from the block returns 0s.
3580 */
e35fd660 3581 map->m_flags |= EXT4_MAP_UNWRITTEN;
0031462b
MC
3582 goto out1;
3583 }
3584
3585 /* buffered write, writepage time, convert*/
e35fd660 3586 ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
a4e5d88b 3587 if (ret >= 0)
b436b9be 3588 ext4_update_inode_fsync_trans(handle, inode, 1);
0031462b
MC
3589out:
3590 if (ret <= 0) {
3591 err = ret;
3592 goto out2;
3593 } else
3594 allocated = ret;
e35fd660 3595 map->m_flags |= EXT4_MAP_NEW;
515f41c3
AK
3596 /*
3597 * if we allocated more blocks than requested
3598 * we need to make sure we unmap the extra block
3599 * allocated. The actual needed block will get
3600 * unmapped later when we find the buffer_head marked
3601 * new.
3602 */
e35fd660 3603 if (allocated > map->m_len) {
515f41c3 3604 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
e35fd660
TT
3605 newblock + map->m_len,
3606 allocated - map->m_len);
3607 allocated = map->m_len;
515f41c3 3608 }
5f634d06
AK
3609
3610 /*
3611 * If we have done fallocate with the offset that is already
3612 * delayed allocated, we would have block reservation
3613 * and quota reservation done in the delayed write path.
3614 * But fallocate would have already updated quota and block
3615 * count for this offset. So cancel these reservation
3616 */
7b415bf6
AK
3617 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
3618 unsigned int reserved_clusters;
3619 reserved_clusters = get_reserved_cluster_alloc(inode,
3620 map->m_lblk, map->m_len);
3621 if (reserved_clusters)
3622 ext4_da_update_reserve_space(inode,
3623 reserved_clusters,
3624 0);
3625 }
5f634d06 3626
0031462b 3627map_out:
e35fd660 3628 map->m_flags |= EXT4_MAP_MAPPED;
a4e5d88b
DM
3629 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
3630 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
3631 map->m_len);
3632 if (err < 0)
3633 goto out2;
3634 }
0031462b 3635out1:
e35fd660
TT
3636 if (allocated > map->m_len)
3637 allocated = map->m_len;
0031462b 3638 ext4_ext_show_leaf(inode, path);
e35fd660
TT
3639 map->m_pblk = newblock;
3640 map->m_len = allocated;
0031462b
MC
3641out2:
3642 if (path) {
3643 ext4_ext_drop_refs(path);
3644 kfree(path);
3645 }
3646 return err ? err : allocated;
3647}
58590b06 3648
4d33b1ef
TT
3649/*
3650 * get_implied_cluster_alloc - check to see if the requested
3651 * allocation (in the map structure) overlaps with a cluster already
3652 * allocated in an extent.
d8990240 3653 * @sb The filesystem superblock structure
4d33b1ef
TT
3654 * @map The requested lblk->pblk mapping
3655 * @ex The extent structure which might contain an implied
3656 * cluster allocation
3657 *
3658 * This function is called by ext4_ext_map_blocks() after we failed to
3659 * find blocks that were already in the inode's extent tree. Hence,
3660 * we know that the beginning of the requested region cannot overlap
3661 * the extent from the inode's extent tree. There are three cases we
3662 * want to catch. The first is this case:
3663 *
3664 * |--- cluster # N--|
3665 * |--- extent ---| |---- requested region ---|
3666 * |==========|
3667 *
3668 * The second case that we need to test for is this one:
3669 *
3670 * |--------- cluster # N ----------------|
3671 * |--- requested region --| |------- extent ----|
3672 * |=======================|
3673 *
3674 * The third case is when the requested region lies between two extents
3675 * within the same cluster:
3676 * |------------- cluster # N-------------|
3677 * |----- ex -----| |---- ex_right ----|
3678 * |------ requested region ------|
3679 * |================|
3680 *
3681 * In each of the above cases, we need to set the map->m_pblk and
3682 * map->m_len so it corresponds to the return the extent labelled as
3683 * "|====|" from cluster #N, since it is already in use for data in
3684 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
3685 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3686 * as a new "allocated" block region. Otherwise, we will return 0 and
3687 * ext4_ext_map_blocks() will then allocate one or more new clusters
3688 * by calling ext4_mb_new_blocks().
3689 */
d8990240 3690static int get_implied_cluster_alloc(struct super_block *sb,
4d33b1ef
TT
3691 struct ext4_map_blocks *map,
3692 struct ext4_extent *ex,
3693 struct ext4_ext_path *path)
3694{
d8990240 3695 struct ext4_sb_info *sbi = EXT4_SB(sb);
4d33b1ef
TT
3696 ext4_lblk_t c_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3697 ext4_lblk_t ex_cluster_start, ex_cluster_end;
14d7f3ef 3698 ext4_lblk_t rr_cluster_start;
4d33b1ef
TT
3699 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3700 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3701 unsigned short ee_len = ext4_ext_get_actual_len(ex);
3702
3703 /* The extent passed in that we are trying to match */
3704 ex_cluster_start = EXT4_B2C(sbi, ee_block);
3705 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
3706
3707 /* The requested region passed into ext4_map_blocks() */
3708 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4d33b1ef
TT
3709
3710 if ((rr_cluster_start == ex_cluster_end) ||
3711 (rr_cluster_start == ex_cluster_start)) {
3712 if (rr_cluster_start == ex_cluster_end)
3713 ee_start += ee_len - 1;
3714 map->m_pblk = (ee_start & ~(sbi->s_cluster_ratio - 1)) +
3715 c_offset;
3716 map->m_len = min(map->m_len,
3717 (unsigned) sbi->s_cluster_ratio - c_offset);
3718 /*
3719 * Check for and handle this case:
3720 *
3721 * |--------- cluster # N-------------|
3722 * |------- extent ----|
3723 * |--- requested region ---|
3724 * |===========|
3725 */
3726
3727 if (map->m_lblk < ee_block)
3728 map->m_len = min(map->m_len, ee_block - map->m_lblk);
3729
3730 /*
3731 * Check for the case where there is already another allocated
3732 * block to the right of 'ex' but before the end of the cluster.
3733 *
3734 * |------------- cluster # N-------------|
3735 * |----- ex -----| |---- ex_right ----|
3736 * |------ requested region ------|
3737 * |================|
3738 */
3739 if (map->m_lblk > ee_block) {
3740 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
3741 map->m_len = min(map->m_len, next - map->m_lblk);
3742 }
d8990240
AK
3743
3744 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4d33b1ef
TT
3745 return 1;
3746 }
d8990240
AK
3747
3748 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4d33b1ef
TT
3749 return 0;
3750}
3751
3752
c278bfec 3753/*
f5ab0d1f
MC
3754 * Block allocation/map/preallocation routine for extents based files
3755 *
3756 *
c278bfec 3757 * Need to be called with
0e855ac8
AK
3758 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3759 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
f5ab0d1f
MC
3760 *
3761 * return > 0, number of of blocks already mapped/allocated
3762 * if create == 0 and these are pre-allocated blocks
3763 * buffer head is unmapped
3764 * otherwise blocks are mapped
3765 *
3766 * return = 0, if plain look up failed (blocks have not been allocated)
3767 * buffer head is unmapped
3768 *
3769 * return < 0, error case.
c278bfec 3770 */
e35fd660
TT
3771int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
3772 struct ext4_map_blocks *map, int flags)
a86c6181
AT
3773{
3774 struct ext4_ext_path *path = NULL;
4d33b1ef
TT
3775 struct ext4_extent newex, *ex, *ex2;
3776 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0562e0ba 3777 ext4_fsblk_t newblock = 0;
4d33b1ef
TT
3778 int free_on_err = 0, err = 0, depth, ret;
3779 unsigned int allocated = 0, offset = 0;
81fdbb4a 3780 unsigned int allocated_clusters = 0;
c9de560d 3781 struct ext4_allocation_request ar;
8d5d02e6 3782 ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
4d33b1ef 3783 ext4_lblk_t cluster_offset;
a86c6181 3784
84fe3bef 3785 ext_debug("blocks %u/%u requested for inode %lu\n",
e35fd660 3786 map->m_lblk, map->m_len, inode->i_ino);
0562e0ba 3787 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
a86c6181
AT
3788
3789 /* check in cache */
7877191c 3790 if (ext4_ext_in_cache(inode, map->m_lblk, &newex)) {
b05e6ae5 3791 if (!newex.ee_start_lo && !newex.ee_start_hi) {
7b415bf6
AK
3792 if ((sbi->s_cluster_ratio > 1) &&
3793 ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3794 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3795
c2177057 3796 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
56055d3a
AA
3797 /*
3798 * block isn't allocated yet and
3799 * user doesn't want to allocate it
3800 */
a86c6181
AT
3801 goto out2;
3802 }
3803 /* we should allocate requested block */
b05e6ae5 3804 } else {
a86c6181 3805 /* block is already allocated */
7b415bf6
AK
3806 if (sbi->s_cluster_ratio > 1)
3807 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
e35fd660 3808 newblock = map->m_lblk
8c55e204 3809 - le32_to_cpu(newex.ee_block)
bf89d16f 3810 + ext4_ext_pblock(&newex);
d0d856e8 3811 /* number of remaining blocks in the extent */
b939e376 3812 allocated = ext4_ext_get_actual_len(&newex) -
e35fd660 3813 (map->m_lblk - le32_to_cpu(newex.ee_block));
a86c6181 3814 goto out;
a86c6181
AT
3815 }
3816 }
3817
3818 /* find extent for this block */
e35fd660 3819 path = ext4_ext_find_extent(inode, map->m_lblk, NULL);
a86c6181
AT
3820 if (IS_ERR(path)) {
3821 err = PTR_ERR(path);
3822 path = NULL;
3823 goto out2;
3824 }
3825
3826 depth = ext_depth(inode);
3827
3828 /*
d0d856e8
RD
3829 * consistent leaf must not be empty;
3830 * this situation is possible, though, _during_ tree modification;
a86c6181
AT
3831 * this is why assert can't be put in ext4_ext_find_extent()
3832 */
273df556
FM
3833 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3834 EXT4_ERROR_INODE(inode, "bad extent address "
f70f362b
TT
3835 "lblock: %lu, depth: %d pblock %lld",
3836 (unsigned long) map->m_lblk, depth,
3837 path[depth].p_block);
034fb4c9
SP
3838 err = -EIO;
3839 goto out2;
3840 }
a86c6181 3841
7e028976
AM
3842 ex = path[depth].p_ext;
3843 if (ex) {
725d26d3 3844 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
bf89d16f 3845 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
a2df2a63 3846 unsigned short ee_len;
471d4011
SB
3847
3848 /*
471d4011 3849 * Uninitialized extents are treated as holes, except that
56055d3a 3850 * we split out initialized portions during a write.
471d4011 3851 */
a2df2a63 3852 ee_len = ext4_ext_get_actual_len(ex);
d8990240
AK
3853
3854 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
3855
d0d856e8 3856 /* if found extent covers block, simply return it */
e35fd660
TT
3857 if (in_range(map->m_lblk, ee_block, ee_len)) {
3858 newblock = map->m_lblk - ee_block + ee_start;
d0d856e8 3859 /* number of remaining blocks in the extent */
e35fd660
TT
3860 allocated = ee_len - (map->m_lblk - ee_block);
3861 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
3862 ee_block, ee_len, newblock);
56055d3a 3863
e861304b 3864 /*
7877191c
LC
3865 * Do not put uninitialized extent
3866 * in the cache
e861304b 3867 */
7877191c
LC
3868 if (!ext4_ext_is_uninitialized(ex)) {
3869 ext4_ext_put_in_cache(inode, ee_block,
3870 ee_len, ee_start);
3871 goto out;
f7d0d379 3872 }
7877191c
LC
3873 ret = ext4_ext_handle_uninitialized_extents(
3874 handle, inode, map, path, flags,
3875 allocated, newblock);
3876 return ret;
a86c6181
AT
3877 }
3878 }
3879
7b415bf6
AK
3880 if ((sbi->s_cluster_ratio > 1) &&
3881 ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3882 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3883
a86c6181 3884 /*
d0d856e8 3885 * requested block isn't allocated yet;
a86c6181
AT
3886 * we couldn't try to create block if create flag is zero
3887 */
c2177057 3888 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
56055d3a
AA
3889 /*
3890 * put just found gap into cache to speed up
3891 * subsequent requests
3892 */
e35fd660 3893 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
a86c6181
AT
3894 goto out2;
3895 }
4d33b1ef 3896
a86c6181 3897 /*
c2ea3fde 3898 * Okay, we need to do block allocation.
63f57933 3899 */
7b415bf6 3900 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
4d33b1ef
TT
3901 newex.ee_block = cpu_to_le32(map->m_lblk);
3902 cluster_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3903
3904 /*
3905 * If we are doing bigalloc, check to see if the extent returned
3906 * by ext4_ext_find_extent() implies a cluster we can use.
3907 */
3908 if (cluster_offset && ex &&
d8990240 3909 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4d33b1ef
TT
3910 ar.len = allocated = map->m_len;
3911 newblock = map->m_pblk;
7b415bf6 3912 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
4d33b1ef
TT
3913 goto got_allocated_blocks;
3914 }
a86c6181 3915
c9de560d 3916 /* find neighbour allocated blocks */
e35fd660 3917 ar.lleft = map->m_lblk;
c9de560d
AT
3918 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3919 if (err)
3920 goto out2;
e35fd660 3921 ar.lright = map->m_lblk;
4d33b1ef
TT
3922 ex2 = NULL;
3923 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
c9de560d
AT
3924 if (err)
3925 goto out2;
25d14f98 3926
4d33b1ef
TT
3927 /* Check if the extent after searching to the right implies a
3928 * cluster we can use. */
3929 if ((sbi->s_cluster_ratio > 1) && ex2 &&
d8990240 3930 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4d33b1ef
TT
3931 ar.len = allocated = map->m_len;
3932 newblock = map->m_pblk;
7b415bf6 3933 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
4d33b1ef
TT
3934 goto got_allocated_blocks;
3935 }
3936
749269fa
AA
3937 /*
3938 * See if request is beyond maximum number of blocks we can have in
3939 * a single extent. For an initialized extent this limit is
3940 * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3941 * EXT_UNINIT_MAX_LEN.
3942 */
e35fd660 3943 if (map->m_len > EXT_INIT_MAX_LEN &&
c2177057 3944 !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
e35fd660
TT
3945 map->m_len = EXT_INIT_MAX_LEN;
3946 else if (map->m_len > EXT_UNINIT_MAX_LEN &&
c2177057 3947 (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
e35fd660 3948 map->m_len = EXT_UNINIT_MAX_LEN;
749269fa 3949
e35fd660 3950 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
e35fd660 3951 newex.ee_len = cpu_to_le16(map->m_len);
4d33b1ef 3952 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
25d14f98 3953 if (err)
b939e376 3954 allocated = ext4_ext_get_actual_len(&newex);
25d14f98 3955 else
e35fd660 3956 allocated = map->m_len;
c9de560d
AT
3957
3958 /* allocate new block */
3959 ar.inode = inode;
e35fd660
TT
3960 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
3961 ar.logical = map->m_lblk;
4d33b1ef
TT
3962 /*
3963 * We calculate the offset from the beginning of the cluster
3964 * for the logical block number, since when we allocate a
3965 * physical cluster, the physical block should start at the
3966 * same offset from the beginning of the cluster. This is
3967 * needed so that future calls to get_implied_cluster_alloc()
3968 * work correctly.
3969 */
3970 offset = map->m_lblk & (sbi->s_cluster_ratio - 1);
3971 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
3972 ar.goal -= offset;
3973 ar.logical -= offset;
c9de560d
AT
3974 if (S_ISREG(inode->i_mode))
3975 ar.flags = EXT4_MB_HINT_DATA;
3976 else
3977 /* disable in-core preallocation for non-regular files */
3978 ar.flags = 0;
556b27ab
VH
3979 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
3980 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
c9de560d 3981 newblock = ext4_mb_new_blocks(handle, &ar, &err);
a86c6181
AT
3982 if (!newblock)
3983 goto out2;
84fe3bef 3984 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
498e5f24 3985 ar.goal, newblock, allocated);
4d33b1ef 3986 free_on_err = 1;
7b415bf6 3987 allocated_clusters = ar.len;
4d33b1ef
TT
3988 ar.len = EXT4_C2B(sbi, ar.len) - offset;
3989 if (ar.len > allocated)
3990 ar.len = allocated;
a86c6181 3991
4d33b1ef 3992got_allocated_blocks:
a86c6181 3993 /* try to insert new extent into found leaf and return */
4d33b1ef 3994 ext4_ext_store_pblock(&newex, newblock + offset);
c9de560d 3995 newex.ee_len = cpu_to_le16(ar.len);
8d5d02e6
MC
3996 /* Mark uninitialized */
3997 if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
a2df2a63 3998 ext4_ext_mark_uninitialized(&newex);
8d5d02e6 3999 /*
744692dc 4000 * io_end structure was created for every IO write to an
25985edc 4001 * uninitialized extent. To avoid unnecessary conversion,
744692dc 4002 * here we flag the IO that really needs the conversion.
5f524950 4003 * For non asycn direct IO case, flag the inode state
25985edc 4004 * that we need to perform conversion when IO is done.
8d5d02e6 4005 */
744692dc 4006 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
0edeb71d
TM
4007 if (io)
4008 ext4_set_io_unwritten_flag(inode, io);
4009 else
19f5fb7a
TT
4010 ext4_set_inode_state(inode,
4011 EXT4_STATE_DIO_UNWRITTEN);
5f524950 4012 }
744692dc 4013 if (ext4_should_dioread_nolock(inode))
e35fd660 4014 map->m_flags |= EXT4_MAP_UNINIT;
8d5d02e6 4015 }
c8d46e41 4016
a4e5d88b
DM
4017 err = 0;
4018 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4019 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4020 path, ar.len);
575a1d4b
JZ
4021 if (!err)
4022 err = ext4_ext_insert_extent(handle, inode, path,
4023 &newex, flags);
4d33b1ef 4024 if (err && free_on_err) {
7132de74
MP
4025 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4026 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
315054f0 4027 /* free data blocks we just allocated */
c9de560d
AT
4028 /* not a good idea to call discard here directly,
4029 * but otherwise we'd need to call it every free() */
c2ea3fde 4030 ext4_discard_preallocations(inode);
7dc57615 4031 ext4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),
7132de74 4032 ext4_ext_get_actual_len(&newex), fb_flags);
a86c6181 4033 goto out2;
315054f0 4034 }
a86c6181 4035
a86c6181 4036 /* previous routine could use block we allocated */
bf89d16f 4037 newblock = ext4_ext_pblock(&newex);
b939e376 4038 allocated = ext4_ext_get_actual_len(&newex);
e35fd660
TT
4039 if (allocated > map->m_len)
4040 allocated = map->m_len;
4041 map->m_flags |= EXT4_MAP_NEW;
a86c6181 4042
5f634d06
AK
4043 /*
4044 * Update reserved blocks/metadata blocks after successful
4045 * block allocation which had been deferred till now.
4046 */
7b415bf6 4047 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
81fdbb4a 4048 unsigned int reserved_clusters;
7b415bf6 4049 /*
81fdbb4a 4050 * Check how many clusters we had reserved this allocated range
7b415bf6
AK
4051 */
4052 reserved_clusters = get_reserved_cluster_alloc(inode,
4053 map->m_lblk, allocated);
4054 if (map->m_flags & EXT4_MAP_FROM_CLUSTER) {
4055 if (reserved_clusters) {
4056 /*
4057 * We have clusters reserved for this range.
4058 * But since we are not doing actual allocation
4059 * and are simply using blocks from previously
4060 * allocated cluster, we should release the
4061 * reservation and not claim quota.
4062 */
4063 ext4_da_update_reserve_space(inode,
4064 reserved_clusters, 0);
4065 }
4066 } else {
4067 BUG_ON(allocated_clusters < reserved_clusters);
4068 /* We will claim quota for all newly allocated blocks.*/
4069 ext4_da_update_reserve_space(inode, allocated_clusters,
4070 1);
4071 if (reserved_clusters < allocated_clusters) {
5356f261 4072 struct ext4_inode_info *ei = EXT4_I(inode);
7b415bf6
AK
4073 int reservation = allocated_clusters -
4074 reserved_clusters;
4075 /*
4076 * It seems we claimed few clusters outside of
4077 * the range of this allocation. We should give
4078 * it back to the reservation pool. This can
4079 * happen in the following case:
4080 *
4081 * * Suppose s_cluster_ratio is 4 (i.e., each
4082 * cluster has 4 blocks. Thus, the clusters
4083 * are [0-3],[4-7],[8-11]...
4084 * * First comes delayed allocation write for
4085 * logical blocks 10 & 11. Since there were no
4086 * previous delayed allocated blocks in the
4087 * range [8-11], we would reserve 1 cluster
4088 * for this write.
4089 * * Next comes write for logical blocks 3 to 8.
4090 * In this case, we will reserve 2 clusters
4091 * (for [0-3] and [4-7]; and not for [8-11] as
4092 * that range has a delayed allocated blocks.
4093 * Thus total reserved clusters now becomes 3.
4094 * * Now, during the delayed allocation writeout
4095 * time, we will first write blocks [3-8] and
4096 * allocate 3 clusters for writing these
4097 * blocks. Also, we would claim all these
4098 * three clusters above.
4099 * * Now when we come here to writeout the
4100 * blocks [10-11], we would expect to claim
4101 * the reservation of 1 cluster we had made
4102 * (and we would claim it since there are no
4103 * more delayed allocated blocks in the range
4104 * [8-11]. But our reserved cluster count had
4105 * already gone to 0.
4106 *
4107 * Thus, at the step 4 above when we determine
4108 * that there are still some unwritten delayed
4109 * allocated blocks outside of our current
4110 * block range, we should increment the
4111 * reserved clusters count so that when the
4112 * remaining blocks finally gets written, we
4113 * could claim them.
4114 */
5356f261
AK
4115 dquot_reserve_block(inode,
4116 EXT4_C2B(sbi, reservation));
4117 spin_lock(&ei->i_block_reservation_lock);
4118 ei->i_reserved_data_blocks += reservation;
4119 spin_unlock(&ei->i_block_reservation_lock);
7b415bf6
AK
4120 }
4121 }
4122 }
5f634d06 4123
b436b9be
JK
4124 /*
4125 * Cache the extent and update transaction to commit on fdatasync only
4126 * when it is _not_ an uninitialized extent.
4127 */
4128 if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
b05e6ae5 4129 ext4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);
b436b9be
JK
4130 ext4_update_inode_fsync_trans(handle, inode, 1);
4131 } else
4132 ext4_update_inode_fsync_trans(handle, inode, 0);
a86c6181 4133out:
e35fd660
TT
4134 if (allocated > map->m_len)
4135 allocated = map->m_len;
a86c6181 4136 ext4_ext_show_leaf(inode, path);
e35fd660
TT
4137 map->m_flags |= EXT4_MAP_MAPPED;
4138 map->m_pblk = newblock;
4139 map->m_len = allocated;
a86c6181
AT
4140out2:
4141 if (path) {
4142 ext4_ext_drop_refs(path);
4143 kfree(path);
4144 }
e861304b 4145
e7b319e3 4146 trace_ext4_ext_map_blocks_exit(inode, map->m_lblk,
7877191c 4147 newblock, map->m_len, err ? err : allocated);
e7b319e3 4148
7877191c 4149 return err ? err : allocated;
a86c6181
AT
4150}
4151
cf108bca 4152void ext4_ext_truncate(struct inode *inode)
a86c6181
AT
4153{
4154 struct address_space *mapping = inode->i_mapping;
4155 struct super_block *sb = inode->i_sb;
725d26d3 4156 ext4_lblk_t last_block;
a86c6181 4157 handle_t *handle;
189e868f 4158 loff_t page_len;
a86c6181
AT
4159 int err = 0;
4160
3889fd57
JZ
4161 /*
4162 * finish any pending end_io work so we won't run the risk of
4163 * converting any truncated blocks to initialized later
4164 */
4165 ext4_flush_completed_IO(inode);
4166
a86c6181
AT
4167 /*
4168 * probably first extent we're gonna free will be last in block
4169 */
f3bd1f3f 4170 err = ext4_writepage_trans_blocks(inode);
a86c6181 4171 handle = ext4_journal_start(inode, err);
cf108bca 4172 if (IS_ERR(handle))
a86c6181 4173 return;
a86c6181 4174
189e868f
AH
4175 if (inode->i_size % PAGE_CACHE_SIZE != 0) {
4176 page_len = PAGE_CACHE_SIZE -
4177 (inode->i_size & (PAGE_CACHE_SIZE - 1));
4178
4179 err = ext4_discard_partial_page_buffers(handle,
4180 mapping, inode->i_size, page_len, 0);
4181
4182 if (err)
4183 goto out_stop;
4184 }
a86c6181 4185
9ddfc3dc
JK
4186 if (ext4_orphan_add(handle, inode))
4187 goto out_stop;
4188
0e855ac8 4189 down_write(&EXT4_I(inode)->i_data_sem);
a86c6181
AT
4190 ext4_ext_invalidate_cache(inode);
4191
c2ea3fde 4192 ext4_discard_preallocations(inode);
c9de560d 4193
a86c6181 4194 /*
d0d856e8
RD
4195 * TODO: optimization is possible here.
4196 * Probably we need not scan at all,
4197 * because page truncation is enough.
a86c6181 4198 */
a86c6181
AT
4199
4200 /* we have to know where to truncate from in crash case */
4201 EXT4_I(inode)->i_disksize = inode->i_size;
4202 ext4_mark_inode_dirty(handle, inode);
4203
4204 last_block = (inode->i_size + sb->s_blocksize - 1)
4205 >> EXT4_BLOCK_SIZE_BITS(sb);
5f95d21f 4206 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
a86c6181
AT
4207
4208 /* In a multi-transaction truncate, we only make the final
56055d3a
AA
4209 * transaction synchronous.
4210 */
a86c6181 4211 if (IS_SYNC(inode))
0390131b 4212 ext4_handle_sync(handle);
a86c6181 4213
9ddfc3dc 4214 up_write(&EXT4_I(inode)->i_data_sem);
f6d2f6b3
EG
4215
4216out_stop:
a86c6181 4217 /*
d0d856e8 4218 * If this was a simple ftruncate() and the file will remain alive,
a86c6181
AT
4219 * then we need to clear up the orphan record which we created above.
4220 * However, if this was a real unlink then we were called by
4221 * ext4_delete_inode(), and we allow that function to clean up the
4222 * orphan info for us.
4223 */
4224 if (inode->i_nlink)
4225 ext4_orphan_del(handle, inode);
4226
ef737728
SR
4227 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4228 ext4_mark_inode_dirty(handle, inode);
a86c6181
AT
4229 ext4_journal_stop(handle);
4230}
4231
fd28784a
AK
4232static void ext4_falloc_update_inode(struct inode *inode,
4233 int mode, loff_t new_size, int update_ctime)
4234{
4235 struct timespec now;
4236
4237 if (update_ctime) {
4238 now = current_fs_time(inode->i_sb);
4239 if (!timespec_equal(&inode->i_ctime, &now))
4240 inode->i_ctime = now;
4241 }
4242 /*
4243 * Update only when preallocation was requested beyond
4244 * the file size.
4245 */
cf17fea6
AK
4246 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
4247 if (new_size > i_size_read(inode))
4248 i_size_write(inode, new_size);
4249 if (new_size > EXT4_I(inode)->i_disksize)
4250 ext4_update_i_disksize(inode, new_size);
c8d46e41
JZ
4251 } else {
4252 /*
4253 * Mark that we allocate beyond EOF so the subsequent truncate
4254 * can proceed even if the new size is the same as i_size.
4255 */
4256 if (new_size > i_size_read(inode))
12e9b892 4257 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
fd28784a
AK
4258 }
4259
4260}
4261
a2df2a63 4262/*
2fe17c10 4263 * preallocate space for a file. This implements ext4's fallocate file
a2df2a63
AA
4264 * operation, which gets called from sys_fallocate system call.
4265 * For block-mapped files, posix_fallocate should fall back to the method
4266 * of writing zeroes to the required new blocks (the same behavior which is
4267 * expected for file systems which do not support fallocate() system call).
4268 */
2fe17c10 4269long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
a2df2a63 4270{
2fe17c10 4271 struct inode *inode = file->f_path.dentry->d_inode;
a2df2a63 4272 handle_t *handle;
fd28784a 4273 loff_t new_size;
498e5f24 4274 unsigned int max_blocks;
a2df2a63
AA
4275 int ret = 0;
4276 int ret2 = 0;
4277 int retries = 0;
a4e5d88b 4278 int flags;
2ed88685 4279 struct ext4_map_blocks map;
a2df2a63
AA
4280 unsigned int credits, blkbits = inode->i_blkbits;
4281
4282 /*
4283 * currently supporting (pre)allocate mode for extent-based
4284 * files _only_
4285 */
12e9b892 4286 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
a2df2a63
AA
4287 return -EOPNOTSUPP;
4288
a4bb6b64
AH
4289 /* Return error if mode is not supported */
4290 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
4291 return -EOPNOTSUPP;
4292
4293 if (mode & FALLOC_FL_PUNCH_HOLE)
4294 return ext4_punch_hole(file, offset, len);
4295
0562e0ba 4296 trace_ext4_fallocate_enter(inode, offset, len, mode);
2ed88685 4297 map.m_lblk = offset >> blkbits;
fd28784a
AK
4298 /*
4299 * We can't just convert len to max_blocks because
4300 * If blocksize = 4096 offset = 3072 and len = 2048
4301 */
a2df2a63 4302 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
2ed88685 4303 - map.m_lblk;
a2df2a63 4304 /*
f3bd1f3f 4305 * credits to insert 1 extent into extent tree
a2df2a63 4306 */
f3bd1f3f 4307 credits = ext4_chunk_trans_blocks(inode, max_blocks);
55bd725a 4308 mutex_lock(&inode->i_mutex);
6d19c42b
NK
4309 ret = inode_newsize_ok(inode, (len + offset));
4310 if (ret) {
4311 mutex_unlock(&inode->i_mutex);
0562e0ba 4312 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
6d19c42b
NK
4313 return ret;
4314 }
3c6fe770 4315 flags = EXT4_GET_BLOCKS_CREATE_UNINIT_EXT;
a4e5d88b
DM
4316 if (mode & FALLOC_FL_KEEP_SIZE)
4317 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
3c6fe770
GH
4318 /*
4319 * Don't normalize the request if it can fit in one extent so
4320 * that it doesn't get unnecessarily split into multiple
4321 * extents.
4322 */
4323 if (len <= EXT_UNINIT_MAX_LEN << blkbits)
4324 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
a2df2a63
AA
4325retry:
4326 while (ret >= 0 && ret < max_blocks) {
2ed88685
TT
4327 map.m_lblk = map.m_lblk + ret;
4328 map.m_len = max_blocks = max_blocks - ret;
a2df2a63
AA
4329 handle = ext4_journal_start(inode, credits);
4330 if (IS_ERR(handle)) {
4331 ret = PTR_ERR(handle);
4332 break;
4333 }
a4e5d88b 4334 ret = ext4_map_blocks(handle, inode, &map, flags);
221879c9 4335 if (ret <= 0) {
2c98615d
AK
4336#ifdef EXT4FS_DEBUG
4337 WARN_ON(ret <= 0);
e35fd660 4338 printk(KERN_ERR "%s: ext4_ext_map_blocks "
2c98615d 4339 "returned error inode#%lu, block=%u, "
9fd9784c 4340 "max_blocks=%u", __func__,
a6371b63 4341 inode->i_ino, map.m_lblk, max_blocks);
2c98615d 4342#endif
a2df2a63
AA
4343 ext4_mark_inode_dirty(handle, inode);
4344 ret2 = ext4_journal_stop(handle);
4345 break;
4346 }
2ed88685 4347 if ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
fd28784a
AK
4348 blkbits) >> blkbits))
4349 new_size = offset + len;
4350 else
29ae07b7 4351 new_size = ((loff_t) map.m_lblk + ret) << blkbits;
a2df2a63 4352
fd28784a 4353 ext4_falloc_update_inode(inode, mode, new_size,
2ed88685 4354 (map.m_flags & EXT4_MAP_NEW));
a2df2a63
AA
4355 ext4_mark_inode_dirty(handle, inode);
4356 ret2 = ext4_journal_stop(handle);
4357 if (ret2)
4358 break;
4359 }
fd28784a
AK
4360 if (ret == -ENOSPC &&
4361 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4362 ret = 0;
a2df2a63 4363 goto retry;
a2df2a63 4364 }
55bd725a 4365 mutex_unlock(&inode->i_mutex);
0562e0ba
JZ
4366 trace_ext4_fallocate_exit(inode, offset, max_blocks,
4367 ret > 0 ? ret2 : ret);
a2df2a63
AA
4368 return ret > 0 ? ret2 : ret;
4369}
6873fa0d 4370
0031462b
MC
4371/*
4372 * This function convert a range of blocks to written extents
4373 * The caller of this function will pass the start offset and the size.
4374 * all unwritten extents within this range will be converted to
4375 * written extents.
4376 *
4377 * This function is called from the direct IO end io call back
4378 * function, to convert the fallocated extents after IO is completed.
109f5565 4379 * Returns 0 on success.
0031462b
MC
4380 */
4381int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
a1de02dc 4382 ssize_t len)
0031462b
MC
4383{
4384 handle_t *handle;
0031462b
MC
4385 unsigned int max_blocks;
4386 int ret = 0;
4387 int ret2 = 0;
2ed88685 4388 struct ext4_map_blocks map;
0031462b
MC
4389 unsigned int credits, blkbits = inode->i_blkbits;
4390
2ed88685 4391 map.m_lblk = offset >> blkbits;
0031462b
MC
4392 /*
4393 * We can't just convert len to max_blocks because
4394 * If blocksize = 4096 offset = 3072 and len = 2048
4395 */
2ed88685
TT
4396 max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
4397 map.m_lblk);
0031462b
MC
4398 /*
4399 * credits to insert 1 extent into extent tree
4400 */
4401 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4402 while (ret >= 0 && ret < max_blocks) {
2ed88685
TT
4403 map.m_lblk += ret;
4404 map.m_len = (max_blocks -= ret);
0031462b
MC
4405 handle = ext4_journal_start(inode, credits);
4406 if (IS_ERR(handle)) {
4407 ret = PTR_ERR(handle);
4408 break;
4409 }
2ed88685 4410 ret = ext4_map_blocks(handle, inode, &map,
c7064ef1 4411 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
0031462b
MC
4412 if (ret <= 0) {
4413 WARN_ON(ret <= 0);
92b97816
TT
4414 ext4_msg(inode->i_sb, KERN_ERR,
4415 "%s:%d: inode #%lu: block %u: len %u: "
4416 "ext4_ext_map_blocks returned %d",
4417 __func__, __LINE__, inode->i_ino, map.m_lblk,
4418 map.m_len, ret);
0031462b
MC
4419 }
4420 ext4_mark_inode_dirty(handle, inode);
4421 ret2 = ext4_journal_stop(handle);
4422 if (ret <= 0 || ret2 )
4423 break;
4424 }
4425 return ret > 0 ? ret2 : ret;
4426}
6d9c85eb 4427
6873fa0d
ES
4428/*
4429 * Callback function called for each extent to gather FIEMAP information.
4430 */
c03f8aa9 4431static int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,
6873fa0d
ES
4432 struct ext4_ext_cache *newex, struct ext4_extent *ex,
4433 void *data)
4434{
6873fa0d
ES
4435 __u64 logical;
4436 __u64 physical;
4437 __u64 length;
4438 __u32 flags = 0;
6d9c85eb
YY
4439 int ret = 0;
4440 struct fiemap_extent_info *fieinfo = data;
4441 unsigned char blksize_bits;
6873fa0d 4442
6d9c85eb
YY
4443 blksize_bits = inode->i_sb->s_blocksize_bits;
4444 logical = (__u64)newex->ec_block << blksize_bits;
6873fa0d 4445
b05e6ae5 4446 if (newex->ec_start == 0) {
6d9c85eb
YY
4447 /*
4448 * No extent in extent-tree contains block @newex->ec_start,
4449 * then the block may stay in 1)a hole or 2)delayed-extent.
4450 *
4451 * Holes or delayed-extents are processed as follows.
4452 * 1. lookup dirty pages with specified range in pagecache.
4453 * If no page is got, then there is no delayed-extent and
4454 * return with EXT_CONTINUE.
4455 * 2. find the 1st mapped buffer,
4456 * 3. check if the mapped buffer is both in the request range
4457 * and a delayed buffer. If not, there is no delayed-extent,
4458 * then return.
4459 * 4. a delayed-extent is found, the extent will be collected.
4460 */
4461 ext4_lblk_t end = 0;
4462 pgoff_t last_offset;
4463 pgoff_t offset;
4464 pgoff_t index;
b221349f 4465 pgoff_t start_index = 0;
6d9c85eb 4466 struct page **pages = NULL;
6873fa0d 4467 struct buffer_head *bh = NULL;
6d9c85eb
YY
4468 struct buffer_head *head = NULL;
4469 unsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);
4470
4471 pages = kmalloc(PAGE_SIZE, GFP_KERNEL);
4472 if (pages == NULL)
4473 return -ENOMEM;
6873fa0d
ES
4474
4475 offset = logical >> PAGE_SHIFT;
6d9c85eb
YY
4476repeat:
4477 last_offset = offset;
4478 head = NULL;
4479 ret = find_get_pages_tag(inode->i_mapping, &offset,
4480 PAGECACHE_TAG_DIRTY, nr_pages, pages);
4481
4482 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4483 /* First time, try to find a mapped buffer. */
4484 if (ret == 0) {
4485out:
4486 for (index = 0; index < ret; index++)
4487 page_cache_release(pages[index]);
4488 /* just a hole. */
4489 kfree(pages);
4490 return EXT_CONTINUE;
4491 }
b221349f 4492 index = 0;
6873fa0d 4493
b221349f 4494next_page:
6d9c85eb 4495 /* Try to find the 1st mapped buffer. */
b221349f 4496 end = ((__u64)pages[index]->index << PAGE_SHIFT) >>
6d9c85eb 4497 blksize_bits;
b221349f 4498 if (!page_has_buffers(pages[index]))
6d9c85eb 4499 goto out;
b221349f 4500 head = page_buffers(pages[index]);
6d9c85eb
YY
4501 if (!head)
4502 goto out;
6873fa0d 4503
b221349f 4504 index++;
6d9c85eb
YY
4505 bh = head;
4506 do {
b221349f
YY
4507 if (end >= newex->ec_block +
4508 newex->ec_len)
4509 /* The buffer is out of
4510 * the request range.
4511 */
4512 goto out;
4513
4514 if (buffer_mapped(bh) &&
4515 end >= newex->ec_block) {
4516 start_index = index - 1;
6d9c85eb 4517 /* get the 1st mapped buffer. */
6d9c85eb
YY
4518 goto found_mapped_buffer;
4519 }
b221349f 4520
6d9c85eb
YY
4521 bh = bh->b_this_page;
4522 end++;
4523 } while (bh != head);
6873fa0d 4524
b221349f
YY
4525 /* No mapped buffer in the range found in this page,
4526 * We need to look up next page.
4527 */
4528 if (index >= ret) {
4529 /* There is no page left, but we need to limit
4530 * newex->ec_len.
4531 */
4532 newex->ec_len = end - newex->ec_block;
4533 goto out;
4534 }
4535 goto next_page;
6873fa0d 4536 } else {
6d9c85eb
YY
4537 /*Find contiguous delayed buffers. */
4538 if (ret > 0 && pages[0]->index == last_offset)
4539 head = page_buffers(pages[0]);
4540 bh = head;
b221349f
YY
4541 index = 1;
4542 start_index = 0;
6873fa0d 4543 }
6d9c85eb
YY
4544
4545found_mapped_buffer:
4546 if (bh != NULL && buffer_delay(bh)) {
4547 /* 1st or contiguous delayed buffer found. */
4548 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4549 /*
4550 * 1st delayed buffer found, record
4551 * the start of extent.
4552 */
4553 flags |= FIEMAP_EXTENT_DELALLOC;
4554 newex->ec_block = end;
4555 logical = (__u64)end << blksize_bits;
4556 }
4557 /* Find contiguous delayed buffers. */
4558 do {
4559 if (!buffer_delay(bh))
4560 goto found_delayed_extent;
4561 bh = bh->b_this_page;
4562 end++;
4563 } while (bh != head);
4564
b221349f 4565 for (; index < ret; index++) {
6d9c85eb
YY
4566 if (!page_has_buffers(pages[index])) {
4567 bh = NULL;
4568 break;
4569 }
4570 head = page_buffers(pages[index]);
4571 if (!head) {
4572 bh = NULL;
4573 break;
4574 }
b221349f 4575
6d9c85eb 4576 if (pages[index]->index !=
b221349f
YY
4577 pages[start_index]->index + index
4578 - start_index) {
6d9c85eb
YY
4579 /* Blocks are not contiguous. */
4580 bh = NULL;
4581 break;
4582 }
4583 bh = head;
4584 do {
4585 if (!buffer_delay(bh))
4586 /* Delayed-extent ends. */
4587 goto found_delayed_extent;
4588 bh = bh->b_this_page;
4589 end++;
4590 } while (bh != head);
4591 }
4592 } else if (!(flags & FIEMAP_EXTENT_DELALLOC))
4593 /* a hole found. */
4594 goto out;
4595
4596found_delayed_extent:
4597 newex->ec_len = min(end - newex->ec_block,
4598 (ext4_lblk_t)EXT_INIT_MAX_LEN);
4599 if (ret == nr_pages && bh != NULL &&
4600 newex->ec_len < EXT_INIT_MAX_LEN &&
4601 buffer_delay(bh)) {
4602 /* Have not collected an extent and continue. */
4603 for (index = 0; index < ret; index++)
4604 page_cache_release(pages[index]);
4605 goto repeat;
6873fa0d 4606 }
6d9c85eb
YY
4607
4608 for (index = 0; index < ret; index++)
4609 page_cache_release(pages[index]);
4610 kfree(pages);
6873fa0d
ES
4611 }
4612
4613 physical = (__u64)newex->ec_start << blksize_bits;
4614 length = (__u64)newex->ec_len << blksize_bits;
4615
4616 if (ex && ext4_ext_is_uninitialized(ex))
4617 flags |= FIEMAP_EXTENT_UNWRITTEN;
4618
c03f8aa9 4619 if (next == EXT_MAX_BLOCKS)
6873fa0d
ES
4620 flags |= FIEMAP_EXTENT_LAST;
4621
6d9c85eb 4622 ret = fiemap_fill_next_extent(fieinfo, logical, physical,
6873fa0d 4623 length, flags);
6d9c85eb
YY
4624 if (ret < 0)
4625 return ret;
4626 if (ret == 1)
6873fa0d 4627 return EXT_BREAK;
6873fa0d
ES
4628 return EXT_CONTINUE;
4629}
6873fa0d
ES
4630/* fiemap flags we can handle specified here */
4631#define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
4632
3a06d778
AK
4633static int ext4_xattr_fiemap(struct inode *inode,
4634 struct fiemap_extent_info *fieinfo)
6873fa0d
ES
4635{
4636 __u64 physical = 0;
4637 __u64 length;
4638 __u32 flags = FIEMAP_EXTENT_LAST;
4639 int blockbits = inode->i_sb->s_blocksize_bits;
4640 int error = 0;
4641
4642 /* in-inode? */
19f5fb7a 4643 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
6873fa0d
ES
4644 struct ext4_iloc iloc;
4645 int offset; /* offset of xattr in inode */
4646
4647 error = ext4_get_inode_loc(inode, &iloc);
4648 if (error)
4649 return error;
4650 physical = iloc.bh->b_blocknr << blockbits;
4651 offset = EXT4_GOOD_OLD_INODE_SIZE +
4652 EXT4_I(inode)->i_extra_isize;
4653 physical += offset;
4654 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4655 flags |= FIEMAP_EXTENT_DATA_INLINE;
fd2dd9fb 4656 brelse(iloc.bh);
6873fa0d
ES
4657 } else { /* external block */
4658 physical = EXT4_I(inode)->i_file_acl << blockbits;
4659 length = inode->i_sb->s_blocksize;
4660 }
4661
4662 if (physical)
4663 error = fiemap_fill_next_extent(fieinfo, 0, physical,
4664 length, flags);
4665 return (error < 0 ? error : 0);
4666}
4667
a4bb6b64
AH
4668/*
4669 * ext4_ext_punch_hole
4670 *
4671 * Punches a hole of "length" bytes in a file starting
4672 * at byte "offset"
4673 *
4674 * @inode: The inode of the file to punch a hole in
4675 * @offset: The starting byte offset of the hole
4676 * @length: The length of the hole
4677 *
4678 * Returns the number of blocks removed or negative on err
4679 */
4680int ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)
4681{
4682 struct inode *inode = file->f_path.dentry->d_inode;
4683 struct super_block *sb = inode->i_sb;
5f95d21f 4684 ext4_lblk_t first_block, stop_block;
a4bb6b64 4685 struct address_space *mapping = inode->i_mapping;
a4bb6b64 4686 handle_t *handle;
ba06208a
AH
4687 loff_t first_page, last_page, page_len;
4688 loff_t first_page_offset, last_page_offset;
5f95d21f 4689 int credits, err = 0;
a4bb6b64 4690
2be4751b
AH
4691 /* No need to punch hole beyond i_size */
4692 if (offset >= inode->i_size)
4693 return 0;
4694
4695 /*
4696 * If the hole extends beyond i_size, set the hole
4697 * to end after the page that contains i_size
4698 */
4699 if (offset + length > inode->i_size) {
4700 length = inode->i_size +
4701 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
4702 offset;
4703 }
4704
a4bb6b64
AH
4705 first_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
4706 last_page = (offset + length) >> PAGE_CACHE_SHIFT;
4707
4708 first_page_offset = first_page << PAGE_CACHE_SHIFT;
4709 last_page_offset = last_page << PAGE_CACHE_SHIFT;
4710
4711 /*
4712 * Write out all dirty pages to avoid race conditions
4713 * Then release them.
4714 */
4715 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4716 err = filemap_write_and_wait_range(mapping,
2be4751b 4717 offset, offset + length - 1);
a4bb6b64 4718
2be4751b
AH
4719 if (err)
4720 return err;
a4bb6b64
AH
4721 }
4722
4723 /* Now release the pages */
4724 if (last_page_offset > first_page_offset) {
4725 truncate_inode_pages_range(mapping, first_page_offset,
4726 last_page_offset-1);
4727 }
4728
4729 /* finish any pending end_io work */
4730 ext4_flush_completed_IO(inode);
4731
4732 credits = ext4_writepage_trans_blocks(inode);
4733 handle = ext4_journal_start(inode, credits);
4734 if (IS_ERR(handle))
4735 return PTR_ERR(handle);
4736
4737 err = ext4_orphan_add(handle, inode);
4738 if (err)
4739 goto out;
4740
4741 /*
ba06208a
AH
4742 * Now we need to zero out the non-page-aligned data in the
4743 * pages at the start and tail of the hole, and unmap the buffer
4744 * heads for the block aligned regions of the page that were
4745 * completely zeroed.
a4bb6b64 4746 */
ba06208a
AH
4747 if (first_page > last_page) {
4748 /*
4749 * If the file space being truncated is contained within a page
4750 * just zero out and unmap the middle of that page
4751 */
4752 err = ext4_discard_partial_page_buffers(handle,
4753 mapping, offset, length, 0);
4754
4755 if (err)
4756 goto out;
4757 } else {
4758 /*
4759 * zero out and unmap the partial page that contains
4760 * the start of the hole
4761 */
4762 page_len = first_page_offset - offset;
4763 if (page_len > 0) {
4764 err = ext4_discard_partial_page_buffers(handle, mapping,
4765 offset, page_len, 0);
4766 if (err)
4767 goto out;
4768 }
4769
4770 /*
4771 * zero out and unmap the partial page that contains
4772 * the end of the hole
4773 */
4774 page_len = offset + length - last_page_offset;
4775 if (page_len > 0) {
4776 err = ext4_discard_partial_page_buffers(handle, mapping,
4777 last_page_offset, page_len, 0);
4778 if (err)
4779 goto out;
a4bb6b64
AH
4780 }
4781 }
4782
2be4751b
AH
4783 /*
4784 * If i_size is contained in the last page, we need to
4785 * unmap and zero the partial page after i_size
4786 */
4787 if (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&
4788 inode->i_size % PAGE_CACHE_SIZE != 0) {
4789
4790 page_len = PAGE_CACHE_SIZE -
4791 (inode->i_size & (PAGE_CACHE_SIZE - 1));
4792
4793 if (page_len > 0) {
4794 err = ext4_discard_partial_page_buffers(handle,
4795 mapping, inode->i_size, page_len, 0);
4796
4797 if (err)
4798 goto out;
4799 }
4800 }
4801
5f95d21f
LC
4802 first_block = (offset + sb->s_blocksize - 1) >>
4803 EXT4_BLOCK_SIZE_BITS(sb);
4804 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4805
a4bb6b64 4806 /* If there are no blocks to remove, return now */
5f95d21f 4807 if (first_block >= stop_block)
a4bb6b64
AH
4808 goto out;
4809
4810 down_write(&EXT4_I(inode)->i_data_sem);
4811 ext4_ext_invalidate_cache(inode);
4812 ext4_discard_preallocations(inode);
4813
5f95d21f 4814 err = ext4_ext_remove_space(inode, first_block, stop_block - 1);
a4bb6b64 4815
5f95d21f
LC
4816 ext4_ext_invalidate_cache(inode);
4817 ext4_discard_preallocations(inode);
a4bb6b64
AH
4818
4819 if (IS_SYNC(inode))
4820 ext4_handle_sync(handle);
4821
4822 up_write(&EXT4_I(inode)->i_data_sem);
4823
4824out:
4825 ext4_orphan_del(handle, inode);
4826 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4827 ext4_mark_inode_dirty(handle, inode);
4828 ext4_journal_stop(handle);
4829 return err;
4830}
6873fa0d
ES
4831int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4832 __u64 start, __u64 len)
4833{
4834 ext4_lblk_t start_blk;
6873fa0d
ES
4835 int error = 0;
4836
4837 /* fallback to generic here if not in extents fmt */
12e9b892 4838 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
6873fa0d
ES
4839 return generic_block_fiemap(inode, fieinfo, start, len,
4840 ext4_get_block);
4841
4842 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
4843 return -EBADR;
4844
4845 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4846 error = ext4_xattr_fiemap(inode, fieinfo);
4847 } else {
aca92ff6
LM
4848 ext4_lblk_t len_blks;
4849 __u64 last_blk;
4850
6873fa0d 4851 start_blk = start >> inode->i_sb->s_blocksize_bits;
aca92ff6 4852 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
f17722f9
LC
4853 if (last_blk >= EXT_MAX_BLOCKS)
4854 last_blk = EXT_MAX_BLOCKS-1;
aca92ff6 4855 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
6873fa0d
ES
4856
4857 /*
4858 * Walk the extent tree gathering extent information.
4859 * ext4_ext_fiemap_cb will push extents back to user.
4860 */
6873fa0d
ES
4861 error = ext4_ext_walk_space(inode, start_blk, len_blks,
4862 ext4_ext_fiemap_cb, fieinfo);
6873fa0d
ES
4863 }
4864
4865 return error;
4866}