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