Skip to contentSkip to conversation

btrfs: fix dio continue after short write due to buffer page fault

PATCH In review Boris Burkov 4 participants 10 messages Mar 7, 2023 – Mar 15, 2023 Btrfs file system

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 btrfs: fix dio continue after short write due to buffer page fault

If an application is doing direct io to a btrfs file and experiences a page fault reading from the write buffer, iomap will issue a partial bio, and allow the fs to keep going. However, there was a subtle bug in this code path in the btrfs dio iomap implementation that led to the partial write ending up as a gap in the file's extents and to be read back as zeros.

The sequence of events in a partial write, lightly summarized and trimmed down for brevity is as follows:

====WRITING TASK====
btrfs_direct_write
__iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create full ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # page fault; partial read submit_bio # partial bio
iomap_iter
btrfs_dio_iomap_end
btrfs_mark_ordered_io_finished # sets BTRFS_ORDERED_IOERR;
# submit to finish_ordered_fn wq
fault_in_iov_iter_readable # btrfs_direct_write detects partial write __iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create second partial ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # read all of remainder submit_bio # partial bio with all of remainder
iomap_iter
btrfs_dio_iomap_end # nothing exciting to do with ordered io

====DIO ENDIO====
==FIRST PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left > 0
# don't submit to finish_ordered_fn wq
==SECOND PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left == 0
# submit to finish_ordered_fn wq

====BTRFS FINISH ORDERED WQ====
==FIRST PARTIAL BIO==
btrfs_finish_ordered_io # called by dio_iomap_end_io, sees
# BTRFS_ORDERED_IOERR, just drops the # ordered_extent
==SECOND PARTIAL BIO==
btrfs_finish_ordered_io # called by btrfs_dio_end_io, writes out file
# extents, csums, etc...

The essence of the problem is that while btrfs_direct_write and iomap properly interact to submit all the correct bios, there is insufficient logic in the btrfs dio functions (btrfs_dio_iomap_begin, btrfs_dio_submit_io, btrfs_dio_end_io, and btrfs_dio_iomap_end) to ensure that every bio is at least a part of a completed ordered_extent. And it is completing an ordered_extent that results in crucial functionality like inserting a file extent item for the range in the subvolume/fs tree.

More specifically, btrfs_dio_end_io treats the ordered extent as unfinished but btrfs_dio_iomap_end sets BTRFS_ORDERED_IOERR on it. Thus, the finish io work doesn't result in file extents, csums, etc... In the aftermath, such a file behaves as though it has a hole in it, instead of the purportedly written data.

We considered a few options for fixing the bug:

1. treat the partial bio as if we had truncated the file, which would result in properly finishing it.
2. split the ordered extent when submitting a partial bio.
3. cache the ordered extent across calls to __iomap_dio_rw in iter->private, so that we could reuse it and correctly apply several bios to it.

I had trouble with 1, and it felt the most like a hack, so I tried 2 and 3. Since 3 has the benefit of also not creating an extra file extent, and avoids an ordered extent lookup during bio submission, it felt like the best option.

A quick summary of the changes necessary to implement this cached ordered_extent behavior:

- btrfs_direct_write keeps track of an ordered_extent for the duration of a call, possible across several __iomap_dio_rws.
- zero the btrfs_dio_data before using it, since its fields constitute state now.
- btrfs_dio_write uses dio_data to pass this ordered extent into and out of __iomap_dio_rw.
- when the write is done, put the ordered_extent.
- if the short write happens to be length 0, then we _don't_ get an extra bio, so we do need to cancel the ordered_extent like we used to (and ditch the cached ordered extent)
- if the short write ordered_extent has an error on it, drop the cached ordered extent, as before.
- in btrfs_dio_iomap_begin, if the cached ordered extent is present, skip all the work of creating it, just look up the extent mapping and jump to setting up the iomap. (This part could likely be more elegant..)

Thanks to Josef, Christoph, and Filipe with their help figuring out the bug and the fix.

---
Changelog:
v3:
- handle BTRFS_IOERR set on the ordered_extent in btrfs_dio_iomap_end. If the bio fails before we loop in the submission loop and exit from the loop early, we never submit a second bio covering the rest of the extent range, resulting in leaking the ordered_extent, which hangs umount. We can distinguish this from a short write in btrfs_dio_iomap_end by checking the ordered_extent.
v2:
- rename new ordered extent function
- pull the new function into a prep patch
- reorganize how the ordered_extent is stored/passed around to avoid so many annoying memsets and exposing it to fs/btrfs/file.c
- lots of small code style improvements
- remove unintentional whitespace changes
- commit message improvements
- various ASSERTs for clarity/debugging

 fs/btrfs/btrfs_inode.h |  1 +
 fs/btrfs/file.c        | 11 +++++-
 fs/btrfs/inode.c       | 76 +++++++++++++++++++++++++++++++-----------
 3 files changed, 68 insertions(+), 20 deletions(-)
fs/btrfs/btrfs_inode.h +1 -0
index 49a92aa65de1..87020aa58121 100644
@@ -516,6 +516,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter,
 		       size_t done_before);
 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
+				  struct btrfs_ordered_extent **ordered_extent,
 				  size_t done_before);
 
 extern const struct dentry_operations btrfs_dentry_operations;
fs/btrfs/file.c +10 -1
index 5cc5a1faaef5..ec5c5355906b 100644
@@ -1465,6 +1465,7 @@ static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
 	ssize_t err;
 	unsigned int ilock_flags = 0;
 	struct iomap_dio *dio;
+	struct btrfs_ordered_extent *ordered_extent = NULL;
 
 	if (iocb->ki_flags & IOCB_NOWAIT)
 		ilock_flags |= BTRFS_ILOCK_TRY;
@@ -1526,7 +1527,7 @@ static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
 	 * got -EFAULT, faulting in the pages before the retry.
 	 */
 	from->nofault = true;
-	dio = btrfs_dio_write(iocb, from, written);
+	dio = btrfs_dio_write(iocb, from, &ordered_extent, written);
 	from->nofault = false;
 
 	/*
@@ -1569,6 +1570,14 @@ static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
 			goto relock;
 		}
 	}
+	/*
+	 * We can't loop back to btrfs_dio_write, so we can drop the cached
+	 * ordered extent. Typically btrfs_dio_iomap_end will run and put the
+	 * ordered_extent, but this is needed to clean up in case of an error
+	 * path breaking out of iomap_iter before the final iomap_end call.
+	 */
+	if (ordered_extent)
+		btrfs_put_ordered_extent(ordered_extent);
 
 	/*
 	 * If 'err' is -ENOTBLK or we have not written all data, then it means
fs/btrfs/inode.c +57 -19

165 lines not on this page · raw message

Signature · 1 line
2.38.1
#1 lore raw
Thank you for the patch! Perhaps something to improve:

Hi Boris,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on kdave/for-next]
[also build test WARNING on linus/master v6.3-rc1]
[cannot apply to next-20230307]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956
base:   https://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux.git for-next
patch link:    https://lore.kernel.org/r/6733f2fac24b674d9f60dc1093de30513c099629.1678212067.git.boris%40bur.io
patch subject: [PATCH v3] btrfs: fix dio continue after short write due to buffer page fault
config: m68k-allyesconfig (https://download.01.org/0day-ci/archive/20230308/[email protected]/config)
compiler: m68k-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/938364315c6a1c0055382359a2d94d4d069a273c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956 git checkout 938364315c6a1c0055382359a2d94d4d069a273c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=m68k olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=m68k SHELL=/bin/bash fs/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

fs/btrfs/inode.c: In function 'btrfs_create_dio_extent':
fs/btrfs/inode.c:7001:19: error: implicit declaration of function 'btrfs_alloc_ordered_extent'; did you mean 'btrfs_split_ordered_extent'? [-Werror=implicit-function-declaration]

    7001 |         ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
         |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~
         |                   btrfs_split_ordered_extent
>> fs/btrfs/inode.c:7001:17: warning: assignment to 'struct btrfs_ordered_extent *' from 'int' makes pointer from integer without a cast [-Wint-conversion]

7001 | ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
| ^
cc1: some warnings being treated as errors

vim +7001 fs/btrfs/inode.c

6978
6979 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,

  6980							  struct btrfs_dio_data *dio_data,
  6981							  const u64 start,
  6982							  const u64 len,
  6983							  const u64 orig_start,
  6984							  const u64 block_start,
  6985							  const u64 block_len,
  6986							  const u64 orig_block_len,
  6987							  const u64 ram_bytes,
  6988							  const int type)
  6989	{
  6990		struct extent_map *em = NULL;
  6991		struct btrfs_ordered_extent *ordered;
  6992	
  6993		if (type != BTRFS_ORDERED_NOCOW) {
  6994			em = create_io_em(inode, start, len, orig_start, block_start,
  6995					  block_len, orig_block_len, ram_bytes,
  6996					  BTRFS_COMPRESS_NONE, /* compress_type */
  6997					  type);
  6998			if (IS_ERR(em))
  6999				goto out;
  7000		}
> 7001		ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
  7002						     block_start, block_len, 0,
  7003						     (1 << type) |
  7004						     (1 << BTRFS_ORDERED_DIRECT),
  7005						     BTRFS_COMPRESS_NONE);

7006 if (IS_ERR(ordered)) {
7007 if (em) {
7008 free_extent_map(em);
7009 btrfs_drop_extent_map_range(inode, start,
7010 start + len - 1, false);
7011 }
7012 em = ERR_PTR(PTR_ERR(ordered));
7013 } else {
7014 ASSERT(!dio_data->ordered);
7015 dio_data->ordered = ordered;
7016 }
7017 out:
7018
7019 return em;
7020 }
7021

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#2 lore raw
In reply to Boris Burkov
Quoted 130 lines · Boris Burkov

If an application is doing direct io to a btrfs file and experiences a page fault reading from the write buffer, iomap will issue a partial bio, and allow the fs to keep going. However, there was a subtle bug in this code path in the btrfs dio iomap implementation that led to the partial write ending up as a gap in the file's extents and to be read back as zeros.

The sequence of events in a partial write, lightly summarized and trimmed down for brevity is as follows:

====WRITING TASK====
btrfs_direct_write
__iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create full ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # page fault; partial read submit_bio # partial bio
iomap_iter
btrfs_dio_iomap_end
btrfs_mark_ordered_io_finished # sets BTRFS_ORDERED_IOERR;
# submit to finish_ordered_fn wq
fault_in_iov_iter_readable # btrfs_direct_write detects partial write __iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create second partial ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # read all of remainder submit_bio # partial bio with all of remainder
iomap_iter
btrfs_dio_iomap_end # nothing exciting to do with ordered io

====DIO ENDIO====
==FIRST PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left > 0
# don't submit to finish_ordered_fn wq
==SECOND PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left == 0
# submit to finish_ordered_fn wq

====BTRFS FINISH ORDERED WQ====
==FIRST PARTIAL BIO==
btrfs_finish_ordered_io # called by dio_iomap_end_io, sees
# BTRFS_ORDERED_IOERR, just drops the # ordered_extent
==SECOND PARTIAL BIO==
btrfs_finish_ordered_io # called by btrfs_dio_end_io, writes out file
# extents, csums, etc...

The essence of the problem is that while btrfs_direct_write and iomap properly interact to submit all the correct bios, there is insufficient logic in the btrfs dio functions (btrfs_dio_iomap_begin, btrfs_dio_submit_io, btrfs_dio_end_io, and btrfs_dio_iomap_end) to ensure that every bio is at least a part of a completed ordered_extent. And it is completing an ordered_extent that results in crucial functionality like inserting a file extent item for the range in the subvolume/fs tree.

More specifically, btrfs_dio_end_io treats the ordered extent as unfinished but btrfs_dio_iomap_end sets BTRFS_ORDERED_IOERR on it. Thus, the finish io work doesn't result in file extents, csums, etc... In the aftermath, such a file behaves as though it has a hole in it, instead of the purportedly written data.

We considered a few options for fixing the bug:

1. treat the partial bio as if we had truncated the file, which would result in properly finishing it.
2. split the ordered extent when submitting a partial bio.
3. cache the ordered extent across calls to __iomap_dio_rw in iter->private, so that we could reuse it and correctly apply several bios to it.

I had trouble with 1, and it felt the most like a hack, so I tried 2 and 3. Since 3 has the benefit of also not creating an extra file extent, and avoids an ordered extent lookup during bio submission, it felt like the best option.

A quick summary of the changes necessary to implement this cached ordered_extent behavior:

- btrfs_direct_write keeps track of an ordered_extent for the duration of a call, possible across several __iomap_dio_rws.
- zero the btrfs_dio_data before using it, since its fields constitute state now.
- btrfs_dio_write uses dio_data to pass this ordered extent into and out of __iomap_dio_rw.
- when the write is done, put the ordered_extent.
- if the short write happens to be length 0, then we _don't_ get an extra bio, so we do need to cancel the ordered_extent like we used to (and ditch the cached ordered extent)
- if the short write ordered_extent has an error on it, drop the cached ordered extent, as before.
- in btrfs_dio_iomap_begin, if the cached ordered extent is present, skip all the work of creating it, just look up the extent mapping and jump to setting up the iomap. (This part could likely be more elegant..)

Thanks to Josef, Christoph, and Filipe with their help figuring out the bug and the fix.

---
Changelog:
v3:
- handle BTRFS_IOERR set on the ordered_extent in btrfs_dio_iomap_end. If the bio fails before we loop in the submission loop and exit from the loop early, we never submit a second bio covering the rest of the extent range, resulting in leaking the ordered_extent, which hangs umount. We can distinguish this from a short write in btrfs_dio_iomap_end by checking the ordered_extent.
v2:
- rename new ordered extent function
- pull the new function into a prep patch
- reorganize how the ordered_extent is stored/passed around to avoid so many annoying memsets and exposing it to fs/btrfs/file.c
- lots of small code style improvements
- remove unintentional whitespace changes
- commit message improvements
- various ASSERTs for clarity/debugging

Quoted 5 lines
  fs/btrfs/btrfs_inode.h |  1 +
  fs/btrfs/file.c        | 11 +++++-
  fs/btrfs/inode.c       | 76 +++++++++++++++++++++++++++++++-----------
  3 files changed, 68 insertions(+), 20 deletions(-)

Ran generic/250 and generic/276 each 7500 times on this patchset, with no failures; previously I'd hit the race condition in each after 10-50 times.

#3 lore raw
In reply to Boris Burkov
Thank you for the patch! Yet something to improve:

Hi Boris,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on kdave/for-next]
[also build test ERROR on linus/master v6.3-rc1 next-20230309] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956
base:   https://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux.git for-next
patch link:    https://lore.kernel.org/r/6733f2fac24b674d9f60dc1093de30513c099629.1678212067.git.boris%40bur.io
patch subject: [PATCH v3] btrfs: fix dio continue after short write due to buffer page fault
config: riscv-randconfig-r042-20230308 (https://download.01.org/0day-ci/archive/20230309/[email protected]/config)
compiler: clang version 17.0.0 (https://github.com/llvm/llvm-project 67409911353323ca5edf2049ef0df54132fa1ca7)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# install riscv cross compiling tool for clang build
# apt-get install binutils-riscv-linux-gnu
# https://github.com/intel-lab-lkp/linux/commit/938364315c6a1c0055382359a2d94d4d069a273c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956 git checkout 938364315c6a1c0055382359a2d94d4d069a273c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=riscv olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=riscv SHELL=/bin/bash fs/btrfs/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> fs/btrfs/inode.c:7001:12: error: call to undeclared function 'btrfs_alloc_ordered_extent'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
           ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
                     ^
>> fs/btrfs/inode.c:7001:10: error: incompatible integer to pointer conversion assigning to 'struct btrfs_ordered_extent *' from 'int' [-Wint-conversion]

ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.

vim +/btrfs_alloc_ordered_extent +7001 fs/btrfs/inode.c

6978
6979 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,

  6980							  struct btrfs_dio_data *dio_data,
  6981							  const u64 start,
  6982							  const u64 len,
  6983							  const u64 orig_start,
  6984							  const u64 block_start,
  6985							  const u64 block_len,
  6986							  const u64 orig_block_len,
  6987							  const u64 ram_bytes,
  6988							  const int type)
  6989	{
  6990		struct extent_map *em = NULL;
  6991		struct btrfs_ordered_extent *ordered;
  6992	
  6993		if (type != BTRFS_ORDERED_NOCOW) {
  6994			em = create_io_em(inode, start, len, orig_start, block_start,
  6995					  block_len, orig_block_len, ram_bytes,
  6996					  BTRFS_COMPRESS_NONE, /* compress_type */
  6997					  type);
  6998			if (IS_ERR(em))
  6999				goto out;
  7000		}
> 7001		ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
  7002						     block_start, block_len, 0,
  7003						     (1 << type) |
  7004						     (1 << BTRFS_ORDERED_DIRECT),
  7005						     BTRFS_COMPRESS_NONE);

7006 if (IS_ERR(ordered)) {
7007 if (em) {
7008 free_extent_map(em);
7009 btrfs_drop_extent_map_range(inode, start,
7010 start + len - 1, false);
7011 }
7012 em = ERR_PTR(PTR_ERR(ordered));
7013 } else {
7014 ASSERT(!dio_data->ordered);
7015 dio_data->ordered = ordered;
7016 }
7017 out:
7018
7019 return em;
7020 }
7021

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#4 lore raw
In reply to Boris Burkov
Thank you for the patch! Yet something to improve:

Hi Boris,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on kdave/for-next]
[also build test ERROR on linus/master v6.3-rc1 next-20230309] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956
base:   https://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux.git for-next
patch link:    https://lore.kernel.org/r/6733f2fac24b674d9f60dc1093de30513c099629.1678212067.git.boris%40bur.io
patch subject: [PATCH v3] btrfs: fix dio continue after short write due to buffer page fault
config: arc-randconfig-r043-20230308 (https://download.01.org/0day-ci/archive/20230309/[email protected]/config)
compiler: arc-elf-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/938364315c6a1c0055382359a2d94d4d069a273c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956 git checkout 938364315c6a1c0055382359a2d94d4d069a273c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=arc olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash fs/btrfs/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All error/warnings (new ones prefixed by >>):

fs/btrfs/inode.c: In function 'btrfs_create_dio_extent':

>> fs/btrfs/inode.c:7001:19: error: implicit declaration of function 'btrfs_alloc_ordered_extent'; did you mean 'btrfs_split_ordered_extent'? [-Werror=implicit-function-declaration]
    7001 |         ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
         |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~
         |                   btrfs_split_ordered_extent
>> fs/btrfs/inode.c:7001:17: warning: assignment to 'struct btrfs_ordered_extent *' from 'int' makes pointer from integer without a cast [-Wint-conversion]

7001 | ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
| ^
cc1: some warnings being treated as errors

vim +7001 fs/btrfs/inode.c

6978
6979 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,

  6980							  struct btrfs_dio_data *dio_data,
  6981							  const u64 start,
  6982							  const u64 len,
  6983							  const u64 orig_start,
  6984							  const u64 block_start,
  6985							  const u64 block_len,
  6986							  const u64 orig_block_len,
  6987							  const u64 ram_bytes,
  6988							  const int type)
  6989	{
  6990		struct extent_map *em = NULL;
  6991		struct btrfs_ordered_extent *ordered;
  6992	
  6993		if (type != BTRFS_ORDERED_NOCOW) {
  6994			em = create_io_em(inode, start, len, orig_start, block_start,
  6995					  block_len, orig_block_len, ram_bytes,
  6996					  BTRFS_COMPRESS_NONE, /* compress_type */
  6997					  type);
  6998			if (IS_ERR(em))
  6999				goto out;
  7000		}
> 7001		ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
  7002						     block_start, block_len, 0,
  7003						     (1 << type) |
  7004						     (1 << BTRFS_ORDERED_DIRECT),
  7005						     BTRFS_COMPRESS_NONE);

7006 if (IS_ERR(ordered)) {
7007 if (em) {
7008 free_extent_map(em);
7009 btrfs_drop_extent_map_range(inode, start,
7010 start + len - 1, false);
7011 }
7012 em = ERR_PTR(PTR_ERR(ordered));
7013 } else {
7014 ASSERT(!dio_data->ordered);
7015 dio_data->ordered = ordered;
7016 }
7017 out:
7018
7019 return em;
7020 }
7021

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#5 lore raw
In reply to Boris Burkov
Thank you for the patch! Perhaps something to improve:

Hi Boris,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on kdave/for-next]
[also build test WARNING on linus/master v6.3-rc1 next-20230309] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956
base:   https://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux.git for-next
patch link:    https://lore.kernel.org/r/6733f2fac24b674d9f60dc1093de30513c099629.1678212067.git.boris%40bur.io
patch subject: [PATCH v3] btrfs: fix dio continue after short write due to buffer page fault
config: x86_64-randconfig-a003 (https://download.01.org/0day-ci/archive/20230309/[email protected]/config)
compiler: clang version 14.0.6 (https://github.com/llvm/llvm-project f28c006a5895fc0e329fe15fead81e37457cb1d1)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/938364315c6a1c0055382359a2d94d4d069a273c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956 git checkout 938364315c6a1c0055382359a2d94d4d069a273c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash fs/btrfs/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

fs/btrfs/inode.c:7001:12: error: implicit declaration of function 'btrfs_alloc_ordered_extent' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
^

>> fs/btrfs/inode.c:7001:10: warning: incompatible integer to pointer conversion assigning to 'struct btrfs_ordered_extent *' from 'int' [-Wint-conversion]

ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.

vim +7001 fs/btrfs/inode.c

6978
6979 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,

  6980							  struct btrfs_dio_data *dio_data,
  6981							  const u64 start,
  6982							  const u64 len,
  6983							  const u64 orig_start,
  6984							  const u64 block_start,
  6985							  const u64 block_len,
  6986							  const u64 orig_block_len,
  6987							  const u64 ram_bytes,
  6988							  const int type)
  6989	{
  6990		struct extent_map *em = NULL;
  6991		struct btrfs_ordered_extent *ordered;
  6992	
  6993		if (type != BTRFS_ORDERED_NOCOW) {
  6994			em = create_io_em(inode, start, len, orig_start, block_start,
  6995					  block_len, orig_block_len, ram_bytes,
  6996					  BTRFS_COMPRESS_NONE, /* compress_type */
  6997					  type);
  6998			if (IS_ERR(em))
  6999				goto out;
  7000		}
> 7001		ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
  7002						     block_start, block_len, 0,
  7003						     (1 << type) |
  7004						     (1 << BTRFS_ORDERED_DIRECT),
  7005						     BTRFS_COMPRESS_NONE);

7006 if (IS_ERR(ordered)) {
7007 if (em) {
7008 free_extent_map(em);
7009 btrfs_drop_extent_map_range(inode, start,
7010 start + len - 1, false);
7011 }
7012 em = ERR_PTR(PTR_ERR(ordered));
7013 } else {
7014 ASSERT(!dio_data->ordered);
7015 dio_data->ordered = ordered;
7016 }
7017 out:
7018
7019 return em;
7020 }
7021

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#6 lore raw
In reply to Boris Burkov
Thank you for the patch! Yet something to improve:

Hi Boris,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on kdave/for-next]
[also build test ERROR on linus/master v6.3-rc1 next-20230309] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956
base:   https://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux.git for-next
patch link:    https://lore.kernel.org/r/6733f2fac24b674d9f60dc1093de30513c099629.1678212067.git.boris%40bur.io
patch subject: [PATCH v3] btrfs: fix dio continue after short write due to buffer page fault
config: x86_64-randconfig-a003 (https://download.01.org/0day-ci/archive/20230309/[email protected]/config)
compiler: clang version 14.0.6 (https://github.com/llvm/llvm-project f28c006a5895fc0e329fe15fead81e37457cb1d1)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/938364315c6a1c0055382359a2d94d4d069a273c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Boris-Burkov/btrfs-fix-dio-continue-after-short-write-due-to-buffer-page-fault/20230308-044956 git checkout 938364315c6a1c0055382359a2d94d4d069a273c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash fs/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> fs/btrfs/inode.c:7001:12: error: implicit declaration of function 'btrfs_alloc_ordered_extent' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
^
fs/btrfs/inode.c:7001:10: warning: incompatible integer to pointer conversion assigning to 'struct btrfs_ordered_extent *' from 'int' [-Wint-conversion]
ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.

vim +/btrfs_alloc_ordered_extent +7001 fs/btrfs/inode.c

6978
6979 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,

  6980							  struct btrfs_dio_data *dio_data,
  6981							  const u64 start,
  6982							  const u64 len,
  6983							  const u64 orig_start,
  6984							  const u64 block_start,
  6985							  const u64 block_len,
  6986							  const u64 orig_block_len,
  6987							  const u64 ram_bytes,
  6988							  const int type)
  6989	{
  6990		struct extent_map *em = NULL;
  6991		struct btrfs_ordered_extent *ordered;
  6992	
  6993		if (type != BTRFS_ORDERED_NOCOW) {
  6994			em = create_io_em(inode, start, len, orig_start, block_start,
  6995					  block_len, orig_block_len, ram_bytes,
  6996					  BTRFS_COMPRESS_NONE, /* compress_type */
  6997					  type);
  6998			if (IS_ERR(em))
  6999				goto out;
  7000		}
> 7001		ordered = btrfs_alloc_ordered_extent(inode, start, len, len,
  7002						     block_start, block_len, 0,
  7003						     (1 << type) |
  7004						     (1 << BTRFS_ORDERED_DIRECT),
  7005						     BTRFS_COMPRESS_NONE);

7006 if (IS_ERR(ordered)) {
7007 if (em) {
7008 free_extent_map(em);
7009 btrfs_drop_extent_map_range(inode, start,
7010 start + len - 1, false);
7011 }
7012 em = ERR_PTR(PTR_ERR(ordered));
7013 } else {
7014 ASSERT(!dio_data->ordered);
7015 dio_data->ordered = ordered;
7016 }
7017 out:
7018
7019 return em;
7020 }
7021

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#7 lore raw
In reply to Boris Burkov
Quoted 111 lines · Boris Burkov

If an application is doing direct io to a btrfs file and experiences a page fault reading from the write buffer, iomap will issue a partial bio, and allow the fs to keep going. However, there was a subtle bug in this code path in the btrfs dio iomap implementation that led to the partial write ending up as a gap in the file's extents and to be read back as zeros.

The sequence of events in a partial write, lightly summarized and trimmed down for brevity is as follows:

====WRITING TASK====
btrfs_direct_write
__iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create full ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # page fault; partial read submit_bio # partial bio
iomap_iter
btrfs_dio_iomap_end
btrfs_mark_ordered_io_finished # sets BTRFS_ORDERED_IOERR;
# submit to finish_ordered_fn wq
fault_in_iov_iter_readable # btrfs_direct_write detects partial write __iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create second partial ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # read all of remainder submit_bio # partial bio with all of remainder
iomap_iter
btrfs_dio_iomap_end # nothing exciting to do with ordered io

====DIO ENDIO====
==FIRST PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left > 0
# don't submit to finish_ordered_fn wq
==SECOND PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left == 0
# submit to finish_ordered_fn wq

====BTRFS FINISH ORDERED WQ====
==FIRST PARTIAL BIO==
btrfs_finish_ordered_io # called by dio_iomap_end_io, sees
# BTRFS_ORDERED_IOERR, just drops the # ordered_extent
==SECOND PARTIAL BIO==
btrfs_finish_ordered_io # called by btrfs_dio_end_io, writes out file
# extents, csums, etc...

The essence of the problem is that while btrfs_direct_write and iomap properly interact to submit all the correct bios, there is insufficient logic in the btrfs dio functions (btrfs_dio_iomap_begin, btrfs_dio_submit_io, btrfs_dio_end_io, and btrfs_dio_iomap_end) to ensure that every bio is at least a part of a completed ordered_extent. And it is completing an ordered_extent that results in crucial functionality like inserting a file extent item for the range in the subvolume/fs tree.

More specifically, btrfs_dio_end_io treats the ordered extent as unfinished but btrfs_dio_iomap_end sets BTRFS_ORDERED_IOERR on it. Thus, the finish io work doesn't result in file extents, csums, etc... In the aftermath, such a file behaves as though it has a hole in it, instead of the purportedly written data.

We considered a few options for fixing the bug:

1. treat the partial bio as if we had truncated the file, which would result in properly finishing it.
2. split the ordered extent when submitting a partial bio.
3. cache the ordered extent across calls to __iomap_dio_rw in iter->private, so that we could reuse it and correctly apply several bios to it.

I had trouble with 1, and it felt the most like a hack, so I tried 2 and 3. Since 3 has the benefit of also not creating an extra file extent, and avoids an ordered extent lookup during bio submission, it felt like the best option.

A quick summary of the changes necessary to implement this cached ordered_extent behavior:

- btrfs_direct_write keeps track of an ordered_extent for the duration of a call, possible across several __iomap_dio_rws.
- zero the btrfs_dio_data before using it, since its fields constitute state now.
- btrfs_dio_write uses dio_data to pass this ordered extent into and out of __iomap_dio_rw.
- when the write is done, put the ordered_extent.
- if the short write happens to be length 0, then we _don't_ get an extra bio, so we do need to cancel the ordered_extent like we used to (and ditch the cached ordered extent)
- if the short write ordered_extent has an error on it, drop the cached ordered extent, as before.
- in btrfs_dio_iomap_begin, if the cached ordered extent is present, skip all the work of creating it, just look up the extent mapping and jump to setting up the iomap. (This part could likely be more elegant..)

Thanks to Josef, Christoph, and Filipe with their help figuring out the bug and the fix.

Quoted 9 lines

---
Changelog:
v3:
- handle BTRFS_IOERR set on the ordered_extent in btrfs_dio_iomap_end. If the bio fails before we loop in the submission loop and exit from the loop early, we never submit a second bio covering the rest of the extent range, resulting in leaking the ordered_extent, which hangs umount. We can distinguish this from a short write in btrfs_dio_iomap_end by checking the ordered_extent.

Replaced v2 in misc-next, thanks.

#8 lore raw
Quoted 122 lines · David Sterba
Quoted 111 lines · Boris Burkov

If an application is doing direct io to a btrfs file and experiences a page fault reading from the write buffer, iomap will issue a partial bio, and allow the fs to keep going. However, there was a subtle bug in this code path in the btrfs dio iomap implementation that led to the partial write ending up as a gap in the file's extents and to be read back as zeros.

The sequence of events in a partial write, lightly summarized and trimmed down for brevity is as follows:

====WRITING TASK====
btrfs_direct_write
__iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create full ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # page fault; partial read submit_bio # partial bio
iomap_iter
btrfs_dio_iomap_end
btrfs_mark_ordered_io_finished # sets BTRFS_ORDERED_IOERR;
# submit to finish_ordered_fn wq
fault_in_iov_iter_readable # btrfs_direct_write detects partial write __iomap_dio_write
iomap_iter
btrfs_dio_iomap_begin # create second partial ordered extent
iomap_dio_bio_iter
bio_iov_iter_get_pages # read all of remainder submit_bio # partial bio with all of remainder
iomap_iter
btrfs_dio_iomap_end # nothing exciting to do with ordered io

====DIO ENDIO====
==FIRST PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left > 0
# don't submit to finish_ordered_fn wq
==SECOND PARTIAL BIO==
btrfs_dio_end_io
btrfs_mark_ordered_io_finished # bytes_left == 0
# submit to finish_ordered_fn wq

====BTRFS FINISH ORDERED WQ====
==FIRST PARTIAL BIO==
btrfs_finish_ordered_io # called by dio_iomap_end_io, sees
# BTRFS_ORDERED_IOERR, just drops the # ordered_extent
==SECOND PARTIAL BIO==
btrfs_finish_ordered_io # called by btrfs_dio_end_io, writes out file
# extents, csums, etc...

The essence of the problem is that while btrfs_direct_write and iomap properly interact to submit all the correct bios, there is insufficient logic in the btrfs dio functions (btrfs_dio_iomap_begin, btrfs_dio_submit_io, btrfs_dio_end_io, and btrfs_dio_iomap_end) to ensure that every bio is at least a part of a completed ordered_extent. And it is completing an ordered_extent that results in crucial functionality like inserting a file extent item for the range in the subvolume/fs tree.

More specifically, btrfs_dio_end_io treats the ordered extent as unfinished but btrfs_dio_iomap_end sets BTRFS_ORDERED_IOERR on it. Thus, the finish io work doesn't result in file extents, csums, etc... In the aftermath, such a file behaves as though it has a hole in it, instead of the purportedly written data.

We considered a few options for fixing the bug:

1. treat the partial bio as if we had truncated the file, which would result in properly finishing it.
2. split the ordered extent when submitting a partial bio.
3. cache the ordered extent across calls to __iomap_dio_rw in iter->private, so that we could reuse it and correctly apply several bios to it.

I had trouble with 1, and it felt the most like a hack, so I tried 2 and 3. Since 3 has the benefit of also not creating an extra file extent, and avoids an ordered extent lookup during bio submission, it felt like the best option.

A quick summary of the changes necessary to implement this cached ordered_extent behavior:

- btrfs_direct_write keeps track of an ordered_extent for the duration of a call, possible across several __iomap_dio_rws.
- zero the btrfs_dio_data before using it, since its fields constitute state now.
- btrfs_dio_write uses dio_data to pass this ordered extent into and out of __iomap_dio_rw.
- when the write is done, put the ordered_extent.
- if the short write happens to be length 0, then we _don't_ get an extra bio, so we do need to cancel the ordered_extent like we used to (and ditch the cached ordered extent)
- if the short write ordered_extent has an error on it, drop the cached ordered extent, as before.
- in btrfs_dio_iomap_begin, if the cached ordered extent is present, skip all the work of creating it, just look up the extent mapping and jump to setting up the iomap. (This part could likely be more elegant..)

Thanks to Josef, Christoph, and Filipe with their help figuring out the bug and the fix.

Quoted 9 lines

---
Changelog:
v3:
- handle BTRFS_IOERR set on the ordered_extent in btrfs_dio_iomap_end. If the bio fails before we loop in the submission loop and exit from the loop early, we never submit a second bio covering the rest of the extent range, resulting in leaking the ordered_extent, which hangs umount. We can distinguish this from a short write in btrfs_dio_iomap_end by checking the ordered_extent.

Quoted 1 line

Replaced v2 in misc-next, thanks.

Embarassingly, I have now proven that this version is _still_ broken :(

TL;DR, this "fix" reintroduces the original bug Filipe was fixing in the first place, just a more subtle version of it.

The original bug (some pseudocode liberties taken) was:
mmap(srcfile) = buf
open(srcfile, O_DIRECT|O_WRONLY|O_TRUNC) = fd write(fd, buf, size=sz, off=0) = HANG!!!

and the issue was that iomap_begin created an OE, and then the page fault handler did btrfs_readahead which blocked on the OE.

this led to the bug I was fixing, which was the case:
mmap(srcfile) = buf
open(dstfile, O_DIRECT|O_WRONLY|O_TRUNC) = fd doStuff(buf); # partially in cache
write(fd, buf, size=sz, off=0) = CORRUPTION!!!

which we fixed by making the OE once again outlive the call into iomap, and survive across multiple partial writes. HOWEVER, now we can trigger the same original deadlock, we just have to work a bit harder. mmap(srcfile) = buf
open(srcfile, O_DIRECT|O_WRONLY) = fd
doStuff(buf); # partially in cache
write(fd, buf, size=sz/2, off=sz/4) = HANG!!!

Crucially, we make two changes: we make the written region overlap with the region backing the write buffer and we remove O_TRUNC. As a result, we create an OE [sz/4, 3sz/4], do a partial write from the start of buf (mapped to offset 0 in srcfile), then fault and attempt to fault in the rest of srcfile while the OE exists, which is exactly the original deadlock. Crucially, O_TRUNC and the exactly matching read/write regions where covering this up by forcing the fault to always happen on the 0 byte, which got special handling, rather than a true partial fault.

With all that said, I think this strategy for fixing it, by keeping the OE around is probably dead on arrival, and I need to scrap it and split the ordered extent on a partial bio instead.

Sorry for the churn,
Boris

#9 lore raw
Quoted 19 lines · Boris Burkov
Quoted 18 lines · David Sterba
Quoted 16 lines · Boris Burkov

---
Changelog:
v3:
- handle BTRFS_IOERR set on the ordered_extent in btrfs_dio_iomap_end. If the bio fails before we loop in the submission loop and exit from the loop early, we never submit a second bio covering the rest of the extent range, resulting in leaking the ordered_extent, which hangs umount. We can distinguish this from a short write in btrfs_dio_iomap_end by checking the ordered_extent.

Quoted 6 lines
Quoted 1 line

Replaced v2 in misc-next, thanks.

Embarassingly, I have now proven that this version is _still_ broken :(

TL;DR, this "fix" reintroduces the original bug Filipe was fixing in the first place, just a more subtle version of it.

Ok thanks, I'll remove the patch from branches.