ext4: Fix insertion point of extent in mext_insert_across_blocks()
[linux-flexiantxendom0-natty.git] / fs / ext4 / move_extent.c
1 /*
2  * Copyright (c) 2008,2009 NEC Software Tohoku, Ltd.
3  * Written by Takashi Sato <t-sato@yk.jp.nec.com>
4  *            Akira Fujita <a-fujita@rs.jp.nec.com>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of version 2.1 of the GNU Lesser General Public License
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include <linux/fs.h>
17 #include <linux/quotaops.h>
18 #include "ext4_jbd2.h"
19 #include "ext4_extents.h"
20 #include "ext4.h"
21
22 /**
23  * get_ext_path - Find an extent path for designated logical block number.
24  *
25  * @inode:      an inode which is searched
26  * @lblock:     logical block number to find an extent path
27  * @path:       pointer to an extent path pointer (for output)
28  *
29  * ext4_ext_find_extent wrapper. Return 0 on success, or a negative error value
30  * on failure.
31  */
32 static inline int
33 get_ext_path(struct inode *inode, ext4_lblk_t lblock,
34                 struct ext4_ext_path **path)
35 {
36         int ret = 0;
37
38         *path = ext4_ext_find_extent(inode, lblock, *path);
39         if (IS_ERR(*path)) {
40                 ret = PTR_ERR(*path);
41                 *path = NULL;
42         } else if ((*path)[ext_depth(inode)].p_ext == NULL)
43                 ret = -ENODATA;
44
45         return ret;
46 }
47
48 /**
49  * copy_extent_status - Copy the extent's initialization status
50  *
51  * @src:        an extent for getting initialize status
52  * @dest:       an extent to be set the status
53  */
54 static void
55 copy_extent_status(struct ext4_extent *src, struct ext4_extent *dest)
56 {
57         if (ext4_ext_is_uninitialized(src))
58                 ext4_ext_mark_uninitialized(dest);
59         else
60                 dest->ee_len = cpu_to_le16(ext4_ext_get_actual_len(dest));
61 }
62
63 /**
64  * mext_next_extent - Search for the next extent and set it to "extent"
65  *
66  * @inode:      inode which is searched
67  * @path:       this will obtain data for the next extent
68  * @extent:     pointer to the next extent we have just gotten
69  *
70  * Search the next extent in the array of ext4_ext_path structure (@path)
71  * and set it to ext4_extent structure (@extent). In addition, the member of
72  * @path (->p_ext) also points the next extent. Return 0 on success, 1 if
73  * ext4_ext_path structure refers to the last extent, or a negative error
74  * value on failure.
75  */
76 static int
77 mext_next_extent(struct inode *inode, struct ext4_ext_path *path,
78                       struct ext4_extent **extent)
79 {
80         struct ext4_extent_header *eh;
81         int ppos, leaf_ppos = path->p_depth;
82
83         ppos = leaf_ppos;
84         if (EXT_LAST_EXTENT(path[ppos].p_hdr) > path[ppos].p_ext) {
85                 /* leaf block */
86                 *extent = ++path[ppos].p_ext;
87                 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
88                 return 0;
89         }
90
91         while (--ppos >= 0) {
92                 if (EXT_LAST_INDEX(path[ppos].p_hdr) >
93                     path[ppos].p_idx) {
94                         int cur_ppos = ppos;
95
96                         /* index block */
97                         path[ppos].p_idx++;
98                         path[ppos].p_block = idx_pblock(path[ppos].p_idx);
99                         if (path[ppos+1].p_bh)
100                                 brelse(path[ppos+1].p_bh);
101                         path[ppos+1].p_bh =
102                                 sb_bread(inode->i_sb, path[ppos].p_block);
103                         if (!path[ppos+1].p_bh)
104                                 return -EIO;
105                         path[ppos+1].p_hdr =
106                                 ext_block_hdr(path[ppos+1].p_bh);
107
108                         /* Halfway index block */
109                         while (++cur_ppos < leaf_ppos) {
110                                 path[cur_ppos].p_idx =
111                                         EXT_FIRST_INDEX(path[cur_ppos].p_hdr);
112                                 path[cur_ppos].p_block =
113                                         idx_pblock(path[cur_ppos].p_idx);
114                                 if (path[cur_ppos+1].p_bh)
115                                         brelse(path[cur_ppos+1].p_bh);
116                                 path[cur_ppos+1].p_bh = sb_bread(inode->i_sb,
117                                         path[cur_ppos].p_block);
118                                 if (!path[cur_ppos+1].p_bh)
119                                         return -EIO;
120                                 path[cur_ppos+1].p_hdr =
121                                         ext_block_hdr(path[cur_ppos+1].p_bh);
122                         }
123
124                         path[leaf_ppos].p_ext = *extent = NULL;
125
126                         eh = path[leaf_ppos].p_hdr;
127                         if (le16_to_cpu(eh->eh_entries) == 0)
128                                 /* empty leaf is found */
129                                 return -ENODATA;
130
131                         /* leaf block */
132                         path[leaf_ppos].p_ext = *extent =
133                                 EXT_FIRST_EXTENT(path[leaf_ppos].p_hdr);
134                         path[leaf_ppos].p_block =
135                                         ext_pblock(path[leaf_ppos].p_ext);
136                         return 0;
137                 }
138         }
139         /* We found the last extent */
140         return 1;
141 }
142
143 /**
144  * mext_check_null_inode - NULL check for two inodes
145  *
146  * If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
147  */
148 static int
149 mext_check_null_inode(struct inode *inode1, struct inode *inode2,
150                 const char *function)
151 {
152         int ret = 0;
153
154         if (inode1 == NULL) {
155                 __ext4_error(inode2->i_sb, function,
156                         "Both inodes should not be NULL: "
157                         "inode1 NULL inode2 %lu", inode2->i_ino);
158                 ret = -EIO;
159         } else if (inode2 == NULL) {
160                 __ext4_error(inode1->i_sb, function,
161                         "Both inodes should not be NULL: "
162                         "inode1 %lu inode2 NULL", inode1->i_ino);
163                 ret = -EIO;
164         }
165         return ret;
166 }
167
168 /**
169  * double_down_write_data_sem - Acquire two inodes' write lock of i_data_sem
170  *
171  * @orig_inode:         original inode structure
172  * @donor_inode:        donor inode structure
173  * Acquire write lock of i_data_sem of the two inodes (orig and donor) by
174  * i_ino order.
175  */
176 static void
177 double_down_write_data_sem(struct inode *orig_inode, struct inode *donor_inode)
178 {
179         struct inode *first = orig_inode, *second = donor_inode;
180
181         /*
182          * Use the inode number to provide the stable locking order instead
183          * of its address, because the C language doesn't guarantee you can
184          * compare pointers that don't come from the same array.
185          */
186         if (donor_inode->i_ino < orig_inode->i_ino) {
187                 first = donor_inode;
188                 second = orig_inode;
189         }
190
191         down_write(&EXT4_I(first)->i_data_sem);
192         down_write_nested(&EXT4_I(second)->i_data_sem, SINGLE_DEPTH_NESTING);
193 }
194
195 /**
196  * double_up_write_data_sem - Release two inodes' write lock of i_data_sem
197  *
198  * @orig_inode:         original inode structure to be released its lock first
199  * @donor_inode:        donor inode structure to be released its lock second
200  * Release write lock of i_data_sem of two inodes (orig and donor).
201  */
202 static void
203 double_up_write_data_sem(struct inode *orig_inode, struct inode *donor_inode)
204 {
205         up_write(&EXT4_I(orig_inode)->i_data_sem);
206         up_write(&EXT4_I(donor_inode)->i_data_sem);
207 }
208
209 /**
210  * mext_insert_across_blocks - Insert extents across leaf block
211  *
212  * @handle:             journal handle
213  * @orig_inode:         original inode
214  * @o_start:            first original extent to be changed
215  * @o_end:              last original extent to be changed
216  * @start_ext:          first new extent to be inserted
217  * @new_ext:            middle of new extent to be inserted
218  * @end_ext:            last new extent to be inserted
219  *
220  * Allocate a new leaf block and insert extents into it. Return 0 on success,
221  * or a negative error value on failure.
222  */
223 static int
224 mext_insert_across_blocks(handle_t *handle, struct inode *orig_inode,
225                 struct ext4_extent *o_start, struct ext4_extent *o_end,
226                 struct ext4_extent *start_ext, struct ext4_extent *new_ext,
227                 struct ext4_extent *end_ext)
228 {
229         struct ext4_ext_path *orig_path = NULL;
230         ext4_lblk_t eblock = 0;
231         int new_flag = 0;
232         int end_flag = 0;
233         int err = 0;
234
235         if (start_ext->ee_len && new_ext->ee_len && end_ext->ee_len) {
236                 if (o_start == o_end) {
237
238                         /*       start_ext   new_ext    end_ext
239                          * donor |---------|-----------|--------|
240                          * orig  |------------------------------|
241                          */
242                         end_flag = 1;
243                 } else {
244
245                         /*       start_ext   new_ext   end_ext
246                          * donor |---------|----------|---------|
247                          * orig  |---------------|--------------|
248                          */
249                         o_end->ee_block = end_ext->ee_block;
250                         o_end->ee_len = end_ext->ee_len;
251                         ext4_ext_store_pblock(o_end, ext_pblock(end_ext));
252                 }
253
254                 o_start->ee_len = start_ext->ee_len;
255                 eblock = le32_to_cpu(start_ext->ee_block);
256                 new_flag = 1;
257
258         } else if (start_ext->ee_len && new_ext->ee_len &&
259                    !end_ext->ee_len && o_start == o_end) {
260
261                 /*       start_ext      new_ext
262                  * donor |--------------|---------------|
263                  * orig  |------------------------------|
264                  */
265                 o_start->ee_len = start_ext->ee_len;
266                 eblock = le32_to_cpu(start_ext->ee_block);
267                 new_flag = 1;
268
269         } else if (!start_ext->ee_len && new_ext->ee_len &&
270                    end_ext->ee_len && o_start == o_end) {
271
272                 /*        new_ext       end_ext
273                  * donor |--------------|---------------|
274                  * orig  |------------------------------|
275                  */
276                 o_end->ee_block = end_ext->ee_block;
277                 o_end->ee_len = end_ext->ee_len;
278                 ext4_ext_store_pblock(o_end, ext_pblock(end_ext));
279
280                 /*
281                  * Set 0 to the extent block if new_ext was
282                  * the first block.
283                  */
284                 if (new_ext->ee_block)
285                         eblock = le32_to_cpu(new_ext->ee_block);
286
287                 new_flag = 1;
288         } else {
289                 ext4_debug("ext4 move extent: Unexpected insert case\n");
290                 return -EIO;
291         }
292
293         if (new_flag) {
294                 err = get_ext_path(orig_inode, eblock, &orig_path);
295                 if (err)
296                         goto out;
297
298                 if (ext4_ext_insert_extent(handle, orig_inode,
299                                         orig_path, new_ext, 0))
300                         goto out;
301         }
302
303         if (end_flag) {
304                 err = get_ext_path(orig_inode,
305                                 le32_to_cpu(end_ext->ee_block) - 1, &orig_path);
306                 if (err)
307                         goto out;
308
309                 if (ext4_ext_insert_extent(handle, orig_inode,
310                                            orig_path, end_ext, 0))
311                         goto out;
312         }
313 out:
314         if (orig_path) {
315                 ext4_ext_drop_refs(orig_path);
316                 kfree(orig_path);
317         }
318
319         return err;
320
321 }
322
323 /**
324  * mext_insert_inside_block - Insert new extent to the extent block
325  *
326  * @o_start:            first original extent to be moved
327  * @o_end:              last original extent to be moved
328  * @start_ext:          first new extent to be inserted
329  * @new_ext:            middle of new extent to be inserted
330  * @end_ext:            last new extent to be inserted
331  * @eh:                 extent header of target leaf block
332  * @range_to_move:      used to decide how to insert extent
333  *
334  * Insert extents into the leaf block. The extent (@o_start) is overwritten
335  * by inserted extents.
336  */
337 static void
338 mext_insert_inside_block(struct ext4_extent *o_start,
339                               struct ext4_extent *o_end,
340                               struct ext4_extent *start_ext,
341                               struct ext4_extent *new_ext,
342                               struct ext4_extent *end_ext,
343                               struct ext4_extent_header *eh,
344                               int range_to_move)
345 {
346         int i = 0;
347         unsigned long len;
348
349         /* Move the existing extents */
350         if (range_to_move && o_end < EXT_LAST_EXTENT(eh)) {
351                 len = (unsigned long)(EXT_LAST_EXTENT(eh) + 1) -
352                         (unsigned long)(o_end + 1);
353                 memmove(o_end + 1 + range_to_move, o_end + 1, len);
354         }
355
356         /* Insert start entry */
357         if (start_ext->ee_len)
358                 o_start[i++].ee_len = start_ext->ee_len;
359
360         /* Insert new entry */
361         if (new_ext->ee_len) {
362                 o_start[i] = *new_ext;
363                 ext4_ext_store_pblock(&o_start[i++], ext_pblock(new_ext));
364         }
365
366         /* Insert end entry */
367         if (end_ext->ee_len)
368                 o_start[i] = *end_ext;
369
370         /* Increment the total entries counter on the extent block */
371         le16_add_cpu(&eh->eh_entries, range_to_move);
372 }
373
374 /**
375  * mext_insert_extents - Insert new extent
376  *
377  * @handle:     journal handle
378  * @orig_inode: original inode
379  * @orig_path:  path indicates first extent to be changed
380  * @o_start:    first original extent to be changed
381  * @o_end:      last original extent to be changed
382  * @start_ext:  first new extent to be inserted
383  * @new_ext:    middle of new extent to be inserted
384  * @end_ext:    last new extent to be inserted
385  *
386  * Call the function to insert extents. If we cannot add more extents into
387  * the leaf block, we call mext_insert_across_blocks() to create a
388  * new leaf block. Otherwise call mext_insert_inside_block(). Return 0
389  * on success, or a negative error value on failure.
390  */
391 static int
392 mext_insert_extents(handle_t *handle, struct inode *orig_inode,
393                          struct ext4_ext_path *orig_path,
394                          struct ext4_extent *o_start,
395                          struct ext4_extent *o_end,
396                          struct ext4_extent *start_ext,
397                          struct ext4_extent *new_ext,
398                          struct ext4_extent *end_ext)
399 {
400         struct  ext4_extent_header *eh;
401         unsigned long need_slots, slots_range;
402         int     range_to_move, depth, ret;
403
404         /*
405          * The extents need to be inserted
406          * start_extent + new_extent + end_extent.
407          */
408         need_slots = (start_ext->ee_len ? 1 : 0) + (end_ext->ee_len ? 1 : 0) +
409                 (new_ext->ee_len ? 1 : 0);
410
411         /* The number of slots between start and end */
412         slots_range = ((unsigned long)(o_end + 1) - (unsigned long)o_start + 1)
413                 / sizeof(struct ext4_extent);
414
415         /* Range to move the end of extent */
416         range_to_move = need_slots - slots_range;
417         depth = orig_path->p_depth;
418         orig_path += depth;
419         eh = orig_path->p_hdr;
420
421         if (depth) {
422                 /* Register to journal */
423                 ret = ext4_journal_get_write_access(handle, orig_path->p_bh);
424                 if (ret)
425                         return ret;
426         }
427
428         /* Expansion */
429         if (range_to_move > 0 &&
430                 (range_to_move > le16_to_cpu(eh->eh_max)
431                         - le16_to_cpu(eh->eh_entries))) {
432
433                 ret = mext_insert_across_blocks(handle, orig_inode, o_start,
434                                         o_end, start_ext, new_ext, end_ext);
435                 if (ret < 0)
436                         return ret;
437         } else
438                 mext_insert_inside_block(o_start, o_end, start_ext, new_ext,
439                                                 end_ext, eh, range_to_move);
440
441         if (depth) {
442                 ret = ext4_handle_dirty_metadata(handle, orig_inode,
443                                                  orig_path->p_bh);
444                 if (ret)
445                         return ret;
446         } else {
447                 ret = ext4_mark_inode_dirty(handle, orig_inode);
448                 if (ret < 0)
449                         return ret;
450         }
451
452         return 0;
453 }
454
455 /**
456  * mext_leaf_block - Move one leaf extent block into the inode.
457  *
458  * @handle:             journal handle
459  * @orig_inode:         original inode
460  * @orig_path:          path indicates first extent to be changed
461  * @dext:               donor extent
462  * @from:               start offset on the target file
463  *
464  * In order to insert extents into the leaf block, we must divide the extent
465  * in the leaf block into three extents. The one is located to be inserted
466  * extents, and the others are located around it.
467  *
468  * Therefore, this function creates structures to save extents of the leaf
469  * block, and inserts extents by calling mext_insert_extents() with
470  * created extents. Return 0 on success, or a negative error value on failure.
471  */
472 static int
473 mext_leaf_block(handle_t *handle, struct inode *orig_inode,
474                      struct ext4_ext_path *orig_path, struct ext4_extent *dext,
475                      ext4_lblk_t *from)
476 {
477         struct ext4_extent *oext, *o_start, *o_end, *prev_ext;
478         struct ext4_extent new_ext, start_ext, end_ext;
479         ext4_lblk_t new_ext_end;
480         ext4_fsblk_t new_phys_end;
481         int oext_alen, new_ext_alen, end_ext_alen;
482         int depth = ext_depth(orig_inode);
483         int ret;
484
485         o_start = o_end = oext = orig_path[depth].p_ext;
486         oext_alen = ext4_ext_get_actual_len(oext);
487         start_ext.ee_len = end_ext.ee_len = 0;
488
489         new_ext.ee_block = cpu_to_le32(*from);
490         ext4_ext_store_pblock(&new_ext, ext_pblock(dext));
491         new_ext.ee_len = dext->ee_len;
492         new_ext_alen = ext4_ext_get_actual_len(&new_ext);
493         new_ext_end = le32_to_cpu(new_ext.ee_block) + new_ext_alen - 1;
494         new_phys_end = ext_pblock(&new_ext) + new_ext_alen - 1;
495
496         /*
497          * Case: original extent is first
498          * oext      |--------|
499          * new_ext      |--|
500          * start_ext |--|
501          */
502         if (le32_to_cpu(oext->ee_block) < le32_to_cpu(new_ext.ee_block) &&
503                 le32_to_cpu(new_ext.ee_block) <
504                 le32_to_cpu(oext->ee_block) + oext_alen) {
505                 start_ext.ee_len = cpu_to_le16(le32_to_cpu(new_ext.ee_block) -
506                                                le32_to_cpu(oext->ee_block));
507                 start_ext.ee_block = oext->ee_block;
508                 copy_extent_status(oext, &start_ext);
509         } else if (oext > EXT_FIRST_EXTENT(orig_path[depth].p_hdr)) {
510                 prev_ext = oext - 1;
511                 /*
512                  * We can merge new_ext into previous extent,
513                  * if these are contiguous and same extent type.
514                  */
515                 if (ext4_can_extents_be_merged(orig_inode, prev_ext,
516                                                &new_ext)) {
517                         o_start = prev_ext;
518                         start_ext.ee_len = cpu_to_le16(
519                                 ext4_ext_get_actual_len(prev_ext) +
520                                 new_ext_alen);
521                         start_ext.ee_block = oext->ee_block;
522                         copy_extent_status(prev_ext, &start_ext);
523                         new_ext.ee_len = 0;
524                 }
525         }
526
527         /*
528          * Case: new_ext_end must be less than oext
529          * oext      |-----------|
530          * new_ext       |-------|
531          */
532         if (le32_to_cpu(oext->ee_block) + oext_alen - 1 < new_ext_end) {
533                 ext4_error(orig_inode->i_sb,
534                         "new_ext_end(%u) should be less than or equal to "
535                         "oext->ee_block(%u) + oext_alen(%d) - 1",
536                         new_ext_end, le32_to_cpu(oext->ee_block),
537                         oext_alen);
538                 ret = -EIO;
539                 goto out;
540         }
541
542         /*
543          * Case: new_ext is smaller than original extent
544          * oext    |---------------|
545          * new_ext |-----------|
546          * end_ext             |---|
547          */
548         if (le32_to_cpu(oext->ee_block) <= new_ext_end &&
549                 new_ext_end < le32_to_cpu(oext->ee_block) + oext_alen - 1) {
550                 end_ext.ee_len =
551                         cpu_to_le16(le32_to_cpu(oext->ee_block) +
552                         oext_alen - 1 - new_ext_end);
553                 copy_extent_status(oext, &end_ext);
554                 end_ext_alen = ext4_ext_get_actual_len(&end_ext);
555                 ext4_ext_store_pblock(&end_ext,
556                         (ext_pblock(o_end) + oext_alen - end_ext_alen));
557                 end_ext.ee_block =
558                         cpu_to_le32(le32_to_cpu(o_end->ee_block) +
559                         oext_alen - end_ext_alen);
560         }
561
562         ret = mext_insert_extents(handle, orig_inode, orig_path, o_start,
563                                 o_end, &start_ext, &new_ext, &end_ext);
564 out:
565         return ret;
566 }
567
568 /**
569  * mext_calc_swap_extents - Calculate extents for extent swapping.
570  *
571  * @tmp_dext:           the extent that will belong to the original inode
572  * @tmp_oext:           the extent that will belong to the donor inode
573  * @orig_off:           block offset of original inode
574  * @donor_off:          block offset of donor inode
575  * @max_count:          the maximum length of extents
576  *
577  * Return 0 on success, or a negative error value on failure.
578  */
579 static int
580 mext_calc_swap_extents(struct ext4_extent *tmp_dext,
581                               struct ext4_extent *tmp_oext,
582                               ext4_lblk_t orig_off, ext4_lblk_t donor_off,
583                               ext4_lblk_t max_count)
584 {
585         ext4_lblk_t diff, orig_diff;
586         struct ext4_extent dext_old, oext_old;
587
588         BUG_ON(orig_off != donor_off);
589
590         /* original and donor extents have to cover the same block offset */
591         if (orig_off < le32_to_cpu(tmp_oext->ee_block) ||
592             le32_to_cpu(tmp_oext->ee_block) +
593                         ext4_ext_get_actual_len(tmp_oext) - 1 < orig_off)
594                 return -ENODATA;
595
596         if (orig_off < le32_to_cpu(tmp_dext->ee_block) ||
597             le32_to_cpu(tmp_dext->ee_block) +
598                         ext4_ext_get_actual_len(tmp_dext) - 1 < orig_off)
599                 return -ENODATA;
600
601         dext_old = *tmp_dext;
602         oext_old = *tmp_oext;
603
604         /* When tmp_dext is too large, pick up the target range. */
605         diff = donor_off - le32_to_cpu(tmp_dext->ee_block);
606
607         ext4_ext_store_pblock(tmp_dext, ext_pblock(tmp_dext) + diff);
608         tmp_dext->ee_block =
609                         cpu_to_le32(le32_to_cpu(tmp_dext->ee_block) + diff);
610         tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_dext->ee_len) - diff);
611
612         if (max_count < ext4_ext_get_actual_len(tmp_dext))
613                 tmp_dext->ee_len = cpu_to_le16(max_count);
614
615         orig_diff = orig_off - le32_to_cpu(tmp_oext->ee_block);
616         ext4_ext_store_pblock(tmp_oext, ext_pblock(tmp_oext) + orig_diff);
617
618         /* Adjust extent length if donor extent is larger than orig */
619         if (ext4_ext_get_actual_len(tmp_dext) >
620             ext4_ext_get_actual_len(tmp_oext) - orig_diff)
621                 tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_oext->ee_len) -
622                                                 orig_diff);
623
624         tmp_oext->ee_len = cpu_to_le16(ext4_ext_get_actual_len(tmp_dext));
625
626         copy_extent_status(&oext_old, tmp_dext);
627         copy_extent_status(&dext_old, tmp_oext);
628
629         return 0;
630 }
631
632 /**
633  * mext_replace_branches - Replace original extents with new extents
634  *
635  * @handle:             journal handle
636  * @orig_inode:         original inode
637  * @donor_inode:        donor inode
638  * @from:               block offset of orig_inode
639  * @count:              block count to be replaced
640  * @err:                pointer to save return value
641  *
642  * Replace original inode extents and donor inode extents page by page.
643  * We implement this replacement in the following three steps:
644  * 1. Save the block information of original and donor inodes into
645  *    dummy extents.
646  * 2. Change the block information of original inode to point at the
647  *    donor inode blocks.
648  * 3. Change the block information of donor inode to point at the saved
649  *    original inode blocks in the dummy extents.
650  *
651  * Return replaced block count.
652  */
653 static int
654 mext_replace_branches(handle_t *handle, struct inode *orig_inode,
655                            struct inode *donor_inode, ext4_lblk_t from,
656                            ext4_lblk_t count, int *err)
657 {
658         struct ext4_ext_path *orig_path = NULL;
659         struct ext4_ext_path *donor_path = NULL;
660         struct ext4_extent *oext, *dext;
661         struct ext4_extent tmp_dext, tmp_oext;
662         ext4_lblk_t orig_off = from, donor_off = from;
663         int depth;
664         int replaced_count = 0;
665         int dext_alen;
666
667         /* Protect extent trees against block allocations via delalloc */
668         double_down_write_data_sem(orig_inode, donor_inode);
669
670         /* Get the original extent for the block "orig_off" */
671         *err = get_ext_path(orig_inode, orig_off, &orig_path);
672         if (*err)
673                 goto out;
674
675         /* Get the donor extent for the head */
676         *err = get_ext_path(donor_inode, donor_off, &donor_path);
677         if (*err)
678                 goto out;
679         depth = ext_depth(orig_inode);
680         oext = orig_path[depth].p_ext;
681         tmp_oext = *oext;
682
683         depth = ext_depth(donor_inode);
684         dext = donor_path[depth].p_ext;
685         tmp_dext = *dext;
686
687         *err = mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
688                                       donor_off, count);
689         if (*err)
690                 goto out;
691
692         /* Loop for the donor extents */
693         while (1) {
694                 /* The extent for donor must be found. */
695                 if (!dext) {
696                         ext4_error(donor_inode->i_sb,
697                                    "The extent for donor must be found");
698                         *err = -EIO;
699                         goto out;
700                 } else if (donor_off != le32_to_cpu(tmp_dext.ee_block)) {
701                         ext4_error(donor_inode->i_sb,
702                                 "Donor offset(%u) and the first block of donor "
703                                 "extent(%u) should be equal",
704                                 donor_off,
705                                 le32_to_cpu(tmp_dext.ee_block));
706                         *err = -EIO;
707                         goto out;
708                 }
709
710                 /* Set donor extent to orig extent */
711                 *err = mext_leaf_block(handle, orig_inode,
712                                            orig_path, &tmp_dext, &orig_off);
713                 if (*err)
714                         goto out;
715
716                 /* Set orig extent to donor extent */
717                 *err = mext_leaf_block(handle, donor_inode,
718                                            donor_path, &tmp_oext, &donor_off);
719                 if (*err)
720                         goto out;
721
722                 dext_alen = ext4_ext_get_actual_len(&tmp_dext);
723                 replaced_count += dext_alen;
724                 donor_off += dext_alen;
725                 orig_off += dext_alen;
726
727                 /* Already moved the expected blocks */
728                 if (replaced_count >= count)
729                         break;
730
731                 if (orig_path)
732                         ext4_ext_drop_refs(orig_path);
733                 *err = get_ext_path(orig_inode, orig_off, &orig_path);
734                 if (*err)
735                         goto out;
736                 depth = ext_depth(orig_inode);
737                 oext = orig_path[depth].p_ext;
738                 tmp_oext = *oext;
739
740                 if (donor_path)
741                         ext4_ext_drop_refs(donor_path);
742                 *err = get_ext_path(donor_inode, donor_off, &donor_path);
743                 if (*err)
744                         goto out;
745                 depth = ext_depth(donor_inode);
746                 dext = donor_path[depth].p_ext;
747                 tmp_dext = *dext;
748
749                 *err = mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
750                                            donor_off, count - replaced_count);
751                 if (*err)
752                         goto out;
753         }
754
755 out:
756         if (orig_path) {
757                 ext4_ext_drop_refs(orig_path);
758                 kfree(orig_path);
759         }
760         if (donor_path) {
761                 ext4_ext_drop_refs(donor_path);
762                 kfree(donor_path);
763         }
764
765         ext4_ext_invalidate_cache(orig_inode);
766         ext4_ext_invalidate_cache(donor_inode);
767
768         double_up_write_data_sem(orig_inode, donor_inode);
769
770         return replaced_count;
771 }
772
773 /**
774  * move_extent_per_page - Move extent data per page
775  *
776  * @o_filp:                     file structure of original file
777  * @donor_inode:                donor inode
778  * @orig_page_offset:           page index on original file
779  * @data_offset_in_page:        block index where data swapping starts
780  * @block_len_in_page:          the number of blocks to be swapped
781  * @uninit:                     orig extent is uninitialized or not
782  * @err:                        pointer to save return value
783  *
784  * Save the data in original inode blocks and replace original inode extents
785  * with donor inode extents by calling mext_replace_branches().
786  * Finally, write out the saved data in new original inode blocks. Return
787  * replaced block count.
788  */
789 static int
790 move_extent_per_page(struct file *o_filp, struct inode *donor_inode,
791                   pgoff_t orig_page_offset, int data_offset_in_page,
792                   int block_len_in_page, int uninit, int *err)
793 {
794         struct inode *orig_inode = o_filp->f_dentry->d_inode;
795         struct address_space *mapping = orig_inode->i_mapping;
796         struct buffer_head *bh;
797         struct page *page = NULL;
798         const struct address_space_operations *a_ops = mapping->a_ops;
799         handle_t *handle;
800         ext4_lblk_t orig_blk_offset;
801         long long offs = orig_page_offset << PAGE_CACHE_SHIFT;
802         unsigned long blocksize = orig_inode->i_sb->s_blocksize;
803         unsigned int w_flags = 0;
804         unsigned int tmp_data_size, data_size, replaced_size;
805         void *fsdata;
806         int i, jblocks;
807         int err2 = 0;
808         int replaced_count = 0;
809         int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
810
811         /*
812          * It needs twice the amount of ordinary journal buffers because
813          * inode and donor_inode may change each different metadata blocks.
814          */
815         jblocks = ext4_writepage_trans_blocks(orig_inode) * 2;
816         handle = ext4_journal_start(orig_inode, jblocks);
817         if (IS_ERR(handle)) {
818                 *err = PTR_ERR(handle);
819                 return 0;
820         }
821
822         if (segment_eq(get_fs(), KERNEL_DS))
823                 w_flags |= AOP_FLAG_UNINTERRUPTIBLE;
824
825         orig_blk_offset = orig_page_offset * blocks_per_page +
826                 data_offset_in_page;
827
828         /*
829          * If orig extent is uninitialized one,
830          * it's not necessary force the page into memory
831          * and then force it to be written out again.
832          * Just swap data blocks between orig and donor.
833          */
834         if (uninit) {
835                 replaced_count = mext_replace_branches(handle, orig_inode,
836                                                 donor_inode, orig_blk_offset,
837                                                 block_len_in_page, err);
838                 goto out2;
839         }
840
841         offs = (long long)orig_blk_offset << orig_inode->i_blkbits;
842
843         /* Calculate data_size */
844         if ((orig_blk_offset + block_len_in_page - 1) ==
845             ((orig_inode->i_size - 1) >> orig_inode->i_blkbits)) {
846                 /* Replace the last block */
847                 tmp_data_size = orig_inode->i_size & (blocksize - 1);
848                 /*
849                  * If data_size equal zero, it shows data_size is multiples of
850                  * blocksize. So we set appropriate value.
851                  */
852                 if (tmp_data_size == 0)
853                         tmp_data_size = blocksize;
854
855                 data_size = tmp_data_size +
856                         ((block_len_in_page - 1) << orig_inode->i_blkbits);
857         } else
858                 data_size = block_len_in_page << orig_inode->i_blkbits;
859
860         replaced_size = data_size;
861
862         *err = a_ops->write_begin(o_filp, mapping, offs, data_size, w_flags,
863                                  &page, &fsdata);
864         if (unlikely(*err < 0))
865                 goto out;
866
867         if (!PageUptodate(page)) {
868                 mapping->a_ops->readpage(o_filp, page);
869                 lock_page(page);
870         }
871
872         /*
873          * try_to_release_page() doesn't call releasepage in writeback mode.
874          * We should care about the order of writing to the same file
875          * by multiple move extent processes.
876          * It needs to call wait_on_page_writeback() to wait for the
877          * writeback of the page.
878          */
879         if (PageWriteback(page))
880                 wait_on_page_writeback(page);
881
882         /* Release old bh and drop refs */
883         try_to_release_page(page, 0);
884
885         replaced_count = mext_replace_branches(handle, orig_inode, donor_inode,
886                                         orig_blk_offset, block_len_in_page,
887                                         &err2);
888         if (err2) {
889                 if (replaced_count) {
890                         block_len_in_page = replaced_count;
891                         replaced_size =
892                                 block_len_in_page << orig_inode->i_blkbits;
893                 } else
894                         goto out;
895         }
896
897         if (!page_has_buffers(page))
898                 create_empty_buffers(page, 1 << orig_inode->i_blkbits, 0);
899
900         bh = page_buffers(page);
901         for (i = 0; i < data_offset_in_page; i++)
902                 bh = bh->b_this_page;
903
904         for (i = 0; i < block_len_in_page; i++) {
905                 *err = ext4_get_block(orig_inode,
906                                 (sector_t)(orig_blk_offset + i), bh, 0);
907                 if (*err < 0)
908                         goto out;
909
910                 if (bh->b_this_page != NULL)
911                         bh = bh->b_this_page;
912         }
913
914         *err = a_ops->write_end(o_filp, mapping, offs, data_size, replaced_size,
915                                page, fsdata);
916         page = NULL;
917
918 out:
919         if (unlikely(page)) {
920                 if (PageLocked(page))
921                         unlock_page(page);
922                 page_cache_release(page);
923                 ext4_journal_stop(handle);
924         }
925 out2:
926         ext4_journal_stop(handle);
927
928         if (err2)
929                 *err = err2;
930
931         return replaced_count;
932 }
933
934 /**
935  * mext_check_argumants - Check whether move extent can be done
936  *
937  * @orig_inode:         original inode
938  * @donor_inode:        donor inode
939  * @orig_start:         logical start offset in block for orig
940  * @donor_start:        logical start offset in block for donor
941  * @len:                the number of blocks to be moved
942  *
943  * Check the arguments of ext4_move_extents() whether the files can be
944  * exchanged with each other.
945  * Return 0 on success, or a negative error value on failure.
946  */
947 static int
948 mext_check_arguments(struct inode *orig_inode,
949                      struct inode *donor_inode, __u64 orig_start,
950                      __u64 donor_start, __u64 *len)
951 {
952         ext4_lblk_t orig_blocks, donor_blocks;
953         unsigned int blkbits = orig_inode->i_blkbits;
954         unsigned int blocksize = 1 << blkbits;
955
956         /* Regular file check */
957         if (!S_ISREG(orig_inode->i_mode) || !S_ISREG(donor_inode->i_mode)) {
958                 ext4_debug("ext4 move extent: The argument files should be "
959                         "regular file [ino:orig %lu, donor %lu]\n",
960                         orig_inode->i_ino, donor_inode->i_ino);
961                 return -EINVAL;
962         }
963
964         if (donor_inode->i_mode & (S_ISUID|S_ISGID)) {
965                 ext4_debug("ext4 move extent: suid or sgid is set"
966                            " to donor file [ino:orig %lu, donor %lu]\n",
967                            orig_inode->i_ino, donor_inode->i_ino);
968                 return -EINVAL;
969         }
970
971         /* Ext4 move extent does not support swapfile */
972         if (IS_SWAPFILE(orig_inode) || IS_SWAPFILE(donor_inode)) {
973                 ext4_debug("ext4 move extent: The argument files should "
974                         "not be swapfile [ino:orig %lu, donor %lu]\n",
975                         orig_inode->i_ino, donor_inode->i_ino);
976                 return -EINVAL;
977         }
978
979         /* Files should be in the same ext4 FS */
980         if (orig_inode->i_sb != donor_inode->i_sb) {
981                 ext4_debug("ext4 move extent: The argument files "
982                         "should be in same FS [ino:orig %lu, donor %lu]\n",
983                         orig_inode->i_ino, donor_inode->i_ino);
984                 return -EINVAL;
985         }
986
987         /* Ext4 move extent supports only extent based file */
988         if (!(EXT4_I(orig_inode)->i_flags & EXT4_EXTENTS_FL)) {
989                 ext4_debug("ext4 move extent: orig file is not extents "
990                         "based file [ino:orig %lu]\n", orig_inode->i_ino);
991                 return -EOPNOTSUPP;
992         } else if (!(EXT4_I(donor_inode)->i_flags & EXT4_EXTENTS_FL)) {
993                 ext4_debug("ext4 move extent: donor file is not extents "
994                         "based file [ino:donor %lu]\n", donor_inode->i_ino);
995                 return -EOPNOTSUPP;
996         }
997
998         if ((!orig_inode->i_size) || (!donor_inode->i_size)) {
999                 ext4_debug("ext4 move extent: File size is 0 byte\n");
1000                 return -EINVAL;
1001         }
1002
1003         /* Start offset should be same */
1004         if (orig_start != donor_start) {
1005                 ext4_debug("ext4 move extent: orig and donor's start "
1006                         "offset are not same [ino:orig %lu, donor %lu]\n",
1007                         orig_inode->i_ino, donor_inode->i_ino);
1008                 return -EINVAL;
1009         }
1010
1011         if ((orig_start > EXT_MAX_BLOCK) ||
1012             (donor_start > EXT_MAX_BLOCK) ||
1013             (*len > EXT_MAX_BLOCK) ||
1014             (orig_start + *len > EXT_MAX_BLOCK))  {
1015                 ext4_debug("ext4 move extent: Can't handle over [%u] blocks "
1016                         "[ino:orig %lu, donor %lu]\n", EXT_MAX_BLOCK,
1017                         orig_inode->i_ino, donor_inode->i_ino);
1018                 return -EINVAL;
1019         }
1020
1021         if (orig_inode->i_size > donor_inode->i_size) {
1022                 donor_blocks = (donor_inode->i_size + blocksize - 1) >> blkbits;
1023                 /* TODO: eliminate this artificial restriction */
1024                 if (orig_start >= donor_blocks) {
1025                         ext4_debug("ext4 move extent: orig start offset "
1026                         "[%llu] should be less than donor file blocks "
1027                         "[%u] [ino:orig %lu, donor %lu]\n",
1028                         orig_start, donor_blocks,
1029                         orig_inode->i_ino, donor_inode->i_ino);
1030                         return -EINVAL;
1031                 }
1032
1033                 /* TODO: eliminate this artificial restriction */
1034                 if (orig_start + *len > donor_blocks) {
1035                         ext4_debug("ext4 move extent: End offset [%llu] should "
1036                                 "be less than donor file blocks [%u]."
1037                                 "So adjust length from %llu to %llu "
1038                                 "[ino:orig %lu, donor %lu]\n",
1039                                 orig_start + *len, donor_blocks,
1040                                 *len, donor_blocks - orig_start,
1041                                 orig_inode->i_ino, donor_inode->i_ino);
1042                         *len = donor_blocks - orig_start;
1043                 }
1044         } else {
1045                 orig_blocks = (orig_inode->i_size + blocksize - 1) >> blkbits;
1046                 if (orig_start >= orig_blocks) {
1047                         ext4_debug("ext4 move extent: start offset [%llu] "
1048                                 "should be less than original file blocks "
1049                                 "[%u] [ino:orig %lu, donor %lu]\n",
1050                                  orig_start, orig_blocks,
1051                                 orig_inode->i_ino, donor_inode->i_ino);
1052                         return -EINVAL;
1053                 }
1054
1055                 if (orig_start + *len > orig_blocks) {
1056                         ext4_debug("ext4 move extent: Adjust length "
1057                                 "from %llu to %llu. Because it should be "
1058                                 "less than original file blocks "
1059                                 "[ino:orig %lu, donor %lu]\n",
1060                                 *len, orig_blocks - orig_start,
1061                                 orig_inode->i_ino, donor_inode->i_ino);
1062                         *len = orig_blocks - orig_start;
1063                 }
1064         }
1065
1066         if (!*len) {
1067                 ext4_debug("ext4 move extent: len should not be 0 "
1068                         "[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
1069                         donor_inode->i_ino);
1070                 return -EINVAL;
1071         }
1072
1073         return 0;
1074 }
1075
1076 /**
1077  * mext_inode_double_lock - Lock i_mutex on both @inode1 and @inode2
1078  *
1079  * @inode1:     the inode structure
1080  * @inode2:     the inode structure
1081  *
1082  * Lock two inodes' i_mutex by i_ino order.
1083  * If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
1084  */
1085 static int
1086 mext_inode_double_lock(struct inode *inode1, struct inode *inode2)
1087 {
1088         int ret = 0;
1089
1090         BUG_ON(inode1 == NULL && inode2 == NULL);
1091
1092         ret = mext_check_null_inode(inode1, inode2, __func__);
1093         if (ret < 0)
1094                 goto out;
1095
1096         if (inode1 == inode2) {
1097                 mutex_lock(&inode1->i_mutex);
1098                 goto out;
1099         }
1100
1101         if (inode1->i_ino < inode2->i_ino) {
1102                 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
1103                 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
1104         } else {
1105                 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_PARENT);
1106                 mutex_lock_nested(&inode1->i_mutex, I_MUTEX_CHILD);
1107         }
1108
1109 out:
1110         return ret;
1111 }
1112
1113 /**
1114  * mext_inode_double_unlock - Release i_mutex on both @inode1 and @inode2
1115  *
1116  * @inode1:     the inode that is released first
1117  * @inode2:     the inode that is released second
1118  *
1119  * If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
1120  */
1121
1122 static int
1123 mext_inode_double_unlock(struct inode *inode1, struct inode *inode2)
1124 {
1125         int ret = 0;
1126
1127         BUG_ON(inode1 == NULL && inode2 == NULL);
1128
1129         ret = mext_check_null_inode(inode1, inode2, __func__);
1130         if (ret < 0)
1131                 goto out;
1132
1133         if (inode1)
1134                 mutex_unlock(&inode1->i_mutex);
1135
1136         if (inode2 && inode2 != inode1)
1137                 mutex_unlock(&inode2->i_mutex);
1138
1139 out:
1140         return ret;
1141 }
1142
1143 /**
1144  * ext4_move_extents - Exchange the specified range of a file
1145  *
1146  * @o_filp:             file structure of the original file
1147  * @d_filp:             file structure of the donor file
1148  * @orig_start:         start offset in block for orig
1149  * @donor_start:        start offset in block for donor
1150  * @len:                the number of blocks to be moved
1151  * @moved_len:          moved block length
1152  *
1153  * This function returns 0 and moved block length is set in moved_len
1154  * if succeed, otherwise returns error value.
1155  *
1156  * Note: ext4_move_extents() proceeds the following order.
1157  * 1:ext4_move_extents() calculates the last block number of moving extent
1158  *   function by the start block number (orig_start) and the number of blocks
1159  *   to be moved (len) specified as arguments.
1160  *   If the {orig, donor}_start points a hole, the extent's start offset
1161  *   pointed by ext_cur (current extent), holecheck_path, orig_path are set
1162  *   after hole behind.
1163  * 2:Continue step 3 to step 5, until the holecheck_path points to last_extent
1164  *   or the ext_cur exceeds the block_end which is last logical block number.
1165  * 3:To get the length of continues area, call mext_next_extent()
1166  *   specified with the ext_cur (initial value is holecheck_path) re-cursive,
1167  *   until find un-continuous extent, the start logical block number exceeds
1168  *   the block_end or the extent points to the last extent.
1169  * 4:Exchange the original inode data with donor inode data
1170  *   from orig_page_offset to seq_end_page.
1171  *   The start indexes of data are specified as arguments.
1172  *   That of the original inode is orig_page_offset,
1173  *   and the donor inode is also orig_page_offset
1174  *   (To easily handle blocksize != pagesize case, the offset for the
1175  *   donor inode is block unit).
1176  * 5:Update holecheck_path and orig_path to points a next proceeding extent,
1177  *   then returns to step 2.
1178  * 6:Release holecheck_path, orig_path and set the len to moved_len
1179  *   which shows the number of moved blocks.
1180  *   The moved_len is useful for the command to calculate the file offset
1181  *   for starting next move extent ioctl.
1182  * 7:Return 0 on success, or a negative error value on failure.
1183  */
1184 int
1185 ext4_move_extents(struct file *o_filp, struct file *d_filp,
1186                  __u64 orig_start, __u64 donor_start, __u64 len,
1187                  __u64 *moved_len)
1188 {
1189         struct inode *orig_inode = o_filp->f_dentry->d_inode;
1190         struct inode *donor_inode = d_filp->f_dentry->d_inode;
1191         struct ext4_ext_path *orig_path = NULL, *holecheck_path = NULL;
1192         struct ext4_extent *ext_prev, *ext_cur, *ext_dummy;
1193         ext4_lblk_t block_start = orig_start;
1194         ext4_lblk_t block_end, seq_start, add_blocks, file_end, seq_blocks = 0;
1195         ext4_lblk_t rest_blocks;
1196         pgoff_t orig_page_offset = 0, seq_end_page;
1197         int ret1, ret2, depth, last_extent = 0;
1198         int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
1199         int data_offset_in_page;
1200         int block_len_in_page;
1201         int uninit;
1202
1203         /* orig and donor should be different file */
1204         if (orig_inode->i_ino == donor_inode->i_ino) {
1205                 ext4_debug("ext4 move extent: The argument files should not "
1206                         "be same file [ino:orig %lu, donor %lu]\n",
1207                         orig_inode->i_ino, donor_inode->i_ino);
1208                 return -EINVAL;
1209         }
1210
1211         /* Protect orig and donor inodes against a truncate */
1212         ret1 = mext_inode_double_lock(orig_inode, donor_inode);
1213         if (ret1 < 0)
1214                 return ret1;
1215
1216         /* Protect extent tree against block allocations via delalloc */
1217         double_down_write_data_sem(orig_inode, donor_inode);
1218         /* Check the filesystem environment whether move_extent can be done */
1219         ret1 = mext_check_arguments(orig_inode, donor_inode, orig_start,
1220                                     donor_start, &len);
1221         if (ret1)
1222                 goto out;
1223
1224         file_end = (i_size_read(orig_inode) - 1) >> orig_inode->i_blkbits;
1225         block_end = block_start + len - 1;
1226         if (file_end < block_end)
1227                 len -= block_end - file_end;
1228
1229         ret1 = get_ext_path(orig_inode, block_start, &orig_path);
1230         if (ret1)
1231                 goto out;
1232
1233         /* Get path structure to check the hole */
1234         ret1 = get_ext_path(orig_inode, block_start, &holecheck_path);
1235         if (ret1)
1236                 goto out;
1237
1238         depth = ext_depth(orig_inode);
1239         ext_cur = holecheck_path[depth].p_ext;
1240
1241         /*
1242          * Get proper starting location of block replacement if block_start was
1243          * within the hole.
1244          */
1245         if (le32_to_cpu(ext_cur->ee_block) +
1246                 ext4_ext_get_actual_len(ext_cur) - 1 < block_start) {
1247                 /*
1248                  * The hole exists between extents or the tail of
1249                  * original file.
1250                  */
1251                 last_extent = mext_next_extent(orig_inode,
1252                                         holecheck_path, &ext_cur);
1253                 if (last_extent < 0) {
1254                         ret1 = last_extent;
1255                         goto out;
1256                 }
1257                 last_extent = mext_next_extent(orig_inode, orig_path,
1258                                                         &ext_dummy);
1259                 if (last_extent < 0) {
1260                         ret1 = last_extent;
1261                         goto out;
1262                 }
1263                 seq_start = le32_to_cpu(ext_cur->ee_block);
1264         } else if (le32_to_cpu(ext_cur->ee_block) > block_start)
1265                 /* The hole exists at the beginning of original file. */
1266                 seq_start = le32_to_cpu(ext_cur->ee_block);
1267         else
1268                 seq_start = block_start;
1269
1270         /* No blocks within the specified range. */
1271         if (le32_to_cpu(ext_cur->ee_block) > block_end) {
1272                 ext4_debug("ext4 move extent: The specified range of file "
1273                                                         "may be the hole\n");
1274                 ret1 = -EINVAL;
1275                 goto out;
1276         }
1277
1278         /* Adjust start blocks */
1279         add_blocks = min(le32_to_cpu(ext_cur->ee_block) +
1280                          ext4_ext_get_actual_len(ext_cur), block_end + 1) -
1281                      max(le32_to_cpu(ext_cur->ee_block), block_start);
1282
1283         while (!last_extent && le32_to_cpu(ext_cur->ee_block) <= block_end) {
1284                 seq_blocks += add_blocks;
1285
1286                 /* Adjust tail blocks */
1287                 if (seq_start + seq_blocks - 1 > block_end)
1288                         seq_blocks = block_end - seq_start + 1;
1289
1290                 ext_prev = ext_cur;
1291                 last_extent = mext_next_extent(orig_inode, holecheck_path,
1292                                                 &ext_cur);
1293                 if (last_extent < 0) {
1294                         ret1 = last_extent;
1295                         break;
1296                 }
1297                 add_blocks = ext4_ext_get_actual_len(ext_cur);
1298
1299                 /*
1300                  * Extend the length of contiguous block (seq_blocks)
1301                  * if extents are contiguous.
1302                  */
1303                 if (ext4_can_extents_be_merged(orig_inode,
1304                                                ext_prev, ext_cur) &&
1305                     block_end >= le32_to_cpu(ext_cur->ee_block) &&
1306                     !last_extent)
1307                         continue;
1308
1309                 /* Is original extent is uninitialized */
1310                 uninit = ext4_ext_is_uninitialized(ext_prev);
1311
1312                 data_offset_in_page = seq_start % blocks_per_page;
1313
1314                 /*
1315                  * Calculate data blocks count that should be swapped
1316                  * at the first page.
1317                  */
1318                 if (data_offset_in_page + seq_blocks > blocks_per_page) {
1319                         /* Swapped blocks are across pages */
1320                         block_len_in_page =
1321                                         blocks_per_page - data_offset_in_page;
1322                 } else {
1323                         /* Swapped blocks are in a page */
1324                         block_len_in_page = seq_blocks;
1325                 }
1326
1327                 orig_page_offset = seq_start >>
1328                                 (PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
1329                 seq_end_page = (seq_start + seq_blocks - 1) >>
1330                                 (PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
1331                 seq_start = le32_to_cpu(ext_cur->ee_block);
1332                 rest_blocks = seq_blocks;
1333
1334                 /*
1335                  * Up semaphore to avoid following problems:
1336                  * a. transaction deadlock among ext4_journal_start,
1337                  *    ->write_begin via pagefault, and jbd2_journal_commit
1338                  * b. racing with ->readpage, ->write_begin, and ext4_get_block
1339                  *    in move_extent_per_page
1340                  */
1341                 double_up_write_data_sem(orig_inode, donor_inode);
1342
1343                 while (orig_page_offset <= seq_end_page) {
1344
1345                         /* Swap original branches with new branches */
1346                         block_len_in_page = move_extent_per_page(
1347                                                 o_filp, donor_inode,
1348                                                 orig_page_offset,
1349                                                 data_offset_in_page,
1350                                                 block_len_in_page, uninit,
1351                                                 &ret1);
1352
1353                         /* Count how many blocks we have exchanged */
1354                         *moved_len += block_len_in_page;
1355                         if (ret1 < 0)
1356                                 break;
1357                         if (*moved_len > len) {
1358                                 ext4_error(orig_inode->i_sb,
1359                                         "We replaced blocks too much! "
1360                                         "sum of replaced: %llu requested: %llu",
1361                                         *moved_len, len);
1362                                 ret1 = -EIO;
1363                                 break;
1364                         }
1365
1366                         orig_page_offset++;
1367                         data_offset_in_page = 0;
1368                         rest_blocks -= block_len_in_page;
1369                         if (rest_blocks > blocks_per_page)
1370                                 block_len_in_page = blocks_per_page;
1371                         else
1372                                 block_len_in_page = rest_blocks;
1373                 }
1374
1375                 double_down_write_data_sem(orig_inode, donor_inode);
1376                 if (ret1 < 0)
1377                         break;
1378
1379                 /* Decrease buffer counter */
1380                 if (holecheck_path)
1381                         ext4_ext_drop_refs(holecheck_path);
1382                 ret1 = get_ext_path(orig_inode, seq_start, &holecheck_path);
1383                 if (ret1)
1384                         break;
1385                 depth = holecheck_path->p_depth;
1386
1387                 /* Decrease buffer counter */
1388                 if (orig_path)
1389                         ext4_ext_drop_refs(orig_path);
1390                 ret1 = get_ext_path(orig_inode, seq_start, &orig_path);
1391                 if (ret1)
1392                         break;
1393
1394                 ext_cur = holecheck_path[depth].p_ext;
1395                 add_blocks = ext4_ext_get_actual_len(ext_cur);
1396                 seq_blocks = 0;
1397
1398         }
1399 out:
1400         if (*moved_len) {
1401                 ext4_discard_preallocations(orig_inode);
1402                 ext4_discard_preallocations(donor_inode);
1403         }
1404
1405         if (orig_path) {
1406                 ext4_ext_drop_refs(orig_path);
1407                 kfree(orig_path);
1408         }
1409         if (holecheck_path) {
1410                 ext4_ext_drop_refs(holecheck_path);
1411                 kfree(holecheck_path);
1412         }
1413         double_up_write_data_sem(orig_inode, donor_inode);
1414         ret2 = mext_inode_double_unlock(orig_inode, donor_inode);
1415
1416         if (ret1)
1417                 return ret1;
1418         else if (ret2)
1419                 return ret2;
1420
1421         return 0;
1422 }