Re: [PATCH] fs: sendfile handles O_NONBLOCK of out_fd

From: Andrei Vagin
Date: Mon May 02 2022 - 03:02:47 EST


Andrew, could you take a look at this patch?

Here is a small reproducer for the problem:

#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/sendfile.h>


#define FILE_SIZE (1UL << 30)
int main(int argc, char **argv) {
int p[2], fd;

if (pipe2(p, O_NONBLOCK))
return 1;

fd = open(argv[1], O_RDWR | O_TMPFILE, 0666);
if (fd < 0)
return 1;
ftruncate(fd, FILE_SIZE);

if (sendfile(p[1], fd, 0, FILE_SIZE) == -1) {
fprintf(stderr, "FAIL\n");
}
if (sendfile(p[1], fd, 0, FILE_SIZE) != -1 || errno != EAGAIN) {
fprintf(stderr, "FAIL\n");
}
return 0;
}

It worked before b964bf53e540, it is stuck after b964bf53e540, and it
works again with this fix.

Thanks,
Andrei

On Thu, Apr 14, 2022 at 5:50 PM Andrei Vagin <avagin@xxxxxxxxx> wrote:
>
> sendfile has to return EAGAIN if out_fd is nonblocking and the write
> into it would block.
>
> Cc: Al Viro <viro@xxxxxxxxxxxxxxxxxx>
> Cc: stable@xxxxxxxxxx
> Fixes: b964bf53e540 ("teach sendfile(2) to handle send-to-pipe directly")
> Signed-off-by: Andrei Vagin <avagin@xxxxxxxxx>
> ---
> fs/read_write.c | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/fs/read_write.c b/fs/read_write.c
> index e643aec2b0ef..ee59419cbf0f 100644
> --- a/fs/read_write.c
> +++ b/fs/read_write.c
> @@ -1247,6 +1247,9 @@ static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos,
> count, fl);
> file_end_write(out.file);
> } else {
> + if (out.file->f_flags & O_NONBLOCK)
> + fl |= SPLICE_F_NONBLOCK;
> +
> retval = splice_file_to_pipe(in.file, opipe, &pos, count, fl);
> }
>
> --
> 2.35.1
>