~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/ext4/extents.c

Version: ~ [ linux-5.9-rc6 ] ~ [ linux-5.8.10 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.66 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.146 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.198 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.236 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.236 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp