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