xref: /openbmc/linux/fs/ext4/move_extent.c (revision 85dd2c8f)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  * Copyright (c) 2008,2009 NEC Software Tohoku, Ltd.
4  * Written by Takashi Sato <t-sato@yk.jp.nec.com>
5  *            Akira Fujita <a-fujita@rs.jp.nec.com>
6  */
7 
8 #include <linux/fs.h>
9 #include <linux/quotaops.h>
10 #include <linux/slab.h>
11 #include <linux/sched/mm.h>
12 #include "ext4_jbd2.h"
13 #include "ext4.h"
14 #include "ext4_extents.h"
15 
16 /**
17  * get_ext_path() - Find an extent path for designated logical block number.
18  * @inode:	inode to be searched
19  * @lblock:	logical block number to find an extent path
20  * @ppath:	pointer to an extent path pointer (for output)
21  *
22  * ext4_find_extent wrapper. Return 0 on success, or a negative error value
23  * on failure.
24  */
25 static inline int
26 get_ext_path(struct inode *inode, ext4_lblk_t lblock,
27 		struct ext4_ext_path **ppath)
28 {
29 	struct ext4_ext_path *path;
30 
31 	path = ext4_find_extent(inode, lblock, ppath, EXT4_EX_NOCACHE);
32 	if (IS_ERR(path))
33 		return PTR_ERR(path);
34 	if (path[ext_depth(inode)].p_ext == NULL) {
35 		ext4_free_ext_path(path);
36 		*ppath = NULL;
37 		return -ENODATA;
38 	}
39 	*ppath = path;
40 	return 0;
41 }
42 
43 /**
44  * ext4_double_down_write_data_sem() - write lock two inodes's i_data_sem
45  * @first: inode to be locked
46  * @second: inode to be locked
47  *
48  * Acquire write lock of i_data_sem of the two inodes
49  */
50 void
51 ext4_double_down_write_data_sem(struct inode *first, struct inode *second)
52 {
53 	if (first < second) {
54 		down_write(&EXT4_I(first)->i_data_sem);
55 		down_write_nested(&EXT4_I(second)->i_data_sem, I_DATA_SEM_OTHER);
56 	} else {
57 		down_write(&EXT4_I(second)->i_data_sem);
58 		down_write_nested(&EXT4_I(first)->i_data_sem, I_DATA_SEM_OTHER);
59 
60 	}
61 }
62 
63 /**
64  * ext4_double_up_write_data_sem - Release two inodes' write lock of i_data_sem
65  *
66  * @orig_inode:		original inode structure to be released its lock first
67  * @donor_inode:	donor inode structure to be released its lock second
68  * Release write lock of i_data_sem of two inodes (orig and donor).
69  */
70 void
71 ext4_double_up_write_data_sem(struct inode *orig_inode,
72 			      struct inode *donor_inode)
73 {
74 	up_write(&EXT4_I(orig_inode)->i_data_sem);
75 	up_write(&EXT4_I(donor_inode)->i_data_sem);
76 }
77 
78 /**
79  * mext_check_coverage - Check that all extents in range has the same type
80  *
81  * @inode:		inode in question
82  * @from:		block offset of inode
83  * @count:		block count to be checked
84  * @unwritten:		extents expected to be unwritten
85  * @err:		pointer to save error value
86  *
87  * Return 1 if all extents in range has expected type, and zero otherwise.
88  */
89 static int
90 mext_check_coverage(struct inode *inode, ext4_lblk_t from, ext4_lblk_t count,
91 		    int unwritten, int *err)
92 {
93 	struct ext4_ext_path *path = NULL;
94 	struct ext4_extent *ext;
95 	int ret = 0;
96 	ext4_lblk_t last = from + count;
97 	while (from < last) {
98 		*err = get_ext_path(inode, from, &path);
99 		if (*err)
100 			goto out;
101 		ext = path[ext_depth(inode)].p_ext;
102 		if (unwritten != ext4_ext_is_unwritten(ext))
103 			goto out;
104 		from += ext4_ext_get_actual_len(ext);
105 	}
106 	ret = 1;
107 out:
108 	ext4_free_ext_path(path);
109 	return ret;
110 }
111 
112 /**
113  * mext_page_double_lock - Grab and lock pages on both @inode1 and @inode2
114  *
115  * @inode1:	the inode structure
116  * @inode2:	the inode structure
117  * @index1:	page index
118  * @index2:	page index
119  * @page:	result page vector
120  *
121  * Grab two locked pages for inode's by inode order
122  */
123 static int
124 mext_page_double_lock(struct inode *inode1, struct inode *inode2,
125 		      pgoff_t index1, pgoff_t index2, struct page *page[2])
126 {
127 	struct address_space *mapping[2];
128 	unsigned int flags;
129 
130 	BUG_ON(!inode1 || !inode2);
131 	if (inode1 < inode2) {
132 		mapping[0] = inode1->i_mapping;
133 		mapping[1] = inode2->i_mapping;
134 	} else {
135 		swap(index1, index2);
136 		mapping[0] = inode2->i_mapping;
137 		mapping[1] = inode1->i_mapping;
138 	}
139 
140 	flags = memalloc_nofs_save();
141 	page[0] = grab_cache_page_write_begin(mapping[0], index1);
142 	if (!page[0]) {
143 		memalloc_nofs_restore(flags);
144 		return -ENOMEM;
145 	}
146 
147 	page[1] = grab_cache_page_write_begin(mapping[1], index2);
148 	memalloc_nofs_restore(flags);
149 	if (!page[1]) {
150 		unlock_page(page[0]);
151 		put_page(page[0]);
152 		return -ENOMEM;
153 	}
154 	/*
155 	 * grab_cache_page_write_begin() may not wait on page's writeback if
156 	 * BDI not demand that. But it is reasonable to be very conservative
157 	 * here and explicitly wait on page's writeback
158 	 */
159 	wait_on_page_writeback(page[0]);
160 	wait_on_page_writeback(page[1]);
161 	if (inode1 > inode2)
162 		swap(page[0], page[1]);
163 
164 	return 0;
165 }
166 
167 /* Force page buffers uptodate w/o dropping page's lock */
168 static int
169 mext_page_mkuptodate(struct page *page, unsigned from, unsigned to)
170 {
171 	struct inode *inode = page->mapping->host;
172 	sector_t block;
173 	struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
174 	unsigned int blocksize, block_start, block_end;
175 	int i, err,  nr = 0, partial = 0;
176 	BUG_ON(!PageLocked(page));
177 	BUG_ON(PageWriteback(page));
178 
179 	if (PageUptodate(page))
180 		return 0;
181 
182 	blocksize = i_blocksize(inode);
183 	if (!page_has_buffers(page))
184 		create_empty_buffers(page, blocksize, 0);
185 
186 	head = page_buffers(page);
187 	block = (sector_t)page->index << (PAGE_SHIFT - inode->i_blkbits);
188 	for (bh = head, block_start = 0; bh != head || !block_start;
189 	     block++, block_start = block_end, bh = bh->b_this_page) {
190 		block_end = block_start + blocksize;
191 		if (block_end <= from || block_start >= to) {
192 			if (!buffer_uptodate(bh))
193 				partial = 1;
194 			continue;
195 		}
196 		if (buffer_uptodate(bh))
197 			continue;
198 		if (!buffer_mapped(bh)) {
199 			err = ext4_get_block(inode, block, bh, 0);
200 			if (err) {
201 				SetPageError(page);
202 				return err;
203 			}
204 			if (!buffer_mapped(bh)) {
205 				zero_user(page, block_start, blocksize);
206 				set_buffer_uptodate(bh);
207 				continue;
208 			}
209 		}
210 		BUG_ON(nr >= MAX_BUF_PER_PAGE);
211 		arr[nr++] = bh;
212 	}
213 	/* No io required */
214 	if (!nr)
215 		goto out;
216 
217 	for (i = 0; i < nr; i++) {
218 		bh = arr[i];
219 		if (!bh_uptodate_or_lock(bh)) {
220 			err = ext4_read_bh(bh, 0, NULL);
221 			if (err)
222 				return err;
223 		}
224 	}
225 out:
226 	if (!partial)
227 		SetPageUptodate(page);
228 	return 0;
229 }
230 
231 /**
232  * move_extent_per_page - Move extent data per page
233  *
234  * @o_filp:			file structure of original file
235  * @donor_inode:		donor inode
236  * @orig_page_offset:		page index on original file
237  * @donor_page_offset:		page index on donor file
238  * @data_offset_in_page:	block index where data swapping starts
239  * @block_len_in_page:		the number of blocks to be swapped
240  * @unwritten:			orig extent is unwritten or not
241  * @err:			pointer to save return value
242  *
243  * Save the data in original inode blocks and replace original inode extents
244  * with donor inode extents by calling ext4_swap_extents().
245  * Finally, write out the saved data in new original inode blocks. Return
246  * replaced block count.
247  */
248 static int
249 move_extent_per_page(struct file *o_filp, struct inode *donor_inode,
250 		     pgoff_t orig_page_offset, pgoff_t donor_page_offset,
251 		     int data_offset_in_page,
252 		     int block_len_in_page, int unwritten, int *err)
253 {
254 	struct inode *orig_inode = file_inode(o_filp);
255 	struct page *pagep[2] = {NULL, NULL};
256 	struct folio *folio[2] = {NULL, NULL};
257 	handle_t *handle;
258 	ext4_lblk_t orig_blk_offset, donor_blk_offset;
259 	unsigned long blocksize = orig_inode->i_sb->s_blocksize;
260 	unsigned int tmp_data_size, data_size, replaced_size;
261 	int i, err2, jblocks, retries = 0;
262 	int replaced_count = 0;
263 	int from = data_offset_in_page << orig_inode->i_blkbits;
264 	int blocks_per_page = PAGE_SIZE >> orig_inode->i_blkbits;
265 	struct super_block *sb = orig_inode->i_sb;
266 	struct buffer_head *bh = NULL;
267 
268 	/*
269 	 * It needs twice the amount of ordinary journal buffers because
270 	 * inode and donor_inode may change each different metadata blocks.
271 	 */
272 again:
273 	*err = 0;
274 	jblocks = ext4_writepage_trans_blocks(orig_inode) * 2;
275 	handle = ext4_journal_start(orig_inode, EXT4_HT_MOVE_EXTENTS, jblocks);
276 	if (IS_ERR(handle)) {
277 		*err = PTR_ERR(handle);
278 		return 0;
279 	}
280 
281 	orig_blk_offset = orig_page_offset * blocks_per_page +
282 		data_offset_in_page;
283 
284 	donor_blk_offset = donor_page_offset * blocks_per_page +
285 		data_offset_in_page;
286 
287 	/* Calculate data_size */
288 	if ((orig_blk_offset + block_len_in_page - 1) ==
289 	    ((orig_inode->i_size - 1) >> orig_inode->i_blkbits)) {
290 		/* Replace the last block */
291 		tmp_data_size = orig_inode->i_size & (blocksize - 1);
292 		/*
293 		 * If data_size equal zero, it shows data_size is multiples of
294 		 * blocksize. So we set appropriate value.
295 		 */
296 		if (tmp_data_size == 0)
297 			tmp_data_size = blocksize;
298 
299 		data_size = tmp_data_size +
300 			((block_len_in_page - 1) << orig_inode->i_blkbits);
301 	} else
302 		data_size = block_len_in_page << orig_inode->i_blkbits;
303 
304 	replaced_size = data_size;
305 
306 	*err = mext_page_double_lock(orig_inode, donor_inode, orig_page_offset,
307 				     donor_page_offset, pagep);
308 	if (unlikely(*err < 0))
309 		goto stop_journal;
310 	/*
311 	 * If orig extent was unwritten it can become initialized
312 	 * at any time after i_data_sem was dropped, in order to
313 	 * serialize with delalloc we have recheck extent while we
314 	 * hold page's lock, if it is still the case data copy is not
315 	 * necessary, just swap data blocks between orig and donor.
316 	 */
317 	folio[0] = page_folio(pagep[0]);
318 	folio[1] = page_folio(pagep[1]);
319 
320 	VM_BUG_ON_FOLIO(folio_test_large(folio[0]), folio[0]);
321 	VM_BUG_ON_FOLIO(folio_test_large(folio[1]), folio[1]);
322 	VM_BUG_ON_FOLIO(folio_nr_pages(folio[0]) != folio_nr_pages(folio[1]), folio[1]);
323 
324 	if (unwritten) {
325 		ext4_double_down_write_data_sem(orig_inode, donor_inode);
326 		/* If any of extents in range became initialized we have to
327 		 * fallback to data copying */
328 		unwritten = mext_check_coverage(orig_inode, orig_blk_offset,
329 						block_len_in_page, 1, err);
330 		if (*err)
331 			goto drop_data_sem;
332 
333 		unwritten &= mext_check_coverage(donor_inode, donor_blk_offset,
334 						 block_len_in_page, 1, err);
335 		if (*err)
336 			goto drop_data_sem;
337 
338 		if (!unwritten) {
339 			ext4_double_up_write_data_sem(orig_inode, donor_inode);
340 			goto data_copy;
341 		}
342 		if ((folio_has_private(folio[0]) &&
343 		     !filemap_release_folio(folio[0], 0)) ||
344 		    (folio_has_private(folio[1]) &&
345 		     !filemap_release_folio(folio[1], 0))) {
346 			*err = -EBUSY;
347 			goto drop_data_sem;
348 		}
349 		replaced_count = ext4_swap_extents(handle, orig_inode,
350 						   donor_inode, orig_blk_offset,
351 						   donor_blk_offset,
352 						   block_len_in_page, 1, err);
353 	drop_data_sem:
354 		ext4_double_up_write_data_sem(orig_inode, donor_inode);
355 		goto unlock_folios;
356 	}
357 data_copy:
358 	*err = mext_page_mkuptodate(&folio[0]->page, from, from + replaced_size);
359 	if (*err)
360 		goto unlock_folios;
361 
362 	/* At this point all buffers in range are uptodate, old mapping layout
363 	 * is no longer required, try to drop it now. */
364 	if ((folio_has_private(folio[0]) &&
365 		!filemap_release_folio(folio[0], 0)) ||
366 	    (folio_has_private(folio[1]) &&
367 		!filemap_release_folio(folio[1], 0))) {
368 		*err = -EBUSY;
369 		goto unlock_folios;
370 	}
371 	ext4_double_down_write_data_sem(orig_inode, donor_inode);
372 	replaced_count = ext4_swap_extents(handle, orig_inode, donor_inode,
373 					       orig_blk_offset, donor_blk_offset,
374 					   block_len_in_page, 1, err);
375 	ext4_double_up_write_data_sem(orig_inode, donor_inode);
376 	if (*err) {
377 		if (replaced_count) {
378 			block_len_in_page = replaced_count;
379 			replaced_size =
380 				block_len_in_page << orig_inode->i_blkbits;
381 		} else
382 			goto unlock_folios;
383 	}
384 	/* Perform all necessary steps similar write_begin()/write_end()
385 	 * but keeping in mind that i_size will not change */
386 	if (!folio_buffers(folio[0]))
387 		create_empty_buffers(&folio[0]->page, 1 << orig_inode->i_blkbits, 0);
388 	bh = folio_buffers(folio[0]);
389 	for (i = 0; i < data_offset_in_page; i++)
390 		bh = bh->b_this_page;
391 	for (i = 0; i < block_len_in_page; i++) {
392 		*err = ext4_get_block(orig_inode, orig_blk_offset + i, bh, 0);
393 		if (*err < 0)
394 			break;
395 		bh = bh->b_this_page;
396 	}
397 	if (!*err)
398 		*err = block_commit_write(&folio[0]->page, from, from + replaced_size);
399 
400 	if (unlikely(*err < 0))
401 		goto repair_branches;
402 
403 	/* Even in case of data=writeback it is reasonable to pin
404 	 * inode to transaction, to prevent unexpected data loss */
405 	*err = ext4_jbd2_inode_add_write(handle, orig_inode,
406 			(loff_t)orig_page_offset << PAGE_SHIFT, replaced_size);
407 
408 unlock_folios:
409 	folio_unlock(folio[0]);
410 	folio_put(folio[0]);
411 	folio_unlock(folio[1]);
412 	folio_put(folio[1]);
413 stop_journal:
414 	ext4_journal_stop(handle);
415 	if (*err == -ENOSPC &&
416 	    ext4_should_retry_alloc(sb, &retries))
417 		goto again;
418 	/* Buffer was busy because probably is pinned to journal transaction,
419 	 * force transaction commit may help to free it. */
420 	if (*err == -EBUSY && retries++ < 4 && EXT4_SB(sb)->s_journal &&
421 	    jbd2_journal_force_commit_nested(EXT4_SB(sb)->s_journal))
422 		goto again;
423 	return replaced_count;
424 
425 repair_branches:
426 	/*
427 	 * This should never ever happen!
428 	 * Extents are swapped already, but we are not able to copy data.
429 	 * Try to swap extents to it's original places
430 	 */
431 	ext4_double_down_write_data_sem(orig_inode, donor_inode);
432 	replaced_count = ext4_swap_extents(handle, donor_inode, orig_inode,
433 					       orig_blk_offset, donor_blk_offset,
434 					   block_len_in_page, 0, &err2);
435 	ext4_double_up_write_data_sem(orig_inode, donor_inode);
436 	if (replaced_count != block_len_in_page) {
437 		ext4_error_inode_block(orig_inode, (sector_t)(orig_blk_offset),
438 				       EIO, "Unable to copy data block,"
439 				       " data will be lost.");
440 		*err = -EIO;
441 	}
442 	replaced_count = 0;
443 	goto unlock_folios;
444 }
445 
446 /**
447  * mext_check_arguments - Check whether move extent can be done
448  *
449  * @orig_inode:		original inode
450  * @donor_inode:	donor inode
451  * @orig_start:		logical start offset in block for orig
452  * @donor_start:	logical start offset in block for donor
453  * @len:		the number of blocks to be moved
454  *
455  * Check the arguments of ext4_move_extents() whether the files can be
456  * exchanged with each other.
457  * Return 0 on success, or a negative error value on failure.
458  */
459 static int
460 mext_check_arguments(struct inode *orig_inode,
461 		     struct inode *donor_inode, __u64 orig_start,
462 		     __u64 donor_start, __u64 *len)
463 {
464 	__u64 orig_eof, donor_eof;
465 	unsigned int blkbits = orig_inode->i_blkbits;
466 	unsigned int blocksize = 1 << blkbits;
467 
468 	orig_eof = (i_size_read(orig_inode) + blocksize - 1) >> blkbits;
469 	donor_eof = (i_size_read(donor_inode) + blocksize - 1) >> blkbits;
470 
471 
472 	if (donor_inode->i_mode & (S_ISUID|S_ISGID)) {
473 		ext4_debug("ext4 move extent: suid or sgid is set"
474 			   " to donor file [ino:orig %lu, donor %lu]\n",
475 			   orig_inode->i_ino, donor_inode->i_ino);
476 		return -EINVAL;
477 	}
478 
479 	if (IS_IMMUTABLE(donor_inode) || IS_APPEND(donor_inode))
480 		return -EPERM;
481 
482 	/* Ext4 move extent does not support swap files */
483 	if (IS_SWAPFILE(orig_inode) || IS_SWAPFILE(donor_inode)) {
484 		ext4_debug("ext4 move extent: The argument files should not be swap files [ino:orig %lu, donor %lu]\n",
485 			orig_inode->i_ino, donor_inode->i_ino);
486 		return -ETXTBSY;
487 	}
488 
489 	if (ext4_is_quota_file(orig_inode) && ext4_is_quota_file(donor_inode)) {
490 		ext4_debug("ext4 move extent: The argument files should not be quota files [ino:orig %lu, donor %lu]\n",
491 			orig_inode->i_ino, donor_inode->i_ino);
492 		return -EOPNOTSUPP;
493 	}
494 
495 	/* Ext4 move extent supports only extent based file */
496 	if (!(ext4_test_inode_flag(orig_inode, EXT4_INODE_EXTENTS))) {
497 		ext4_debug("ext4 move extent: orig file is not extents "
498 			"based file [ino:orig %lu]\n", orig_inode->i_ino);
499 		return -EOPNOTSUPP;
500 	} else if (!(ext4_test_inode_flag(donor_inode, EXT4_INODE_EXTENTS))) {
501 		ext4_debug("ext4 move extent: donor file is not extents "
502 			"based file [ino:donor %lu]\n", donor_inode->i_ino);
503 		return -EOPNOTSUPP;
504 	}
505 
506 	if ((!orig_inode->i_size) || (!donor_inode->i_size)) {
507 		ext4_debug("ext4 move extent: File size is 0 byte\n");
508 		return -EINVAL;
509 	}
510 
511 	/* Start offset should be same */
512 	if ((orig_start & ~(PAGE_MASK >> orig_inode->i_blkbits)) !=
513 	    (donor_start & ~(PAGE_MASK >> orig_inode->i_blkbits))) {
514 		ext4_debug("ext4 move extent: orig and donor's start "
515 			"offsets are not aligned [ino:orig %lu, donor %lu]\n",
516 			orig_inode->i_ino, donor_inode->i_ino);
517 		return -EINVAL;
518 	}
519 
520 	if ((orig_start >= EXT_MAX_BLOCKS) ||
521 	    (donor_start >= EXT_MAX_BLOCKS) ||
522 	    (*len > EXT_MAX_BLOCKS) ||
523 	    (donor_start + *len >= EXT_MAX_BLOCKS) ||
524 	    (orig_start + *len >= EXT_MAX_BLOCKS))  {
525 		ext4_debug("ext4 move extent: Can't handle over [%u] blocks "
526 			"[ino:orig %lu, donor %lu]\n", EXT_MAX_BLOCKS,
527 			orig_inode->i_ino, donor_inode->i_ino);
528 		return -EINVAL;
529 	}
530 	if (orig_eof <= orig_start)
531 		*len = 0;
532 	else if (orig_eof < orig_start + *len - 1)
533 		*len = orig_eof - orig_start;
534 	if (donor_eof <= donor_start)
535 		*len = 0;
536 	else if (donor_eof < donor_start + *len - 1)
537 		*len = donor_eof - donor_start;
538 	if (!*len) {
539 		ext4_debug("ext4 move extent: len should not be 0 "
540 			"[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
541 			donor_inode->i_ino);
542 		return -EINVAL;
543 	}
544 
545 	return 0;
546 }
547 
548 /**
549  * ext4_move_extents - Exchange the specified range of a file
550  *
551  * @o_filp:		file structure of the original file
552  * @d_filp:		file structure of the donor file
553  * @orig_blk:		start offset in block for orig
554  * @donor_blk:		start offset in block for donor
555  * @len:		the number of blocks to be moved
556  * @moved_len:		moved block length
557  *
558  * This function returns 0 and moved block length is set in moved_len
559  * if succeed, otherwise returns error value.
560  *
561  */
562 int
563 ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk,
564 		  __u64 donor_blk, __u64 len, __u64 *moved_len)
565 {
566 	struct inode *orig_inode = file_inode(o_filp);
567 	struct inode *donor_inode = file_inode(d_filp);
568 	struct ext4_ext_path *path = NULL;
569 	int blocks_per_page = PAGE_SIZE >> orig_inode->i_blkbits;
570 	ext4_lblk_t o_end, o_start = orig_blk;
571 	ext4_lblk_t d_start = donor_blk;
572 	int ret;
573 
574 	if (orig_inode->i_sb != donor_inode->i_sb) {
575 		ext4_debug("ext4 move extent: The argument files "
576 			"should be in same FS [ino:orig %lu, donor %lu]\n",
577 			orig_inode->i_ino, donor_inode->i_ino);
578 		return -EINVAL;
579 	}
580 
581 	/* orig and donor should be different inodes */
582 	if (orig_inode == donor_inode) {
583 		ext4_debug("ext4 move extent: The argument files should not "
584 			"be same inode [ino:orig %lu, donor %lu]\n",
585 			orig_inode->i_ino, donor_inode->i_ino);
586 		return -EINVAL;
587 	}
588 
589 	/* Regular file check */
590 	if (!S_ISREG(orig_inode->i_mode) || !S_ISREG(donor_inode->i_mode)) {
591 		ext4_debug("ext4 move extent: The argument files should be "
592 			"regular file [ino:orig %lu, donor %lu]\n",
593 			orig_inode->i_ino, donor_inode->i_ino);
594 		return -EINVAL;
595 	}
596 
597 	/* TODO: it's not obvious how to swap blocks for inodes with full
598 	   journaling enabled */
599 	if (ext4_should_journal_data(orig_inode) ||
600 	    ext4_should_journal_data(donor_inode)) {
601 		ext4_msg(orig_inode->i_sb, KERN_ERR,
602 			 "Online defrag not supported with data journaling");
603 		return -EOPNOTSUPP;
604 	}
605 
606 	if (IS_ENCRYPTED(orig_inode) || IS_ENCRYPTED(donor_inode)) {
607 		ext4_msg(orig_inode->i_sb, KERN_ERR,
608 			 "Online defrag not supported for encrypted files");
609 		return -EOPNOTSUPP;
610 	}
611 
612 	/* Protect orig and donor inodes against a truncate */
613 	lock_two_nondirectories(orig_inode, donor_inode);
614 
615 	/* Wait for all existing dio workers */
616 	inode_dio_wait(orig_inode);
617 	inode_dio_wait(donor_inode);
618 
619 	/* Protect extent tree against block allocations via delalloc */
620 	ext4_double_down_write_data_sem(orig_inode, donor_inode);
621 	/* Check the filesystem environment whether move_extent can be done */
622 	ret = mext_check_arguments(orig_inode, donor_inode, orig_blk,
623 				    donor_blk, &len);
624 	if (ret)
625 		goto out;
626 	o_end = o_start + len;
627 
628 	while (o_start < o_end) {
629 		struct ext4_extent *ex;
630 		ext4_lblk_t cur_blk, next_blk;
631 		pgoff_t orig_page_index, donor_page_index;
632 		int offset_in_page;
633 		int unwritten, cur_len;
634 
635 		ret = get_ext_path(orig_inode, o_start, &path);
636 		if (ret)
637 			goto out;
638 		ex = path[path->p_depth].p_ext;
639 		cur_blk = le32_to_cpu(ex->ee_block);
640 		cur_len = ext4_ext_get_actual_len(ex);
641 		/* Check hole before the start pos */
642 		if (cur_blk + cur_len - 1 < o_start) {
643 			next_blk = ext4_ext_next_allocated_block(path);
644 			if (next_blk == EXT_MAX_BLOCKS) {
645 				ret = -ENODATA;
646 				goto out;
647 			}
648 			d_start += next_blk - o_start;
649 			o_start = next_blk;
650 			continue;
651 		/* Check hole after the start pos */
652 		} else if (cur_blk > o_start) {
653 			/* Skip hole */
654 			d_start += cur_blk - o_start;
655 			o_start = cur_blk;
656 			/* Extent inside requested range ?*/
657 			if (cur_blk >= o_end)
658 				goto out;
659 		} else { /* in_range(o_start, o_blk, o_len) */
660 			cur_len += cur_blk - o_start;
661 		}
662 		unwritten = ext4_ext_is_unwritten(ex);
663 		if (o_end - o_start < cur_len)
664 			cur_len = o_end - o_start;
665 
666 		orig_page_index = o_start >> (PAGE_SHIFT -
667 					       orig_inode->i_blkbits);
668 		donor_page_index = d_start >> (PAGE_SHIFT -
669 					       donor_inode->i_blkbits);
670 		offset_in_page = o_start % blocks_per_page;
671 		if (cur_len > blocks_per_page - offset_in_page)
672 			cur_len = blocks_per_page - offset_in_page;
673 		/*
674 		 * Up semaphore to avoid following problems:
675 		 * a. transaction deadlock among ext4_journal_start,
676 		 *    ->write_begin via pagefault, and jbd2_journal_commit
677 		 * b. racing with ->read_folio, ->write_begin, and
678 		 *    ext4_get_block in move_extent_per_page
679 		 */
680 		ext4_double_up_write_data_sem(orig_inode, donor_inode);
681 		/* Swap original branches with new branches */
682 		move_extent_per_page(o_filp, donor_inode,
683 				     orig_page_index, donor_page_index,
684 				     offset_in_page, cur_len,
685 				     unwritten, &ret);
686 		ext4_double_down_write_data_sem(orig_inode, donor_inode);
687 		if (ret < 0)
688 			break;
689 		o_start += cur_len;
690 		d_start += cur_len;
691 	}
692 	*moved_len = o_start - orig_blk;
693 	if (*moved_len > len)
694 		*moved_len = len;
695 
696 out:
697 	if (*moved_len) {
698 		ext4_discard_preallocations(orig_inode, 0);
699 		ext4_discard_preallocations(donor_inode, 0);
700 	}
701 
702 	ext4_free_ext_path(path);
703 	ext4_double_up_write_data_sem(orig_inode, donor_inode);
704 	unlock_two_nondirectories(orig_inode, donor_inode);
705 
706 	return ret;
707 }
708