This series adds an API for reading compressed data on a filesystem
without decompressing it as well as support for writing compressed data
directly to the filesystem. As with the previous submissions, I've
included a man page patch describing the API. I have test cases
(including fsstress support) and example programs which I'll send up
soon [1].
The main use-case is Btrfs send/receive: currently, when sending data
from one compressed filesystem to another, the sending side decompresses
the data and the receiving side recompresses it before writing it out.
This is wasteful and can be avoided if we can just send and write
compressed extents. Since the last posting of this series, I've
implemented the send support and Boris Burkov has implemented the
receive support using this interface; the speedup is significant. Those
patches will be sent shortly.
Patches 1-3 add the VFS support and UAPI. Patches 4-7 are Btrfs prep
patches. Patch 8 adds Btrfs encoded read support and patch 9 adds Btrfs
encoded write support.
These patches are based on Dave Sterba's Btrfs misc-next branch [2],
which is in turn based on v5.9-rc1.
Changes since v4 [3]:
- Rebased on kdave/misc-next.
- Clarified the man pages in several places.
1: https://github.com/osandov/xfstests/tree/rwf-encoded
2: https://github.com/kdave/btrfs-devel/tree/misc-next
3: https://lore.kernel.org/linux-fsdevel/cover.1582930832.git.osandov@fb.com/
Omar Sandoval (9):
iov_iter: add copy_struct_from_iter()
fs: add O_ALLOW_ENCODED open flag
fs: add RWF_ENCODED for reading/writing compressed data
btrfs: don't advance offset for compressed bios in
btrfs_csum_one_bio()
btrfs: add ram_bytes and offset to btrfs_ordered_extent
btrfs: support different disk extent size for delalloc
btrfs: optionally extend i_size in cow_file_range_inline()
btrfs: implement RWF_ENCODED reads
btrfs: implement RWF_ENCODED writes
Documentation/filesystems/encoded_io.rst | 74 ++
Documentation/filesystems/index.rst | 1 +
arch/alpha/include/uapi/asm/fcntl.h | 1 +
arch/parisc/include/uapi/asm/fcntl.h | 1 +
arch/sparc/include/uapi/asm/fcntl.h | 1 +
fs/btrfs/compression.c | 12 +-
fs/btrfs/compression.h | 6 +-
fs/btrfs/ctree.h | 9 +-
fs/btrfs/delalloc-space.c | 18 +-
fs/btrfs/file-item.c | 35 +-
fs/btrfs/file.c | 55 +-
fs/btrfs/inode.c | 904 ++++++++++++++++++++---
fs/btrfs/ordered-data.c | 80 +-
fs/btrfs/ordered-data.h | 18 +-
fs/btrfs/relocation.c | 4 +-
fs/fcntl.c | 10 +-
fs/namei.c | 4 +
include/linux/fcntl.h | 2 +-
include/linux/fs.h | 16 +
include/linux/uio.h | 2 +
include/uapi/asm-generic/fcntl.h | 4 +
include/uapi/linux/fs.h | 33 +-
lib/iov_iter.c | 82 ++
mm/filemap.c | 166 ++++-
24 files changed, 1336 insertions(+), 202 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
--
2.28.0
@@ -221,8 +221,9 @@ On Linux, this command can change only the .BRO_ASYNC, .BRO_DIRECT, .BRO_NOATIME,+.BRO_NONBLOCK, and-.BO_NONBLOCK+.BO_ALLOW_ENCODED flags. It is not possible to change the .BRO_DSYNC
@@ -1820,6 +1821,13 @@ Attempted to clear the flag on a file that has the append-only attribute set. .TP .BEPERM+Attempted to set the+.BO_ALLOW_ENCODED+flag and the calling process did not have the+.BCAP_SYS_ADMIN+capability.+.TP+.BEPERM .Icmd was .BRF_ADD_SEALS,
@@ -437,6 +437,14 @@ was followed by a call to .BRfdatasync(2)). .IR"See NOTES below". .TP+.BO_ALLOW_ENCODED+Open the file with encoded I/O permissions;+see+.BRencoded_io(7).+The caller must have the+.BCAP_SYS_ADMIN+capability.+.TP .BO_EXCL Ensure that this call creates the file: if this flag is specified in conjunction with
@@ -1230,6 +1238,11 @@ did not match the owner of the file and the caller was not privileged. The operation was prevented by a file seal; see .BRfcntl(2). .TP+.BEPERM+The+.BO_ALLOW_ENCODED+flag was specified, but the caller was not privileged.+.TP .BEROFS .Ipathname refers to a file on a read-only filesystem and write access was
@@ -264,6 +264,11 @@ the data is always appended to the end of the file. However, if the .Ioffset argument is \-1, the current file offset is updated.+.TP+.BRRWF_ENCODED" (since Linux 5.8)"+Read or write encoded (e.g., compressed) data.+See+.BRencoded_io(7). .SHRETURNVALUE On success, .BRreadv(),
@@ -283,6 +288,13 @@ than requested (see and .BRwrite(2)). .PP+If+.B+RWF_ENCODED+was specified in+.IRflags,+then the return value is the number of encoded bytes.+.PP On error, \-1 is returned, and \fIerrno\fP is set appropriately. .SHERRORS The errors are as given for
@@ -313,6 +325,58 @@ is less than zero or greater than the permitted maximum. .TP .BEOPNOTSUPP An unknown flag is specified in \fIflags\fP.+.TP+.BEOPNOTSUPP+.BRWF_ENCODED+is specified in+.Iflags+and the filesystem does not implement encoded I/O.+.TP+.BEPERM+.BRWF_ENCODED+is specified in+.Iflags+and the file was not opened with the+.BO_ALLOW_ENCODED+flag.+.PP+.BRpreadv2()+can fail for the following reasons:+.TP+.BE2BIG+.BRWF_ENCODED+is specified in+.Iflags+and+.Iiov[0]+is not large enough to return the encoding metadata.+.TP+.BENOBUFS+.BRWF_ENCODED+is specified in+.Iflags+and the buffers in+.Iiov+are not big enough to return the encoded data.+.PP+.BRpwritev2()+can fail for the following reasons:+.TP+.BE2BIG+.BRWF_ENCODED+is specified in+.Iflags+and+.Iiov[0]+contains non-zero fields+after the kernel's+.IR"sizeof(struct\ encoded_iov)".+.TP+.BEINVAL+.BRWF_ENCODED+is specified in+.Iflags+and the alignment and/or size requirements are not met. .SHVERSIONS .BRpreadv() and
@@ -0,0 +1,347 @@+.\" Copyright (c) 2019 by Omar Sandoval <osandov@fb.com>+.\"+.\" %%%LICENSE_START(VERBATIM)+.\" Permission is granted to make and distribute verbatim copies of this+.\" manual provided the copyright notice and this permission notice are+.\" preserved on all copies.+.\"+.\" Permission is granted to copy and distribute modified versions of this+.\" manual under the conditions for verbatim copying, provided that the+.\" entire resulting derived work is distributed under the terms of a+.\" permission notice identical to this one.+.\"+.\" Since the Linux kernel and libraries are constantly changing, this+.\" manual page may be incorrect or out-of-date. The author(s) assume no+.\" responsibility for errors or omissions, or for damages resulting from+.\" the use of the information contained herein. The author(s) may not+.\" have taken the same level of care in the production of this manual,+.\" which is licensed free of charge, as they might when working+.\" professionally.+.\"+.\" Formatted or processed versions of this manual, if unaccompanied by+.\" the source, must acknowledge the copyright and authors of this work.+.\" %%%LICENSE_END+.\"+.\"+.THENCODED_IO72019-10-14"Linux""Linux Programmer's Manual"+.SHNAME+encoded_io \- overview of encoded I/O+.SHDESCRIPTION+Several filesystems (e.g., Btrfs) support transparent encoding+(e.g., compression, encryption) of data on disk:+written data is encoded by the kernel before it is written to disk,+and read data is decoded before being returned to the user.+In some cases, it is useful to skip this encoding step.+For example, the user may want to read the compressed contents of a file+or write pre-compressed data directly to a file.+This is referred to as "encoded I/O".+.SSEncodedI/OAPI+Encoded I/O is specified with the+.BRWF_ENCODED+flag to+.BRpreadv2(2)+and+.BRpwritev2(2).+If+.BRWF_ENCODED+is specified, then+.Iiov[0].iov_base+points to an+.I+encoded_iov+structure, defined in+.I<linux/fs.h>+as:+.PP+.in+4n+.EX+struct encoded_iov {+ __aligned_u64 len;+ __aligned_u64 unencoded_len;+ __aligned_u64 unencoded_offset;+ __u32 compression;+ __u32 encryption;+};+.EE+.in+.PP+This may be extended in the future, so+.Iiov[0].iov_len+must be set to+.I"sizeof(struct\ encoded_iov)"+for forward/backward compatibility.+The remaining buffers contain the encoded data.+.PP+.Icompression+and+.Iencryption+are the encoding fields.+.Icompression+is one of+.BENCODED_IOV_COMPRESSION_NONE+(zero),+.BRENCODED_IOV_COMPRESSION_ZLIB,+.BRENCODED_IOV_COMPRESSION_LZO,+or+.BRENCODED_IOV_COMPRESSION_ZSTD.+.Iencryption+is currently always+.BENCODED_IOV_ENCRYPTION_NONE+(zero).+.PP+.Iunencoded_len+is the length of the unencoded (i.e., decrypted and decompressed) data.+.Iunencoded_offset+is the offset into the unencoded data where the data in the file begins+(less than or equal to+.IRunencoded_len).+.Ilen+is the length of the data in the file+(less than or equal to+.Iunencoded_len+-+.IRunencoded_offset).+See+.BExtentlayout+below for some examples.+.I+.PP+If the unencoded data is actually longer than+.IRunencoded_len,+then it is truncated;+if it is shorter, then it is extended with zeroes.+.PP++.BRpwritev2()+uses the metadata specified in+.IRiov[0],+writes the encoded data from the remaining buffers,+and returns the number of encoded bytes written+(that is, the sum of+.Iiov[n].iov_len+for 1 <=+.In+<+.IRiovcnt;+partial writes will not occur).+At least one encoding field must be non-zero.+Note that the encoded data is not validated when it is written;+if it is not valid (e.g., it cannot be decompressed),+then a subsequent read may return an error.+If the+.Ioffset+argument to+.BRpwritev2()+is -1, then the file offset is incremented by+.IRlen.+If+.Iiov[0].iov_len+is less than+.I"sizeof(struct\ encoded_iov)"+in the kernel,+then any fields unknown to userspace are treated as if they were zero;+if it is greater and any fields unknown to the kernel are non-zero,+then this returns -1 and sets+.Ierrno+to+.BRE2BIG.+.PP+.BRpreadv2()+populates the metadata in+.IRiov[0],+the encoded data in the remaining buffers,+and returns the number of encoded bytes read.+This will only return one extent per call.+This can also read data which is not encoded;+all encoding fields will be zero in that case.+If the+.Ioffset+argument to+.BRpreadv2()+is -1, then the file offset is incremented by+.IRlen.+If+.Iiov[0].iov_len+is less than+.I"sizeof(struct\ encoded_iov)"+in the kernel and any fields unknown to userspace are non-zero,+then+.BRpreadv2()+returns -1 and sets+.Ierrno+to+.BRE2BIG;+if it is greater,+then any fields unknown to the kernel are returned as zero.+If the provided buffers are not large enough to return an entire encoded+extent,+then+.BRpreadv2()+returns -1 and sets+.Ierrno+to+.BRENOBUFS.+.PP+As the filesystem page cache typically contains decoded data,+encoded I/O bypasses the page cache.+.SSExtentlayout+By using+.IRlen,+.IRunencoded_len,+and+.IRunencoded_offset,+it is possible to refer to a subset of an unencoded extent.+.PP+In the simplest case,+.Ilen+is equal to+.Iunencoded_len+and+.Iunencoded_offset+is zero.+This means that the entire unencoded extent is used.+.PP+However, suppose we read 50 bytes into a file+which contains a single compressed extent.+The filesystem must still return the entire compressed extent+for us to be able to decompress it,+so+.Iunencoded_len+would be the length of the entire decompressed extent.+However, because the read was at offset 50,+the first 50 bytes should be ignored.+Therefore,+.Iunencoded_offset+would be 50,+and+.Ilen+would accordingly be+.IRunencoded_len\-\50.+.PP+Additionally, suppose we want to create an encrypted file with length 500,+but the file is encrypted with a block cipher using a block size of 4096.+The unencoded data would therefore include the appropriate padding,+and+.Iunencoded_len+would be 4096.+However, to represent the logical size of the file,+.Ilen+would be 500+(and+.Iunencoded_offset+would be 0).+.PP+Similar situations can arise in other cases:+.IP*3+If the filesystem pads data to the filesystem block size before compressing,+then compressed files with a size unaligned to the filesystem block size will+end with an extent with+.Ilen+<+.IRunencoded_len.+.IP*+Extents cloned from the middle of a larger encoded extent with+.BFICLONERANGE+may have a non-zero+.Iunencoded_offset+and/or+.Ilen+<+.IRunencoded_len.+.IP*+If the middle of an encoded extent is overwritten,+the filesystem may create extents with a non-zero+.Iunencoded_offset+and/or+.Ilen+<+.Iunencoded_len+for the parts that were not overwritten.+.SSSecurity+Encoded I/O creates the potential for some security issues:+.IP*3+Encoded writes allow writing arbitrary data which the kernel will decode on+a subsequent read. Decompression algorithms are complex and may have bugs+which can be exploited by maliciously crafted data.+.IP*+Encoded reads may return data which is not logically present in the file+(see the discussion of+.Ilen+vs.+.Iunencoded_len+above).+It may not be intended for this data to be readable.+.PP+Therefore, encoded I/O requires privilege.+Namely, the+.BRWF_ENCODED+flag may only be used when the file was opened with the+.BO_ALLOW_ENCODED+flag to+.BRopen(2),+which requires the+.BCAP_SYS_ADMIN+capability.+.BO_ALLOW_ENCODED+may be set and cleared with+.BRfcntl(2).+Note that it is not cleared on+.BRfork(2)+or+.BRexecve(2);+one may wish to use+.BO_CLOEXEC+with+.BRO_ALLOW_ENCODED.+.SSFilesystemsupport+Encoded I/O is supported on the following filesystems:+.TP+Btrfs (since Linux 5.10)+.IP+Btrfs supports encoded reads and writes of compressed data.+The data is encoded as follows:+.RS+.IP*3+If+.Icompression+is+.BRENCODED_IOV_COMPRESSION_ZLIB,+then the encoded data is a single zlib stream.+.IP*+If+.Icompression+is+.BRENCODED_IOV_COMPRESSION_LZO,+then the encoded data is compressed page by page with LZO1X+and wrapped in the format documented in the Linux kernel source file+.IRfs/btrfs/lzo.c.+.IP*+If+.Icompression+is+.BRENCODED_IOV_COMPRESSION_ZSTD,+then the encoded data is a single zstd frame compressed with the+.IwindowLog+compression parameter set to no more than 17.+.RE+.IP+Additionally, there are some restrictions on+.BRpwritev2():+.RS+.IP*3+.Ioffset+(or the current file offset if+.Ioffset+is -1) must be aligned to the sector size of the filesystem.+.IP*+.Ilen+must be aligned to the sector size of the filesystem+unless the data ends at or beyond the current end of the file.+.IP*+.Iunencoded_len+and the length of the encoded data must each be no more than 128 KiB.+This limit may increase in the future.+.IP*+The length of the encoded data must be less than or equal to+.IRunencoded_len.+.RE
From: Omar Sandoval <redacted>
The upcoming RWF_ENCODED operation introduces some security concerns:
1. Compressed writes will pass arbitrary data to decompression
algorithms in the kernel.
2. Compressed reads can leak truncated/hole punched data.
Therefore, we need to require privilege for RWF_ENCODED. It's not
possible to do the permissions checks at the time of the read or write
because, e.g., io_uring submits IO from a worker thread. So, add an open
flag which requires CAP_SYS_ADMIN. It can also be set and cleared with
fcntl(). The flag is not cleared in any way on fork or exec; it should
probably be used with O_CLOEXEC in most cases.
Note that the usual issue that unknown open flags are ignored doesn't
really matter for O_ALLOW_ENCODED; if the kernel doesn't support
O_ALLOW_ENCODED, then it doesn't support RWF_ENCODED, either.
Signed-off-by: Omar Sandoval <redacted>
---
arch/alpha/include/uapi/asm/fcntl.h | 1 +
arch/parisc/include/uapi/asm/fcntl.h | 1 +
arch/sparc/include/uapi/asm/fcntl.h | 1 +
fs/fcntl.c | 10 ++++++++--
fs/namei.c | 4 ++++
include/linux/fcntl.h | 2 +-
include/uapi/asm-generic/fcntl.h | 4 ++++
7 files changed, 20 insertions(+), 3 deletions(-)
@@ -49,6 +50,11 @@ static int setfl(int fd, struct file * filp, unsigned long arg)if(!inode_owner_or_capable(inode))return-EPERM;+/* O_ALLOW_ENCODED can only be set by superuser */+if((arg&O_ALLOW_ENCODED)&&!(filp->f_flags&O_ALLOW_ENCODED)&&+!capable(CAP_SYS_ADMIN))+return-EPERM;+/* required for strict SunOS emulation */if(O_NONBLOCK!=O_NDELAY)if(arg&O_NDELAY)
@@ -1033,7 +1039,7 @@ static int __init fcntl_init(void)*Exceptions:O_NONBLOCKisatwobitdefineonparisc;O_NDELAY*isdefinedasO_NONBLOCKonsomeplatformsandnotonothers.*/-BUILD_BUG_ON(21-1/* for O_RDONLY being 0 */!=+BUILD_BUG_ON(22-1/* for O_RDONLY being 0 */!=HWEIGHT32((VALID_OPEN_FLAGS&~(O_NONBLOCK|O_NDELAY))|__FMODE_EXEC|__FMODE_NONOTIFY));
@@ -2889,6 +2889,10 @@ static int may_open(const struct path *path, int acc_mode, int flag)if(flag&O_NOATIME&&!inode_owner_or_capable(inode))return-EPERM;+/* O_ALLOW_ENCODED can only be set by superuser */+if((flag&O_ALLOW_ENCODED)&&!capable(CAP_SYS_ADMIN))+return-EPERM;+return0;}
@@ -10,7 +10,7 @@(O_RDONLY|O_WRONLY|O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_TRUNC|\O_APPEND|O_NDELAY|O_NONBLOCK|O_NDELAY|__O_SYNC|O_DSYNC|\FASYNC|O_DIRECT|O_LARGEFILE|O_DIRECTORY|O_NOFOLLOW|\-O_NOATIME|O_CLOEXEC|O_PATH|__O_TMPFILE)+O_NOATIME|O_CLOEXEC|O_PATH|__O_TMPFILE|O_ALLOW_ENCODED)/* List of all valid flags for the how->upgrade_mask argument: */#define VALID_UPGRADE_FLAGS \
@@ -89,6 +89,10 @@#define __O_TMPFILE 020000000#endif+#ifndef O_ALLOW_ENCODED+#define O_ALLOW_ENCODED 040000000+#endif+/* a horrid kludge trying to make sure that this will fail on old kernels */#define O_TMPFILE (__O_TMPFILE | O_DIRECTORY)#define O_TMPFILE_MASK (__O_TMPFILE | O_DIRECTORY | O_CREAT)
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
---
Documentation/filesystems/encoded_io.rst | 74 ++++++++++
Documentation/filesystems/index.rst | 1 +
include/linux/fs.h | 16 +++
include/uapi/linux/fs.h | 33 ++++-
mm/filemap.c | 166 +++++++++++++++++++++--
5 files changed, 276 insertions(+), 14 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
@@ -0,0 +1,74 @@+===========+Encoded I/O+===========++Encoded I/O is a mechanism for reading and writing encoded (e.g., compressed+and/or encrypted) data directly from/to the filesystem. The userspace interface+is thoroughly described in the :manpage:`encoded_io(7)` man page; this document+describes the requirements for filesystem support.++First of all, a filesystem supporting encoded I/O must indicate this by setting+the ``FMODE_ENCODED_IO`` flag in its ``file_open`` file operation::++ static int foo_file_open(struct inode *inode, struct file *filp)+ {+ ...+ filep->f_mode |= FMODE_ENCODED_IO;+ ...+ }++Encoded I/O goes through ``read_iter`` and ``write_iter``, designated by the+``IOCB_ENCODED`` flag in ``kiocb->ki_flags``.++Reads+=====++Encoded ``read_iter`` should:++1. Call ``generic_encoded_read_checks()`` to validate the file and buffers+ provided by userspace.+2. Initialize the ``encoded_iov`` appropriately.+3. Copy it to the user with ``copy_encoded_iov_to_iter()``.+4. Copy the encoded data to the user.+5. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+6. Return the size of the encoded data read, not including the ``encoded_iov``.++There are a few details to be aware of:++* Encoded ``read_iter`` should support reading unencoded data if the extent is+ not encoded.+* If the buffers provided by the user are not large enough to contain an entire+ encoded extent, then ``read_iter`` should return ``-ENOBUFS``. This is to+ avoid confusing userspace with truncated data that cannot be properly+ decoded.+* Reads in the middle of an encoded extent can be returned by setting+``encoded_iov->unencoded_offset`` to non-zero.+* Truncated unencoded data (e.g., because the file does not end on a block+ boundary) may be returned by setting ``encoded_iov->len`` to a value smaller+ value than ``encoded_iov->unencoded_len - encoded_iov->unencoded_offset``.++Writes+======++Encoded ``write_iter`` should (in addition to the usual accounting/checks done+by ``write_iter``):++1. Call ``copy_encoded_iov_from_iter()`` to get and validate the+``encoded_iov``.+2. Call ``generic_encoded_write_checks()`` instead of+``generic_write_checks()``.+3. Check that the provided encoding in ``encoded_iov`` is supported.+4. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+5. Return the size of the encoded data written.++Again, there are a few details:++* Encoded ``write_iter`` doesn't need to support writing unencoded data.+*``write_iter`` should either write all of the encoded data or none of it; it+ must not do partial writes.+*``write_iter`` doesn't need to validate the encoded data; a subsequent read+ may return, e.g., ``-EIO`` if the data is not valid.+* The user may lie about the unencoded size of the data; a subsequent read+ should truncate or zero-extend the unencoded data rather than returning an+ error.+* Be careful of page cache coherency.
@@ -3022,24 +3022,15 @@ static int generic_write_check_limits(struct file *file, loff_t pos,return0;}-/*-*Performsnecessarychecksbeforedoingawrite-*-*Canadjustwritingpositionoramountofbytestowrite.-*Returnsappropriateerrorcodethatcallershouldreturnor-*zeroincasethatwriteshouldbeallowed.-*/-inlinessize_tgeneric_write_checks(structkiocb*iocb,structiov_iter*from)+staticintgeneric_write_checks_common(structkiocb*iocb,loff_t*count){structfile*file=iocb->ki_filp;structinode*inode=file->f_mapping->host;-loff_tcount;-intret;if(IS_SWAPFILE(inode))return-ETXTBSY;-if(!iov_iter_count(from))+if(!*count)return0;/* FIXME: this is for backwards compatibility with 2.4 */
From: Omar Sandoval <redacted>
btrfs_csum_one_bio() loops over each filesystem block in the bio while
keeping a cursor of its current logical position in the file in order to
look up the ordered extent to add the checksums to. However, this
doesn't make much sense for compressed extents, as a sector on disk does
not correspond to a sector of decompressed file data. It happens to work
because 1) the compressed bio always covers one ordered extent and 2)
the size of the bio is always less than the size of the ordered extent.
However, the second point will not always be true for encoded writes.
Let's add a boolean parameter to btrfs_csum_one_bio() to indicate that
it can assume that the bio only covers one ordered extent. Since we're
already changing the signature, let's get rid of the contig parameter
and make it implied by the offset parameter, similar to the change we
recently made to btrfs_lookup_bio_sums(). Additionally, let's rename
nr_sectors to blockcount to make it clear that it's the number of
filesystem blocks, not the number of 512-byte sectors.
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/compression.c | 5 +++--
fs/btrfs/ctree.h | 2 +-
fs/btrfs/file-item.c | 35 ++++++++++++++++-------------------
fs/btrfs/inode.c | 8 ++++----
4 files changed, 24 insertions(+), 26 deletions(-)
From: Omar Sandoval <redacted>
Currently, we only create ordered extents when ram_bytes == num_bytes
and offset == 0. However, RWF_ENCODED writes may create extents which
only refer to a subset of the full unencoded extent, so we need to plumb
these fields through the ordered extent infrastructure and pass them
down to insert_reserved_file_extent().
Since we're changing the btrfs_add_ordered_extent* signature, let's get
rid of the trivial wrappers and add a kernel-doc.
Reviewed-by: Nikolay Borisov <redacted>
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/inode.c | 56 ++++++++++++++++++---------------
fs/btrfs/ordered-data.c | 68 ++++++++++++++++-------------------------
fs/btrfs/ordered-data.h | 16 ++++------
3 files changed, 64 insertions(+), 76 deletions(-)
@@ -1083,8 +1082,9 @@ static noinline int cow_file_range(struct btrfs_inode *inode,}free_extent_map(em);-ret=btrfs_add_ordered_extent(inode,start,ins.objectid,-ram_size,cur_alloc_size,0);+ret=btrfs_add_ordered_extent(inode,start,ram_size,ram_size,+ins.objectid,cur_alloc_size,0,+0,BTRFS_COMPRESS_NONE);if(ret)gotoout_drop_extent_cache;
@@ -1716,10 +1716,11 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,gotoerror;}free_extent_map(em);-ret=btrfs_add_ordered_extent(inode,cur_offset,-disk_bytenr,num_bytes,-num_bytes,-BTRFS_ORDERED_PREALLOC);+ret=btrfs_add_ordered_extent(inode,+cur_offset,num_bytes,num_bytes,+disk_bytenr,num_bytes,0,+1<<BTRFS_ORDERED_PREALLOC,+BTRFS_COMPRESS_NONE);if(ret){btrfs_drop_extent_cache(inode,cur_offset,cur_offset+num_bytes-1,
@@ -1728,9 +1729,11 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,}}else{ret=btrfs_add_ordered_extent(inode,cur_offset,+num_bytes,num_bytes,disk_bytenr,num_bytes,-num_bytes,-BTRFS_ORDERED_NOCOW);+0,+1<<BTRFS_ORDERED_NOCOW,+BTRFS_COMPRESS_NONE);if(ret)gotoerror;}
@@ -2470,6 +2473,7 @@ static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,structbtrfs_keyins;u64disk_num_bytes=btrfs_stack_file_extent_disk_num_bytes(stack_fi);u64disk_bytenr=btrfs_stack_file_extent_disk_bytenr(stack_fi);+u64offset=btrfs_stack_file_extent_offset(stack_fi);u64num_bytes=btrfs_stack_file_extent_num_bytes(stack_fi);u64ram_bytes=btrfs_stack_file_extent_ram_bytes(stack_fi);intextent_inserted=0;
@@ -2525,7 +2529,8 @@ static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,gotoout;ret=btrfs_alloc_reserved_file_extent(trans,root,btrfs_ino(inode),-file_pos,qgroup_reserved,&ins);+file_pos-offset,+qgroup_reserved,&ins);out:btrfs_free_path(path);
@@ -2552,19 +2557,19 @@ static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,structbtrfs_ordered_extent*oe){structbtrfs_file_extent_itemstack_fi;-u64logical_len;+u64num_bytes=oe->num_bytes;+u64ram_bytes=oe->ram_bytes;memset(&stack_fi,0,sizeof(stack_fi));btrfs_set_stack_file_extent_type(&stack_fi,BTRFS_FILE_EXTENT_REG);btrfs_set_stack_file_extent_disk_bytenr(&stack_fi,oe->disk_bytenr);btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,oe->disk_num_bytes);+btrfs_set_stack_file_extent_offset(&stack_fi,oe->offset);if(test_bit(BTRFS_ORDERED_TRUNCATED,&oe->flags))-logical_len=oe->truncated_len;-else-logical_len=oe->num_bytes;-btrfs_set_stack_file_extent_num_bytes(&stack_fi,logical_len);-btrfs_set_stack_file_extent_ram_bytes(&stack_fi,logical_len);+num_bytes=ram_bytes=oe->truncated_len;+btrfs_set_stack_file_extent_num_bytes(&stack_fi,num_bytes);+btrfs_set_stack_file_extent_ram_bytes(&stack_fi,ram_bytes);btrfs_set_stack_file_extent_compression(&stack_fi,oe->compress_type);/* Encryption and other encoding is reserved and all 0 */
@@ -171,7 +182,8 @@ static int __btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offsetstructbtrfs_ordered_extent*entry;intret;-if(type==BTRFS_ORDERED_NOCOW||type==BTRFS_ORDERED_PREALLOC){+if(flags&+((1<<BTRFS_ORDERED_NOCOW)|(1<<BTRFS_ORDERED_PREALLOC))){/* For nocow write, we can release the qgroup rsv right now */ret=btrfs_qgroup_free_data(inode,NULL,file_offset,num_bytes);if(ret<0)
@@ -191,21 +203,21 @@ static int __btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offsetreturn-ENOMEM;entry->file_offset=file_offset;-entry->disk_bytenr=disk_bytenr;entry->num_bytes=num_bytes;+entry->ram_bytes=ram_bytes;+entry->disk_bytenr=disk_bytenr;entry->disk_num_bytes=disk_num_bytes;+entry->offset=offset;entry->bytes_left=num_bytes;entry->inode=igrab(&inode->vfs_inode);entry->compress_type=compress_type;entry->truncated_len=(u64)-1;entry->qgroup_rsv=ret;-if(type!=BTRFS_ORDERED_IO_DONE&&type!=BTRFS_ORDERED_COMPLETE)-set_bit(type,&entry->flags);-if(dio){+entry->flags=flags;+if(flags&(1<<BTRFS_ORDERED_DIRECT)){percpu_counter_add_batch(&fs_info->dio_bytes,num_bytes,fs_info->delalloc_batch);-set_bit(BTRFS_ORDERED_DIRECT,&entry->flags);}/* one ref for the tree */
@@ -72,9 +72,11 @@ struct btrfs_ordered_extent {*Thesefieldsdirectlycorrespondtothesamefieldsin*btrfs_file_extent_item.*/-u64disk_bytenr;u64num_bytes;+u64ram_bytes;+u64disk_bytenr;u64disk_num_bytes;+u64offset;/* number of bytes that still need writing */u64bytes_left;
@@ -161,15 +163,9 @@ int btrfs_dec_test_first_ordered_pending(struct btrfs_inode *inode,u64*file_offset,u64io_size,intuptodate);intbtrfs_add_ordered_extent(structbtrfs_inode*inode,u64file_offset,-u64disk_bytenr,u64num_bytes,u64disk_num_bytes,-inttype);-intbtrfs_add_ordered_extent_dio(structbtrfs_inode*inode,u64file_offset,-u64disk_bytenr,u64num_bytes,-u64disk_num_bytes,inttype);-intbtrfs_add_ordered_extent_compress(structbtrfs_inode*inode,u64file_offset,-u64disk_bytenr,u64num_bytes,-u64disk_num_bytes,inttype,-intcompress_type);+u64num_bytes,u64ram_bytes,u64disk_bytenr,+u64disk_num_bytes,u64offset,intflags,+intcompress_type);voidbtrfs_add_ordered_sum(structbtrfs_ordered_extent*entry,structbtrfs_ordered_sum*sum);structbtrfs_ordered_extent*btrfs_lookup_ordered_extent(structbtrfs_inode*inode,
From: Omar Sandoval <redacted>
Currently, an inline extent is always created after i_size is extended
from btrfs_dirty_pages(). However, for encoded writes, we only want to
update i_size after we successfully created the inline extent. Add an
update_i_size parameter to cow_file_range_inline() and
insert_inline_extent() and pass in the size of the extent rather than
determining it from i_size. Since the start parameter is always passed
as 0, get rid of it and simplify the logic in these two functions. While
we're here, let's document the requirements for creating an inline
extent.
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/inode.c | 100 +++++++++++++++++++++++------------------------
1 file changed, 48 insertions(+), 52 deletions(-)
@@ -618,14 +610,15 @@ static noinline int compress_file_range(struct async_chunk *async_chunk)/* we didn't compress the entire range, try*tomakeanuncompressedinlineextent.*/-ret=cow_file_range_inline(BTRFS_I(inode),start,end,+ret=cow_file_range_inline(BTRFS_I(inode),actual_end,0,BTRFS_COMPRESS_NONE,-NULL);+NULL,false);}else{/* try making a compressed inline extent */-ret=cow_file_range_inline(BTRFS_I(inode),start,end,+ret=cow_file_range_inline(BTRFS_I(inode),actual_end,total_compressed,-compress_type,pages);+compress_type,pages,+false);}if(ret<=0){unsignedlongclear_flags=EXTENT_DELALLOC|
@@ -1013,9 +1006,12 @@ static noinline int cow_file_range(struct btrfs_inode *inode,inode_should_defrag(inode,start,end,num_bytes,SZ_64K);if(start==0){+u64actual_end=min_t(u64,i_size_read(&inode->vfs_inode),+end+1);+/* lets try to make an inline extent */-ret=cow_file_range_inline(inode,start,end,0,-BTRFS_COMPRESS_NONE,NULL);+ret=cow_file_range_inline(inode,actual_end,0,+BTRFS_COMPRESS_NONE,NULL,false);if(ret==0){/**WeuseDO_ACCOUNTINGherebecauseweneedthe
From: Omar Sandoval <redacted>
Currently, we always reserve the same extent size in the file and extent
size on disk for delalloc because the former is the worst case for the
latter. For RWF_ENCODED writes, we know the exact size of the extent on
disk, which may be less than or greater than (for bookends) the size in
the file. Add a disk_num_bytes parameter to
btrfs_delalloc_reserve_metadata() so that we can reserve the correct
amount of csum bytes. No functional change.
Reviewed-by: Nikolay Borisov <redacted>
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/ctree.h | 3 ++-
fs/btrfs/delalloc-space.c | 18 ++++++++++--------
fs/btrfs/file.c | 3 ++-
fs/btrfs/inode.c | 3 ++-
fs/btrfs/relocation.c | 4 ++--
5 files changed, 18 insertions(+), 13 deletions(-)
From: Omar Sandoval <redacted>
There are 4 main cases:
1. Inline extents: we copy the data straight out of the extent buffer.
2. Hole/preallocated extents: we fill in zeroes.
3. Regular, uncompressed extents: we read the sectors we need directly
from disk.
4. Regular, compressed extents: we read the entire compressed extent
from disk and indicate what subset of the decompressed extent is in
the file.
This initial implementation simplifies a few things that can be improved
in the future:
- We hold the inode lock during the operation.
- Cases 1, 3, and 4 allocate temporary memory to read into before
copying out to userspace.
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/ctree.h | 2 +
fs/btrfs/file.c | 12 +-
fs/btrfs/inode.c | 491 +++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 504 insertions(+), 1 deletion(-)
@@ -379,6 +379,16 @@ int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)return0;}+staticssize_tbtrfs_file_read_iter(structkiocb*iocb,structiov_iter*iter)+{+if(iocb->ki_flags&IOCB_ENCODED){+if(iocb->ki_flags&IOCB_NOWAIT)+return-EOPNOTSUPP;+returnbtrfs_encoded_read(iocb,iter);+}+returngeneric_file_read_iter(iocb,iter);+}+/* simple helper to fault in pages and copy. This should go away*andbereplacedwithcallsintogenericcode.*/
From: Omar Sandoval <redacted>
The implementation resembles direct I/O: we have to flush any ordered
extents, invalidate the page cache, and do the io tree/delalloc/extent
map/ordered extent dance. From there, we can reuse the compression code
with a minor modification to distinguish the write from writeback. This
also creates inline extents when possible.
Now that read and write are implemented, this also sets the
FMODE_ENCODED_IO flag in btrfs_file_open().
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/compression.c | 7 +-
fs/btrfs/compression.h | 6 +-
fs/btrfs/ctree.h | 2 +
fs/btrfs/file.c | 40 +++++--
fs/btrfs/inode.c | 246 +++++++++++++++++++++++++++++++++++++++-
fs/btrfs/ordered-data.c | 12 +-
fs/btrfs/ordered-data.h | 2 +
7 files changed, 298 insertions(+), 17 deletions(-)
@@ -338,7 +338,8 @@ static void end_compressed_bio_write(struct bio *bio)bio->bi_status==BLK_STS_OK);cb->compressed_pages[0]->mapping=NULL;-end_compressed_writeback(inode,cb);+if(cb->writeback)+end_compressed_writeback(inode,cb);/* note, our inode could be gone now *//*
@@ -49,6 +49,9 @@ struct compressed_bio {/* the compression algorithm for this bio */intcompress_type;+/* Whether this is a write for writeback. */+boolwriteback;+/* number of compressed pages in the array */unsignedlongnr_pages;
@@ -2602,7 +2602,8 @@ static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)if(!test_bit(BTRFS_ORDERED_NOCOW,&ordered_extent->flags)&&!test_bit(BTRFS_ORDERED_PREALLOC,&ordered_extent->flags)&&-!test_bit(BTRFS_ORDERED_DIRECT,&ordered_extent->flags))+!test_bit(BTRFS_ORDERED_DIRECT,&ordered_extent->flags)&&+!test_bit(BTRFS_ORDERED_ENCODED,&ordered_extent->flags))clear_new_delalloc_bytes=true;freespace_inode=btrfs_is_free_space_inode(BTRFS_I(inode));
@@ -10308,6 +10309,247 @@ ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter)returnret;}+ssize_tbtrfs_encoded_write(structkiocb*iocb,structiov_iter*from,+structencoded_iov*encoded)+{+structinode*inode=file_inode(iocb->ki_filp);+structbtrfs_fs_info*fs_info=btrfs_sb(inode->i_sb);+structbtrfs_root*root=BTRFS_I(inode)->root;+structextent_io_tree*io_tree=&BTRFS_I(inode)->io_tree;+structextent_changeset*data_reserved=NULL;+structextent_state*cached_state=NULL;+intcompression;+size_torig_count;+u64start,end;+u64num_bytes,ram_bytes,disk_num_bytes;+unsignedlongnr_pages,i;+structpage**pages;+structbtrfs_keyins;+boolextent_reserved=false;+structextent_map*em;+ssize_tret;++switch(encoded->compression){+caseENCODED_IOV_COMPRESSION_ZLIB:+compression=BTRFS_COMPRESS_ZLIB;+break;+caseENCODED_IOV_COMPRESSION_LZO:+compression=BTRFS_COMPRESS_LZO;+break;+caseENCODED_IOV_COMPRESSION_ZSTD:+compression=BTRFS_COMPRESS_ZSTD;+break;+default:+return-EINVAL;+}+if(encoded->encryption!=ENCODED_IOV_ENCRYPTION_NONE)+return-EINVAL;++orig_count=iov_iter_count(from);++/* The extent size must be sane. */+if(encoded->unencoded_len>BTRFS_MAX_UNCOMPRESSED||+orig_count>BTRFS_MAX_COMPRESSED||orig_count==0)+return-EINVAL;++/*+*Thecompresseddatamustbesmallerthanthedecompresseddata.+*+*It'sofcoursepossiblefordatatocompresstolargerorthesame+*size,butthebufferedI/Opathfallsbacktonocompressionforsuch+*data,andwedon'twanttobreakanyassumptionsbycreatingthese+*extents.+*+*Notethatthisislessstrictthanthecurrentcheckwehavethatthe+*compresseddatamustbeatleastonesectorsmallerthanthe+*decompresseddata.Weonlywanttoenforcetheweakerrequirement+*fromoldkernelsthatitisatleastonebytesmaller.+*/+if(orig_count>=encoded->unencoded_len)+return-EINVAL;++/* The extent must start on a sector boundary. */+start=iocb->ki_pos;+if(!IS_ALIGNED(start,fs_info->sectorsize))+return-EINVAL;++/*+*Theextentmustendonasectorboundary.However,weallowawrite+*whichendsatorextendsi_sizetohaveanunalignedlength;weround+*uptheextentsizeandseti_sizetotheunalignedend.+*/+if(start+encoded->len<inode->i_size&&+!IS_ALIGNED(start+encoded->len,fs_info->sectorsize))+return-EINVAL;++/* Finally, the offset in the unencoded data must be sector-aligned. */+if(!IS_ALIGNED(encoded->unencoded_offset,fs_info->sectorsize))+return-EINVAL;++num_bytes=ALIGN(encoded->len,fs_info->sectorsize);+ram_bytes=ALIGN(encoded->unencoded_len,fs_info->sectorsize);+end=start+num_bytes-1;++/*+*Iftheextentcannotbeinline,thecompresseddataondiskmustbe+*sector-aligned.Forconvenience,weextenditwithzeroesifit+*isn't.+*/+disk_num_bytes=ALIGN(orig_count,fs_info->sectorsize);+nr_pages=DIV_ROUND_UP(disk_num_bytes,PAGE_SIZE);+pages=kvcalloc(nr_pages,sizeof(structpage*),GFP_KERNEL_ACCOUNT);+if(!pages)+return-ENOMEM;+for(i=0;i<nr_pages;i++){+size_tbytes=min_t(size_t,PAGE_SIZE,iov_iter_count(from));+char*kaddr;++pages[i]=alloc_page(GFP_KERNEL_ACCOUNT|__GFP_HIGHMEM);+if(!pages[i]){+ret=-ENOMEM;+gotoout_pages;+}+kaddr=kmap(pages[i]);+if(copy_from_iter(kaddr,bytes,from)!=bytes){+kunmap(pages[i]);+ret=-EFAULT;+gotoout_pages;+}+if(bytes<PAGE_SIZE)+memset(kaddr+bytes,0,PAGE_SIZE-bytes);+kunmap(pages[i]);+}++for(;;){+structbtrfs_ordered_extent*ordered;++ret=btrfs_wait_ordered_range(inode,start,num_bytes);+if(ret)+gotoout_pages;+ret=invalidate_inode_pages2_range(inode->i_mapping,+start>>PAGE_SHIFT,+end>>PAGE_SHIFT);+if(ret)+gotoout_pages;+lock_extent_bits(io_tree,start,end,&cached_state);+ordered=btrfs_lookup_ordered_range(BTRFS_I(inode),start,+num_bytes);+if(!ordered&&+!filemap_range_has_page(inode->i_mapping,start,end))+break;+if(ordered)+btrfs_put_ordered_extent(ordered);+unlock_extent_cached(io_tree,start,end,&cached_state);+cond_resched();+}++ret=btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),disk_num_bytes);+if(ret)+gotoout_unlock;+ret=btrfs_qgroup_reserve_data(BTRFS_I(inode),&data_reserved,start,+num_bytes);+if(ret)+gotoout_free_data_space;+ret=btrfs_delalloc_reserve_metadata(BTRFS_I(inode),num_bytes,+disk_num_bytes);+if(ret)+gotoout_qgroup_free_data;++/* Try an inline extent first. */+if(start==0&&encoded->unencoded_len==encoded->len&&+encoded->unencoded_offset==0){+ret=cow_file_range_inline(BTRFS_I(inode),encoded->len,+orig_count,compression,pages,+true);+if(ret<=0){+if(ret==0)+ret=orig_count;+gotoout_delalloc_release;+}+}++ret=btrfs_reserve_extent(root,disk_num_bytes,disk_num_bytes,+disk_num_bytes,0,0,&ins,1,1);+if(ret)+gotoout_delalloc_release;+extent_reserved=true;++em=create_io_em(BTRFS_I(inode),start,num_bytes,+start-encoded->unencoded_offset,ins.objectid,+ins.offset,ins.offset,ram_bytes,compression,+BTRFS_ORDERED_COMPRESSED);+if(IS_ERR(em)){+ret=PTR_ERR(em);+gotoout_free_reserved;+}+free_extent_map(em);++ret=btrfs_add_ordered_extent(BTRFS_I(inode),start,num_bytes,+ram_bytes,ins.objectid,ins.offset,+encoded->unencoded_offset,+(1<<BTRFS_ORDERED_ENCODED)|+(1<<BTRFS_ORDERED_COMPRESSED),+compression);+if(ret){+btrfs_drop_extent_cache(BTRFS_I(inode),start,end,0);+gotoout_free_reserved;+}+btrfs_dec_block_group_reservations(fs_info,ins.objectid);++if(start+encoded->len>inode->i_size)+i_size_write(inode,start+encoded->len);++unlock_extent_cached(io_tree,start,end,&cached_state);++btrfs_delalloc_release_extents(BTRFS_I(inode),num_bytes);++if(btrfs_submit_compressed_write(BTRFS_I(inode),start,num_bytes,+ins.objectid,ins.offset,pages,+nr_pages,0,NULL,false)){+structpage*page=pages[0];++page->mapping=inode->i_mapping;+btrfs_writepage_endio_finish_ordered(page,start,end,0);+page->mapping=NULL;+ret=-EIO;+gotoout_pages;+}+ret=orig_count;+gotoout;++out_free_reserved:+btrfs_dec_block_group_reservations(fs_info,ins.objectid);+btrfs_free_reserved_extent(fs_info,ins.objectid,ins.offset,1);+out_delalloc_release:+btrfs_delalloc_release_extents(BTRFS_I(inode),num_bytes);+btrfs_delalloc_release_metadata(BTRFS_I(inode),disk_num_bytes,+ret<0);+out_qgroup_free_data:+if(ret<0){+btrfs_qgroup_free_data(BTRFS_I(inode),data_reserved,start,+num_bytes);+}+out_free_data_space:+/*+*Ifbtrfs_reserve_extent()succeeded,thenwealreadydecremented+*bytes_may_use.+*/+if(!extent_reserved)+btrfs_free_reserved_data_space_noquota(fs_info,disk_num_bytes);+out_unlock:+unlock_extent_cached(io_tree,start,end,&cached_state);+out_pages:+for(i=0;i<nr_pages;i++){+if(pages[i])+__free_page(pages[i]);+}+kvfree(pages);+out:+if(ret>=0)+iocb->ki_pos+=encoded->len;+returnret;+}+#ifdef CONFIG_SWAP/**Addanentryindicatingablockgroupordevicewhichispinnedbya
@@ -62,6 +62,8 @@ enum {BTRFS_ORDERED_LOGGED_CSUM,/* We wait for this extent to complete in the current transaction */BTRFS_ORDERED_PENDING,+/* RWF_ENCODED I/O */+BTRFS_ORDERED_ENCODED,};structbtrfs_ordered_extent{
From: Amir Goldstein <amir73il@gmail.com> Date: 2020-08-21 08:48:09
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
quoted hunk
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
---
Documentation/filesystems/encoded_io.rst | 74 ++++++++++
Documentation/filesystems/index.rst | 1 +
include/linux/fs.h | 16 +++
include/uapi/linux/fs.h | 33 ++++-
mm/filemap.c | 166 +++++++++++++++++++++--
5 files changed, 276 insertions(+), 14 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
@@ -0,0 +1,74 @@+===========+Encoded I/O+===========++Encoded I/O is a mechanism for reading and writing encoded (e.g., compressed+and/or encrypted) data directly from/to the filesystem. The userspace interface+is thoroughly described in the :manpage:`encoded_io(7)` man page; this document+describes the requirements for filesystem support.++First of all, a filesystem supporting encoded I/O must indicate this by setting+the ``FMODE_ENCODED_IO`` flag in its ``file_open`` file operation::++ static int foo_file_open(struct inode *inode, struct file *filp)+ {+ ...+ filep->f_mode |= FMODE_ENCODED_IO;+ ...+ }++Encoded I/O goes through ``read_iter`` and ``write_iter``, designated by the+``IOCB_ENCODED`` flag in ``kiocb->ki_flags``.++Reads+=====++Encoded ``read_iter`` should:++1. Call ``generic_encoded_read_checks()`` to validate the file and buffers+ provided by userspace.+2. Initialize the ``encoded_iov`` appropriately.+3. Copy it to the user with ``copy_encoded_iov_to_iter()``.+4. Copy the encoded data to the user.+5. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+6. Return the size of the encoded data read, not including the ``encoded_iov``.++There are a few details to be aware of:++* Encoded ``read_iter`` should support reading unencoded data if the extent is+ not encoded.+* If the buffers provided by the user are not large enough to contain an entire+ encoded extent, then ``read_iter`` should return ``-ENOBUFS``. This is to+ avoid confusing userspace with truncated data that cannot be properly+ decoded.+* Reads in the middle of an encoded extent can be returned by setting+``encoded_iov->unencoded_offset`` to non-zero.+* Truncated unencoded data (e.g., because the file does not end on a block+ boundary) may be returned by setting ``encoded_iov->len`` to a value smaller+ value than ``encoded_iov->unencoded_len - encoded_iov->unencoded_offset``.++Writes+======++Encoded ``write_iter`` should (in addition to the usual accounting/checks done+by ``write_iter``):++1. Call ``copy_encoded_iov_from_iter()`` to get and validate the+``encoded_iov``.+2. Call ``generic_encoded_write_checks()`` instead of+``generic_write_checks()``.+3. Check that the provided encoding in ``encoded_iov`` is supported.+4. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+5. Return the size of the encoded data written.++Again, there are a few details:++* Encoded ``write_iter`` doesn't need to support writing unencoded data.+*``write_iter`` should either write all of the encoded data or none of it; it+ must not do partial writes.+*``write_iter`` doesn't need to validate the encoded data; a subsequent read+ may return, e.g., ``-EIO`` if the data is not valid.+* The user may lie about the unencoded size of the data; a subsequent read+ should truncate or zero-extend the unencoded data rather than returning an+ error.+* Be careful of page cache coherency.
Haha that rings in my head like the "Smoking kills!" warnings...
I find it a bit odd that you mix page cache at all when reading
unencoded extents.
Feels like a file with FMODE_ENCODED_IO should stick to direct IO in all cases.
I don't know how btrfs deals with mixing direct IO and page cache IO normally,
but surely the rules could be made even stricter for an inode accessed with this
new API?
Is there something I am misunderstanding?
Thanks,
Amir.
From: Amir Goldstein <amir73il@gmail.com> Date: 2020-08-21 09:25:05
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
From: Omar Sandoval <redacted>
This adds a new page, encoded_io(7), providing an overview of encoded
I/O and updates fcntl(2), open(2), and preadv2(2)/pwritev2(2) to
reference it.
Cc: Michael Kerrisk <redacted>
Cc: linux-man <redacted>
Signed-off-by: Omar Sandoval <redacted>
---
Omar,
Thanks for making the clarifications. Some questions below.
[...]
+.PP
+As the filesystem page cache typically contains decoded data,
+encoded I/O bypasses the page cache.
+.SS Extent layout
+By using
+.IR len ,
+.IR unencoded_len ,
+and
+.IR unencoded_offset ,
+it is possible to refer to a subset of an unencoded extent.
+.PP
+In the simplest case,
+.I len
+is equal to
+.I unencoded_len
+and
+.I unencoded_offset
+is zero.
+This means that the entire unencoded extent is used.
+.PP
+However, suppose we read 50 bytes into a file
+which contains a single compressed extent.
+The filesystem must still return the entire compressed extent
+for us to be able to decompress it,
+so
+.I unencoded_len
+would be the length of the entire decompressed extent.
+However, because the read was at offset 50,
+the first 50 bytes should be ignored.
+Therefore,
+.I unencoded_offset
+would be 50,
+and
+.I len
+would accordingly be
+.IR unencoded_len\ -\ 50 .
+.PP
+Additionally, suppose we want to create an encrypted file with length 500,
+but the file is encrypted with a block cipher using a block size of 4096.
+The unencoded data would therefore include the appropriate padding,
+and
+.I unencoded_len
+would be 4096.
+However, to represent the logical size of the file,
+.I len
+would be 500
+(and
+.I unencoded_offset
+would be 0).
+.PP
+Similar situations can arise in other cases:
+.IP * 3
+If the filesystem pads data to the filesystem block size before compressing,
+then compressed files with a size unaligned to the filesystem block size will
+end with an extent with
+.I len
+<
+.IR unencoded_len .
+.IP *
+Extents cloned from the middle of a larger encoded extent with
+.B FICLONERANGE
+may have a non-zero
+.I unencoded_offset
+and/or
+.I len
+<
+.IR unencoded_len .
+.IP *
+If the middle of an encoded extent is overwritten,
+the filesystem may create extents with a non-zero
+.I unencoded_offset
+and/or
+.I len
+<
+.I unencoded_len
+for the parts that were not overwritten.
So in this case, would the reader be getting extents "out of unencoded order"?
e.g. unencoded range 0..4096 and then unencoded range 10..20?
Or would reader be reading the encoded full block twice, once for
ragne 0..10 and once for range 20..4096?
+.SS Security
+Encoded I/O creates the potential for some security issues:
+.IP * 3
+Encoded writes allow writing arbitrary data which the kernel will decode on
+a subsequent read. Decompression algorithms are complex and may have bugs
+which can be exploited by maliciously crafted data.
+.IP *
+Encoded reads may return data which is not logically present in the file
+(see the discussion of
+.I len
+vs.
+.I unencoded_len
+above).
+It may not be intended for this data to be readable.
+.PP
+Therefore, encoded I/O requires privilege.
+Namely, the
+.B RWF_ENCODED
+flag may only be used when the file was opened with the
+.B O_ALLOW_ENCODED
+flag to
+.BR open (2),
+which requires the
+.B CAP_SYS_ADMIN
+capability.
+.B O_ALLOW_ENCODED
+may be set and cleared with
+.BR fcntl (2).
+Note that it is not cleared on
+.BR fork (2)
+or
+.BR execve (2);
+one may wish to use
+.B O_CLOEXEC
+with
+.BR O_ALLOW_ENCODED .
+.SS Filesystem support
+Encoded I/O is supported on the following filesystems:
+.TP
+Btrfs (since Linux 5.10)
+.IP
+Btrfs supports encoded reads and writes of compressed data.
+The data is encoded as follows:
+.RS
+.IP * 3
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_ZLIB ,
+then the encoded data is a single zlib stream.
+.IP *
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_LZO ,
+then the encoded data is compressed page by page with LZO1X
+and wrapped in the format documented in the Linux kernel source file
+.IR fs/btrfs/lzo.c .
:-/ So maybe call it ENCODED_IOV_COMPRESSION_BTRFS_LZO?
I understand why you want the encoding format not to be opaque, but
I imagine the encoded data is not going to be migrated as is between
different filesystems. So just call it for what it is - a private
filesystem encoding
format. If you have a format that is standard and other filesystems are likely
to use, fine, but let's not make an API that discourages using
"private" encoding, just for the sake of it and make life harder for no good
reason.
All the reader of this man page may be interested to know is which
filesystems are expected to support which encoding types and a general
description of what they mean (as you did).
Making this page wrongly appear as a standard for encoding formats is not
going to play out well...
+.IP *
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_ZSTD ,
+then the encoded data is a single zstd frame compressed with the
+.I windowLog
+compression parameter set to no more than 17.
Even that small detail is a bit limiting to filesystems and should
therefore be tagged as a private btrfs encoding IMO.
Thanks,
Amir.
On Fri, Aug 21, 2020 at 12:24:48PM +0300, Amir Goldstein wrote:
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
quoted
From: Omar Sandoval <redacted>
This adds a new page, encoded_io(7), providing an overview of encoded
I/O and updates fcntl(2), open(2), and preadv2(2)/pwritev2(2) to
reference it.
Cc: Michael Kerrisk <redacted>
Cc: linux-man <redacted>
Signed-off-by: Omar Sandoval <redacted>
---
Omar,
Thanks for making the clarifications. Some questions below.
[...]
quoted
+.PP
+As the filesystem page cache typically contains decoded data,
+encoded I/O bypasses the page cache.
+.SS Extent layout
+By using
+.IR len ,
+.IR unencoded_len ,
+and
+.IR unencoded_offset ,
+it is possible to refer to a subset of an unencoded extent.
+.PP
+In the simplest case,
+.I len
+is equal to
+.I unencoded_len
+and
+.I unencoded_offset
+is zero.
+This means that the entire unencoded extent is used.
+.PP
+However, suppose we read 50 bytes into a file
+which contains a single compressed extent.
+The filesystem must still return the entire compressed extent
+for us to be able to decompress it,
+so
+.I unencoded_len
+would be the length of the entire decompressed extent.
+However, because the read was at offset 50,
+the first 50 bytes should be ignored.
+Therefore,
+.I unencoded_offset
+would be 50,
+and
+.I len
+would accordingly be
+.IR unencoded_len\ -\ 50 .
+.PP
+Additionally, suppose we want to create an encrypted file with length 500,
+but the file is encrypted with a block cipher using a block size of 4096.
+The unencoded data would therefore include the appropriate padding,
+and
+.I unencoded_len
+would be 4096.
+However, to represent the logical size of the file,
+.I len
+would be 500
+(and
+.I unencoded_offset
+would be 0).
+.PP
+Similar situations can arise in other cases:
+.IP * 3
+If the filesystem pads data to the filesystem block size before compressing,
+then compressed files with a size unaligned to the filesystem block size will
+end with an extent with
+.I len
+<
+.IR unencoded_len .
+.IP *
+Extents cloned from the middle of a larger encoded extent with
+.B FICLONERANGE
+may have a non-zero
+.I unencoded_offset
+and/or
+.I len
+<
+.IR unencoded_len .
+.IP *
+If the middle of an encoded extent is overwritten,
+the filesystem may create extents with a non-zero
+.I unencoded_offset
+and/or
+.I len
+<
+.I unencoded_len
+for the parts that were not overwritten.
So in this case, would the reader be getting extents "out of unencoded order"?
e.g. unencoded range 0..4096 and then unencoded range 10..20?
Or would reader be reading the encoded full block twice, once for
ragne 0..10 and once for range 20..4096?
The latter. If the file refers to the same encoded data twice, reading
the file sequentially with RWF_ENCODED will return it twice (with
different offsets each time). This is obviously not perfect, but it
keeps the interface simpler: the abstraction is not "what exactly is the
extent layout of the file" but rather "I want to read this logical range
of data", even if that involves pulling in some details from the extent
metadata.
quoted
+.SS Security
+Encoded I/O creates the potential for some security issues:
+.IP * 3
+Encoded writes allow writing arbitrary data which the kernel will decode on
+a subsequent read. Decompression algorithms are complex and may have bugs
+which can be exploited by maliciously crafted data.
+.IP *
+Encoded reads may return data which is not logically present in the file
+(see the discussion of
+.I len
+vs.
+.I unencoded_len
+above).
+It may not be intended for this data to be readable.
+.PP
+Therefore, encoded I/O requires privilege.
+Namely, the
+.B RWF_ENCODED
+flag may only be used when the file was opened with the
+.B O_ALLOW_ENCODED
+flag to
+.BR open (2),
+which requires the
+.B CAP_SYS_ADMIN
+capability.
+.B O_ALLOW_ENCODED
+may be set and cleared with
+.BR fcntl (2).
+Note that it is not cleared on
+.BR fork (2)
+or
+.BR execve (2);
+one may wish to use
+.B O_CLOEXEC
+with
+.BR O_ALLOW_ENCODED .
+.SS Filesystem support
+Encoded I/O is supported on the following filesystems:
+.TP
+Btrfs (since Linux 5.10)
+.IP
+Btrfs supports encoded reads and writes of compressed data.
+The data is encoded as follows:
+.RS
+.IP * 3
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_ZLIB ,
+then the encoded data is a single zlib stream.
+.IP *
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_LZO ,
+then the encoded data is compressed page by page with LZO1X
+and wrapped in the format documented in the Linux kernel source file
+.IR fs/btrfs/lzo.c .
:-/ So maybe call it ENCODED_IOV_COMPRESSION_BTRFS_LZO?
I understand why you want the encoding format not to be opaque, but
I imagine the encoded data is not going to be migrated as is between
different filesystems. So just call it for what it is - a private
filesystem encoding
format. If you have a format that is standard and other filesystems are likely
to use, fine, but let's not make an API that discourages using
"private" encoding, just for the sake of it and make life harder for no good
reason.
All the reader of this man page may be interested to know is which
filesystems are expected to support which encoding types and a general
description of what they mean (as you did).
Making this page wrongly appear as a standard for encoding formats is not
going to play out well...
quoted
+.IP *
+If
+.I compression
+is
+.BR ENCODED_IOV_COMPRESSION_ZSTD ,
+then the encoded data is a single zstd frame compressed with the
+.I windowLog
+compression parameter set to no more than 17.
Even that small detail is a bit limiting to filesystems and should
therefore be tagged as a private btrfs encoding IMO.
Agreed, I'll make the LZO and ZSTD encodings Btrfs-specific. My
assumption was that decoders would look at the filesystem type from,
say, statfs(2), but making it explicit in the encoding is much better.
On the other hand, I think ENCODED_IOV_COMPRESSION_ZLIB is generic
enough to be reused.
Thanks for taking a look!
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 18:28:48
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
The upcoming RWF_ENCODED operation introduces some security concerns:
1. Compressed writes will pass arbitrary data to decompression
algorithms in the kernel.
2. Compressed reads can leak truncated/hole punched data.
Therefore, we need to require privilege for RWF_ENCODED. It's not
possible to do the permissions checks at the time of the read or write
because, e.g., io_uring submits IO from a worker thread. So, add an open
flag which requires CAP_SYS_ADMIN. It can also be set and cleared with
fcntl(). The flag is not cleared in any way on fork or exec; it should
probably be used with O_CLOEXEC in most cases.
Note that the usual issue that unknown open flags are ignored doesn't
really matter for O_ALLOW_ENCODED; if the kernel doesn't support
O_ALLOW_ENCODED, then it doesn't support RWF_ENCODED, either.
It seemed like you agreed to require O_CLOEXEC to be set when using
O_ALLOW_ENCODED in your last go around, what happened to that? I know I'd feel
better if we had that requirement, and if we aren't I'd like to know why we
can't. Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 18:52:31
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
This is essentially copy_struct_from_user() but for an iov_iter.
Suggested-by: Aleksa Sarai <redacted>
Signed-off-by: Omar Sandoval <redacted>
This took me a lot longer to grok than I'm proud of, but the idea is you'll have
a single segment that represents the incoming encoded data, and then subsequent
segments will be the read/write buffer, correct? The code looks fine to me,
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:07:40
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:18:05
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
btrfs_csum_one_bio() loops over each filesystem block in the bio while
keeping a cursor of its current logical position in the file in order to
look up the ordered extent to add the checksums to. However, this
doesn't make much sense for compressed extents, as a sector on disk does
not correspond to a sector of decompressed file data. It happens to work
because 1) the compressed bio always covers one ordered extent and 2)
the size of the bio is always less than the size of the ordered extent.
However, the second point will not always be true for encoded writes.
Let's add a boolean parameter to btrfs_csum_one_bio() to indicate that
it can assume that the bio only covers one ordered extent. Since we're
already changing the signature, let's get rid of the contig parameter
and make it implied by the offset parameter, similar to the change we
recently made to btrfs_lookup_bio_sums(). Additionally, let's rename
nr_sectors to blockcount to make it clear that it's the number of
filesystem blocks, not the number of 512-byte sectors.
Signed-off-by: Omar Sandoval <redacted>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:23:41
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
Currently, we only create ordered extents when ram_bytes == num_bytes
and offset == 0. However, RWF_ENCODED writes may create extents which
only refer to a subset of the full unencoded extent, so we need to plumb
these fields through the ordered extent infrastructure and pass them
down to insert_reserved_file_extent().
Since we're changing the btrfs_add_ordered_extent* signature, let's get
rid of the trivial wrappers and add a kernel-doc.
Reviewed-by: Nikolay Borisov <redacted>
Signed-off-by: Omar Sandoval <redacted>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:26:13
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
Currently, we always reserve the same extent size in the file and extent
size on disk for delalloc because the former is the worst case for the
latter. For RWF_ENCODED writes, we know the exact size of the extent on
disk, which may be less than or greater than (for bookends) the size in
the file. Add a disk_num_bytes parameter to
btrfs_delalloc_reserve_metadata() so that we can reserve the correct
amount of csum bytes. No functional change.
Reviewed-by: Nikolay Borisov <redacted>
Signed-off-by: Omar Sandoval <redacted>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:33:26
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
Currently, an inline extent is always created after i_size is extended
from btrfs_dirty_pages(). However, for encoded writes, we only want to
update i_size after we successfully created the inline extent. Add an
update_i_size parameter to cow_file_range_inline() and
insert_inline_extent() and pass in the size of the extent rather than
determining it from i_size. Since the start parameter is always passed
as 0, get rid of it and simplify the logic in these two functions. While
we're here, let's document the requirements for creating an inline
extent.
Signed-off-by: Omar Sandoval <redacted>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 19:54:34
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
There are 4 main cases:
1. Inline extents: we copy the data straight out of the extent buffer.
2. Hole/preallocated extents: we fill in zeroes.
3. Regular, uncompressed extents: we read the sectors we need directly
from disk.
4. Regular, compressed extents: we read the entire compressed extent
from disk and indicate what subset of the decompressed extent is in
the file.
This initial implementation simplifies a few things that can be improved
in the future:
- We hold the inode lock during the operation.
- Cases 1, 3, and 4 allocate temporary memory to read into before
copying out to userspace.
Signed-off-by: Omar Sandoval <redacted>
Why not just btrfs_release_path(), you're freeing below anyway.
Also a mention that we're explicitly not handling read repairs and backup copies
would be good in the changelog as well. Thanks,
Josef
From: Josef Bacik <josef@toxicpanda.com> Date: 2020-08-24 20:30:58
On 8/21/20 3:38 AM, Omar Sandoval wrote:
From: Omar Sandoval <redacted>
The implementation resembles direct I/O: we have to flush any ordered
extents, invalidate the page cache, and do the io tree/delalloc/extent
map/ordered extent dance. From there, we can reuse the compression code
with a minor modification to distinguish the write from writeback. This
also creates inline extents when possible.
Now that read and write are implemented, this also sets the
FMODE_ENCODED_IO flag in btrfs_file_open().
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/compression.c | 7 +-
fs/btrfs/compression.h | 6 +-
fs/btrfs/ctree.h | 2 +
fs/btrfs/file.c | 40 +++++--
fs/btrfs/inode.c | 246 +++++++++++++++++++++++++++++++++++++++-
fs/btrfs/ordered-data.c | 12 +-
fs/btrfs/ordered-data.h | 2 +
7 files changed, 298 insertions(+), 17 deletions(-)
<snip>
+
+ ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), disk_num_bytes);
+ if (ret)
+ goto out_unlock;
+ ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved, start,
+ num_bytes);
+ if (ret)
+ goto out_free_data_space;
+ ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), num_bytes,
+ disk_num_bytes);
+ if (ret)
+ goto out_qgroup_free_data;
This can just be btrfs_delalloc_reserve_space() and that way the error handling
is much cleaner.
<snip>
On Mon, Aug 24, 2020 at 02:52:24PM -0400, Josef Bacik wrote:
On 8/21/20 3:38 AM, Omar Sandoval wrote:
quoted
From: Omar Sandoval <redacted>
This is essentially copy_struct_from_user() but for an iov_iter.
Suggested-by: Aleksa Sarai <redacted>
Signed-off-by: Omar Sandoval <redacted>
This took me a lot longer to grok than I'm proud of, but the idea is you'll
have a single segment that represents the incoming encoded data, and then
subsequent segments will be the read/write buffer, correct? The code looks
fine to me,
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Thanks,
Josef
Yes, that's the idea for RWF_ENCODED. This patch is the generic way to
shove an extra metadata struct at the beginning of an iov_iter in a way
that is backwards/forwards compatible.
Thanks!
On Mon, Aug 24, 2020 at 02:28:39PM -0400, Josef Bacik wrote:
On 8/21/20 3:38 AM, Omar Sandoval wrote:
quoted
From: Omar Sandoval <redacted>
The upcoming RWF_ENCODED operation introduces some security concerns:
1. Compressed writes will pass arbitrary data to decompression
algorithms in the kernel.
2. Compressed reads can leak truncated/hole punched data.
Therefore, we need to require privilege for RWF_ENCODED. It's not
possible to do the permissions checks at the time of the read or write
because, e.g., io_uring submits IO from a worker thread. So, add an open
flag which requires CAP_SYS_ADMIN. It can also be set and cleared with
fcntl(). The flag is not cleared in any way on fork or exec; it should
probably be used with O_CLOEXEC in most cases.
Note that the usual issue that unknown open flags are ignored doesn't
really matter for O_ALLOW_ENCODED; if the kernel doesn't support
O_ALLOW_ENCODED, then it doesn't support RWF_ENCODED, either.
It seemed like you agreed to require O_CLOEXEC to be set when using
O_ALLOW_ENCODED in your last go around, what happened to that? I know I'd
feel better if we had that requirement, and if we aren't I'd like to know
why we can't. Thanks,
Josef
Yup I was still on the fence about it since it's a bit of an awkward
requirement, but I'm convinced now that we might as well be safe and
require it.
On Mon, Aug 24, 2020 at 03:54:29PM -0400, Josef Bacik wrote:
On 8/21/20 3:38 AM, Omar Sandoval wrote:
quoted
From: Omar Sandoval <redacted>
There are 4 main cases:
1. Inline extents: we copy the data straight out of the extent buffer.
2. Hole/preallocated extents: we fill in zeroes.
3. Regular, uncompressed extents: we read the sectors we need directly
from disk.
4. Regular, compressed extents: we read the entire compressed extent
from disk and indicate what subset of the decompressed extent is in
the file.
This initial implementation simplifies a few things that can be improved
in the future:
- We hold the inode lock during the operation.
- Cases 1, 3, and 4 allocate temporary memory to read into before
copying out to userspace.
Signed-off-by: Omar Sandoval <redacted>
On Mon, Aug 24, 2020 at 04:30:52PM -0400, Josef Bacik wrote:
On 8/21/20 3:38 AM, Omar Sandoval wrote:
quoted
From: Omar Sandoval <redacted>
The implementation resembles direct I/O: we have to flush any ordered
extents, invalidate the page cache, and do the io tree/delalloc/extent
map/ordered extent dance. From there, we can reuse the compression code
with a minor modification to distinguish the write from writeback. This
also creates inline extents when possible.
Now that read and write are implemented, this also sets the
FMODE_ENCODED_IO flag in btrfs_file_open().
Signed-off-by: Omar Sandoval <redacted>
---
fs/btrfs/compression.c | 7 +-
fs/btrfs/compression.h | 6 +-
fs/btrfs/ctree.h | 2 +
fs/btrfs/file.c | 40 +++++--
fs/btrfs/inode.c | 246 +++++++++++++++++++++++++++++++++++++++-
fs/btrfs/ordered-data.c | 12 +-
fs/btrfs/ordered-data.h | 2 +
7 files changed, 298 insertions(+), 17 deletions(-)
<snip>
quoted
+
+ ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), disk_num_bytes);
+ if (ret)
+ goto out_unlock;
+ ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved, start,
+ num_bytes);
+ if (ret)
+ goto out_free_data_space;
+ ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), num_bytes,
+ disk_num_bytes);
+ if (ret)
+ goto out_qgroup_free_data;
This can just be btrfs_delalloc_reserve_space() and that way the error
handling is much cleaner.
<snip>
Likewise this can all just be btrfs_free_reserved_data_space(). Thanks,
Josef
btrfs_delalloc_reserve_space() and btrfs_free_reserved_data_space()
assume that num_bytes == disk_num_bytes, which isn't true for
RWF_ENCODED.
I figured it'd be cleaner to open-code this special case in the one
place that it's needed, but I could also add explicit num_bytes and
disk_num_bytes arguments to btrfs_delalloc_reserve_space() and
btrfs_free_reserved_data_space(). They'd just be equal everywhere except
for here.
If you're fine with keeping it this way, I'll add a comment explaining
why we can't use the higher-level helpers.
On Fri, Aug 21, 2020 at 11:47:54AM +0300, Amir Goldstein wrote:
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
quoted
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
---
Documentation/filesystems/encoded_io.rst | 74 ++++++++++
Documentation/filesystems/index.rst | 1 +
include/linux/fs.h | 16 +++
include/uapi/linux/fs.h | 33 ++++-
mm/filemap.c | 166 +++++++++++++++++++++--
5 files changed, 276 insertions(+), 14 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
@@ -0,0 +1,74 @@+===========+Encoded I/O+===========++Encoded I/O is a mechanism for reading and writing encoded (e.g., compressed+and/or encrypted) data directly from/to the filesystem. The userspace interface+is thoroughly described in the :manpage:`encoded_io(7)` man page; this document+describes the requirements for filesystem support.++First of all, a filesystem supporting encoded I/O must indicate this by setting+the ``FMODE_ENCODED_IO`` flag in its ``file_open`` file operation::++ static int foo_file_open(struct inode *inode, struct file *filp)+ {+ ...+ filep->f_mode |= FMODE_ENCODED_IO;+ ...+ }++Encoded I/O goes through ``read_iter`` and ``write_iter``, designated by the+``IOCB_ENCODED`` flag in ``kiocb->ki_flags``.++Reads+=====++Encoded ``read_iter`` should:++1. Call ``generic_encoded_read_checks()`` to validate the file and buffers+ provided by userspace.+2. Initialize the ``encoded_iov`` appropriately.+3. Copy it to the user with ``copy_encoded_iov_to_iter()``.+4. Copy the encoded data to the user.+5. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+6. Return the size of the encoded data read, not including the ``encoded_iov``.++There are a few details to be aware of:++* Encoded ``read_iter`` should support reading unencoded data if the extent is+ not encoded.+* If the buffers provided by the user are not large enough to contain an entire+ encoded extent, then ``read_iter`` should return ``-ENOBUFS``. This is to+ avoid confusing userspace with truncated data that cannot be properly+ decoded.+* Reads in the middle of an encoded extent can be returned by setting+``encoded_iov->unencoded_offset`` to non-zero.+* Truncated unencoded data (e.g., because the file does not end on a block+ boundary) may be returned by setting ``encoded_iov->len`` to a value smaller+ value than ``encoded_iov->unencoded_len - encoded_iov->unencoded_offset``.++Writes+======++Encoded ``write_iter`` should (in addition to the usual accounting/checks done+by ``write_iter``):++1. Call ``copy_encoded_iov_from_iter()`` to get and validate the+``encoded_iov``.+2. Call ``generic_encoded_write_checks()`` instead of+``generic_write_checks()``.+3. Check that the provided encoding in ``encoded_iov`` is supported.+4. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+5. Return the size of the encoded data written.++Again, there are a few details:++* Encoded ``write_iter`` doesn't need to support writing unencoded data.+*``write_iter`` should either write all of the encoded data or none of it; it+ must not do partial writes.+*``write_iter`` doesn't need to validate the encoded data; a subsequent read+ may return, e.g., ``-EIO`` if the data is not valid.+* The user may lie about the unencoded size of the data; a subsequent read+ should truncate or zero-extend the unencoded data rather than returning an+ error.+* Be careful of page cache coherency.
Haha that rings in my head like the "Smoking kills!" warnings...
I find it a bit odd that you mix page cache at all when reading
unencoded extents.
Feels like a file with FMODE_ENCODED_IO should stick to direct IO in all cases.
I don't know how btrfs deals with mixing direct IO and page cache IO normally,
but surely the rules could be made even stricter for an inode accessed with this
new API?
Is there something I am misunderstanding?
Thanks,
Amir.
I'm not completely following here, are you suggesting that if a file is
open with O_ALLOW_ENCODED, buffered I/O to that file should return an
error? Btrfs at least does the necessary range locking and page cache
invalidation to ensure that direct I/O gets along with buffered I/O (and
now encoded I/O).
From: Amir Goldstein <amir73il@gmail.com> Date: 2020-08-25 08:25:23
On Tue, Aug 25, 2020 at 2:49 AM Omar Sandoval [off-list ref] wrote:
On Fri, Aug 21, 2020 at 11:47:54AM +0300, Amir Goldstein wrote:
quoted
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
quoted
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
---
Documentation/filesystems/encoded_io.rst | 74 ++++++++++
Documentation/filesystems/index.rst | 1 +
include/linux/fs.h | 16 +++
include/uapi/linux/fs.h | 33 ++++-
mm/filemap.c | 166 +++++++++++++++++++++--
5 files changed, 276 insertions(+), 14 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
@@ -0,0 +1,74 @@+===========+Encoded I/O+===========++Encoded I/O is a mechanism for reading and writing encoded (e.g., compressed+and/or encrypted) data directly from/to the filesystem. The userspace interface+is thoroughly described in the :manpage:`encoded_io(7)` man page; this document+describes the requirements for filesystem support.++First of all, a filesystem supporting encoded I/O must indicate this by setting+the ``FMODE_ENCODED_IO`` flag in its ``file_open`` file operation::++ static int foo_file_open(struct inode *inode, struct file *filp)+ {+ ...+ filep->f_mode |= FMODE_ENCODED_IO;+ ...+ }++Encoded I/O goes through ``read_iter`` and ``write_iter``, designated by the+``IOCB_ENCODED`` flag in ``kiocb->ki_flags``.++Reads+=====++Encoded ``read_iter`` should:++1. Call ``generic_encoded_read_checks()`` to validate the file and buffers+ provided by userspace.+2. Initialize the ``encoded_iov`` appropriately.+3. Copy it to the user with ``copy_encoded_iov_to_iter()``.+4. Copy the encoded data to the user.+5. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+6. Return the size of the encoded data read, not including the ``encoded_iov``.++There are a few details to be aware of:++* Encoded ``read_iter`` should support reading unencoded data if the extent is+ not encoded.+* If the buffers provided by the user are not large enough to contain an entire+ encoded extent, then ``read_iter`` should return ``-ENOBUFS``. This is to+ avoid confusing userspace with truncated data that cannot be properly+ decoded.+* Reads in the middle of an encoded extent can be returned by setting+``encoded_iov->unencoded_offset`` to non-zero.+* Truncated unencoded data (e.g., because the file does not end on a block+ boundary) may be returned by setting ``encoded_iov->len`` to a value smaller+ value than ``encoded_iov->unencoded_len - encoded_iov->unencoded_offset``.++Writes+======++Encoded ``write_iter`` should (in addition to the usual accounting/checks done+by ``write_iter``):++1. Call ``copy_encoded_iov_from_iter()`` to get and validate the+``encoded_iov``.+2. Call ``generic_encoded_write_checks()`` instead of+``generic_write_checks()``.+3. Check that the provided encoding in ``encoded_iov`` is supported.+4. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+5. Return the size of the encoded data written.++Again, there are a few details:++* Encoded ``write_iter`` doesn't need to support writing unencoded data.+*``write_iter`` should either write all of the encoded data or none of it; it+ must not do partial writes.+*``write_iter`` doesn't need to validate the encoded data; a subsequent read+ may return, e.g., ``-EIO`` if the data is not valid.+* The user may lie about the unencoded size of the data; a subsequent read+ should truncate or zero-extend the unencoded data rather than returning an+ error.+* Be careful of page cache coherency.
Haha that rings in my head like the "Smoking kills!" warnings...
I find it a bit odd that you mix page cache at all when reading
unencoded extents.
Feels like a file with FMODE_ENCODED_IO should stick to direct IO in all cases.
I don't know how btrfs deals with mixing direct IO and page cache IO normally,
but surely the rules could be made even stricter for an inode accessed with this
new API?
Is there something I am misunderstanding?
Thanks,
Amir.
I'm not completely following here, are you suggesting that if a file is
open with O_ALLOW_ENCODED, buffered I/O to that file should return an
error?
No. I don't.
Btrfs at least does the necessary range locking and page cache
invalidation to ensure that direct I/O gets along with buffered I/O (and
now encoded I/O).
That's a good start :-)
I saw btrfs_encoded_read_regular_fill_pages() and concluded that even
in FMODE_ENCODED_IO, when reading an unencoded extent, you fill
page cache with the unencoded data.
Is that correct? or did I miss read the code?
If correct, does it serve any purpose?
Seems more sensible to me to read/write FMODE_ENCODED_IO only in direct io
regardless if the extent is encoded or not (for simpler code if nothing else).
Thanks,
Amir.
On Tue, Aug 25, 2020 at 11:25:05AM +0300, Amir Goldstein wrote:
On Tue, Aug 25, 2020 at 2:49 AM Omar Sandoval [off-list ref] wrote:
quoted
On Fri, Aug 21, 2020 at 11:47:54AM +0300, Amir Goldstein wrote:
quoted
On Fri, Aug 21, 2020 at 10:38 AM Omar Sandoval [off-list ref] wrote:
quoted
From: Omar Sandoval <redacted>
Btrfs supports transparent compression: data written by the user can be
compressed when written to disk and decompressed when read back.
However, we'd like to add an interface to write pre-compressed data
directly to the filesystem, and the matching interface to read
compressed data without decompressing it. This adds support for
so-called "encoded I/O" via preadv2() and pwritev2().
A new RWF_ENCODED flags indicates that a read or write is "encoded". If
this flag is set, iov[0].iov_base points to a struct encoded_iov which
is used for metadata: namely, the compression algorithm, unencoded
(i.e., decompressed) length, and what subrange of the unencoded data
should be used (needed for truncated or hole-punched extents and when
reading in the middle of an extent). For reads, the filesystem returns
this information; for writes, the caller provides it to the filesystem.
iov[0].iov_len must be set to sizeof(struct encoded_iov), which can be
used to extend the interface in the future a la copy_struct_from_user().
The remaining iovecs contain the encoded extent.
This adds the VFS helpers for supporting encoded I/O and documentation
for filesystem support.
Signed-off-by: Omar Sandoval <redacted>
---
Documentation/filesystems/encoded_io.rst | 74 ++++++++++
Documentation/filesystems/index.rst | 1 +
include/linux/fs.h | 16 +++
include/uapi/linux/fs.h | 33 ++++-
mm/filemap.c | 166 +++++++++++++++++++++--
5 files changed, 276 insertions(+), 14 deletions(-)
create mode 100644 Documentation/filesystems/encoded_io.rst
@@ -0,0 +1,74 @@+===========+Encoded I/O+===========++Encoded I/O is a mechanism for reading and writing encoded (e.g., compressed+and/or encrypted) data directly from/to the filesystem. The userspace interface+is thoroughly described in the :manpage:`encoded_io(7)` man page; this document+describes the requirements for filesystem support.++First of all, a filesystem supporting encoded I/O must indicate this by setting+the ``FMODE_ENCODED_IO`` flag in its ``file_open`` file operation::++ static int foo_file_open(struct inode *inode, struct file *filp)+ {+ ...+ filep->f_mode |= FMODE_ENCODED_IO;+ ...+ }++Encoded I/O goes through ``read_iter`` and ``write_iter``, designated by the+``IOCB_ENCODED`` flag in ``kiocb->ki_flags``.++Reads+=====++Encoded ``read_iter`` should:++1. Call ``generic_encoded_read_checks()`` to validate the file and buffers+ provided by userspace.+2. Initialize the ``encoded_iov`` appropriately.+3. Copy it to the user with ``copy_encoded_iov_to_iter()``.+4. Copy the encoded data to the user.+5. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+6. Return the size of the encoded data read, not including the ``encoded_iov``.++There are a few details to be aware of:++* Encoded ``read_iter`` should support reading unencoded data if the extent is+ not encoded.+* If the buffers provided by the user are not large enough to contain an entire+ encoded extent, then ``read_iter`` should return ``-ENOBUFS``. This is to+ avoid confusing userspace with truncated data that cannot be properly+ decoded.+* Reads in the middle of an encoded extent can be returned by setting+``encoded_iov->unencoded_offset`` to non-zero.+* Truncated unencoded data (e.g., because the file does not end on a block+ boundary) may be returned by setting ``encoded_iov->len`` to a value smaller+ value than ``encoded_iov->unencoded_len - encoded_iov->unencoded_offset``.++Writes+======++Encoded ``write_iter`` should (in addition to the usual accounting/checks done+by ``write_iter``):++1. Call ``copy_encoded_iov_from_iter()`` to get and validate the+``encoded_iov``.+2. Call ``generic_encoded_write_checks()`` instead of+``generic_write_checks()``.+3. Check that the provided encoding in ``encoded_iov`` is supported.+4. Advance ``kiocb->ki_pos`` by ``encoded_iov->len``.+5. Return the size of the encoded data written.++Again, there are a few details:++* Encoded ``write_iter`` doesn't need to support writing unencoded data.+*``write_iter`` should either write all of the encoded data or none of it; it+ must not do partial writes.+*``write_iter`` doesn't need to validate the encoded data; a subsequent read+ may return, e.g., ``-EIO`` if the data is not valid.+* The user may lie about the unencoded size of the data; a subsequent read+ should truncate or zero-extend the unencoded data rather than returning an+ error.+* Be careful of page cache coherency.
Haha that rings in my head like the "Smoking kills!" warnings...
I find it a bit odd that you mix page cache at all when reading
unencoded extents.
Feels like a file with FMODE_ENCODED_IO should stick to direct IO in all cases.
I don't know how btrfs deals with mixing direct IO and page cache IO normally,
but surely the rules could be made even stricter for an inode accessed with this
new API?
Is there something I am misunderstanding?
Thanks,
Amir.
I'm not completely following here, are you suggesting that if a file is
open with O_ALLOW_ENCODED, buffered I/O to that file should return an
error?
No. I don't.
quoted
Btrfs at least does the necessary range locking and page cache
invalidation to ensure that direct I/O gets along with buffered I/O (and
now encoded I/O).
That's a good start :-)
I saw btrfs_encoded_read_regular_fill_pages() and concluded that even
in FMODE_ENCODED_IO, when reading an unencoded extent, you fill
page cache with the unencoded data.
Is that correct? or did I miss read the code?
If correct, does it serve any purpose?
Seems more sensible to me to read/write FMODE_ENCODED_IO only in direct io
regardless if the extent is encoded or not (for simpler code if nothing else).
Thanks,
Amir.
Oh, I see. btrfs_encoded_read_regular_fill_pages() fills temporary pages
allocated for the read, not page cache pages. RWF_ENCODED always
bypasses the page cache, which I agree is the most sensible option.