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