]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - fs/ext4/extents.c
UBUNTU: Ubuntu-4.15.0-96.97
[mirror_ubuntu-bionic-kernel.git] / fs / ext4 / extents.c
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
4 *
5 * Architecture independence:
6 * Copyright (c) 2005, Bull S.A.
7 * Written by Pierre Peiffer <pierre.peiffer@bull.net>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
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/fs.h>
33 #include <linux/time.h>
34 #include <linux/jbd2.h>
35 #include <linux/highuid.h>
36 #include <linux/pagemap.h>
37 #include <linux/quotaops.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <linux/uaccess.h>
41 #include <linux/fiemap.h>
42 #include <linux/backing-dev.h>
43 #include "ext4_jbd2.h"
44 #include "ext4_extents.h"
45 #include "xattr.h"
46
47 #include <trace/events/ext4.h>
48
49 /*
50 * used by extent splitting.
51 */
52 #define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
53 due to ENOSPC */
54 #define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
55 #define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
56
57 #define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
58 #define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
59
60 static __le32 ext4_extent_block_csum(struct inode *inode,
61 struct ext4_extent_header *eh)
62 {
63 struct ext4_inode_info *ei = EXT4_I(inode);
64 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
65 __u32 csum;
66
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
68 EXT4_EXTENT_TAIL_OFFSET(eh));
69 return cpu_to_le32(csum);
70 }
71
72 static int ext4_extent_block_csum_verify(struct inode *inode,
73 struct ext4_extent_header *eh)
74 {
75 struct ext4_extent_tail *et;
76
77 if (!ext4_has_metadata_csum(inode->i_sb))
78 return 1;
79
80 et = find_ext4_extent_tail(eh);
81 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
82 return 0;
83 return 1;
84 }
85
86 static void ext4_extent_block_csum_set(struct inode *inode,
87 struct ext4_extent_header *eh)
88 {
89 struct ext4_extent_tail *et;
90
91 if (!ext4_has_metadata_csum(inode->i_sb))
92 return;
93
94 et = find_ext4_extent_tail(eh);
95 et->et_checksum = ext4_extent_block_csum(inode, eh);
96 }
97
98 static int ext4_split_extent(handle_t *handle,
99 struct inode *inode,
100 struct ext4_ext_path **ppath,
101 struct ext4_map_blocks *map,
102 int split_flag,
103 int flags);
104
105 static int ext4_split_extent_at(handle_t *handle,
106 struct inode *inode,
107 struct ext4_ext_path **ppath,
108 ext4_lblk_t split,
109 int split_flag,
110 int flags);
111
112 static int ext4_find_delayed_extent(struct inode *inode,
113 struct extent_status *newes);
114
115 static int ext4_ext_truncate_extend_restart(handle_t *handle,
116 struct inode *inode,
117 int needed)
118 {
119 int err;
120
121 if (!ext4_handle_valid(handle))
122 return 0;
123 if (handle->h_buffer_credits >= needed)
124 return 0;
125 /*
126 * If we need to extend the journal get a few extra blocks
127 * while we're at it for efficiency's sake.
128 */
129 needed += 3;
130 err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
131 if (err <= 0)
132 return err;
133 err = ext4_truncate_restart_trans(handle, inode, needed);
134 if (err == 0)
135 err = -EAGAIN;
136
137 return err;
138 }
139
140 /*
141 * could return:
142 * - EROFS
143 * - ENOMEM
144 */
145 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
146 struct ext4_ext_path *path)
147 {
148 if (path->p_bh) {
149 /* path points to block */
150 BUFFER_TRACE(path->p_bh, "get_write_access");
151 return ext4_journal_get_write_access(handle, path->p_bh);
152 }
153 /* path points to leaf/index in inode body */
154 /* we use in-core data, no need to protect them */
155 return 0;
156 }
157
158 /*
159 * could return:
160 * - EROFS
161 * - ENOMEM
162 * - EIO
163 */
164 int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
165 struct inode *inode, struct ext4_ext_path *path)
166 {
167 int err;
168
169 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
170 if (path->p_bh) {
171 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
172 /* path points to block */
173 err = __ext4_handle_dirty_metadata(where, line, handle,
174 inode, path->p_bh);
175 } else {
176 /* path points to leaf/index in inode body */
177 err = ext4_mark_inode_dirty(handle, inode);
178 }
179 return err;
180 }
181
182 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
183 struct ext4_ext_path *path,
184 ext4_lblk_t block)
185 {
186 if (path) {
187 int depth = path->p_depth;
188 struct ext4_extent *ex;
189
190 /*
191 * Try to predict block placement assuming that we are
192 * filling in a file which will eventually be
193 * non-sparse --- i.e., in the case of libbfd writing
194 * an ELF object sections out-of-order but in a way
195 * the eventually results in a contiguous object or
196 * executable file, or some database extending a table
197 * space file. However, this is actually somewhat
198 * non-ideal if we are writing a sparse file such as
199 * qemu or KVM writing a raw image file that is going
200 * to stay fairly sparse, since it will end up
201 * fragmenting the file system's free space. Maybe we
202 * should have some hueristics or some way to allow
203 * userspace to pass a hint to file system,
204 * especially if the latter case turns out to be
205 * common.
206 */
207 ex = path[depth].p_ext;
208 if (ex) {
209 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
210 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
211
212 if (block > ext_block)
213 return ext_pblk + (block - ext_block);
214 else
215 return ext_pblk - (ext_block - block);
216 }
217
218 /* it looks like index is empty;
219 * try to find starting block from index itself */
220 if (path[depth].p_bh)
221 return path[depth].p_bh->b_blocknr;
222 }
223
224 /* OK. use inode's group */
225 return ext4_inode_to_goal_block(inode);
226 }
227
228 /*
229 * Allocation for a meta data block
230 */
231 static ext4_fsblk_t
232 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
233 struct ext4_ext_path *path,
234 struct ext4_extent *ex, int *err, unsigned int flags)
235 {
236 ext4_fsblk_t goal, newblock;
237
238 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
239 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
240 NULL, err);
241 return newblock;
242 }
243
244 static inline int ext4_ext_space_block(struct inode *inode, int check)
245 {
246 int size;
247
248 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249 / sizeof(struct ext4_extent);
250 #ifdef AGGRESSIVE_TEST
251 if (!check && size > 6)
252 size = 6;
253 #endif
254 return size;
255 }
256
257 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
258 {
259 int size;
260
261 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
262 / sizeof(struct ext4_extent_idx);
263 #ifdef AGGRESSIVE_TEST
264 if (!check && size > 5)
265 size = 5;
266 #endif
267 return size;
268 }
269
270 static inline int ext4_ext_space_root(struct inode *inode, int check)
271 {
272 int size;
273
274 size = sizeof(EXT4_I(inode)->i_data);
275 size -= sizeof(struct ext4_extent_header);
276 size /= sizeof(struct ext4_extent);
277 #ifdef AGGRESSIVE_TEST
278 if (!check && size > 3)
279 size = 3;
280 #endif
281 return size;
282 }
283
284 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
285 {
286 int size;
287
288 size = sizeof(EXT4_I(inode)->i_data);
289 size -= sizeof(struct ext4_extent_header);
290 size /= sizeof(struct ext4_extent_idx);
291 #ifdef AGGRESSIVE_TEST
292 if (!check && size > 4)
293 size = 4;
294 #endif
295 return size;
296 }
297
298 static inline int
299 ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
300 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
301 int nofail)
302 {
303 struct ext4_ext_path *path = *ppath;
304 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
305
306 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
307 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
308 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
309 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
310 }
311
312 /*
313 * Calculate the number of metadata blocks needed
314 * to allocate @blocks
315 * Worse case is one block per extent
316 */
317 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
318 {
319 struct ext4_inode_info *ei = EXT4_I(inode);
320 int idxs;
321
322 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
323 / sizeof(struct ext4_extent_idx));
324
325 /*
326 * If the new delayed allocation block is contiguous with the
327 * previous da block, it can share index blocks with the
328 * previous block, so we only need to allocate a new index
329 * block every idxs leaf blocks. At ldxs**2 blocks, we need
330 * an additional index block, and at ldxs**3 blocks, yet
331 * another index blocks.
332 */
333 if (ei->i_da_metadata_calc_len &&
334 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
335 int num = 0;
336
337 if ((ei->i_da_metadata_calc_len % idxs) == 0)
338 num++;
339 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
340 num++;
341 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
342 num++;
343 ei->i_da_metadata_calc_len = 0;
344 } else
345 ei->i_da_metadata_calc_len++;
346 ei->i_da_metadata_calc_last_lblock++;
347 return num;
348 }
349
350 /*
351 * In the worst case we need a new set of index blocks at
352 * every level of the inode's extent tree.
353 */
354 ei->i_da_metadata_calc_len = 1;
355 ei->i_da_metadata_calc_last_lblock = lblock;
356 return ext_depth(inode) + 1;
357 }
358
359 static int
360 ext4_ext_max_entries(struct inode *inode, int depth)
361 {
362 int max;
363
364 if (depth == ext_depth(inode)) {
365 if (depth == 0)
366 max = ext4_ext_space_root(inode, 1);
367 else
368 max = ext4_ext_space_root_idx(inode, 1);
369 } else {
370 if (depth == 0)
371 max = ext4_ext_space_block(inode, 1);
372 else
373 max = ext4_ext_space_block_idx(inode, 1);
374 }
375
376 return max;
377 }
378
379 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
380 {
381 ext4_fsblk_t block = ext4_ext_pblock(ext);
382 int len = ext4_ext_get_actual_len(ext);
383 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
384
385 /*
386 * We allow neither:
387 * - zero length
388 * - overflow/wrap-around
389 */
390 if (lblock + len <= lblock)
391 return 0;
392 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
393 }
394
395 static int ext4_valid_extent_idx(struct inode *inode,
396 struct ext4_extent_idx *ext_idx)
397 {
398 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
399
400 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
401 }
402
403 static int ext4_valid_extent_entries(struct inode *inode,
404 struct ext4_extent_header *eh,
405 int depth)
406 {
407 unsigned short entries;
408 if (eh->eh_entries == 0)
409 return 1;
410
411 entries = le16_to_cpu(eh->eh_entries);
412
413 if (depth == 0) {
414 /* leaf entries */
415 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
416 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
417 ext4_fsblk_t pblock = 0;
418 ext4_lblk_t lblock = 0;
419 ext4_lblk_t prev = 0;
420 int len = 0;
421 while (entries) {
422 if (!ext4_valid_extent(inode, ext))
423 return 0;
424
425 /* Check for overlapping extents */
426 lblock = le32_to_cpu(ext->ee_block);
427 len = ext4_ext_get_actual_len(ext);
428 if ((lblock <= prev) && prev) {
429 pblock = ext4_ext_pblock(ext);
430 es->s_last_error_block = cpu_to_le64(pblock);
431 return 0;
432 }
433 ext++;
434 entries--;
435 prev = lblock + len - 1;
436 }
437 } else {
438 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
439 while (entries) {
440 if (!ext4_valid_extent_idx(inode, ext_idx))
441 return 0;
442 ext_idx++;
443 entries--;
444 }
445 }
446 return 1;
447 }
448
449 static int __ext4_ext_check(const char *function, unsigned int line,
450 struct inode *inode, struct ext4_extent_header *eh,
451 int depth, ext4_fsblk_t pblk)
452 {
453 const char *error_msg;
454 int max = 0, err = -EFSCORRUPTED;
455
456 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
457 error_msg = "invalid magic";
458 goto corrupted;
459 }
460 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
461 error_msg = "unexpected eh_depth";
462 goto corrupted;
463 }
464 if (unlikely(eh->eh_max == 0)) {
465 error_msg = "invalid eh_max";
466 goto corrupted;
467 }
468 max = ext4_ext_max_entries(inode, depth);
469 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
470 error_msg = "too large eh_max";
471 goto corrupted;
472 }
473 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
474 error_msg = "invalid eh_entries";
475 goto corrupted;
476 }
477 if (!ext4_valid_extent_entries(inode, eh, depth)) {
478 error_msg = "invalid extent entries";
479 goto corrupted;
480 }
481 if (unlikely(depth > 32)) {
482 error_msg = "too large eh_depth";
483 goto corrupted;
484 }
485 /* Verify checksum on non-root extent tree nodes */
486 if (ext_depth(inode) != depth &&
487 !ext4_extent_block_csum_verify(inode, eh)) {
488 error_msg = "extent tree corrupted";
489 err = -EFSBADCRC;
490 goto corrupted;
491 }
492 return 0;
493
494 corrupted:
495 ext4_error_inode(inode, function, line, 0,
496 "pblk %llu bad header/extent: %s - magic %x, "
497 "entries %u, max %u(%u), depth %u(%u)",
498 (unsigned long long) pblk, error_msg,
499 le16_to_cpu(eh->eh_magic),
500 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
501 max, le16_to_cpu(eh->eh_depth), depth);
502 return err;
503 }
504
505 #define ext4_ext_check(inode, eh, depth, pblk) \
506 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
507
508 int ext4_ext_check_inode(struct inode *inode)
509 {
510 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
511 }
512
513 static struct buffer_head *
514 __read_extent_tree_block(const char *function, unsigned int line,
515 struct inode *inode, ext4_fsblk_t pblk, int depth,
516 int flags)
517 {
518 struct buffer_head *bh;
519 int err;
520
521 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
522 if (unlikely(!bh))
523 return ERR_PTR(-ENOMEM);
524
525 if (!bh_uptodate_or_lock(bh)) {
526 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
527 err = bh_submit_read(bh);
528 if (err < 0)
529 goto errout;
530 }
531 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
532 return bh;
533 if (!ext4_has_feature_journal(inode->i_sb) ||
534 (inode->i_ino !=
535 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum))) {
536 err = __ext4_ext_check(function, line, inode,
537 ext_block_hdr(bh), depth, pblk);
538 if (err)
539 goto errout;
540 }
541 set_buffer_verified(bh);
542 /*
543 * If this is a leaf block, cache all of its entries
544 */
545 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
546 struct ext4_extent_header *eh = ext_block_hdr(bh);
547 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
548 ext4_lblk_t prev = 0;
549 int i;
550
551 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
552 unsigned int status = EXTENT_STATUS_WRITTEN;
553 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
554 int len = ext4_ext_get_actual_len(ex);
555
556 if (prev && (prev != lblk))
557 ext4_es_cache_extent(inode, prev,
558 lblk - prev, ~0,
559 EXTENT_STATUS_HOLE);
560
561 if (ext4_ext_is_unwritten(ex))
562 status = EXTENT_STATUS_UNWRITTEN;
563 ext4_es_cache_extent(inode, lblk, len,
564 ext4_ext_pblock(ex), status);
565 prev = lblk + len;
566 }
567 }
568 return bh;
569 errout:
570 put_bh(bh);
571 return ERR_PTR(err);
572
573 }
574
575 #define read_extent_tree_block(inode, pblk, depth, flags) \
576 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
577 (depth), (flags))
578
579 /*
580 * This function is called to cache a file's extent information in the
581 * extent status tree
582 */
583 int ext4_ext_precache(struct inode *inode)
584 {
585 struct ext4_inode_info *ei = EXT4_I(inode);
586 struct ext4_ext_path *path = NULL;
587 struct buffer_head *bh;
588 int i = 0, depth, ret = 0;
589
590 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
591 return 0; /* not an extent-mapped inode */
592
593 down_read(&ei->i_data_sem);
594 depth = ext_depth(inode);
595
596 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
597 GFP_NOFS);
598 if (path == NULL) {
599 up_read(&ei->i_data_sem);
600 return -ENOMEM;
601 }
602
603 /* Don't cache anything if there are no external extent blocks */
604 if (depth == 0)
605 goto out;
606 path[0].p_hdr = ext_inode_hdr(inode);
607 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
608 if (ret)
609 goto out;
610 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
611 while (i >= 0) {
612 /*
613 * If this is a leaf block or we've reached the end of
614 * the index block, go up
615 */
616 if ((i == depth) ||
617 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
618 brelse(path[i].p_bh);
619 path[i].p_bh = NULL;
620 i--;
621 continue;
622 }
623 bh = read_extent_tree_block(inode,
624 ext4_idx_pblock(path[i].p_idx++),
625 depth - i - 1,
626 EXT4_EX_FORCE_CACHE);
627 if (IS_ERR(bh)) {
628 ret = PTR_ERR(bh);
629 break;
630 }
631 i++;
632 path[i].p_bh = bh;
633 path[i].p_hdr = ext_block_hdr(bh);
634 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
635 }
636 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
637 out:
638 up_read(&ei->i_data_sem);
639 ext4_ext_drop_refs(path);
640 kfree(path);
641 return ret;
642 }
643
644 #ifdef EXT_DEBUG
645 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
646 {
647 int k, l = path->p_depth;
648
649 ext_debug("path:");
650 for (k = 0; k <= l; k++, path++) {
651 if (path->p_idx) {
652 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
653 ext4_idx_pblock(path->p_idx));
654 } else if (path->p_ext) {
655 ext_debug(" %d:[%d]%d:%llu ",
656 le32_to_cpu(path->p_ext->ee_block),
657 ext4_ext_is_unwritten(path->p_ext),
658 ext4_ext_get_actual_len(path->p_ext),
659 ext4_ext_pblock(path->p_ext));
660 } else
661 ext_debug(" []");
662 }
663 ext_debug("\n");
664 }
665
666 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
667 {
668 int depth = ext_depth(inode);
669 struct ext4_extent_header *eh;
670 struct ext4_extent *ex;
671 int i;
672
673 if (!path)
674 return;
675
676 eh = path[depth].p_hdr;
677 ex = EXT_FIRST_EXTENT(eh);
678
679 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
680
681 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
682 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
683 ext4_ext_is_unwritten(ex),
684 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
685 }
686 ext_debug("\n");
687 }
688
689 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
690 ext4_fsblk_t newblock, int level)
691 {
692 int depth = ext_depth(inode);
693 struct ext4_extent *ex;
694
695 if (depth != level) {
696 struct ext4_extent_idx *idx;
697 idx = path[level].p_idx;
698 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
699 ext_debug("%d: move %d:%llu in new index %llu\n", level,
700 le32_to_cpu(idx->ei_block),
701 ext4_idx_pblock(idx),
702 newblock);
703 idx++;
704 }
705
706 return;
707 }
708
709 ex = path[depth].p_ext;
710 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
711 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
712 le32_to_cpu(ex->ee_block),
713 ext4_ext_pblock(ex),
714 ext4_ext_is_unwritten(ex),
715 ext4_ext_get_actual_len(ex),
716 newblock);
717 ex++;
718 }
719 }
720
721 #else
722 #define ext4_ext_show_path(inode, path)
723 #define ext4_ext_show_leaf(inode, path)
724 #define ext4_ext_show_move(inode, path, newblock, level)
725 #endif
726
727 void ext4_ext_drop_refs(struct ext4_ext_path *path)
728 {
729 int depth, i;
730
731 if (!path)
732 return;
733 depth = path->p_depth;
734 for (i = 0; i <= depth; i++, path++)
735 if (path->p_bh) {
736 brelse(path->p_bh);
737 path->p_bh = NULL;
738 }
739 }
740
741 /*
742 * ext4_ext_binsearch_idx:
743 * binary search for the closest index of the given block
744 * the header must be checked before calling this
745 */
746 static void
747 ext4_ext_binsearch_idx(struct inode *inode,
748 struct ext4_ext_path *path, ext4_lblk_t block)
749 {
750 struct ext4_extent_header *eh = path->p_hdr;
751 struct ext4_extent_idx *r, *l, *m;
752
753
754 ext_debug("binsearch for %u(idx): ", block);
755
756 l = EXT_FIRST_INDEX(eh) + 1;
757 r = EXT_LAST_INDEX(eh);
758 while (l <= r) {
759 m = l + (r - l) / 2;
760 if (block < le32_to_cpu(m->ei_block))
761 r = m - 1;
762 else
763 l = m + 1;
764 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
765 m, le32_to_cpu(m->ei_block),
766 r, le32_to_cpu(r->ei_block));
767 }
768
769 path->p_idx = l - 1;
770 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
771 ext4_idx_pblock(path->p_idx));
772
773 #ifdef CHECK_BINSEARCH
774 {
775 struct ext4_extent_idx *chix, *ix;
776 int k;
777
778 chix = ix = EXT_FIRST_INDEX(eh);
779 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
780 if (k != 0 &&
781 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
782 printk(KERN_DEBUG "k=%d, ix=0x%p, "
783 "first=0x%p\n", k,
784 ix, EXT_FIRST_INDEX(eh));
785 printk(KERN_DEBUG "%u <= %u\n",
786 le32_to_cpu(ix->ei_block),
787 le32_to_cpu(ix[-1].ei_block));
788 }
789 BUG_ON(k && le32_to_cpu(ix->ei_block)
790 <= le32_to_cpu(ix[-1].ei_block));
791 if (block < le32_to_cpu(ix->ei_block))
792 break;
793 chix = ix;
794 }
795 BUG_ON(chix != path->p_idx);
796 }
797 #endif
798
799 }
800
801 /*
802 * ext4_ext_binsearch:
803 * binary search for closest extent of the given block
804 * the header must be checked before calling this
805 */
806 static void
807 ext4_ext_binsearch(struct inode *inode,
808 struct ext4_ext_path *path, ext4_lblk_t block)
809 {
810 struct ext4_extent_header *eh = path->p_hdr;
811 struct ext4_extent *r, *l, *m;
812
813 if (eh->eh_entries == 0) {
814 /*
815 * this leaf is empty:
816 * we get such a leaf in split/add case
817 */
818 return;
819 }
820
821 ext_debug("binsearch for %u: ", block);
822
823 l = EXT_FIRST_EXTENT(eh) + 1;
824 r = EXT_LAST_EXTENT(eh);
825
826 while (l <= r) {
827 m = l + (r - l) / 2;
828 if (block < le32_to_cpu(m->ee_block))
829 r = m - 1;
830 else
831 l = m + 1;
832 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
833 m, le32_to_cpu(m->ee_block),
834 r, le32_to_cpu(r->ee_block));
835 }
836
837 path->p_ext = l - 1;
838 ext_debug(" -> %d:%llu:[%d]%d ",
839 le32_to_cpu(path->p_ext->ee_block),
840 ext4_ext_pblock(path->p_ext),
841 ext4_ext_is_unwritten(path->p_ext),
842 ext4_ext_get_actual_len(path->p_ext));
843
844 #ifdef CHECK_BINSEARCH
845 {
846 struct ext4_extent *chex, *ex;
847 int k;
848
849 chex = ex = EXT_FIRST_EXTENT(eh);
850 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
851 BUG_ON(k && le32_to_cpu(ex->ee_block)
852 <= le32_to_cpu(ex[-1].ee_block));
853 if (block < le32_to_cpu(ex->ee_block))
854 break;
855 chex = ex;
856 }
857 BUG_ON(chex != path->p_ext);
858 }
859 #endif
860
861 }
862
863 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
864 {
865 struct ext4_extent_header *eh;
866
867 eh = ext_inode_hdr(inode);
868 eh->eh_depth = 0;
869 eh->eh_entries = 0;
870 eh->eh_magic = EXT4_EXT_MAGIC;
871 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
872 ext4_mark_inode_dirty(handle, inode);
873 return 0;
874 }
875
876 struct ext4_ext_path *
877 ext4_find_extent(struct inode *inode, ext4_lblk_t block,
878 struct ext4_ext_path **orig_path, int flags)
879 {
880 struct ext4_extent_header *eh;
881 struct buffer_head *bh;
882 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
883 short int depth, i, ppos = 0;
884 int ret;
885
886 eh = ext_inode_hdr(inode);
887 depth = ext_depth(inode);
888 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
889 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
890 depth);
891 ret = -EFSCORRUPTED;
892 goto err;
893 }
894
895 if (path) {
896 ext4_ext_drop_refs(path);
897 if (depth > path[0].p_maxdepth) {
898 kfree(path);
899 *orig_path = path = NULL;
900 }
901 }
902 if (!path) {
903 /* account possible depth increase */
904 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
905 GFP_NOFS);
906 if (unlikely(!path))
907 return ERR_PTR(-ENOMEM);
908 path[0].p_maxdepth = depth + 1;
909 }
910 path[0].p_hdr = eh;
911 path[0].p_bh = NULL;
912
913 i = depth;
914 /* walk through the tree */
915 while (i) {
916 ext_debug("depth %d: num %d, max %d\n",
917 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
918
919 ext4_ext_binsearch_idx(inode, path + ppos, block);
920 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
921 path[ppos].p_depth = i;
922 path[ppos].p_ext = NULL;
923
924 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
925 flags);
926 if (IS_ERR(bh)) {
927 ret = PTR_ERR(bh);
928 goto err;
929 }
930
931 eh = ext_block_hdr(bh);
932 ppos++;
933 path[ppos].p_bh = bh;
934 path[ppos].p_hdr = eh;
935 }
936
937 path[ppos].p_depth = i;
938 path[ppos].p_ext = NULL;
939 path[ppos].p_idx = NULL;
940
941 /* find extent */
942 ext4_ext_binsearch(inode, path + ppos, block);
943 /* if not an empty leaf */
944 if (path[ppos].p_ext)
945 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
946
947 ext4_ext_show_path(inode, path);
948
949 return path;
950
951 err:
952 ext4_ext_drop_refs(path);
953 kfree(path);
954 if (orig_path)
955 *orig_path = NULL;
956 return ERR_PTR(ret);
957 }
958
959 /*
960 * ext4_ext_insert_index:
961 * insert new index [@logical;@ptr] into the block at @curp;
962 * check where to insert: before @curp or after @curp
963 */
964 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
965 struct ext4_ext_path *curp,
966 int logical, ext4_fsblk_t ptr)
967 {
968 struct ext4_extent_idx *ix;
969 int len, err;
970
971 err = ext4_ext_get_access(handle, inode, curp);
972 if (err)
973 return err;
974
975 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
976 EXT4_ERROR_INODE(inode,
977 "logical %d == ei_block %d!",
978 logical, le32_to_cpu(curp->p_idx->ei_block));
979 return -EFSCORRUPTED;
980 }
981
982 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
983 >= le16_to_cpu(curp->p_hdr->eh_max))) {
984 EXT4_ERROR_INODE(inode,
985 "eh_entries %d >= eh_max %d!",
986 le16_to_cpu(curp->p_hdr->eh_entries),
987 le16_to_cpu(curp->p_hdr->eh_max));
988 return -EFSCORRUPTED;
989 }
990
991 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
992 /* insert after */
993 ext_debug("insert new index %d after: %llu\n", logical, ptr);
994 ix = curp->p_idx + 1;
995 } else {
996 /* insert before */
997 ext_debug("insert new index %d before: %llu\n", logical, ptr);
998 ix = curp->p_idx;
999 }
1000
1001 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1002 BUG_ON(len < 0);
1003 if (len > 0) {
1004 ext_debug("insert new index %d: "
1005 "move %d indices from 0x%p to 0x%p\n",
1006 logical, len, ix, ix + 1);
1007 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1008 }
1009
1010 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1011 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1012 return -EFSCORRUPTED;
1013 }
1014
1015 ix->ei_block = cpu_to_le32(logical);
1016 ext4_idx_store_pblock(ix, ptr);
1017 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1018
1019 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1020 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1021 return -EFSCORRUPTED;
1022 }
1023
1024 err = ext4_ext_dirty(handle, inode, curp);
1025 ext4_std_error(inode->i_sb, err);
1026
1027 return err;
1028 }
1029
1030 /*
1031 * ext4_ext_split:
1032 * inserts new subtree into the path, using free index entry
1033 * at depth @at:
1034 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1035 * - makes decision where to split
1036 * - moves remaining extents and index entries (right to the split point)
1037 * into the newly allocated blocks
1038 * - initializes subtree
1039 */
1040 static int ext4_ext_split(handle_t *handle, struct inode *inode,
1041 unsigned int flags,
1042 struct ext4_ext_path *path,
1043 struct ext4_extent *newext, int at)
1044 {
1045 struct buffer_head *bh = NULL;
1046 int depth = ext_depth(inode);
1047 struct ext4_extent_header *neh;
1048 struct ext4_extent_idx *fidx;
1049 int i = at, k, m, a;
1050 ext4_fsblk_t newblock, oldblock;
1051 __le32 border;
1052 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
1053 int err = 0;
1054 size_t ext_size = 0;
1055
1056 /* make decision: where to split? */
1057 /* FIXME: now decision is simplest: at current extent */
1058
1059 /* if current leaf will be split, then we should use
1060 * border from split point */
1061 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1062 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1063 return -EFSCORRUPTED;
1064 }
1065 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1066 border = path[depth].p_ext[1].ee_block;
1067 ext_debug("leaf will be split."
1068 " next leaf starts at %d\n",
1069 le32_to_cpu(border));
1070 } else {
1071 border = newext->ee_block;
1072 ext_debug("leaf will be added."
1073 " next leaf starts at %d\n",
1074 le32_to_cpu(border));
1075 }
1076
1077 /*
1078 * If error occurs, then we break processing
1079 * and mark filesystem read-only. index won't
1080 * be inserted and tree will be in consistent
1081 * state. Next mount will repair buffers too.
1082 */
1083
1084 /*
1085 * Get array to track all allocated blocks.
1086 * We need this to handle errors and free blocks
1087 * upon them.
1088 */
1089 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
1090 if (!ablocks)
1091 return -ENOMEM;
1092
1093 /* allocate all needed blocks */
1094 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1095 for (a = 0; a < depth - at; a++) {
1096 newblock = ext4_ext_new_meta_block(handle, inode, path,
1097 newext, &err, flags);
1098 if (newblock == 0)
1099 goto cleanup;
1100 ablocks[a] = newblock;
1101 }
1102
1103 /* initialize new leaf */
1104 newblock = ablocks[--a];
1105 if (unlikely(newblock == 0)) {
1106 EXT4_ERROR_INODE(inode, "newblock == 0!");
1107 err = -EFSCORRUPTED;
1108 goto cleanup;
1109 }
1110 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1111 if (unlikely(!bh)) {
1112 err = -ENOMEM;
1113 goto cleanup;
1114 }
1115 lock_buffer(bh);
1116
1117 err = ext4_journal_get_create_access(handle, bh);
1118 if (err)
1119 goto cleanup;
1120
1121 neh = ext_block_hdr(bh);
1122 neh->eh_entries = 0;
1123 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1124 neh->eh_magic = EXT4_EXT_MAGIC;
1125 neh->eh_depth = 0;
1126
1127 /* move remainder of path[depth] to the new leaf */
1128 if (unlikely(path[depth].p_hdr->eh_entries !=
1129 path[depth].p_hdr->eh_max)) {
1130 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1131 path[depth].p_hdr->eh_entries,
1132 path[depth].p_hdr->eh_max);
1133 err = -EFSCORRUPTED;
1134 goto cleanup;
1135 }
1136 /* start copy from next extent */
1137 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1138 ext4_ext_show_move(inode, path, newblock, depth);
1139 if (m) {
1140 struct ext4_extent *ex;
1141 ex = EXT_FIRST_EXTENT(neh);
1142 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1143 le16_add_cpu(&neh->eh_entries, m);
1144 }
1145
1146 /* zero out unused area in the extent block */
1147 ext_size = sizeof(struct ext4_extent_header) +
1148 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1149 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1150 ext4_extent_block_csum_set(inode, neh);
1151 set_buffer_uptodate(bh);
1152 unlock_buffer(bh);
1153
1154 err = ext4_handle_dirty_metadata(handle, inode, bh);
1155 if (err)
1156 goto cleanup;
1157 brelse(bh);
1158 bh = NULL;
1159
1160 /* correct old leaf */
1161 if (m) {
1162 err = ext4_ext_get_access(handle, inode, path + depth);
1163 if (err)
1164 goto cleanup;
1165 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1166 err = ext4_ext_dirty(handle, inode, path + depth);
1167 if (err)
1168 goto cleanup;
1169
1170 }
1171
1172 /* create intermediate indexes */
1173 k = depth - at - 1;
1174 if (unlikely(k < 0)) {
1175 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1176 err = -EFSCORRUPTED;
1177 goto cleanup;
1178 }
1179 if (k)
1180 ext_debug("create %d intermediate indices\n", k);
1181 /* insert new index into current index block */
1182 /* current depth stored in i var */
1183 i = depth - 1;
1184 while (k--) {
1185 oldblock = newblock;
1186 newblock = ablocks[--a];
1187 bh = sb_getblk(inode->i_sb, newblock);
1188 if (unlikely(!bh)) {
1189 err = -ENOMEM;
1190 goto cleanup;
1191 }
1192 lock_buffer(bh);
1193
1194 err = ext4_journal_get_create_access(handle, bh);
1195 if (err)
1196 goto cleanup;
1197
1198 neh = ext_block_hdr(bh);
1199 neh->eh_entries = cpu_to_le16(1);
1200 neh->eh_magic = EXT4_EXT_MAGIC;
1201 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1202 neh->eh_depth = cpu_to_le16(depth - i);
1203 fidx = EXT_FIRST_INDEX(neh);
1204 fidx->ei_block = border;
1205 ext4_idx_store_pblock(fidx, oldblock);
1206
1207 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1208 i, newblock, le32_to_cpu(border), oldblock);
1209
1210 /* move remainder of path[i] to the new index block */
1211 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1212 EXT_LAST_INDEX(path[i].p_hdr))) {
1213 EXT4_ERROR_INODE(inode,
1214 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1215 le32_to_cpu(path[i].p_ext->ee_block));
1216 err = -EFSCORRUPTED;
1217 goto cleanup;
1218 }
1219 /* start copy indexes */
1220 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1221 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1222 EXT_MAX_INDEX(path[i].p_hdr));
1223 ext4_ext_show_move(inode, path, newblock, i);
1224 if (m) {
1225 memmove(++fidx, path[i].p_idx,
1226 sizeof(struct ext4_extent_idx) * m);
1227 le16_add_cpu(&neh->eh_entries, m);
1228 }
1229 /* zero out unused area in the extent block */
1230 ext_size = sizeof(struct ext4_extent_header) +
1231 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1232 memset(bh->b_data + ext_size, 0,
1233 inode->i_sb->s_blocksize - ext_size);
1234 ext4_extent_block_csum_set(inode, neh);
1235 set_buffer_uptodate(bh);
1236 unlock_buffer(bh);
1237
1238 err = ext4_handle_dirty_metadata(handle, inode, bh);
1239 if (err)
1240 goto cleanup;
1241 brelse(bh);
1242 bh = NULL;
1243
1244 /* correct old index */
1245 if (m) {
1246 err = ext4_ext_get_access(handle, inode, path + i);
1247 if (err)
1248 goto cleanup;
1249 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1250 err = ext4_ext_dirty(handle, inode, path + i);
1251 if (err)
1252 goto cleanup;
1253 }
1254
1255 i--;
1256 }
1257
1258 /* insert new index */
1259 err = ext4_ext_insert_index(handle, inode, path + at,
1260 le32_to_cpu(border), newblock);
1261
1262 cleanup:
1263 if (bh) {
1264 if (buffer_locked(bh))
1265 unlock_buffer(bh);
1266 brelse(bh);
1267 }
1268
1269 if (err) {
1270 /* free all allocated blocks in error case */
1271 for (i = 0; i < depth; i++) {
1272 if (!ablocks[i])
1273 continue;
1274 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1275 EXT4_FREE_BLOCKS_METADATA);
1276 }
1277 }
1278 kfree(ablocks);
1279
1280 return err;
1281 }
1282
1283 /*
1284 * ext4_ext_grow_indepth:
1285 * implements tree growing procedure:
1286 * - allocates new block
1287 * - moves top-level data (index block or leaf) into the new block
1288 * - initializes new top-level, creating index that points to the
1289 * just created block
1290 */
1291 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1292 unsigned int flags)
1293 {
1294 struct ext4_extent_header *neh;
1295 struct buffer_head *bh;
1296 ext4_fsblk_t newblock, goal = 0;
1297 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1298 int err = 0;
1299 size_t ext_size = 0;
1300
1301 /* Try to prepend new index to old one */
1302 if (ext_depth(inode))
1303 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1304 if (goal > le32_to_cpu(es->s_first_data_block)) {
1305 flags |= EXT4_MB_HINT_TRY_GOAL;
1306 goal--;
1307 } else
1308 goal = ext4_inode_to_goal_block(inode);
1309 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1310 NULL, &err);
1311 if (newblock == 0)
1312 return err;
1313
1314 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1315 if (unlikely(!bh))
1316 return -ENOMEM;
1317 lock_buffer(bh);
1318
1319 err = ext4_journal_get_create_access(handle, bh);
1320 if (err) {
1321 unlock_buffer(bh);
1322 goto out;
1323 }
1324
1325 ext_size = sizeof(EXT4_I(inode)->i_data);
1326 /* move top-level index/leaf into new block */
1327 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1328 /* zero out unused area in the extent block */
1329 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
1330
1331 /* set size of new block */
1332 neh = ext_block_hdr(bh);
1333 /* old root could have indexes or leaves
1334 * so calculate e_max right way */
1335 if (ext_depth(inode))
1336 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1337 else
1338 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1339 neh->eh_magic = EXT4_EXT_MAGIC;
1340 ext4_extent_block_csum_set(inode, neh);
1341 set_buffer_uptodate(bh);
1342 unlock_buffer(bh);
1343
1344 err = ext4_handle_dirty_metadata(handle, inode, bh);
1345 if (err)
1346 goto out;
1347
1348 /* Update top-level index: num,max,pointer */
1349 neh = ext_inode_hdr(inode);
1350 neh->eh_entries = cpu_to_le16(1);
1351 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1352 if (neh->eh_depth == 0) {
1353 /* Root extent block becomes index block */
1354 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1355 EXT_FIRST_INDEX(neh)->ei_block =
1356 EXT_FIRST_EXTENT(neh)->ee_block;
1357 }
1358 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1359 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1360 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1361 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1362
1363 le16_add_cpu(&neh->eh_depth, 1);
1364 ext4_mark_inode_dirty(handle, inode);
1365 out:
1366 brelse(bh);
1367
1368 return err;
1369 }
1370
1371 /*
1372 * ext4_ext_create_new_leaf:
1373 * finds empty index and adds new leaf.
1374 * if no free index is found, then it requests in-depth growing.
1375 */
1376 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1377 unsigned int mb_flags,
1378 unsigned int gb_flags,
1379 struct ext4_ext_path **ppath,
1380 struct ext4_extent *newext)
1381 {
1382 struct ext4_ext_path *path = *ppath;
1383 struct ext4_ext_path *curp;
1384 int depth, i, err = 0;
1385
1386 repeat:
1387 i = depth = ext_depth(inode);
1388
1389 /* walk up to the tree and look for free index entry */
1390 curp = path + depth;
1391 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1392 i--;
1393 curp--;
1394 }
1395
1396 /* we use already allocated block for index block,
1397 * so subsequent data blocks should be contiguous */
1398 if (EXT_HAS_FREE_INDEX(curp)) {
1399 /* if we found index with free entry, then use that
1400 * entry: create all needed subtree and add new leaf */
1401 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1402 if (err)
1403 goto out;
1404
1405 /* refill path */
1406 path = ext4_find_extent(inode,
1407 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1408 ppath, gb_flags);
1409 if (IS_ERR(path))
1410 err = PTR_ERR(path);
1411 } else {
1412 /* tree is full, time to grow in depth */
1413 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1414 if (err)
1415 goto out;
1416
1417 /* refill path */
1418 path = ext4_find_extent(inode,
1419 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1420 ppath, gb_flags);
1421 if (IS_ERR(path)) {
1422 err = PTR_ERR(path);
1423 goto out;
1424 }
1425
1426 /*
1427 * only first (depth 0 -> 1) produces free space;
1428 * in all other cases we have to split the grown tree
1429 */
1430 depth = ext_depth(inode);
1431 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1432 /* now we need to split */
1433 goto repeat;
1434 }
1435 }
1436
1437 out:
1438 return err;
1439 }
1440
1441 /*
1442 * search the closest allocated block to the left for *logical
1443 * and returns it at @logical + it's physical address at @phys
1444 * if *logical is the smallest allocated block, the function
1445 * returns 0 at @phys
1446 * return value contains 0 (success) or error code
1447 */
1448 static int ext4_ext_search_left(struct inode *inode,
1449 struct ext4_ext_path *path,
1450 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1451 {
1452 struct ext4_extent_idx *ix;
1453 struct ext4_extent *ex;
1454 int depth, ee_len;
1455
1456 if (unlikely(path == NULL)) {
1457 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1458 return -EFSCORRUPTED;
1459 }
1460 depth = path->p_depth;
1461 *phys = 0;
1462
1463 if (depth == 0 && path->p_ext == NULL)
1464 return 0;
1465
1466 /* usually extent in the path covers blocks smaller
1467 * then *logical, but it can be that extent is the
1468 * first one in the file */
1469
1470 ex = path[depth].p_ext;
1471 ee_len = ext4_ext_get_actual_len(ex);
1472 if (*logical < le32_to_cpu(ex->ee_block)) {
1473 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1474 EXT4_ERROR_INODE(inode,
1475 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1476 *logical, le32_to_cpu(ex->ee_block));
1477 return -EFSCORRUPTED;
1478 }
1479 while (--depth >= 0) {
1480 ix = path[depth].p_idx;
1481 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1482 EXT4_ERROR_INODE(inode,
1483 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1484 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1485 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1486 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1487 depth);
1488 return -EFSCORRUPTED;
1489 }
1490 }
1491 return 0;
1492 }
1493
1494 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1495 EXT4_ERROR_INODE(inode,
1496 "logical %d < ee_block %d + ee_len %d!",
1497 *logical, le32_to_cpu(ex->ee_block), ee_len);
1498 return -EFSCORRUPTED;
1499 }
1500
1501 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1502 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1503 return 0;
1504 }
1505
1506 /*
1507 * search the closest allocated block to the right for *logical
1508 * and returns it at @logical + it's physical address at @phys
1509 * if *logical is the largest allocated block, the function
1510 * returns 0 at @phys
1511 * return value contains 0 (success) or error code
1512 */
1513 static int ext4_ext_search_right(struct inode *inode,
1514 struct ext4_ext_path *path,
1515 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1516 struct ext4_extent **ret_ex)
1517 {
1518 struct buffer_head *bh = NULL;
1519 struct ext4_extent_header *eh;
1520 struct ext4_extent_idx *ix;
1521 struct ext4_extent *ex;
1522 ext4_fsblk_t block;
1523 int depth; /* Note, NOT eh_depth; depth from top of tree */
1524 int ee_len;
1525
1526 if (unlikely(path == NULL)) {
1527 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1528 return -EFSCORRUPTED;
1529 }
1530 depth = path->p_depth;
1531 *phys = 0;
1532
1533 if (depth == 0 && path->p_ext == NULL)
1534 return 0;
1535
1536 /* usually extent in the path covers blocks smaller
1537 * then *logical, but it can be that extent is the
1538 * first one in the file */
1539
1540 ex = path[depth].p_ext;
1541 ee_len = ext4_ext_get_actual_len(ex);
1542 if (*logical < le32_to_cpu(ex->ee_block)) {
1543 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1544 EXT4_ERROR_INODE(inode,
1545 "first_extent(path[%d].p_hdr) != ex",
1546 depth);
1547 return -EFSCORRUPTED;
1548 }
1549 while (--depth >= 0) {
1550 ix = path[depth].p_idx;
1551 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1552 EXT4_ERROR_INODE(inode,
1553 "ix != EXT_FIRST_INDEX *logical %d!",
1554 *logical);
1555 return -EFSCORRUPTED;
1556 }
1557 }
1558 goto found_extent;
1559 }
1560
1561 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1562 EXT4_ERROR_INODE(inode,
1563 "logical %d < ee_block %d + ee_len %d!",
1564 *logical, le32_to_cpu(ex->ee_block), ee_len);
1565 return -EFSCORRUPTED;
1566 }
1567
1568 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1569 /* next allocated block in this leaf */
1570 ex++;
1571 goto found_extent;
1572 }
1573
1574 /* go up and search for index to the right */
1575 while (--depth >= 0) {
1576 ix = path[depth].p_idx;
1577 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1578 goto got_index;
1579 }
1580
1581 /* we've gone up to the root and found no index to the right */
1582 return 0;
1583
1584 got_index:
1585 /* we've found index to the right, let's
1586 * follow it and find the closest allocated
1587 * block to the right */
1588 ix++;
1589 block = ext4_idx_pblock(ix);
1590 while (++depth < path->p_depth) {
1591 /* subtract from p_depth to get proper eh_depth */
1592 bh = read_extent_tree_block(inode, block,
1593 path->p_depth - depth, 0);
1594 if (IS_ERR(bh))
1595 return PTR_ERR(bh);
1596 eh = ext_block_hdr(bh);
1597 ix = EXT_FIRST_INDEX(eh);
1598 block = ext4_idx_pblock(ix);
1599 put_bh(bh);
1600 }
1601
1602 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
1603 if (IS_ERR(bh))
1604 return PTR_ERR(bh);
1605 eh = ext_block_hdr(bh);
1606 ex = EXT_FIRST_EXTENT(eh);
1607 found_extent:
1608 *logical = le32_to_cpu(ex->ee_block);
1609 *phys = ext4_ext_pblock(ex);
1610 *ret_ex = ex;
1611 if (bh)
1612 put_bh(bh);
1613 return 0;
1614 }
1615
1616 /*
1617 * ext4_ext_next_allocated_block:
1618 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1619 * NOTE: it considers block number from index entry as
1620 * allocated block. Thus, index entries have to be consistent
1621 * with leaves.
1622 */
1623 ext4_lblk_t
1624 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1625 {
1626 int depth;
1627
1628 BUG_ON(path == NULL);
1629 depth = path->p_depth;
1630
1631 if (depth == 0 && path->p_ext == NULL)
1632 return EXT_MAX_BLOCKS;
1633
1634 while (depth >= 0) {
1635 if (depth == path->p_depth) {
1636 /* leaf */
1637 if (path[depth].p_ext &&
1638 path[depth].p_ext !=
1639 EXT_LAST_EXTENT(path[depth].p_hdr))
1640 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1641 } else {
1642 /* index */
1643 if (path[depth].p_idx !=
1644 EXT_LAST_INDEX(path[depth].p_hdr))
1645 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1646 }
1647 depth--;
1648 }
1649
1650 return EXT_MAX_BLOCKS;
1651 }
1652
1653 /*
1654 * ext4_ext_next_leaf_block:
1655 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1656 */
1657 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1658 {
1659 int depth;
1660
1661 BUG_ON(path == NULL);
1662 depth = path->p_depth;
1663
1664 /* zero-tree has no leaf blocks at all */
1665 if (depth == 0)
1666 return EXT_MAX_BLOCKS;
1667
1668 /* go to index block */
1669 depth--;
1670
1671 while (depth >= 0) {
1672 if (path[depth].p_idx !=
1673 EXT_LAST_INDEX(path[depth].p_hdr))
1674 return (ext4_lblk_t)
1675 le32_to_cpu(path[depth].p_idx[1].ei_block);
1676 depth--;
1677 }
1678
1679 return EXT_MAX_BLOCKS;
1680 }
1681
1682 /*
1683 * ext4_ext_correct_indexes:
1684 * if leaf gets modified and modified extent is first in the leaf,
1685 * then we have to correct all indexes above.
1686 * TODO: do we need to correct tree in all cases?
1687 */
1688 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1689 struct ext4_ext_path *path)
1690 {
1691 struct ext4_extent_header *eh;
1692 int depth = ext_depth(inode);
1693 struct ext4_extent *ex;
1694 __le32 border;
1695 int k, err = 0;
1696
1697 eh = path[depth].p_hdr;
1698 ex = path[depth].p_ext;
1699
1700 if (unlikely(ex == NULL || eh == NULL)) {
1701 EXT4_ERROR_INODE(inode,
1702 "ex %p == NULL or eh %p == NULL", ex, eh);
1703 return -EFSCORRUPTED;
1704 }
1705
1706 if (depth == 0) {
1707 /* there is no tree at all */
1708 return 0;
1709 }
1710
1711 if (ex != EXT_FIRST_EXTENT(eh)) {
1712 /* we correct tree if first leaf got modified only */
1713 return 0;
1714 }
1715
1716 /*
1717 * TODO: we need correction if border is smaller than current one
1718 */
1719 k = depth - 1;
1720 border = path[depth].p_ext->ee_block;
1721 err = ext4_ext_get_access(handle, inode, path + k);
1722 if (err)
1723 return err;
1724 path[k].p_idx->ei_block = border;
1725 err = ext4_ext_dirty(handle, inode, path + k);
1726 if (err)
1727 return err;
1728
1729 while (k--) {
1730 /* change all left-side indexes */
1731 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1732 break;
1733 err = ext4_ext_get_access(handle, inode, path + k);
1734 if (err)
1735 break;
1736 path[k].p_idx->ei_block = border;
1737 err = ext4_ext_dirty(handle, inode, path + k);
1738 if (err)
1739 break;
1740 }
1741
1742 return err;
1743 }
1744
1745 int
1746 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1747 struct ext4_extent *ex2)
1748 {
1749 unsigned short ext1_ee_len, ext2_ee_len;
1750
1751 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1752 return 0;
1753
1754 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1755 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1756
1757 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1758 le32_to_cpu(ex2->ee_block))
1759 return 0;
1760
1761 /*
1762 * To allow future support for preallocated extents to be added
1763 * as an RO_COMPAT feature, refuse to merge to extents if
1764 * this can result in the top bit of ee_len being set.
1765 */
1766 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1767 return 0;
1768 /*
1769 * The check for IO to unwritten extent is somewhat racy as we
1770 * increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
1771 * dropping i_data_sem. But reserved blocks should save us in that
1772 * case.
1773 */
1774 if (ext4_ext_is_unwritten(ex1) &&
1775 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1776 atomic_read(&EXT4_I(inode)->i_unwritten) ||
1777 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
1778 return 0;
1779 #ifdef AGGRESSIVE_TEST
1780 if (ext1_ee_len >= 4)
1781 return 0;
1782 #endif
1783
1784 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1785 return 1;
1786 return 0;
1787 }
1788
1789 /*
1790 * This function tries to merge the "ex" extent to the next extent in the tree.
1791 * It always tries to merge towards right. If you want to merge towards
1792 * left, pass "ex - 1" as argument instead of "ex".
1793 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1794 * 1 if they got merged.
1795 */
1796 static int ext4_ext_try_to_merge_right(struct inode *inode,
1797 struct ext4_ext_path *path,
1798 struct ext4_extent *ex)
1799 {
1800 struct ext4_extent_header *eh;
1801 unsigned int depth, len;
1802 int merge_done = 0, unwritten;
1803
1804 depth = ext_depth(inode);
1805 BUG_ON(path[depth].p_hdr == NULL);
1806 eh = path[depth].p_hdr;
1807
1808 while (ex < EXT_LAST_EXTENT(eh)) {
1809 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1810 break;
1811 /* merge with next extent! */
1812 unwritten = ext4_ext_is_unwritten(ex);
1813 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1814 + ext4_ext_get_actual_len(ex + 1));
1815 if (unwritten)
1816 ext4_ext_mark_unwritten(ex);
1817
1818 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1819 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1820 * sizeof(struct ext4_extent);
1821 memmove(ex + 1, ex + 2, len);
1822 }
1823 le16_add_cpu(&eh->eh_entries, -1);
1824 merge_done = 1;
1825 WARN_ON(eh->eh_entries == 0);
1826 if (!eh->eh_entries)
1827 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1828 }
1829
1830 return merge_done;
1831 }
1832
1833 /*
1834 * This function does a very simple check to see if we can collapse
1835 * an extent tree with a single extent tree leaf block into the inode.
1836 */
1837 static void ext4_ext_try_to_merge_up(handle_t *handle,
1838 struct inode *inode,
1839 struct ext4_ext_path *path)
1840 {
1841 size_t s;
1842 unsigned max_root = ext4_ext_space_root(inode, 0);
1843 ext4_fsblk_t blk;
1844
1845 if ((path[0].p_depth != 1) ||
1846 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1847 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1848 return;
1849
1850 /*
1851 * We need to modify the block allocation bitmap and the block
1852 * group descriptor to release the extent tree block. If we
1853 * can't get the journal credits, give up.
1854 */
1855 if (ext4_journal_extend(handle, 2))
1856 return;
1857
1858 /*
1859 * Copy the extent data up to the inode
1860 */
1861 blk = ext4_idx_pblock(path[0].p_idx);
1862 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1863 sizeof(struct ext4_extent_idx);
1864 s += sizeof(struct ext4_extent_header);
1865
1866 path[1].p_maxdepth = path[0].p_maxdepth;
1867 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1868 path[0].p_depth = 0;
1869 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1870 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1871 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1872
1873 brelse(path[1].p_bh);
1874 ext4_free_blocks(handle, inode, NULL, blk, 1,
1875 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1876 }
1877
1878 /*
1879 * This function tries to merge the @ex extent to neighbours in the tree.
1880 * return 1 if merge left else 0.
1881 */
1882 static void ext4_ext_try_to_merge(handle_t *handle,
1883 struct inode *inode,
1884 struct ext4_ext_path *path,
1885 struct ext4_extent *ex) {
1886 struct ext4_extent_header *eh;
1887 unsigned int depth;
1888 int merge_done = 0;
1889
1890 depth = ext_depth(inode);
1891 BUG_ON(path[depth].p_hdr == NULL);
1892 eh = path[depth].p_hdr;
1893
1894 if (ex > EXT_FIRST_EXTENT(eh))
1895 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1896
1897 if (!merge_done)
1898 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1899
1900 ext4_ext_try_to_merge_up(handle, inode, path);
1901 }
1902
1903 /*
1904 * check if a portion of the "newext" extent overlaps with an
1905 * existing extent.
1906 *
1907 * If there is an overlap discovered, it updates the length of the newext
1908 * such that there will be no overlap, and then returns 1.
1909 * If there is no overlap found, it returns 0.
1910 */
1911 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1912 struct inode *inode,
1913 struct ext4_extent *newext,
1914 struct ext4_ext_path *path)
1915 {
1916 ext4_lblk_t b1, b2;
1917 unsigned int depth, len1;
1918 unsigned int ret = 0;
1919
1920 b1 = le32_to_cpu(newext->ee_block);
1921 len1 = ext4_ext_get_actual_len(newext);
1922 depth = ext_depth(inode);
1923 if (!path[depth].p_ext)
1924 goto out;
1925 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1926
1927 /*
1928 * get the next allocated block if the extent in the path
1929 * is before the requested block(s)
1930 */
1931 if (b2 < b1) {
1932 b2 = ext4_ext_next_allocated_block(path);
1933 if (b2 == EXT_MAX_BLOCKS)
1934 goto out;
1935 b2 = EXT4_LBLK_CMASK(sbi, b2);
1936 }
1937
1938 /* check for wrap through zero on extent logical start block*/
1939 if (b1 + len1 < b1) {
1940 len1 = EXT_MAX_BLOCKS - b1;
1941 newext->ee_len = cpu_to_le16(len1);
1942 ret = 1;
1943 }
1944
1945 /* check for overlap */
1946 if (b1 + len1 > b2) {
1947 newext->ee_len = cpu_to_le16(b2 - b1);
1948 ret = 1;
1949 }
1950 out:
1951 return ret;
1952 }
1953
1954 /*
1955 * ext4_ext_insert_extent:
1956 * tries to merge requsted extent into the existing extent or
1957 * inserts requested extent as new one into the tree,
1958 * creating new leaf in the no-space case.
1959 */
1960 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1961 struct ext4_ext_path **ppath,
1962 struct ext4_extent *newext, int gb_flags)
1963 {
1964 struct ext4_ext_path *path = *ppath;
1965 struct ext4_extent_header *eh;
1966 struct ext4_extent *ex, *fex;
1967 struct ext4_extent *nearex; /* nearest extent */
1968 struct ext4_ext_path *npath = NULL;
1969 int depth, len, err;
1970 ext4_lblk_t next;
1971 int mb_flags = 0, unwritten;
1972
1973 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1974 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1975 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1976 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1977 return -EFSCORRUPTED;
1978 }
1979 depth = ext_depth(inode);
1980 ex = path[depth].p_ext;
1981 eh = path[depth].p_hdr;
1982 if (unlikely(path[depth].p_hdr == NULL)) {
1983 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1984 return -EFSCORRUPTED;
1985 }
1986
1987 /* try to insert block into found extent and return */
1988 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1989
1990 /*
1991 * Try to see whether we should rather test the extent on
1992 * right from ex, or from the left of ex. This is because
1993 * ext4_find_extent() can return either extent on the
1994 * left, or on the right from the searched position. This
1995 * will make merging more effective.
1996 */
1997 if (ex < EXT_LAST_EXTENT(eh) &&
1998 (le32_to_cpu(ex->ee_block) +
1999 ext4_ext_get_actual_len(ex) <
2000 le32_to_cpu(newext->ee_block))) {
2001 ex += 1;
2002 goto prepend;
2003 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2004 (le32_to_cpu(newext->ee_block) +
2005 ext4_ext_get_actual_len(newext) <
2006 le32_to_cpu(ex->ee_block)))
2007 ex -= 1;
2008
2009 /* Try to append newex to the ex */
2010 if (ext4_can_extents_be_merged(inode, ex, newext)) {
2011 ext_debug("append [%d]%d block to %u:[%d]%d"
2012 "(from %llu)\n",
2013 ext4_ext_is_unwritten(newext),
2014 ext4_ext_get_actual_len(newext),
2015 le32_to_cpu(ex->ee_block),
2016 ext4_ext_is_unwritten(ex),
2017 ext4_ext_get_actual_len(ex),
2018 ext4_ext_pblock(ex));
2019 err = ext4_ext_get_access(handle, inode,
2020 path + depth);
2021 if (err)
2022 return err;
2023 unwritten = ext4_ext_is_unwritten(ex);
2024 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2025 + ext4_ext_get_actual_len(newext));
2026 if (unwritten)
2027 ext4_ext_mark_unwritten(ex);
2028 eh = path[depth].p_hdr;
2029 nearex = ex;
2030 goto merge;
2031 }
2032
2033 prepend:
2034 /* Try to prepend newex to the ex */
2035 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2036 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2037 "(from %llu)\n",
2038 le32_to_cpu(newext->ee_block),
2039 ext4_ext_is_unwritten(newext),
2040 ext4_ext_get_actual_len(newext),
2041 le32_to_cpu(ex->ee_block),
2042 ext4_ext_is_unwritten(ex),
2043 ext4_ext_get_actual_len(ex),
2044 ext4_ext_pblock(ex));
2045 err = ext4_ext_get_access(handle, inode,
2046 path + depth);
2047 if (err)
2048 return err;
2049
2050 unwritten = ext4_ext_is_unwritten(ex);
2051 ex->ee_block = newext->ee_block;
2052 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2053 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2054 + ext4_ext_get_actual_len(newext));
2055 if (unwritten)
2056 ext4_ext_mark_unwritten(ex);
2057 eh = path[depth].p_hdr;
2058 nearex = ex;
2059 goto merge;
2060 }
2061 }
2062
2063 depth = ext_depth(inode);
2064 eh = path[depth].p_hdr;
2065 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2066 goto has_space;
2067
2068 /* probably next leaf has space for us? */
2069 fex = EXT_LAST_EXTENT(eh);
2070 next = EXT_MAX_BLOCKS;
2071 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2072 next = ext4_ext_next_leaf_block(path);
2073 if (next != EXT_MAX_BLOCKS) {
2074 ext_debug("next leaf block - %u\n", next);
2075 BUG_ON(npath != NULL);
2076 npath = ext4_find_extent(inode, next, NULL, 0);
2077 if (IS_ERR(npath))
2078 return PTR_ERR(npath);
2079 BUG_ON(npath->p_depth != path->p_depth);
2080 eh = npath[depth].p_hdr;
2081 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
2082 ext_debug("next leaf isn't full(%d)\n",
2083 le16_to_cpu(eh->eh_entries));
2084 path = npath;
2085 goto has_space;
2086 }
2087 ext_debug("next leaf has no free space(%d,%d)\n",
2088 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2089 }
2090
2091 /*
2092 * There is no free space in the found leaf.
2093 * We're gonna add a new leaf in the tree.
2094 */
2095 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2096 mb_flags |= EXT4_MB_USE_RESERVED;
2097 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2098 ppath, newext);
2099 if (err)
2100 goto cleanup;
2101 depth = ext_depth(inode);
2102 eh = path[depth].p_hdr;
2103
2104 has_space:
2105 nearex = path[depth].p_ext;
2106
2107 err = ext4_ext_get_access(handle, inode, path + depth);
2108 if (err)
2109 goto cleanup;
2110
2111 if (!nearex) {
2112 /* there is no extent in this leaf, create first one */
2113 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
2114 le32_to_cpu(newext->ee_block),
2115 ext4_ext_pblock(newext),
2116 ext4_ext_is_unwritten(newext),
2117 ext4_ext_get_actual_len(newext));
2118 nearex = EXT_FIRST_EXTENT(eh);
2119 } else {
2120 if (le32_to_cpu(newext->ee_block)
2121 > le32_to_cpu(nearex->ee_block)) {
2122 /* Insert after */
2123 ext_debug("insert %u:%llu:[%d]%d before: "
2124 "nearest %p\n",
2125 le32_to_cpu(newext->ee_block),
2126 ext4_ext_pblock(newext),
2127 ext4_ext_is_unwritten(newext),
2128 ext4_ext_get_actual_len(newext),
2129 nearex);
2130 nearex++;
2131 } else {
2132 /* Insert before */
2133 BUG_ON(newext->ee_block == nearex->ee_block);
2134 ext_debug("insert %u:%llu:[%d]%d after: "
2135 "nearest %p\n",
2136 le32_to_cpu(newext->ee_block),
2137 ext4_ext_pblock(newext),
2138 ext4_ext_is_unwritten(newext),
2139 ext4_ext_get_actual_len(newext),
2140 nearex);
2141 }
2142 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2143 if (len > 0) {
2144 ext_debug("insert %u:%llu:[%d]%d: "
2145 "move %d extents from 0x%p to 0x%p\n",
2146 le32_to_cpu(newext->ee_block),
2147 ext4_ext_pblock(newext),
2148 ext4_ext_is_unwritten(newext),
2149 ext4_ext_get_actual_len(newext),
2150 len, nearex, nearex + 1);
2151 memmove(nearex + 1, nearex,
2152 len * sizeof(struct ext4_extent));
2153 }
2154 }
2155
2156 le16_add_cpu(&eh->eh_entries, 1);
2157 path[depth].p_ext = nearex;
2158 nearex->ee_block = newext->ee_block;
2159 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2160 nearex->ee_len = newext->ee_len;
2161
2162 merge:
2163 /* try to merge extents */
2164 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2165 ext4_ext_try_to_merge(handle, inode, path, nearex);
2166
2167
2168 /* time to correct all indexes above */
2169 err = ext4_ext_correct_indexes(handle, inode, path);
2170 if (err)
2171 goto cleanup;
2172
2173 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2174
2175 cleanup:
2176 ext4_ext_drop_refs(npath);
2177 kfree(npath);
2178 return err;
2179 }
2180
2181 static int ext4_fill_fiemap_extents(struct inode *inode,
2182 ext4_lblk_t block, ext4_lblk_t num,
2183 struct fiemap_extent_info *fieinfo)
2184 {
2185 struct ext4_ext_path *path = NULL;
2186 struct ext4_extent *ex;
2187 struct extent_status es;
2188 ext4_lblk_t next, next_del, start = 0, end = 0;
2189 ext4_lblk_t last = block + num;
2190 int exists, depth = 0, err = 0;
2191 unsigned int flags = 0;
2192 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2193
2194 while (block < last && block != EXT_MAX_BLOCKS) {
2195 num = last - block;
2196 /* find extent for this block */
2197 down_read(&EXT4_I(inode)->i_data_sem);
2198
2199 path = ext4_find_extent(inode, block, &path, 0);
2200 if (IS_ERR(path)) {
2201 up_read(&EXT4_I(inode)->i_data_sem);
2202 err = PTR_ERR(path);
2203 path = NULL;
2204 break;
2205 }
2206
2207 depth = ext_depth(inode);
2208 if (unlikely(path[depth].p_hdr == NULL)) {
2209 up_read(&EXT4_I(inode)->i_data_sem);
2210 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2211 err = -EFSCORRUPTED;
2212 break;
2213 }
2214 ex = path[depth].p_ext;
2215 next = ext4_ext_next_allocated_block(path);
2216
2217 flags = 0;
2218 exists = 0;
2219 if (!ex) {
2220 /* there is no extent yet, so try to allocate
2221 * all requested space */
2222 start = block;
2223 end = block + num;
2224 } else if (le32_to_cpu(ex->ee_block) > block) {
2225 /* need to allocate space before found extent */
2226 start = block;
2227 end = le32_to_cpu(ex->ee_block);
2228 if (block + num < end)
2229 end = block + num;
2230 } else if (block >= le32_to_cpu(ex->ee_block)
2231 + ext4_ext_get_actual_len(ex)) {
2232 /* need to allocate space after found extent */
2233 start = block;
2234 end = block + num;
2235 if (end >= next)
2236 end = next;
2237 } else if (block >= le32_to_cpu(ex->ee_block)) {
2238 /*
2239 * some part of requested space is covered
2240 * by found extent
2241 */
2242 start = block;
2243 end = le32_to_cpu(ex->ee_block)
2244 + ext4_ext_get_actual_len(ex);
2245 if (block + num < end)
2246 end = block + num;
2247 exists = 1;
2248 } else {
2249 BUG();
2250 }
2251 BUG_ON(end <= start);
2252
2253 if (!exists) {
2254 es.es_lblk = start;
2255 es.es_len = end - start;
2256 es.es_pblk = 0;
2257 } else {
2258 es.es_lblk = le32_to_cpu(ex->ee_block);
2259 es.es_len = ext4_ext_get_actual_len(ex);
2260 es.es_pblk = ext4_ext_pblock(ex);
2261 if (ext4_ext_is_unwritten(ex))
2262 flags |= FIEMAP_EXTENT_UNWRITTEN;
2263 }
2264
2265 /*
2266 * Find delayed extent and update es accordingly. We call
2267 * it even in !exists case to find out whether es is the
2268 * last existing extent or not.
2269 */
2270 next_del = ext4_find_delayed_extent(inode, &es);
2271 if (!exists && next_del) {
2272 exists = 1;
2273 flags |= (FIEMAP_EXTENT_DELALLOC |
2274 FIEMAP_EXTENT_UNKNOWN);
2275 }
2276 up_read(&EXT4_I(inode)->i_data_sem);
2277
2278 if (unlikely(es.es_len == 0)) {
2279 EXT4_ERROR_INODE(inode, "es.es_len == 0");
2280 err = -EFSCORRUPTED;
2281 break;
2282 }
2283
2284 /*
2285 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2286 * we need to check next == EXT_MAX_BLOCKS because it is
2287 * possible that an extent is with unwritten and delayed
2288 * status due to when an extent is delayed allocated and
2289 * is allocated by fallocate status tree will track both of
2290 * them in a extent.
2291 *
2292 * So we could return a unwritten and delayed extent, and
2293 * its block is equal to 'next'.
2294 */
2295 if (next == next_del && next == EXT_MAX_BLOCKS) {
2296 flags |= FIEMAP_EXTENT_LAST;
2297 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2298 next != EXT_MAX_BLOCKS)) {
2299 EXT4_ERROR_INODE(inode,
2300 "next extent == %u, next "
2301 "delalloc extent = %u",
2302 next, next_del);
2303 err = -EFSCORRUPTED;
2304 break;
2305 }
2306 }
2307
2308 if (exists) {
2309 err = fiemap_fill_next_extent(fieinfo,
2310 (__u64)es.es_lblk << blksize_bits,
2311 (__u64)es.es_pblk << blksize_bits,
2312 (__u64)es.es_len << blksize_bits,
2313 flags);
2314 if (err < 0)
2315 break;
2316 if (err == 1) {
2317 err = 0;
2318 break;
2319 }
2320 }
2321
2322 block = es.es_lblk + es.es_len;
2323 }
2324
2325 ext4_ext_drop_refs(path);
2326 kfree(path);
2327 return err;
2328 }
2329
2330 /*
2331 * ext4_ext_determine_hole - determine hole around given block
2332 * @inode: inode we lookup in
2333 * @path: path in extent tree to @lblk
2334 * @lblk: pointer to logical block around which we want to determine hole
2335 *
2336 * Determine hole length (and start if easily possible) around given logical
2337 * block. We don't try too hard to find the beginning of the hole but @path
2338 * actually points to extent before @lblk, we provide it.
2339 *
2340 * The function returns the length of a hole starting at @lblk. We update @lblk
2341 * to the beginning of the hole if we managed to find it.
2342 */
2343 static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2344 struct ext4_ext_path *path,
2345 ext4_lblk_t *lblk)
2346 {
2347 int depth = ext_depth(inode);
2348 struct ext4_extent *ex;
2349 ext4_lblk_t len;
2350
2351 ex = path[depth].p_ext;
2352 if (ex == NULL) {
2353 /* there is no extent yet, so gap is [0;-] */
2354 *lblk = 0;
2355 len = EXT_MAX_BLOCKS;
2356 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2357 len = le32_to_cpu(ex->ee_block) - *lblk;
2358 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2359 + ext4_ext_get_actual_len(ex)) {
2360 ext4_lblk_t next;
2361
2362 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2363 next = ext4_ext_next_allocated_block(path);
2364 BUG_ON(next == *lblk);
2365 len = next - *lblk;
2366 } else {
2367 BUG();
2368 }
2369 return len;
2370 }
2371
2372 /*
2373 * ext4_ext_put_gap_in_cache:
2374 * calculate boundaries of the gap that the requested block fits into
2375 * and cache this gap
2376 */
2377 static void
2378 ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2379 ext4_lblk_t hole_len)
2380 {
2381 struct extent_status es;
2382
2383 ext4_es_find_delayed_extent_range(inode, hole_start,
2384 hole_start + hole_len - 1, &es);
2385 if (es.es_len) {
2386 /* There's delayed extent containing lblock? */
2387 if (es.es_lblk <= hole_start)
2388 return;
2389 hole_len = min(es.es_lblk - hole_start, hole_len);
2390 }
2391 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2392 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2393 EXTENT_STATUS_HOLE);
2394 }
2395
2396 /*
2397 * ext4_ext_rm_idx:
2398 * removes index from the index block.
2399 */
2400 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2401 struct ext4_ext_path *path, int depth)
2402 {
2403 int err;
2404 ext4_fsblk_t leaf;
2405
2406 /* free index block */
2407 depth--;
2408 path = path + depth;
2409 leaf = ext4_idx_pblock(path->p_idx);
2410 if (unlikely(path->p_hdr->eh_entries == 0)) {
2411 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2412 return -EFSCORRUPTED;
2413 }
2414 err = ext4_ext_get_access(handle, inode, path);
2415 if (err)
2416 return err;
2417
2418 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2419 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2420 len *= sizeof(struct ext4_extent_idx);
2421 memmove(path->p_idx, path->p_idx + 1, len);
2422 }
2423
2424 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2425 err = ext4_ext_dirty(handle, inode, path);
2426 if (err)
2427 return err;
2428 ext_debug("index is empty, remove it, free block %llu\n", leaf);
2429 trace_ext4_ext_rm_idx(inode, leaf);
2430
2431 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2432 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2433
2434 while (--depth >= 0) {
2435 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2436 break;
2437 path--;
2438 err = ext4_ext_get_access(handle, inode, path);
2439 if (err)
2440 break;
2441 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2442 err = ext4_ext_dirty(handle, inode, path);
2443 if (err)
2444 break;
2445 }
2446 return err;
2447 }
2448
2449 /*
2450 * ext4_ext_calc_credits_for_single_extent:
2451 * This routine returns max. credits that needed to insert an extent
2452 * to the extent tree.
2453 * When pass the actual path, the caller should calculate credits
2454 * under i_data_sem.
2455 */
2456 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2457 struct ext4_ext_path *path)
2458 {
2459 if (path) {
2460 int depth = ext_depth(inode);
2461 int ret = 0;
2462
2463 /* probably there is space in leaf? */
2464 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2465 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2466
2467 /*
2468 * There are some space in the leaf tree, no
2469 * need to account for leaf block credit
2470 *
2471 * bitmaps and block group descriptor blocks
2472 * and other metadata blocks still need to be
2473 * accounted.
2474 */
2475 /* 1 bitmap, 1 block group descriptor */
2476 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2477 return ret;
2478 }
2479 }
2480
2481 return ext4_chunk_trans_blocks(inode, nrblocks);
2482 }
2483
2484 /*
2485 * How many index/leaf blocks need to change/allocate to add @extents extents?
2486 *
2487 * If we add a single extent, then in the worse case, each tree level
2488 * index/leaf need to be changed in case of the tree split.
2489 *
2490 * If more extents are inserted, they could cause the whole tree split more
2491 * than once, but this is really rare.
2492 */
2493 int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2494 {
2495 int index;
2496 int depth;
2497
2498 /* If we are converting the inline data, only one is needed here. */
2499 if (ext4_has_inline_data(inode))
2500 return 1;
2501
2502 depth = ext_depth(inode);
2503
2504 if (extents <= 1)
2505 index = depth * 2;
2506 else
2507 index = depth * 3;
2508
2509 return index;
2510 }
2511
2512 static inline int get_default_free_blocks_flags(struct inode *inode)
2513 {
2514 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2515 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2516 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2517 else if (ext4_should_journal_data(inode))
2518 return EXT4_FREE_BLOCKS_FORGET;
2519 return 0;
2520 }
2521
2522 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2523 struct ext4_extent *ex,
2524 long long *partial_cluster,
2525 ext4_lblk_t from, ext4_lblk_t to)
2526 {
2527 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2528 unsigned short ee_len = ext4_ext_get_actual_len(ex);
2529 ext4_fsblk_t pblk;
2530 int flags = get_default_free_blocks_flags(inode);
2531
2532 /*
2533 * For bigalloc file systems, we never free a partial cluster
2534 * at the beginning of the extent. Instead, we make a note
2535 * that we tried freeing the cluster, and check to see if we
2536 * need to free it on a subsequent call to ext4_remove_blocks,
2537 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2538 */
2539 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2540
2541 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2542 /*
2543 * If we have a partial cluster, and it's different from the
2544 * cluster of the last block, we need to explicitly free the
2545 * partial cluster here.
2546 */
2547 pblk = ext4_ext_pblock(ex) + ee_len - 1;
2548 if (*partial_cluster > 0 &&
2549 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2550 ext4_free_blocks(handle, inode, NULL,
2551 EXT4_C2B(sbi, *partial_cluster),
2552 sbi->s_cluster_ratio, flags);
2553 *partial_cluster = 0;
2554 }
2555
2556 #ifdef EXTENTS_STATS
2557 {
2558 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2559 spin_lock(&sbi->s_ext_stats_lock);
2560 sbi->s_ext_blocks += ee_len;
2561 sbi->s_ext_extents++;
2562 if (ee_len < sbi->s_ext_min)
2563 sbi->s_ext_min = ee_len;
2564 if (ee_len > sbi->s_ext_max)
2565 sbi->s_ext_max = ee_len;
2566 if (ext_depth(inode) > sbi->s_depth_max)
2567 sbi->s_depth_max = ext_depth(inode);
2568 spin_unlock(&sbi->s_ext_stats_lock);
2569 }
2570 #endif
2571 if (from >= le32_to_cpu(ex->ee_block)
2572 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2573 /* tail removal */
2574 ext4_lblk_t num;
2575 long long first_cluster;
2576
2577 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2578 pblk = ext4_ext_pblock(ex) + ee_len - num;
2579 /*
2580 * Usually we want to free partial cluster at the end of the
2581 * extent, except for the situation when the cluster is still
2582 * used by any other extent (partial_cluster is negative).
2583 */
2584 if (*partial_cluster < 0 &&
2585 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
2586 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2587
2588 ext_debug("free last %u blocks starting %llu partial %lld\n",
2589 num, pblk, *partial_cluster);
2590 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2591 /*
2592 * If the block range to be freed didn't start at the
2593 * beginning of a cluster, and we removed the entire
2594 * extent and the cluster is not used by any other extent,
2595 * save the partial cluster here, since we might need to
2596 * delete if we determine that the truncate or punch hole
2597 * operation has removed all of the blocks in the cluster.
2598 * If that cluster is used by another extent, preserve its
2599 * negative value so it isn't freed later on.
2600 *
2601 * If the whole extent wasn't freed, we've reached the
2602 * start of the truncated/punched region and have finished
2603 * removing blocks. If there's a partial cluster here it's
2604 * shared with the remainder of the extent and is no longer
2605 * a candidate for removal.
2606 */
2607 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2608 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2609 if (first_cluster != -*partial_cluster)
2610 *partial_cluster = first_cluster;
2611 } else {
2612 *partial_cluster = 0;
2613 }
2614 } else
2615 ext4_error(sbi->s_sb, "strange request: removal(2) "
2616 "%u-%u from %u:%u",
2617 from, to, le32_to_cpu(ex->ee_block), ee_len);
2618 return 0;
2619 }
2620
2621
2622 /*
2623 * ext4_ext_rm_leaf() Removes the extents associated with the
2624 * blocks appearing between "start" and "end". Both "start"
2625 * and "end" must appear in the same extent or EIO is returned.
2626 *
2627 * @handle: The journal handle
2628 * @inode: The files inode
2629 * @path: The path to the leaf
2630 * @partial_cluster: The cluster which we'll have to free if all extents
2631 * has been released from it. However, if this value is
2632 * negative, it's a cluster just to the right of the
2633 * punched region and it must not be freed.
2634 * @start: The first block to remove
2635 * @end: The last block to remove
2636 */
2637 static int
2638 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2639 struct ext4_ext_path *path,
2640 long long *partial_cluster,
2641 ext4_lblk_t start, ext4_lblk_t end)
2642 {
2643 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2644 int err = 0, correct_index = 0;
2645 int depth = ext_depth(inode), credits;
2646 struct ext4_extent_header *eh;
2647 ext4_lblk_t a, b;
2648 unsigned num;
2649 ext4_lblk_t ex_ee_block;
2650 unsigned short ex_ee_len;
2651 unsigned unwritten = 0;
2652 struct ext4_extent *ex;
2653 ext4_fsblk_t pblk;
2654
2655 /* the header must be checked already in ext4_ext_remove_space() */
2656 ext_debug("truncate since %u in leaf to %u\n", start, end);
2657 if (!path[depth].p_hdr)
2658 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2659 eh = path[depth].p_hdr;
2660 if (unlikely(path[depth].p_hdr == NULL)) {
2661 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2662 return -EFSCORRUPTED;
2663 }
2664 /* find where to start removing */
2665 ex = path[depth].p_ext;
2666 if (!ex)
2667 ex = EXT_LAST_EXTENT(eh);
2668
2669 ex_ee_block = le32_to_cpu(ex->ee_block);
2670 ex_ee_len = ext4_ext_get_actual_len(ex);
2671
2672 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2673
2674 while (ex >= EXT_FIRST_EXTENT(eh) &&
2675 ex_ee_block + ex_ee_len > start) {
2676
2677 if (ext4_ext_is_unwritten(ex))
2678 unwritten = 1;
2679 else
2680 unwritten = 0;
2681
2682 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2683 unwritten, ex_ee_len);
2684 path[depth].p_ext = ex;
2685
2686 a = ex_ee_block > start ? ex_ee_block : start;
2687 b = ex_ee_block+ex_ee_len - 1 < end ?
2688 ex_ee_block+ex_ee_len - 1 : end;
2689
2690 ext_debug(" border %u:%u\n", a, b);
2691
2692 /* If this extent is beyond the end of the hole, skip it */
2693 if (end < ex_ee_block) {
2694 /*
2695 * We're going to skip this extent and move to another,
2696 * so note that its first cluster is in use to avoid
2697 * freeing it when removing blocks. Eventually, the
2698 * right edge of the truncated/punched region will
2699 * be just to the left.
2700 */
2701 if (sbi->s_cluster_ratio > 1) {
2702 pblk = ext4_ext_pblock(ex);
2703 *partial_cluster =
2704 -(long long) EXT4_B2C(sbi, pblk);
2705 }
2706 ex--;
2707 ex_ee_block = le32_to_cpu(ex->ee_block);
2708 ex_ee_len = ext4_ext_get_actual_len(ex);
2709 continue;
2710 } else if (b != ex_ee_block + ex_ee_len - 1) {
2711 EXT4_ERROR_INODE(inode,
2712 "can not handle truncate %u:%u "
2713 "on extent %u:%u",
2714 start, end, ex_ee_block,
2715 ex_ee_block + ex_ee_len - 1);
2716 err = -EFSCORRUPTED;
2717 goto out;
2718 } else if (a != ex_ee_block) {
2719 /* remove tail of the extent */
2720 num = a - ex_ee_block;
2721 } else {
2722 /* remove whole extent: excellent! */
2723 num = 0;
2724 }
2725 /*
2726 * 3 for leaf, sb, and inode plus 2 (bmap and group
2727 * descriptor) for each block group; assume two block
2728 * groups plus ex_ee_len/blocks_per_block_group for
2729 * the worst case
2730 */
2731 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2732 if (ex == EXT_FIRST_EXTENT(eh)) {
2733 correct_index = 1;
2734 credits += (ext_depth(inode)) + 1;
2735 }
2736 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2737
2738 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2739 if (err)
2740 goto out;
2741
2742 err = ext4_ext_get_access(handle, inode, path + depth);
2743 if (err)
2744 goto out;
2745
2746 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2747 a, b);
2748 if (err)
2749 goto out;
2750
2751 if (num == 0)
2752 /* this extent is removed; mark slot entirely unused */
2753 ext4_ext_store_pblock(ex, 0);
2754
2755 ex->ee_len = cpu_to_le16(num);
2756 /*
2757 * Do not mark unwritten if all the blocks in the
2758 * extent have been removed.
2759 */
2760 if (unwritten && num)
2761 ext4_ext_mark_unwritten(ex);
2762 /*
2763 * If the extent was completely released,
2764 * we need to remove it from the leaf
2765 */
2766 if (num == 0) {
2767 if (end != EXT_MAX_BLOCKS - 1) {
2768 /*
2769 * For hole punching, we need to scoot all the
2770 * extents up when an extent is removed so that
2771 * we dont have blank extents in the middle
2772 */
2773 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2774 sizeof(struct ext4_extent));
2775
2776 /* Now get rid of the one at the end */
2777 memset(EXT_LAST_EXTENT(eh), 0,
2778 sizeof(struct ext4_extent));
2779 }
2780 le16_add_cpu(&eh->eh_entries, -1);
2781 }
2782
2783 err = ext4_ext_dirty(handle, inode, path + depth);
2784 if (err)
2785 goto out;
2786
2787 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2788 ext4_ext_pblock(ex));
2789 ex--;
2790 ex_ee_block = le32_to_cpu(ex->ee_block);
2791 ex_ee_len = ext4_ext_get_actual_len(ex);
2792 }
2793
2794 if (correct_index && eh->eh_entries)
2795 err = ext4_ext_correct_indexes(handle, inode, path);
2796
2797 /*
2798 * If there's a partial cluster and at least one extent remains in
2799 * the leaf, free the partial cluster if it isn't shared with the
2800 * current extent. If it is shared with the current extent
2801 * we zero partial_cluster because we've reached the start of the
2802 * truncated/punched region and we're done removing blocks.
2803 */
2804 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2805 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2806 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2807 ext4_free_blocks(handle, inode, NULL,
2808 EXT4_C2B(sbi, *partial_cluster),
2809 sbi->s_cluster_ratio,
2810 get_default_free_blocks_flags(inode));
2811 }
2812 *partial_cluster = 0;
2813 }
2814
2815 /* if this leaf is free, then we should
2816 * remove it from index block above */
2817 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2818 err = ext4_ext_rm_idx(handle, inode, path, depth);
2819
2820 out:
2821 return err;
2822 }
2823
2824 /*
2825 * ext4_ext_more_to_rm:
2826 * returns 1 if current index has to be freed (even partial)
2827 */
2828 static int
2829 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2830 {
2831 BUG_ON(path->p_idx == NULL);
2832
2833 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2834 return 0;
2835
2836 /*
2837 * if truncate on deeper level happened, it wasn't partial,
2838 * so we have to consider current index for truncation
2839 */
2840 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2841 return 0;
2842 return 1;
2843 }
2844
2845 int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2846 ext4_lblk_t end)
2847 {
2848 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2849 int depth = ext_depth(inode);
2850 struct ext4_ext_path *path = NULL;
2851 long long partial_cluster = 0;
2852 handle_t *handle;
2853 int i = 0, err = 0;
2854
2855 ext_debug("truncate since %u to %u\n", start, end);
2856
2857 /* probably first extent we're gonna free will be last in block */
2858 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
2859 if (IS_ERR(handle))
2860 return PTR_ERR(handle);
2861
2862 again:
2863 trace_ext4_ext_remove_space(inode, start, end, depth);
2864
2865 /*
2866 * Check if we are removing extents inside the extent tree. If that
2867 * is the case, we are going to punch a hole inside the extent tree
2868 * so we have to check whether we need to split the extent covering
2869 * the last block to remove so we can easily remove the part of it
2870 * in ext4_ext_rm_leaf().
2871 */
2872 if (end < EXT_MAX_BLOCKS - 1) {
2873 struct ext4_extent *ex;
2874 ext4_lblk_t ee_block, ex_end, lblk;
2875 ext4_fsblk_t pblk;
2876
2877 /* find extent for or closest extent to this block */
2878 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
2879 if (IS_ERR(path)) {
2880 ext4_journal_stop(handle);
2881 return PTR_ERR(path);
2882 }
2883 depth = ext_depth(inode);
2884 /* Leaf not may not exist only if inode has no blocks at all */
2885 ex = path[depth].p_ext;
2886 if (!ex) {
2887 if (depth) {
2888 EXT4_ERROR_INODE(inode,
2889 "path[%d].p_hdr == NULL",
2890 depth);
2891 err = -EFSCORRUPTED;
2892 }
2893 goto out;
2894 }
2895
2896 ee_block = le32_to_cpu(ex->ee_block);
2897 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2898
2899 /*
2900 * See if the last block is inside the extent, if so split
2901 * the extent at 'end' block so we can easily remove the
2902 * tail of the first part of the split extent in
2903 * ext4_ext_rm_leaf().
2904 */
2905 if (end >= ee_block && end < ex_end) {
2906
2907 /*
2908 * If we're going to split the extent, note that
2909 * the cluster containing the block after 'end' is
2910 * in use to avoid freeing it when removing blocks.
2911 */
2912 if (sbi->s_cluster_ratio > 1) {
2913 pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
2914 partial_cluster =
2915 -(long long) EXT4_B2C(sbi, pblk);
2916 }
2917
2918 /*
2919 * Split the extent in two so that 'end' is the last
2920 * block in the first new extent. Also we should not
2921 * fail removing space due to ENOSPC so try to use
2922 * reserved block if that happens.
2923 */
2924 err = ext4_force_split_extent_at(handle, inode, &path,
2925 end + 1, 1);
2926 if (err < 0)
2927 goto out;
2928
2929 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2930 /*
2931 * If there's an extent to the right its first cluster
2932 * contains the immediate right boundary of the
2933 * truncated/punched region. Set partial_cluster to
2934 * its negative value so it won't be freed if shared
2935 * with the current extent. The end < ee_block case
2936 * is handled in ext4_ext_rm_leaf().
2937 */
2938 lblk = ex_end + 1;
2939 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2940 &ex);
2941 if (err)
2942 goto out;
2943 if (pblk)
2944 partial_cluster =
2945 -(long long) EXT4_B2C(sbi, pblk);
2946 }
2947 }
2948 /*
2949 * We start scanning from right side, freeing all the blocks
2950 * after i_size and walking into the tree depth-wise.
2951 */
2952 depth = ext_depth(inode);
2953 if (path) {
2954 int k = i = depth;
2955 while (--k > 0)
2956 path[k].p_block =
2957 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2958 } else {
2959 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2960 GFP_NOFS);
2961 if (path == NULL) {
2962 ext4_journal_stop(handle);
2963 return -ENOMEM;
2964 }
2965 path[0].p_maxdepth = path[0].p_depth = depth;
2966 path[0].p_hdr = ext_inode_hdr(inode);
2967 i = 0;
2968
2969 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2970 err = -EFSCORRUPTED;
2971 goto out;
2972 }
2973 }
2974 err = 0;
2975
2976 while (i >= 0 && err == 0) {
2977 if (i == depth) {
2978 /* this is leaf block */
2979 err = ext4_ext_rm_leaf(handle, inode, path,
2980 &partial_cluster, start,
2981 end);
2982 /* root level has p_bh == NULL, brelse() eats this */
2983 brelse(path[i].p_bh);
2984 path[i].p_bh = NULL;
2985 i--;
2986 continue;
2987 }
2988
2989 /* this is index block */
2990 if (!path[i].p_hdr) {
2991 ext_debug("initialize header\n");
2992 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2993 }
2994
2995 if (!path[i].p_idx) {
2996 /* this level hasn't been touched yet */
2997 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2998 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2999 ext_debug("init index ptr: hdr 0x%p, num %d\n",
3000 path[i].p_hdr,
3001 le16_to_cpu(path[i].p_hdr->eh_entries));
3002 } else {
3003 /* we were already here, see at next index */
3004 path[i].p_idx--;
3005 }
3006
3007 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
3008 i, EXT_FIRST_INDEX(path[i].p_hdr),
3009 path[i].p_idx);
3010 if (ext4_ext_more_to_rm(path + i)) {
3011 struct buffer_head *bh;
3012 /* go to the next level */
3013 ext_debug("move to level %d (block %llu)\n",
3014 i + 1, ext4_idx_pblock(path[i].p_idx));
3015 memset(path + i + 1, 0, sizeof(*path));
3016 bh = read_extent_tree_block(inode,
3017 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
3018 EXT4_EX_NOCACHE);
3019 if (IS_ERR(bh)) {
3020 /* should we reset i_size? */
3021 err = PTR_ERR(bh);
3022 break;
3023 }
3024 /* Yield here to deal with large extent trees.
3025 * Should be a no-op if we did IO above. */
3026 cond_resched();
3027 if (WARN_ON(i + 1 > depth)) {
3028 err = -EFSCORRUPTED;
3029 break;
3030 }
3031 path[i + 1].p_bh = bh;
3032
3033 /* save actual number of indexes since this
3034 * number is changed at the next iteration */
3035 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3036 i++;
3037 } else {
3038 /* we finished processing this index, go up */
3039 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3040 /* index is empty, remove it;
3041 * handle must be already prepared by the
3042 * truncatei_leaf() */
3043 err = ext4_ext_rm_idx(handle, inode, path, i);
3044 }
3045 /* root level has p_bh == NULL, brelse() eats this */
3046 brelse(path[i].p_bh);
3047 path[i].p_bh = NULL;
3048 i--;
3049 ext_debug("return to level %d\n", i);
3050 }
3051 }
3052
3053 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3054 partial_cluster, path->p_hdr->eh_entries);
3055
3056 /*
3057 * If we still have something in the partial cluster and we have removed
3058 * even the first extent, then we should free the blocks in the partial
3059 * cluster as well. (This code will only run when there are no leaves
3060 * to the immediate left of the truncated/punched region.)
3061 */
3062 if (partial_cluster > 0 && err == 0) {
3063 /* don't zero partial_cluster since it's not used afterwards */
3064 ext4_free_blocks(handle, inode, NULL,
3065 EXT4_C2B(sbi, partial_cluster),
3066 sbi->s_cluster_ratio,
3067 get_default_free_blocks_flags(inode));
3068 }
3069
3070 /* TODO: flexible tree reduction should be here */
3071 if (path->p_hdr->eh_entries == 0) {
3072 /*
3073 * truncate to zero freed all the tree,
3074 * so we need to correct eh_depth
3075 */
3076 err = ext4_ext_get_access(handle, inode, path);
3077 if (err == 0) {
3078 ext_inode_hdr(inode)->eh_depth = 0;
3079 ext_inode_hdr(inode)->eh_max =
3080 cpu_to_le16(ext4_ext_space_root(inode, 0));
3081 err = ext4_ext_dirty(handle, inode, path);
3082 }
3083 }
3084 out:
3085 ext4_ext_drop_refs(path);
3086 kfree(path);
3087 path = NULL;
3088 if (err == -EAGAIN)
3089 goto again;
3090 ext4_journal_stop(handle);
3091
3092 return err;
3093 }
3094
3095 /*
3096 * called at mount time
3097 */
3098 void ext4_ext_init(struct super_block *sb)
3099 {
3100 /*
3101 * possible initialization would be here
3102 */
3103
3104 if (ext4_has_feature_extents(sb)) {
3105 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3106 printk(KERN_INFO "EXT4-fs: file extents enabled"
3107 #ifdef AGGRESSIVE_TEST
3108 ", aggressive tests"
3109 #endif
3110 #ifdef CHECK_BINSEARCH
3111 ", check binsearch"
3112 #endif
3113 #ifdef EXTENTS_STATS
3114 ", stats"
3115 #endif
3116 "\n");
3117 #endif
3118 #ifdef EXTENTS_STATS
3119 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3120 EXT4_SB(sb)->s_ext_min = 1 << 30;
3121 EXT4_SB(sb)->s_ext_max = 0;
3122 #endif
3123 }
3124 }
3125
3126 /*
3127 * called at umount time
3128 */
3129 void ext4_ext_release(struct super_block *sb)
3130 {
3131 if (!ext4_has_feature_extents(sb))
3132 return;
3133
3134 #ifdef EXTENTS_STATS
3135 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3136 struct ext4_sb_info *sbi = EXT4_SB(sb);
3137 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3138 sbi->s_ext_blocks, sbi->s_ext_extents,
3139 sbi->s_ext_blocks / sbi->s_ext_extents);
3140 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3141 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3142 }
3143 #endif
3144 }
3145
3146 static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3147 {
3148 ext4_lblk_t ee_block;
3149 ext4_fsblk_t ee_pblock;
3150 unsigned int ee_len;
3151
3152 ee_block = le32_to_cpu(ex->ee_block);
3153 ee_len = ext4_ext_get_actual_len(ex);
3154 ee_pblock = ext4_ext_pblock(ex);
3155
3156 if (ee_len == 0)
3157 return 0;
3158
3159 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3160 EXTENT_STATUS_WRITTEN);
3161 }
3162
3163 /* FIXME!! we need to try to merge to left or right after zero-out */
3164 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3165 {
3166 ext4_fsblk_t ee_pblock;
3167 unsigned int ee_len;
3168
3169 ee_len = ext4_ext_get_actual_len(ex);
3170 ee_pblock = ext4_ext_pblock(ex);
3171 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3172 ee_len);
3173 }
3174
3175 /*
3176 * ext4_split_extent_at() splits an extent at given block.
3177 *
3178 * @handle: the journal handle
3179 * @inode: the file inode
3180 * @path: the path to the extent
3181 * @split: the logical block where the extent is splitted.
3182 * @split_flags: indicates if the extent could be zeroout if split fails, and
3183 * the states(init or unwritten) of new extents.
3184 * @flags: flags used to insert new extent to extent tree.
3185 *
3186 *
3187 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3188 * of which are deterimined by split_flag.
3189 *
3190 * There are two cases:
3191 * a> the extent are splitted into two extent.
3192 * b> split is not needed, and just mark the extent.
3193 *
3194 * return 0 on success.
3195 */
3196 static int ext4_split_extent_at(handle_t *handle,
3197 struct inode *inode,
3198 struct ext4_ext_path **ppath,
3199 ext4_lblk_t split,
3200 int split_flag,
3201 int flags)
3202 {
3203 struct ext4_ext_path *path = *ppath;
3204 ext4_fsblk_t newblock;
3205 ext4_lblk_t ee_block;
3206 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3207 struct ext4_extent *ex2 = NULL;
3208 unsigned int ee_len, depth;
3209 int err = 0;
3210
3211 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3212 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3213
3214 ext_debug("ext4_split_extents_at: inode %lu, logical"
3215 "block %llu\n", inode->i_ino, (unsigned long long)split);
3216
3217 ext4_ext_show_leaf(inode, path);
3218
3219 depth = ext_depth(inode);
3220 ex = path[depth].p_ext;
3221 ee_block = le32_to_cpu(ex->ee_block);
3222 ee_len = ext4_ext_get_actual_len(ex);
3223 newblock = split - ee_block + ext4_ext_pblock(ex);
3224
3225 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3226 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3227 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3228 EXT4_EXT_MARK_UNWRIT1 |
3229 EXT4_EXT_MARK_UNWRIT2));
3230
3231 err = ext4_ext_get_access(handle, inode, path + depth);
3232 if (err)
3233 goto out;
3234
3235 if (split == ee_block) {
3236 /*
3237 * case b: block @split is the block that the extent begins with
3238 * then we just change the state of the extent, and splitting
3239 * is not needed.
3240 */
3241 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3242 ext4_ext_mark_unwritten(ex);
3243 else
3244 ext4_ext_mark_initialized(ex);
3245
3246 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3247 ext4_ext_try_to_merge(handle, inode, path, ex);
3248
3249 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3250 goto out;
3251 }
3252
3253 /* case a */
3254 memcpy(&orig_ex, ex, sizeof(orig_ex));
3255 ex->ee_len = cpu_to_le16(split - ee_block);
3256 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3257 ext4_ext_mark_unwritten(ex);
3258
3259 /*
3260 * path may lead to new leaf, not to original leaf any more
3261 * after ext4_ext_insert_extent() returns,
3262 */
3263 err = ext4_ext_dirty(handle, inode, path + depth);
3264 if (err)
3265 goto fix_extent_len;
3266
3267 ex2 = &newex;
3268 ex2->ee_block = cpu_to_le32(split);
3269 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3270 ext4_ext_store_pblock(ex2, newblock);
3271 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3272 ext4_ext_mark_unwritten(ex2);
3273
3274 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
3275 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3276 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3277 if (split_flag & EXT4_EXT_DATA_VALID1) {
3278 err = ext4_ext_zeroout(inode, ex2);
3279 zero_ex.ee_block = ex2->ee_block;
3280 zero_ex.ee_len = cpu_to_le16(
3281 ext4_ext_get_actual_len(ex2));
3282 ext4_ext_store_pblock(&zero_ex,
3283 ext4_ext_pblock(ex2));
3284 } else {
3285 err = ext4_ext_zeroout(inode, ex);
3286 zero_ex.ee_block = ex->ee_block;
3287 zero_ex.ee_len = cpu_to_le16(
3288 ext4_ext_get_actual_len(ex));
3289 ext4_ext_store_pblock(&zero_ex,
3290 ext4_ext_pblock(ex));
3291 }
3292 } else {
3293 err = ext4_ext_zeroout(inode, &orig_ex);
3294 zero_ex.ee_block = orig_ex.ee_block;
3295 zero_ex.ee_len = cpu_to_le16(
3296 ext4_ext_get_actual_len(&orig_ex));
3297 ext4_ext_store_pblock(&zero_ex,
3298 ext4_ext_pblock(&orig_ex));
3299 }
3300
3301 if (err)
3302 goto fix_extent_len;
3303 /* update the extent length and mark as initialized */
3304 ex->ee_len = cpu_to_le16(ee_len);
3305 ext4_ext_try_to_merge(handle, inode, path, ex);
3306 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3307 if (err)
3308 goto fix_extent_len;
3309
3310 /* update extent status tree */
3311 err = ext4_zeroout_es(inode, &zero_ex);
3312
3313 goto out;
3314 } else if (err)
3315 goto fix_extent_len;
3316
3317 out:
3318 ext4_ext_show_leaf(inode, path);
3319 return err;
3320
3321 fix_extent_len:
3322 ex->ee_len = orig_ex.ee_len;
3323 ext4_ext_dirty(handle, inode, path + path->p_depth);
3324 return err;
3325 }
3326
3327 /*
3328 * ext4_split_extents() splits an extent and mark extent which is covered
3329 * by @map as split_flags indicates
3330 *
3331 * It may result in splitting the extent into multiple extents (up to three)
3332 * There are three possibilities:
3333 * a> There is no split required
3334 * b> Splits in two extents: Split is happening at either end of the extent
3335 * c> Splits in three extents: Somone is splitting in middle of the extent
3336 *
3337 */
3338 static int ext4_split_extent(handle_t *handle,
3339 struct inode *inode,
3340 struct ext4_ext_path **ppath,
3341 struct ext4_map_blocks *map,
3342 int split_flag,
3343 int flags)
3344 {
3345 struct ext4_ext_path *path = *ppath;
3346 ext4_lblk_t ee_block;
3347 struct ext4_extent *ex;
3348 unsigned int ee_len, depth;
3349 int err = 0;
3350 int unwritten;
3351 int split_flag1, flags1;
3352 int allocated = map->m_len;
3353
3354 depth = ext_depth(inode);
3355 ex = path[depth].p_ext;
3356 ee_block = le32_to_cpu(ex->ee_block);
3357 ee_len = ext4_ext_get_actual_len(ex);
3358 unwritten = ext4_ext_is_unwritten(ex);
3359
3360 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3361 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3362 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3363 if (unwritten)
3364 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3365 EXT4_EXT_MARK_UNWRIT2;
3366 if (split_flag & EXT4_EXT_DATA_VALID2)
3367 split_flag1 |= EXT4_EXT_DATA_VALID1;
3368 err = ext4_split_extent_at(handle, inode, ppath,
3369 map->m_lblk + map->m_len, split_flag1, flags1);
3370 if (err)
3371 goto out;
3372 } else {
3373 allocated = ee_len - (map->m_lblk - ee_block);
3374 }
3375 /*
3376 * Update path is required because previous ext4_split_extent_at() may
3377 * result in split of original leaf or extent zeroout.
3378 */
3379 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3380 if (IS_ERR(path))
3381 return PTR_ERR(path);
3382 depth = ext_depth(inode);
3383 ex = path[depth].p_ext;
3384 if (!ex) {
3385 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3386 (unsigned long) map->m_lblk);
3387 return -EFSCORRUPTED;
3388 }
3389 unwritten = ext4_ext_is_unwritten(ex);
3390 split_flag1 = 0;
3391
3392 if (map->m_lblk >= ee_block) {
3393 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3394 if (unwritten) {
3395 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3396 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3397 EXT4_EXT_MARK_UNWRIT2);
3398 }
3399 err = ext4_split_extent_at(handle, inode, ppath,
3400 map->m_lblk, split_flag1, flags);
3401 if (err)
3402 goto out;
3403 }
3404
3405 ext4_ext_show_leaf(inode, path);
3406 out:
3407 return err ? err : allocated;
3408 }
3409
3410 /*
3411 * This function is called by ext4_ext_map_blocks() if someone tries to write
3412 * to an unwritten extent. It may result in splitting the unwritten
3413 * extent into multiple extents (up to three - one initialized and two
3414 * unwritten).
3415 * There are three possibilities:
3416 * a> There is no split required: Entire extent should be initialized
3417 * b> Splits in two extents: Write is happening at either end of the extent
3418 * c> Splits in three extents: Somone is writing in middle of the extent
3419 *
3420 * Pre-conditions:
3421 * - The extent pointed to by 'path' is unwritten.
3422 * - The extent pointed to by 'path' contains a superset
3423 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3424 *
3425 * Post-conditions on success:
3426 * - the returned value is the number of blocks beyond map->l_lblk
3427 * that are allocated and initialized.
3428 * It is guaranteed to be >= map->m_len.
3429 */
3430 static int ext4_ext_convert_to_initialized(handle_t *handle,
3431 struct inode *inode,
3432 struct ext4_map_blocks *map,
3433 struct ext4_ext_path **ppath,
3434 int flags)
3435 {
3436 struct ext4_ext_path *path = *ppath;
3437 struct ext4_sb_info *sbi;
3438 struct ext4_extent_header *eh;
3439 struct ext4_map_blocks split_map;
3440 struct ext4_extent zero_ex1, zero_ex2;
3441 struct ext4_extent *ex, *abut_ex;
3442 ext4_lblk_t ee_block, eof_block;
3443 unsigned int ee_len, depth, map_len = map->m_len;
3444 int allocated = 0, max_zeroout = 0;
3445 int err = 0;
3446 int split_flag = EXT4_EXT_DATA_VALID2;
3447
3448 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3449 "block %llu, max_blocks %u\n", inode->i_ino,
3450 (unsigned long long)map->m_lblk, map_len);
3451
3452 sbi = EXT4_SB(inode->i_sb);
3453 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3454 inode->i_sb->s_blocksize_bits;
3455 if (eof_block < map->m_lblk + map_len)
3456 eof_block = map->m_lblk + map_len;
3457
3458 depth = ext_depth(inode);
3459 eh = path[depth].p_hdr;
3460 ex = path[depth].p_ext;
3461 ee_block = le32_to_cpu(ex->ee_block);
3462 ee_len = ext4_ext_get_actual_len(ex);
3463 zero_ex1.ee_len = 0;
3464 zero_ex2.ee_len = 0;
3465
3466 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3467
3468 /* Pre-conditions */
3469 BUG_ON(!ext4_ext_is_unwritten(ex));
3470 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3471
3472 /*
3473 * Attempt to transfer newly initialized blocks from the currently
3474 * unwritten extent to its neighbor. This is much cheaper
3475 * than an insertion followed by a merge as those involve costly
3476 * memmove() calls. Transferring to the left is the common case in
3477 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3478 * followed by append writes.
3479 *
3480 * Limitations of the current logic:
3481 * - L1: we do not deal with writes covering the whole extent.
3482 * This would require removing the extent if the transfer
3483 * is possible.
3484 * - L2: we only attempt to merge with an extent stored in the
3485 * same extent tree node.
3486 */
3487 if ((map->m_lblk == ee_block) &&
3488 /* See if we can merge left */
3489 (map_len < ee_len) && /*L1*/
3490 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3491 ext4_lblk_t prev_lblk;
3492 ext4_fsblk_t prev_pblk, ee_pblk;
3493 unsigned int prev_len;
3494
3495 abut_ex = ex - 1;
3496 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3497 prev_len = ext4_ext_get_actual_len(abut_ex);
3498 prev_pblk = ext4_ext_pblock(abut_ex);
3499 ee_pblk = ext4_ext_pblock(ex);
3500
3501 /*
3502 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3503 * upon those conditions:
3504 * - C1: abut_ex is initialized,
3505 * - C2: abut_ex is logically abutting ex,
3506 * - C3: abut_ex is physically abutting ex,
3507 * - C4: abut_ex can receive the additional blocks without
3508 * overflowing the (initialized) length limit.
3509 */
3510 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3511 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3512 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3513 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3514 err = ext4_ext_get_access(handle, inode, path + depth);
3515 if (err)
3516 goto out;
3517
3518 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3519 map, ex, abut_ex);
3520
3521 /* Shift the start of ex by 'map_len' blocks */
3522 ex->ee_block = cpu_to_le32(ee_block + map_len);
3523 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3524 ex->ee_len = cpu_to_le16(ee_len - map_len);
3525 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3526
3527 /* Extend abut_ex by 'map_len' blocks */
3528 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3529
3530 /* Result: number of initialized blocks past m_lblk */
3531 allocated = map_len;
3532 }
3533 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3534 (map_len < ee_len) && /*L1*/
3535 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3536 /* See if we can merge right */
3537 ext4_lblk_t next_lblk;
3538 ext4_fsblk_t next_pblk, ee_pblk;
3539 unsigned int next_len;
3540
3541 abut_ex = ex + 1;
3542 next_lblk = le32_to_cpu(abut_ex->ee_block);
3543 next_len = ext4_ext_get_actual_len(abut_ex);
3544 next_pblk = ext4_ext_pblock(abut_ex);
3545 ee_pblk = ext4_ext_pblock(ex);
3546
3547 /*
3548 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3549 * upon those conditions:
3550 * - C1: abut_ex is initialized,
3551 * - C2: abut_ex is logically abutting ex,
3552 * - C3: abut_ex is physically abutting ex,
3553 * - C4: abut_ex can receive the additional blocks without
3554 * overflowing the (initialized) length limit.
3555 */
3556 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3557 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3558 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3559 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3560 err = ext4_ext_get_access(handle, inode, path + depth);
3561 if (err)
3562 goto out;
3563
3564 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3565 map, ex, abut_ex);
3566
3567 /* Shift the start of abut_ex by 'map_len' blocks */
3568 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3569 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3570 ex->ee_len = cpu_to_le16(ee_len - map_len);
3571 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3572
3573 /* Extend abut_ex by 'map_len' blocks */
3574 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3575
3576 /* Result: number of initialized blocks past m_lblk */
3577 allocated = map_len;
3578 }
3579 }
3580 if (allocated) {
3581 /* Mark the block containing both extents as dirty */
3582 ext4_ext_dirty(handle, inode, path + depth);
3583
3584 /* Update path to point to the right extent */
3585 path[depth].p_ext = abut_ex;
3586 goto out;
3587 } else
3588 allocated = ee_len - (map->m_lblk - ee_block);
3589
3590 WARN_ON(map->m_lblk < ee_block);
3591 /*
3592 * It is safe to convert extent to initialized via explicit
3593 * zeroout only if extent is fully inside i_size or new_size.
3594 */
3595 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3596
3597 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3598 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3599 (inode->i_sb->s_blocksize_bits - 10);
3600
3601 if (ext4_encrypted_inode(inode))
3602 max_zeroout = 0;
3603
3604 /*
3605 * five cases:
3606 * 1. split the extent into three extents.
3607 * 2. split the extent into two extents, zeroout the head of the first
3608 * extent.
3609 * 3. split the extent into two extents, zeroout the tail of the second
3610 * extent.
3611 * 4. split the extent into two extents with out zeroout.
3612 * 5. no splitting needed, just possibly zeroout the head and / or the
3613 * tail of the extent.
3614 */
3615 split_map.m_lblk = map->m_lblk;
3616 split_map.m_len = map->m_len;
3617
3618 if (max_zeroout && (allocated > split_map.m_len)) {
3619 if (allocated <= max_zeroout) {
3620 /* case 3 or 5 */
3621 zero_ex1.ee_block =
3622 cpu_to_le32(split_map.m_lblk +
3623 split_map.m_len);
3624 zero_ex1.ee_len =
3625 cpu_to_le16(allocated - split_map.m_len);
3626 ext4_ext_store_pblock(&zero_ex1,
3627 ext4_ext_pblock(ex) + split_map.m_lblk +
3628 split_map.m_len - ee_block);
3629 err = ext4_ext_zeroout(inode, &zero_ex1);
3630 if (err)
3631 goto out;
3632 split_map.m_len = allocated;
3633 }
3634 if (split_map.m_lblk - ee_block + split_map.m_len <
3635 max_zeroout) {
3636 /* case 2 or 5 */
3637 if (split_map.m_lblk != ee_block) {
3638 zero_ex2.ee_block = ex->ee_block;
3639 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3640 ee_block);
3641 ext4_ext_store_pblock(&zero_ex2,
3642 ext4_ext_pblock(ex));
3643 err = ext4_ext_zeroout(inode, &zero_ex2);
3644 if (err)
3645 goto out;
3646 }
3647
3648 split_map.m_len += split_map.m_lblk - ee_block;
3649 split_map.m_lblk = ee_block;
3650 allocated = map->m_len;
3651 }
3652 }
3653
3654 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3655 flags);
3656 if (err > 0)
3657 err = 0;
3658 out:
3659 /* If we have gotten a failure, don't zero out status tree */
3660 if (!err) {
3661 err = ext4_zeroout_es(inode, &zero_ex1);
3662 if (!err)
3663 err = ext4_zeroout_es(inode, &zero_ex2);
3664 }
3665 return err ? err : allocated;
3666 }
3667
3668 /*
3669 * This function is called by ext4_ext_map_blocks() from
3670 * ext4_get_blocks_dio_write() when DIO to write
3671 * to an unwritten extent.
3672 *
3673 * Writing to an unwritten extent may result in splitting the unwritten
3674 * extent into multiple initialized/unwritten extents (up to three)
3675 * There are three possibilities:
3676 * a> There is no split required: Entire extent should be unwritten
3677 * b> Splits in two extents: Write is happening at either end of the extent
3678 * c> Splits in three extents: Somone is writing in middle of the extent
3679 *
3680 * This works the same way in the case of initialized -> unwritten conversion.
3681 *
3682 * One of more index blocks maybe needed if the extent tree grow after
3683 * the unwritten extent split. To prevent ENOSPC occur at the IO
3684 * complete, we need to split the unwritten extent before DIO submit
3685 * the IO. The unwritten extent called at this time will be split
3686 * into three unwritten extent(at most). After IO complete, the part
3687 * being filled will be convert to initialized by the end_io callback function
3688 * via ext4_convert_unwritten_extents().
3689 *
3690 * Returns the size of unwritten extent to be written on success.
3691 */
3692 static int ext4_split_convert_extents(handle_t *handle,
3693 struct inode *inode,
3694 struct ext4_map_blocks *map,
3695 struct ext4_ext_path **ppath,
3696 int flags)
3697 {
3698 struct ext4_ext_path *path = *ppath;
3699 ext4_lblk_t eof_block;
3700 ext4_lblk_t ee_block;
3701 struct ext4_extent *ex;
3702 unsigned int ee_len;
3703 int split_flag = 0, depth;
3704
3705 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3706 __func__, inode->i_ino,
3707 (unsigned long long)map->m_lblk, map->m_len);
3708
3709 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3710 inode->i_sb->s_blocksize_bits;
3711 if (eof_block < map->m_lblk + map->m_len)
3712 eof_block = map->m_lblk + map->m_len;
3713 /*
3714 * It is safe to convert extent to initialized via explicit
3715 * zeroout only if extent is fully insde i_size or new_size.
3716 */
3717 depth = ext_depth(inode);
3718 ex = path[depth].p_ext;
3719 ee_block = le32_to_cpu(ex->ee_block);
3720 ee_len = ext4_ext_get_actual_len(ex);
3721
3722 /* Convert to unwritten */
3723 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3724 split_flag |= EXT4_EXT_DATA_VALID1;
3725 /* Convert to initialized */
3726 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3727 split_flag |= ee_block + ee_len <= eof_block ?
3728 EXT4_EXT_MAY_ZEROOUT : 0;
3729 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3730 }
3731 flags |= EXT4_GET_BLOCKS_PRE_IO;
3732 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3733 }
3734
3735 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3736 struct inode *inode,
3737 struct ext4_map_blocks *map,
3738 struct ext4_ext_path **ppath)
3739 {
3740 struct ext4_ext_path *path = *ppath;
3741 struct ext4_extent *ex;
3742 ext4_lblk_t ee_block;
3743 unsigned int ee_len;
3744 int depth;
3745 int err = 0;
3746
3747 depth = ext_depth(inode);
3748 ex = path[depth].p_ext;
3749 ee_block = le32_to_cpu(ex->ee_block);
3750 ee_len = ext4_ext_get_actual_len(ex);
3751
3752 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3753 "block %llu, max_blocks %u\n", inode->i_ino,
3754 (unsigned long long)ee_block, ee_len);
3755
3756 /* If extent is larger than requested it is a clear sign that we still
3757 * have some extent state machine issues left. So extent_split is still
3758 * required.
3759 * TODO: Once all related issues will be fixed this situation should be
3760 * illegal.
3761 */
3762 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3763 #ifdef CONFIG_EXT4_DEBUG
3764 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3765 " len %u; IO logical block %llu, len %u",
3766 inode->i_ino, (unsigned long long)ee_block, ee_len,
3767 (unsigned long long)map->m_lblk, map->m_len);
3768 #endif
3769 err = ext4_split_convert_extents(handle, inode, map, ppath,
3770 EXT4_GET_BLOCKS_CONVERT);
3771 if (err < 0)
3772 return err;
3773 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3774 if (IS_ERR(path))
3775 return PTR_ERR(path);
3776 depth = ext_depth(inode);
3777 ex = path[depth].p_ext;
3778 }
3779
3780 err = ext4_ext_get_access(handle, inode, path + depth);
3781 if (err)
3782 goto out;
3783 /* first mark the extent as initialized */
3784 ext4_ext_mark_initialized(ex);
3785
3786 /* note: ext4_ext_correct_indexes() isn't needed here because
3787 * borders are not changed
3788 */
3789 ext4_ext_try_to_merge(handle, inode, path, ex);
3790
3791 /* Mark modified extent as dirty */
3792 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3793 out:
3794 ext4_ext_show_leaf(inode, path);
3795 return err;
3796 }
3797
3798 /*
3799 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3800 */
3801 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3802 ext4_lblk_t lblk,
3803 struct ext4_ext_path *path,
3804 unsigned int len)
3805 {
3806 int i, depth;
3807 struct ext4_extent_header *eh;
3808 struct ext4_extent *last_ex;
3809
3810 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3811 return 0;
3812
3813 depth = ext_depth(inode);
3814 eh = path[depth].p_hdr;
3815
3816 /*
3817 * We're going to remove EOFBLOCKS_FL entirely in future so we
3818 * do not care for this case anymore. Simply remove the flag
3819 * if there are no extents.
3820 */
3821 if (unlikely(!eh->eh_entries))
3822 goto out;
3823 last_ex = EXT_LAST_EXTENT(eh);
3824 /*
3825 * We should clear the EOFBLOCKS_FL flag if we are writing the
3826 * last block in the last extent in the file. We test this by
3827 * first checking to see if the caller to
3828 * ext4_ext_get_blocks() was interested in the last block (or
3829 * a block beyond the last block) in the current extent. If
3830 * this turns out to be false, we can bail out from this
3831 * function immediately.
3832 */
3833 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3834 ext4_ext_get_actual_len(last_ex))
3835 return 0;
3836 /*
3837 * If the caller does appear to be planning to write at or
3838 * beyond the end of the current extent, we then test to see
3839 * if the current extent is the last extent in the file, by
3840 * checking to make sure it was reached via the rightmost node
3841 * at each level of the tree.
3842 */
3843 for (i = depth-1; i >= 0; i--)
3844 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3845 return 0;
3846 out:
3847 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3848 return ext4_mark_inode_dirty(handle, inode);
3849 }
3850
3851 /**
3852 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3853 *
3854 * Return 1 if there is a delalloc block in the range, otherwise 0.
3855 */
3856 int ext4_find_delalloc_range(struct inode *inode,
3857 ext4_lblk_t lblk_start,
3858 ext4_lblk_t lblk_end)
3859 {
3860 struct extent_status es;
3861
3862 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
3863 if (es.es_len == 0)
3864 return 0; /* there is no delay extent in this tree */
3865 else if (es.es_lblk <= lblk_start &&
3866 lblk_start < es.es_lblk + es.es_len)
3867 return 1;
3868 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
3869 return 1;
3870 else
3871 return 0;
3872 }
3873
3874 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
3875 {
3876 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3877 ext4_lblk_t lblk_start, lblk_end;
3878 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
3879 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3880
3881 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
3882 }
3883
3884 /**
3885 * Determines how many complete clusters (out of those specified by the 'map')
3886 * are under delalloc and were reserved quota for.
3887 * This function is called when we are writing out the blocks that were
3888 * originally written with their allocation delayed, but then the space was
3889 * allocated using fallocate() before the delayed allocation could be resolved.
3890 * The cases to look for are:
3891 * ('=' indicated delayed allocated blocks
3892 * '-' indicates non-delayed allocated blocks)
3893 * (a) partial clusters towards beginning and/or end outside of allocated range
3894 * are not delalloc'ed.
3895 * Ex:
3896 * |----c---=|====c====|====c====|===-c----|
3897 * |++++++ allocated ++++++|
3898 * ==> 4 complete clusters in above example
3899 *
3900 * (b) partial cluster (outside of allocated range) towards either end is
3901 * marked for delayed allocation. In this case, we will exclude that
3902 * cluster.
3903 * Ex:
3904 * |----====c========|========c========|
3905 * |++++++ allocated ++++++|
3906 * ==> 1 complete clusters in above example
3907 *
3908 * Ex:
3909 * |================c================|
3910 * |++++++ allocated ++++++|
3911 * ==> 0 complete clusters in above example
3912 *
3913 * The ext4_da_update_reserve_space will be called only if we
3914 * determine here that there were some "entire" clusters that span
3915 * this 'allocated' range.
3916 * In the non-bigalloc case, this function will just end up returning num_blks
3917 * without ever calling ext4_find_delalloc_range.
3918 */
3919 static unsigned int
3920 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3921 unsigned int num_blks)
3922 {
3923 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3924 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3925 ext4_lblk_t lblk_from, lblk_to, c_offset;
3926 unsigned int allocated_clusters = 0;
3927
3928 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3929 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3930
3931 /* max possible clusters for this allocation */
3932 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3933
3934 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3935
3936 /* Check towards left side */
3937 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
3938 if (c_offset) {
3939 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
3940 lblk_to = lblk_from + c_offset - 1;
3941
3942 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3943 allocated_clusters--;
3944 }
3945
3946 /* Now check towards right. */
3947 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
3948 if (allocated_clusters && c_offset) {
3949 lblk_from = lblk_start + num_blks;
3950 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3951
3952 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
3953 allocated_clusters--;
3954 }
3955
3956 return allocated_clusters;
3957 }
3958
3959 static int
3960 convert_initialized_extent(handle_t *handle, struct inode *inode,
3961 struct ext4_map_blocks *map,
3962 struct ext4_ext_path **ppath,
3963 unsigned int allocated)
3964 {
3965 struct ext4_ext_path *path = *ppath;
3966 struct ext4_extent *ex;
3967 ext4_lblk_t ee_block;
3968 unsigned int ee_len;
3969 int depth;
3970 int err = 0;
3971
3972 /*
3973 * Make sure that the extent is no bigger than we support with
3974 * unwritten extent
3975 */
3976 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3977 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3978
3979 depth = ext_depth(inode);
3980 ex = path[depth].p_ext;
3981 ee_block = le32_to_cpu(ex->ee_block);
3982 ee_len = ext4_ext_get_actual_len(ex);
3983
3984 ext_debug("%s: inode %lu, logical"
3985 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3986 (unsigned long long)ee_block, ee_len);
3987
3988 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3989 err = ext4_split_convert_extents(handle, inode, map, ppath,
3990 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3991 if (err < 0)
3992 return err;
3993 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3994 if (IS_ERR(path))
3995 return PTR_ERR(path);
3996 depth = ext_depth(inode);
3997 ex = path[depth].p_ext;
3998 if (!ex) {
3999 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4000 (unsigned long) map->m_lblk);
4001 return -EFSCORRUPTED;
4002 }
4003 }
4004
4005 err = ext4_ext_get_access(handle, inode, path + depth);
4006 if (err)
4007 return err;
4008 /* first mark the extent as unwritten */
4009 ext4_ext_mark_unwritten(ex);
4010
4011 /* note: ext4_ext_correct_indexes() isn't needed here because
4012 * borders are not changed
4013 */
4014 ext4_ext_try_to_merge(handle, inode, path, ex);
4015
4016 /* Mark modified extent as dirty */
4017 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4018 if (err)
4019 return err;
4020 ext4_ext_show_leaf(inode, path);
4021
4022 ext4_update_inode_fsync_trans(handle, inode, 1);
4023 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4024 if (err)
4025 return err;
4026 map->m_flags |= EXT4_MAP_UNWRITTEN;
4027 if (allocated > map->m_len)
4028 allocated = map->m_len;
4029 map->m_len = allocated;
4030 return allocated;
4031 }
4032
4033 static int
4034 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4035 struct ext4_map_blocks *map,
4036 struct ext4_ext_path **ppath, int flags,
4037 unsigned int allocated, ext4_fsblk_t newblock)
4038 {
4039 struct ext4_ext_path *path = *ppath;
4040 int ret = 0;
4041 int err = 0;
4042
4043 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4044 "block %llu, max_blocks %u, flags %x, allocated %u\n",
4045 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4046 flags, allocated);
4047 ext4_ext_show_leaf(inode, path);
4048
4049 /*
4050 * When writing into unwritten space, we should not fail to
4051 * allocate metadata blocks for the new extent block if needed.
4052 */
4053 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4054
4055 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4056 allocated, newblock);
4057
4058 /* get_block() before submit the IO, split the extent */
4059 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4060 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4061 flags | EXT4_GET_BLOCKS_CONVERT);
4062 if (ret <= 0)
4063 goto out;
4064 map->m_flags |= EXT4_MAP_UNWRITTEN;
4065 goto out;
4066 }
4067 /* IO end_io complete, convert the filled extent to written */
4068 if (flags & EXT4_GET_BLOCKS_CONVERT) {
4069 if (flags & EXT4_GET_BLOCKS_ZERO) {
4070 if (allocated > map->m_len)
4071 allocated = map->m_len;
4072 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4073 allocated);
4074 if (err < 0)
4075 goto out2;
4076 }
4077 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4078 ppath);
4079 if (ret >= 0) {
4080 ext4_update_inode_fsync_trans(handle, inode, 1);
4081 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4082 path, map->m_len);
4083 } else
4084 err = ret;
4085 map->m_flags |= EXT4_MAP_MAPPED;
4086 map->m_pblk = newblock;
4087 if (allocated > map->m_len)
4088 allocated = map->m_len;
4089 map->m_len = allocated;
4090 goto out2;
4091 }
4092 /* buffered IO case */
4093 /*
4094 * repeat fallocate creation request
4095 * we already have an unwritten extent
4096 */
4097 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4098 map->m_flags |= EXT4_MAP_UNWRITTEN;
4099 goto map_out;
4100 }
4101
4102 /* buffered READ or buffered write_begin() lookup */
4103 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4104 /*
4105 * We have blocks reserved already. We
4106 * return allocated blocks so that delalloc
4107 * won't do block reservation for us. But
4108 * the buffer head will be unmapped so that
4109 * a read from the block returns 0s.
4110 */
4111 map->m_flags |= EXT4_MAP_UNWRITTEN;
4112 goto out1;
4113 }
4114
4115 /* buffered write, writepage time, convert*/
4116 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4117 if (ret >= 0)
4118 ext4_update_inode_fsync_trans(handle, inode, 1);
4119 out:
4120 if (ret <= 0) {
4121 err = ret;
4122 goto out2;
4123 } else
4124 allocated = ret;
4125 map->m_flags |= EXT4_MAP_NEW;
4126 /*
4127 * if we allocated more blocks than requested
4128 * we need to make sure we unmap the extra block
4129 * allocated. The actual needed block will get
4130 * unmapped later when we find the buffer_head marked
4131 * new.
4132 */
4133 if (allocated > map->m_len) {
4134 clean_bdev_aliases(inode->i_sb->s_bdev, newblock + map->m_len,
4135 allocated - map->m_len);
4136 allocated = map->m_len;
4137 }
4138 map->m_len = allocated;
4139
4140 /*
4141 * If we have done fallocate with the offset that is already
4142 * delayed allocated, we would have block reservation
4143 * and quota reservation done in the delayed write path.
4144 * But fallocate would have already updated quota and block
4145 * count for this offset. So cancel these reservation
4146 */
4147 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4148 unsigned int reserved_clusters;
4149 reserved_clusters = get_reserved_cluster_alloc(inode,
4150 map->m_lblk, map->m_len);
4151 if (reserved_clusters)
4152 ext4_da_update_reserve_space(inode,
4153 reserved_clusters,
4154 0);
4155 }
4156
4157 map_out:
4158 map->m_flags |= EXT4_MAP_MAPPED;
4159 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4160 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4161 map->m_len);
4162 if (err < 0)
4163 goto out2;
4164 }
4165 out1:
4166 if (allocated > map->m_len)
4167 allocated = map->m_len;
4168 ext4_ext_show_leaf(inode, path);
4169 map->m_pblk = newblock;
4170 map->m_len = allocated;
4171 out2:
4172 return err ? err : allocated;
4173 }
4174
4175 /*
4176 * get_implied_cluster_alloc - check to see if the requested
4177 * allocation (in the map structure) overlaps with a cluster already
4178 * allocated in an extent.
4179 * @sb The filesystem superblock structure
4180 * @map The requested lblk->pblk mapping
4181 * @ex The extent structure which might contain an implied
4182 * cluster allocation
4183 *
4184 * This function is called by ext4_ext_map_blocks() after we failed to
4185 * find blocks that were already in the inode's extent tree. Hence,
4186 * we know that the beginning of the requested region cannot overlap
4187 * the extent from the inode's extent tree. There are three cases we
4188 * want to catch. The first is this case:
4189 *
4190 * |--- cluster # N--|
4191 * |--- extent ---| |---- requested region ---|
4192 * |==========|
4193 *
4194 * The second case that we need to test for is this one:
4195 *
4196 * |--------- cluster # N ----------------|
4197 * |--- requested region --| |------- extent ----|
4198 * |=======================|
4199 *
4200 * The third case is when the requested region lies between two extents
4201 * within the same cluster:
4202 * |------------- cluster # N-------------|
4203 * |----- ex -----| |---- ex_right ----|
4204 * |------ requested region ------|
4205 * |================|
4206 *
4207 * In each of the above cases, we need to set the map->m_pblk and
4208 * map->m_len so it corresponds to the return the extent labelled as
4209 * "|====|" from cluster #N, since it is already in use for data in
4210 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4211 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4212 * as a new "allocated" block region. Otherwise, we will return 0 and
4213 * ext4_ext_map_blocks() will then allocate one or more new clusters
4214 * by calling ext4_mb_new_blocks().
4215 */
4216 static int get_implied_cluster_alloc(struct super_block *sb,
4217 struct ext4_map_blocks *map,
4218 struct ext4_extent *ex,
4219 struct ext4_ext_path *path)
4220 {
4221 struct ext4_sb_info *sbi = EXT4_SB(sb);
4222 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4223 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4224 ext4_lblk_t rr_cluster_start;
4225 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4226 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4227 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4228
4229 /* The extent passed in that we are trying to match */
4230 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4231 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4232
4233 /* The requested region passed into ext4_map_blocks() */
4234 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4235
4236 if ((rr_cluster_start == ex_cluster_end) ||
4237 (rr_cluster_start == ex_cluster_start)) {
4238 if (rr_cluster_start == ex_cluster_end)
4239 ee_start += ee_len - 1;
4240 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4241 map->m_len = min(map->m_len,
4242 (unsigned) sbi->s_cluster_ratio - c_offset);
4243 /*
4244 * Check for and handle this case:
4245 *
4246 * |--------- cluster # N-------------|
4247 * |------- extent ----|
4248 * |--- requested region ---|
4249 * |===========|
4250 */
4251
4252 if (map->m_lblk < ee_block)
4253 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4254
4255 /*
4256 * Check for the case where there is already another allocated
4257 * block to the right of 'ex' but before the end of the cluster.
4258 *
4259 * |------------- cluster # N-------------|
4260 * |----- ex -----| |---- ex_right ----|
4261 * |------ requested region ------|
4262 * |================|
4263 */
4264 if (map->m_lblk > ee_block) {
4265 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4266 map->m_len = min(map->m_len, next - map->m_lblk);
4267 }
4268
4269 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4270 return 1;
4271 }
4272
4273 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4274 return 0;
4275 }
4276
4277
4278 /*
4279 * Block allocation/map/preallocation routine for extents based files
4280 *
4281 *
4282 * Need to be called with
4283 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4284 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4285 *
4286 * return > 0, number of of blocks already mapped/allocated
4287 * if create == 0 and these are pre-allocated blocks
4288 * buffer head is unmapped
4289 * otherwise blocks are mapped
4290 *
4291 * return = 0, if plain look up failed (blocks have not been allocated)
4292 * buffer head is unmapped
4293 *
4294 * return < 0, error case.
4295 */
4296 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4297 struct ext4_map_blocks *map, int flags)
4298 {
4299 struct ext4_ext_path *path = NULL;
4300 struct ext4_extent newex, *ex, *ex2;
4301 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4302 ext4_fsblk_t newblock = 0;
4303 int free_on_err = 0, err = 0, depth, ret;
4304 unsigned int allocated = 0, offset = 0;
4305 unsigned int allocated_clusters = 0;
4306 struct ext4_allocation_request ar;
4307 ext4_lblk_t cluster_offset;
4308 bool map_from_cluster = false;
4309
4310 ext_debug("blocks %u/%u requested for inode %lu\n",
4311 map->m_lblk, map->m_len, inode->i_ino);
4312 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4313
4314 /* find extent for this block */
4315 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4316 if (IS_ERR(path)) {
4317 err = PTR_ERR(path);
4318 path = NULL;
4319 goto out2;
4320 }
4321
4322 depth = ext_depth(inode);
4323
4324 /*
4325 * consistent leaf must not be empty;
4326 * this situation is possible, though, _during_ tree modification;
4327 * this is why assert can't be put in ext4_find_extent()
4328 */
4329 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4330 EXT4_ERROR_INODE(inode, "bad extent address "
4331 "lblock: %lu, depth: %d pblock %lld",
4332 (unsigned long) map->m_lblk, depth,
4333 path[depth].p_block);
4334 err = -EFSCORRUPTED;
4335 goto out2;
4336 }
4337
4338 ex = path[depth].p_ext;
4339 if (ex) {
4340 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4341 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4342 unsigned short ee_len;
4343
4344
4345 /*
4346 * unwritten extents are treated as holes, except that
4347 * we split out initialized portions during a write.
4348 */
4349 ee_len = ext4_ext_get_actual_len(ex);
4350
4351 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4352
4353 /* if found extent covers block, simply return it */
4354 if (in_range(map->m_lblk, ee_block, ee_len)) {
4355 newblock = map->m_lblk - ee_block + ee_start;
4356 /* number of remaining blocks in the extent */
4357 allocated = ee_len - (map->m_lblk - ee_block);
4358 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4359 ee_block, ee_len, newblock);
4360
4361 /*
4362 * If the extent is initialized check whether the
4363 * caller wants to convert it to unwritten.
4364 */
4365 if ((!ext4_ext_is_unwritten(ex)) &&
4366 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4367 allocated = convert_initialized_extent(
4368 handle, inode, map, &path,
4369 allocated);
4370 goto out2;
4371 } else if (!ext4_ext_is_unwritten(ex))
4372 goto out;
4373
4374 ret = ext4_ext_handle_unwritten_extents(
4375 handle, inode, map, &path, flags,
4376 allocated, newblock);
4377 if (ret < 0)
4378 err = ret;
4379 else
4380 allocated = ret;
4381 goto out2;
4382 }
4383 }
4384
4385 /*
4386 * requested block isn't allocated yet;
4387 * we couldn't try to create block if create flag is zero
4388 */
4389 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4390 ext4_lblk_t hole_start, hole_len;
4391
4392 hole_start = map->m_lblk;
4393 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4394 /*
4395 * put just found gap into cache to speed up
4396 * subsequent requests
4397 */
4398 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4399
4400 /* Update hole_len to reflect hole size after map->m_lblk */
4401 if (hole_start != map->m_lblk)
4402 hole_len -= map->m_lblk - hole_start;
4403 map->m_pblk = 0;
4404 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4405
4406 goto out2;
4407 }
4408
4409 /*
4410 * Okay, we need to do block allocation.
4411 */
4412 newex.ee_block = cpu_to_le32(map->m_lblk);
4413 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4414
4415 /*
4416 * If we are doing bigalloc, check to see if the extent returned
4417 * by ext4_find_extent() implies a cluster we can use.
4418 */
4419 if (cluster_offset && ex &&
4420 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4421 ar.len = allocated = map->m_len;
4422 newblock = map->m_pblk;
4423 map_from_cluster = true;
4424 goto got_allocated_blocks;
4425 }
4426
4427 /* find neighbour allocated blocks */
4428 ar.lleft = map->m_lblk;
4429 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4430 if (err)
4431 goto out2;
4432 ar.lright = map->m_lblk;
4433 ex2 = NULL;
4434 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4435 if (err)
4436 goto out2;
4437
4438 /* Check if the extent after searching to the right implies a
4439 * cluster we can use. */
4440 if ((sbi->s_cluster_ratio > 1) && ex2 &&
4441 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4442 ar.len = allocated = map->m_len;
4443 newblock = map->m_pblk;
4444 map_from_cluster = true;
4445 goto got_allocated_blocks;
4446 }
4447
4448 /*
4449 * See if request is beyond maximum number of blocks we can have in
4450 * a single extent. For an initialized extent this limit is
4451 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4452 * EXT_UNWRITTEN_MAX_LEN.
4453 */
4454 if (map->m_len > EXT_INIT_MAX_LEN &&
4455 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4456 map->m_len = EXT_INIT_MAX_LEN;
4457 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4458 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4459 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4460
4461 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4462 newex.ee_len = cpu_to_le16(map->m_len);
4463 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4464 if (err)
4465 allocated = ext4_ext_get_actual_len(&newex);
4466 else
4467 allocated = map->m_len;
4468
4469 /* allocate new block */
4470 ar.inode = inode;
4471 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4472 ar.logical = map->m_lblk;
4473 /*
4474 * We calculate the offset from the beginning of the cluster
4475 * for the logical block number, since when we allocate a
4476 * physical cluster, the physical block should start at the
4477 * same offset from the beginning of the cluster. This is
4478 * needed so that future calls to get_implied_cluster_alloc()
4479 * work correctly.
4480 */
4481 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4482 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4483 ar.goal -= offset;
4484 ar.logical -= offset;
4485 if (S_ISREG(inode->i_mode))
4486 ar.flags = EXT4_MB_HINT_DATA;
4487 else
4488 /* disable in-core preallocation for non-regular files */
4489 ar.flags = 0;
4490 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4491 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4492 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4493 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4494 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4495 ar.flags |= EXT4_MB_USE_RESERVED;
4496 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4497 if (!newblock)
4498 goto out2;
4499 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4500 ar.goal, newblock, allocated);
4501 free_on_err = 1;
4502 allocated_clusters = ar.len;
4503 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4504 if (ar.len > allocated)
4505 ar.len = allocated;
4506
4507 got_allocated_blocks:
4508 /* try to insert new extent into found leaf and return */
4509 ext4_ext_store_pblock(&newex, newblock + offset);
4510 newex.ee_len = cpu_to_le16(ar.len);
4511 /* Mark unwritten */
4512 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4513 ext4_ext_mark_unwritten(&newex);
4514 map->m_flags |= EXT4_MAP_UNWRITTEN;
4515 }
4516
4517 err = 0;
4518 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4519 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4520 path, ar.len);
4521 if (!err)
4522 err = ext4_ext_insert_extent(handle, inode, &path,
4523 &newex, flags);
4524
4525 if (err && free_on_err) {
4526 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4527 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4528 /* free data blocks we just allocated */
4529 /* not a good idea to call discard here directly,
4530 * but otherwise we'd need to call it every free() */
4531 ext4_discard_preallocations(inode);
4532 ext4_free_blocks(handle, inode, NULL, newblock,
4533 EXT4_C2B(sbi, allocated_clusters), fb_flags);
4534 goto out2;
4535 }
4536
4537 /* previous routine could use block we allocated */
4538 newblock = ext4_ext_pblock(&newex);
4539 allocated = ext4_ext_get_actual_len(&newex);
4540 if (allocated > map->m_len)
4541 allocated = map->m_len;
4542 map->m_flags |= EXT4_MAP_NEW;
4543
4544 /*
4545 * Update reserved blocks/metadata blocks after successful
4546 * block allocation which had been deferred till now.
4547 */
4548 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4549 unsigned int reserved_clusters;
4550 /*
4551 * Check how many clusters we had reserved this allocated range
4552 */
4553 reserved_clusters = get_reserved_cluster_alloc(inode,
4554 map->m_lblk, allocated);
4555 if (!map_from_cluster) {
4556 BUG_ON(allocated_clusters < reserved_clusters);
4557 if (reserved_clusters < allocated_clusters) {
4558 struct ext4_inode_info *ei = EXT4_I(inode);
4559 int reservation = allocated_clusters -
4560 reserved_clusters;
4561 /*
4562 * It seems we claimed few clusters outside of
4563 * the range of this allocation. We should give
4564 * it back to the reservation pool. This can
4565 * happen in the following case:
4566 *
4567 * * Suppose s_cluster_ratio is 4 (i.e., each
4568 * cluster has 4 blocks. Thus, the clusters
4569 * are [0-3],[4-7],[8-11]...
4570 * * First comes delayed allocation write for
4571 * logical blocks 10 & 11. Since there were no
4572 * previous delayed allocated blocks in the
4573 * range [8-11], we would reserve 1 cluster
4574 * for this write.
4575 * * Next comes write for logical blocks 3 to 8.
4576 * In this case, we will reserve 2 clusters
4577 * (for [0-3] and [4-7]; and not for [8-11] as
4578 * that range has a delayed allocated blocks.
4579 * Thus total reserved clusters now becomes 3.
4580 * * Now, during the delayed allocation writeout
4581 * time, we will first write blocks [3-8] and
4582 * allocate 3 clusters for writing these
4583 * blocks. Also, we would claim all these
4584 * three clusters above.
4585 * * Now when we come here to writeout the
4586 * blocks [10-11], we would expect to claim
4587 * the reservation of 1 cluster we had made
4588 * (and we would claim it since there are no
4589 * more delayed allocated blocks in the range
4590 * [8-11]. But our reserved cluster count had
4591 * already gone to 0.
4592 *
4593 * Thus, at the step 4 above when we determine
4594 * that there are still some unwritten delayed
4595 * allocated blocks outside of our current
4596 * block range, we should increment the
4597 * reserved clusters count so that when the
4598 * remaining blocks finally gets written, we
4599 * could claim them.
4600 */
4601 dquot_reserve_block(inode,
4602 EXT4_C2B(sbi, reservation));
4603 spin_lock(&ei->i_block_reservation_lock);
4604 ei->i_reserved_data_blocks += reservation;
4605 spin_unlock(&ei->i_block_reservation_lock);
4606 }
4607 /*
4608 * We will claim quota for all newly allocated blocks.
4609 * We're updating the reserved space *after* the
4610 * correction above so we do not accidentally free
4611 * all the metadata reservation because we might
4612 * actually need it later on.
4613 */
4614 ext4_da_update_reserve_space(inode, allocated_clusters,
4615 1);
4616 }
4617 }
4618
4619 /*
4620 * Cache the extent and update transaction to commit on fdatasync only
4621 * when it is _not_ an unwritten extent.
4622 */
4623 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4624 ext4_update_inode_fsync_trans(handle, inode, 1);
4625 else
4626 ext4_update_inode_fsync_trans(handle, inode, 0);
4627 out:
4628 if (allocated > map->m_len)
4629 allocated = map->m_len;
4630 ext4_ext_show_leaf(inode, path);
4631 map->m_flags |= EXT4_MAP_MAPPED;
4632 map->m_pblk = newblock;
4633 map->m_len = allocated;
4634 out2:
4635 ext4_ext_drop_refs(path);
4636 kfree(path);
4637
4638 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4639 err ? err : allocated);
4640 return err ? err : allocated;
4641 }
4642
4643 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4644 {
4645 struct super_block *sb = inode->i_sb;
4646 ext4_lblk_t last_block;
4647 int err = 0;
4648
4649 /*
4650 * TODO: optimization is possible here.
4651 * Probably we need not scan at all,
4652 * because page truncation is enough.
4653 */
4654
4655 /* we have to know where to truncate from in crash case */
4656 EXT4_I(inode)->i_disksize = inode->i_size;
4657 err = ext4_mark_inode_dirty(handle, inode);
4658 if (err)
4659 return err;
4660
4661 last_block = (inode->i_size + sb->s_blocksize - 1)
4662 >> EXT4_BLOCK_SIZE_BITS(sb);
4663 retry:
4664 err = ext4_es_remove_extent(inode, last_block,
4665 EXT_MAX_BLOCKS - last_block);
4666 if (err == -ENOMEM) {
4667 cond_resched();
4668 congestion_wait(BLK_RW_ASYNC, HZ/50);
4669 goto retry;
4670 }
4671 if (err)
4672 return err;
4673 return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4674 }
4675
4676 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4677 ext4_lblk_t len, loff_t new_size,
4678 int flags)
4679 {
4680 struct inode *inode = file_inode(file);
4681 handle_t *handle;
4682 int ret = 0;
4683 int ret2 = 0;
4684 int retries = 0;
4685 int depth = 0;
4686 struct ext4_map_blocks map;
4687 unsigned int credits;
4688 loff_t epos;
4689
4690 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4691 map.m_lblk = offset;
4692 map.m_len = len;
4693 /*
4694 * Don't normalize the request if it can fit in one extent so
4695 * that it doesn't get unnecessarily split into multiple
4696 * extents.
4697 */
4698 if (len <= EXT_UNWRITTEN_MAX_LEN)
4699 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4700
4701 /*
4702 * credits to insert 1 extent into extent tree
4703 */
4704 credits = ext4_chunk_trans_blocks(inode, len);
4705 depth = ext_depth(inode);
4706
4707 retry:
4708 while (ret >= 0 && len) {
4709 /*
4710 * Recalculate credits when extent tree depth changes.
4711 */
4712 if (depth != ext_depth(inode)) {
4713 credits = ext4_chunk_trans_blocks(inode, len);
4714 depth = ext_depth(inode);
4715 }
4716
4717 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4718 credits);
4719 if (IS_ERR(handle)) {
4720 ret = PTR_ERR(handle);
4721 break;
4722 }
4723 ret = ext4_map_blocks(handle, inode, &map, flags);
4724 if (ret <= 0) {
4725 ext4_debug("inode #%lu: block %u: len %u: "
4726 "ext4_ext_map_blocks returned %d",
4727 inode->i_ino, map.m_lblk,
4728 map.m_len, ret);
4729 ext4_mark_inode_dirty(handle, inode);
4730 ret2 = ext4_journal_stop(handle);
4731 break;
4732 }
4733 map.m_lblk += ret;
4734 map.m_len = len = len - ret;
4735 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4736 inode->i_ctime = current_time(inode);
4737 if (new_size) {
4738 if (epos > new_size)
4739 epos = new_size;
4740 if (ext4_update_inode_size(inode, epos) & 0x1)
4741 inode->i_mtime = inode->i_ctime;
4742 } else {
4743 if (epos > inode->i_size)
4744 ext4_set_inode_flag(inode,
4745 EXT4_INODE_EOFBLOCKS);
4746 }
4747 ext4_mark_inode_dirty(handle, inode);
4748 ext4_update_inode_fsync_trans(handle, inode, 1);
4749 ret2 = ext4_journal_stop(handle);
4750 if (ret2)
4751 break;
4752 }
4753 if (ret == -ENOSPC &&
4754 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4755 ret = 0;
4756 goto retry;
4757 }
4758
4759 return ret > 0 ? ret2 : ret;
4760 }
4761
4762 static long ext4_zero_range(struct file *file, loff_t offset,
4763 loff_t len, int mode)
4764 {
4765 struct inode *inode = file_inode(file);
4766 handle_t *handle = NULL;
4767 unsigned int max_blocks;
4768 loff_t new_size = 0;
4769 int ret = 0;
4770 int flags;
4771 int credits;
4772 int partial_begin, partial_end;
4773 loff_t start, end;
4774 ext4_lblk_t lblk;
4775 unsigned int blkbits = inode->i_blkbits;
4776
4777 trace_ext4_zero_range(inode, offset, len, mode);
4778
4779 if (!S_ISREG(inode->i_mode))
4780 return -EINVAL;
4781
4782 /* Call ext4_force_commit to flush all data in case of data=journal. */
4783 if (ext4_should_journal_data(inode)) {
4784 ret = ext4_force_commit(inode->i_sb);
4785 if (ret)
4786 return ret;
4787 }
4788
4789 /*
4790 * Round up offset. This is not fallocate, we neet to zero out
4791 * blocks, so convert interior block aligned part of the range to
4792 * unwritten and possibly manually zero out unaligned parts of the
4793 * range.
4794 */
4795 start = round_up(offset, 1 << blkbits);
4796 end = round_down((offset + len), 1 << blkbits);
4797
4798 if (start < offset || end > offset + len)
4799 return -EINVAL;
4800 partial_begin = offset & ((1 << blkbits) - 1);
4801 partial_end = (offset + len) & ((1 << blkbits) - 1);
4802
4803 lblk = start >> blkbits;
4804 max_blocks = (end >> blkbits);
4805 if (max_blocks < lblk)
4806 max_blocks = 0;
4807 else
4808 max_blocks -= lblk;
4809
4810 inode_lock(inode);
4811
4812 /*
4813 * Indirect files do not support unwritten extnets
4814 */
4815 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4816 ret = -EOPNOTSUPP;
4817 goto out_mutex;
4818 }
4819
4820 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4821 (offset + len > i_size_read(inode) ||
4822 offset + len > EXT4_I(inode)->i_disksize)) {
4823 new_size = offset + len;
4824 ret = inode_newsize_ok(inode, new_size);
4825 if (ret)
4826 goto out_mutex;
4827 }
4828
4829 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4830 if (mode & FALLOC_FL_KEEP_SIZE)
4831 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4832
4833 /* Wait all existing dio workers, newcomers will block on i_mutex */
4834 ext4_inode_block_unlocked_dio(inode);
4835 inode_dio_wait(inode);
4836
4837 /* Preallocate the range including the unaligned edges */
4838 if (partial_begin || partial_end) {
4839 ret = ext4_alloc_file_blocks(file,
4840 round_down(offset, 1 << blkbits) >> blkbits,
4841 (round_up((offset + len), 1 << blkbits) -
4842 round_down(offset, 1 << blkbits)) >> blkbits,
4843 new_size, flags);
4844 if (ret)
4845 goto out_dio;
4846
4847 }
4848
4849 /* Zero range excluding the unaligned edges */
4850 if (max_blocks > 0) {
4851 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4852 EXT4_EX_NOCACHE);
4853
4854 /*
4855 * Prevent page faults from reinstantiating pages we have
4856 * released from page cache.
4857 */
4858 down_write(&EXT4_I(inode)->i_mmap_sem);
4859 ret = ext4_update_disksize_before_punch(inode, offset, len);
4860 if (ret) {
4861 up_write(&EXT4_I(inode)->i_mmap_sem);
4862 goto out_dio;
4863 }
4864 /* Now release the pages and zero block aligned part of pages */
4865 truncate_pagecache_range(inode, start, end - 1);
4866 inode->i_mtime = inode->i_ctime = current_time(inode);
4867
4868 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4869 flags);
4870 up_write(&EXT4_I(inode)->i_mmap_sem);
4871 if (ret)
4872 goto out_dio;
4873 }
4874 if (!partial_begin && !partial_end)
4875 goto out_dio;
4876
4877 /*
4878 * In worst case we have to writeout two nonadjacent unwritten
4879 * blocks and update the inode
4880 */
4881 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4882 if (ext4_should_journal_data(inode))
4883 credits += 2;
4884 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4885 if (IS_ERR(handle)) {
4886 ret = PTR_ERR(handle);
4887 ext4_std_error(inode->i_sb, ret);
4888 goto out_dio;
4889 }
4890
4891 inode->i_mtime = inode->i_ctime = current_time(inode);
4892 if (new_size) {
4893 ext4_update_inode_size(inode, new_size);
4894 } else {
4895 /*
4896 * Mark that we allocate beyond EOF so the subsequent truncate
4897 * can proceed even if the new size is the same as i_size.
4898 */
4899 if ((offset + len) > i_size_read(inode))
4900 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4901 }
4902 ext4_mark_inode_dirty(handle, inode);
4903
4904 /* Zero out partial block at the edges of the range */
4905 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4906 if (ret >= 0)
4907 ext4_update_inode_fsync_trans(handle, inode, 1);
4908
4909 if (file->f_flags & O_SYNC)
4910 ext4_handle_sync(handle);
4911
4912 ext4_journal_stop(handle);
4913 out_dio:
4914 ext4_inode_resume_unlocked_dio(inode);
4915 out_mutex:
4916 inode_unlock(inode);
4917 return ret;
4918 }
4919
4920 /*
4921 * preallocate space for a file. This implements ext4's fallocate file
4922 * operation, which gets called from sys_fallocate system call.
4923 * For block-mapped files, posix_fallocate should fall back to the method
4924 * of writing zeroes to the required new blocks (the same behavior which is
4925 * expected for file systems which do not support fallocate() system call).
4926 */
4927 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4928 {
4929 struct inode *inode = file_inode(file);
4930 loff_t new_size = 0;
4931 unsigned int max_blocks;
4932 int ret = 0;
4933 int flags;
4934 ext4_lblk_t lblk;
4935 unsigned int blkbits = inode->i_blkbits;
4936
4937 /*
4938 * Encrypted inodes can't handle collapse range or insert
4939 * range since we would need to re-encrypt blocks with a
4940 * different IV or XTS tweak (which are based on the logical
4941 * block number).
4942 *
4943 * XXX It's not clear why zero range isn't working, but we'll
4944 * leave it disabled for encrypted inodes for now. This is a
4945 * bug we should fix....
4946 */
4947 if (ext4_encrypted_inode(inode) &&
4948 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4949 FALLOC_FL_ZERO_RANGE)))
4950 return -EOPNOTSUPP;
4951
4952 /* Return error if mode is not supported */
4953 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4954 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4955 FALLOC_FL_INSERT_RANGE))
4956 return -EOPNOTSUPP;
4957
4958 if (mode & FALLOC_FL_PUNCH_HOLE)
4959 return ext4_punch_hole(inode, offset, len);
4960
4961 ret = ext4_convert_inline_data(inode);
4962 if (ret)
4963 return ret;
4964
4965 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4966 return ext4_collapse_range(inode, offset, len);
4967
4968 if (mode & FALLOC_FL_INSERT_RANGE)
4969 return ext4_insert_range(inode, offset, len);
4970
4971 if (mode & FALLOC_FL_ZERO_RANGE)
4972 return ext4_zero_range(file, offset, len, mode);
4973
4974 trace_ext4_fallocate_enter(inode, offset, len, mode);
4975 lblk = offset >> blkbits;
4976
4977 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4978 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4979 if (mode & FALLOC_FL_KEEP_SIZE)
4980 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4981
4982 inode_lock(inode);
4983
4984 /*
4985 * We only support preallocation for extent-based files only
4986 */
4987 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4988 ret = -EOPNOTSUPP;
4989 goto out;
4990 }
4991
4992 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4993 (offset + len > i_size_read(inode) ||
4994 offset + len > EXT4_I(inode)->i_disksize)) {
4995 new_size = offset + len;
4996 ret = inode_newsize_ok(inode, new_size);
4997 if (ret)
4998 goto out;
4999 }
5000
5001 /* Wait all existing dio workers, newcomers will block on i_mutex */
5002 ext4_inode_block_unlocked_dio(inode);
5003 inode_dio_wait(inode);
5004
5005 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
5006 ext4_inode_resume_unlocked_dio(inode);
5007 if (ret)
5008 goto out;
5009
5010 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5011 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5012 EXT4_I(inode)->i_sync_tid);
5013 }
5014 out:
5015 inode_unlock(inode);
5016 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5017 return ret;
5018 }
5019
5020 /*
5021 * This function convert a range of blocks to written extents
5022 * The caller of this function will pass the start offset and the size.
5023 * all unwritten extents within this range will be converted to
5024 * written extents.
5025 *
5026 * This function is called from the direct IO end io call back
5027 * function, to convert the fallocated extents after IO is completed.
5028 * Returns 0 on success.
5029 */
5030 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5031 loff_t offset, ssize_t len)
5032 {
5033 unsigned int max_blocks;
5034 int ret = 0;
5035 int ret2 = 0;
5036 struct ext4_map_blocks map;
5037 unsigned int credits, blkbits = inode->i_blkbits;
5038
5039 map.m_lblk = offset >> blkbits;
5040 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
5041
5042 /*
5043 * This is somewhat ugly but the idea is clear: When transaction is
5044 * reserved, everything goes into it. Otherwise we rather start several
5045 * smaller transactions for conversion of each extent separately.
5046 */
5047 if (handle) {
5048 handle = ext4_journal_start_reserved(handle,
5049 EXT4_HT_EXT_CONVERT);
5050 if (IS_ERR(handle))
5051 return PTR_ERR(handle);
5052 credits = 0;
5053 } else {
5054 /*
5055 * credits to insert 1 extent into extent tree
5056 */
5057 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5058 }
5059 while (ret >= 0 && ret < max_blocks) {
5060 map.m_lblk += ret;
5061 map.m_len = (max_blocks -= ret);
5062 if (credits) {
5063 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5064 credits);
5065 if (IS_ERR(handle)) {
5066 ret = PTR_ERR(handle);
5067 break;
5068 }
5069 }
5070 ret = ext4_map_blocks(handle, inode, &map,
5071 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5072 if (ret <= 0)
5073 ext4_warning(inode->i_sb,
5074 "inode #%lu: block %u: len %u: "
5075 "ext4_ext_map_blocks returned %d",
5076 inode->i_ino, map.m_lblk,
5077 map.m_len, ret);
5078 ext4_mark_inode_dirty(handle, inode);
5079 if (credits)
5080 ret2 = ext4_journal_stop(handle);
5081 if (ret <= 0 || ret2)
5082 break;
5083 }
5084 if (!credits)
5085 ret2 = ext4_journal_stop(handle);
5086 return ret > 0 ? ret2 : ret;
5087 }
5088
5089 /*
5090 * If newes is not existing extent (newes->ec_pblk equals zero) find
5091 * delayed extent at start of newes and update newes accordingly and
5092 * return start of the next delayed extent.
5093 *
5094 * If newes is existing extent (newes->ec_pblk is not equal zero)
5095 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5096 * extent found. Leave newes unmodified.
5097 */
5098 static int ext4_find_delayed_extent(struct inode *inode,
5099 struct extent_status *newes)
5100 {
5101 struct extent_status es;
5102 ext4_lblk_t block, next_del;
5103
5104 if (newes->es_pblk == 0) {
5105 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5106 newes->es_lblk + newes->es_len - 1, &es);
5107
5108 /*
5109 * No extent in extent-tree contains block @newes->es_pblk,
5110 * then the block may stay in 1)a hole or 2)delayed-extent.
5111 */
5112 if (es.es_len == 0)
5113 /* A hole found. */
5114 return 0;
5115
5116 if (es.es_lblk > newes->es_lblk) {
5117 /* A hole found. */
5118 newes->es_len = min(es.es_lblk - newes->es_lblk,
5119 newes->es_len);
5120 return 0;
5121 }
5122
5123 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5124 }
5125
5126 block = newes->es_lblk + newes->es_len;
5127 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
5128 if (es.es_len == 0)
5129 next_del = EXT_MAX_BLOCKS;
5130 else
5131 next_del = es.es_lblk;
5132
5133 return next_del;
5134 }
5135 /* fiemap flags we can handle specified here */
5136 #define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5137
5138 static int ext4_xattr_fiemap(struct inode *inode,
5139 struct fiemap_extent_info *fieinfo)
5140 {
5141 __u64 physical = 0;
5142 __u64 length;
5143 __u32 flags = FIEMAP_EXTENT_LAST;
5144 int blockbits = inode->i_sb->s_blocksize_bits;
5145 int error = 0;
5146
5147 /* in-inode? */
5148 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5149 struct ext4_iloc iloc;
5150 int offset; /* offset of xattr in inode */
5151
5152 error = ext4_get_inode_loc(inode, &iloc);
5153 if (error)
5154 return error;
5155 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5156 offset = EXT4_GOOD_OLD_INODE_SIZE +
5157 EXT4_I(inode)->i_extra_isize;
5158 physical += offset;
5159 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5160 flags |= FIEMAP_EXTENT_DATA_INLINE;
5161 brelse(iloc.bh);
5162 } else { /* external block */
5163 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5164 length = inode->i_sb->s_blocksize;
5165 }
5166
5167 if (physical)
5168 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5169 length, flags);
5170 return (error < 0 ? error : 0);
5171 }
5172
5173 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5174 __u64 start, __u64 len)
5175 {
5176 ext4_lblk_t start_blk;
5177 int error = 0;
5178
5179 if (ext4_has_inline_data(inode)) {
5180 int has_inline = 1;
5181
5182 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5183 start, len);
5184
5185 if (has_inline)
5186 return error;
5187 }
5188
5189 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5190 error = ext4_ext_precache(inode);
5191 if (error)
5192 return error;
5193 }
5194
5195 /* fallback to generic here if not in extents fmt */
5196 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5197 return generic_block_fiemap(inode, fieinfo, start, len,
5198 ext4_get_block);
5199
5200 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5201 return -EBADR;
5202
5203 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5204 error = ext4_xattr_fiemap(inode, fieinfo);
5205 } else {
5206 ext4_lblk_t len_blks;
5207 __u64 last_blk;
5208
5209 start_blk = start >> inode->i_sb->s_blocksize_bits;
5210 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5211 if (last_blk >= EXT_MAX_BLOCKS)
5212 last_blk = EXT_MAX_BLOCKS-1;
5213 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5214
5215 /*
5216 * Walk the extent tree gathering extent information
5217 * and pushing extents back to the user.
5218 */
5219 error = ext4_fill_fiemap_extents(inode, start_blk,
5220 len_blks, fieinfo);
5221 }
5222 return error;
5223 }
5224
5225 /*
5226 * ext4_access_path:
5227 * Function to access the path buffer for marking it dirty.
5228 * It also checks if there are sufficient credits left in the journal handle
5229 * to update path.
5230 */
5231 static int
5232 ext4_access_path(handle_t *handle, struct inode *inode,
5233 struct ext4_ext_path *path)
5234 {
5235 int credits, err;
5236
5237 if (!ext4_handle_valid(handle))
5238 return 0;
5239
5240 /*
5241 * Check if need to extend journal credits
5242 * 3 for leaf, sb, and inode plus 2 (bmap and group
5243 * descriptor) for each block group; assume two block
5244 * groups
5245 */
5246 if (handle->h_buffer_credits < 7) {
5247 credits = ext4_writepage_trans_blocks(inode);
5248 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5249 /* EAGAIN is success */
5250 if (err && err != -EAGAIN)
5251 return err;
5252 }
5253
5254 err = ext4_ext_get_access(handle, inode, path);
5255 return err;
5256 }
5257
5258 /*
5259 * ext4_ext_shift_path_extents:
5260 * Shift the extents of a path structure lying between path[depth].p_ext
5261 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5262 * if it is right shift or left shift operation.
5263 */
5264 static int
5265 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5266 struct inode *inode, handle_t *handle,
5267 enum SHIFT_DIRECTION SHIFT)
5268 {
5269 int depth, err = 0;
5270 struct ext4_extent *ex_start, *ex_last;
5271 bool update = 0;
5272 depth = path->p_depth;
5273
5274 while (depth >= 0) {
5275 if (depth == path->p_depth) {
5276 ex_start = path[depth].p_ext;
5277 if (!ex_start)
5278 return -EFSCORRUPTED;
5279
5280 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5281
5282 err = ext4_access_path(handle, inode, path + depth);
5283 if (err)
5284 goto out;
5285
5286 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5287 update = 1;
5288
5289 while (ex_start <= ex_last) {
5290 if (SHIFT == SHIFT_LEFT) {
5291 le32_add_cpu(&ex_start->ee_block,
5292 -shift);
5293 /* Try to merge to the left. */
5294 if ((ex_start >
5295 EXT_FIRST_EXTENT(path[depth].p_hdr))
5296 &&
5297 ext4_ext_try_to_merge_right(inode,
5298 path, ex_start - 1))
5299 ex_last--;
5300 else
5301 ex_start++;
5302 } else {
5303 le32_add_cpu(&ex_last->ee_block, shift);
5304 ext4_ext_try_to_merge_right(inode, path,
5305 ex_last);
5306 ex_last--;
5307 }
5308 }
5309 err = ext4_ext_dirty(handle, inode, path + depth);
5310 if (err)
5311 goto out;
5312
5313 if (--depth < 0 || !update)
5314 break;
5315 }
5316
5317 /* Update index too */
5318 err = ext4_access_path(handle, inode, path + depth);
5319 if (err)
5320 goto out;
5321
5322 if (SHIFT == SHIFT_LEFT)
5323 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5324 else
5325 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5326 err = ext4_ext_dirty(handle, inode, path + depth);
5327 if (err)
5328 goto out;
5329
5330 /* we are done if current index is not a starting index */
5331 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5332 break;
5333
5334 depth--;
5335 }
5336
5337 out:
5338 return err;
5339 }
5340
5341 /*
5342 * ext4_ext_shift_extents:
5343 * All the extents which lies in the range from @start to the last allocated
5344 * block for the @inode are shifted either towards left or right (depending
5345 * upon @SHIFT) by @shift blocks.
5346 * On success, 0 is returned, error otherwise.
5347 */
5348 static int
5349 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5350 ext4_lblk_t start, ext4_lblk_t shift,
5351 enum SHIFT_DIRECTION SHIFT)
5352 {
5353 struct ext4_ext_path *path;
5354 int ret = 0, depth;
5355 struct ext4_extent *extent;
5356 ext4_lblk_t stop, *iterator, ex_start, ex_end;
5357
5358 /* Let path point to the last extent */
5359 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5360 EXT4_EX_NOCACHE);
5361 if (IS_ERR(path))
5362 return PTR_ERR(path);
5363
5364 depth = path->p_depth;
5365 extent = path[depth].p_ext;
5366 if (!extent)
5367 goto out;
5368
5369 stop = le32_to_cpu(extent->ee_block);
5370
5371 /*
5372 * For left shifts, make sure the hole on the left is big enough to
5373 * accommodate the shift. For right shifts, make sure the last extent
5374 * won't be shifted beyond EXT_MAX_BLOCKS.
5375 */
5376 if (SHIFT == SHIFT_LEFT) {
5377 path = ext4_find_extent(inode, start - 1, &path,
5378 EXT4_EX_NOCACHE);
5379 if (IS_ERR(path))
5380 return PTR_ERR(path);
5381 depth = path->p_depth;
5382 extent = path[depth].p_ext;
5383 if (extent) {
5384 ex_start = le32_to_cpu(extent->ee_block);
5385 ex_end = le32_to_cpu(extent->ee_block) +
5386 ext4_ext_get_actual_len(extent);
5387 } else {
5388 ex_start = 0;
5389 ex_end = 0;
5390 }
5391
5392 if ((start == ex_start && shift > ex_start) ||
5393 (shift > start - ex_end)) {
5394 ret = -EINVAL;
5395 goto out;
5396 }
5397 } else {
5398 if (shift > EXT_MAX_BLOCKS -
5399 (stop + ext4_ext_get_actual_len(extent))) {
5400 ret = -EINVAL;
5401 goto out;
5402 }
5403 }
5404
5405 /*
5406 * In case of left shift, iterator points to start and it is increased
5407 * till we reach stop. In case of right shift, iterator points to stop
5408 * and it is decreased till we reach start.
5409 */
5410 if (SHIFT == SHIFT_LEFT)
5411 iterator = &start;
5412 else
5413 iterator = &stop;
5414
5415 /*
5416 * Its safe to start updating extents. Start and stop are unsigned, so
5417 * in case of right shift if extent with 0 block is reached, iterator
5418 * becomes NULL to indicate the end of the loop.
5419 */
5420 while (iterator && start <= stop) {
5421 path = ext4_find_extent(inode, *iterator, &path,
5422 EXT4_EX_NOCACHE);
5423 if (IS_ERR(path))
5424 return PTR_ERR(path);
5425 depth = path->p_depth;
5426 extent = path[depth].p_ext;
5427 if (!extent) {
5428 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5429 (unsigned long) *iterator);
5430 return -EFSCORRUPTED;
5431 }
5432 if (SHIFT == SHIFT_LEFT && *iterator >
5433 le32_to_cpu(extent->ee_block)) {
5434 /* Hole, move to the next extent */
5435 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5436 path[depth].p_ext++;
5437 } else {
5438 *iterator = ext4_ext_next_allocated_block(path);
5439 continue;
5440 }
5441 }
5442
5443 if (SHIFT == SHIFT_LEFT) {
5444 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5445 *iterator = le32_to_cpu(extent->ee_block) +
5446 ext4_ext_get_actual_len(extent);
5447 } else {
5448 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5449 if (le32_to_cpu(extent->ee_block) > 0)
5450 *iterator = le32_to_cpu(extent->ee_block) - 1;
5451 else
5452 /* Beginning is reached, end of the loop */
5453 iterator = NULL;
5454 /* Update path extent in case we need to stop */
5455 while (le32_to_cpu(extent->ee_block) < start)
5456 extent++;
5457 path[depth].p_ext = extent;
5458 }
5459 ret = ext4_ext_shift_path_extents(path, shift, inode,
5460 handle, SHIFT);
5461 if (ret)
5462 break;
5463 }
5464 out:
5465 ext4_ext_drop_refs(path);
5466 kfree(path);
5467 return ret;
5468 }
5469
5470 /*
5471 * ext4_collapse_range:
5472 * This implements the fallocate's collapse range functionality for ext4
5473 * Returns: 0 and non-zero on error.
5474 */
5475 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5476 {
5477 struct super_block *sb = inode->i_sb;
5478 ext4_lblk_t punch_start, punch_stop;
5479 handle_t *handle;
5480 unsigned int credits;
5481 loff_t new_size, ioffset;
5482 int ret;
5483
5484 /*
5485 * We need to test this early because xfstests assumes that a
5486 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5487 * system does not support collapse range.
5488 */
5489 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5490 return -EOPNOTSUPP;
5491
5492 /* Collapse range works only on fs block size aligned offsets. */
5493 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5494 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5495 return -EINVAL;
5496
5497 if (!S_ISREG(inode->i_mode))
5498 return -EINVAL;
5499
5500 trace_ext4_collapse_range(inode, offset, len);
5501
5502 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5503 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5504
5505 /* Call ext4_force_commit to flush all data in case of data=journal. */
5506 if (ext4_should_journal_data(inode)) {
5507 ret = ext4_force_commit(inode->i_sb);
5508 if (ret)
5509 return ret;
5510 }
5511
5512 inode_lock(inode);
5513 /*
5514 * There is no need to overlap collapse range with EOF, in which case
5515 * it is effectively a truncate operation
5516 */
5517 if (offset + len >= i_size_read(inode)) {
5518 ret = -EINVAL;
5519 goto out_mutex;
5520 }
5521
5522 /* Currently just for extent based files */
5523 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5524 ret = -EOPNOTSUPP;
5525 goto out_mutex;
5526 }
5527
5528 /* Wait for existing dio to complete */
5529 ext4_inode_block_unlocked_dio(inode);
5530 inode_dio_wait(inode);
5531
5532 /*
5533 * Prevent page faults from reinstantiating pages we have released from
5534 * page cache.
5535 */
5536 down_write(&EXT4_I(inode)->i_mmap_sem);
5537 /*
5538 * Need to round down offset to be aligned with page size boundary
5539 * for page size > block size.
5540 */
5541 ioffset = round_down(offset, PAGE_SIZE);
5542 /*
5543 * Write tail of the last page before removed range since it will get
5544 * removed from the page cache below.
5545 */
5546 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5547 if (ret)
5548 goto out_mmap;
5549 /*
5550 * Write data that will be shifted to preserve them when discarding
5551 * page cache below. We are also protected from pages becoming dirty
5552 * by i_mmap_sem.
5553 */
5554 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5555 LLONG_MAX);
5556 if (ret)
5557 goto out_mmap;
5558 truncate_pagecache(inode, ioffset);
5559
5560 credits = ext4_writepage_trans_blocks(inode);
5561 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5562 if (IS_ERR(handle)) {
5563 ret = PTR_ERR(handle);
5564 goto out_mmap;
5565 }
5566
5567 down_write(&EXT4_I(inode)->i_data_sem);
5568 ext4_discard_preallocations(inode);
5569
5570 ret = ext4_es_remove_extent(inode, punch_start,
5571 EXT_MAX_BLOCKS - punch_start);
5572 if (ret) {
5573 up_write(&EXT4_I(inode)->i_data_sem);
5574 goto out_stop;
5575 }
5576
5577 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5578 if (ret) {
5579 up_write(&EXT4_I(inode)->i_data_sem);
5580 goto out_stop;
5581 }
5582 ext4_discard_preallocations(inode);
5583
5584 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5585 punch_stop - punch_start, SHIFT_LEFT);
5586 if (ret) {
5587 up_write(&EXT4_I(inode)->i_data_sem);
5588 goto out_stop;
5589 }
5590
5591 new_size = i_size_read(inode) - len;
5592 i_size_write(inode, new_size);
5593 EXT4_I(inode)->i_disksize = new_size;
5594
5595 up_write(&EXT4_I(inode)->i_data_sem);
5596 if (IS_SYNC(inode))
5597 ext4_handle_sync(handle);
5598 inode->i_mtime = inode->i_ctime = current_time(inode);
5599 ext4_mark_inode_dirty(handle, inode);
5600 ext4_update_inode_fsync_trans(handle, inode, 1);
5601
5602 out_stop:
5603 ext4_journal_stop(handle);
5604 out_mmap:
5605 up_write(&EXT4_I(inode)->i_mmap_sem);
5606 ext4_inode_resume_unlocked_dio(inode);
5607 out_mutex:
5608 inode_unlock(inode);
5609 return ret;
5610 }
5611
5612 /*
5613 * ext4_insert_range:
5614 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5615 * The data blocks starting from @offset to the EOF are shifted by @len
5616 * towards right to create a hole in the @inode. Inode size is increased
5617 * by len bytes.
5618 * Returns 0 on success, error otherwise.
5619 */
5620 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5621 {
5622 struct super_block *sb = inode->i_sb;
5623 handle_t *handle;
5624 struct ext4_ext_path *path;
5625 struct ext4_extent *extent;
5626 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5627 unsigned int credits, ee_len;
5628 int ret = 0, depth, split_flag = 0;
5629 loff_t ioffset;
5630
5631 /*
5632 * We need to test this early because xfstests assumes that an
5633 * insert range of (0, 1) will return EOPNOTSUPP if the file
5634 * system does not support insert range.
5635 */
5636 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5637 return -EOPNOTSUPP;
5638
5639 /* Insert range works only on fs block size aligned offsets. */
5640 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5641 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5642 return -EINVAL;
5643
5644 if (!S_ISREG(inode->i_mode))
5645 return -EOPNOTSUPP;
5646
5647 trace_ext4_insert_range(inode, offset, len);
5648
5649 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5650 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5651
5652 /* Call ext4_force_commit to flush all data in case of data=journal */
5653 if (ext4_should_journal_data(inode)) {
5654 ret = ext4_force_commit(inode->i_sb);
5655 if (ret)
5656 return ret;
5657 }
5658
5659 inode_lock(inode);
5660 /* Currently just for extent based files */
5661 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5662 ret = -EOPNOTSUPP;
5663 goto out_mutex;
5664 }
5665
5666 /* Check for wrap through zero */
5667 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5668 ret = -EFBIG;
5669 goto out_mutex;
5670 }
5671
5672 /* Offset should be less than i_size */
5673 if (offset >= i_size_read(inode)) {
5674 ret = -EINVAL;
5675 goto out_mutex;
5676 }
5677
5678 /* Wait for existing dio to complete */
5679 ext4_inode_block_unlocked_dio(inode);
5680 inode_dio_wait(inode);
5681
5682 /*
5683 * Prevent page faults from reinstantiating pages we have released from
5684 * page cache.
5685 */
5686 down_write(&EXT4_I(inode)->i_mmap_sem);
5687 /*
5688 * Need to round down to align start offset to page size boundary
5689 * for page size > block size.
5690 */
5691 ioffset = round_down(offset, PAGE_SIZE);
5692 /* Write out all dirty pages */
5693 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5694 LLONG_MAX);
5695 if (ret)
5696 goto out_mmap;
5697 truncate_pagecache(inode, ioffset);
5698
5699 credits = ext4_writepage_trans_blocks(inode);
5700 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5701 if (IS_ERR(handle)) {
5702 ret = PTR_ERR(handle);
5703 goto out_mmap;
5704 }
5705
5706 /* Expand file to avoid data loss if there is error while shifting */
5707 inode->i_size += len;
5708 EXT4_I(inode)->i_disksize += len;
5709 inode->i_mtime = inode->i_ctime = current_time(inode);
5710 ret = ext4_mark_inode_dirty(handle, inode);
5711 if (ret)
5712 goto out_stop;
5713
5714 down_write(&EXT4_I(inode)->i_data_sem);
5715 ext4_discard_preallocations(inode);
5716
5717 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5718 if (IS_ERR(path)) {
5719 up_write(&EXT4_I(inode)->i_data_sem);
5720 goto out_stop;
5721 }
5722
5723 depth = ext_depth(inode);
5724 extent = path[depth].p_ext;
5725 if (extent) {
5726 ee_start_lblk = le32_to_cpu(extent->ee_block);
5727 ee_len = ext4_ext_get_actual_len(extent);
5728
5729 /*
5730 * If offset_lblk is not the starting block of extent, split
5731 * the extent @offset_lblk
5732 */
5733 if ((offset_lblk > ee_start_lblk) &&
5734 (offset_lblk < (ee_start_lblk + ee_len))) {
5735 if (ext4_ext_is_unwritten(extent))
5736 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5737 EXT4_EXT_MARK_UNWRIT2;
5738 ret = ext4_split_extent_at(handle, inode, &path,
5739 offset_lblk, split_flag,
5740 EXT4_EX_NOCACHE |
5741 EXT4_GET_BLOCKS_PRE_IO |
5742 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5743 }
5744
5745 ext4_ext_drop_refs(path);
5746 kfree(path);
5747 if (ret < 0) {
5748 up_write(&EXT4_I(inode)->i_data_sem);
5749 goto out_stop;
5750 }
5751 } else {
5752 ext4_ext_drop_refs(path);
5753 kfree(path);
5754 }
5755
5756 ret = ext4_es_remove_extent(inode, offset_lblk,
5757 EXT_MAX_BLOCKS - offset_lblk);
5758 if (ret) {
5759 up_write(&EXT4_I(inode)->i_data_sem);
5760 goto out_stop;
5761 }
5762
5763 /*
5764 * if offset_lblk lies in a hole which is at start of file, use
5765 * ee_start_lblk to shift extents
5766 */
5767 ret = ext4_ext_shift_extents(inode, handle,
5768 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5769 len_lblk, SHIFT_RIGHT);
5770
5771 up_write(&EXT4_I(inode)->i_data_sem);
5772 if (IS_SYNC(inode))
5773 ext4_handle_sync(handle);
5774 if (ret >= 0)
5775 ext4_update_inode_fsync_trans(handle, inode, 1);
5776
5777 out_stop:
5778 ext4_journal_stop(handle);
5779 out_mmap:
5780 up_write(&EXT4_I(inode)->i_mmap_sem);
5781 ext4_inode_resume_unlocked_dio(inode);
5782 out_mutex:
5783 inode_unlock(inode);
5784 return ret;
5785 }
5786
5787 /**
5788 * ext4_swap_extents - Swap extents between two inodes
5789 *
5790 * @inode1: First inode
5791 * @inode2: Second inode
5792 * @lblk1: Start block for first inode
5793 * @lblk2: Start block for second inode
5794 * @count: Number of blocks to swap
5795 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5796 * @erp: Pointer to save error value
5797 *
5798 * This helper routine does exactly what is promise "swap extents". All other
5799 * stuff such as page-cache locking consistency, bh mapping consistency or
5800 * extent's data copying must be performed by caller.
5801 * Locking:
5802 * i_mutex is held for both inodes
5803 * i_data_sem is locked for write for both inodes
5804 * Assumptions:
5805 * All pages from requested range are locked for both inodes
5806 */
5807 int
5808 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5809 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5810 ext4_lblk_t count, int unwritten, int *erp)
5811 {
5812 struct ext4_ext_path *path1 = NULL;
5813 struct ext4_ext_path *path2 = NULL;
5814 int replaced_count = 0;
5815
5816 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5817 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5818 BUG_ON(!inode_is_locked(inode1));
5819 BUG_ON(!inode_is_locked(inode2));
5820
5821 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5822 if (unlikely(*erp))
5823 return 0;
5824 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5825 if (unlikely(*erp))
5826 return 0;
5827
5828 while (count) {
5829 struct ext4_extent *ex1, *ex2, tmp_ex;
5830 ext4_lblk_t e1_blk, e2_blk;
5831 int e1_len, e2_len, len;
5832 int split = 0;
5833
5834 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5835 if (IS_ERR(path1)) {
5836 *erp = PTR_ERR(path1);
5837 path1 = NULL;
5838 finish:
5839 count = 0;
5840 goto repeat;
5841 }
5842 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5843 if (IS_ERR(path2)) {
5844 *erp = PTR_ERR(path2);
5845 path2 = NULL;
5846 goto finish;
5847 }
5848 ex1 = path1[path1->p_depth].p_ext;
5849 ex2 = path2[path2->p_depth].p_ext;
5850 /* Do we have somthing to swap ? */
5851 if (unlikely(!ex2 || !ex1))
5852 goto finish;
5853
5854 e1_blk = le32_to_cpu(ex1->ee_block);
5855 e2_blk = le32_to_cpu(ex2->ee_block);
5856 e1_len = ext4_ext_get_actual_len(ex1);
5857 e2_len = ext4_ext_get_actual_len(ex2);
5858
5859 /* Hole handling */
5860 if (!in_range(lblk1, e1_blk, e1_len) ||
5861 !in_range(lblk2, e2_blk, e2_len)) {
5862 ext4_lblk_t next1, next2;
5863
5864 /* if hole after extent, then go to next extent */
5865 next1 = ext4_ext_next_allocated_block(path1);
5866 next2 = ext4_ext_next_allocated_block(path2);
5867 /* If hole before extent, then shift to that extent */
5868 if (e1_blk > lblk1)
5869 next1 = e1_blk;
5870 if (e2_blk > lblk2)
5871 next2 = e2_blk;
5872 /* Do we have something to swap */
5873 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5874 goto finish;
5875 /* Move to the rightest boundary */
5876 len = next1 - lblk1;
5877 if (len < next2 - lblk2)
5878 len = next2 - lblk2;
5879 if (len > count)
5880 len = count;
5881 lblk1 += len;
5882 lblk2 += len;
5883 count -= len;
5884 goto repeat;
5885 }
5886
5887 /* Prepare left boundary */
5888 if (e1_blk < lblk1) {
5889 split = 1;
5890 *erp = ext4_force_split_extent_at(handle, inode1,
5891 &path1, lblk1, 0);
5892 if (unlikely(*erp))
5893 goto finish;
5894 }
5895 if (e2_blk < lblk2) {
5896 split = 1;
5897 *erp = ext4_force_split_extent_at(handle, inode2,
5898 &path2, lblk2, 0);
5899 if (unlikely(*erp))
5900 goto finish;
5901 }
5902 /* ext4_split_extent_at() may result in leaf extent split,
5903 * path must to be revalidated. */
5904 if (split)
5905 goto repeat;
5906
5907 /* Prepare right boundary */
5908 len = count;
5909 if (len > e1_blk + e1_len - lblk1)
5910 len = e1_blk + e1_len - lblk1;
5911 if (len > e2_blk + e2_len - lblk2)
5912 len = e2_blk + e2_len - lblk2;
5913
5914 if (len != e1_len) {
5915 split = 1;
5916 *erp = ext4_force_split_extent_at(handle, inode1,
5917 &path1, lblk1 + len, 0);
5918 if (unlikely(*erp))
5919 goto finish;
5920 }
5921 if (len != e2_len) {
5922 split = 1;
5923 *erp = ext4_force_split_extent_at(handle, inode2,
5924 &path2, lblk2 + len, 0);
5925 if (*erp)
5926 goto finish;
5927 }
5928 /* ext4_split_extent_at() may result in leaf extent split,
5929 * path must to be revalidated. */
5930 if (split)
5931 goto repeat;
5932
5933 BUG_ON(e2_len != e1_len);
5934 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5935 if (unlikely(*erp))
5936 goto finish;
5937 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5938 if (unlikely(*erp))
5939 goto finish;
5940
5941 /* Both extents are fully inside boundaries. Swap it now */
5942 tmp_ex = *ex1;
5943 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5944 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5945 ex1->ee_len = cpu_to_le16(e2_len);
5946 ex2->ee_len = cpu_to_le16(e1_len);
5947 if (unwritten)
5948 ext4_ext_mark_unwritten(ex2);
5949 if (ext4_ext_is_unwritten(&tmp_ex))
5950 ext4_ext_mark_unwritten(ex1);
5951
5952 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5953 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5954 *erp = ext4_ext_dirty(handle, inode2, path2 +
5955 path2->p_depth);
5956 if (unlikely(*erp))
5957 goto finish;
5958 *erp = ext4_ext_dirty(handle, inode1, path1 +
5959 path1->p_depth);
5960 /*
5961 * Looks scarry ah..? second inode already points to new blocks,
5962 * and it was successfully dirtied. But luckily error may happen
5963 * only due to journal error, so full transaction will be
5964 * aborted anyway.
5965 */
5966 if (unlikely(*erp))
5967 goto finish;
5968 lblk1 += len;
5969 lblk2 += len;
5970 replaced_count += len;
5971 count -= len;
5972
5973 repeat:
5974 ext4_ext_drop_refs(path1);
5975 kfree(path1);
5976 ext4_ext_drop_refs(path2);
5977 kfree(path2);
5978 path1 = path2 = NULL;
5979 }
5980 return replaced_count;
5981 }