Skip to contentSkip to conversation

btrfs: add fscrypt support

PATCH In review Daniel Vacek 4 participants 87 messages May 13 – Sep 22 1 message not in the archive

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v7 cover btrfs: add fscrypt support

Hello,

These are the remaining parts from former series [1] from Omar, Sweet Tea and Josef. Some bits of it were split into the separate set [2] before.

Notably, at this stage encryption is not supported with RAID5/6 setup and send is also disabled for now.

For straight git access you can find this series as the fscrypt-v7 tag e85358ef9fba here:

[0] https://github.com/dvacek/linux-btrfs/tree/fscrypt-v7

Changes since v6 [3]
* Rebased onto linux v7.1-rc3.
* Adapted to the v7.0 fscrypt API changes, mostly following commit bb8e2019ad613 ("blk-crypto: handle the fallback above the block layer")
* Addressed all the review feedback, thanks to Eric Biggers, Chris Mason
(and his LLM review prompts) and Neal Gompa.
* Adapted to the v7.1 fscrypt API cleanups, using byte offsets as function arguments instead of logical block numbers for newly introduced functions. This should match https://lore.kernel.org/linux-fscrypt/[email protected]/
As a result btrfs_set_bio_crypt_ctx_from_extent() and btrfs_mergeable_encrypted_bio() helpers were no longer needed and they got removed.

There are a few changes since v5 [1]:
* Rebased to btrfs/for-next branch. Couple things changed in the last years. A few patches were dropped as the code cleaned up or refactored. More details in the patches themselves.
* As suggested by Qu and Dave, the on-disk format of storing the extent encryption context was re-designed. Now, a new tree item with dedicated key is inserted instead of extending the file extent item. As a result a special care needs to be taken when removing the encrypted extents to also remove the related encryption context item.
* Fixed bugs found during testing.

Have a nice day,
Daniel

[1] v5 https://lore.kernel.org/linux-btrfs/[email protected]/
[2] https://lore.kernel.org/linux-btrfs/[email protected]/
[3] v6 https://lore.kernel.org/linux-btrfs/[email protected]/

Josef Bacik (33):
fscrypt: add per-extent encryption support
fscrypt: allow inline encryption for extent based encryption
fscrypt: add a __fscrypt_file_open helper
fscrypt: conditionally don't wipe mk secret until the last active user
is done
blk-crypto: add a process bio callback
fscrypt: add a process_bio hook to fscrypt_operations
fscrypt: add documentation about extent encryption
btrfs: add infrastructure for safe em freeing
btrfs: select encryption dependencies if FS_ENCRYPTION
btrfs: add fscrypt_info and encryption_type to ordered_extent
btrfs: plumb through setting the fscrypt_info for ordered extents
btrfs: populate the ordered_extent with the fscrypt context
btrfs: keep track of fscrypt info and orig_start for dio reads
btrfs: add extent encryption context tree item type
btrfs: pass through fscrypt_extent_info to the file extent helpers
btrfs: implement the fscrypt extent encryption hooks
btrfs: setup fscrypt_extent_info for new extents
btrfs: populate ordered_extent with the orig offset
btrfs: set the bio fscrypt context when applicable
btrfs: add a bio argument to btrfs_csum_one_bio
btrfs: limit encrypted writes to 256 segments
btrfs: implement process_bio cb for fscrypt
btrfs: implement read repair for encryption
btrfs: add test_dummy_encryption support
btrfs: make btrfs_ref_to_path handle encrypted filenames
btrfs: deal with encrypted symlinks in send
btrfs: decrypt file names for send
btrfs: load the inode context before sending writes
btrfs: set the appropriate free space settings in reconfigure
btrfs: support encryption with log replay
btrfs: disable auto defrag on encrypted files
btrfs: disable encryption on RAID5/6
btrfs: disable send if we have encryption enabled

Omar Sandoval (6):
fscrypt: expose fscrypt_nokey_name
btrfs: start using fscrypt hooks
btrfs: add inode encryption contexts
btrfs: add new FEATURE_INCOMPAT_ENCRYPT flag
btrfs: adapt readdir for encrypted and nokey names
btrfs: implement fscrypt ioctls

Sweet Tea Dorminy (4):
btrfs: handle nokey names
btrfs: add get_devices hook for fscrypt
btrfs: set file extent encryption excplicitly
btrfs: add fscrypt_info and encryption_type to extent_map

 Documentation/filesystems/fscrypt.rst |  41 +++
 block/blk-crypto-fallback.c           |  41 +++
 block/blk-crypto-internal.h           |   8 +
 block/blk-crypto-profile.c            |   2 +
 block/blk-crypto.c                    |   6 +-
 fs/btrfs/Kconfig                      |   4 +
 fs/btrfs/Makefile                     |   1 +
 fs/btrfs/accessors.h                  |   2 +
 fs/btrfs/backref.c                    |  43 ++-
 fs/btrfs/bio.c                        | 155 +++++++++-
 fs/btrfs/bio.h                        |  14 +-
 fs/btrfs/btrfs_inode.h                |   7 +-
 fs/btrfs/compression.c                |   6 +
 fs/btrfs/ctree.h                      |   3 +
 fs/btrfs/defrag.c                     |  14 +
 fs/btrfs/delayed-inode.c              |  25 +-
 fs/btrfs/delayed-inode.h              |   5 +-
 fs/btrfs/dir-item.c                   | 110 ++++++-
 fs/btrfs/dir-item.h                   |  10 +-
 fs/btrfs/direct-io.c                  |  28 +-
 fs/btrfs/disk-io.c                    |   3 +-
 fs/btrfs/extent_io.c                  | 115 ++++++-
 fs/btrfs/extent_io.h                  |   3 +
 fs/btrfs/extent_map.c                 | 102 ++++++-
 fs/btrfs/extent_map.h                 |  26 ++
 fs/btrfs/file-item.c                  |  28 +-
 fs/btrfs/file-item.h                  |   2 +-
 fs/btrfs/file.c                       |  79 +++++
 fs/btrfs/fs.h                         |   6 +-
 fs/btrfs/fscrypt.c                    | 413 ++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h                    |  86 ++++++
 fs/btrfs/inode.c                      | 404 +++++++++++++++++++------
 fs/btrfs/ioctl.c                      |  41 ++-
 fs/btrfs/ordered-data.c               |  35 ++-
 fs/btrfs/ordered-data.h               |  14 +
 fs/btrfs/reflink.c                    |  43 ++-
 fs/btrfs/root-tree.c                  |   9 +-
 fs/btrfs/root-tree.h                  |   2 +-
 fs/btrfs/send.c                       | 134 ++++++++-
 fs/btrfs/super.c                      |  99 +++++-
 fs/btrfs/super.h                      |   3 +-
 fs/btrfs/sysfs.c                      |   6 +
 fs/btrfs/tree-checker.c               |  64 +++-
 fs/btrfs/tree-log.c                   |  34 ++-
 fs/btrfs/volumes.c                    |   5 +
 fs/crypto/crypto.c                    |  10 +-
 fs/crypto/fname.c                     |  36 ---
 fs/crypto/fscrypt_private.h           |  51 +++-
 fs/crypto/hooks.c                     |  38 ++-
 fs/crypto/inline_crypt.c              |  91 +++++-
 fs/crypto/keyring.c                   |  18 +-
 fs/crypto/keysetup.c                  | 164 ++++++++++
 fs/crypto/policy.c                    |  47 +++
 include/linux/blk-crypto.h            |  15 +-
 include/linux/fscrypt.h               | 127 ++++++++
 include/uapi/linux/btrfs.h            |   1 +
 include/uapi/linux/btrfs_tree.h       |  26 +-
 57 files changed, 2665 insertions(+), 240 deletions(-)
 create mode 100644 fs/btrfs/fscrypt.c
 create mode 100644 fs/btrfs/fscrypt.h
Signature · 1 line
2.53.0
#1 lore raw

PATCH v7 1/43 fscrypt: add per-extent encryption support

From: Josef Bacik <[email protected]>

This adds the code necessary for per-extent encryption. We will store a nonce for every extent we create, and then use the inode's policy and the extents nonce to derive a per-extent key.

This is meant to be flexible, if we choose to expand the on-disk extent information in the future we have a version number we can use to change what exists on disk.

The file system indicates it wants to use per-extent encryption by setting s_cop->has_per_extent_encryption. This also requires the use of inline block encryption.

The support is relatively straightforward, the only "extra" bit is we're deriving a per-extent key to use for the encryption, the inode still controls the policy and access to the master key.

Since extent based encryption uses a lot of keys, we're requiring the use of inline block crypto if you use extent-based encryption. This enables us to take advantage of the built in pooling and reclamation of the crypto structures that underpin all of the encryption.

The different encryption related options for fscrypt are too numerous to support for extent based encryption. Support for a few of these options could possibly be added, but since they're niche options simply reject them for file systems using extent based encryption.

---

v7 changes:
* Code cleanup in setup_extent_info(), no functional changes.
* API cleanup passing a byte offset as an argument rather then logical
block number in new functions. This follows upstream v7.1 changes:
https://lore.kernel.org/linux-fscrypt/[email protected]/
* Make fscrypt_set_bio_crypt_ctx_from_extent() and fscrypt_mergeable_extent_bio()
handle unencrypted extents gracefully (ei == NULL). This way they can
be called unconditionally.
* Constify ctx argument of fscrypt_load_extent_info().
* Comment cleanups as suggested by Eric.
v6 changes:
* Fixed a merge collision with HW wrapped keydefinition.
* Adapt to fscrypt changes.
- Key derivation is void now instead of returning err.
- Crypt info structure was split from VFS inode
into FS specific inode structure.
v5: https://lore.kernel.org/linux-btrfs/37c2237bf485e44b0c813716f9506413026ce6dc.1706116485.git.josef@toxicpanda.com/

---
 fs/crypto/crypto.c          |  10 ++-
 fs/crypto/fscrypt_private.h |  42 +++++++++
 fs/crypto/inline_crypt.c    |  81 ++++++++++++++++++
 fs/crypto/keysetup.c        | 164 ++++++++++++++++++++++++++++++++++++
 fs/crypto/policy.c          |  47 +++++++++++
 include/linux/fscrypt.h     |  69 +++++++++++++++
 6 files changed, 412 insertions(+), 1 deletion(-)
fs/crypto/crypto.c +9 -1
index 570a2231c945..8ac9d3626b1d 100644
@@ -42,6 +42,7 @@ static struct workqueue_struct *fscrypt_read_workqueue;
 static DEFINE_MUTEX(fscrypt_init_mutex);
 
 struct kmem_cache *fscrypt_inode_info_cachep;
+struct kmem_cache *fscrypt_extent_info_cachep;
 
 void fscrypt_enqueue_decrypt_work(struct work_struct *work)
 {
@@ -402,12 +403,19 @@ static int __init fscrypt_init(void)
 	if (!fscrypt_inode_info_cachep)
 		goto fail_free_queue;
 
+	fscrypt_extent_info_cachep = KMEM_CACHE(fscrypt_extent_info,
+						SLAB_RECLAIM_ACCOUNT);
+	if (!fscrypt_extent_info_cachep)
+		goto fail_free_inode_info;
+
 	err = fscrypt_init_keyring();
 	if (err)
-		goto fail_free_inode_info;
+		goto fail_free_extent_info;
 
 	return 0;
 
+fail_free_extent_info:
+	kmem_cache_destroy(fscrypt_extent_info_cachep);
 fail_free_inode_info:
 	kmem_cache_destroy(fscrypt_inode_info_cachep);
 fail_free_queue:
fs/crypto/fscrypt_private.h +42 -0

72 lines not on this page · raw message

fs/crypto/inline_crypt.c +81 -0

93 lines not on this page · raw message

fs/crypto/keysetup.c +164 -0

167 lines not on this page · raw message

fs/crypto/policy.c +47 -0

65 lines not on this page · raw message

include/linux/fscrypt.h +69 -0

126 lines not on this page · raw message

Signature · 1 line
2.53.0
maintainer
#2 lore raw

Re: [PATCH v7 01/43] fscrypt: add per-extent encryption support

Quoted 14 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

This adds the code necessary for per-extent encryption. We will store a nonce for every extent we create, and then use the inode's policy and the extents nonce to derive a per-extent key.

This is meant to be flexible, if we choose to expand the on-disk extent information in the future we have a version number we can use to change what exists on disk.

The file system indicates it wants to use per-extent encryption by setting s_cop->has_per_extent_encryption. This also requires the use of inline block encryption.

Quoted 8 lines

The support is relatively straightforward, the only "extra" bit is we're deriving a per-extent key to use for the encryption, the inode still controls the policy and access to the master key.

Since extent based encryption uses a lot of keys, we're requiring the use of inline block crypto if you use extent-based encryption. This enables us to take advantage of the built in pooling and reclamation of the crypto structures that underpin all of the encryption.

The whole reason for extent-based encryption is that extents can be shared between inodes. So the repeated mentions of "the inode" are really confusing. This shows up in a lot of different places.

What's actually implemented is that each extent stores its own (encryption_mode, master_key_identifier, nonce), but for now the invariant is maintained that all inodes that reference an extent share the same (encryption_mode, master_key_identifier) as the extent.

It would be helpful to document this stuff accordingly.

Quoted 7 lines

+/*
+ * fscrypt_extent_context - the encryption context of an extent
+ *
+ * This is the on-disk information stored for an extent. The nonce is used as a
+ * KDF input in conjuction with the inode context to derive a per-extent key for
+ * encryption. This is used only when the filesystem uses per-extent encryption.
+ *

Basically the same issue here. The master_key_identifier is actually stored in the extent. Just the current implementation enforces that when the filesystem accesses the extent through some inode, that inode also has the same master_key_identifier. How about replacing the second sentence with something like: "The nonce and master_key_identifier are used to derive the key which encrypts the extent."

Quoted 5 lines

+ * With the current implementation, master_key_identifier and encryption mode
+ * must match the inode context. These are here for future expansion where we
+ * may want the option of mixing different keys and encryption modes for the
+ * same file.
+ */

Likewise. Something like: With the current implementation, master_key_identifier and encryption_mode always match the corresponding values from the fscrypt_context in each inode that shares the extent.

fs/crypto/fscrypt_private.h struct fscrypt_context_v2 { · line 111

Quoted 6 lines
fs/crypto/fscrypt_private.h +6 -0
+struct fscrypt_extent_context {
+	u8 version; /* FSCRYPT_EXTENT_CONTEXT_V1 */
+	u8 encryption_mode;
+	u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
+	u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
+};

Well, it's an extent nonce, not a file nonce. It seems it's handled completely separately from the existing file nonce, so it probably should get its own size constant FSCRYPT_EXTENT_NONCE_SIZE.

Quoted 6 lines

+/**
+ * fscrypt_set_bio_crypt_ctx_from_extent() - prepare a file contents bio for
+ * inline crypto with extent
+ * encryption
+ * @bio: a bio which will eventually be submitted to the file
+ * @ei: the extent's crypto info

@ei: the extent's crypto info, or NULL if the extent is unencrypted

Quoted 2 lines

+ * If the contents of the file should be encrypted (or decrypted) with inline
+ * encryption, then assign the appropriate encryption context to the bio.

"If the contents of the file should be encrypted (or decrypted) with inline encryption" => "If the extent should be encrypted (or decrypted)"

There's no "file" here. And inline encryption is the only option for extents.

Quoted 4 lines

+/**
+ * fscrypt_mergeable_extent_bio() - test whether data can be added to a bio
+ * @bio: the bio being built up
+ * @ei: the fscrypt_extent_info for this extent

@ei: the extent's crypto info, or NULL if the extent is unencrypted

Quoted 4 lines

+ * @pos: the next extent logical offset (in bytes) in the I/O
+ *
+ * When building a bio which may contain data which should undergo inline
+ * encryption (or decryption) via fscrypt,

When building a bio which may contain data which should undergo extent encryption (or decryption)

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 861

Quoted 11 lines
fs/crypto/keysetup.c +11 -0
+static struct fscrypt_extent_info *
+setup_extent_info(struct inode *inode, const u8 nonce[FSCRYPT_FILE_NONCE_SIZE])
+{
+	struct fscrypt_extent_info *ei;
+	struct fscrypt_inode_info *ci;
+	struct fscrypt_master_key *mk;
+	u8 derived_key[FSCRYPT_MAX_RAW_KEY_SIZE];
+	int keysize;
+	int err;
+
+	ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw()

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode)

Quoted 9 lines
fs/crypto/keysetup.c +9 -0
+/**
+ * fscrypt_prepare_new_extent() - prepare to create a new extent for a file
+ * @inode: the encrypted inode
+ *
+ * If the inode is encrypted, setup the fscrypt_extent_info for a new extent.
+
+ * This will include the nonce and the derived key necessary for the extent to
+ * be encrypted.  This is only meant to be used with inline crypto and on inodes
+ * that need their contents encrypted.

This is ambiguous and contradictory about what type of @inode is required. It should be something like:

* @inode: an encrypted regular file with its key already set up, on a
* filesystem that uses per-extent encryption
*
* Prepare to encrypt a new extent by generating a new extent nonce,
* deriving an extent key, and allocating an fscrypt_extent_info.

Quoted 2 lines

* This doesn't persist the new extents encryption context, this is done later
* by calling fscrypt_set_extent_context().

There's no function with that name

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 918

Quoted 4 lines
fs/crypto/keysetup.c +4 -0
+	if (WARN_ON_ONCE(!*fscrypt_inode_info_addr(inode)))
+		return ERR_PTR(-EOPNOTSUPP);
+	if (WARN_ON_ONCE(!fscrypt_inode_uses_inline_crypto(inode)))
+		return ERR_PTR(-EOPNOTSUPP);

I'm confused what these checks are trying to do. The first part checks for the inode's encryption key, but setup_extent_info() does that anyway. The second part is maybe intended to check that the file uses extent encryption, but it doesn't do it correctly. That would require:
fscrypt_needs_contents_encryption(inode) && inode->i_sb->s_cop->has_per_extent_encryption.

It probably would make sense to check that directly in setup_extent_info(), so that it's closer to the call to fscrypt_hkdf_expand() which would has a *very* bad failure mode when !has_per_extent_encryption.

Quoted 4 lines

+/**
+ * fscrypt_load_extent_info() - create an fscrypt_extent_info from the context
+ * @inode: the inode
+ * @ctx: the context buffer

Quoted 8 lines

+ * @ctx_size: the size of the context buffer
+ *
+ * Create the fscrypt_extent_info and derive the key based on the
+ * fscrypt_extent_context buffer that is provided.
+ *
+ * Return: The newly allocated fscrypt_extent_info on success, -EOPNOTSUPP if
+ * we're not encrypted, or another -errno code
+ */

What context is this expected to be called in? I see the caller uses memalloc_nofs_save(). This would require making ->mk_sem nofs-safe; is there a plan to do that? (Sashiko noticed this too, by the way.)

Review

Quoted 1 line
(quoted diff) +1 -0
+	const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

Quoted 2 lines

+/**
+ * fscrypt_set_extent_context() - Set the fscrypt extent context of a new extent

It seems the function name and semantics changed at some point, but the kerneldoc wasn't updated.

Quoted 1 line

+ * @inode: the inode this extent belongs to

The inode that the extent will initially belong to, I guess?

fs/crypto/policy.c int fscrypt_set_context(struct inode *inode, void *fs_data) · line 824

Quoted 5 lines
fs/crypto/policy.c +5 -0
+ssize_t fscrypt_context_for_new_extent(struct inode *inode,
+				       struct fscrypt_extent_info *ei, u8 *buf)
+{
+	struct fscrypt_extent_context *ctx = (struct fscrypt_extent_context *)buf;
+	const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

- Eric

#3 lore raw

Re: [PATCH v7 01/43] fscrypt: add per-extent encryption support

Quoted 28 lines · Eric Biggers
Quoted 14 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

This adds the code necessary for per-extent encryption. We will store a nonce for every extent we create, and then use the inode's policy and the extents nonce to derive a per-extent key.

This is meant to be flexible, if we choose to expand the on-disk extent information in the future we have a version number we can use to change what exists on disk.

The file system indicates it wants to use per-extent encryption by setting s_cop->has_per_extent_encryption. This also requires the use of inline block encryption.

Quoted 8 lines

The support is relatively straightforward, the only "extra" bit is we're deriving a per-extent key to use for the encryption, the inode still controls the policy and access to the master key.

Since extent based encryption uses a lot of keys, we're requiring the use of inline block crypto if you use extent-based encryption. This enables us to take advantage of the built in pooling and reclamation of the crypto structures that underpin all of the encryption.

The whole reason for extent-based encryption is that extents can be shared between inodes. So the repeated mentions of "the inode" are really confusing. This shows up in a lot of different places.

Quoted 6 lines

What's actually implemented is that each extent stores its own (encryption_mode, master_key_identifier, nonce), but for now the invariant is maintained that all inodes that reference an extent share the same (encryption_mode, master_key_identifier) as the extent.

It would be helpful to document this stuff accordingly.

Yeah, that makes sense. I believe this is what we want - any file is unlocked by one key. Not that you would need multiple keys for unlocking different parts of a file.

Quoted 8 lines
Quoted 7 lines

+/*
+ * fscrypt_extent_context - the encryption context of an extent
+ *
+ * This is the on-disk information stored for an extent. The nonce is used as a
+ * KDF input in conjuction with the inode context to derive a per-extent key for
+ * encryption. This is used only when the filesystem uses per-extent encryption.
+ *

Quoted 6 lines

Basically the same issue here. The master_key_identifier is actually stored in the extent. Just the current implementation enforces that when the filesystem accesses the extent through some inode, that inode also has the same master_key_identifier. How about replacing the second sentence with something like: "The nonce and master_key_identifier are used to derive the key which encrypts the extent."

Right, this sounds better.

Quoted 9 lines
Quoted 5 lines

+ * With the current implementation, master_key_identifier and encryption mode
+ * must match the inode context. These are here for future expansion where we
+ * may want the option of mixing different keys and encryption modes for the
+ * same file.
+ */

Likewise. Something like: With the current implementation, master_key_identifier and encryption_mode always match the corresponding values from the fscrypt_context in each inode that shares the extent.

Do we actually want this freedom or should we drop the encryption_mode and master_key_identifier and consider them implicit from inode/fscrypt_context?
That would mean storing only the nonce in the extent context. The version field still remains, preserving the flexibility to eventually add them back later if we decide to.

Quoted 10 lines

fs/crypto/fscrypt_private.h struct fscrypt_context_v2 { · line 111

Quoted 6 lines
fs/crypto/fscrypt_private.h +6 -0
+struct fscrypt_extent_context {
+     u8 version; /* FSCRYPT_EXTENT_CONTEXT_V1 */
+     u8 encryption_mode;
+     u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
+     u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
+};

Well, it's an extent nonce, not a file nonce. It seems it's handled completely separately from the existing file nonce, so it probably should get its own size constant FSCRYPT_EXTENT_NONCE_SIZE.

This actually sounds more confusing to me. They are both the same thing. My understanding was that extent is "kind of file" on it's own. If anything I'd argue for FSCRYPT_NONCE_SIZE used in both places. But a FSCRYPT_FILE_NONCE_SIZE used in inode context as well as in extent context sounds fine to me.

Quoted 8 lines
Quoted 6 lines

+/**
+ * fscrypt_set_bio_crypt_ctx_from_extent() - prepare a file contents bio for
+ * inline crypto with extent
+ * encryption
+ * @bio: a bio which will eventually be submitted to the file
+ * @ei: the extent's crypto info

@ei: the extent's crypto info, or NULL if the extent is unencrypted

True, the @ei is optional. I'll fix that.

Quoted 8 lines
Quoted 2 lines

+ * If the contents of the file should be encrypted (or decrypted) with inline
+ * encryption, then assign the appropriate encryption context to the bio.

"If the contents of the file should be encrypted (or decrypted) with inline encryption" => "If the extent should be encrypted (or decrypted)"

There's no "file" here. And inline encryption is the only option for extents.

OK.

Quoted 6 lines
Quoted 4 lines

+/**
+ * fscrypt_mergeable_extent_bio() - test whether data can be added to a bio
+ * @bio: the bio being built up
+ * @ei: the fscrypt_extent_info for this extent

@ei: the extent's crypto info, or NULL if the extent is unencrypted

True.

Quoted 7 lines
Quoted 4 lines

+ * @pos: the next extent logical offset (in bytes) in the I/O
+ *
+ * When building a bio which may contain data which should undergo inline
+ * encryption (or decryption) via fscrypt,

When building a bio which may contain data which should undergo extent encryption (or decryption)

Ack.

Quoted 5 lines
Quoted 5 lines
fs/crypto/keysetup.c +5 -0
+static struct fscrypt_extent_info *
+setup_extent_info(struct inode *inode, const u8 nonce[FSCRYPT_FILE_NONCE_SIZE])
+{
+     struct fscrypt_extent_info *ei;
+     struct fscrypt_inode_info *ci;
Quoted 8 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 861

Quoted 6 lines
fs/crypto/keysetup.c +6 -0
+     struct fscrypt_master_key *mk;
+     u8 derived_key[FSCRYPT_MAX_RAW_KEY_SIZE];
+     int keysize;
+     int err;
+
+     ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw()

That would add a useless VFS_WARN_ON_ONCE() which will never trigger; otherwise, the next line would crash.
But I guess that's OK.

Quoted 13 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode)

Quoted 9 lines
fs/crypto/keysetup.c +9 -0
+/**
+ * fscrypt_prepare_new_extent() - prepare to create a new extent for a file
+ * @inode: the encrypted inode
+ *
+ * If the inode is encrypted, setup the fscrypt_extent_info for a new extent.
+
+ * This will include the nonce and the derived key necessary for the extent to
+ * be encrypted.  This is only meant to be used with inline crypto and on inodes
+ * that need their contents encrypted.

This is ambiguous and contradictory about what type of @inode is required. It should be something like:

Quoted 5 lines

* @inode: an encrypted regular file with its key already set up, on a
* filesystem that uses per-extent encryption
*
* Prepare to encrypt a new extent by generating a new extent nonce,
* deriving an extent key, and allocating an fscrypt_extent_info.

OK.

Quoted 4 lines
Quoted 2 lines

* This doesn't persist the new extents encryption context, this is done later
* by calling fscrypt_set_extent_context().

There's no function with that name

That should be fscrypt_context_for_new_extent(). I see it was renamed in v5 but this one (and the one below) was forgotten.
Will fix.

Quoted 8 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 918

Quoted 4 lines
fs/crypto/keysetup.c +4 -0
+     if (WARN_ON_ONCE(!*fscrypt_inode_info_addr(inode)))
+             return ERR_PTR(-EOPNOTSUPP);
+     if (WARN_ON_ONCE(!fscrypt_inode_uses_inline_crypto(inode)))
+             return ERR_PTR(-EOPNOTSUPP);

I'm confused what these checks are trying to do. The first part checks for the inode's encryption key, but setup_extent_info() does that anyway.

setup_extent_info() dereferences ci right away. Without this check it would crash if the inode was not encrypted.

Quoted 4 lines

... The second part is maybe intended to check that the file uses extent encryption, but it doesn't do it correctly. That would require:
fscrypt_needs_contents_encryption(inode) && inode->i_sb->s_cop->has_per_extent_encryption.

This may be better. The comment says this is only meant to be used with inline crypto but that actually looks fishy. We ensure this in btrfs but fscrypt itself does not need to.

Quoted 4 lines

It probably would make sense to check that directly in setup_extent_info(), so that it's closer to the call to fscrypt_hkdf_expand() which would has a *very* bad failure mode when !has_per_extent_encryption.

I think it makes sense to check before consuming entropy. setup_extent_info() can have a second check if needed, though perhaps it was not needed so far?

Quoted 13 lines
Quoted 4 lines

+/**
+ * fscrypt_load_extent_info() - create an fscrypt_extent_info from the context
+ * @inode: the inode
+ * @ctx: the context buffer

Quoted 8 lines

+ * @ctx_size: the size of the context buffer
+ *
+ * Create the fscrypt_extent_info and derive the key based on the
+ * fscrypt_extent_context buffer that is provided.
+ *
+ * Return: The newly allocated fscrypt_extent_info on success, -EOPNOTSUPP if
+ * we're not encrypted, or another -errno code
+ */

Quoted 3 lines

What context is this expected to be called in? I see the caller uses memalloc_nofs_save(). This would require making ->mk_sem nofs-safe; is there a plan to do that? (Sashiko noticed this too, by the way.)

Honestly, I have to admit I was puzzled by Sashiko's explanation and I did not trust it. It sounded rather off.

Trying to dig up the origin of that memalloc_nofs_save() - it is there since the very beginning of Josef's [v1] posting. This was around the time of Linux v6.6 but the code is still similar.
So far I don't see if it is really needed or why it was implemented this way in the first place. It is called from btrfs_do_readpage()->btrfs_get_extent() to set up the key context. IIUC, this should not be called from a reclaim path. Hence, I think that that memalloc_nofs_save() is redundant and it should be OK to simply remove it.

[v1] https://lore.kernel.org/linux-btrfs/de7dec18d4dd440ebf3c538af5c765d747e1d3ef.1695750478.git.josef@toxicpanda.com/

Quoted 3 lines
Quoted 1 line

+ const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

OK.

Quoted 5 lines
Quoted 2 lines

+/**
+ * fscrypt_set_extent_context() - Set the fscrypt extent context of a new extent

It seems the function name and semantics changed at some point, but the kerneldoc wasn't updated.

As mentioned above, I see V4 -> v5 rename. No semantics changes.

Quoted 3 lines
Quoted 1 line

+ * @inode: the inode this extent belongs to

The inode that the extent will initially belong to, I guess?

Yes, at this point it's a new extent for this inode.

Quoted 7 lines

fs/crypto/policy.c int fscrypt_set_context(struct inode *inode, void *fs_data) · line 824

Quoted 5 lines
fs/crypto/policy.c +5 -0
+ssize_t fscrypt_context_for_new_extent(struct inode *inode,
+                                    struct fscrypt_extent_info *ei, u8 *buf)
+{
+     struct fscrypt_extent_context *ctx = (struct fscrypt_extent_context *)buf;
+     const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

Again, adds an useless WARN_ON_ONCE, but won't hurt.

Thanks!

--nX

Quoted 1 line

- Eric

#4 lore raw

Re: [PATCH v7 01/43] fscrypt: add per-extent encryption support

Quoted 230 lines · Daniel Vacek
Quoted 28 lines · Eric Biggers
Quoted 14 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

This adds the code necessary for per-extent encryption. We will store a nonce for every extent we create, and then use the inode's policy and the extents nonce to derive a per-extent key.

This is meant to be flexible, if we choose to expand the on-disk extent information in the future we have a version number we can use to change what exists on disk.

The file system indicates it wants to use per-extent encryption by setting s_cop->has_per_extent_encryption. This also requires the use of inline block encryption.

Quoted 8 lines

The support is relatively straightforward, the only "extra" bit is we're deriving a per-extent key to use for the encryption, the inode still controls the policy and access to the master key.

Since extent based encryption uses a lot of keys, we're requiring the use of inline block crypto if you use extent-based encryption. This enables us to take advantage of the built in pooling and reclamation of the crypto structures that underpin all of the encryption.

The whole reason for extent-based encryption is that extents can be shared between inodes. So the repeated mentions of "the inode" are really confusing. This shows up in a lot of different places.

Quoted 6 lines

What's actually implemented is that each extent stores its own (encryption_mode, master_key_identifier, nonce), but for now the invariant is maintained that all inodes that reference an extent share the same (encryption_mode, master_key_identifier) as the extent.

It would be helpful to document this stuff accordingly.

Yeah, that makes sense. I believe this is what we want - any file is unlocked by one key. Not that you would need multiple keys for unlocking different parts of a file.

Quoted 8 lines
Quoted 7 lines

+/*
+ * fscrypt_extent_context - the encryption context of an extent
+ *
+ * This is the on-disk information stored for an extent. The nonce is used as a
+ * KDF input in conjuction with the inode context to derive a per-extent key for
+ * encryption. This is used only when the filesystem uses per-extent encryption.
+ *

Quoted 6 lines

Basically the same issue here. The master_key_identifier is actually stored in the extent. Just the current implementation enforces that when the filesystem accesses the extent through some inode, that inode also has the same master_key_identifier. How about replacing the second sentence with something like: "The nonce and master_key_identifier are used to derive the key which encrypts the extent."

Right, this sounds better.

Quoted 9 lines
Quoted 5 lines

+ * With the current implementation, master_key_identifier and encryption mode
+ * must match the inode context. These are here for future expansion where we
+ * may want the option of mixing different keys and encryption modes for the
+ * same file.
+ */

Likewise. Something like: With the current implementation, master_key_identifier and encryption_mode always match the corresponding values from the fscrypt_context in each inode that shares the extent.

Do we actually want this freedom or should we drop the encryption_mode and master_key_identifier and consider them implicit from inode/fscrypt_context?
That would mean storing only the nonce in the extent context. The version field still remains, preserving the flexibility to eventually add them back later if we decide to.

Quoted 10 lines

fs/crypto/fscrypt_private.h struct fscrypt_context_v2 { · line 111

Quoted 6 lines
fs/crypto/fscrypt_private.h +6 -0
+struct fscrypt_extent_context {
+     u8 version; /* FSCRYPT_EXTENT_CONTEXT_V1 */
+     u8 encryption_mode;
+     u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
+     u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
+};

Well, it's an extent nonce, not a file nonce. It seems it's handled completely separately from the existing file nonce, so it probably should get its own size constant FSCRYPT_EXTENT_NONCE_SIZE.

This actually sounds more confusing to me. They are both the same thing. My understanding was that extent is "kind of file" on it's own. If anything I'd argue for FSCRYPT_NONCE_SIZE used in both places. But a FSCRYPT_FILE_NONCE_SIZE used in inode context as well as in extent context sounds fine to me.

Quoted 8 lines
Quoted 6 lines

+/**
+ * fscrypt_set_bio_crypt_ctx_from_extent() - prepare a file contents bio for
+ * inline crypto with extent
+ * encryption
+ * @bio: a bio which will eventually be submitted to the file
+ * @ei: the extent's crypto info

@ei: the extent's crypto info, or NULL if the extent is unencrypted

True, the @ei is optional. I'll fix that.

Quoted 8 lines
Quoted 2 lines

+ * If the contents of the file should be encrypted (or decrypted) with inline
+ * encryption, then assign the appropriate encryption context to the bio.

"If the contents of the file should be encrypted (or decrypted) with inline encryption" => "If the extent should be encrypted (or decrypted)"

There's no "file" here. And inline encryption is the only option for extents.

OK.

Quoted 6 lines
Quoted 4 lines

+/**
+ * fscrypt_mergeable_extent_bio() - test whether data can be added to a bio
+ * @bio: the bio being built up
+ * @ei: the fscrypt_extent_info for this extent

@ei: the extent's crypto info, or NULL if the extent is unencrypted

True.

Quoted 7 lines
Quoted 4 lines

+ * @pos: the next extent logical offset (in bytes) in the I/O
+ *
+ * When building a bio which may contain data which should undergo inline
+ * encryption (or decryption) via fscrypt,

When building a bio which may contain data which should undergo extent encryption (or decryption)

Ack.

Quoted 5 lines
Quoted 5 lines
fs/crypto/keysetup.c +5 -0
+static struct fscrypt_extent_info *
+setup_extent_info(struct inode *inode, const u8 nonce[FSCRYPT_FILE_NONCE_SIZE])
+{
+     struct fscrypt_extent_info *ei;
+     struct fscrypt_inode_info *ci;
Quoted 8 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 861

Quoted 6 lines
fs/crypto/keysetup.c +6 -0
+     struct fscrypt_master_key *mk;
+     u8 derived_key[FSCRYPT_MAX_RAW_KEY_SIZE];
+     int keysize;
+     int err;
+
+     ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw()

That would add a useless VFS_WARN_ON_ONCE() which will never trigger; otherwise, the next line would crash.
But I guess that's OK.

Quoted 13 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode)

Quoted 9 lines
fs/crypto/keysetup.c +9 -0
+/**
+ * fscrypt_prepare_new_extent() - prepare to create a new extent for a file
+ * @inode: the encrypted inode
+ *
+ * If the inode is encrypted, setup the fscrypt_extent_info for a new extent.
+
+ * This will include the nonce and the derived key necessary for the extent to
+ * be encrypted.  This is only meant to be used with inline crypto and on inodes
+ * that need their contents encrypted.

This is ambiguous and contradictory about what type of @inode is required. It should be something like:

Quoted 5 lines

* @inode: an encrypted regular file with its key already set up, on a
* filesystem that uses per-extent encryption
*
* Prepare to encrypt a new extent by generating a new extent nonce,
* deriving an extent key, and allocating an fscrypt_extent_info.

OK.

Quoted 4 lines
Quoted 2 lines

* This doesn't persist the new extents encryption context, this is done later
* by calling fscrypt_set_extent_context().

There's no function with that name

That should be fscrypt_context_for_new_extent(). I see it was renamed in v5 but this one (and the one below) was forgotten.
Will fix.

Quoted 8 lines

fs/crypto/keysetup.c int fscrypt_drop_inode(struct inode *inode) · line 918

Quoted 4 lines
fs/crypto/keysetup.c +4 -0
+     if (WARN_ON_ONCE(!*fscrypt_inode_info_addr(inode)))
+             return ERR_PTR(-EOPNOTSUPP);
+     if (WARN_ON_ONCE(!fscrypt_inode_uses_inline_crypto(inode)))
+             return ERR_PTR(-EOPNOTSUPP);

I'm confused what these checks are trying to do. The first part checks for the inode's encryption key, but setup_extent_info() does that anyway.

setup_extent_info() dereferences ci right away. Without this check it would crash if the inode was not encrypted.

Quoted 4 lines

... The second part is maybe intended to check that the file uses extent encryption, but it doesn't do it correctly. That would require:
fscrypt_needs_contents_encryption(inode) && inode->i_sb->s_cop->has_per_extent_encryption.

This may be better. The comment says this is only meant to be used with inline crypto but that actually looks fishy. We ensure this in btrfs but fscrypt itself does not need to.

Quoted 4 lines

It probably would make sense to check that directly in setup_extent_info(), so that it's closer to the call to fscrypt_hkdf_expand() which would has a *very* bad failure mode when !has_per_extent_encryption.

I think it makes sense to check before consuming entropy. setup_extent_info() can have a second check if needed, though perhaps it was not needed so far?

Quoted 13 lines
Quoted 4 lines

+/**
+ * fscrypt_load_extent_info() - create an fscrypt_extent_info from the context
+ * @inode: the inode
+ * @ctx: the context buffer

Quoted 8 lines

+ * @ctx_size: the size of the context buffer
+ *
+ * Create the fscrypt_extent_info and derive the key based on the
+ * fscrypt_extent_context buffer that is provided.
+ *
+ * Return: The newly allocated fscrypt_extent_info on success, -EOPNOTSUPP if
+ * we're not encrypted, or another -errno code
+ */

Quoted 3 lines

What context is this expected to be called in? I see the caller uses memalloc_nofs_save(). This would require making ->mk_sem nofs-safe; is there a plan to do that? (Sashiko noticed this too, by the way.)

Honestly, I have to admit I was puzzled by Sashiko's explanation and I did not trust it. It sounded rather off.

Quoted 9 lines

Trying to dig up the origin of that memalloc_nofs_save() - it is there since the very beginning of Josef's [v1] posting. This was around the time of Linux v6.6 but the code is still similar.
So far I don't see if it is really needed or why it was implemented this way in the first place. It is called from btrfs_do_readpage()->btrfs_get_extent() to set up the key context. IIUC, this should not be called from a reclaim path. Hence, I think that that memalloc_nofs_save() is redundant and it should be OK to simply remove it.

And removing it and testing with stress-ng induced memory pressure seems to confirm the memalloc_nofs_save() is not needed in this code path.

@Josef: By any chance, do you recall why this was originally put in?

--nX

Quoted 37 lines

[v1] https://lore.kernel.org/linux-btrfs/de7dec18d4dd440ebf3c538af5c765d747e1d3ef.1695750478.git.josef@toxicpanda.com/

Quoted 3 lines
Quoted 1 line

+ const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

OK.

Quoted 5 lines
Quoted 2 lines

+/**
+ * fscrypt_set_extent_context() - Set the fscrypt extent context of a new extent

It seems the function name and semantics changed at some point, but the kerneldoc wasn't updated.

As mentioned above, I see V4 -> v5 rename. No semantics changes.

Quoted 3 lines
Quoted 1 line

+ * @inode: the inode this extent belongs to

The inode that the extent will initially belong to, I guess?

Yes, at this point it's a new extent for this inode.

Quoted 7 lines

fs/crypto/policy.c int fscrypt_set_context(struct inode *inode, void *fs_data) · line 824

Quoted 5 lines
fs/crypto/policy.c +5 -0
+ssize_t fscrypt_context_for_new_extent(struct inode *inode,
+                                    struct fscrypt_extent_info *ei, u8 *buf)
+{
+     struct fscrypt_extent_context *ctx = (struct fscrypt_extent_context *)buf;
+     const struct fscrypt_inode_info *ci = *fscrypt_inode_info_addr(inode);

fscrypt_get_inode_info_raw(inode)

Again, adds an useless WARN_ON_ONCE, but won't hurt.

Thanks!

--nX

Quoted 1 line

- Eric

#5 lore raw

PATCH v7 2/43 fscrypt: allow inline encryption for extent based encryption

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Instead of requiring -o inlinecrypt to enable inline encryption, allow having s_cop->has_per_extent_encryption to indicate that this file system supports inline encryption.

---

v5: https://lore.kernel.org/linux-btrfs/ba0289bf103653d5d98ef576756c9a2a66192865.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/crypto/inline_crypt.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
fs/crypto/inline_crypt.c +5 -2
index 1bf8621093ed..31791fb98a9e 100644
@@ -108,8 +108,11 @@ int fscrypt_select_encryption_impl(struct fscrypt_inode_info *ci,
 	if (ci->ci_mode->blk_crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
 		return 0;
 
-	/* The filesystem must be mounted with -o inlinecrypt */
-	if (!(sb->s_flags & SB_INLINECRYPT))
+	/*
+	 * The filesystem must be mounted with -o inlinecrypt or have
+	 * has_per_extent_encryption enabled.
+	 */
+	if (!(sb->s_flags & SB_INLINECRYPT) && !sb->s_cop->has_per_extent_encryption)
 		return 0;
 
 	/*
Signature · 1 line
2.53.0
maintainer
#6 lore raw

Re: [PATCH v7 02/43] fscrypt: allow inline encryption for extent based encryption

Quoted 6 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Instead of requiring -o inlinecrypt to enable inline encryption, allow having s_cop->has_per_extent_encryption to indicate that this file system supports inline encryption.

Quoted 6 lines

---

v5: https://lore.kernel.org/linux-btrfs/ba0289bf103653d5d98ef576756c9a2a66192865.1706116485.git.josef@toxicpanda.com/
* No changes since.

There are multiple places that check SB_INLINECRYPT, and just one was updated. Perhaps we should just require that if a filesystem sets has_per_extent_encryption, then it also sets SB_INLINECRYPT unconditionally?

- Eric

#7 lore raw

Re: [PATCH v7 02/43] fscrypt: allow inline encryption for extent based encryption

Quoted 11 lines · Eric Biggers
Quoted 10 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Instead of requiring -o inlinecrypt to enable inline encryption, allow having s_cop->has_per_extent_encryption to indicate that this file system supports inline encryption.

---

Quoted 7 lines
Quoted 2 lines

v5: https://lore.kernel.org/linux-btrfs/ba0289bf103653d5d98ef576756c9a2a66192865.1706116485.git.josef@toxicpanda.com/
* No changes since.

There are multiple places that check SB_INLINECRYPT, and just one was updated. Perhaps we should just require that if a filesystem sets has_per_extent_encryption, then it also sets SB_INLINECRYPT unconditionally?

has_per_extent_encryption means the kernel fs implementation supports extent encryption, not that the mounted filesystem uses encryption. That said it would result in all btrfs mounts setting SB_INLINECRYPT. Is that what you meant?

--nX

Quoted 1 line

- Eric

#8 lore raw

PATCH v7 3/43 fscrypt: add a __fscrypt_file_open helper

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We have fscrypt_file_open() which is meant to be called on files being opened so that their key is loaded when we start reading data from them.

However for btrfs send we are opening the inode directly without a filp, so we need a different helper to make sure we can load the fscrypt context for the inode before reading its contents.

---

No changes in v7.
v6 changes:
* Adapted to fscrypt changes since the last two years.
v5: https://lore.kernel.org/linux-btrfs/4a372419c3fe6ad425e1b124c342a054e9d6db23.1706116485.git.josef@toxicpanda.com/

---
 fs/crypto/hooks.c       | 38 ++++++++++++++++++++++++++++++++------
 include/linux/fscrypt.h |  8 ++++++++
 2 files changed, 40 insertions(+), 6 deletions(-)
fs/crypto/hooks.c +32 -6
index a7a8a3f581a0..3142cf106bde 100644
@@ -9,6 +9,37 @@
 
 #include "fscrypt_private.h"
 
+/**
+ * __fscrypt_file_open() - prepare for filesystem-internal access to a
+ *			   possibly-encrypted regular file
+ * @dir: the inode for the directory via which the file is being accessed
+ * @inode: the inode being "opened"
+ *
+ * This is like fscrypt_file_open(), but instead of taking the 'struct file'
+ * being opened it takes the parent directory explicitly.  This is intended for
+ * use cases such as "send/receive" which involve the filesystem accessing file
+ * contents without setting up a 'struct file'.
+ *
+ * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
+ */
+int __fscrypt_file_open(struct inode *dir, struct inode *inode)
+{
+	int err;
+
+	err = fscrypt_require_key(inode);
+	if (err)
+		return err;
+
+	if (!fscrypt_has_permitted_context(dir, inode)) {
+		fscrypt_warn(inode,
+			     "Inconsistent encryption context (parent directory: %llu)",
+			     dir->i_ino);
+		return -EPERM;
+	}
+	return 0;
+}
+EXPORT_SYMBOL_GPL(__fscrypt_file_open);
+
 /**
  * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
  * @inode: the inode being opened
@@ -60,12 +91,7 @@ int fscrypt_file_open(struct inode *inode, struct file *filp)
 	rcu_read_unlock();
 
 	dentry_parent = dget_parent(dentry);
-	if (!fscrypt_has_permitted_context(d_inode(dentry_parent), inode)) {
-		fscrypt_warn(inode,
-			     "Inconsistent encryption context (parent directory: %llu)",
-			     d_inode(dentry_parent)->i_ino);
-		err = -EPERM;
-	}
+	err = __fscrypt_file_open(d_inode(dentry_parent), inode);
 	dput(dentry_parent);
 	return err;
 }
include/linux/fscrypt.h +8 -0
index f216f1a78069..dda5b1d32f78 100644
@@ -471,6 +471,7 @@ int fscrypt_zeroout_range(const struct inode *inode, loff_t pos,
 
 /* hooks.c */
 int fscrypt_file_open(struct inode *inode, struct file *filp);
+int __fscrypt_file_open(struct inode *dir, struct inode *inode);
 int __fscrypt_prepare_link(struct inode *inode, struct inode *dir,
 			   struct dentry *dentry);
 int __fscrypt_prepare_rename(struct inode *old_dir, struct dentry *old_dentry,
@@ -818,6 +819,13 @@ static inline int fscrypt_file_open(struct inode *inode, struct file *filp)
 	return 0;
 }
 
+static inline int __fscrypt_file_open(struct inode *dir, struct inode *inode)
+{
+	if (IS_ENCRYPTED(inode))
+		return -EOPNOTSUPP;
+	return 0;
+}
+
 static inline int __fscrypt_prepare_link(struct inode *inode, struct inode *dir,
 					 struct dentry *dentry)
 {
Signature · 1 line
2.53.0
maintainer
#9 lore raw

Re: [PATCH v7 03/43] fscrypt: add a __fscrypt_file_open helper

Quoted 68 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

We have fscrypt_file_open() which is meant to be called on files being opened so that their key is loaded when we start reading data from them.

However for btrfs send we are opening the inode directly without a filp, so we need a different helper to make sure we can load the fscrypt context for the inode before reading its contents.

---

No changes in v7.
v6 changes:
* Adapted to fscrypt changes since the last two years.
v5: https://lore.kernel.org/linux-btrfs/4a372419c3fe6ad425e1b124c342a054e9d6db23.1706116485.git.josef@toxicpanda.com/

---
 fs/crypto/hooks.c       | 38 ++++++++++++++++++++++++++++++++------
 include/linux/fscrypt.h |  8 ++++++++
 2 files changed, 40 insertions(+), 6 deletions(-)
fs/crypto/hooks.c +31 -0
index a7a8a3f581a0..3142cf106bde 100644
@@ -9,6 +9,37 @@
 
 #include "fscrypt_private.h"
 
+/**
+ * __fscrypt_file_open() - prepare for filesystem-internal access to a
+ *			   possibly-encrypted regular file
+ * @dir: the inode for the directory via which the file is being accessed
+ * @inode: the inode being "opened"
+ *
+ * This is like fscrypt_file_open(), but instead of taking the 'struct file'
+ * being opened it takes the parent directory explicitly.  This is intended for
+ * use cases such as "send/receive" which involve the filesystem accessing file
+ * contents without setting up a 'struct file'.
+ *
+ * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
+ */
+int __fscrypt_file_open(struct inode *dir, struct inode *inode)
+{
+	int err;
+
+	err = fscrypt_require_key(inode);
+	if (err)
+		return err;
+
+	if (!fscrypt_has_permitted_context(dir, inode)) {
+		fscrypt_warn(inode,
+			     "Inconsistent encryption context (parent directory: %llu)",
+			     dir->i_ino);
+		return -EPERM;
+	}
+	return 0;
+}
+EXPORT_SYMBOL_GPL(__fscrypt_file_open);
+
 /**
  * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
  * @inode: the inode being opened
@@ -60,12 +91,7 @@ int fscrypt_file_open(struct inode *inode, struct file *filp)
 	rcu_read_unlock();
 
 	dentry_parent = dget_parent(dentry);

fs/crypto/hooks.c int fscrypt_file_open(struct inode *inode, struct file *filp) · line 97

Quoted 10 lines
fs/crypto/hooks.c +1 -6
-	if (!fscrypt_has_permitted_context(d_inode(dentry_parent), inode)) {
-		fscrypt_warn(inode,
-			     "Inconsistent encryption context (parent directory: %llu)",
-			     d_inode(dentry_parent)->i_ino);
-		err = -EPERM;
-	}
+	err = __fscrypt_file_open(d_inode(dentry_parent), inode);
 	dput(dentry_parent);
 	return err;
 }

This change makes fscrypt_file_open() execute an unnecessary extra fscrypt_require_key(). Could we just leave fscrypt_file_open() as-is?

- Eric

#10 lore raw

Re: [PATCH v7 03/43] fscrypt: add a __fscrypt_file_open helper

Quoted 68 lines · Eric Biggers
Quoted 67 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

We have fscrypt_file_open() which is meant to be called on files being opened so that their key is loaded when we start reading data from them.

However for btrfs send we are opening the inode directly without a filp, so we need a different helper to make sure we can load the fscrypt context for the inode before reading its contents.

---

No changes in v7.
v6 changes:
* Adapted to fscrypt changes since the last two years.
v5: https://lore.kernel.org/linux-btrfs/4a372419c3fe6ad425e1b124c342a054e9d6db23.1706116485.git.josef@toxicpanda.com/

---
 fs/crypto/hooks.c       | 38 ++++++++++++++++++++++++++++++++------
 include/linux/fscrypt.h |  8 ++++++++
 2 files changed, 40 insertions(+), 6 deletions(-)
fs/crypto/hooks.c +31 -0
index a7a8a3f581a0..3142cf106bde 100644
@@ -9,6 +9,37 @@
 
 #include "fscrypt_private.h"
 
+/**
+ * __fscrypt_file_open() - prepare for filesystem-internal access to a
+ *                      possibly-encrypted regular file
+ * @dir: the inode for the directory via which the file is being accessed
+ * @inode: the inode being "opened"
+ *
+ * This is like fscrypt_file_open(), but instead of taking the 'struct file'
+ * being opened it takes the parent directory explicitly.  This is intended for
+ * use cases such as "send/receive" which involve the filesystem accessing file
+ * contents without setting up a 'struct file'.
+ *
+ * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
+ */
+int __fscrypt_file_open(struct inode *dir, struct inode *inode)
+{
+     int err;
+
+     err = fscrypt_require_key(inode);
+     if (err)
+             return err;
+
+     if (!fscrypt_has_permitted_context(dir, inode)) {
+             fscrypt_warn(inode,
+                          "Inconsistent encryption context (parent directory: %llu)",
+                          dir->i_ino);
+             return -EPERM;
+     }
+     return 0;
+}
+EXPORT_SYMBOL_GPL(__fscrypt_file_open);
+
 /**
  * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
  * @inode: the inode being opened
@@ -60,12 +91,7 @@ int fscrypt_file_open(struct inode *inode, struct file *filp)
      rcu_read_unlock();
 
Quoted 14 lines

fs/crypto/hooks.c int fscrypt_file_open(struct inode *inode, struct file *filp) · line 97

Quoted 11 lines
fs/crypto/hooks.c +1 -6
      dentry_parent = dget_parent(dentry);
-     if (!fscrypt_has_permitted_context(d_inode(dentry_parent), inode)) {
-             fscrypt_warn(inode,
-                          "Inconsistent encryption context (parent directory: %llu)",
-                          d_inode(dentry_parent)->i_ino);
-             err = -EPERM;
-     }
+     err = __fscrypt_file_open(d_inode(dentry_parent), inode);
      dput(dentry_parent);
      return err;
 }

This change makes fscrypt_file_open() execute an unnecessary extra fscrypt_require_key(). Could we just leave fscrypt_file_open() as-is?

Yes, I'm aware of that. Well, it's static inline and gated only for encrypted inodes. But yeah, I'll refactor it a bit further.

--nX

Quoted 1 line

- Eric

#11 lore raw

PATCH v7 4/43 fscrypt: conditionally don't wipe mk secret until the last active user is done

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Previously we were wiping the master key secret when we do FS_IOC_REMOVE_ENCRYPTION_KEY, and then using the fact that it was cleared as the mechanism from keeping new users from being setup. This works with inode based encryption, as the per-inode key is derived at setup time, so the secret disappearing doesn't affect any currently open files from being able to continue working.

However for extent based encryption we do our key derivation at page writeout and readpage time, which means we need the master key secret to be available while we still have our file open.

Since the master key lifetime is controlled by a flag, move the clearing of the secret to the mk_active_users cleanup stage if we have extent based encryption enabled on this super block. This counter represents the actively open files that still exist on the file system, and thus should still be able to operate normally. Once the last user is closed we can clear the secret. Until then no new users are allowed, and this allows currently open files to continue to operate until they're closed.

---

v7 changes:
* Updated the comment about key status in fscrypt_master_key_secret structure
as suggested by Eric.
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/5f28e46ce99d918a16f5bf4d8190870d0fffefc4.1706116485.git.josef@toxicpanda.com/

---
 fs/crypto/fscrypt_private.h |  9 ++++++---
 fs/crypto/keyring.c         | 18 +++++++++++++++++-
 2 files changed, 23 insertions(+), 4 deletions(-)
fs/crypto/fscrypt_private.h +6 -3
index e5ab9893dfed..2f5f4e7f8f65 100644
@@ -592,9 +592,12 @@ struct fscrypt_master_key_secret {
  *
  * FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED
  *	Removal of this key has been initiated, but some inodes that were
- *	unlocked with it are still in-use.  Like ABSENT, ->mk_secret is wiped,
- *	and the key can no longer be used to unlock inodes.  Unlike ABSENT, the
- *	key is still in the keyring; ->mk_decrypted_inodes is nonempty; and
+ *	unlocked with it are still in-use.
+ *	For filesystems using per-extent encryption ->mk_secret is still
+ *	being kept as the per-extent keys are derived at writeout time.
+ *	Otherwise, like ABSENT, ->mk_secret is wiped, and the key can
+ *	no longer be used to unlock inodes.  Unlike ABSENT, the key is
+ *	still in the keyring; ->mk_decrypted_inodes is nonempty; and
  *	->mk_active_refs > 0, being equal to the size of ->mk_decrypted_inodes.
  *
  *	This state transitions to ABSENT if ->mk_decrypted_inodes becomes empty,
fs/crypto/keyring.c +17 -1
index be8e6e8011f2..796e02a0db25 100644
@@ -110,6 +110,14 @@ void fscrypt_put_master_key_activeref(struct super_block *sb,
 	WARN_ON_ONCE(mk->mk_present);
 	WARN_ON_ONCE(!list_empty(&mk->mk_decrypted_inodes));
 
+	/* We can't wipe the master key secret until the last activeref is
+	 * dropped on the master key with per-extent encryption since the key
+	 * derivation continues to happen as long as there are active refs.
+	 * Wipe it here now that we're done using it.
+	 */
+	if (sb->s_cop->has_per_extent_encryption)
+		wipe_master_key_secret(&mk->mk_secret);
+
 	for (i = 0; i <= FSCRYPT_MODE_MAX; i++) {
 		fscrypt_destroy_prepared_key(
 				sb, &mk->mk_direct_keys[i]);
@@ -134,7 +142,15 @@ static void fscrypt_initiate_key_removal(struct super_block *sb,
 					 struct fscrypt_master_key *mk)
 {
 	WRITE_ONCE(mk->mk_present, false);
-	wipe_master_key_secret(&mk->mk_secret);
+
+	/*
+	 * Per-extent encryption requires the master key to stick around until
+	 * writeout has completed as we derive the per-extent keys at writeout
+	 * time.  Once the activeref drops to 0 we'll wipe the master secret
+	 * key.
+	 */
+	if (!sb->s_cop->has_per_extent_encryption)
+		wipe_master_key_secret(&mk->mk_secret);
 	fscrypt_put_master_key_activeref(sb, mk);
 }
 
Signature · 1 line
2.53.0
maintainer
#12 lore raw

Re: [PATCH v7 04/43] fscrypt: conditionally don't wipe mk secret until the last active user is done

Quoted 5 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Previously we were wiping the master key secret when we do FS_IOC_REMOVE_ENCRYPTION_KEY, and then using the fact that it was cleared as the mechanism from keeping new users from being setup.

This seems to be describing the state prior to commit 15baf55481de, not the current tip of tree. We do still wipe on FS_IOC_REMOVE_ENCRYPTION_KEY, but there's a separate boolean that maintains the status and everyone looks at that now.

Quoted 4 lines

* FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED
* Removal of this key has been initiated, but some inodes that were
- * unlocked with it are still in-use. Like ABSENT, ->mk_secret is wiped,
- * and the key can no longer be used to unlock inodes. Unlike ABSENT, the

Quoted 8 lines

- * key is still in the keyring; ->mk_decrypted_inodes is nonempty; and
+ * unlocked with it are still in-use.
+ * For filesystems using per-extent encryption ->mk_secret is still
+ * being kept as the per-extent keys are derived at writeout time.
+ * Otherwise, like ABSENT, ->mk_secret is wiped, and the key can
+ * no longer be used to unlock inodes. Unlike ABSENT, the key is
+ * still in the keyring; ->mk_decrypted_inodes is nonempty; and
* ->mk_active_refs > 0, being equal to the size of ->mk_decrypted_inodes.

This is saying that a bunch of things don't apply to extent-based encryption, due to being after the "Otherwise," when in fact they actually still do. So the wording here needs improvement. How about:

    ->mk_secret exists only if the filesystem uses extent-based
    encryption, to support key derivation during file data writeback;
    otherwise it is wiped.  Either way, the key can no longer be used to
    unlock inodes.  Unlike ABSENT, the key is still in the keyring;
    ->mk_decrypted_inodes is nonempty; and ->mk_active_refs
    > 0, being equal to the size of ->mk_decrypted_inodes.
Quoted 7 lines

*
* This state transitions to ABSENT if ->mk_decrypted_inodes becomes empty,

fs/crypto/keyring.c +0 -0
index be8e6e8011f2..796e02a0db25 100644

fs/crypto/keyring.c void fscrypt_put_master_key_activeref(struct super_block *sb, · line 119

Quoted 10 lines
fs/crypto/keyring.c +7 -0
@@ -110,6 +110,14 @@ void fscrypt_put_master_key_activeref(struct super_block *sb,
 	WARN_ON_ONCE(mk->mk_present);
 	WARN_ON_ONCE(!list_empty(&mk->mk_decrypted_inodes));
 
+	/* We can't wipe the master key secret until the last activeref is
+	 * dropped on the master key with per-extent encryption since the key
+	 * derivation continues to happen as long as there are active refs.
+	 * Wipe it here now that we're done using it.
+	 */
+	if (sb->s_cop->has_per_extent_encryption)
+		wipe_master_key_secret(&mk->mk_secret);

wipe_master_key_secret() is idempotent, so we might as well just do it unconditionally here.

- Eric

#13 lore raw

Re: [PATCH v7 04/43] fscrypt: conditionally don't wipe mk secret until the last active user is done

Quoted 11 lines · Eric Biggers
Quoted 5 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Previously we were wiping the master key secret when we do FS_IOC_REMOVE_ENCRYPTION_KEY, and then using the fact that it was cleared as the mechanism from keeping new users from being setup.

This seems to be describing the state prior to commit 15baf55481de, not the current tip of tree. We do still wipe on FS_IOC_REMOVE_ENCRYPTION_KEY, but there's a separate boolean that maintains the status and everyone looks at that now.

I see, I'll clear that out.

Quoted 17 lines
Quoted 12 lines

* FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED

  *   Removal of this key has been initiated, but some inodes that were
- *   unlocked with it are still in-use.  Like ABSENT, ->mk_secret is wiped,
- *   and the key can no longer be used to unlock inodes.  Unlike ABSENT, the
- *   key is still in the keyring; ->mk_decrypted_inodes is nonempty; and
+ *   unlocked with it are still in-use.
+ *   For filesystems using per-extent encryption ->mk_secret is still
+ *   being kept as the per-extent keys are derived at writeout time.
+ *   Otherwise, like ABSENT, ->mk_secret is wiped, and the key can
+ *   no longer be used to unlock inodes.  Unlike ABSENT, the key is
+ *   still in the keyring; ->mk_decrypted_inodes is nonempty; and
  *   ->mk_active_refs > 0, being equal to the size of ->mk_decrypted_inodes.

This is saying that a bunch of things don't apply to extent-based encryption, due to being after the "Otherwise," when in fact they actually still do. So the wording here needs improvement. How about:

Quoted 6 lines
    ->mk_secret exists only if the filesystem uses extent-based
    encryption, to support key derivation during file data writeback;
    otherwise it is wiped.  Either way, the key can no longer be used to
    unlock inodes.  Unlike ABSENT, the key is still in the keyring;
    ->mk_decrypted_inodes is nonempty; and ->mk_active_refs
    > 0, being equal to the size of ->mk_decrypted_inodes.

Agreed, this sounds better. I'll use that.

Quoted 10 lines
Quoted 10 lines

*
* This state transitions to ABSENT if ->mk_decrypted_inodes becomes empty,

fs/crypto/keyring.c +0 -0
index be8e6e8011f2..796e02a0db25 100644
@@ -110,6 +110,14 @@ void fscrypt_put_master_key_activeref(struct super_block *sb,
      WARN_ON_ONCE(mk->mk_present);
      WARN_ON_ONCE(!list_empty(&mk->mk_decrypted_inodes));
 
Quoted 10 lines

fs/crypto/keyring.c void fscrypt_put_master_key_activeref(struct super_block *sb, · line 119

Quoted 7 lines
fs/crypto/keyring.c +7 -0
+     /* We can't wipe the master key secret until the last activeref is
+      * dropped on the master key with per-extent encryption since the key
+      * derivation continues to happen as long as there are active refs.
+      * Wipe it here now that we're done using it.
+      */
+     if (sb->s_cop->has_per_extent_encryption)
+             wipe_master_key_secret(&mk->mk_secret);

wipe_master_key_secret() is idempotent, so we might as well just do it unconditionally here.

While this is true, it also (kind of) documents that the secret should already be wiped out by now in case of !extent encryption.

But I can wipe the secret unconditionally here if you insist.

--nX

Quoted 1 line

- Eric

maintainer
#14 lore raw

Re: [PATCH v7 04/43] fscrypt: conditionally don't wipe mk secret until the last active user is done

Quoted 8 lines · Daniel Vacek
Quoted 8 lines
Quoted 7 lines
fs/crypto/keyring.c +7 -0
+     /* We can't wipe the master key secret until the last activeref is
+      * dropped on the master key with per-extent encryption since the key
+      * derivation continues to happen as long as there are active refs.
+      * Wipe it here now that we're done using it.
+      */
+     if (sb->s_cop->has_per_extent_encryption)
+             wipe_master_key_secret(&mk->mk_secret);
Quoted 7 lines
Quoted 2 lines

wipe_master_key_secret() is idempotent, so we might as well just do it unconditionally here.

While this is true, it also (kind of) documents that the secret should already be wiped out by now in case of !extent encryption.

But I can wipe the secret unconditionally here if you insist.

So leave a comment that mentions that it's not always needed. Just like how fscrypt_free_master_key() does kfree_sensitive(), because why not.

- Eric

#15 lore raw

Re: [PATCH v7 04/43] fscrypt: conditionally don't wipe mk secret until the last active user is done

Quoted 12 lines · Eric Biggers
Quoted 11 lines · Daniel Vacek
Quoted 10 lines

fs/crypto/keyring.c void fscrypt_put_master_key_activeref(struct super_block *sb, · line 119

Quoted 7 lines
fs/crypto/keyring.c +7 -0
+     /* We can't wipe the master key secret until the last activeref is
+      * dropped on the master key with per-extent encryption since the key
+      * derivation continues to happen as long as there are active refs.
+      * Wipe it here now that we're done using it.
+      */
+     if (sb->s_cop->has_per_extent_encryption)
+             wipe_master_key_secret(&mk->mk_secret);

wipe_master_key_secret() is idempotent, so we might as well just do it unconditionally here.

Quoted 7 lines
Quoted 4 lines

While this is true, it also (kind of) documents that the secret should already be wiped out by now in case of !extent encryption.

But I can wipe the secret unconditionally here if you insist.

So leave a comment that mentions that it's not always needed. Just like how fscrypt_free_master_key() does kfree_sensitive(), because why not.

Right. Thanks.

--nX

Quoted 1 line

- Eric

#16 lore raw

PATCH v7 5/43 blk-crypto: add a process bio callback

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Btrfs does checksumming, and the checksums need to match the bytes on disk. In order to facilitate this add a process bio callback for the blk-crypto layer. This allows the file system to specify a callback and then can process the encrypted bio as necessary.

For btrfs, writes will have the checksums calculated and saved into our relevant data structures for storage once the write completes. For reads we will validate the checksums match what is on disk and error out if there is a mismatch.

This is incompatible with native encryption obviously, so make sure we don't use native encryption if this callback is set.

---

v7 changes:
* Adapt to fscrypt changes
- b37fbce460ad ("blk-crypto: optimize bio splitting in blk_crypto_fallback_encrypt_bio")
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/66c781f3b2afdf2c558efdf33a7bba8bcfe47ce7.1706116485.git.josef@toxicpanda.com/

---
 block/blk-crypto-fallback.c | 41 +++++++++++++++++++++++++++++++++++++
 block/blk-crypto-internal.h |  8 ++++++++
 block/blk-crypto-profile.c  |  2 ++
 block/blk-crypto.c          |  6 +++++-
 fs/crypto/inline_crypt.c    |  3 ++-
 include/linux/blk-crypto.h  | 15 ++++++++++++--
 6 files changed, 71 insertions(+), 4 deletions(-)
block/blk-crypto-fallback.c +41 -0
index 61f595410832..5d35f0687bf8 100644
@@ -330,6 +330,17 @@ static void __blk_crypto_fallback_encrypt_bio(struct bio *src_bio,
 		}
 	}
 
+	/* Process the encrypted bio before we submit it. */
+	if (bc->bc_key->crypto_cfg.process_bio) {
+		blk_status_t status;
+
+		status = bc->bc_key->crypto_cfg.process_bio(src_bio, enc_bio);
+		if (status != BLK_STS_OK) {
+			enc_bio->bi_status = status;
+			goto out_free_enc_bio;
+		}
+	}
+
 	submit_bio(enc_bio);
 	return;
 
@@ -358,6 +369,16 @@ static void blk_crypto_fallback_encrypt_bio(struct bio *src_bio)
 	struct blk_crypto_keyslot *slot;
 	blk_status_t status;
 
+	/*
+	 * We cannot split bio's that have process_bio, as they require the original bio.
+	 * The upper layer must make sure to limit the submitted bio's appropriately.
+	 */
+	if (bio_segments(src_bio) > BIO_MAX_VECS && bc->bc_key->crypto_cfg.process_bio) {
+		src_bio->bi_status = BLK_STS_RESOURCE;
+		bio_endio(src_bio);
+		return;
+	}
+
 	status = blk_crypto_get_keyslot(blk_crypto_fallback_profile,
 					bc->bc_key, &slot);
 	if (status != BLK_STS_OK) {
@@ -427,6 +448,13 @@ static void blk_crypto_fallback_decrypt_bio(struct work_struct *work)
 	struct blk_crypto_keyslot *slot;
 	blk_status_t status;
 
+	/* Process the bio first before trying to decrypt. */
+	if (bc->bc_key->crypto_cfg.process_bio) {
+		status = bc->bc_key->crypto_cfg.process_bio(bio, bio);
+		if (status != BLK_STS_OK)
+			goto out;
+	}
+
 	status = blk_crypto_get_keyslot(blk_crypto_fallback_profile,
 					bc->bc_key, &slot);
 	if (status == BLK_STS_OK) {
@@ -435,12 +463,25 @@ static void blk_crypto_fallback_decrypt_bio(struct work_struct *work)
 				blk_crypto_fallback_tfm(slot));
 		blk_crypto_put_keyslot(slot);
 	}
+out:
 	mempool_free(f_ctx, bio_fallback_crypt_ctx_pool);
 
 	bio->bi_status = status;
 	bio_endio(bio);
 }
 
+/**
+ * blk_crypto_profile_is_fallback - check if this profile is the fallback
+ *				    profile
+ * @profile: the profile we're checking
+ *
+ * This is just a quick check to make sure @profile is the fallback profile.
+ */
+bool blk_crypto_profile_is_fallback(struct blk_crypto_profile *profile)
+{
+	return profile == blk_crypto_fallback_profile;
+}
+
 /**
  * blk_crypto_fallback_decrypt_endio - queue bio for fallback decryption
  *
block/blk-crypto-internal.h +8 -0
index 742694213529..c857ebeb9637 100644
@@ -226,6 +226,8 @@ int blk_crypto_fallback_start_using_mode(enum blk_crypto_mode_num mode_num);
 
 int blk_crypto_fallback_evict_key(const struct blk_crypto_key *key);
 
+bool blk_crypto_profile_is_fallback(struct blk_crypto_profile *profile);
+
 #else /* CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK */
 
 static inline int
@@ -241,6 +243,12 @@ blk_crypto_fallback_evict_key(const struct blk_crypto_key *key)
 	return 0;
 }
 
+static inline bool
+blk_crypto_profile_is_fallback(struct blk_crypto_profile *profile)
+{
+	return false;
+}
+
 #endif /* CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK */
 
 #endif /* __LINUX_BLK_CRYPTO_INTERNAL_H */
block/blk-crypto-profile.c +2 -0
index 4ac74443687a..ced35ee186f0 100644
@@ -352,6 +352,8 @@ bool __blk_crypto_cfg_supported(struct blk_crypto_profile *profile,
 		return false;
 	if (!(profile->key_types_supported & cfg->key_type))
 		return false;
+	if (cfg->process_bio && !blk_crypto_profile_is_fallback(profile))
+		return false;
 	return true;
 }
 
block/blk-crypto.c +5 -1
index 856d3c5b1fa0..d93c593ae1eb 100644
@@ -300,6 +300,8 @@ int __blk_crypto_rq_bio_prep(struct request *rq, struct bio *bio,
  * @dun_bytes: number of bytes that will be used to specify the DUN when this
  *	       key is used
  * @data_unit_size: the data unit size to use for en/decryption
+ * @process_bio: the call back if the upper layer needs to process the encrypted
+ *		 bio
  *
  * Return: 0 on success, -errno on failure.  The caller is responsible for
  *	   zeroizing both blk_key and key_bytes when done with them.
@@ -309,7 +311,8 @@ int blk_crypto_init_key(struct blk_crypto_key *blk_key,
 			enum blk_crypto_key_type key_type,
 			enum blk_crypto_mode_num crypto_mode,
 			unsigned int dun_bytes,
-			unsigned int data_unit_size)
+			unsigned int data_unit_size,
+			blk_crypto_process_bio_t process_bio)
 {
 	const struct blk_crypto_mode *mode;
 
@@ -343,6 +346,7 @@ int blk_crypto_init_key(struct blk_crypto_key *blk_key,
 	blk_key->crypto_cfg.dun_bytes = dun_bytes;
 	blk_key->crypto_cfg.data_unit_size = data_unit_size;
 	blk_key->crypto_cfg.key_type = key_type;
+	blk_key->crypto_cfg.process_bio = process_bio;
 	blk_key->data_unit_size_bits = ilog2(data_unit_size);
 	blk_key->size = key_size;
 	memcpy(blk_key->bytes, key_bytes, key_size);
fs/crypto/inline_crypt.c +2 -1
index 31791fb98a9e..c51c6eb2259f 100644
@@ -178,7 +178,8 @@ int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
 
 	err = blk_crypto_init_key(blk_key, key_bytes, key_size, key_type,
 				  crypto_mode, fscrypt_get_dun_bytes(ci),
-				  1U << ci->ci_data_unit_bits);
+				  1U << ci->ci_data_unit_bits,
+				  NULL);
 	if (err) {
 		fscrypt_err(inode, "error %d initializing blk-crypto key", err);
 		goto fail;
include/linux/blk-crypto.h +13 -2
index f7c3cb4a342f..34512f6f5086 100644
@@ -7,7 +7,7 @@
 #define __LINUX_BLK_CRYPTO_H
 
 #include <linux/minmax.h>
-#include <linux/types.h>
+#include <linux/blk_types.h>
 #include <uapi/linux/blk-crypto.h>
 
 enum blk_crypto_mode_num {
@@ -19,6 +19,14 @@ enum blk_crypto_mode_num {
 	BLK_ENCRYPTION_MODE_MAX,
 };
 
+/*
+ * orig_bio must be the bio that was submitted from the upper layer as the upper
+ * layer could have used a specific bioset and expect the orig_bio to be from
+ * its bioset.
+ */
+typedef blk_status_t (*blk_crypto_process_bio_t)(struct bio *orig_bio,
+						 struct bio *enc_bio);
+
 /*
  * Supported types of keys.  Must be bitflags due to their use in
  * blk_crypto_profile::key_types_supported.
@@ -77,12 +85,14 @@ enum blk_crypto_key_type {
  *	filesystem block size or the disk sector size.
  * @dun_bytes: the maximum number of bytes of DUN used when using this key
  * @key_type: the type of this key -- either raw or hardware-wrapped
+ * @proces_bio: optional callback to process encrypted bios.
  */
 struct blk_crypto_config {
 	enum blk_crypto_mode_num crypto_mode;
 	unsigned int data_unit_size;
 	unsigned int dun_bytes;
 	enum blk_crypto_key_type key_type;
+	blk_crypto_process_bio_t process_bio;
 };
 
 /**
@@ -150,7 +160,8 @@ int blk_crypto_init_key(struct blk_crypto_key *blk_key,
 			enum blk_crypto_key_type key_type,
 			enum blk_crypto_mode_num crypto_mode,
 			unsigned int dun_bytes,
-			unsigned int data_unit_size);
+			unsigned int data_unit_size,
+			blk_crypto_process_bio_t process_bio);
 
 int blk_crypto_start_using_key(struct block_device *bdev,
 			       const struct blk_crypto_key *key);
Signature · 1 line
2.53.0
maintainer
#17 lore raw

Re: [PATCH v7 05/43] blk-crypto: add a process bio callback

Quoted 4 lines · Daniel Vacek
block/blk-crypto-fallback.c +0 -0
@@ -330,6 +330,17 @@ static void __blk_crypto_fallback_encrypt_bio(struct bio *src_bio,
 		}
 	}
 

block/blk-crypto-fallback.c static void __blk_crypto_fallback_encrypt_bio(struct bio *src_bio, · line 342

Quoted 10 lines
block/blk-crypto-fallback.c +10 -0
+	/* Process the encrypted bio before we submit it. */
+	if (bc->bc_key->crypto_cfg.process_bio) {
+		blk_status_t status;
+
+		status = bc->bc_key->crypto_cfg.process_bio(src_bio, enc_bio);
+		if (status != BLK_STS_OK) {
+			enc_bio->bi_status = status;
+			goto out_free_enc_bio;
+		}
+	}

This looks very out of place in this function, because this function potentially submits multiple encrypted bios whereas this code assumes there's just one. I think we could at least use a comment here, as well as a WARN_ON_ONCE(!bc->bc_key->crypto_cfg.process_bio) in the case where an additional bio is being submitted.

block/blk-crypto-fallback.c static void blk_crypto_fallback_encrypt_bio(struct bio *src_bio) · line 376

Quoted 5 lines
block/blk-crypto-fallback.c +5 -0
+	/*
+	 * We cannot split bio's that have process_bio, as they require the original bio.
+	 * The upper layer must make sure to limit the submitted bio's appropriately.
+	 */
+	if (bio_segments(src_bio) > BIO_MAX_VECS && bc->bc_key->crypto_cfg.process_bio) {

Checks should be reversed so that the expensive bio_segments() check only gets done if process_bio is non-NULL.

(Sashiko spotted this too, by the way)

Quoted 2 lines

+ * @process_bio: the call back if the upper layer needs to process the encrypted
+ * bio

or NULL if no such callback is needed.

Quoted 1 line

+ * @proces_bio: optional callback to process encrypted bios.

Typo.

By the way, after writing kerneldoc you should run the kerneldoc checker, as it will find things like this:

$ scripts/kernel-doc -v -none include/linux/blk-crypto.h 
Info: include/linux/blk-crypto.h:79 Scanning doc for struct blk_crypto_config
Warning: include/linux/blk-crypto.h:95 struct member 'process_bio' not described in 'blk_crypto_config'
#18 lore raw

Re: [PATCH v7 05/43] blk-crypto: add a process bio callback

Quoted 5 lines · Eric Biggers
Quoted 4 lines · Daniel Vacek
(quoted diff) +0 -0
@@ -330,6 +330,17 @@ static void __blk_crypto_fallback_encrypt_bio(struct bio *src_bio,
              }
      }
 
Quoted 16 lines

block/blk-crypto-fallback.c static void __blk_crypto_fallback_encrypt_bio(struct bio *src_bio, · line 342

Quoted 10 lines
block/blk-crypto-fallback.c +10 -0
+     /* Process the encrypted bio before we submit it. */
+     if (bc->bc_key->crypto_cfg.process_bio) {
+             blk_status_t status;
+
+             status = bc->bc_key->crypto_cfg.process_bio(src_bio, enc_bio);
+             if (status != BLK_STS_OK) {
+                     enc_bio->bi_status = status;
+                     goto out_free_enc_bio;
+             }
+     }

This looks very out of place in this function, because this function potentially submits multiple encrypted bios whereas this code assumes there's just one. I think we could at least use a comment here, as well as a WARN_ON_ONCE(!bc->bc_key->crypto_cfg.process_bio) in the case where an additional bio is being submitted.

While this funcion may submit multiple encrypted bios in general case, the check below makes sure that in case of crypto_cfg.process_bio callback splitting is not allowed and only single encrypted bio will be submitted. The WARN_ON would be impossible to hit. That's why no handling is implemented with the in-loop submit.

Quoted 10 lines

block/blk-crypto-fallback.c static void blk_crypto_fallback_encrypt_bio(struct bio *src_bio) · line 376

Quoted 5 lines
block/blk-crypto-fallback.c +5 -0
+     /*
+      * We cannot split bio's that have process_bio, as they require the original bio.
+      * The upper layer must make sure to limit the submitted bio's appropriately.
+      */
+     if (bio_segments(src_bio) > BIO_MAX_VECS && bc->bc_key->crypto_cfg.process_bio) {

Checks should be reversed so that the expensive bio_segments() check only gets done if process_bio is non-NULL.

(Sashiko spotted this too, by the way)

Yup, true.

Quoted 4 lines
Quoted 2 lines

+ * @process_bio: the call back if the upper layer needs to process the encrypted
+ * bio

or NULL if no such callback is needed.

I'll add this.

Quoted 3 lines
Quoted 1 line

+ * @proces_bio: optional callback to process encrypted bios.

Typo.

Already fixed. Sashiko also noticed.

Quoted 6 lines

By the way, after writing kerneldoc you should run the kerneldoc checker, as it will find things like this:

$ scripts/kernel-doc -v -none include/linux/blk-crypto.h
Info: include/linux/blk-crypto.h:79 Scanning doc for struct blk_crypto_config
Warning: include/linux/blk-crypto.h:95 struct member 'process_bio' not described in 'blk_crypto_config'

Hey, this is a good hint. Thanks, I'll keep that in mind.

--nX

maintainer
#19 lore raw

Re: [PATCH v7 05/43] blk-crypto: add a process bio callback

In reply to Daniel Vacek
Quoted 6 lines · Daniel Vacek

/*
* Supported types of keys. Must be bitflags due to their use in
* blk_crypto_profile::key_types_supported.

include/linux/blk-crypto.h +0 -0
@@ -77,12 +85,14 @@ enum blk_crypto_key_type {
  *	filesystem block size or the disk sector size.
  * @dun_bytes: the maximum number of bytes of DUN used when using this key

include/linux/blk-crypto.h enum blk_crypto_key_type { · line 96

Quoted 10 lines
include/linux/blk-crypto.h +2 -0
  * @key_type: the type of this key -- either raw or hardware-wrapped
+ * @proces_bio: optional callback to process encrypted bios.
  */
 struct blk_crypto_config {
 	enum blk_crypto_mode_num crypto_mode;
 	unsigned int data_unit_size;
 	unsigned int dun_bytes;
 	enum blk_crypto_key_type key_type;
+	blk_crypto_process_bio_t process_bio;
 };

This new field needs to be initialized in fscrypt_select_encryption_impl(). Otherwise it breaks native inline encryption for ext4 and f2fs.

- Eric

#20 lore raw

Re: [PATCH v7 05/43] blk-crypto: add a process bio callback

Quoted 13 lines · Eric Biggers
Quoted 12 lines · Daniel Vacek

/*
* Supported types of keys. Must be bitflags due to their use in
* blk_crypto_profile::key_types_supported.

include/linux/blk-crypto.h +1 -0
@@ -77,12 +85,14 @@ enum blk_crypto_key_type {
  *   filesystem block size or the disk sector size.
  * @dun_bytes: the maximum number of bytes of DUN used when using this key
  * @key_type: the type of this key -- either raw or hardware-wrapped
+ * @proces_bio: optional callback to process encrypted bios.
  */
 struct blk_crypto_config {
      enum blk_crypto_mode_num crypto_mode;
      unsigned int data_unit_size;
Quoted 8 lines

include/linux/blk-crypto.h enum blk_crypto_key_type { · line 96

Quoted 4 lines
include/linux/blk-crypto.h +1 -0
      unsigned int dun_bytes;
      enum blk_crypto_key_type key_type;
+     blk_crypto_process_bio_t process_bio;
 };

This new field needs to be initialized in fscrypt_select_encryption_impl(). Otherwise it breaks native inline encryption for ext4 and f2fs.

Ouch, sorry. I should do regression testing on at least one of these.

Thanks.

--nX

Quoted 1 line

- Eric

#21 lore raw

PATCH v7 6/43 fscrypt: add a process_bio hook to fscrypt_operations

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

This will allow file systems to set a process_bio hook for inline encryption. This will be utilized by btrfs in order to make sure the checksumming work is done on the encrypted bio's.

---

v5: https://lore.kernel.org/linux-btrfs/2c638e5fa1b7868dbf79d932b15364c3c30ca9de.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/crypto/inline_crypt.c |  2 +-
 include/linux/fscrypt.h  | 14 ++++++++++++++
 2 files changed, 15 insertions(+), 1 deletion(-)
fs/crypto/inline_crypt.c +1 -1
index c51c6eb2259f..fde844aaac1a 100644
@@ -179,7 +179,7 @@ int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
 	err = blk_crypto_init_key(blk_key, key_bytes, key_size, key_type,
 				  crypto_mode, fscrypt_get_dun_bytes(ci),
 				  1U << ci->ci_data_unit_bits,
-				  NULL);
+				  sb->s_cop->process_bio);
 	if (err) {
 		fscrypt_err(inode, "error %d initializing blk-crypto key", err);
 		goto fail;
include/linux/fscrypt.h +14 -0
index dda5b1d32f78..a1cbd1be154c 100644
@@ -16,6 +16,7 @@
 #include <linux/fs.h>
 #include <linux/mm.h>
 #include <linux/slab.h>
+#include <linux/blk-crypto.h>
 #include <uapi/linux/fscrypt.h>
 
 /*
@@ -205,6 +206,19 @@ struct fscrypt_operations {
 	 */
 	struct block_device **(*get_devices)(struct super_block *sb,
 					     unsigned int *num_devs);
+
+	/*
+	 * A callback if the file system requires the ability to process the
+	 * encrypted bio, used only with inline encryption.
+	 *
+	 * @orig_bio: the original bio submitted.
+	 * @enc_bio: the encrypted bio.
+	 *
+	 * For writes the enc_bio will be different from the orig_bio, for reads
+	 * they will be the same.  For reads we get the bio before it is
+	 * decrypted, for writes we get the bio before it is submitted.
+	 */
+	blk_crypto_process_bio_t process_bio;
 };
 
 int fscrypt_d_revalidate(struct inode *dir, const struct qstr *name,
Signature · 1 line
2.53.0
#22 lore raw

PATCH v7 7/43 fscrypt: expose fscrypt_nokey_name

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

btrfs stores its data structures, including filenames in directories, in its own buffer implementation, struct extent_buffer, composed of several non-contiguous pages. We could copy filenames into a temporary buffer and use fscrypt_match_name() against that buffer, such extensive memcpying would be expensive. Instead, exposing fscrypt_nokey_name as in this change allows btrfs to recapitulate fscrypt_match_name() using methods on struct extent_buffer instead of dealing with a raw byte array.

---

v5: https://lore.kernel.org/linux-btrfs/132b64edf1e6b705995fb1a6dc2f194527f6be75.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/crypto/fname.c       | 36 ------------------------------------
 include/linux/fscrypt.h | 36 ++++++++++++++++++++++++++++++++++++
 2 files changed, 36 insertions(+), 36 deletions(-)
fs/crypto/fname.c +0 -36
index 629eb0d72e86..ca73efcf5658 100644
@@ -27,42 +27,6 @@
  */
 #define FSCRYPT_FNAME_MIN_MSG_LEN 16
 
-/*
- * struct fscrypt_nokey_name - identifier for directory entry when key is absent
- *
- * When userspace lists an encrypted directory without access to the key, the
- * filesystem must present a unique "no-key name" for each filename that allows
- * it to find the directory entry again if requested.  Naively, that would just
- * mean using the ciphertext filenames.  However, since the ciphertext filenames
- * can contain illegal characters ('\0' and '/'), they must be encoded in some
- * way.  We use base64url.  But that can cause names to exceed NAME_MAX (255
- * bytes), so we also need to use a strong hash to abbreviate long names.
- *
- * The filesystem may also need another kind of hash, the "dirhash", to quickly
- * find the directory entry.  Since filesystems normally compute the dirhash
- * over the on-disk filename (i.e. the ciphertext), it's not computable from
- * no-key names that abbreviate the ciphertext using the strong hash to fit in
- * NAME_MAX.  It's also not computable if it's a keyed hash taken over the
- * plaintext (but it may still be available in the on-disk directory entry);
- * casefolded directories use this type of dirhash.  At least in these cases,
- * each no-key name must include the name's dirhash too.
- *
- * To meet all these requirements, we base64url-encode the following
- * variable-length structure.  It contains the dirhash, or 0's if the filesystem
- * didn't provide one; up to 149 bytes of the ciphertext name; and for
- * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
- *
- * This ensures that each no-key name contains everything needed to find the
- * directory entry again, contains only legal characters, doesn't exceed
- * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
- * take the performance hit of SHA-256 on very long filenames (which are rare).
- */
-struct fscrypt_nokey_name {
-	u32 dirhash[2];
-	u8 bytes[149];
-	u8 sha256[SHA256_DIGEST_SIZE];
-}; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
-
 /*
  * Decoded size of max-size no-key name, i.e. a name that was abbreviated using
  * the strong hash and thus includes the 'sha256' field.  This isn't simply
include/linux/fscrypt.h +36 -0
index a1cbd1be154c..9eef488340ea 100644
@@ -56,6 +56,42 @@ struct fscrypt_name {
 #define fname_name(p)		((p)->disk_name.name)
 #define fname_len(p)		((p)->disk_name.len)
 
+/*
+ * struct fscrypt_nokey_name - identifier for directory entry when key is absent
+ *
+ * When userspace lists an encrypted directory without access to the key, the
+ * filesystem must present a unique "no-key name" for each filename that allows
+ * it to find the directory entry again if requested.  Naively, that would just
+ * mean using the ciphertext filenames.  However, since the ciphertext filenames
+ * can contain illegal characters ('\0' and '/'), they must be encoded in some
+ * way.  We use base64url.  But that can cause names to exceed NAME_MAX (255
+ * bytes), so we also need to use a strong hash to abbreviate long names.
+ *
+ * The filesystem may also need another kind of hash, the "dirhash", to quickly
+ * find the directory entry.  Since filesystems normally compute the dirhash
+ * over the on-disk filename (i.e. the ciphertext), it's not computable from
+ * no-key names that abbreviate the ciphertext using the strong hash to fit in
+ * NAME_MAX.  It's also not computable if it's a keyed hash taken over the
+ * plaintext (but it may still be available in the on-disk directory entry);
+ * casefolded directories use this type of dirhash.  At least in these cases,
+ * each no-key name must include the name's dirhash too.
+ *
+ * To meet all these requirements, we base64url-encode the following
+ * variable-length structure.  It contains the dirhash, or 0's if the filesystem
+ * didn't provide one; up to 149 bytes of the ciphertext name; and for
+ * ciphertexts longer than 149 bytes, also the SHA-256 of the remaining bytes.
+ *
+ * This ensures that each no-key name contains everything needed to find the
+ * directory entry again, contains only legal characters, doesn't exceed
+ * NAME_MAX, is unambiguous unless there's a SHA-256 collision, and that we only
+ * take the performance hit of SHA-256 on very long filenames (which are rare).
+ */
+struct fscrypt_nokey_name {
+	u32 dirhash[2];
+	u8 bytes[149];
+	u8 sha256[32];
+}; /* 189 bytes => 252 bytes base64url-encoded, which is <= NAME_MAX (255) */
+
 /* Maximum value for the third parameter of fscrypt_operations.set_context(). */
 #define FSCRYPT_SET_CONTEXT_MAX_SIZE	40
 
Signature · 1 line
2.53.0
#23 lore raw

PATCH v7 8/43 fscrypt: add documentation about extent encryption

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Add a couple of sections to the fscrypt documentation about per-extent encryption.

---

v7 changes:
* Fix spelling and typos.
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/7b2cc4dd423c3930e51b1ef5dd209164ff11c05a.1706116485.git.josef@toxicpanda.com/

---
 Documentation/filesystems/fscrypt.rst | 41 +++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)
Documentation/filesystems/fscrypt.rst +41 -0
index c0dd35f1af12..a1b0b50da869 100644
@@ -283,6 +283,21 @@ alternative master keys or to support rotating master keys.  Instead,
 the master keys may be wrapped in userspace, e.g. as is done by the
 `fscrypt <https://github.com/google/fscrypt>`_ tool.
 
+Per-extent encryption keys
+--------------------------
+
+For certain file systems, such as btrfs, it's desired to derive a
+per-extent encryption key.  This is to enable features such as snapshots
+and reflink, where you could have different inodes pointing at the same
+extent.  When a new extent is created fscrypt randomly generates a
+16-byte nonce and the file system stores it alongside the extent.
+Then, it uses a KDF (as described in `Key derivation function`_) to
+derive the extent's key from the master key and nonce.
+
+Currently the inode's master key and encryption policy must match the
+extent, so you cannot share extents between inodes that were encrypted
+differently.
+
 DIRECT_KEY policies
 -------------------
 
@@ -1483,6 +1498,27 @@ by the kernel and is used as KDF input or as a tweak to cause
 different files to be encrypted differently; see `Per-file encryption
 keys`_ and `DIRECT_KEY policies`_.
 
+Extent encryption context
+-------------------------
+
+The extent encryption context mirrors the important parts of the above
+`Encryption context`_, with a few omissions.  The struct is defined as
+follows::
+
+        struct fscrypt_extent_context {
+                u8 version;
+                u8 encryption_mode;
+                u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
+                u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
+        };
+
+Currently all fields much match the containing inode's encryption
+context, with the exception of the nonce.
+
+Additionally extent encryption is only supported with
+FSCRYPT_EXTENT_CONTEXT_V2 using the standard policy; all other policies
+are disallowed.
+
 Data path changes
 -----------------
 
@@ -1506,6 +1542,11 @@ buffer.  Some filesystems, such as UBIFS, already use temporary
 buffers regardless of encryption.  Other filesystems, such as ext4 and
 F2FS, have to allocate bounce pages specially for encryption.
 
+Inline encryption is not optional for extent encryption based file
+systems; the amount of objects required to be kept around is too much.
+Inline encryption handles the object lifetime details which results in a
+cleaner implementation.
+
 Filename hashing and encoding
 -----------------------------
 
Signature · 1 line
2.53.0
maintainer
#24 lore raw

Re: [PATCH v7 08/43] fscrypt: add documentation about extent encryption

Quoted 4 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Add a couple of sections to the fscrypt documentation about per-extent encryption.

A few things that were missed:

- "Contents encryption" section should be updated to document how extents are encrypted

- btrfs should be added to the list of filesystems in the introduction section and in the "Tests" section

- "Read-only kernel memory compromise" should be updated to mention the new limitation which extent-based encryption creates. Maybe after the sentence "Per-file keys for in-use files will *not* be removed or wiped.", insert "On filesystems that use per-extent encryption, master keys for in-use files will not be wiped either."

The list of filesystems can also be found in the help text for the CONFIG_FS_ENCRYPTION kconfig. That should be updated too.

Documentation/filesystems/fscrypt.rst alternative master keys or to support rotating master keys. Instead, · line 290

Quoted 2 lines
Documentation/filesystems/fscrypt.rst +2 -0
+For certain file systems, such as btrfs, it's desired to derive a
+per-extent encryption key.  This is to enable features such as snapshots

It's necessary, not just "desired". The per-file keys just don't work when multiple files can share the same extents.

Documentation/filesystems/fscrypt.rst alternative master keys or to support rotating master keys. Instead, · line 299

Quoted 3 lines
Documentation/filesystems/fscrypt.rst +3 -0
+Currently the inode's master key and encryption policy must match the
+extent, so you cannot share extents between inodes that were encrypted
+differently.

Here's another instance of "the inode". It should say something like:
Currently, each extent's master key and encryption mode always match the corresponding values from each inode that shares the extent.

Quoted 7 lines
Documentation/filesystems/fscrypt.rst +7 -0
+The extent encryption context mirrors the important parts of the above
+`Encryption context`_, with a few omissions.  The struct is defined as
+follows::
+
+        struct fscrypt_extent_context {
+                u8 version;
+                u8 encryption_mode;

Documentation/filesystems/fscrypt.rst by the kernel and is used as KDF input or as a tweak to cause · line 1520

Quoted 10 lines
Documentation/filesystems/fscrypt.rst +10 -0
+                u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
+                u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
+        };
+
+Currently all fields much match the containing inode's encryption
+context, with the exception of the nonce.
+
+Additionally extent encryption is only supported with
+FSCRYPT_EXTENT_CONTEXT_V2 using the standard policy; all other policies
+are disallowed.

FSCRYPT_EXTENT_CONTEXT_V2 should say FSCRYPT_EXTENT_CONTEXT_V1.

Both version and nonce are exceptions, not just nonce.

Unclear what "the standard policy" is.

- Eric

#25 lore raw

PATCH v7 9/43 btrfs: add infrastructure for safe em freeing

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

When we add fscrypt support we're going to have fscrypt objects hanging off of extent_maps. This includes a block key, which if we're the last one freeing the key we may have to unregister it from the block layer. This requires taking a semaphore in the block layer, which means we can't free em's under the extent map tree lock.

Thankfully we only do this in two places, one where we're dropping a range of extent maps, and when we're freeing logged extents. Add a free_extent_map_safe() which will add the em to a list in the em_tree if we free'd the object. Currently this is unconditional but will be changed to conditional on the fscrypt object we will add in a later patch.

To process these delayed objects add a free_pending_extent_maps() that is called after the lock has been dropped on the em_tree. This will process the extent maps on the freed list and do the appropriate freeing work in a safe manner.

---

v5: https://lore.kernel.org/linux-btrfs/6cf44f7860e94de68df242e69f4c5250bd061cff.1706116485.git.josef@toxicpanda.com/
* No changes since (other than simple function renames).

---
 fs/btrfs/extent_map.c | 76 +++++++++++++++++++++++++++++++++++++++++--
 fs/btrfs/extent_map.h | 10 ++++++
 fs/btrfs/tree-log.c   |  6 ++--
 3 files changed, 87 insertions(+), 5 deletions(-)
fs/btrfs/extent_map.c +73 -3
index 9284c0a81bef..61fe262667ee 100644
@@ -34,7 +34,9 @@ void __cold btrfs_extent_map_exit(void)
 void btrfs_extent_map_tree_init(struct extent_map_tree *tree)
 {
 	tree->root = RB_ROOT;
+	tree->flags = 0;
 	INIT_LIST_HEAD(&tree->modified_extents);
+	INIT_LIST_HEAD(&tree->freed_extents);
 	rwlock_init(&tree->lock);
 }
 
@@ -51,9 +53,15 @@ struct extent_map *btrfs_alloc_extent_map(void)
 	RB_CLEAR_NODE(&em->rb_node);
 	refcount_set(&em->refs, 1);
 	INIT_LIST_HEAD(&em->list);
+	INIT_LIST_HEAD(&em->free_list);
 	return em;
 }
 
+static void free_extent_map(struct extent_map *em)
+{
+	kmem_cache_free(extent_map_cache, em);
+}
+
 /*
  * Drop the reference out on @em by one and free the structure if the reference
  * count hits zero.
@@ -65,10 +73,69 @@ void btrfs_free_extent_map(struct extent_map *em)
 	if (refcount_dec_and_test(&em->refs)) {
 		WARN_ON(btrfs_extent_map_in_tree(em));
 		WARN_ON(!list_empty(&em->list));
-		kmem_cache_free(extent_map_cache, em);
+		free_extent_map(em);
+	}
+}
+
+/*
+ * Drop a ref for the extent map in the given tree.
+ *
+ * @tree:	tree that the em is a part of.
+ * @em:		the em to drop the reference to.
+ *
+ * Drop the reference count on @em by one, if the reference count hits 0 and
+ * there is an object on the em that can't be safely freed in the current
+ * context (if we are holding the extent_map_tree->lock for example), then add
+ * it to the freed_extents list on the extent_map_tree for later processing.
+ *
+ * This must be followed by a btrfs_free_pending_extent_maps() to clear
+ * the pending frees.
+ */
+void btrfs_free_extent_map_safe(struct extent_map_tree *tree,
+				struct extent_map *em)
+{
+	lockdep_assert_held_write(&tree->lock);
+
+	if (!em)
+		return;
+
+	if (refcount_dec_and_test(&em->refs)) {
+		WARN_ON(btrfs_extent_map_in_tree(em));
+		WARN_ON(!list_empty(&em->list));
+		list_add_tail(&em->free_list, &tree->freed_extents);
+		set_bit(EXTENT_MAP_TREE_PENDING_FREES, &tree->flags);
 	}
 }
 
+/*
+ * Free the em objects that exist on the em tree
+ *
+ * @tree:	the tree to free the objects from.
+ *
+ * If there are any objects on the em->freed_extents list go ahead and
+ * free them here in a safe way.  This is to be coupled with any uses of
+ * btrfs_free_extent_map_safe().
+ */
+void btrfs_free_pending_extent_maps(struct extent_map_tree *tree)
+{
+	struct extent_map *em;
+
+	/* Avoid taking the write lock if we don't have any pending frees. */
+	if (!test_and_clear_bit(EXTENT_MAP_TREE_PENDING_FREES, &tree->flags))
+		return;
+
+	write_lock(&tree->lock);
+	while ((em = list_first_entry_or_null(&tree->freed_extents,
+					      struct extent_map, free_list))) {
+		list_del_init(&em->free_list);
+		write_unlock(&tree->lock);
+		free_extent_map(em);
+		cond_resched();
+		write_lock(&tree->lock);
+	}
+	write_unlock(&tree->lock);
+}
+
 /* Do the math around the end of an extent, handling wrapping. */
 static u64 range_end(u64 start, u64 len)
 {
@@ -784,7 +851,7 @@ static void drop_all_extent_maps_fast(struct btrfs_inode *inode)
 		em = rb_entry(node, struct extent_map, rb_node);
 		em->flags &= ~(EXTENT_FLAG_PINNED | EXTENT_FLAG_LOGGING);
 		btrfs_remove_extent_mapping(inode, em);
-		btrfs_free_extent_map(em);
+		btrfs_free_extent_map_safe(tree, em);
 
 		if (cond_resched_rwlock_write(&tree->lock))
 			node = rb_first(&tree->root);
@@ -792,6 +859,8 @@ static void drop_all_extent_maps_fast(struct btrfs_inode *inode)
 			node = next;
 	}
 	write_unlock(&tree->lock);
+
+	btrfs_free_pending_extent_maps(tree);
 }
 
 /*
@@ -986,13 +1055,14 @@ void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end,
 		btrfs_free_extent_map(em);
 next:
 		/* Once for us (for our lookup reference). */
-		btrfs_free_extent_map(em);
+		btrfs_free_extent_map_safe(em_tree, em);
 
 		em = next_em;
 	}
 
 	write_unlock(&em_tree->lock);
 
+	btrfs_free_pending_extent_maps(em_tree);
 	btrfs_free_extent_map(split);
 	btrfs_free_extent_map(split2);
 }
fs/btrfs/extent_map.h +10 -0
index 6f685f3c9327..a962012be1c3 100644
@@ -97,11 +97,18 @@ struct extent_map {
 	u32 flags;
 	refcount_t refs;
 	struct list_head list;
+	struct list_head free_list;
+};
+
+enum extent_map_flags {
+	EXTENT_MAP_TREE_PENDING_FREES,
 };
 
 struct extent_map_tree {
 	struct rb_root root;
+	unsigned long flags;
 	struct list_head modified_extents;
+	struct list_head freed_extents;
 	rwlock_t lock;
 };
 
@@ -175,6 +182,9 @@ int btrfs_split_extent_map(struct btrfs_inode *inode, u64 start, u64 len, u64 pr
 
 struct extent_map *btrfs_alloc_extent_map(void);
 void btrfs_free_extent_map(struct extent_map *em);
+void btrfs_free_extent_map_safe(struct extent_map_tree *tree,
+				struct extent_map *em);
+void btrfs_free_pending_extent_maps(struct extent_map_tree *tree);
 int __init btrfs_extent_map_init(void);
 void __cold btrfs_extent_map_exit(void);
 int btrfs_unpin_extent_cache(struct btrfs_inode *inode, u64 start, u64 len, u64 gen);
fs/btrfs/tree-log.c +4 -2
index 9123adafa0d1..e6cd475057db 100644
@@ -5410,7 +5410,7 @@ static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
 		 */
 		if (ret) {
 			btrfs_clear_em_logging(inode, em);
-			btrfs_free_extent_map(em);
+			btrfs_free_extent_map_safe(tree, em);
 			continue;
 		}
 
@@ -5419,11 +5419,13 @@ static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
 		ret = log_one_extent(trans, inode, em, path, ctx);
 		write_lock(&tree->lock);
 		btrfs_clear_em_logging(inode, em);
-		btrfs_free_extent_map(em);
+		btrfs_free_extent_map_safe(tree, em);
 	}
 	WARN_ON(!list_empty(&extents));
 	write_unlock(&tree->lock);
 
+	btrfs_free_pending_extent_maps(tree);
+
 	if (!ret)
 		ret = btrfs_log_prealloc_extents(trans, inode, path, ctx);
 	if (ret)
Signature · 1 line
2.53.0
maintainer
#26 lore raw

Re: [PATCH v7 09/43] btrfs: add infrastructure for safe em freeing

Quoted 6 lines · Daniel Vacek
fs/btrfs/extent_map.c +6 -0
+/*
+ * Drop a ref for the extent map in the given tree.
+ *
+ * @tree:	tree that the em is a part of.
+ * @em:		the em to drop the reference to.
+ *

fs/btrfs/extent_map.c void btrfs_free_extent_map(struct extent_map *em) · line 95

Quoted 10 lines
fs/btrfs/extent_map.c +10 -0
+ * Drop the reference count on @em by one, if the reference count hits 0 and
+ * there is an object on the em that can't be safely freed in the current
+ * context (if we are holding the extent_map_tree->lock for example), then add
+ * it to the freed_extents list on the extent_map_tree for later processing.
+ *
+ * This must be followed by a btrfs_free_pending_extent_maps() to clear
+ * the pending frees.
+ */
+void btrfs_free_extent_map_safe(struct extent_map_tree *tree,
+				struct extent_map *em)

The "unsafe" btrfs_free_extent_map() still exists. Assuming both variants will continue to be needed, shouldn't the comment above the "unsafe" variant be updated to document the preconditions for using it?

fs/btrfs/extent_map.h struct extent_map { · line 101

Quoted 10 lines
fs/btrfs/extent_map.h +2 -0
index 6f685f3c9327..a962012be1c3 100644
@@ -97,11 +97,18 @@ struct extent_map {
 	u32 flags;
 	refcount_t refs;
 	struct list_head list;
+	struct list_head free_list;
+};

The comment above this struct says "Keep this structure as compact as possible, as we can have really large amounts of allocated extent maps at any time." Is there any way to avoid adding a whole list_head?

- Eric

#27 lore raw

Re: [PATCH v7 09/43] btrfs: add infrastructure for safe em freeing

Quoted 13 lines · Eric Biggers
Quoted 12 lines · Daniel Vacek

+/*
+ * Drop a ref for the extent map in the given tree.
+ *
+ * @tree: tree that the em is a part of.
+ * @em: the em to drop the reference to.
+ *
+ * Drop the reference count on @em by one, if the reference count hits 0 and
+ * there is an object on the em that can't be safely freed in the current
+ * context (if we are holding the extent_map_tree->lock for example), then add
+ * it to the freed_extents list on the extent_map_tree for later processing.
+ *
+ * This must be followed by a btrfs_free_pending_extent_maps() to clear

Quoted 8 lines

fs/btrfs/extent_map.c void btrfs_free_extent_map(struct extent_map *em) · line 95

Quoted 4 lines

+ * the pending frees.
+ */

fs/btrfs/extent_map.c +2 -0
+void btrfs_free_extent_map_safe(struct extent_map_tree *tree,
+                             struct extent_map *em)

The "unsafe" btrfs_free_extent_map() still exists. Assuming both variants will continue to be needed, shouldn't the comment above the "unsafe" variant be updated to document the preconditions for using it?

Actually this could be cleaned up and unified into a single function with optional argument.

Quoted 6 lines
Quoted 6 lines
fs/btrfs/extent_map.h +0 -0
index 6f685f3c9327..a962012be1c3 100644
@@ -97,11 +97,18 @@ struct extent_map {
      u32 flags;
Quoted 8 lines

fs/btrfs/extent_map.h struct extent_map { · line 101

Quoted 4 lines
fs/btrfs/extent_map.h +2 -0
      refcount_t refs;
      struct list_head list;
+     struct list_head free_list;
+};

The comment above this struct says "Keep this structure as compact as possible, as we can have really large amounts of allocated extent maps at any time." Is there any way to avoid adding a whole list_head?

Good catch. In fact we can reuse the old list member. No need for a new one.

--nX

Quoted 1 line

- Eric

#28 lore raw

PATCH v7 10/43 btrfs: start using fscrypt hooks

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

In order to appropriately encrypt, create, open, rename, and various symlink operations must call fscrypt hooks. These determine whether the inode should be encrypted and do other preparatory actions. The superblock must have fscrypt operations registered, so implement the minimal set also, and introduce the new fscrypt.[ch] files to hold the fscrypt-specific functionality.

---

v7 changes:
* Fix rebase conflicts.
* Fix a memory leak as suggested by Chris' AI review.
v6 changes:
* FSCrypt info moved from VFS inode to FS specific inode structure.
* Trivial renames.
v5: https://lore.kernel.org/linux-btrfs/333de15efb2d7ec220293c4b5e3782fe85634c06.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/Makefile      |   1 +
 fs/btrfs/btrfs_inode.h |   5 ++
 fs/btrfs/file.c        |   3 ++
 fs/btrfs/fscrypt.c     |  10 ++++
 fs/btrfs/fscrypt.h     |  10 ++++
 fs/btrfs/inode.c       | 105 ++++++++++++++++++++++++++++++++++-------
 fs/btrfs/super.c       |   2 +
 7 files changed, 119 insertions(+), 17 deletions(-)
 create mode 100644 fs/btrfs/fscrypt.c
 create mode 100644 fs/btrfs/fscrypt.h
fs/btrfs/Makefile +1 -0
index b15122aa26f9..7397db45eb36 100644
@@ -38,6 +38,7 @@ btrfs-$(CONFIG_BTRFS_FS_POSIX_ACL) += acl.o
 btrfs-$(CONFIG_BTRFS_DEBUG) += ref-verify.o
 btrfs-$(CONFIG_BLK_DEV_ZONED) += zoned.o
 btrfs-$(CONFIG_FS_VERITY) += verity.o
+btrfs-$(CONFIG_FS_ENCRYPTION) += fscrypt.o
 
 btrfs-$(CONFIG_BTRFS_FS_RUN_SANITY_TESTS) += tests/free-space-tests.o \
 	tests/extent-buffer-tests.o tests/btrfs-tests.o \
fs/btrfs/btrfs_inode.h +5 -0
index 55c272fe5d92..81940b27b037 100644
@@ -339,6 +339,10 @@ struct btrfs_inode {
 
 	struct rw_semaphore i_mmap_lock;
 
+#ifdef CONFIG_FS_ENCRYPTION
+	struct fscrypt_inode_info *i_crypt_info;
+#endif
+
 	struct inode vfs_inode;
 };
 
@@ -582,6 +586,7 @@ struct btrfs_new_inode_args {
 	struct posix_acl *default_acl;
 	struct posix_acl *acl;
 	struct fscrypt_name fname;
+	bool encrypt;
 };
 
 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
fs/btrfs/file.c +3 -0
index cf1cb5c4db75..8b0ebdeca9dd 100644
@@ -3813,6 +3813,9 @@ static int btrfs_file_open(struct inode *inode, struct file *filp)
 		return -EIO;
 
 	filp->f_mode |= FMODE_NOWAIT | FMODE_CAN_ODIRECT;
+	ret = fscrypt_file_open(inode, filp);
+	if (ret)
+		return ret;
 
 	ret = fsverity_file_open(inode, filp);
 	if (ret)
fs/btrfs/fscrypt.c new file +10 -0
new file mode 100644
index 000000000000..6cfba7d94e72
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include "ctree.h"
+#include "btrfs_inode.h"
+#include "fscrypt.h"
+
+const struct fscrypt_operations btrfs_fscrypt_ops = {
+	.inode_info_offs = (int)offsetof(struct btrfs_inode, i_crypt_info) -
+			   (int)offsetof(struct btrfs_inode, vfs_inode),
+};
fs/btrfs/fscrypt.h new file +10 -0
new file mode 100644
index 000000000000..7f4e6888bd43
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef BTRFS_FSCRYPT_H
+#define BTRFS_FSCRYPT_H
+
+#include <linux/fscrypt.h>
+
+extern const struct fscrypt_operations btrfs_fscrypt_ops;
+
+#endif /* BTRFS_FSCRYPT_H */
fs/btrfs/inode.c +88 -17

217 lines not on this page · raw message

fs/btrfs/super.c +2 -0
index b26aa9169e83..efaa0788c1fc 100644
@@ -49,6 +49,7 @@
 #include "tests/btrfs-tests.h"
 #include "block-group.h"
 #include "discard.h"
+#include "fscrypt.h"
 #include "qgroup.h"
 #include "raid56.h"
 #include "fs.h"
@@ -969,6 +970,7 @@ static int btrfs_fill_super(struct super_block *sb,
 	sb->s_vop = &btrfs_verityops;
 #endif
 	sb->s_xattr = btrfs_xattr_handlers;
+	fscrypt_set_ops(sb, &btrfs_fscrypt_ops);
 	sb->s_time_gran = 1;
 	sb->s_iflags |= SB_I_CGROUPWB | SB_I_ALLOW_HSM;
 
Signature · 1 line
2.53.0
maintainer
#29 lore raw

Re: [PATCH v7 10/43] btrfs: start using fscrypt hooks

Quoted 23 lines · Daniel Vacek
fs/btrfs/inode.c +10 -3
@@ -9041,20 +9063,28 @@ static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
 	};
 	unsigned int trans_num_items;
 	int ret;
-	int name_len;
 	int datasize;
 	unsigned long ptr;
 	struct btrfs_file_extent_item *ei;
 	struct extent_buffer *leaf;
+	struct fscrypt_str disk_link;
+	size_t max_len;
+	u32 name_len = strlen(symname);
+
+	/*
+	 * BTRFS_MAX_INLINE_DATA_SIZE() isn't actually telling the truth, we actually
+	 * limit inline data extents to min(BTRFS_MAX_INLINE_DATA_SIZE(), sectorsize),
+	 * so adjust max_len given this wonderful bit of inconsistency.
+	 */
+	max_len = min_t(size_t, BTRFS_MAX_INLINE_DATA_SIZE(fs_info), fs_info->sectorsize);
 
-	name_len = strlen(symname);
 	/*
-	 * Symlinks utilize uncompressed inline extent data, which should not

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9087

Quoted 10 lines
fs/btrfs/inode.c +5 -4
-	 * reach block size.
+	 * fscrypt sets disk_link.len to be len + 1, including a NUL terminator,
+	 * but we don't store that '\0' character.
 	 */
-	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
-	    name_len >= fs_info->sectorsize)
-		return -ENAMETOOLONG;
+	ret = fscrypt_prepare_symlink(dir, symname, name_len, max_len + 1, &disk_link);
+	if (ret)
+		return ret;

This is off by one from the other filesystems. Yes, the way the other filesystems do encrypted symlinks is weird, but this still doesn't fix it, since the unnecessary 'struct fscrypt_symlink_data' is still stored. If it's not being fixed completely, it should just be done the same way.

Did you do it this way because you're trying to squeeze out an extra byte, to allow 4094-byte symlink targets instead of 4093 as the other filesystems do? Or did you do it this way because btrfs doesn't count a nul terminator when checking unencrypted symlinks against BTRFS_MAX_INLINE_DATA_SIZE(fs_info), and you needed to preserve that behavior? But at the same time, btrfs *does* count the nul terminator when validating against 'fs_info->sectorsize', and this changes that behavior. So it's not clear what was intended here.

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9134

Quoted 10 lines
fs/btrfs/inode.c +10 -0
+	if (IS_ENCRYPTED(inode)) {
+		ret = fscrypt_encrypt_symlink(inode, symname, name_len, &disk_link);
+		if (ret) {
+			btrfs_abort_transaction(trans, ret);
+			btrfs_free_path(path);
+			discard_new_inode(inode);
+			inode = NULL;
+			goto out;
+		}
+	}

fscrypt_encrypt_symlink() already has an IS_ENCRYPTED(inode) check built-in.

Quoted 10 lines
fs/btrfs/inode.c +10 -0
+static const char *btrfs_get_link(struct dentry *dentry, struct inode *inode,
+				  struct delayed_call *done)
+{
+	struct page *cpage;
+	const char *paddr;
+	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
+
+	if (!IS_ENCRYPTED(inode))
+		return page_get_link(dentry, inode, done);
+

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9198

Quoted 10 lines
fs/btrfs/inode.c +10 -0
+	if (!dentry)
+		return ERR_PTR(-ECHILD);
+
+	cpage = read_mapping_page(inode->i_mapping, 0, NULL);
+	if (IS_ERR(cpage))
+		return ERR_CAST(cpage);
+
+	paddr = fscrypt_get_symlink(inode, page_address(cpage),
+				    BTRFS_MAX_INLINE_DATA_SIZE(fs_info), done);
+	put_page(cpage);

This uses a different max_len from btrfs_symlink().

Speaking of symlinks, btrfs is also missing a hookup to fscrypt_symlink_getattr().

- Eric

A message that is not in the archive (sent off-list or not yet received): CAPjX3Fer=5gfiBuB0Nk8rRdUZdhpk9txeBYtGFy=p6W-DmiVDQ@mail.gmail.com

#31 lore raw

Re: [PATCH v7 10/43] btrfs: start using fscrypt hooks

Quoted 40 lines · Eric Biggers
Quoted 23 lines · Daniel Vacek
fs/btrfs/inode.c +10 -3
@@ -9041,20 +9063,28 @@ static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
      };
      unsigned int trans_num_items;
      int ret;
-     int name_len;
      int datasize;
      unsigned long ptr;
      struct btrfs_file_extent_item *ei;
      struct extent_buffer *leaf;
+     struct fscrypt_str disk_link;
+     size_t max_len;
+     u32 name_len = strlen(symname);
+
+     /*
+      * BTRFS_MAX_INLINE_DATA_SIZE() isn't actually telling the truth, we actually
+      * limit inline data extents to min(BTRFS_MAX_INLINE_DATA_SIZE(), sectorsize),
+      * so adjust max_len given this wonderful bit of inconsistency.
+      */
+     max_len = min_t(size_t, BTRFS_MAX_INLINE_DATA_SIZE(fs_info), fs_info->sectorsize);
 
-     name_len = strlen(symname);
      /*
-      * Symlinks utilize uncompressed inline extent data, which should not

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9087

Quoted 10 lines
fs/btrfs/inode.c +5 -4
-      * reach block size.
+      * fscrypt sets disk_link.len to be len + 1, including a NUL terminator,
+      * but we don't store that '\0' character.
       */
-     if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
-         name_len >= fs_info->sectorsize)
-             return -ENAMETOOLONG;
+     ret = fscrypt_prepare_symlink(dir, symname, name_len, max_len + 1, &disk_link);
+     if (ret)
+             return ret;

This is off by one from the other filesystems. Yes, the way the other filesystems do encrypted symlinks is weird, but this still doesn't fix it, since the unnecessary 'struct fscrypt_symlink_data' is still stored. If it's not being fixed completely, it should just be done the same way.

Quoted 8 lines

Did you do it this way because you're trying to squeeze out an extra byte, to allow 4094-byte symlink targets instead of 4093 as the other filesystems do? Or did you do it this way because btrfs doesn't count a nul terminator when checking unencrypted symlinks against BTRFS_MAX_INLINE_DATA_SIZE(fs_info), and you needed to preserve that behavior? But at the same time, btrfs *does* count the nul terminator when validating against 'fs_info->sectorsize', and this changes that behavior. So it's not clear what was intended here.

This comes from Omar/Josef authored [v1] of the patchset from September 2023. I understand the intent was to utilize the last byte. But yeah, I think it's perfectly fine sticking to 4093 bytes limit as other FSes do. I'll drop the +1.

[v1] https://lore.kernel.org/linux-btrfs/912762ca48efcc684cd5cdde99b5a78cd25f1078.1695750478.git.josef@toxicpanda.com/

Quoted 11 lines

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9134

Quoted 10 lines
fs/btrfs/inode.c +10 -0
+     if (IS_ENCRYPTED(inode)) {
+             ret = fscrypt_encrypt_symlink(inode, symname, name_len, &disk_link);
+             if (ret) {
+                     btrfs_abort_transaction(trans, ret);
+                     btrfs_free_path(path);
+                     discard_new_inode(inode);
+                     inode = NULL;
+                     goto out;
+             }
+     }
Quoted 2 lines

fscrypt_encrypt_symlink() already has an IS_ENCRYPTED(inode) check built-in.

Correct. I'll drop the check.

Quoted 14 lines
Quoted 14 lines
fs/btrfs/inode.c +14 -0
+static const char *btrfs_get_link(struct dentry *dentry, struct inode *inode,
+                               struct delayed_call *done)
+{
+     struct page *cpage;
+     const char *paddr;
+     struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
+
+     if (!IS_ENCRYPTED(inode))
+             return page_get_link(dentry, inode, done);
+
+     if (!dentry)
+             return ERR_PTR(-ECHILD);
+
+     cpage = read_mapping_page(inode->i_mapping, 0, NULL);
Quoted 8 lines

fs/btrfs/inode.c static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir, · line 9198

Quoted 6 lines
fs/btrfs/inode.c +6 -0
+     if (IS_ERR(cpage))
+             return ERR_CAST(cpage);
+
+     paddr = fscrypt_get_symlink(inode, page_address(cpage),
+                                 BTRFS_MAX_INLINE_DATA_SIZE(fs_info), done);
+     put_page(cpage);

This uses a different max_len from btrfs_symlink().

I'm not sure that matters. But unifying them shouldn't hurt.

Quoted 2 lines

Speaking of symlinks, btrfs is also missing a hookup to fscrypt_symlink_getattr().

Uh, I was not aware of that. It seems like fstests is missing for this feature.

Thanks a lot.

--nX

Quoted 1 line

- Eric

#32 lore raw

PATCH v7 11/43 btrfs: add inode encryption contexts

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

fscrypt stores a context item with encrypted inodes that contains the related encryption information. fscrypt provides an arbitrary blob for the filesystem to store, and it does not clearly fit into an existing structure, so this goes in a new item type.

---

v7 changes:
* Fix a path leak as found by Chri's AI review.
v6 changes:
* Shorten the inode context key macro name to BTRFS_FSCRYPT_INODE_CTX_KEY.
v5: https://lore.kernel.org/linux-btrfs/5a88efb484b0874a7430b83bc6e5f6b9aa5858d5.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/fscrypt.c              | 116 ++++++++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h              |   2 +
 fs/btrfs/inode.c                |  19 ++++++
 fs/btrfs/ioctl.c                |   8 ++-
 include/uapi/linux/btrfs_tree.h |  10 +++
 5 files changed, 153 insertions(+), 2 deletions(-)
fs/btrfs/fscrypt.c +116 -0
index 6cfba7d94e72..c503f817cbe7 100644
@@ -1,10 +1,126 @@
 // SPDX-License-Identifier: GPL-2.0
 
+#include <linux/iversion.h>
 #include "ctree.h"
+#include "accessors.h"
 #include "btrfs_inode.h"
+#include "disk-io.h"
+#include "fs.h"
 #include "fscrypt.h"
+#include "ioctl.h"
+#include "messages.h"
+#include "transaction.h"
+#include "xattr.h"
+
+static int btrfs_fscrypt_get_context(struct inode *inode, void *ctx, size_t len)
+{
+	struct btrfs_key key = {
+		.objectid = btrfs_ino(BTRFS_I(inode)),
+		.type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+		.offset = 0,
+	};
+	struct btrfs_path *path;
+	struct extent_buffer *leaf;
+	unsigned long ptr;
+	int ret;
+
+
+	path = btrfs_alloc_path();
+	if (!path)
+		return -ENOMEM;
+
+	ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
+	if (ret) {
+		len = -ENOENT;
+		goto out;
+	}
+
+	leaf = path->nodes[0];
+	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+	/* fscrypt provides max context length, but it could be less */
+	len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+	read_extent_buffer(leaf, ctx, ptr, len);
+
+out:
+	btrfs_free_path(path);
+	return len;
+}
+
+static int btrfs_fscrypt_set_context(struct inode *inode, const void *ctx,
+				     size_t len, void *fs_data)
+{
+	struct btrfs_trans_handle *trans = fs_data;
+	struct btrfs_key key = {
+		.objectid = btrfs_ino(BTRFS_I(inode)),
+		.type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+		.offset = 0,
+	};
+	struct btrfs_path *path = NULL;
+	struct extent_buffer *leaf;
+	unsigned long ptr;
+	int ret;
+
+	if (!trans)
+		trans = btrfs_start_transaction(BTRFS_I(inode)->root, 2);
+	if (IS_ERR(trans))
+		return PTR_ERR(trans);
+
+	path = btrfs_alloc_path();
+	if (!path) {
+		ret = -ENOMEM;
+		goto out_err;
+	}
+
+	ret = btrfs_search_slot(trans, BTRFS_I(inode)->root, &key, path, 0, 1);
+	if (ret < 0)
+		goto out_err;
+
+	if (ret > 0) {
+		btrfs_release_path(path);
+		ret = btrfs_insert_empty_item(trans, BTRFS_I(inode)->root, path, &key, len);
+		if (ret)
+			goto out_err;
+	}
+
+	leaf = path->nodes[0];
+	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+
+	len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+	write_extent_buffer(leaf, ctx, ptr, len);
+	btrfs_mark_buffer_dirty(trans, leaf);
+	btrfs_release_path(path);
+
+	if (fs_data)
+		goto out_err;
+
+	BTRFS_I(inode)->flags |= BTRFS_INODE_ENCRYPT;
+	btrfs_sync_inode_flags_to_i_flags(BTRFS_I(inode));
+	inode_inc_iversion(inode);
+	inode_set_ctime_current(inode);
+	ret = btrfs_update_inode(trans, BTRFS_I(inode));
+	if (ret)
+		goto out_abort;
+	btrfs_free_path(path);
+	btrfs_end_transaction(trans);
+	return 0;
+out_abort:
+	btrfs_abort_transaction(trans, ret);
+out_err:
+	if (!fs_data)
+		btrfs_end_transaction(trans);
+	btrfs_free_path(path);
+	return ret;
+}
+
+static bool btrfs_fscrypt_empty_dir(struct inode *inode)
+{
+	return inode->i_size == BTRFS_EMPTY_DIR_SIZE;
+}
 
 const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.inode_info_offs = (int)offsetof(struct btrfs_inode, i_crypt_info) -
 			   (int)offsetof(struct btrfs_inode, vfs_inode),
+	.get_context = btrfs_fscrypt_get_context,
+	.set_context = btrfs_fscrypt_set_context,
+	.empty_dir = btrfs_fscrypt_empty_dir,
 };
fs/btrfs/fscrypt.h +2 -0
index 7f4e6888bd43..80adb7e56826 100644
@@ -5,6 +5,8 @@
 
 #include <linux/fscrypt.h>
 
+#include "fs.h"
+
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
 
 #endif /* BTRFS_FSCRYPT_H */
fs/btrfs/inode.c +19 -0
index 8f89e44b2d53..14bad4cdb900 100644
@@ -60,6 +60,7 @@
 #include "defrag.h"
 #include "dir-item.h"
 #include "file-item.h"
+#include "fscrypt.h"
 #include "uuid-tree.h"
 #include "ioctl.h"
 #include "file.h"
@@ -6529,6 +6530,9 @@ int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
 	struct inode *inode = args->inode;
 	int ret;
 
+	if (fscrypt_is_nokey_name(args->dentry))
+		return -ENOKEY;
+
 	if (!args->orphan) {
 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
 					     &args->fname);
@@ -6564,6 +6568,9 @@ int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
 	if (dir->i_security)
 		(*trans_num_items)++;
 #endif
+	/* 1 to add fscrypt item */
+	if (args->encrypt)
+		(*trans_num_items)++;
 	if (args->orphan) {
 		/* 1 to add orphan item */
 		(*trans_num_items)++;
@@ -6776,6 +6783,11 @@ int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
 	BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
 	BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
 
+	if (args->encrypt) {
+		BTRFS_I(inode)->flags |= BTRFS_INODE_ENCRYPT;
+		btrfs_sync_inode_flags_to_i_flags(BTRFS_I(inode));
+	}
+
 	/*
 	 * We're going to fill the inode item now, so at this point the inode
 	 * must be fully initialized.
@@ -6849,6 +6861,13 @@ int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
 			goto discard;
 		}
 	}
+	if (args->encrypt) {
+		ret = fscrypt_set_context(inode, trans);
+		if (ret) {
+			btrfs_abort_transaction(trans, ret);
+			goto discard;
+		}
+	}
 
 	ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
 	if (WARN_ON(ret)) {
fs/btrfs/ioctl.c +6 -2
index a39460bf68a7..6a37dd3cc5ee 100644
@@ -153,6 +153,8 @@ static unsigned int btrfs_inode_flags_to_fsflags(const struct btrfs_inode *inode
 		iflags |= FS_DIRSYNC_FL;
 	if (flags & BTRFS_INODE_NODATACOW)
 		iflags |= FS_NOCOW_FL;
+	if (flags & BTRFS_INODE_ENCRYPT)
+		iflags |= FS_ENCRYPT_FL;
 	if (ro_flags & BTRFS_INODE_RO_VERITY)
 		iflags |= FS_VERITY_FL;
 
@@ -181,12 +183,14 @@ void btrfs_sync_inode_flags_to_i_flags(struct btrfs_inode *inode)
 		new_fl |= S_NOATIME;
 	if (inode->flags & BTRFS_INODE_DIRSYNC)
 		new_fl |= S_DIRSYNC;
+	if (inode->flags & BTRFS_INODE_ENCRYPT)
+		new_fl |= S_ENCRYPTED;
 	if (inode->ro_flags & BTRFS_INODE_RO_VERITY)
 		new_fl |= S_VERITY;
 
 	set_mask_bits(&inode->vfs_inode.i_flags,
 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
-		      S_VERITY, new_fl);
+		      S_VERITY | S_ENCRYPTED, new_fl);
 }
 
 /*
@@ -199,7 +203,7 @@ static int check_fsflags(unsigned int old_flags, unsigned int flags)
 		      FS_NOATIME_FL | FS_NODUMP_FL | \
 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
 		      FS_NOCOMP_FL | FS_COMPR_FL |
-		      FS_NOCOW_FL))
+		      FS_NOCOW_FL | FS_ENCRYPT_FL))
 		return -EOPNOTSUPP;
 
 	/* COMPR and NOCOMP on new/old are valid */
include/uapi/linux/btrfs_tree.h +10 -0
index cc3b9f7dccaf..3cec245268e7 100644
@@ -167,6 +167,8 @@
 #define BTRFS_VERITY_DESC_ITEM_KEY	36
 #define BTRFS_VERITY_MERKLE_ITEM_KEY	37
 
+#define BTRFS_FSCRYPT_INODE_CTX_KEY	41
+
 #define BTRFS_ORPHAN_ITEM_KEY		48
 /* reserve 2-15 close to the inode for later flexibility */
 
@@ -431,6 +433,7 @@ static inline __u8 btrfs_dir_flags_to_ftype(__u8 flags)
 #define BTRFS_INODE_NOATIME		(1U << 9)
 #define BTRFS_INODE_DIRSYNC		(1U << 10)
 #define BTRFS_INODE_COMPRESS		(1U << 11)
+#define BTRFS_INODE_ENCRYPT		(1U << 12)
 
 #define BTRFS_INODE_ROOT_ITEM_INIT	(1U << 31)
 
@@ -447,6 +450,7 @@ static inline __u8 btrfs_dir_flags_to_ftype(__u8 flags)
 	 BTRFS_INODE_NOATIME |						\
 	 BTRFS_INODE_DIRSYNC |						\
 	 BTRFS_INODE_COMPRESS |						\
+	 BTRFS_INODE_ENCRYPT |						\
 	 BTRFS_INODE_ROOT_ITEM_INIT)
 
 #define BTRFS_INODE_RO_VERITY		(1U << 0)
@@ -1075,6 +1079,12 @@ enum {
 	BTRFS_NR_FILE_EXTENT_TYPES = 3,
 };
 
+enum btrfs_encryption_type {
+	BTRFS_ENCRYPTION_NONE,
+	BTRFS_ENCRYPTION_FSCRYPT,
+	BTRFS_NR_ENCRYPTION_TYPES,
+};
+
 struct btrfs_file_extent_item {
 	/*
 	 * transaction id that created this extent
Signature · 1 line
2.53.0
maintainer
#33 lore raw

Re: [PATCH v7 11/43] btrfs: add inode encryption contexts

Quoted 68 lines · Daniel Vacek

From: Omar Sandoval <[email protected]>

fscrypt stores a context item with encrypted inodes that contains the related encryption information. fscrypt provides an arbitrary blob for the filesystem to store, and it does not clearly fit into an existing structure, so this goes in a new item type.

---

v7 changes:
* Fix a path leak as found by Chri's AI review.
v6 changes:
* Shorten the inode context key macro name to BTRFS_FSCRYPT_INODE_CTX_KEY.
v5: https://lore.kernel.org/linux-btrfs/5a88efb484b0874a7430b83bc6e5f6b9aa5858d5.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/fscrypt.c              | 116 ++++++++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h              |   2 +
 fs/btrfs/inode.c                |  19 ++++++
 fs/btrfs/ioctl.c                |   8 ++-
 include/uapi/linux/btrfs_tree.h |  10 +++
 5 files changed, 153 insertions(+), 2 deletions(-)
fs/btrfs/fscrypt.c +32 -0
index 6cfba7d94e72..c503f817cbe7 100644
@@ -1,10 +1,126 @@
 // SPDX-License-Identifier: GPL-2.0
 
+#include <linux/iversion.h>
 #include "ctree.h"
+#include "accessors.h"
 #include "btrfs_inode.h"
+#include "disk-io.h"
+#include "fs.h"
 #include "fscrypt.h"
+#include "ioctl.h"
+#include "messages.h"
+#include "transaction.h"
+#include "xattr.h"
+
+static int btrfs_fscrypt_get_context(struct inode *inode, void *ctx, size_t len)
+{
+	struct btrfs_key key = {
+		.objectid = btrfs_ino(BTRFS_I(inode)),
+		.type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+		.offset = 0,
+	};
+	struct btrfs_path *path;
+	struct extent_buffer *leaf;
+	unsigned long ptr;
+	int ret;
+
+
+	path = btrfs_alloc_path();
+	if (!path)
+		return -ENOMEM;
+
+	ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
+	if (ret) {
+		len = -ENOENT;
+		goto out;
+	}
+

fs/btrfs/fscrypt.c line 47

Quoted 10 lines
fs/btrfs/fscrypt.c +10 -0
+	leaf = path->nodes[0];
+	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+	/* fscrypt provides max context length, but it could be less */
+	len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+	read_extent_buffer(leaf, ctx, ptr, len);
+
+out:
+	btrfs_free_path(path);
+	return len;
+}

This doesn't conform to the calling convention for fscrypt_operations::get_context, specifically in the cases where -ENODATA and -ERANGE are expected.

/*
* Get the fscrypt context of the given inode.
*
* @inode: the inode whose context to get
* @ctx: the buffer into which to get the context
* @len: length of the @ctx buffer in bytes
*
* Return: On success, returns the length of the context in bytes; this
* may be less than @len. On failure, returns -ENODATA if the
* inode doesn't have a context, -ERANGE if the context is
* longer than @len, or another -errno code.
*/
int (*get_context)(struct inode *inode, void *ctx, size_t len);

It also seems to be assuming that any error from btrfs_search_slot() means "not found", which isn't correct.

The size_t variable called 'len' is also being used to store negative errno values, which is weird.

Quoted 55 lines
fs/btrfs/fscrypt.c +55 -0
+static int btrfs_fscrypt_set_context(struct inode *inode, const void *ctx,
+				     size_t len, void *fs_data)
+{
+	struct btrfs_trans_handle *trans = fs_data;
+	struct btrfs_key key = {
+		.objectid = btrfs_ino(BTRFS_I(inode)),
+		.type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+		.offset = 0,
+	};
+	struct btrfs_path *path = NULL;
+	struct extent_buffer *leaf;
+	unsigned long ptr;
+	int ret;
+
+	if (!trans)
+		trans = btrfs_start_transaction(BTRFS_I(inode)->root, 2);
+	if (IS_ERR(trans))
+		return PTR_ERR(trans);
+
+	path = btrfs_alloc_path();
+	if (!path) {
+		ret = -ENOMEM;
+		goto out_err;
+	}
+
+	ret = btrfs_search_slot(trans, BTRFS_I(inode)->root, &key, path, 0, 1);
+	if (ret < 0)
+		goto out_err;
+
+	if (ret > 0) {
+		btrfs_release_path(path);
+		ret = btrfs_insert_empty_item(trans, BTRFS_I(inode)->root, path, &key, len);
+		if (ret)
+			goto out_err;
+	}
+
+	leaf = path->nodes[0];
+	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+
+	len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+	write_extent_buffer(leaf, ctx, ptr, len);
+	btrfs_mark_buffer_dirty(trans, leaf);
+	btrfs_release_path(path);
+
+	if (fs_data)
+		goto out_err;
+
+	BTRFS_I(inode)->flags |= BTRFS_INODE_ENCRYPT;
+	btrfs_sync_inode_flags_to_i_flags(BTRFS_I(inode));
+	inode_inc_iversion(inode);
+	inode_set_ctime_current(inode);
+	ret = btrfs_update_inode(trans, BTRFS_I(inode));
+	if (ret)
+		goto out_abort;
+	btrfs_free_path(path);

fs/btrfs/fscrypt.c line 113

Quoted 10 lines
fs/btrfs/fscrypt.c +10 -0
+	btrfs_end_transaction(trans);
+	return 0;
+out_abort:
+	btrfs_abort_transaction(trans, ret);
+out_err:
+	if (!fs_data)
+		btrfs_end_transaction(trans);
+	btrfs_free_path(path);
+	return ret;
+}

The 'len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));' line seems scary, since it just truncates the data given.

fs/btrfs/fscrypt.c static int check_fsflags(unsigned int old_flags, unsigned int flags) · line 207

Quoted 7 lines
fs/btrfs/fscrypt.c +1 -1
@@ -199,7 +203,7 @@ static int check_fsflags(unsigned int old_flags, unsigned int flags)
 		      FS_NOATIME_FL | FS_NODUMP_FL | \
 		      FS_SYNC_FL | FS_DIRSYNC_FL | \
 		      FS_NOCOMP_FL | FS_COMPR_FL |
-		      FS_NOCOW_FL))
+		      FS_NOCOW_FL | FS_ENCRYPT_FL))
 		return -EOPNOTSUPP;

Do you know why FS_VERITY_FL isn't in this mask?

- Eric

#34 lore raw

Re: [PATCH v7 11/43] btrfs: add inode encryption contexts

Quoted 98 lines · Eric Biggers
Quoted 68 lines · Daniel Vacek

From: Omar Sandoval <[email protected]>

fscrypt stores a context item with encrypted inodes that contains the related encryption information. fscrypt provides an arbitrary blob for the filesystem to store, and it does not clearly fit into an existing structure, so this goes in a new item type.

---

v7 changes:
* Fix a path leak as found by Chri's AI review.
v6 changes:
* Shorten the inode context key macro name to BTRFS_FSCRYPT_INODE_CTX_KEY.
v5: https://lore.kernel.org/linux-btrfs/5a88efb484b0874a7430b83bc6e5f6b9aa5858d5.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/fscrypt.c              | 116 ++++++++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h              |   2 +
 fs/btrfs/inode.c                |  19 ++++++
 fs/btrfs/ioctl.c                |   8 ++-
 include/uapi/linux/btrfs_tree.h |  10 +++
 5 files changed, 153 insertions(+), 2 deletions(-)
fs/btrfs/fscrypt.c +32 -0
index 6cfba7d94e72..c503f817cbe7 100644
@@ -1,10 +1,126 @@
 // SPDX-License-Identifier: GPL-2.0
 
+#include <linux/iversion.h>
 #include "ctree.h"
+#include "accessors.h"
 #include "btrfs_inode.h"
+#include "disk-io.h"
+#include "fs.h"
 #include "fscrypt.h"
+#include "ioctl.h"
+#include "messages.h"
+#include "transaction.h"
+#include "xattr.h"
+
+static int btrfs_fscrypt_get_context(struct inode *inode, void *ctx, size_t len)
+{
+     struct btrfs_key key = {
+             .objectid = btrfs_ino(BTRFS_I(inode)),
+             .type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+             .offset = 0,
+     };
+     struct btrfs_path *path;
+     struct extent_buffer *leaf;
+     unsigned long ptr;
+     int ret;
+
+
+     path = btrfs_alloc_path();
+     if (!path)
+             return -ENOMEM;
+
+     ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
+     if (ret) {
+             len = -ENOENT;
+             goto out;
+     }
+

fs/btrfs/fscrypt.c line 47

Quoted 10 lines
fs/btrfs/fscrypt.c +10 -0
+     leaf = path->nodes[0];
+     ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+     /* fscrypt provides max context length, but it could be less */
+     len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+     read_extent_buffer(leaf, ctx, ptr, len);
+
+out:
+     btrfs_free_path(path);
+     return len;
+}

This doesn't conform to the calling convention for fscrypt_operations::get_context, specifically in the cases where -ENODATA and -ERANGE are expected.

/*
* Get the fscrypt context of the given inode.
*
* @inode: the inode whose context to get
* @ctx: the buffer into which to get the context
* @len: length of the @ctx buffer in bytes
*
* Return: On success, returns the length of the context in bytes; this
* may be less than @len. On failure, returns -ENODATA if the
* inode doesn't have a context, -ERANGE if the context is
* longer than @len, or another -errno code.
*/
int (*get_context)(struct inode *inode, void *ctx, size_t len);

Quoted 5 lines

It also seems to be assuming that any error from btrfs_search_slot() means "not found", which isn't correct.

The size_t variable called 'len' is also being used to store negative errno values, which is weird.

Those are valid points. I fixed the return codes and cleaned up the function a bit.

Quoted 60 lines
Quoted 60 lines
fs/btrfs/fscrypt.c +60 -0
+static int btrfs_fscrypt_set_context(struct inode *inode, const void *ctx,
+                                  size_t len, void *fs_data)
+{
+     struct btrfs_trans_handle *trans = fs_data;
+     struct btrfs_key key = {
+             .objectid = btrfs_ino(BTRFS_I(inode)),
+             .type = BTRFS_FSCRYPT_INODE_CTX_KEY,
+             .offset = 0,
+     };
+     struct btrfs_path *path = NULL;
+     struct extent_buffer *leaf;
+     unsigned long ptr;
+     int ret;
+
+     if (!trans)
+             trans = btrfs_start_transaction(BTRFS_I(inode)->root, 2);
+     if (IS_ERR(trans))
+             return PTR_ERR(trans);
+
+     path = btrfs_alloc_path();
+     if (!path) {
+             ret = -ENOMEM;
+             goto out_err;
+     }
+
+     ret = btrfs_search_slot(trans, BTRFS_I(inode)->root, &key, path, 0, 1);
+     if (ret < 0)
+             goto out_err;
+
+     if (ret > 0) {
+             btrfs_release_path(path);
+             ret = btrfs_insert_empty_item(trans, BTRFS_I(inode)->root, path, &key, len);
+             if (ret)
+                     goto out_err;
+     }
+
+     leaf = path->nodes[0];
+     ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
+
+     len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));
+     write_extent_buffer(leaf, ctx, ptr, len);
+     btrfs_mark_buffer_dirty(trans, leaf);
+     btrfs_release_path(path);
+
+     if (fs_data)
+             goto out_err;
+
+     BTRFS_I(inode)->flags |= BTRFS_INODE_ENCRYPT;
+     btrfs_sync_inode_flags_to_i_flags(BTRFS_I(inode));
+     inode_inc_iversion(inode);
+     inode_set_ctime_current(inode);
+     ret = btrfs_update_inode(trans, BTRFS_I(inode));
+     if (ret)
+             goto out_abort;
+     btrfs_free_path(path);
+     btrfs_end_transaction(trans);
+     return 0;
+out_abort:
+     btrfs_abort_transaction(trans, ret);
+out_err:
Quoted 8 lines

fs/btrfs/fscrypt.c line 113

Quoted 5 lines
fs/btrfs/fscrypt.c +5 -0
+     if (!fs_data)
+             btrfs_end_transaction(trans);
+     btrfs_free_path(path);
+     return ret;
+}

The 'len = min_t(size_t, len, btrfs_item_size(leaf, path->slots[0]));' line seems scary, since it just truncates the data given.

Right. Actually let's refactor both functions and split the common part.

Quoted 9 lines

fs/btrfs/fscrypt.c static int check_fsflags(unsigned int old_flags, unsigned int flags) · line 207

Quoted 7 lines
fs/btrfs/fscrypt.c +1 -1
@@ -199,7 +203,7 @@ static int check_fsflags(unsigned int old_flags, unsigned int flags)
                    FS_NOATIME_FL | FS_NODUMP_FL | \
                    FS_SYNC_FL | FS_DIRSYNC_FL | \
                    FS_NOCOMP_FL | FS_COMPR_FL |
-                   FS_NOCOW_FL))
+                   FS_NOCOW_FL | FS_ENCRYPT_FL))
              return -EOPNOTSUPP;

Do you know why FS_VERITY_FL isn't in this mask?

Not really. It seems that 41b37c51937e ("btrfs: initial fsverity support") did not add this flag. I'm not sure if that is a mistake or intentional. Maybe @Boris or @Chris would know?

--nX

Quoted 1 line

- Eric

#35 lore raw

PATCH v7 12/43 btrfs: add new FEATURE_INCOMPAT_ENCRYPT flag

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

As encrypted files will be incompatible with older filesystem versions, new filesystems should be created with an incompat flag for fscrypt, which will gate access to the encryption ioctls.

---

v5: https://lore.kernel.org/linux-btrfs/ccbea52046c1dadbbef926bfc878cc23af952729.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/fs.h              | 3 ++-
 fs/btrfs/super.c           | 5 +++++
 fs/btrfs/sysfs.c           | 6 ++++++
 include/uapi/linux/btrfs.h | 1 +
 4 files changed, 14 insertions(+), 1 deletion(-)
fs/btrfs/fs.h +2 -1
index a4758d94b32e..dbdb73722c14 100644
@@ -322,7 +322,8 @@ enum {
 	(BTRFS_FEATURE_INCOMPAT_SUPP_STABLE |	\
 	 BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE | \
 	 BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2 | \
-	 BTRFS_FEATURE_INCOMPAT_REMAP_TREE)
+	 BTRFS_FEATURE_INCOMPAT_REMAP_TREE |	\
+	 BTRFS_FEATURE_INCOMPAT_ENCRYPT)
 
 #else
 
fs/btrfs/super.c +5 -0
index efaa0788c1fc..84df97363611 100644
@@ -2563,6 +2563,11 @@ static int __init btrfs_print_mod_info(void)
 			", fsverity=yes"
 #else
 			", fsverity=no"
+#endif
+#ifdef CONFIG_FS_ENCRYPTION
+			", fscrypt=yes"
+#else
+			", fscrypt=no"
 #endif
 			;
 
fs/btrfs/sysfs.c +6 -0
index 0d14570c8bc2..3fe57843f902 100644
@@ -305,6 +305,9 @@ BTRFS_FEAT_ATTR_INCOMPAT(remap_tree, REMAP_TREE);
 #ifdef CONFIG_FS_VERITY
 BTRFS_FEAT_ATTR_COMPAT_RO(verity, VERITY);
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+BTRFS_FEAT_ATTR_INCOMPAT(encryption, ENCRYPT);
+#endif /* CONFIG_FS_ENCRYPTION */
 
 /*
  * Features which depend on feature bits and may differ between each fs.
@@ -338,6 +341,9 @@ static struct attribute *btrfs_supported_feature_attrs[] = {
 #ifdef CONFIG_FS_VERITY
 	BTRFS_FEAT_ATTR_PTR(verity),
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+	BTRFS_FEAT_ATTR_PTR(encryption),
+#endif /* CONFIG_FS_ENCRYPTION */
 	NULL
 };
 
include/uapi/linux/btrfs.h +1 -0
index 9165154a274d..2f6a46e5f4ce 100644
@@ -335,6 +335,7 @@ struct btrfs_ioctl_fs_info_args {
 #define BTRFS_FEATURE_INCOMPAT_ZONED		(1ULL << 12)
 #define BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2	(1ULL << 13)
 #define BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE	(1ULL << 14)
+#define BTRFS_FEATURE_INCOMPAT_ENCRYPT		(1ULL << 15)
 #define BTRFS_FEATURE_INCOMPAT_SIMPLE_QUOTA	(1ULL << 16)
 #define BTRFS_FEATURE_INCOMPAT_REMAP_TREE	(1ULL << 17)
 
Signature · 1 line
2.53.0
maintainer
#36 lore raw

Re: [PATCH v7 12/43] btrfs: add new FEATURE_INCOMPAT_ENCRYPT flag

Quoted 80 lines · Daniel Vacek

From: Omar Sandoval <[email protected]>

As encrypted files will be incompatible with older filesystem versions, new filesystems should be created with an incompat flag for fscrypt, which will gate access to the encryption ioctls.

---

v5: https://lore.kernel.org/linux-btrfs/ccbea52046c1dadbbef926bfc878cc23af952729.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/fs.h              | 3 ++-
 fs/btrfs/super.c           | 5 +++++
 fs/btrfs/sysfs.c           | 6 ++++++
 include/uapi/linux/btrfs.h | 1 +
 4 files changed, 14 insertions(+), 1 deletion(-)
fs/btrfs/fs.h +2 -1
index a4758d94b32e..dbdb73722c14 100644
@@ -322,7 +322,8 @@ enum {
 	(BTRFS_FEATURE_INCOMPAT_SUPP_STABLE |	\
 	 BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE | \
 	 BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2 | \
-	 BTRFS_FEATURE_INCOMPAT_REMAP_TREE)
+	 BTRFS_FEATURE_INCOMPAT_REMAP_TREE |	\
+	 BTRFS_FEATURE_INCOMPAT_ENCRYPT)
 
 #else
 
fs/btrfs/super.c +5 -0
index efaa0788c1fc..84df97363611 100644
@@ -2563,6 +2563,11 @@ static int __init btrfs_print_mod_info(void)
 			", fsverity=yes"
 #else
 			", fsverity=no"
+#endif
+#ifdef CONFIG_FS_ENCRYPTION
+			", fscrypt=yes"
+#else
+			", fscrypt=no"
 #endif
 			;
 
fs/btrfs/sysfs.c +6 -0
index 0d14570c8bc2..3fe57843f902 100644
@@ -305,6 +305,9 @@ BTRFS_FEAT_ATTR_INCOMPAT(remap_tree, REMAP_TREE);
 #ifdef CONFIG_FS_VERITY
 BTRFS_FEAT_ATTR_COMPAT_RO(verity, VERITY);
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+BTRFS_FEAT_ATTR_INCOMPAT(encryption, ENCRYPT);
+#endif /* CONFIG_FS_ENCRYPTION */
 
 /*
  * Features which depend on feature bits and may differ between each fs.
@@ -338,6 +341,9 @@ static struct attribute *btrfs_supported_feature_attrs[] = {
 #ifdef CONFIG_FS_VERITY
 	BTRFS_FEAT_ATTR_PTR(verity),
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+	BTRFS_FEAT_ATTR_PTR(encryption),
+#endif /* CONFIG_FS_ENCRYPTION */
 	NULL
 };
 
include/uapi/linux/btrfs.h +0 -0
index 9165154a274d..2f6a46e5f4ce 100644

include/uapi/linux/btrfs.h struct btrfs_ioctl_fs_info_args { · line 340

Quoted 6 lines
include/uapi/linux/btrfs.h +1 -0
@@ -335,6 +335,7 @@ struct btrfs_ioctl_fs_info_args {
 #define BTRFS_FEATURE_INCOMPAT_ZONED		(1ULL << 12)
 #define BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2	(1ULL << 13)
 #define BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE	(1ULL << 14)
+#define BTRFS_FEATURE_INCOMPAT_ENCRYPT		(1ULL << 15)
 #define BTRFS_FEATURE_INCOMPAT_SIMPLE_QUOTA	(1ULL << 16)
 #define BTRFS_FEATURE_INCOMPAT_REMAP_TREE	(1ULL << 17)

There seems to be an inconsistency where btrfs's fscrypt support depends on CONFIG_BTRFS_EXPERIMENTAL, but the support is advertised in sysfs regardless.

- Eric

#37 lore raw

Re: [PATCH v7 12/43] btrfs: add new FEATURE_INCOMPAT_ENCRYPT flag

Quoted 76 lines · Eric Biggers
Quoted 75 lines · Daniel Vacek

From: Omar Sandoval <[email protected]>

As encrypted files will be incompatible with older filesystem versions, new filesystems should be created with an incompat flag for fscrypt, which will gate access to the encryption ioctls.

---

v5: https://lore.kernel.org/linux-btrfs/ccbea52046c1dadbbef926bfc878cc23af952729.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/fs.h              | 3 ++-
 fs/btrfs/super.c           | 5 +++++
 fs/btrfs/sysfs.c           | 6 ++++++
 include/uapi/linux/btrfs.h | 1 +
 4 files changed, 14 insertions(+), 1 deletion(-)
fs/btrfs/fs.h +2 -1
index a4758d94b32e..dbdb73722c14 100644
@@ -322,7 +322,8 @@ enum {
      (BTRFS_FEATURE_INCOMPAT_SUPP_STABLE |   \
       BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE | \
       BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2 | \
-      BTRFS_FEATURE_INCOMPAT_REMAP_TREE)
+      BTRFS_FEATURE_INCOMPAT_REMAP_TREE |    \
+      BTRFS_FEATURE_INCOMPAT_ENCRYPT)
 
 #else
 
fs/btrfs/super.c +5 -0
index efaa0788c1fc..84df97363611 100644
@@ -2563,6 +2563,11 @@ static int __init btrfs_print_mod_info(void)
                      ", fsverity=yes"
 #else
                      ", fsverity=no"
+#endif
+#ifdef CONFIG_FS_ENCRYPTION
+                     ", fscrypt=yes"
+#else
+                     ", fscrypt=no"
 #endif
                      ;
 
fs/btrfs/sysfs.c +6 -0
index 0d14570c8bc2..3fe57843f902 100644
@@ -305,6 +305,9 @@ BTRFS_FEAT_ATTR_INCOMPAT(remap_tree, REMAP_TREE);
 #ifdef CONFIG_FS_VERITY
 BTRFS_FEAT_ATTR_COMPAT_RO(verity, VERITY);
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+BTRFS_FEAT_ATTR_INCOMPAT(encryption, ENCRYPT);
+#endif /* CONFIG_FS_ENCRYPTION */
 
 /*
  * Features which depend on feature bits and may differ between each fs.
@@ -338,6 +341,9 @@ static struct attribute *btrfs_supported_feature_attrs[] = {
 #ifdef CONFIG_FS_VERITY
      BTRFS_FEAT_ATTR_PTR(verity),
 #endif
+#ifdef CONFIG_FS_ENCRYPTION
+     BTRFS_FEAT_ATTR_PTR(encryption),
+#endif /* CONFIG_FS_ENCRYPTION */
      NULL
 };
 
Quoted 15 lines

include/uapi/linux/btrfs.h struct btrfs_ioctl_fs_info_args { · line 340

Quoted 11 lines
include/uapi/linux/btrfs.h +1 -0
index 9165154a274d..2f6a46e5f4ce 100644
@@ -335,6 +335,7 @@ struct btrfs_ioctl_fs_info_args {
 #define BTRFS_FEATURE_INCOMPAT_ZONED         (1ULL << 12)
 #define BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2        (1ULL << 13)
 #define BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE      (1ULL << 14)
+#define BTRFS_FEATURE_INCOMPAT_ENCRYPT               (1ULL << 15)
 #define BTRFS_FEATURE_INCOMPAT_SIMPLE_QUOTA  (1ULL << 16)
 #define BTRFS_FEATURE_INCOMPAT_REMAP_TREE    (1ULL << 17)

There seems to be an inconsistency where btrfs's fscrypt support depends on CONFIG_BTRFS_EXPERIMENTAL, but the support is advertised in sysfs regardless.

That is true. These should also depend on BTRFS_EXPERIMENTAL. Will amend. Thank you.

--nX

Quoted 1 line

- Eric

#38 lore raw

PATCH v7 13/43 btrfs: adapt readdir for encrypted and nokey names

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

Deleting an encrypted file must always be permitted, even if the user does not have the appropriate key. Therefore, for listing an encrypted directory, so-called 'nokey' names are provided, and these nokey names must be sufficient to look up and delete the appropriate encrypted files. See 'struct fscrypt_nokey_name' for more information on the format of these names.

The first part of supporting nokey names is allowing lookups by nokey name. Only a few entry points need to support these: deleting a directory, file, or subvolume -- each of these call fscrypt_setup_filename() with a '1' argument, indicating that the key is not required and therefore a nokey name may be provided. If a nokey name is provided, the fscrypt_name returned by fscrypt_setup_filename() will not have its disk_name field populated, but will have various other fields set.

This change alters the relevant codepaths to pass a complete fscrypt_name anywhere that it might contain a nokey name. When it does contain a nokey name, the first time the name is successfully matched to a stored name populates the disk name field of the fscrypt_name, allowing the caller to use the normal disk name codepaths afterward. Otherwise, the matching functionality is in close analogue to the function fscrypt_match_name().

Functions where most callers are providing a fscrypt_str are duplicated and adapted for a fscrypt_name, and functions where most callers are providing a fscrypt_name are changed to so require at all callsites.

---

v7 changes:
* Return true instead of error as suggested by Chris' AI review.
v6 changes:
* Adapt to changed prototypes.
* Return error directly instead of goto out and remove the label in
btrfs_inode_by_name().
v5: https://lore.kernel.org/linux-btrfs/52b31cd6e5c86f8fe3d08ce65bca5f40c3ce5c5a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/btrfs_inode.h   |   2 +-
 fs/btrfs/delayed-inode.c |  25 ++++++-
 fs/btrfs/delayed-inode.h |   5 +-
 fs/btrfs/dir-item.c      |  73 +++++++++++++++---
 fs/btrfs/dir-item.h      |  10 ++-
 fs/btrfs/extent_io.c     |  41 +++++++++++
 fs/btrfs/extent_io.h     |   3 +
 fs/btrfs/fscrypt.c       |  33 +++++++++
 fs/btrfs/fscrypt.h       |  18 +++++
 fs/btrfs/inode.c         | 155 ++++++++++++++++++++++++---------------
 fs/btrfs/root-tree.c     |   9 ++-
 fs/btrfs/root-tree.h     |   2 +-
 fs/btrfs/tree-log.c      |   3 +-
 13 files changed, 301 insertions(+), 78 deletions(-)
fs/btrfs/btrfs_inode.h +1 -1
index 81940b27b037..9499e15609b3 100644
@@ -560,7 +560,7 @@ struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry);
 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index);
 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
-		       const struct fscrypt_str *name);
+		       struct fscrypt_name *name);
 int btrfs_add_link(struct btrfs_trans_handle *trans,
 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
 		   const struct fscrypt_str *name, bool add_backref, u64 index);
fs/btrfs/delayed-inode.c +23 -2
index 09795439b9fb..097fe6ec60ba 100644
@@ -1784,7 +1784,9 @@ bool btrfs_should_delete_dir_index(const struct list_head *del_list, u64 index)
 /*
  * Read dir info stored in the delayed tree.
  */
-bool btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
+bool btrfs_readdir_delayed_dir_index(const struct inode *inode,
+				     struct fscrypt_str *fstr,
+				     struct dir_context *ctx,
 				     const struct list_head *ins_list)
 {
 	struct btrfs_dir_item *di;
@@ -1793,6 +1795,7 @@ bool btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
 	char *name;
 	int name_len;
 	unsigned char d_type;
+	size_t fstr_len = fstr->len;
 
 	/*
 	 * Changing the data of the delayed item is impossible. So
@@ -1819,7 +1822,25 @@ bool btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
 		d_type = fs_ftype_to_dtype(btrfs_dir_flags_to_ftype(di->type));
 		btrfs_disk_key_to_cpu(&location, &di->location);
 
-		over = !dir_emit(ctx, name, name_len, location.objectid, d_type);
+		if (di->type & BTRFS_FT_ENCRYPTED) {
+			int ret;
+			struct fscrypt_str iname = FSTR_INIT(name, name_len);
+
+			fstr->len = fstr_len;
+			/*
+			 * The hash is only used when the encryption key is not
+			 * available. But if we have delayed insertions, then we
+			 * must have the encryption key available or we wouldn't
+			 * have been able to create entries in the directory.
+			 * So, we don't calculate the hash.
+			 */
+			ret = fscrypt_fname_disk_to_usr(inode, 0, 0, &iname, fstr);
+			if (ret)
+				return true;
+			over = !dir_emit(ctx, fstr->name, fstr->len, location.objectid, d_type);
+		} else {
+			over = !dir_emit(ctx, name, name_len, location.objectid, d_type);
+		}
 
 		if (refcount_dec_and_test(&curr->refs))
 			kfree(curr);
fs/btrfs/delayed-inode.h +4 -1
index fc752863f89b..9bff11478632 100644
@@ -19,6 +19,7 @@
 #include <linux/ref_tracker.h>
 #include "ctree.h"
 
+struct fscrypt_str;
 struct btrfs_disk_key;
 struct btrfs_fs_info;
 struct btrfs_inode;
@@ -159,7 +160,9 @@ void btrfs_readdir_put_delayed_items(struct btrfs_inode *inode,
 				     struct list_head *ins_list,
 				     struct list_head *del_list);
 bool btrfs_should_delete_dir_index(const struct list_head *del_list, u64 index);
-bool btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
+bool btrfs_readdir_delayed_dir_index(const struct inode *inode,
+				     struct fscrypt_str *fstr,
+				     struct dir_context *ctx,
 				     const struct list_head *ins_list);
 
 /* Used during directory logging. */
fs/btrfs/dir-item.c +64 -9

122 lines not on this page · raw message

fs/btrfs/dir-item.h +9 -1
index e52174a8baf9..f89d12ee28a7 100644
@@ -7,6 +7,7 @@
 #include <linux/crc32c.h>
 
 struct fscrypt_str;
+struct fscrypt_name;
 struct btrfs_fs_info;
 struct btrfs_key;
 struct btrfs_path;
@@ -23,6 +24,11 @@ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
 					     struct btrfs_root *root,
 					     struct btrfs_path *path, u64 dir,
 					     const struct fscrypt_str *name, int mod);
+struct btrfs_dir_item *btrfs_lookup_dir_item_fname(
+			struct btrfs_trans_handle *trans,
+			struct btrfs_root *root,
+			struct btrfs_path *path, u64 dir,
+			struct fscrypt_name *name, int mod);
 struct btrfs_dir_item *btrfs_lookup_dir_index_item(
 			struct btrfs_trans_handle *trans,
 			struct btrfs_root *root,
@@ -30,7 +36,7 @@ struct btrfs_dir_item *btrfs_lookup_dir_index_item(
 			u64 index, const struct fscrypt_str *name, int mod);
 struct btrfs_dir_item *btrfs_search_dir_index_item(struct btrfs_root *root,
 			    struct btrfs_path *path, u64 dirid,
-			    const struct fscrypt_str *name);
+			    struct fscrypt_name *name);
 int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans,
 			      struct btrfs_root *root,
 			      struct btrfs_path *path,
@@ -48,6 +54,8 @@ struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans,
 struct btrfs_dir_item *btrfs_match_dir_item_name(const struct btrfs_path *path,
 						 const char *name,
 						 int name_len);
+struct btrfs_dir_item *btrfs_match_dir_item_fname(const struct btrfs_path *path,
+						  struct fscrypt_name *name);
 
 static inline u64 btrfs_name_hash(const char *name, int len)
 {
fs/btrfs/extent_io.c +41 -0

47 lines not on this page · raw message

fs/btrfs/extent_io.h +3 -0
index b310a5145cf6..8c7da2962cd4 100644
@@ -329,6 +329,9 @@ static inline bool extent_buffer_uptodate(const struct extent_buffer *eb)
 
 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
 			 unsigned long start, unsigned long len);
+void extent_buffer_sha256(const struct extent_buffer *eb,
+			  unsigned long start,
+			  unsigned long len, u8 *out);
 void read_extent_buffer(const struct extent_buffer *eb, void *dst,
 			unsigned long start,
 			unsigned long len);
fs/btrfs/fscrypt.c +33 -0
index c503f817cbe7..ae4f15762842 100644
@@ -1,17 +1,50 @@
 // SPDX-License-Identifier: GPL-2.0
 
 #include <linux/iversion.h>
+#include <crypto/sha2.h>
 #include "ctree.h"
 #include "accessors.h"
 #include "btrfs_inode.h"
 #include "disk-io.h"
+#include "ioctl.h"
 #include "fs.h"
 #include "fscrypt.h"
 #include "ioctl.h"
 #include "messages.h"
+#include "root-tree.h"
 #include "transaction.h"
 #include "xattr.h"
 
+/*
+ * This function is extremely similar to fscrypt_match_name() but uses an
+ * extent_buffer.
+ */
+bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
+			      struct extent_buffer *leaf, unsigned long de_name,
+			      u32 de_name_len)
+{
+	const struct fscrypt_nokey_name *nokey_name =
+		(const struct fscrypt_nokey_name *)fname->crypto_buf.name;
+	u8 digest[SHA256_DIGEST_SIZE];
+
+	if (likely(fname->disk_name.name)) {
+		if (de_name_len != fname->disk_name.len)
+			return false;
+		return !memcmp_extent_buffer(leaf, fname->disk_name.name, de_name, de_name_len);
+	}
+
+	if (de_name_len <= sizeof(nokey_name->bytes))
+		return false;
+
+	if (memcmp_extent_buffer(leaf, nokey_name->bytes, de_name, sizeof(nokey_name->bytes)))
+		return false;
+
+	extent_buffer_sha256(leaf, de_name + sizeof(nokey_name->bytes),
+			     de_name_len - sizeof(nokey_name->bytes), digest);
+
+	return !memcmp(digest, nokey_name->sha256, sizeof(digest));
+}
+
 static int btrfs_fscrypt_get_context(struct inode *inode, void *ctx, size_t len)
 {
 	struct btrfs_key key = {
fs/btrfs/fscrypt.h +18 -0
index 80adb7e56826..4e9c87290158 100644
@@ -4,9 +4,27 @@
 #define BTRFS_FSCRYPT_H
 
 #include <linux/fscrypt.h>
+#include "extent_map.h"
 
 #include "fs.h"
 
+#ifdef CONFIG_FS_ENCRYPTION
+bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
+			      struct extent_buffer *leaf,
+			      unsigned long de_name, u32 de_name_len);
+
+#else
+static inline bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
+					    struct extent_buffer *leaf,
+					    unsigned long de_name,
+					    u32 de_name_len)
+{
+	if (de_name_len != fname_len(fname))
+		return false;
+	return !memcmp_extent_buffer(leaf, fname->disk_name.name, de_name, de_name_len);
+}
+#endif /* CONFIG_FS_ENCRYPTION */
+
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
 
 #endif /* BTRFS_FSCRYPT_H */
fs/btrfs/inode.c +97 -58

377 lines not on this page · raw message

fs/btrfs/root-tree.c +5 -4
index d85a09ae1733..9f0f73200889 100644
@@ -10,6 +10,7 @@
 #include "messages.h"
 #include "transaction.h"
 #include "disk-io.h"
+#include "fscrypt.h"
 #include "qgroup.h"
 #include "space-info.h"
 #include "accessors.h"
@@ -328,7 +329,7 @@ int btrfs_del_root(struct btrfs_trans_handle *trans,
 
 int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 		       u64 ref_id, u64 dirid, u64 *sequence,
-		       const struct fscrypt_str *name)
+		       struct fscrypt_name *name)
 {
 	struct btrfs_root *tree_root = trans->fs_info->tree_root;
 	BTRFS_PATH_AUTO_FREE(path);
@@ -350,15 +351,15 @@ int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 	if (ret < 0) {
 		return ret;
 	} else if (ret == 0) {
+		u32 name_len;
 		leaf = path->nodes[0];
 		ref = btrfs_item_ptr(leaf, path->slots[0],
 				     struct btrfs_root_ref);
 		ptr = (unsigned long)(ref + 1);
+		name_len = btrfs_root_ref_name_len(leaf, ref);
 		if ((btrfs_root_ref_dirid(leaf, ref) != dirid) ||
-		    (btrfs_root_ref_name_len(leaf, ref) != name->len) ||
-		    memcmp_extent_buffer(leaf, name->name, ptr, name->len))
+		    !btrfs_fscrypt_match_name(name, leaf, ptr, name_len))
 			return -ENOENT;
-
 		*sequence = btrfs_root_ref_sequence(leaf, ref);
 
 		ret = btrfs_del_item(trans, tree_root, path);
fs/btrfs/root-tree.h +1 -1
index 8f5739e732b9..e85623dba952 100644
@@ -23,7 +23,7 @@ int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 		       const struct fscrypt_str *name);
 int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 		       u64 ref_id, u64 dirid, u64 *sequence,
-		       const struct fscrypt_str *name);
+		       struct fscrypt_name *name);
 int btrfs_del_root(struct btrfs_trans_handle *trans, const struct btrfs_key *key);
 int btrfs_insert_root(struct btrfs_trans_handle *trans, struct btrfs_root *root,
 		      const struct btrfs_key *key,
fs/btrfs/tree-log.c +2 -1
index e6cd475057db..81f0990d638b 100644
@@ -1045,9 +1045,10 @@ static int unlink_inode_for_log_replay(struct walk_control *wc,
 				       const struct fscrypt_str *name)
 {
 	struct btrfs_trans_handle *trans = wc->trans;
+	struct fscrypt_name fname = { .disk_name = *name, };
 	int ret;
 
-	ret = btrfs_unlink_inode(trans, dir, inode, name);
+	ret = btrfs_unlink_inode(trans, dir, inode, &fname);
 	if (ret) {
 		btrfs_abort_log_replay(wc, ret,
 	       "failed to unlink inode %llu parent dir %llu name %.*s root %llu",
Signature · 1 line
2.53.0
maintainer
#39 lore raw

Re: [PATCH v7 13/43] btrfs: adapt readdir for encrypted and nokey names

fs/btrfs/extent_io.c static void assert_eb_folio_uptodate(const struct extent_buffer *eb, int i) · line 4188

Quoted 5 lines · Daniel Vacek
fs/btrfs/extent_io.c +5 -0
+	/*
+	 * TODO: This should maybe be using the crypto API, not the fallback,
+	 * but fscrypt uses the fallback and this is only used in emulation of
+	 * fscrypt's buffer sha256 method.
+	 */

You can delete this TODO. The SHA-256 library functions just do the right thing now.

- Eric

#40 lore raw

Re: [PATCH v7 13/43] btrfs: adapt readdir for encrypted and nokey names

Quoted 9 lines · Eric Biggers

fs/btrfs/extent_io.c static void assert_eb_folio_uptodate(const struct extent_buffer *eb, int i) · line 4188

Quoted 5 lines · Daniel Vacek
fs/btrfs/extent_io.c +5 -0
+     /*
+      * TODO: This should maybe be using the crypto API, not the fallback,
+      * but fscrypt uses the fallback and this is only used in emulation of
+      * fscrypt's buffer sha256 method.
+      */

You can delete this TODO. The SHA-256 library functions just do the right thing now.

That's great! Thanks.

While at it, there was also a BUG for folios of order > 0. So I cleaned up the whole function a bit.

--nX

Quoted 1 line

- Eric

#41 lore raw

PATCH v7 14/43 btrfs: handle nokey names

In reply to Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

For encrypted or unencrypted names, we calculate the offset for the dir item by hashing the name for the dir item. However, this doesn't work for a long nokey name, where we do not have the complete ciphertext. Instead, fscrypt stores the filesystem-provided hash in the nokey name, and we can extract it from the fscrypt_name structure in such a case.

Additionally, for nokey names, if we find the nokey name on disk we can update the fscrypt_name with the disk name, so add that to searching for diritems.

---

v7 changes:
* Fix a memory leak as found by Chris' AI review.
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/a7e3aec8ec03814b4baa1d929ae8fb77f13c17d2.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/dir-item.c | 43 +++++++++++++++++++++++++++++++++++++++++--
 fs/btrfs/fscrypt.c  | 27 +++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h  | 11 +++++++++++
 3 files changed, 79 insertions(+), 2 deletions(-)
fs/btrfs/dir-item.c +41 -2
index 1525b945646b..09ce1b85af74 100644
@@ -228,6 +228,35 @@ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
 	return di;
 }
 
+/*
+ * If appropriate, populate the disk name for a fscrypt_name looked up without
+ * a key.
+ *
+ * @path:	The path to the extent buffer in which the name was found.
+ * @di:		The dir item corresponding.
+ * @fname:	The fscrypt_name to perhaps populate.
+ *
+ * Returns: 0 if the name is already populated or the dir item doesn't exist
+ * or the name was successfully populated, else an error code.
+ */
+static int ensure_disk_name_from_dir_item(struct btrfs_path *path,
+					  struct btrfs_dir_item *di,
+					  struct fscrypt_name *name)
+{
+	int ret;
+
+	if (name->disk_name.name || !di)
+		return 0;
+
+	ret = btrfs_fscrypt_get_disk_name(path->nodes[0], di, &name->disk_name);
+	if (ret)
+		return ret;
+
+	name->crypto_buf.name = name->disk_name.name;
+	name->crypto_buf.len  = name->disk_name.len;
+	return 0;
+}
+
 /*
  * Lookup for a directory item by fscrypt_name.
  *
@@ -254,8 +283,11 @@ struct btrfs_dir_item *btrfs_lookup_dir_item_fname(struct btrfs_trans_handle *tr
 
 	key.objectid = dir;
 	key.type = BTRFS_DIR_ITEM_KEY;
-	key.offset = btrfs_name_hash(name->disk_name.name, name->disk_name.len);
-	/* XXX get the right hash for no-key names */
+
+	if (!name->disk_name.name)
+		key.offset = name->hash | ((u64)name->minor_hash << 32);
+	else
+		key.offset = btrfs_name_hash(name->disk_name.name, name->disk_name.len);
 
 	ret = btrfs_search_slot(trans, root, &key, path, mod, -mod);
 	if (ret == 0)
@@ -263,6 +295,8 @@ struct btrfs_dir_item *btrfs_lookup_dir_item_fname(struct btrfs_trans_handle *tr
 
 	if (ret == -ENOENT || (di && IS_ERR(di) && PTR_ERR(di) == -ENOENT))
 		return NULL;
+	if (ret == 0)
+		ret = ensure_disk_name_from_dir_item(path, di, name);
 	if (ret < 0)
 		di = ERR_PTR(ret);
 
@@ -371,7 +405,12 @@ btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path,
 	btrfs_for_each_slot(root, &key, &key, path, ret) {
 		if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY)
 			break;
+
 		di = btrfs_match_dir_item_fname(path, name);
+		if (di)
+			ret = ensure_disk_name_from_dir_item(path, di, name);
+		if (ret)
+			break;
 		if (di)
 			return di;
 	}
fs/btrfs/fscrypt.c +27 -0
index ae4f15762842..2fa33e69083d 100644
@@ -15,6 +15,33 @@
 #include "transaction.h"
 #include "xattr.h"
 
+/*
+ * From a given location in a leaf, read a name into a qstr (usually a
+ * fscrypt_name's disk_name), allocating the required buffer. Used for
+ * nokey names.
+ */
+int btrfs_fscrypt_get_disk_name(struct extent_buffer *leaf,
+				struct btrfs_dir_item *dir_item,
+				struct fscrypt_str *name)
+{
+	unsigned long de_name_len = btrfs_dir_name_len(leaf, dir_item);
+	unsigned long de_name = (unsigned long)(dir_item + 1);
+	/*
+	 * For no-key names, we use this opportunity to find the disk
+	 * name, so future searches don't need to deal with nokey names
+	 * and we know what the encrypted size is.
+	 */
+	name->name = kmalloc(de_name_len, GFP_NOFS);
+
+	if (!name->name)
+		return -ENOMEM;
+
+	read_extent_buffer(leaf, name->name, de_name, de_name_len);
+
+	name->len = de_name_len;
+	return 0;
+}
+
 /*
  * This function is extremely similar to fscrypt_match_name() but uses an
  * extent_buffer.
fs/btrfs/fscrypt.h +11 -0
index 4e9c87290158..c5cdc27f943c 100644
@@ -9,11 +9,22 @@
 #include "fs.h"
 
 #ifdef CONFIG_FS_ENCRYPTION
+int btrfs_fscrypt_get_disk_name(struct extent_buffer *leaf,
+				struct btrfs_dir_item *di,
+				struct fscrypt_str *qstr);
+
 bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
 			      struct extent_buffer *leaf,
 			      unsigned long de_name, u32 de_name_len);
 
 #else
+static inline int btrfs_fscrypt_get_disk_name(struct extent_buffer *leaf,
+					      struct btrfs_dir_item *di,
+					      struct fscrypt_str *qstr)
+{
+	return 0;
+}
+
 static inline bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
 					    struct extent_buffer *leaf,
 					    unsigned long de_name,
Signature · 1 line
2.53.0
#42 lore raw

PATCH v7 15/43 btrfs: implement fscrypt ioctls

In reply to Daniel Vacek

From: Omar Sandoval <[email protected]>

These ioctls allow encryption to actually be used.

The set_encryption_policy ioctl is the thing which actually turns on encryption, and therefore sets the ENCRYPT flag in the superblock. This prevents the filesystem from being loaded on older kernels.

fscrypt provides CONFIG_FS_ENCRYPTION-disabled versions of all these functions which just return -EOPNOTSUPP, so the ioctls don't need to be compiled out if CONFIG_FS_ENCRYPTION isn't enabled.

We could instead gate this ioctl on the superblock having the flag set, if we wanted to require mkfs with the encrypt flag in order to have a filesystem with any encryption.

Since this is a disk format change and is currently in development, gate the fscrypt ioctls for btrfs behind BTRFS_EXPERIMENTAL.

---

No changes in v7.
v6 changes:
* Squash in https://lore.kernel.org/linux-btrfs/5134ab713b080f78b90eae46671596f72bbb1815.1706116485.git.josef@toxicpanda.com/
("btrfs: gate encryption behind BTRFS_DEBUG") and change it to
BTRFS_EXPERIMENTAL as suggested by Dave.
v5: https://lore.kernel.org/linux-btrfs/6182b77868d0c9f9447641f869658ef017c1f467.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/ioctl.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
fs/btrfs/ioctl.c +29 -0
index 6a37dd3cc5ee..2e0b79f41197 100644
@@ -5159,6 +5159,35 @@ long btrfs_ioctl(struct file *file, unsigned int
 		return btrfs_ioctl_get_fslabel(fs_info, argp);
 	case FS_IOC_SETFSLABEL:
 		return btrfs_ioctl_set_fslabel(file, argp);
+#ifdef CONFIG_BTRFS_EXPERIMENTAL
+	case FS_IOC_SET_ENCRYPTION_POLICY: {
+		if (!IS_ENABLED(CONFIG_FS_ENCRYPTION))
+			return -EOPNOTSUPP;
+		if (sb_rdonly(fs_info->sb))
+			return -EROFS;
+		/*
+		 *  If we crash before we commit, nothing encrypted could have
+		 * been written so it doesn't matter whether the encrypted
+		 * state persists.
+		 */
+		btrfs_set_fs_incompat(fs_info, ENCRYPT);
+		return fscrypt_ioctl_set_policy(file, (const void __user *)arg);
+	}
+	case FS_IOC_GET_ENCRYPTION_POLICY:
+		return fscrypt_ioctl_get_policy(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_POLICY_EX:
+		return fscrypt_ioctl_get_policy_ex(file, (void __user *)arg);
+	case FS_IOC_ADD_ENCRYPTION_KEY:
+		return fscrypt_ioctl_add_key(file, (void __user *)arg);
+	case FS_IOC_REMOVE_ENCRYPTION_KEY:
+		return fscrypt_ioctl_remove_key(file, (void __user *)arg);
+	case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
+		return fscrypt_ioctl_remove_key_all_users(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
+		return fscrypt_ioctl_get_key_status(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_NONCE:
+		return fscrypt_ioctl_get_nonce(file, (void __user *)arg);
+#endif /* CONFIG_BTRFS_EXPERIMENTAL */
 	case FITRIM:
 		return btrfs_ioctl_fitrim(fs_info, argp);
 	case BTRFS_IOC_SNAP_CREATE:
Signature · 1 line
2.53.0
maintainer
#43 lore raw

Re: [PATCH v7 15/43] btrfs: implement fscrypt ioctls

Quoted 27 lines · Daniel Vacek
fs/btrfs/ioctl.c +19 -0
index 6a37dd3cc5ee..2e0b79f41197 100644
@@ -5159,6 +5159,35 @@ long btrfs_ioctl(struct file *file, unsigned int
 		return btrfs_ioctl_get_fslabel(fs_info, argp);
 	case FS_IOC_SETFSLABEL:
 		return btrfs_ioctl_set_fslabel(file, argp);
+#ifdef CONFIG_BTRFS_EXPERIMENTAL
+	case FS_IOC_SET_ENCRYPTION_POLICY: {
+		if (!IS_ENABLED(CONFIG_FS_ENCRYPTION))
+			return -EOPNOTSUPP;
+		if (sb_rdonly(fs_info->sb))
+			return -EROFS;
+		/*
+		 *  If we crash before we commit, nothing encrypted could have
+		 * been written so it doesn't matter whether the encrypted
+		 * state persists.
+		 */
+		btrfs_set_fs_incompat(fs_info, ENCRYPT);
+		return fscrypt_ioctl_set_policy(file, (const void __user *)arg);
+	}
+	case FS_IOC_GET_ENCRYPTION_POLICY:
+		return fscrypt_ioctl_get_policy(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_POLICY_EX:
+		return fscrypt_ioctl_get_policy_ex(file, (void __user *)arg);
+	case FS_IOC_ADD_ENCRYPTION_KEY:

fs/btrfs/ioctl.c long btrfs_ioctl(struct file *file, unsigned int · line 5190

Quoted 10 lines
fs/btrfs/ioctl.c +10 -0
+		return fscrypt_ioctl_add_key(file, (void __user *)arg);
+	case FS_IOC_REMOVE_ENCRYPTION_KEY:
+		return fscrypt_ioctl_remove_key(file, (void __user *)arg);
+	case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
+		return fscrypt_ioctl_remove_key_all_users(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
+		return fscrypt_ioctl_get_key_status(file, (void __user *)arg);
+	case FS_IOC_GET_ENCRYPTION_NONCE:
+		return fscrypt_ioctl_get_nonce(file, (void __user *)arg);
+#endif /* CONFIG_BTRFS_EXPERIMENTAL */

Are you sure you want to auto-enable the "encrypt" feature flag like this? It doesn't even require a privilege.

It's also only in FS_IOC_SET_ENCRYPTION_POLICY, so this doesn't work in cases where users add a key first.

- Eric

#44 lore raw

Re: [PATCH v7 15/43] btrfs: implement fscrypt ioctls

Quoted 42 lines · Eric Biggers
Quoted 27 lines · Daniel Vacek
fs/btrfs/ioctl.c +19 -0
index 6a37dd3cc5ee..2e0b79f41197 100644
@@ -5159,6 +5159,35 @@ long btrfs_ioctl(struct file *file, unsigned int
              return btrfs_ioctl_get_fslabel(fs_info, argp);
      case FS_IOC_SETFSLABEL:
              return btrfs_ioctl_set_fslabel(file, argp);
+#ifdef CONFIG_BTRFS_EXPERIMENTAL
+     case FS_IOC_SET_ENCRYPTION_POLICY: {
+             if (!IS_ENABLED(CONFIG_FS_ENCRYPTION))
+                     return -EOPNOTSUPP;
+             if (sb_rdonly(fs_info->sb))
+                     return -EROFS;
+             /*
+              *  If we crash before we commit, nothing encrypted could have
+              * been written so it doesn't matter whether the encrypted
+              * state persists.
+              */
+             btrfs_set_fs_incompat(fs_info, ENCRYPT);
+             return fscrypt_ioctl_set_policy(file, (const void __user *)arg);
+     }
+     case FS_IOC_GET_ENCRYPTION_POLICY:
+             return fscrypt_ioctl_get_policy(file, (void __user *)arg);
+     case FS_IOC_GET_ENCRYPTION_POLICY_EX:
+             return fscrypt_ioctl_get_policy_ex(file, (void __user *)arg);
+     case FS_IOC_ADD_ENCRYPTION_KEY:

fs/btrfs/ioctl.c long btrfs_ioctl(struct file *file, unsigned int · line 5190

Quoted 10 lines
fs/btrfs/ioctl.c +10 -0
+             return fscrypt_ioctl_add_key(file, (void __user *)arg);
+     case FS_IOC_REMOVE_ENCRYPTION_KEY:
+             return fscrypt_ioctl_remove_key(file, (void __user *)arg);
+     case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
+             return fscrypt_ioctl_remove_key_all_users(file, (void __user *)arg);
+     case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
+             return fscrypt_ioctl_get_key_status(file, (void __user *)arg);
+     case FS_IOC_GET_ENCRYPTION_NONCE:
+             return fscrypt_ioctl_get_nonce(file, (void __user *)arg);
+#endif /* CONFIG_BTRFS_EXPERIMENTAL */

Are you sure you want to auto-enable the "encrypt" feature flag like this? It doesn't even require a privilege.

Quoted 2 lines

It's also only in FS_IOC_SET_ENCRYPTION_POLICY, so this doesn't work in cases where users add a key first.

The filesystem is flagged with encryption once the first file is encrypted. Adding a key does not change any on-disk data if I'm not mistaken.

Though I'm open to suggestions.

--nX

Quoted 1 line

- Eric

#45 lore raw

PATCH v7 16/43 btrfs: select encryption dependencies if FS_ENCRYPTION

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We need this to make sure the appropriate encryption algorithms are turned on in our config if we have FS_ENCRYPTION enabled, and additionally we only support inline encryption with the fallback block crypto, so we need to make sure we pull in those dependencies.

---

v7 changes:
* Alsos depend on BLK_INLINE_ENCRYPTION as suggested by Chris' AI review.
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/396f5067b2551a9f2de4b439509e1a285985d358.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/Kconfig | 4 ++++
 1 file changed, 4 insertions(+)
fs/btrfs/Kconfig +4 -0
index 5e75438e0b73..3a41392135da 100644
@@ -16,6 +16,10 @@ config BTRFS_FS
 	select RAID6_PQ
 	select XOR_BLOCKS
 	select XXHASH
+	select FS_ENCRYPTION_ALGS if FS_ENCRYPTION
+	select FS_ENCRYPTION_INLINE_CRYPT if FS_ENCRYPTION
+	select BLK_INLINE_ENCRYPTION if FS_ENCRYPTION
+	select BLK_INLINE_ENCRYPTION_FALLBACK if FS_ENCRYPTION
 	depends on PAGE_SIZE_LESS_THAN_256KB
 
 	help
Signature · 1 line
2.53.0
#46 lore raw

PATCH v7 17/43 btrfs: add get_devices hook for fscrypt

In reply to Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

Since extent encryption requires inline encryption, even though we expect to use the inlinecrypt software fallback most of the time, we need to enumerate all the devices in use by btrfs.

---

v5: https://lore.kernel.org/linux-btrfs/47ff044fae65cb2b06a6bb6ffc91027511c4d1f4.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/fscrypt.c | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
fs/btrfs/fscrypt.c +36 -0
index 2fa33e69083d..1d29cfa7037c 100644
@@ -12,7 +12,9 @@
 #include "ioctl.h"
 #include "messages.h"
 #include "root-tree.h"
+#include "super.h"
 #include "transaction.h"
+#include "volumes.h"
 #include "xattr.h"
 
 /*
@@ -177,10 +179,44 @@ static bool btrfs_fscrypt_empty_dir(struct inode *inode)
 	return inode->i_size == BTRFS_EMPTY_DIR_SIZE;
 }
 
+static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb,
+						       unsigned int *num_devs)
+{
+	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	int nr_devices = fs_devices->open_devices;
+	struct block_device **devs;
+	struct btrfs_device *device;
+	int i = 0;
+
+	devs = kmalloc_array(nr_devices, sizeof(*devs), GFP_NOFS | GFP_NOWAIT);
+	if (!devs)
+		return ERR_PTR(-ENOMEM);
+
+	rcu_read_lock();
+	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
+		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) ||
+		    !device->bdev ||
+		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
+			continue;
+
+		devs[i++] = device->bdev;
+
+		if (i >= nr_devices)
+			break;
+
+	}
+	rcu_read_unlock();
+
+	*num_devs = i;
+	return devs;
+}
+
 const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.inode_info_offs = (int)offsetof(struct btrfs_inode, i_crypt_info) -
 			   (int)offsetof(struct btrfs_inode, vfs_inode),
 	.get_context = btrfs_fscrypt_get_context,
 	.set_context = btrfs_fscrypt_set_context,
 	.empty_dir = btrfs_fscrypt_empty_dir,
+	.get_devices = btrfs_fscrypt_get_devices,
 };
Signature · 1 line
2.53.0
#47 lore raw

Re: [PATCH v7 17/43] btrfs: add get_devices hook for fscrypt

Quoted 5 lines · Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

Since extent encryption requires inline encryption, even though we expect to use the inlinecrypt software fallback most of the time, we need to enumerate all the devices in use by btrfs.

How does this handled adding/removing devices at runtime?

#48 lore raw

Re: [PATCH v7 17/43] btrfs: add get_devices hook for fscrypt

Quoted 8 lines · Christoph Hellwig
Quoted 5 lines · Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

Since extent encryption requires inline encryption, even though we expect to use the inlinecrypt software fallback most of the time, we need to enumerate all the devices in use by btrfs.

How does this handled adding/removing devices at runtime?

When called, this callback returns the list of bdevs opened by the given superblock. If devices are added or removed, this function returns a different list.
In other words it always returns a valid list.

This is called from fscrypt_get_devices(), which is called from fscrypt_select_encryption_impl() or fscrypt_prepare_inline_crypt_key() or fscrypt_destroy_inline_crypt_key(). All these functions walk the returned list and discard it immediately afterwards.

Note that with btrfs at this point we're only using the inline crypto fallback. Is there any particular reason you asked this question?

--nX

#49 lore raw

Re: [PATCH v7 17/43] btrfs: add get_devices hook for fscrypt

Quoted 7 lines · Daniel Vacek
Quoted 1 line

How does this handled adding/removing devices at runtime?

When called, this callback returns the list of bdevs opened by the given superblock. If devices are added or removed, this function returns a different list.
In other words it always returns a valid list.

Quoted 8 lines

This is called from fscrypt_get_devices(), which is called from fscrypt_select_encryption_impl() or fscrypt_prepare_inline_crypt_key() or fscrypt_destroy_inline_crypt_key(). All these functions walk the returned list and discard it immediately afterwards.

Note that with btrfs at this point we're only using the inline crypto fallback. Is there any particular reason you asked this question?

Well, assume you have a single device fs, and then you add a device later, you will not get the blk_crypto_config_supported call for this device, and it will not be taken into account.

Now can btrfs even support hardware inline encryption? The way the bio processing is special cased I somehow doubt it. But the concept of a static device list just doesn't work for btrfs, so I think the fscrypt side of this will need refactoring not to rely on it. If we never support hardware inline encryption on such dynamic file systems that would be relative easy, if we need to support that case things might get a lot more complicated.

#50 lore raw

Re: [PATCH v7 17/43] btrfs: add get_devices hook for fscrypt

Quoted 14 lines · Christoph Hellwig
Quoted 13 lines · Daniel Vacek
Quoted 1 line

How does this handled adding/removing devices at runtime?

When called, this callback returns the list of bdevs opened by the given superblock. If devices are added or removed, this function returns a different list.
In other words it always returns a valid list.

This is called from fscrypt_get_devices(), which is called from fscrypt_select_encryption_impl() or fscrypt_prepare_inline_crypt_key() or fscrypt_destroy_inline_crypt_key(). All these functions walk the returned list and discard it immediately afterwards.

Quoted 6 lines
Quoted 2 lines

Note that with btrfs at this point we're only using the inline crypto fallback. Is there any particular reason you asked this question?

Well, assume you have a single device fs, and then you add a device later, you will not get the blk_crypto_config_supported call for this device, and it will not be taken into account.

This function is called from fscrypt_prepare_new_inode() from btrfs_new_inode_prepare() as well as from many other places. It looks quite OK to me and I can also confirm this with tracing. Using the following bpftrace script:

```
fr:fscrypt_get_devices {
//      $num_devs = args.num_devs[0];
        $num_devs = ((uint32 *)args.num_devs)[0];
//      if ($num_devs < 2) { return; }
        printf("%s()\t\t\t(%4d %13s[%d])\tnum_devs %d\n", func,
                cpu, curtask->comm, curtask->pid, $num_devs);
}

f:blk_crypto_config_supported {
        printf("%s()\t\t(%4d %13s[%d])\tbdev %18p\n", func,
                cpu, curtask->comm, curtask->pid, args.bdev);
}
```

... and mounting an encrypted FS, then adding an additional device, like this:

```
$ mount /dev/vdb /mnt/scratch; \
echo -ne $TEST_RAW_KEY | xfs_io -c add_enckey /mnt/scratch; \
touch /mnt/scratch/dir/foo; \
btrfs device add /dev/vdc /mnt/scratch; \
touch /mnt/scratch/dir/bar
```

I'm getting this:

```
fscrypt_get_devices()            (   5         touch[26840])    num_devs 1
blk_crypto_config_supported()    (   5         touch[26840])    bdev
0xffff88a9c33fc880
fscrypt_get_devices()            (   5         touch[26840])    num_devs 1
fscrypt_get_devices()            (   5         touch[26844])    num_devs 2
blk_crypto_config_supported()    (   5         touch[26844])    bdev
0xffff88a9c3262b80
blk_crypto_config_supported()    (   5         touch[26844])    bdev
0xffff88a9c33fc880
fscrypt_get_devices()            (   5         touch[26844])    num_devs 2
```

Here you can see the newly added device is being considered.

Moreover btrfs only supports the fallback encryption due to the need to compute the checksums of encrypted data stored on the device.

Quoted 7 lines

Now can btrfs even support hardware inline encryption? The way the bio processing is special cased I somehow doubt it. But the concept of a static device list just doesn't work for btrfs, so I think the fscrypt side of this will need refactoring not to rely on it. If we never support hardware inline encryption on such dynamic file systems that would be relative easy, if we need to support that case things might get a lot more complicated.

Yeah, this depends. If the device or fscrypt could return the checksum to the FS, btrfs could use the inline HW encryption. Note that the checksum must also be one that btrfs supports.
Otherwise we need to get the encrypted data to compute the checksum ourselves. That is precisely why only fallback encryption is currently supported. And it's where the FS callback hook is used to compute the checksum.

--nX

#51 lore raw

PATCH v7 18/43 btrfs: set file extent encryption excplicitly

In reply to Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

This puts the long-preserved 1-byte encryption field to work, storing whether the extent is encrypted. Update the tree-checker to allow for the encryption bit to be set to our valid types.

---

v5: https://lore.kernel.org/linux-btrfs/1bf1cb768bc8bc54b3855e271412077c60f23c50.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/accessors.h            | 2 ++
 fs/btrfs/inode.c                | 6 ++++--
 fs/btrfs/tree-checker.c         | 8 +++++---
 fs/btrfs/tree-log.c             | 2 ++
 include/uapi/linux/btrfs_tree.h | 8 +++++++-
 5 files changed, 20 insertions(+), 6 deletions(-)
fs/btrfs/accessors.h +2 -0
index 8938357fcb40..09ed68fa2041 100644
@@ -907,6 +907,8 @@ BTRFS_SETGET_STACK_FUNCS(stack_file_extent_disk_num_bytes,
 			 struct btrfs_file_extent_item, disk_num_bytes, 64);
 BTRFS_SETGET_STACK_FUNCS(stack_file_extent_compression,
 			 struct btrfs_file_extent_item, compression, 8);
+BTRFS_SETGET_STACK_FUNCS(stack_file_extent_encryption,
+			 struct btrfs_file_extent_item, encryption, 8);
 
 
 BTRFS_SETGET_FUNCS(file_extent_type, struct btrfs_file_extent_item, type, 8);
fs/btrfs/inode.c +4 -2
index 0bae9179eb12..bc2460292e43 100644
@@ -3161,7 +3161,8 @@ static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
 	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 */
+	btrfs_set_stack_file_extent_encryption(&stack_fi, BTRFS_ENCRYPTION_NONE);
+	/* Other encoding is reserved and always 0 */
 
 	/*
 	 * For delalloc, when completing an ordered extent we update the inode's
@@ -9280,7 +9281,8 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
-	/* Encryption and other encoding is reserved and all 0 */
+	btrfs_set_stack_file_extent_encryption(&stack_fi, BTRFS_ENCRYPTION_NONE);
+	/* Other encoding is reserved and always 0 */
 
 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
 	if (ret < 0)
fs/btrfs/tree-checker.c +5 -3
index 1f15d0793a9c..61987353b138 100644
@@ -213,6 +213,7 @@ static int check_extent_data_item(struct extent_buffer *leaf,
 	u32 sectorsize = fs_info->sectorsize;
 	u32 item_size = btrfs_item_size(leaf, slot);
 	u64 extent_end;
+	u8 policy;
 
 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
 		file_extent_err(leaf, slot,
@@ -264,10 +265,11 @@ static int check_extent_data_item(struct extent_buffer *leaf,
 			BTRFS_NR_COMPRESS_TYPES - 1);
 		return -EUCLEAN;
 	}
-	if (unlikely(btrfs_file_extent_encryption(leaf, fi))) {
+	policy = btrfs_file_extent_encryption(leaf, fi);
+	if (unlikely(policy >= BTRFS_NR_ENCRYPTION_TYPES)) {
 		file_extent_err(leaf, slot,
-			"invalid encryption for file extent, have %u expect 0",
-			btrfs_file_extent_encryption(leaf, fi));
+			"invalid encryption for file extent, have %u expect range [0, %u]",
+			policy, BTRFS_NR_ENCRYPTION_TYPES - 1);
 		return -EUCLEAN;
 	}
 	if (btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE) {
fs/btrfs/tree-log.c +2 -0
index 81f0990d638b..3229a60bffb7 100644
@@ -5150,6 +5150,7 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	u64 block_start = btrfs_extent_map_block_start(em);
 	u64 block_len;
 	int ret;
+	u8 encryption = BTRFS_ENCRYPTION_NONE;
 
 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
 	if (em->flags & EXTENT_FLAG_PREALLOC)
@@ -5171,6 +5172,7 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
 	btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
 	btrfs_set_stack_file_extent_compression(&fi, compress_type);
+	btrfs_set_stack_file_extent_encryption(&fi, encryption);
 
 	ret = log_extent_csums(trans, inode, log, em, ctx);
 	if (ret)
include/uapi/linux/btrfs_tree.h +7 -1
index 3cec245268e7..7b1922c3265a 100644
@@ -1107,8 +1107,14 @@ struct btrfs_file_extent_item {
 	 * but not for stat.
 	 */
 	__u8 compression;
+
+	/*
+	 * Type of encryption in use. Unencrypted value is 0.
+	 */
 	__u8 encryption;
-	__le16 other_encoding; /* spare for later use */
+
+	/* spare for later use */
+	__le16 other_encoding;
 
 	/* are we inline data or a real extent? */
 	__u8 type;
Signature · 1 line
2.53.0
#52 lore raw

PATCH v7 19/43 btrfs: add fscrypt_info and encryption_type to extent_map

In reply to Daniel Vacek

From: Sweet Tea Dorminy <[email protected]>

Each extent_map will end up with a pointer to its associated fscrypt_info if any, which should have the same lifetime as the extent_map. We are also going to need to track the encryption_type for the file extent items. Add the fscrypt_info to the extent_map and the subsequent code for transferring it in the split and merge cases as well as the code necessary to free them. A future patch will add the code to load them as appropriate.

---

v5: https://lore.kernel.org/linux-btrfs/9818cd4134d048d2d641b9b8ae10be6c6af51956.1706116485.git.josef@toxicpanda.com/
* No significant changes since. Just add some btrfs_ prefixes even
to static functions in extent map header file to match the style.

---
 fs/btrfs/extent_map.c | 32 +++++++++++++++++++++++++++++---
 fs/btrfs/extent_map.h | 16 ++++++++++++++++
 fs/btrfs/file-item.c  |  1 +
 fs/btrfs/inode.c      |  1 +
 4 files changed, 47 insertions(+), 3 deletions(-)
fs/btrfs/extent_map.c +29 -3
index 61fe262667ee..d13fb42dafab 100644
@@ -59,6 +59,7 @@ struct extent_map *btrfs_alloc_extent_map(void)
 
 static void free_extent_map(struct extent_map *em)
 {
+	fscrypt_put_extent_info(em->fscrypt_info);
 	kmem_cache_free(extent_map_cache, em);
 }
 
@@ -99,12 +100,24 @@ void btrfs_free_extent_map_safe(struct extent_map_tree *tree,
 	if (!em)
 		return;
 
-	if (refcount_dec_and_test(&em->refs)) {
-		WARN_ON(btrfs_extent_map_in_tree(em));
-		WARN_ON(!list_empty(&em->list));
+	if (!refcount_dec_and_test(&em->refs))
+		return;
+
+	WARN_ON(btrfs_extent_map_in_tree(em));
+	WARN_ON(!list_empty(&em->list));
+
+	/*
+	 * We could take a lock freeing the fscrypt_info, so add this to the
+	 * list of freed_extents to be freed later.
+	 */
+	if (em->fscrypt_info) {
 		list_add_tail(&em->free_list, &tree->freed_extents);
 		set_bit(EXTENT_MAP_TREE_PENDING_FREES, &tree->flags);
+		return;
 	}
+
+	/* Nothing scary here, just free the object. */
+	free_extent_map(em);
 }
 
 /*
@@ -291,6 +304,10 @@ static bool can_merge_extent_map(const struct extent_map *em)
 	if (!list_empty(&em->list))
 		return false;
 
+	/* We can't merge encrypted extents. */
+	if (em->fscrypt_info)
+		return false;
+
 	return true;
 }
 
@@ -311,6 +328,10 @@ static bool mergeable_maps(const struct extent_map *prev, const struct extent_ma
 	if (next->disk_bytenr < EXTENT_MAP_LAST_BYTE - 1)
 		return btrfs_extent_map_block_start(next) == extent_map_block_end(prev);
 
+	/* Don't merge adjacent encrypted maps. */
+	if (prev->fscrypt_info || next->fscrypt_info)
+		return false;
+
 	/* HOLES and INLINE extents. */
 	return next->disk_bytenr == prev->disk_bytenr;
 }
@@ -977,6 +998,7 @@ void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end,
 
 			split->generation = gen;
 			split->flags = flags;
+			split->fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
 			replace_extent_mapping(inode, em, split, modified);
 			btrfs_free_extent_map(split);
 			split = split2;
@@ -1005,6 +1027,7 @@ void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end,
 				split->ram_bytes = split->len;
 			}
 
+			split->fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
 			if (btrfs_extent_map_in_tree(em)) {
 				replace_extent_mapping(inode, em, split, modified);
 			} else {
@@ -1163,6 +1186,7 @@ int btrfs_split_extent_map(struct btrfs_inode *inode, u64 start, u64 len, u64 pr
 	split_pre->ram_bytes = split_pre->len;
 	split_pre->flags = flags;
 	split_pre->generation = em->generation;
+	split_pre->fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
 
 	replace_extent_mapping(inode, em, split_pre, true);
 
@@ -1180,6 +1204,8 @@ int btrfs_split_extent_map(struct btrfs_inode *inode, u64 start, u64 len, u64 pr
 	split_mid->ram_bytes = split_mid->len;
 	split_mid->flags = flags;
 	split_mid->generation = em->generation;
+	split_mid->fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
+
 	add_extent_mapping(inode, split_mid, true);
 
 	/* Once for us */
fs/btrfs/extent_map.h +16 -0
index a962012be1c3..a0d5be758e7e 100644
@@ -24,6 +24,7 @@ enum {
 	ENUM_BIT(EXTENT_FLAG_COMPRESS_ZLIB),
 	ENUM_BIT(EXTENT_FLAG_COMPRESS_LZO),
 	ENUM_BIT(EXTENT_FLAG_COMPRESS_ZSTD),
+	ENUM_BIT(EXTENT_FLAG_ENCRYPT_FSCRYPT),
 	/* pre-allocated extent */
 	ENUM_BIT(EXTENT_FLAG_PREALLOC),
 	/* Logging this extent */
@@ -96,6 +97,7 @@ struct extent_map {
 	u64 generation;
 	u32 flags;
 	refcount_t refs;
+	struct fscrypt_extent_info *fscrypt_info;
 	struct list_head list;
 	struct list_head free_list;
 };
@@ -114,6 +116,20 @@ struct extent_map_tree {
 
 struct btrfs_inode;
 
+static inline void btrfs_extent_map_set_encryption(struct extent_map *em,
+					     enum btrfs_encryption_type type)
+{
+	if (type == BTRFS_ENCRYPTION_FSCRYPT)
+		em->flags |= EXTENT_FLAG_ENCRYPT_FSCRYPT;
+}
+
+static inline enum btrfs_encryption_type btrfs_extent_map_encryption(const struct extent_map *em)
+{
+	if (em->flags & EXTENT_FLAG_ENCRYPT_FSCRYPT)
+		return BTRFS_ENCRYPTION_FSCRYPT;
+	return BTRFS_ENCRYPTION_NONE;
+}
+
 static inline void btrfs_extent_map_set_compression(struct extent_map *em,
 						    enum btrfs_compression_type type)
 {
fs/btrfs/file-item.c +1 -0
index d72249390030..020d30709770 100644
@@ -1364,6 +1364,7 @@ void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
 			if (type == BTRFS_FILE_EXTENT_PREALLOC)
 				em->flags |= EXTENT_FLAG_PREALLOC;
 		}
+		btrfs_extent_map_set_encryption(em, btrfs_file_extent_encryption(leaf, fi));
 	} else if (type == BTRFS_FILE_EXTENT_INLINE) {
 		/* Tree-checker has ensured this. */
 		ASSERT(extent_start == 0);
fs/btrfs/inode.c +1 -0
index bc2460292e43..17e2c77c584a 100644
@@ -7655,6 +7655,7 @@ struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
 	em->flags |= EXTENT_FLAG_PINNED;
 	if (type == BTRFS_ORDERED_COMPRESSED)
 		btrfs_extent_map_set_compression(em, file_extent->compression);
+	btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_NONE);
 
 	ret = btrfs_replace_extent_map_range(inode, em, true);
 	if (ret) {
Signature · 1 line
2.53.0
#53 lore raw

PATCH v7 20/43 btrfs: add fscrypt_info and encryption_type to ordered_extent

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We're going to need these to update the file extent items once the writes are complete. Add them and add the pieces necessary to assign them and free everything.

---

No changes in v7.
v6 changes:
* Changed encryption_type member to u8 as suggested by Dave.
v5: https://lore.kernel.org/linux-btrfs/de9ff13d1dc042b764c224d039fbb2a08946e004.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/ordered-data.c | 2 ++
 fs/btrfs/ordered-data.h | 6 ++++++
 2 files changed, 8 insertions(+)
fs/btrfs/ordered-data.c +2 -0
index e5a24b3ff95e..ac302fb7484b 100644
@@ -205,6 +205,7 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
 	}
 	entry->inode = inode;
 	entry->compress_type = compress_type;
+	entry->encryption_type = BTRFS_ENCRYPTION_NONE;
 	entry->truncated_len = (u64)-1;
 	entry->qgroup_rsv = qgroup_rsv;
 	entry->flags = flags;
@@ -629,6 +630,7 @@ void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
 		btrfs_add_delayed_iput(entry->inode);
 		list_for_each_entry_safe(sum, tmp, &entry->csum_list, list)
 			kvfree(sum);
+		fscrypt_put_extent_info(entry->fscrypt_info);
 		kmem_cache_free(btrfs_ordered_extent_cache, entry);
 	}
 }
fs/btrfs/ordered-data.h +6 -0
index 03e12380a2fd..9b288c3908f9 100644
@@ -131,6 +131,9 @@ struct btrfs_ordered_extent {
 	/* compression algorithm */
 	int compress_type;
 
+	/* encryption mode */
+	u8 encryption_type;
+
 	/* Qgroup reserved space */
 	int qgroup_rsv;
 
@@ -140,6 +143,9 @@ struct btrfs_ordered_extent {
 	/* the inode we belong to */
 	struct btrfs_inode *inode;
 
+	/* the fscrypt_info for this extent, if necessary */
+	struct fscrypt_extent_info *fscrypt_info;
+
 	/* list of checksums for insertion when the extent io is done */
 	struct list_head csum_list;
 
Signature · 1 line
2.53.0
#54 lore raw

PATCH v7 21/43 btrfs: plumb through setting the fscrypt_info for ordered extents

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We're going to be getting fscrypt_info from the extent maps. Pass the fscrypt_info to helpers using the file_extent structure and use that to set the encryption type on the ordered extent.

For prealloc extents we create an em, since we already have the context loaded from the original prealloc extent creation we need to pre- populate the extent map fscrypt info so it can be read properly later if the pages are evicted.

---

No changes in v7.
v6 changes:
* Added fscrypt_info to file_extent structure to clean up and simplify
the code following upstream changes since.
* Squashed in https://lore.kernel.org/linux-btrfs/f2b402eac1963296b6b8db3cb59cdf24a8121b97.1706116485.git.josef@toxicpanda.com/
("btrfs: plumb the fscrypt extent context through create_io_em").
* Moved fscrypt_info to be the last argument of alloc_ordered_extent().
v5: https://lore.kernel.org/linux-btrfs/80c5dabfe190b84e31a95160021da64ebcf7ecf7.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/direct-io.c    |  1 +
 fs/btrfs/inode.c        |  3 +++
 fs/btrfs/ordered-data.c | 18 ++++++++++++------
 fs/btrfs/ordered-data.h |  1 +
 4 files changed, 17 insertions(+), 6 deletions(-)
fs/btrfs/direct-io.c +1 -0
index 57167d56dc72..5a53739e9445 100644
@@ -202,6 +202,7 @@ static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
 	file_extent.ram_bytes = ins.offset;
 	file_extent.offset = 0;
 	file_extent.compression = BTRFS_COMPRESS_NONE;
+	file_extent.fscrypt_info = NULL;
 	em = btrfs_create_dio_extent(inode, dio_data, start, &file_extent,
 				     BTRFS_ORDERED_REGULAR);
 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
fs/btrfs/inode.c +3 -0
index 17e2c77c584a..c6c8ae05e471 100644
@@ -1112,6 +1112,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
 	file_extent.num_bytes = async_extent->ram_size;
 	file_extent.offset = 0;
 	file_extent.compression = async_extent->cb->compress_type;
+	file_extent.fscrypt_info = NULL;
 
 	async_extent->cb->bbio.bio.bi_iter.bi_sector = ins.objectid >> SECTOR_SHIFT;
 
@@ -1249,6 +1250,7 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
 	file_extent.ram_bytes = ins->offset;
 	file_extent.offset = 0;
 	file_extent.compression = BTRFS_COMPRESS_NONE;
+	file_extent.fscrypt_info = NULL;
 
 	/*
 	 * Locked range will be released either during error clean up (inside
@@ -10201,6 +10203,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
 	file_extent.ram_bytes = ram_bytes;
 	file_extent.offset = encoded->unencoded_offset;
 	file_extent.compression = compression;
+	file_extent.fscrypt_info = NULL;
 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
 	if (IS_ERR(em)) {
 		ret = PTR_ERR(em);
fs/btrfs/ordered-data.c +12 -6
index ac302fb7484b..5a9bb0e8a18c 100644
@@ -148,7 +148,8 @@ static inline struct rb_node *ordered_tree_search(struct btrfs_inode *inode,
 static struct btrfs_ordered_extent *alloc_ordered_extent(
 			struct btrfs_inode *inode, u64 file_offset, u64 num_bytes,
 			u64 ram_bytes, u64 disk_bytenr, u64 disk_num_bytes,
-			u64 offset, unsigned long flags, int compress_type)
+			u64 offset, unsigned long flags, int compress_type,
+			struct fscrypt_extent_info *fscrypt_info)
 {
 	struct btrfs_ordered_extent *entry;
 	int ret;
@@ -205,10 +206,12 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
 	}
 	entry->inode = inode;
 	entry->compress_type = compress_type;
-	entry->encryption_type = BTRFS_ENCRYPTION_NONE;
 	entry->truncated_len = (u64)-1;
 	entry->qgroup_rsv = qgroup_rsv;
 	entry->flags = flags;
+	entry->fscrypt_info = fscrypt_get_extent_info(fscrypt_info);
+	entry->encryption_type = entry->fscrypt_info ?
+		BTRFS_ENCRYPTION_FSCRYPT : BTRFS_ENCRYPTION_NONE;
 	refcount_set(&entry->refs, 1);
 	init_waitqueue_head(&entry->wait);
 	INIT_LIST_HEAD(&entry->csum_list);
@@ -290,6 +293,7 @@ static void insert_ordered_extent(struct btrfs_ordered_extent *entry)
  * @offset:          Offset into unencoded data where file data starts.
  * @flags:           Flags specifying type of extent (1U << BTRFS_ORDERED_*).
  * @compress_type:   Compression algorithm used for data.
+ * @fscrypt_info:    The fscrypt_extent_info for this extent, if necessary.
  *
  * Most of these parameters correspond to &struct btrfs_file_extent_item. The
  * tree is given a single reference on the ordered extent that was inserted, and
@@ -323,7 +327,8 @@ struct btrfs_ordered_extent *btrfs_alloc_ordered_extent(
 					     file_extent->num_bytes,
 					     file_extent->disk_bytenr + file_extent->offset,
 					     file_extent->num_bytes, 0, flags,
-					     file_extent->compression);
+					     file_extent->compression,
+					     file_extent->fscrypt_info);
 	else
 		entry = alloc_ordered_extent(inode, file_offset,
 					     file_extent->num_bytes,
@@ -331,7 +336,8 @@ struct btrfs_ordered_extent *btrfs_alloc_ordered_extent(
 					     file_extent->disk_bytenr,
 					     file_extent->disk_num_bytes,
 					     file_extent->offset, flags,
-					     file_extent->compression);
+					     file_extent->compression,
+					     file_extent->fscrypt_info);
 	if (!IS_ERR(entry))
 		insert_ordered_extent(entry);
 	return entry;
@@ -1270,8 +1276,8 @@ struct btrfs_ordered_extent *btrfs_split_ordered_extent(
 	if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes))
 		return ERR_PTR(-EINVAL);
 
-	new = alloc_ordered_extent(inode, file_offset, len, len, disk_bytenr,
-				   len, 0, flags, ordered->compress_type);
+	new = alloc_ordered_extent(inode, file_offset, len, len, disk_bytenr, len, 0,
+				   flags, ordered->compress_type, ordered->fscrypt_info);
 	if (IS_ERR(new))
 		return new;
 
fs/btrfs/ordered-data.h +1 -0
index 9b288c3908f9..a3514a4d9ea1 100644
@@ -192,6 +192,7 @@ struct btrfs_file_extent {
 	u64 num_bytes;
 	u64 ram_bytes;
 	u64 offset;
+	struct fscrypt_extent_info *fscrypt_info;
 	u8 compression;
 };
 
Signature · 1 line
2.53.0
#55 lore raw

PATCH v7 22/43 btrfs: populate the ordered_extent with the fscrypt context

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

The fscrypt_extent_info will be tied to the extent_map lifetime, so it will be created when we create the IO em, or it'll already exist in the NOCOW case. Use this fscrypt_info when creating the ordered extent to make sure everything is passed through properly.

---

No changes in v7.
v6 changes:
* Splitted the dio-related hunks from inode.c to direct-io.c as upstream
refactored in the meantime.
* Pass fscrypt_info using the file_extent structure to follow the
upstream cleanup.
v5: https://lore.kernel.org/linux-btrfs/33e650f3e91ed0318211301beb27fa613382f28e.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/direct-io.c |  4 +++-
 fs/btrfs/inode.c     | 36 ++++++++++++++++++++++++++++++------
 2 files changed, 33 insertions(+), 7 deletions(-)
fs/btrfs/direct-io.c +3 -1
index 5a53739e9445..e46bca590f35 100644
@@ -140,7 +140,7 @@ static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
 						  struct btrfs_dio_data *dio_data,
 						  const u64 start,
-						  const struct btrfs_file_extent *file_extent,
+						  struct btrfs_file_extent *file_extent,
 						  const int type)
 {
 	struct extent_map *em = NULL;
@@ -150,6 +150,7 @@ static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
 		em = btrfs_create_io_em(inode, start, file_extent, type);
 		if (IS_ERR(em))
 			goto out;
+		file_extent->fscrypt_info = em->fscrypt_info;
 	}
 
 	ordered = btrfs_alloc_ordered_extent(inode, start, file_extent,
@@ -276,6 +277,7 @@ static int btrfs_get_blocks_direct_write(struct extent_map **map,
 		}
 		space_reserved = true;
 
+		file_extent.fscrypt_info = em->fscrypt_info;
 		em2 = btrfs_create_dio_extent(BTRFS_I(inode), dio_data, start,
 					      &file_extent, type);
 		btrfs_dec_nocow_writers(bg);
fs/btrfs/inode.c +30 -6
index c6c8ae05e471..eab7950372ae 100644
@@ -1121,10 +1121,11 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
 		ret = PTR_ERR(em);
 		goto out_free_reserve;
 	}
-	btrfs_free_extent_map(em);
 
+	file_extent.fscrypt_info = em->fscrypt_info;
 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
 					     1U << BTRFS_ORDERED_COMPRESSED);
+	btrfs_free_extent_map(em);
 	if (IS_ERR(ordered)) {
 		btrfs_drop_extent_map_range(inode, start, end, false);
 		ret = PTR_ERR(ordered);
@@ -1263,10 +1264,11 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
 		ret = PTR_ERR(em);
 		goto free_reserved;
 	}
-	btrfs_free_extent_map(em);
 
+	file_extent.fscrypt_info = em->fscrypt_info;
 	ordered = btrfs_alloc_ordered_extent(inode, file_offset, &file_extent,
 					     1U << BTRFS_ORDERED_REGULAR);
+	btrfs_free_extent_map(em);
 	if (IS_ERR(ordered)) {
 		btrfs_drop_extent_map_range(inode, file_offset, cur_end, false);
 		ret = PTR_ERR(ordered);
@@ -1933,18 +1935,32 @@ static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio
 			   u64 file_pos, bool is_prealloc)
 {
 	struct btrfs_ordered_extent *ordered;
+	struct extent_map *em;
 	const u64 len = nocow_args->file_extent.num_bytes;
 	const u64 end = file_pos + len - 1;
 	int ret = 0;
 
 	btrfs_lock_extent(&inode->io_tree, file_pos, end, cached);
 
-	if (is_prealloc) {
-		struct extent_map *em;
+	/*
+	 * We only want to do this lookup if we're encrypted, otherwise
+	 * fsrypt_info will be null and we can avoid this lookup.
+	 */
+	if (IS_ENCRYPTED(&inode->vfs_inode)) {
+		em = btrfs_get_extent(inode, NULL, file_pos, len);
+		if (IS_ERR(em)) {
+			btrfs_unlock_extent(&inode->io_tree, file_pos, end, cached);
+			return PTR_ERR(em);
+		}
+		nocow_args->file_extent.fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
+		btrfs_free_extent_map(em);
+	}
 
+	if (is_prealloc) {
 		em = btrfs_create_io_em(inode, file_pos, &nocow_args->file_extent,
 					BTRFS_ORDERED_PREALLOC);
 		if (IS_ERR(em)) {
+			fscrypt_put_extent_info(nocow_args->file_extent.fscrypt_info);
 			ret = PTR_ERR(em);
 			goto error;
 		}
@@ -1955,6 +1971,7 @@ static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio
 					     is_prealloc
 					     ? (1U << BTRFS_ORDERED_PREALLOC)
 					     : (1U << BTRFS_ORDERED_NOCOW));
+	fscrypt_put_extent_info(nocow_args->file_extent.fscrypt_info);
 	if (IS_ERR(ordered)) {
 		if (is_prealloc)
 			btrfs_drop_extent_map_range(inode, file_pos, end, false);
@@ -7657,7 +7674,13 @@ struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
 	em->flags |= EXTENT_FLAG_PINNED;
 	if (type == BTRFS_ORDERED_COMPRESSED)
 		btrfs_extent_map_set_compression(em, file_extent->compression);
-	btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_NONE);
+
+	if (file_extent->fscrypt_info) {
+		btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_FSCRYPT);
+		em->fscrypt_info = fscrypt_get_extent_info(file_extent->fscrypt_info);
+	} else {
+		btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_NONE);
+	}
 
 	ret = btrfs_replace_extent_map_range(inode, em, true);
 	if (ret) {
@@ -10209,11 +10232,12 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
 		ret = PTR_ERR(em);
 		goto out_free_reserved;
 	}
-	btrfs_free_extent_map(em);
 
+	file_extent.fscrypt_info = em->fscrypt_info;
 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
 				       (1U << BTRFS_ORDERED_ENCODED) |
 				       (1U << BTRFS_ORDERED_COMPRESSED));
+	btrfs_free_extent_map(em);
 	if (IS_ERR(ordered)) {
 		btrfs_drop_extent_map_range(inode, start, end, false);
 		ret = PTR_ERR(ordered);
Signature · 1 line
2.53.0
#56 lore raw

PATCH v7 23/43 btrfs: keep track of fscrypt info and orig_start for dio reads

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We keep track of this information in the ordered extent for writes, but we need it for reads as well. Add fscrypt_extent_info and orig_start to the dio_data so we can populate this on reads. This will be used later when we attach the fscrypt context to the bios.

---

No changes in v7.
v6 changes:
* Open-code orig_start to start - offset.
v5: https://lore.kernel.org/linux-btrfs/acf3d79bcd72a4447b2993e78d9742fa5a05397f.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/direct-io.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/btrfs/direct-io.c +10 -0
index e46bca590f35..f87656db6157 100644
@@ -17,6 +17,8 @@ struct btrfs_dio_data {
 	ssize_t submitted;
 	struct extent_changeset *data_reserved;
 	struct btrfs_ordered_extent *ordered;
+	struct fscrypt_extent_info *fscrypt_info;
+	u64 orig_start;
 	bool data_space_reserved;
 	bool nocow_done;
 };
@@ -550,6 +552,9 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
 							       release_offset,
 							       release_len);
 		}
+	} else {
+		dio_data->fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
+		dio_data->orig_start = em->start - em->offset;
 	}
 
 	/*
@@ -640,6 +645,11 @@ static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
 		dio_data->ordered = NULL;
 	}
 
+	if (dio_data->fscrypt_info) {
+		fscrypt_put_extent_info(dio_data->fscrypt_info);
+		dio_data->fscrypt_info = NULL;
+	}
+
 	if (write)
 		extent_changeset_free(dio_data->data_reserved);
 	return ret;
Signature · 1 line
2.53.0
#57 lore raw

PATCH v7 24/43 btrfs: add extent encryption context tree item type

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

The fscrypt encryption context will be stored as a new tree item type. This gives us flexibility to include different things in the future.

Also update the tree-checker to validate the new item type.

---

v7 changes:
* Keep the original error if any as suggested by Chris' AI review.
* Fix a comment in check_fscrypt_context() to match the new design
as suggested by Chris' AI review.
v6 changes:
* Not much left from the original commit.
- This was reworked so that the encryption context is now a separate
tree item with it's unique key.
- It is tightly related to the file extent item but still optional and
only used for encrypted extents.
- The content (and hence the size as well) comes from the fscrrypt
subsystem and it is not touched by btrfs at all.
- It's handled as a raw binary data (u8 *).
- This patch makes sure it is correctly removed when the related extent
is dropped.
* As a result, the following patch https://lore.kernel.org/linux-btrfs/f0d9b2d3a40b7a963a977d3dfb62793ff7b065d1.1706116485.git.josef@toxicpanda.com/
("btrfs: explicitly track file extent length for replace and drop")
was dropped as not applicable. There's no need to track the size
anymore as it just matches the size of the stored item.

[RFC]: Should I have kept the structure with __u8 type? Like:

   |  struct btrfs_encryption_info {
   |        __u8 context[0];
   |  };

I did remove it as it was only used to extend the file extent item
structure and hence no longer needed.
v5: https://lore.kernel.org/linux-btrfs/7ee9171262857336011bf0e121846617c5181fa4.1706116485.git.josef@toxicpanda.com/
("btrfs: add an optional encryption context to the end of file extents")

---
 fs/btrfs/file.c                 | 65 +++++++++++++++++++++++++++++++++
 fs/btrfs/tree-checker.c         | 56 ++++++++++++++++++++++++++--
 include/uapi/linux/btrfs_tree.h |  8 ++++
 3 files changed, 125 insertions(+), 4 deletions(-)
fs/btrfs/file.c +65 -0
index 8b0ebdeca9dd..fe7baecbf83b 100644
@@ -151,6 +151,7 @@ int btrfs_drop_extents(struct btrfs_trans_handle *trans,
 	u64 extent_offset = 0;
 	u64 extent_end = 0;
 	u64 last_end = args->start;
+	u64 first_ctx = 1, last_ctx = 0;
 	int del_nr = 0;
 	int del_slot = 0;
 	int extent_type;
@@ -408,6 +409,12 @@ int btrfs_drop_extents(struct btrfs_trans_handle *trans,
 				del_nr++;
 			}
 
+			if (btrfs_file_extent_encryption(leaf, fi) == BTRFS_ENCRYPTION_FSCRYPT) {
+				if (first_ctx > last_ctx)
+					first_ctx = key.offset;
+				last_ctx = key.offset;
+			}
+
 			if (update_refs &&
 			    extent_type == BTRFS_FILE_EXTENT_INLINE) {
 				args->bytes_found += extent_end - key.offset;
@@ -497,6 +504,64 @@ int btrfs_drop_extents(struct btrfs_trans_handle *trans,
 		args->extent_inserted = true;
 	}
 
+	if (first_ctx <= last_ctx) {
+		int slot, nritems;
+
+		btrfs_release_path(path);
+
+		key.objectid = ino;
+		key.type = BTRFS_FSCRYPT_CTX_KEY;
+		key.offset = first_ctx;
+
+		ret = btrfs_search_slot(trans, root, &key, path, modify_tree, !!modify_tree);
+		if (ret < 0)
+			goto out_ctx;
+next_leaf:
+		leaf = path->nodes[0];
+		slot = path->slots[0];
+
+		del_slot = slot;
+		del_nr = 0;
+		nritems = btrfs_header_nritems(leaf);
+		while (slot < nritems) {
+			btrfs_item_key_to_cpu(leaf, &key, slot);
+			if (key.objectid > ino ||
+			    key.type > BTRFS_FSCRYPT_CTX_KEY ||
+			    key.offset > last_ctx)
+				break;
+			del_nr++;
+			slot++;
+		}
+		if (del_nr) {
+			ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
+			if (unlikely(ret)) {
+				btrfs_abort_transaction(trans, ret);
+				goto out_ctx;
+			}
+
+			if (slot == nritems) {
+				ret = btrfs_next_leaf(root, path);
+				if (!ret)
+					goto next_leaf;
+				if (ret > 0)
+					ret = 0;
+			}
+		}
+out_ctx:
+		if (args->path && args->extent_inserted) {
+			int err;
+
+			btrfs_release_path(path);
+
+			key.objectid = ino;
+			key.type = BTRFS_EXTENT_DATA_KEY;
+			key.offset = args->start;
+			err = btrfs_search_slot(trans, root, &key, path, 0, 0);
+			if (err && ret >= 0)
+				ret = err;
+		}
+	}
+
 	if (!args->path)
 		btrfs_free_path(path);
 	else if (!args->extent_inserted)
fs/btrfs/tree-checker.c +52 -4

94 lines not on this page · raw message

include/uapi/linux/btrfs_tree.h +8 -0
index 7b1922c3265a..26b793396132 100644
@@ -168,6 +168,7 @@
 #define BTRFS_VERITY_MERKLE_ITEM_KEY	37
 
 #define BTRFS_FSCRYPT_INODE_CTX_KEY	41
+#define BTRFS_FSCRYPT_CTX_KEY		42
 
 #define BTRFS_ORPHAN_ITEM_KEY		48
 /* reserve 2-15 close to the inode for later flexibility */
@@ -1079,6 +1080,13 @@ enum {
 	BTRFS_NR_FILE_EXTENT_TYPES = 3,
 };
 
+/*
+ * Currently just the FSCRYPT_SET_CONTEXT_MAX_SIZE, which is larger than the
+ * current extent context size from fscrypt, so this should give us plenty of
+ * breathing room for expansion later.
+ */
+#define BTRFS_MAX_EXTENT_CTX_SIZE 40
+
 enum btrfs_encryption_type {
 	BTRFS_ENCRYPTION_NONE,
 	BTRFS_ENCRYPTION_FSCRYPT,
Signature · 1 line
2.53.0
#58 lore raw

PATCH v7 25/43 btrfs: pass through fscrypt_extent_info to the file extent helpers

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Now that we have the fscrypt_extnet_info in all of the supporting structures, pass this through and set the file extent encryption bit accordingly from the supporting structures. In subsequent patches code will be added to populate these appropriately.

---

v5: https://lore.kernel.org/linux-btrfs/a8b9dd312a4504f209e861cca5289a528b30ff95.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/inode.c    | 16 ++++++++++------
 fs/btrfs/tree-log.c |  2 +-
 2 files changed, 11 insertions(+), 7 deletions(-)
fs/btrfs/inode.c +10 -6
index eab7950372ae..cdd2d7bc50cc 100644
@@ -3056,7 +3056,9 @@ int btrfs_writepage_cow_fixup(struct folio *folio)
 }
 
 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
-				       struct btrfs_inode *inode, u64 file_pos,
+				       struct btrfs_inode *inode,
+				       struct fscrypt_extent_info *fscrypt_info,
+				       u64 file_pos,
 				       struct btrfs_file_extent_item *stack_fi,
 				       const bool update_inode_bytes,
 				       u64 qgroup_reserved)
@@ -3180,7 +3182,7 @@ static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
 	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);
-	btrfs_set_stack_file_extent_encryption(&stack_fi, BTRFS_ENCRYPTION_NONE);
+	btrfs_set_stack_file_extent_encryption(&stack_fi, oe->encryption_type);
 	/* Other encoding is reserved and always 0 */
 
 	/*
@@ -3193,7 +3195,7 @@ static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
 			     test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
 			     test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
 
-	return insert_reserved_file_extent(trans, oe->inode,
+	return insert_reserved_file_extent(trans, oe->inode, oe->fscrypt_info,
 					   oe->file_offset, &stack_fi,
 					   update_inode_bytes, oe->qgroup_rsv);
 }
@@ -9288,6 +9290,7 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 				       struct btrfs_trans_handle *trans_in,
 				       struct btrfs_inode *inode,
 				       struct btrfs_key *ins,
+				       struct fscrypt_extent_info *fscrypt_info,
 				       u64 file_offset)
 {
 	struct btrfs_file_extent_item stack_fi;
@@ -9307,7 +9310,8 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
-	btrfs_set_stack_file_extent_encryption(&stack_fi, BTRFS_ENCRYPTION_NONE);
+	btrfs_set_stack_file_extent_encryption(&stack_fi, fscrypt_info? BTRFS_ENCRYPTION_FSCRYPT:
+									BTRFS_ENCRYPTION_NONE);
 	/* Other encoding is reserved and always 0 */
 
 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
@@ -9315,7 +9319,7 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 		return ERR_PTR(ret);
 
 	if (trans) {
-		ret = insert_reserved_file_extent(trans, inode,
+		ret = insert_reserved_file_extent(trans, inode, fscrypt_info,
 						  file_offset, &stack_fi,
 						  true, qgroup_released);
 		if (ret)
@@ -9408,7 +9412,7 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 
 		last_alloc = ins.offset;
 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
-						    &ins, cur_offset);
+						    &ins, NULL, cur_offset);
 		/*
 		 * Now that we inserted the prealloc extent we can finally
 		 * decrement the number of reservations in the block group.
fs/btrfs/tree-log.c +1 -1
index 3229a60bffb7..60aa763d2fa4 100644
@@ -5150,7 +5150,7 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	u64 block_start = btrfs_extent_map_block_start(em);
 	u64 block_len;
 	int ret;
-	u8 encryption = BTRFS_ENCRYPTION_NONE;
+	u8 encryption = btrfs_extent_map_encryption(em);
 
 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
 	if (em->flags & EXTENT_FLAG_PREALLOC)
Signature · 1 line
2.53.0
#59 lore raw

PATCH v7 26/43 btrfs: implement the fscrypt extent encryption hooks

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

This patch implements the necessary hooks from fscrypt to support per-extent encryption. There's two main entry points

btrfs_fscrypt_load_extent_info
btrfs_fscrypt_save_extent_info

btrfs_fscrypt_load_extent_info gets called when we create the extent maps from the file extent item at btrfs_get_extent() time. We read the extent context, and pass it into fscrypt to create the appropriate fscrypt_extent_info structure. This is then used on the bio's to make sure the encryption is done properly.

btrfs_fscrypt_save_extent_info is used to generate the fscrypt context from fscrypt and save it into the tree item when we create a new file extent item.

---

No changes in v7.
v6 changes:
* Significantly reworked due to the changes in previous commit [24/43].
v5: https://lore.kernel.org/linux-btrfs/30eaad31964c88c3497a0c5bc8f2c727c1dc763a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/ctree.h    |  3 ++
 fs/btrfs/defrag.c   |  6 ++++
 fs/btrfs/file.c     | 11 ++++++
 fs/btrfs/fscrypt.c  | 84 +++++++++++++++++++++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h  | 29 ++++++++++++++++
 fs/btrfs/inode.c    | 36 +++++++++++++++++++
 fs/btrfs/reflink.c  | 43 ++++++++++++++++++++++-
 fs/btrfs/tree-log.c | 19 ++++++++++
 8 files changed, 230 insertions(+), 1 deletion(-)
fs/btrfs/ctree.h +3 -0
index 6de7ad191e04..89d3c3137786 100644
@@ -400,6 +400,9 @@ struct btrfs_replace_extent_info {
 	u64 file_offset;
 	/* Pointer to a file extent item of type regular or prealloc. */
 	char *extent_buf;
+	/* The fscrypt_extent_info for a new extent. */
+	u8 *fscrypt_ctx;
+	u32 fscrypt_context_size;
 	/*
 	 * Set to true when attempting to replace a file range with a new extent
 	 * described by this structure, set to false when attempting to clone an
fs/btrfs/defrag.c +6 -0
index 7e2db5d3a4d4..a828ec45bb5f 100644
@@ -16,6 +16,7 @@
 #include "file-item.h"
 #include "super.h"
 #include "compression.h"
+#include "fscrypt.h"
 
 static struct kmem_cache *btrfs_inode_defrag_cachep;
 
@@ -720,6 +721,11 @@ static struct extent_map *defrag_get_extent(struct btrfs_inode *inode,
 		if (ret > 0)
 			goto not_found;
 	}
+	btrfs_release_path(&path);
+
+	ret = btrfs_fscrypt_load_extent_info(inode, &path, &key, em);
+	if (ret)
+		goto err;
 	return em;
 
 not_found:
fs/btrfs/file.c +11 -0
index fe7baecbf83b..b845556d2100 100644
@@ -38,6 +38,7 @@
 #include "file.h"
 #include "super.h"
 #include "print-tree.h"
+#include "fscrypt.h"
 
 /*
  * Unlock folio after btrfs_file_write() is done with it.
@@ -2406,6 +2407,16 @@ static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
 	if (extent_info->is_new_extent)
 		btrfs_set_file_extent_generation(leaf, extent, trans->transid);
 	btrfs_release_path(path);
+	if (extent_info->fscrypt_context_size) {
+		key.type = BTRFS_FSCRYPT_CTX_KEY;
+		ret = btrfs_insert_empty_item(trans, root, path, &key,
+					      extent_info->fscrypt_context_size);
+		if (ret)
+			return ret;
+		btrfs_fscrypt_save_extent_info(path,
+					       extent_info->fscrypt_ctx,
+					       extent_info->fscrypt_context_size);
+	}
 
 	ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
 						replace_len);
fs/btrfs/fscrypt.c +84 -0

93 lines not on this page · raw message

fs/btrfs/fscrypt.h +29 -0
index c5cdc27f943c..68eab4606935 100644
@@ -16,8 +16,27 @@ int btrfs_fscrypt_get_disk_name(struct extent_buffer *leaf,
 bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
 			      struct extent_buffer *leaf,
 			      unsigned long de_name, u32 de_name_len);
+int btrfs_fscrypt_load_extent_info(struct btrfs_inode *inode,
+				   struct btrfs_path *path,
+				   struct btrfs_key *key,
+				   struct extent_map *em);
+void btrfs_fscrypt_save_extent_info(struct btrfs_path *path, u8 *ctx, unsigned long size);
+ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *inode,
+					     struct fscrypt_extent_info *info,
+					     u8 *ctx);
 
 #else
+static inline void btrfs_fscrypt_save_extent_info(struct btrfs_path *path,
+						  u8 *ctx, unsigned long size) { }
+
+static inline int btrfs_fscrypt_load_extent_info(struct btrfs_inode *inode,
+						 struct btrfs_path *path,
+						 struct btrfs_key *key,
+						 struct extent_map *em)
+{
+	return 0;
+}
+
 static inline int btrfs_fscrypt_get_disk_name(struct extent_buffer *leaf,
 					      struct btrfs_dir_item *di,
 					      struct fscrypt_str *qstr)
@@ -34,6 +53,16 @@ static inline bool btrfs_fscrypt_match_name(struct fscrypt_name *fname,
 		return false;
 	return !memcmp_extent_buffer(leaf, fname->disk_name.name, de_name, de_name_len);
 }
+
+static inline ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *inode,
+							   struct fscrypt_extent_info *info,
+							   u8 *ctx)
+{
+	if (!info)
+		return 0;
+	return -EINVAL;
+}
+
 #endif /* CONFIG_FS_ENCRYPTION */
 
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
fs/btrfs/inode.c +36 -0
index cdd2d7bc50cc..a78a7206a291 100644
@@ -3074,8 +3074,16 @@ static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
 	u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
 	u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
 	struct btrfs_drop_extents_args drop_args = { 0 };
+	u8 fscrypt_ctx[FSCRYPT_SET_CONTEXT_MAX_SIZE];
+	ssize_t fscrypt_context_size;
 	int ret;
 
+	fscrypt_context_size = btrfs_fscrypt_context_for_new_extent(inode,
+								    fscrypt_info,
+								    fscrypt_ctx);
+	if (fscrypt_context_size < 0)
+		return (int)fscrypt_context_size;
+
 	path = btrfs_alloc_path();
 	if (!path)
 		return -ENOMEM;
@@ -3116,6 +3124,16 @@ static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
 
 	btrfs_release_path(path);
 
+	if (fscrypt_context_size) {
+		ins.objectid = btrfs_ino(inode);
+		ins.type = BTRFS_FSCRYPT_CTX_KEY;
+		ins.offset = file_pos;
+		ret = btrfs_insert_empty_item(trans, root, path, &ins, fscrypt_context_size);
+		if (ret)
+			return ret;
+		btrfs_fscrypt_save_extent_info(path, fscrypt_ctx, fscrypt_context_size);
+	}
+
 	/*
 	 * If we dropped an inline extent here, we know the range where it is
 	 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
@@ -7481,6 +7499,12 @@ struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
 		goto out;
 	}
 
+	ret = btrfs_fscrypt_load_extent_info(inode, path, &found_key, em);
+	if (ret > 0)
+		ret = -EIO;
+	if (ret < 0)
+		goto out;
+
 	write_lock(&em_tree->lock);
 	ret = btrfs_add_extent_mapping(inode, &em, start, len);
 	write_unlock(&em_tree->lock);
@@ -9294,6 +9318,8 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 				       u64 file_offset)
 {
 	struct btrfs_file_extent_item stack_fi;
+	u8 fscrypt_ctx[FSCRYPT_SET_CONTEXT_MAX_SIZE];
+	ssize_t fscrypt_context_size;
 	struct btrfs_replace_extent_info extent_info;
 	struct btrfs_trans_handle *trans = trans_in;
 	struct btrfs_path *path;
@@ -9327,6 +9353,14 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 		return trans;
 	}
 
+	fscrypt_context_size = btrfs_fscrypt_context_for_new_extent(inode,
+								    fscrypt_info,
+								    fscrypt_ctx);
+	if (fscrypt_context_size < 0) {
+		ret = (int)fscrypt_context_size;
+		goto free_qgroup;
+	}
+
 	extent_info.disk_offset = start;
 	extent_info.disk_len = len;
 	extent_info.data_offset = 0;
@@ -9337,6 +9371,8 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 	extent_info.update_times = true;
 	extent_info.qgroup_reserved = qgroup_released;
 	extent_info.insertions = 0;
+	extent_info.fscrypt_ctx = fscrypt_ctx;
+	extent_info.fscrypt_context_size = fscrypt_context_size;
 
 	path = btrfs_alloc_path();
 	if (!path) {
fs/btrfs/reflink.c +42 -1

73 lines not on this page · raw message

fs/btrfs/tree-log.c +19 -0
index 60aa763d2fa4..f3b839950855 100644
@@ -30,6 +30,7 @@
 #include "print-tree.h"
 #include "tree-checker.h"
 #include "delayed-inode.h"
+#include "fscrypt.h"
 
 #define MAX_CONFLICT_INODES 10
 
@@ -5145,6 +5146,8 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	struct btrfs_file_extent_item fi = { 0 };
 	struct extent_buffer *leaf;
 	struct btrfs_key key;
+	u8 fscrypt_ctx[FSCRYPT_SET_CONTEXT_MAX_SIZE];
+	ssize_t fscrypt_context_size;
 	enum btrfs_compression_type compress_type;
 	u64 extent_offset = em->offset;
 	u64 block_start = btrfs_extent_map_block_start(em);
@@ -5152,6 +5155,12 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	int ret;
 	u8 encryption = btrfs_extent_map_encryption(em);
 
+	fscrypt_context_size = btrfs_fscrypt_context_for_new_extent(inode,
+								    em->fscrypt_info,
+								    fscrypt_ctx);
+	if (fscrypt_context_size < 0)
+		return (int)fscrypt_context_size;
+
 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
 	if (em->flags & EXTENT_FLAG_PREALLOC)
 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
@@ -5215,6 +5224,16 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 
 	btrfs_release_path(path);
 
+	if (fscrypt_context_size) {
+		key.objectid = btrfs_ino(inode);
+		key.type = BTRFS_FSCRYPT_CTX_KEY;
+		key.offset = em->start;
+		ret = btrfs_insert_empty_item(trans, log, path, &key, fscrypt_context_size);
+		if (ret)
+			return ret;
+		btrfs_fscrypt_save_extent_info(path, fscrypt_ctx, fscrypt_context_size);
+	}
+
 	return ret;
 }
 
Signature · 1 line
2.53.0
#60 lore raw

PATCH v7 27/43 btrfs: setup fscrypt_extent_info for new extents

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

New extents for encrypted inodes must have a fscrypt_extent_info, which has the necessary keys and does all the registration at the block layer for them. This is passed through all of the infrastructure we've previously added to make sure the context gets saved properly with the file extents.

---

v5: https://lore.kernel.org/linux-btrfs/d8ab016d25f70c9365f508af1d8e0b9ab7c09d76.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/inode.c | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
fs/btrfs/inode.c +29 -1
index a78a7206a291..e864006296dd 100644
@@ -7704,6 +7704,16 @@ struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
 	if (file_extent->fscrypt_info) {
 		btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_FSCRYPT);
 		em->fscrypt_info = fscrypt_get_extent_info(file_extent->fscrypt_info);
+	} else if (IS_ENCRYPTED(&inode->vfs_inode)) {
+		struct fscrypt_extent_info *fscrypt_info;
+
+		btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_FSCRYPT);
+		fscrypt_info = fscrypt_prepare_new_extent(&inode->vfs_inode);
+		if (IS_ERR(fscrypt_info)) {
+			btrfs_free_extent_map(em);
+			return ERR_CAST(fscrypt_info);
+		}
+		em->fscrypt_info = fscrypt_info;
 	} else {
 		btrfs_extent_map_set_encryption(em, BTRFS_ENCRYPTION_NONE);
 	}
@@ -9423,6 +9433,9 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 	if (trans)
 		own_trans = false;
 	while (num_bytes > 0) {
+		struct fscrypt_extent_info *fscrypt_info = NULL;
+		int encryption_type = BTRFS_ENCRYPTION_NONE;
+
 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
 		cur_bytes = max(cur_bytes, min_size);
 		/*
@@ -9437,6 +9450,17 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 		if (ret)
 			break;
 
+		if (IS_ENCRYPTED(inode)) {
+			fscrypt_info = fscrypt_prepare_new_extent(inode);
+			if (IS_ERR(fscrypt_info)) {
+				btrfs_dec_block_group_reservations(fs_info, ins.objectid);
+				btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
+				ret = PTR_ERR(fscrypt_info);
+				break;
+			}
+			encryption_type = BTRFS_ENCRYPTION_FSCRYPT;
+		}
+
 		/*
 		 * We've reserved this space, and thus converted it from
 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
@@ -9448,7 +9472,7 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 
 		last_alloc = ins.offset;
 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
-						    &ins, NULL, cur_offset);
+						    &ins, fscrypt_info, cur_offset);
 		/*
 		 * Now that we inserted the prealloc extent we can finally
 		 * decrement the number of reservations in the block group.
@@ -9458,6 +9482,7 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
 		if (IS_ERR(trans)) {
 			ret = PTR_ERR(trans);
+			fscrypt_put_extent_info(fscrypt_info);
 			btrfs_free_reserved_extent(fs_info, ins.objectid,
 						   ins.offset, false);
 			break;
@@ -9465,6 +9490,7 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 
 		em = btrfs_alloc_extent_map();
 		if (!em) {
+			fscrypt_put_extent_info(fscrypt_info);
 			btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
 					    cur_offset + ins.offset - 1, false);
 			btrfs_set_inode_full_sync(BTRFS_I(inode));
@@ -9479,6 +9505,8 @@ static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
 		em->ram_bytes = ins.offset;
 		em->flags |= EXTENT_FLAG_PREALLOC;
 		em->generation = trans->transid;
+		em->fscrypt_info = fscrypt_info;
+		btrfs_extent_map_set_encryption(em, encryption_type);
 
 		ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
 		btrfs_free_extent_map(em);
Signature · 1 line
2.53.0
#61 lore raw

PATCH v7 28/43 btrfs: populate ordered_extent with the orig offset

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

For extent encryption we have to use a logical block nr as input for the IV. For btrfs we're using the offset into the extent we're operating on. For most ordered extents this is the same as the file_offset, however for prealloc and NOCOW we have to use the original offset.

Add this as an argument and plumb it through everywhere, this will be used when setting up the bio.

---

No changes in v7.
v6 changes:
* Splitted the dio-related hunks from inode.c to direct-io.c as upstream
refactored in the meantime.
* Open-code orig_start to start - offset.
v5: https://lore.kernel.org/linux-btrfs/fe06053fe2973c424dd539fecfee8cc171bdd22d.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/direct-io.c    |  1 +
 fs/btrfs/inode.c        |  5 +++++
 fs/btrfs/ordered-data.c | 21 ++++++++++++++++++---
 fs/btrfs/ordered-data.h |  7 +++++++
 4 files changed, 31 insertions(+), 3 deletions(-)
fs/btrfs/direct-io.c +1 -0
index f87656db6157..e8b1ce4a3a11 100644
@@ -155,6 +155,7 @@ static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
 		file_extent->fscrypt_info = em->fscrypt_info;
 	}
 
+	file_extent->orig_offset = start - file_extent->offset;
 	ordered = btrfs_alloc_ordered_extent(inode, start, file_extent,
 					     (1U << type) |
 					     (1U << BTRFS_ORDERED_DIRECT));
fs/btrfs/inode.c +5 -0
index e864006296dd..8a9f80c8364e 100644
@@ -1123,6 +1123,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
 	}
 
 	file_extent.fscrypt_info = em->fscrypt_info;
+	file_extent.orig_offset = start;
 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
 					     1U << BTRFS_ORDERED_COMPRESSED);
 	btrfs_free_extent_map(em);
@@ -1266,6 +1267,7 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
 	}
 
 	file_extent.fscrypt_info = em->fscrypt_info;
+	file_extent.orig_offset = file_offset;
 	ordered = btrfs_alloc_ordered_extent(inode, file_offset, &file_extent,
 					     1U << BTRFS_ORDERED_REGULAR);
 	btrfs_free_extent_map(em);
@@ -2208,6 +2210,8 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
 			cow_start = (u64)-1;
 		}
 
+		nocow_args.file_extent.orig_offset =
+			found_key.offset - nocow_args.file_extent.offset;
 		ret = nocow_one_range(inode, locked_folio, &cached_state,
 				      &nocow_args, cur_offset,
 				      extent_type == BTRFS_FILE_EXTENT_PREALLOC);
@@ -10302,6 +10306,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
 	}
 
 	file_extent.fscrypt_info = em->fscrypt_info;
+	file_extent.orig_offset = start - encoded->unencoded_offset;
 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
 				       (1U << BTRFS_ORDERED_ENCODED) |
 				       (1U << BTRFS_ORDERED_COMPRESSED));
fs/btrfs/ordered-data.c +18 -3
index 5a9bb0e8a18c..f796dd7ea925 100644
@@ -146,7 +146,8 @@ static inline struct rb_node *ordered_tree_search(struct btrfs_inode *inode,
 }
 
 static struct btrfs_ordered_extent *alloc_ordered_extent(
-			struct btrfs_inode *inode, u64 file_offset, u64 num_bytes,
+			struct btrfs_inode *inode,
+			u64 file_offset, u64 orig_offset, u64 num_bytes,
 			u64 ram_bytes, u64 disk_bytenr, u64 disk_num_bytes,
 			u64 offset, unsigned long flags, int compress_type,
 			struct fscrypt_extent_info *fscrypt_info)
@@ -193,6 +194,7 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
 	}
 
 	entry->file_offset = file_offset;
+	entry->orig_offset = orig_offset;
 	entry->num_bytes = num_bytes;
 	entry->ram_bytes = ram_bytes;
 	entry->disk_bytenr = disk_bytenr;
@@ -286,6 +288,7 @@ static void insert_ordered_extent(struct btrfs_ordered_extent *entry)
  *
  * @inode:           Inode that this extent is for.
  * @file_offset:     Logical offset in file where the extent starts.
+ * @orig_offset:     Logical offset of the original extent (PREALLOC or NOCOW)
  * @num_bytes:       Logical length of extent in file.
  * @ram_bytes:       Full length of unencoded data.
  * @disk_bytenr:     Offset of extent on disk.
@@ -323,6 +326,7 @@ struct btrfs_ordered_extent *btrfs_alloc_ordered_extent(
 	 */
 	if (flags & ((1U << BTRFS_ORDERED_NOCOW) | (1U << BTRFS_ORDERED_PREALLOC)))
 		entry = alloc_ordered_extent(inode, file_offset,
+					     file_extent->orig_offset,
 					     file_extent->num_bytes,
 					     file_extent->num_bytes,
 					     file_extent->disk_bytenr + file_extent->offset,
@@ -331,6 +335,7 @@ struct btrfs_ordered_extent *btrfs_alloc_ordered_extent(
 					     file_extent->fscrypt_info);
 	else
 		entry = alloc_ordered_extent(inode, file_offset,
+					     file_extent->orig_offset,
 					     file_extent->num_bytes,
 					     file_extent->ram_bytes,
 					     file_extent->disk_bytenr,
@@ -1276,8 +1281,8 @@ struct btrfs_ordered_extent *btrfs_split_ordered_extent(
 	if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes))
 		return ERR_PTR(-EINVAL);
 
-	new = alloc_ordered_extent(inode, file_offset, len, len, disk_bytenr, len, 0,
-				   flags, ordered->compress_type, ordered->fscrypt_info);
+	new = alloc_ordered_extent(inode, file_offset, ordered->orig_offset, len, len, disk_bytenr,
+				   len, 0, flags, ordered->compress_type, ordered->fscrypt_info);
 	if (IS_ERR(new))
 		return new;
 
@@ -1314,6 +1319,16 @@ struct btrfs_ordered_extent *btrfs_split_ordered_extent(
 	ordered->disk_num_bytes -= len;
 	ordered->ram_bytes -= len;
 
+	/*
+	 * ->orig_offset is the original offset of the original extent, which
+	 * for PREALLOC or NOCOW stays the same, but if we're a regular extent
+	 * that means this is a new extent and thus ->orig_offset must equal
+	 * ->file_offset.  This is only important for encryption as we only use
+	 * it for setting the offset for the bio encryption context.
+	 */
+	if (test_bit(BTRFS_ORDERED_REGULAR, &ordered->flags))
+		ordered->orig_offset = ordered->file_offset;
+
 	if (test_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags)) {
 		ASSERT(ordered->bytes_left == 0);
 		new->bytes_left = 0;
fs/btrfs/ordered-data.h +7 -0
index a3514a4d9ea1..f4ad5ff1a1e2 100644
@@ -106,6 +106,12 @@ struct btrfs_ordered_extent {
 	/* logical offset in the file */
 	u64 file_offset;
 
+	/*
+	 * The original logical offset of the extent, this is for NOCOW and
+	 * PREALLOC extents, otherwise it'll be the same as file_offset.
+	 */
+	u64 orig_offset;
+
 	/*
 	 * These fields directly correspond to the same fields in
 	 * btrfs_file_extent_item.
@@ -192,6 +198,7 @@ struct btrfs_file_extent {
 	u64 num_bytes;
 	u64 ram_bytes;
 	u64 offset;
+	u64 orig_offset;
 	struct fscrypt_extent_info *fscrypt_info;
 	u8 compression;
 };
Signature · 1 line
2.53.0
#62 lore raw

PATCH v7 29/43 btrfs: set the bio fscrypt context when applicable

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Now that we have the fscrypt_info plumbed through everywhere, add the code to setup the bio encryption context from the extent context.

We use the per-extent fscrypt_extent_info for encryption/decryption. We use the offset into the extent as the lblk for fscrypt. So the start of the extent has the lblk of 0, 4k into the extent has the lblk of 4k, etc. This is done to allow things like relocation to continue to work properly.

---

v7 changes:
* s/\<submit_bio(/blk_crypto_\0/ in btrfs_submit_dev_bio() due to commit
bb8e2019ad613 ("blk-crypto: handle the fallback above the block layer")
* Follow upstream fscrypt cleanup and use byte offsets instead of
logical block numbers in the new api. As a result remove the btrfs_set_bio_crypt_ctx_from_extent() and btrfs_mergeable_encrypted_bio()
helpers and directly use fscrypt_set_bio_crypt_ctx_from_extent()
and fscrypt_mergeable_extent_bio().
v6 changes:
* The dio-related changes in inode.c were moved to direct-io.c
as upstream refactored in the meantime.
* Open-code orig_start to start - offset.
* Get the inode from bbio instead of from page mapping
as we no longer have the page in btrfs_bio_is_contig().
* Directly use the file_offset passed to btrfs_bio_is_contig(), no need
to compute it locally. We even no longer have the page and offset.
v5: https://lore.kernel.org/linux-btrfs/9ca883acc746b5aba980d1d19317168a7491aba6.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c         |  2 +-
 fs/btrfs/compression.c |  4 +++
 fs/btrfs/direct-io.c   | 10 ++++++
 fs/btrfs/extent_io.c   | 72 +++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 86 insertions(+), 2 deletions(-)
fs/btrfs/bio.c +1 -1
index cc0bd03048ba..689cc41409e5 100644
@@ -535,7 +535,7 @@ static void btrfs_submit_dev_bio(struct btrfs_device *dev, struct bio *bio)
 	if (bio->bi_opf & REQ_BTRFS_CGROUP_PUNT)
 		blkcg_punt_bio_submit(bio);
 	else
-		submit_bio(bio);
+		blk_crypto_submit_bio(bio);
 }
 
 static void btrfs_submit_mirrored_bio(struct btrfs_io_context *bioc, int dev_nr)
fs/btrfs/compression.c +4 -0
index b2393a48a8fe..e235a2ac5838 100644
@@ -33,6 +33,7 @@
 #include "subpage.h"
 #include "messages.h"
 #include "super.h"
+#include "fscrypt.h"
 
 static struct bio_set btrfs_compressed_bioset;
 
@@ -333,6 +334,8 @@ void btrfs_submit_compressed_write(struct btrfs_ordered_extent *ordered,
 	cb->bbio.bio.bi_iter.bi_sector = ordered->disk_bytenr >> SECTOR_SHIFT;
 	cb->bbio.ordered = ordered;
 
+	fscrypt_set_bio_crypt_ctx_from_extent(&cb->bbio.bio, ordered->fscrypt_info, 0, GFP_NOFS);
+
 	btrfs_submit_bbio(&cb->bbio, 0);
 }
 
@@ -590,6 +593,7 @@ void btrfs_submit_compressed_read(struct btrfs_bio *bbio)
 	cb->orig_bbio = bbio;
 	cb->bbio.csum_search_commit_root = bbio->csum_search_commit_root;
 
+	fscrypt_set_bio_crypt_ctx_from_extent(&cb->bbio.bio, em->fscrypt_info, 0, GFP_NOFS);
 	btrfs_free_extent_map(em);
 
 	for (int i = 0; i * min_folio_size < compressed_len; i++) {
fs/btrfs/direct-io.c +10 -0
index e8b1ce4a3a11..4891bf233536 100644
@@ -12,6 +12,7 @@
 #include "volumes.h"
 #include "bio.h"
 #include "ordered-data.h"
+#include "fscrypt.h"
 
 struct btrfs_dio_data {
 	ssize_t submitted;
@@ -727,6 +728,8 @@ static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
 	struct btrfs_dio_private *dip =
 		container_of(bbio, struct btrfs_dio_private, bbio);
 	struct btrfs_dio_data *dio_data = iter->private;
+	struct fscrypt_extent_info *fscrypt_info = NULL;
+	u64 offset = 0;
 
 	btrfs_bio_init(bbio, BTRFS_I(iter->inode), file_offset,
 		       btrfs_dio_end_io, bio->bi_private);
@@ -746,6 +749,9 @@ static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
 	if (iter->flags & IOMAP_WRITE) {
 		int ret;
 
+		fscrypt_info = dio_data->ordered->fscrypt_info;
+		offset = file_offset - dio_data->ordered->orig_offset;
+
 		ret = btrfs_extract_ordered_extent(bbio, dio_data->ordered);
 		if (ret) {
 			btrfs_finish_ordered_extent(dio_data->ordered,
@@ -755,8 +761,12 @@ static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
 			iomap_dio_bio_end_io(bio);
 			return;
 		}
+	} else {
+		fscrypt_info = dio_data->fscrypt_info;
+		offset = file_offset - dio_data->orig_start;
 	}
 
+	fscrypt_set_bio_crypt_ctx_from_extent(&bbio->bio, fscrypt_info, offset, GFP_NOFS);
 	btrfs_submit_bbio(bbio, 0);
 }
 
fs/btrfs/extent_io.c +71 -1

146 lines not on this page · raw message

Signature · 1 line
2.53.0
#63 lore raw

PATCH v7 30/43 btrfs: add a bio argument to btrfs_csum_one_bio

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We only ever needed the bbio in btrfs_csum_one_bio, since that has the bio embedded in it. However with encryption we'll have a different bio with the encrypted data in it, and the original bbio. Update btrfs_csum_one_bio to take the bio we're going to csum as an argument, which will allow us to csum the encrypted bio and stuff the csums into the corresponding bbio to be used later when the IO completes.

---

No changes in v7.
v6 changes:
* Adapted for async csums. For writes we have to stick with sync
csums. Otherwise fscrypt would have to hand us the bounced bio
instead of releasing it. Though that is not implemented yet.
v5: https://lore.kernel.org/linux-btrfs/595a2e46dae3d18bceb5dfa60ac3ae23760fc800.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c       |  4 ++--
 fs/btrfs/bio.h       |  1 +
 fs/btrfs/file-item.c | 13 ++++++-------
 fs/btrfs/file-item.h |  2 +-
 4 files changed, 10 insertions(+), 10 deletions(-)
fs/btrfs/bio.c +2 -2
index 689cc41409e5..b79fc467445d 100644
@@ -600,9 +600,9 @@ static int btrfs_bio_csum(struct btrfs_bio *bbio)
 	if (bbio->bio.bi_opf & REQ_META)
 		return btree_csum_one_bio(bbio);
 #ifdef CONFIG_BTRFS_EXPERIMENTAL
-	return btrfs_csum_one_bio(bbio, true);
+	return btrfs_csum_one_bio(bbio, &bbio->bio, true);
 #else
-	return btrfs_csum_one_bio(bbio, false);
+	return btrfs_csum_one_bio(bbio, &bbio->bio, false);
 #endif
 }
 
fs/btrfs/bio.h +1 -0
index 303ed6c7103d..43f7544029ac 100644
@@ -59,6 +59,7 @@ struct btrfs_bio {
 			struct btrfs_ordered_sum *sums;
 			struct work_struct csum_work;
 			struct completion csum_done;
+			struct bio *csum_bio;
 			struct bvec_iter csum_saved_iter;
 			u64 orig_physical;
 			u64 orig_logical;
fs/btrfs/file-item.c +6 -7
index 020d30709770..986914078708 100644
@@ -771,11 +771,10 @@ int btrfs_lookup_csums_bitmap(struct btrfs_root *root, struct btrfs_path *path,
 	return ret;
 }
 
-static void csum_one_bio(struct btrfs_bio *bbio, struct bvec_iter *src)
+static void csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, struct bvec_iter *src)
 {
 	struct btrfs_inode *inode = bbio->inode;
 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
-	struct bio *bio = &bbio->bio;
 	struct btrfs_ordered_sum *sums = bbio->sums;
 	struct bvec_iter iter = *src;
 	phys_addr_t paddr;
@@ -803,19 +802,18 @@ static void csum_one_bio_work(struct work_struct *work)
 
 	ASSERT(btrfs_op(&bbio->bio) == BTRFS_MAP_WRITE);
 	ASSERT(bbio->async_csum == true);
-	csum_one_bio(bbio, &bbio->csum_saved_iter);
+	csum_one_bio(bbio, bbio->csum_bio, &bbio->csum_saved_iter);
 	complete(&bbio->csum_done);
 }
 
 /*
  * Calculate checksums of the data contained inside a bio.
  */
-int btrfs_csum_one_bio(struct btrfs_bio *bbio, bool async)
+int btrfs_csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, bool async)
 {
 	struct btrfs_ordered_extent *ordered = bbio->ordered;
 	struct btrfs_inode *inode = bbio->inode;
 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
-	struct bio *bio = &bbio->bio;
 	struct btrfs_ordered_sum *sums;
 	unsigned nofs_flag;
 
@@ -834,12 +832,13 @@ int btrfs_csum_one_bio(struct btrfs_bio *bbio, bool async)
 	btrfs_add_ordered_sum(ordered, sums);
 
 	if (!async) {
-		csum_one_bio(bbio, &bbio->bio.bi_iter);
+		csum_one_bio(bbio, bio, &bio->bi_iter);
 		return 0;
 	}
 	init_completion(&bbio->csum_done);
 	bbio->async_csum = true;
-	bbio->csum_saved_iter = bbio->bio.bi_iter;
+	bbio->csum_bio = bio;
+	bbio->csum_saved_iter = bio->bi_iter;
 	INIT_WORK(&bbio->csum_work, csum_one_bio_work);
 	schedule_work(&bbio->csum_work);
 	return 0;
fs/btrfs/file-item.h +1 -1
index 6c678787c770..e170bac310ac 100644
@@ -64,7 +64,7 @@ int btrfs_lookup_file_extent(struct btrfs_trans_handle *trans,
 int btrfs_insert_data_csums(struct btrfs_trans_handle *trans,
 			    struct btrfs_root *root,
 			    struct btrfs_ordered_sum *sums);
-int btrfs_csum_one_bio(struct btrfs_bio *bbio, bool async);
+int btrfs_csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, bool async);
 int btrfs_alloc_dummy_sum(struct btrfs_bio *bbio);
 int btrfs_lookup_csums_range(struct btrfs_root *root, u64 start, u64 end,
 			     struct list_head *list, int search_commit,
Signature · 1 line
2.53.0
#64 lore raw

PATCH v7 31/43 btrfs: limit encrypted writes to 256 segments

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

For the fallback encrypted writes it allocates a bounce buffer to encrypt, and if the bio is larger than 256 segments it splits the bio we send down. This wreaks havoc on us because we need our actual original bio to be passed into the process_cb callback in order to get at our ordered extent. With the split we'll get some cloned bio that has none of our information. Handle this by returning the length we need to be truncated to and then splitting ourselves, which will handle giving us the correct btrfs_bio that we need.

---

v5: https://lore.kernel.org/linux-btrfs/1fc07b885453495bccea5a37e13d7d26333bd2af.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/bio.c     | 29 ++++++++++++++++++++++++++++-
 fs/btrfs/fscrypt.c | 24 ++++++++++++++++++++++++
 fs/btrfs/fscrypt.h |  6 ++++++
 3 files changed, 58 insertions(+), 1 deletion(-)
fs/btrfs/bio.c +28 -1
index b79fc467445d..3e2ee19aab50 100644
@@ -15,6 +15,7 @@
 #include "zoned.h"
 #include "file-item.h"
 #include "raid-stripe-tree.h"
+#include "fscrypt.h"
 
 static struct bio_set btrfs_bioset;
 static struct bio_set btrfs_clone_bioset;
@@ -759,6 +760,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
 	u64 logical = bio->bi_iter.bi_sector << SECTOR_SHIFT;
 	u64 length = bio->bi_iter.bi_size;
 	u64 map_length = length;
+	u64 max_bio_len = length;
 	struct btrfs_io_context *bioc = NULL;
 	struct btrfs_io_stripe smap;
 	blk_status_t status;
@@ -770,6 +772,31 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
 		smap.rst_search_commit_root = false;
 
 	btrfs_bio_counter_inc_blocked(fs_info);
+
+	/*
+	 * The blk-crypto-fallback limits bio sizes to 256 segments, because it
+	 * has no way of controlling the pages it gets for the bounce bio it
+	 * submits.
+	 *
+	 * If we don't pre-split our bio blk-crypto-fallback will do it for us,
+	 * and then call into our checksum callback with a random cloned bio
+	 * that isn't a btrfs_bio.
+	 *
+	 * To account for this we must truncate the bio ourselves, so we need to
+	 * get our length at 256 segments and return that.  We must do this
+	 * before btrfs_map_block because the RAID5/6 code relies on having
+	 * properly stripe aligned things, so we return the truncated length
+	 * here so that btrfs_map_block() does the correct thing.  Further down
+	 * we actually truncate map_length to map_bio_len because map_length
+	 * will be set to whatever the mapping length is for the underlying
+	 * geometry.  This will work properly with RAID5/6 as it will have
+	 * already setup everything for the expected length, and everything else
+	 * can handle with a truncated map_length.
+	 */
+	if (bio_has_crypt_ctx(bio))
+		max_bio_len = btrfs_fscrypt_bio_length(bio, map_length);
+
+	map_length = max_bio_len;
 	ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
 			      &bioc, &smap, &mirror_num);
 	if (ret) {
@@ -788,7 +815,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
 
 	bbio->can_use_append = btrfs_use_zone_append(bbio);
 
-	map_length = min(map_length, length);
+	map_length = min(map_length, max_bio_len);
 	if (bbio->can_use_append)
 		map_length = btrfs_append_map_length(bbio, map_length);
 
fs/btrfs/fscrypt.c +24 -0
index 5d4802fce7eb..5d34a8b94da5 100644
@@ -295,6 +295,30 @@ ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *inode,
 	return ret;
 }
 
+/*
+ * The block crypto stuff allocates bounce buffers for encryption, so splits at
+ * BIO_MAX_VECS worth of segments.  If we are larger than that number of
+ * segments then we need to limit the size to the size that BIO_MAX_VECS covers.
+ */
+int btrfs_fscrypt_bio_length(struct bio *bio, u64 map_length)
+{
+	unsigned int i = 0;
+	struct bio_vec bv;
+	struct bvec_iter iter;
+	u64 segments_length = 0;
+
+	if (bio_op(bio) != REQ_OP_WRITE)
+		return map_length;
+
+	bio_for_each_segment(bv, bio, iter) {
+		segments_length += bv.bv_len;
+		if (++i == BIO_MAX_VECS)
+			return segments_length;
+	}
+
+	return map_length;
+}
+
 const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.inode_info_offs = (int)offsetof(struct btrfs_inode, i_crypt_info) -
 			   (int)offsetof(struct btrfs_inode, vfs_inode),
fs/btrfs/fscrypt.h +6 -0
index 68eab4606935..f7ce2b2e6639 100644
@@ -24,6 +24,7 @@ void btrfs_fscrypt_save_extent_info(struct btrfs_path *path, u8 *ctx, unsigned l
 ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *inode,
 					     struct fscrypt_extent_info *info,
 					     u8 *ctx);
+int btrfs_fscrypt_bio_length(struct bio *bio, u64 map_length);
 
 #else
 static inline void btrfs_fscrypt_save_extent_info(struct btrfs_path *path,
@@ -63,6 +64,11 @@ static inline ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *i
 	return -EINVAL;
 }
 
+static inline u64 btrfs_fscrypt_bio_length(struct bio *bio, u64 map_length)
+{
+	return map_length;
+}
+
 #endif /* CONFIG_FS_ENCRYPTION */
 
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
Signature · 1 line
2.53.0
#65 lore raw

PATCH v7 32/43 btrfs: implement process_bio cb for fscrypt

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We are going to be checksumming the encrypted data, so we have to implement the ->process_bio fscrypt callback. This will provide us with the original bio and the encrypted bio to do work on. For WRITE's this will happen after the encrypted bio has been encrypted. For READ's this will happen after the read has completed and before the decryption step is done.

For write's this is straightforward, we can just pass in the encrypted bio to btrfs_csum_one_bio and then the csums will be added to the bbio as normal.

For read's this is relatively straightforward, but requires some care. We assume (because that's how it works currently) that the encrypted bio match the original bio, this is important because we save the iter of the bio before we submit. If this changes in the future we'll need a hook to give us the bi_iter of the decryption bio before it's submitted. We check the csums before decryption. If it doesn't match we simply error out and we let the normal path handle the repair work.

---

v7 changes:
* Fixed array overflow stack corruption for bios > max blocksize (>64KiB)
as reported by Chris' AI review.
v6 changes:
* Adapt to btrfs_data_csum_ok() changes for bs > ps. Mostly follow
what was done in 052fd7a5cace ("btrfs: make read verification
handle bs > ps cases without large folios").
* Rename bbio::csum_done to csum_ok due to name collision.
With upstream, member name csum_done was used for async csums.
v5: https://lore.kernel.org/linux-btrfs/ca32684b01ff8c252be515509137e0a4a0e5db7a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c       | 44 +++++++++++++++++++++++++++++++++++++++++++-
 fs/btrfs/bio.h       |  3 +++
 fs/btrfs/file-item.c | 14 ++++++++++++--
 fs/btrfs/fscrypt.c   | 29 +++++++++++++++++++++++++++++
 4 files changed, 87 insertions(+), 3 deletions(-)
fs/btrfs/bio.c +43 -1
index 3e2ee19aab50..729c5aff5c3d 100644
@@ -301,6 +301,40 @@ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio,
 	return fbio;
 }
 
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio, struct bio *enc_bio)
+{
+	struct btrfs_inode *inode = bbio->inode;
+	struct btrfs_fs_info *fs_info = inode->root->fs_info;
+	struct bvec_iter iter = bbio->saved_iter;
+	struct btrfs_device *dev = bbio->bio.bi_private;
+	const u32 blocksize = fs_info->sectorsize;
+	const u32 step = min(blocksize, PAGE_SIZE);
+	const u32 nr_steps = iter.bi_size / step;
+	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
+	phys_addr_t paddr;
+	unsigned int slot = 0;
+	u32 offset = 0;
+
+	/*
+	 * We have to use a copy of iter in case there's an error,
+	 * btrfs_check_read_bio will handle submitting the repair bios.
+	 */
+	btrfs_bio_for_each_block(paddr, enc_bio, &iter, step) {
+		ASSERT(slot < nr_steps);
+		paddrs[slot] = paddr;
+		slot++;
+		offset += step;
+		if (IS_ALIGNED(offset, blocksize)) {
+			if (!btrfs_data_csum_ok(bbio, dev, offset - blocksize, paddrs))
+				return BLK_STS_IOERR;
+			slot = 0;
+		}
+	}
+
+	bbio->csum_ok = true;
+	return BLK_STS_OK;
+}
+
 static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *dev)
 {
 	struct btrfs_inode *inode = bbio->inode;
@@ -330,6 +364,10 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
 	/* Clear the I/O error. A failed repair will reset it. */
 	bbio->bio.bi_status = BLK_STS_OK;
 
+	/* This was an encrypted bio and we've already done the csum check. */
+	if (status == BLK_STS_OK && bbio->csum_ok)
+		goto out;
+
 	btrfs_bio_for_each_block(paddr, &bbio->bio, iter, step) {
 		paddrs[(offset / step) % nr_steps] = paddr;
 		offset += step;
@@ -341,6 +379,7 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
 							 paddrs, fbio);
 		}
 	}
+out:
 	if (bbio->csum != bbio->csum_inline)
 		kvfree(bbio->csum);
 
@@ -859,10 +898,13 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
 		/*
 		 * Csum items for reloc roots have already been cloned at this
 		 * point, so they are handled as part of the no-checksum case.
+		 *
+		 * Encrypted inodes are csum'ed via the ->process_bio callback.
 		 */
 		if (!(inode->flags & BTRFS_INODE_NODATASUM) &&
 		    !test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state) &&
-		    !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap) {
+		    !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap &&
+		    !IS_ENCRYPTED(&inode->vfs_inode)) {
 			if (should_async_write(bbio) &&
 			    btrfs_wq_submit_bio(bbio, bioc, &smap, mirror_num))
 				goto done;
fs/btrfs/bio.h +3 -0
index 43f7544029ac..456d32db9e9e 100644
@@ -43,6 +43,7 @@ struct btrfs_bio {
 		struct {
 			u8 *csum;
 			u8 csum_inline[BTRFS_BIO_INLINE_CSUM_SIZE];
+			bool csum_ok;
 			struct bvec_iter saved_iter;
 		};
 
@@ -130,5 +131,7 @@ void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_
 int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff,
 			    u32 length, u64 logical, const phys_addr_t paddrs[],
 			    unsigned int step, int mirror_num);
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio,
+					    struct bio *enc_bio);
 
 #endif
fs/btrfs/file-item.c +12 -2
index 986914078708..72d9d3243460 100644
@@ -338,6 +338,14 @@ static int search_csum_tree(struct btrfs_fs_info *fs_info,
 	return ret;
 }
 
+static inline bool inode_skip_csum(struct btrfs_inode *inode)
+{
+	struct btrfs_fs_info *fs_info = inode->root->fs_info;
+
+	return (inode->flags & BTRFS_INODE_NODATASUM) ||
+		test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
+}
+
 /*
  * Lookup the checksum for the read bio in csum tree.
  *
@@ -357,8 +365,7 @@ int btrfs_lookup_bio_sums(struct btrfs_bio *bbio)
 	int ret = 0;
 	u32 bio_offset = 0;
 
-	if ((inode->flags & BTRFS_INODE_NODATASUM) ||
-	    test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state))
+	if (inode_skip_csum(inode))
 		return 0;
 
 	/*
@@ -817,6 +824,9 @@ int btrfs_csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, bool async)
 	struct btrfs_ordered_sum *sums;
 	unsigned nofs_flag;
 
+	if (inode_skip_csum(inode))
+		return 0;
+
 	nofs_flag = memalloc_nofs_save();
 	sums = kvzalloc(btrfs_ordered_sum_size(fs_info, bio->bi_iter.bi_size),
 		       GFP_KERNEL);
fs/btrfs/fscrypt.c +29 -0
index 5d34a8b94da5..924ee3df7f32 100644
@@ -16,6 +16,7 @@
 #include "transaction.h"
 #include "volumes.h"
 #include "xattr.h"
+#include "file-item.h"
 
 /*
  * From a given location in a leaf, read a name into a qstr (usually a
@@ -212,6 +213,33 @@ static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb,
 	return devs;
 }
 
+static blk_status_t btrfs_process_encrypted_bio(struct bio *orig_bio,
+						struct bio *enc_bio)
+{
+	struct btrfs_bio *bbio;
+
+	/*
+	 * If our bio is from the normal fs_bio_set then we know this is a
+	 * mirror split and we can skip it, we'll get the real bio on the last
+	 * mirror and we can process that one.
+	 */
+	if (orig_bio->bi_pool == &fs_bio_set)
+		return BLK_STS_OK;
+
+	bbio = btrfs_bio(orig_bio);
+
+	if (bio_op(orig_bio) == REQ_OP_READ) {
+		/*
+		 * We have ->saved_iter based on the orig_bio, so if the block
+		 * layer changes we need to notice this asap so we can update
+		 * our code to handle the new world order.
+		 */
+		ASSERT(orig_bio == enc_bio);
+		return btrfs_check_encrypted_read_bio(bbio, enc_bio);
+	}
+	return btrfs_csum_one_bio(bbio, enc_bio, false);
+}
+
 int btrfs_fscrypt_load_extent_info(struct btrfs_inode *inode,
 				   struct btrfs_path *path,
 				   struct btrfs_key *key,
@@ -327,4 +355,5 @@ const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.set_context = btrfs_fscrypt_set_context,
 	.empty_dir = btrfs_fscrypt_empty_dir,
 	.get_devices = btrfs_fscrypt_get_devices,
+	.process_bio = btrfs_process_encrypted_bio,
 };
Signature · 1 line
2.53.0
#66 lore raw

Re: [PATCH v7 32/43] btrfs: implement process_bio cb for fscrypt

Quoted 211 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

We are going to be checksumming the encrypted data, so we have to implement the ->process_bio fscrypt callback. This will provide us with the original bio and the encrypted bio to do work on. For WRITE's this will happen after the encrypted bio has been encrypted. For READ's this will happen after the read has completed and before the decryption step is done.

For write's this is straightforward, we can just pass in the encrypted bio to btrfs_csum_one_bio and then the csums will be added to the bbio as normal.

For read's this is relatively straightforward, but requires some care. We assume (because that's how it works currently) that the encrypted bio match the original bio, this is important because we save the iter of the bio before we submit. If this changes in the future we'll need a hook to give us the bi_iter of the decryption bio before it's submitted. We check the csums before decryption. If it doesn't match we simply error out and we let the normal path handle the repair work.

---

v7 changes:
* Fixed array overflow stack corruption for bios > max blocksize (>64KiB)
as reported by Chris' AI review.
v6 changes:
* Adapt to btrfs_data_csum_ok() changes for bs > ps. Mostly follow
what was done in 052fd7a5cace ("btrfs: make read verification
handle bs > ps cases without large folios").
* Rename bbio::csum_done to csum_ok due to name collision.
With upstream, member name csum_done was used for async csums.
v5: https://lore.kernel.org/linux-btrfs/ca32684b01ff8c252be515509137e0a4a0e5db7a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c       | 44 +++++++++++++++++++++++++++++++++++++++++++-
 fs/btrfs/bio.h       |  3 +++
 fs/btrfs/file-item.c | 14 ++++++++++++--
 fs/btrfs/fscrypt.c   | 29 +++++++++++++++++++++++++++++
 4 files changed, 87 insertions(+), 3 deletions(-)
fs/btrfs/bio.c +43 -1
index 3e2ee19aab50..729c5aff5c3d 100644
@@ -301,6 +301,40 @@ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio,
 	return fbio;
 }
 
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio, struct bio *enc_bio)
+{
+	struct btrfs_inode *inode = bbio->inode;
+	struct btrfs_fs_info *fs_info = inode->root->fs_info;
+	struct bvec_iter iter = bbio->saved_iter;
+	struct btrfs_device *dev = bbio->bio.bi_private;
+	const u32 blocksize = fs_info->sectorsize;
+	const u32 step = min(blocksize, PAGE_SIZE);
+	const u32 nr_steps = iter.bi_size / step;
+	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
+	phys_addr_t paddr;
+	unsigned int slot = 0;
+	u32 offset = 0;
+
+	/*
+	 * We have to use a copy of iter in case there's an error,
+	 * btrfs_check_read_bio will handle submitting the repair bios.
+	 */
+	btrfs_bio_for_each_block(paddr, enc_bio, &iter, step) {
+		ASSERT(slot < nr_steps);
+		paddrs[slot] = paddr;
+		slot++;
+		offset += step;
+		if (IS_ALIGNED(offset, blocksize)) {
+			if (!btrfs_data_csum_ok(bbio, dev, offset - blocksize, paddrs))
+				return BLK_STS_IOERR;
+			slot = 0;
+		}
+	}
+
+	bbio->csum_ok = true;
+	return BLK_STS_OK;
+}
+
 static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *dev)
 {
 	struct btrfs_inode *inode = bbio->inode;
@@ -330,6 +364,10 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
 	/* Clear the I/O error. A failed repair will reset it. */
 	bbio->bio.bi_status = BLK_STS_OK;
 
+	/* This was an encrypted bio and we've already done the csum check. */
+	if (status == BLK_STS_OK && bbio->csum_ok)
+		goto out;
+
 	btrfs_bio_for_each_block(paddr, &bbio->bio, iter, step) {
 		paddrs[(offset / step) % nr_steps] = paddr;
 		offset += step;
@@ -341,6 +379,7 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
 							 paddrs, fbio);
 		}
 	}
+out:
 	if (bbio->csum != bbio->csum_inline)
 		kvfree(bbio->csum);
 
@@ -859,10 +898,13 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
 		/*
 		 * Csum items for reloc roots have already been cloned at this
 		 * point, so they are handled as part of the no-checksum case.
+		 *
+		 * Encrypted inodes are csum'ed via the ->process_bio callback.
 		 */
 		if (!(inode->flags & BTRFS_INODE_NODATASUM) &&
 		    !test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state) &&
-		    !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap) {
+		    !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap &&
+		    !IS_ENCRYPTED(&inode->vfs_inode)) {
 			if (should_async_write(bbio) &&
 			    btrfs_wq_submit_bio(bbio, bioc, &smap, mirror_num))
 				goto done;
fs/btrfs/bio.h +3 -0
index 43f7544029ac..456d32db9e9e 100644
@@ -43,6 +43,7 @@ struct btrfs_bio {
 		struct {
 			u8 *csum;
 			u8 csum_inline[BTRFS_BIO_INLINE_CSUM_SIZE];
+			bool csum_ok;
 			struct bvec_iter saved_iter;
 		};
 
@@ -130,5 +131,7 @@ void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_
 int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff,
 			    u32 length, u64 logical, const phys_addr_t paddrs[],
 			    unsigned int step, int mirror_num);
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio,
+					    struct bio *enc_bio);
 
 #endif
fs/btrfs/file-item.c +12 -2
index 986914078708..72d9d3243460 100644
@@ -338,6 +338,14 @@ static int search_csum_tree(struct btrfs_fs_info *fs_info,
 	return ret;
 }
 
+static inline bool inode_skip_csum(struct btrfs_inode *inode)
+{
+	struct btrfs_fs_info *fs_info = inode->root->fs_info;
+
+	return (inode->flags & BTRFS_INODE_NODATASUM) ||
+		test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
+}
+
 /*
  * Lookup the checksum for the read bio in csum tree.
  *
@@ -357,8 +365,7 @@ int btrfs_lookup_bio_sums(struct btrfs_bio *bbio)
 	int ret = 0;
 	u32 bio_offset = 0;
 
-	if ((inode->flags & BTRFS_INODE_NODATASUM) ||
-	    test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state))
+	if (inode_skip_csum(inode))
 		return 0;
 
 	/*
@@ -817,6 +824,9 @@ int btrfs_csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, bool async)
 	struct btrfs_ordered_sum *sums;
 	unsigned nofs_flag;
 
+	if (inode_skip_csum(inode))
+		return 0;
+
 	nofs_flag = memalloc_nofs_save();
 	sums = kvzalloc(btrfs_ordered_sum_size(fs_info, bio->bi_iter.bi_size),
 		       GFP_KERNEL);
fs/btrfs/fscrypt.c +16 -0
index 5d34a8b94da5..924ee3df7f32 100644
@@ -16,6 +16,7 @@
 #include "transaction.h"
 #include "volumes.h"
 #include "xattr.h"
+#include "file-item.h"
 
 /*
  * From a given location in a leaf, read a name into a qstr (usually a
@@ -212,6 +213,33 @@ static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb,
 	return devs;
 }
 
+static blk_status_t btrfs_process_encrypted_bio(struct bio *orig_bio,
+						struct bio *enc_bio)
+{
+	struct btrfs_bio *bbio;
+
+	/*
+	 * If our bio is from the normal fs_bio_set then we know this is a
+	 * mirror split and we can skip it, we'll get the real bio on the last
+	 * mirror and we can process that one.
+	 */
+	if (orig_bio->bi_pool == &fs_bio_set)
+		return BLK_STS_OK;
+
+	bbio = btrfs_bio(orig_bio);
+

fs/btrfs/fscrypt.c static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb, · line 240

Quoted 10 lines
fs/btrfs/fscrypt.c +10 -0
+	if (bio_op(orig_bio) == REQ_OP_READ) {
+		/*
+		 * We have ->saved_iter based on the orig_bio, so if the block
+		 * layer changes we need to notice this asap so we can update
+		 * our code to handle the new world order.
+		 */
+		ASSERT(orig_bio == enc_bio);
+		return btrfs_check_encrypted_read_bio(bbio, enc_bio);
+	}
+	return btrfs_csum_one_bio(bbio, enc_bio, false);

Honestly, all this shows that the architecture of the I/O path in this series is pretty broken. It needs all this magic detection, and the passing of arguments that mixes the bbio for state and the lower encrypted bio without the btrfs context shows something doesn't work well.

So let's take a step back, if we think of the I/O pipeline, it should do things in this order for writes:

- encrypt data
- generate checksums
- do mirroring/striping/parity

and reverse for reads.

All this suggest that the btrfs_bio needs to exist for the encrypted data. So I think you'll need to and refactor this, preferably with the really annoying two-level callbacks that this really hard to follow (or implement). Your caller is in the file system, and it should be able to call fscrypt as helpers instead of going two layers down using direct calls and then two layers back up using indirect calls. The recent refactoring that moves the fscrypt fallback above the block layer instead of calling it from the bottom should help a lot with that.

#67 lore raw

Re: [PATCH v7 32/43] btrfs: implement process_bio cb for fscrypt

Quoted 220 lines · Christoph Hellwig
Quoted 219 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

We are going to be checksumming the encrypted data, so we have to implement the ->process_bio fscrypt callback. This will provide us with the original bio and the encrypted bio to do work on. For WRITE's this will happen after the encrypted bio has been encrypted. For READ's this will happen after the read has completed and before the decryption step is done.

For write's this is straightforward, we can just pass in the encrypted bio to btrfs_csum_one_bio and then the csums will be added to the bbio as normal.

For read's this is relatively straightforward, but requires some care. We assume (because that's how it works currently) that the encrypted bio match the original bio, this is important because we save the iter of the bio before we submit. If this changes in the future we'll need a hook to give us the bi_iter of the decryption bio before it's submitted. We check the csums before decryption. If it doesn't match we simply error out and we let the normal path handle the repair work.

---

v7 changes:
* Fixed array overflow stack corruption for bios > max blocksize (>64KiB)
as reported by Chris' AI review.
v6 changes:
* Adapt to btrfs_data_csum_ok() changes for bs > ps. Mostly follow
what was done in 052fd7a5cace ("btrfs: make read verification
handle bs > ps cases without large folios").
* Rename bbio::csum_done to csum_ok due to name collision.
With upstream, member name csum_done was used for async csums.
v5: https://lore.kernel.org/linux-btrfs/ca32684b01ff8c252be515509137e0a4a0e5db7a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c       | 44 +++++++++++++++++++++++++++++++++++++++++++-
 fs/btrfs/bio.h       |  3 +++
 fs/btrfs/file-item.c | 14 ++++++++++++--
 fs/btrfs/fscrypt.c   | 29 +++++++++++++++++++++++++++++
 4 files changed, 87 insertions(+), 3 deletions(-)
fs/btrfs/bio.c +43 -1
index 3e2ee19aab50..729c5aff5c3d 100644
@@ -301,6 +301,40 @@ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio,
      return fbio;
 }
 
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio, struct bio *enc_bio)
+{
+     struct btrfs_inode *inode = bbio->inode;
+     struct btrfs_fs_info *fs_info = inode->root->fs_info;
+     struct bvec_iter iter = bbio->saved_iter;
+     struct btrfs_device *dev = bbio->bio.bi_private;
+     const u32 blocksize = fs_info->sectorsize;
+     const u32 step = min(blocksize, PAGE_SIZE);
+     const u32 nr_steps = iter.bi_size / step;
+     phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
+     phys_addr_t paddr;
+     unsigned int slot = 0;
+     u32 offset = 0;
+
+     /*
+      * We have to use a copy of iter in case there's an error,
+      * btrfs_check_read_bio will handle submitting the repair bios.
+      */
+     btrfs_bio_for_each_block(paddr, enc_bio, &iter, step) {
+             ASSERT(slot < nr_steps);
+             paddrs[slot] = paddr;
+             slot++;
+             offset += step;
+             if (IS_ALIGNED(offset, blocksize)) {
+                     if (!btrfs_data_csum_ok(bbio, dev, offset - blocksize, paddrs))
+                             return BLK_STS_IOERR;
+                     slot = 0;
+             }
+     }
+
+     bbio->csum_ok = true;
+     return BLK_STS_OK;
+}
+
 static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *dev)
 {
      struct btrfs_inode *inode = bbio->inode;
@@ -330,6 +364,10 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
      /* Clear the I/O error. A failed repair will reset it. */
      bbio->bio.bi_status = BLK_STS_OK;
 
+     /* This was an encrypted bio and we've already done the csum check. */
+     if (status == BLK_STS_OK && bbio->csum_ok)
+             goto out;
+
      btrfs_bio_for_each_block(paddr, &bbio->bio, iter, step) {
              paddrs[(offset / step) % nr_steps] = paddr;
              offset += step;
@@ -341,6 +379,7 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
                                                       paddrs, fbio);
              }
      }
+out:
      if (bbio->csum != bbio->csum_inline)
              kvfree(bbio->csum);
 
@@ -859,10 +898,13 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num)
              /*
               * Csum items for reloc roots have already been cloned at this
               * point, so they are handled as part of the no-checksum case.
+              *
+              * Encrypted inodes are csum'ed via the ->process_bio callback.
               */
              if (!(inode->flags & BTRFS_INODE_NODATASUM) &&
                  !test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state) &&
-                 !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap) {
+                 !btrfs_is_data_reloc_root(inode->root) && !bbio->is_remap &&
+                 !IS_ENCRYPTED(&inode->vfs_inode)) {
                      if (should_async_write(bbio) &&
                          btrfs_wq_submit_bio(bbio, bioc, &smap, mirror_num))
                              goto done;
fs/btrfs/bio.h +3 -0
index 43f7544029ac..456d32db9e9e 100644
@@ -43,6 +43,7 @@ struct btrfs_bio {
              struct {
                      u8 *csum;
                      u8 csum_inline[BTRFS_BIO_INLINE_CSUM_SIZE];
+                     bool csum_ok;
                      struct bvec_iter saved_iter;
              };
 
@@ -130,5 +131,7 @@ void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_
 int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff,
                          u32 length, u64 logical, const phys_addr_t paddrs[],
                          unsigned int step, int mirror_num);
+blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio,
+                                         struct bio *enc_bio);
 
 #endif
fs/btrfs/file-item.c +12 -2
index 986914078708..72d9d3243460 100644
@@ -338,6 +338,14 @@ static int search_csum_tree(struct btrfs_fs_info *fs_info,
      return ret;
 }
 
+static inline bool inode_skip_csum(struct btrfs_inode *inode)
+{
+     struct btrfs_fs_info *fs_info = inode->root->fs_info;
+
+     return (inode->flags & BTRFS_INODE_NODATASUM) ||
+             test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
+}
+
 /*
  * Lookup the checksum for the read bio in csum tree.
  *
@@ -357,8 +365,7 @@ int btrfs_lookup_bio_sums(struct btrfs_bio *bbio)
      int ret = 0;
      u32 bio_offset = 0;
 
-     if ((inode->flags & BTRFS_INODE_NODATASUM) ||
-         test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state))
+     if (inode_skip_csum(inode))
              return 0;
 
      /*
@@ -817,6 +824,9 @@ int btrfs_csum_one_bio(struct btrfs_bio *bbio, struct bio *bio, bool async)
      struct btrfs_ordered_sum *sums;
      unsigned nofs_flag;
 
+     if (inode_skip_csum(inode))
+             return 0;
+
      nofs_flag = memalloc_nofs_save();
      sums = kvzalloc(btrfs_ordered_sum_size(fs_info, bio->bi_iter.bi_size),
                     GFP_KERNEL);
fs/btrfs/fscrypt.c +24 -0
index 5d34a8b94da5..924ee3df7f32 100644
@@ -16,6 +16,7 @@
 #include "transaction.h"
 #include "volumes.h"
 #include "xattr.h"
+#include "file-item.h"
 
 /*
  * From a given location in a leaf, read a name into a qstr (usually a
@@ -212,6 +213,33 @@ static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb,
      return devs;
 }
 
+static blk_status_t btrfs_process_encrypted_bio(struct bio *orig_bio,
+                                             struct bio *enc_bio)
+{
+     struct btrfs_bio *bbio;
+
+     /*
+      * If our bio is from the normal fs_bio_set then we know this is a
+      * mirror split and we can skip it, we'll get the real bio on the last
+      * mirror and we can process that one.
+      */
+     if (orig_bio->bi_pool == &fs_bio_set)
+             return BLK_STS_OK;
+
+     bbio = btrfs_bio(orig_bio);
+
+     if (bio_op(orig_bio) == REQ_OP_READ) {
+             /*
+              * We have ->saved_iter based on the orig_bio, so if the block
+              * layer changes we need to notice this asap so we can update
+              * our code to handle the new world order.
+              */
+             ASSERT(orig_bio == enc_bio);
+             return btrfs_check_encrypted_read_bio(bbio, enc_bio);
Quoted 8 lines

fs/btrfs/fscrypt.c static struct block_device **btrfs_fscrypt_get_devices(struct super_block *sb, · line 240

Quoted 2 lines
fs/btrfs/fscrypt.c +2 -0
+     }
+     return btrfs_csum_one_bio(bbio, enc_bio, false);

Honestly, all this shows that the architecture of the I/O path in this series is pretty broken. It needs all this magic detection, and the passing of arguments that mixes the bbio for state and the lower encrypted bio without the btrfs context shows something doesn't work well.

Well, this is all limited within the scope of the filesystem. Since btrfs needs to compute the data checksum and the bounce bio (with the encrypted pages) is created by the lower fscrypt layer, how else could we accomplish this?

As the blk-crypto is inlined, without the callback the filesystem never sees the encrypted data at all and it won't be able to get checksums.

Quoted 11 lines

So let's take a step back, if we think of the I/O pipeline, it should do things in this order for writes:

- encrypt data
- generate checksums
- do mirroring/striping/parity

and reverse for reads.

All this suggest that the btrfs_bio needs to exist for the encrypted data.

My understanding was that fscrypt works differently. The bounce bio is created inline in the lower layer, agnostic to any filesystem.

Quoted 7 lines

So I think you'll need to and refactor this, preferably with the
really annoying two-level callbacks that this really hard to follow (or implement). Your caller is in the file system, and it should be able to call fscrypt as helpers instead of going two layers down using direct calls and then two layers back up using indirect calls. The recent refactoring that moves the fscrypt fallback above the block layer instead of calling it from the bottom should help a lot with that.

Yeah, I may look into that. What you're talking about is a pretty recent change. This is an old patch [1] from 2023 rebased without many changes since as there was not much feedback before. So it still follows the original (former) design.

If fscrypt supported checksumming the encrypted data and returned the value back to the filesystem, no callbacks would be needed. Though to me that sounds more invasive than this callback.

[1] https://lore.kernel.org/linux-btrfs/a26514814b4d2a54ff2317369365dc2bf1c280dc.1695750478.git.josef@toxicpanda.com/

--nX

#68 lore raw

PATCH v7 33/43 btrfs: implement read repair for encryption

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

In order to do read repair we will allocate sectorsize bio's and read them one at a time, repairing any sectors that don't match their csum. In order to do this we re-submit the IO's after it's failed, and at this point we still need the fscrypt_extent_info for these new bio's.

Add the fscrypt_extent_info to the read part of the union in the btrfs_bio, and then pass this through all the places where we do reads. Additionally add the orig_start, because we need to be able to put the correct extent offset for the encryption context.

With these in place we can utilize the normal read repair path. The only exception is that the actual repair of the bad copies has to be triggered from the ->process_bio callback, because this is the encrypted data. If we waited until the end_io we would have the decrypted data and we don't want to write that to the disk. This is the only change to the normal read repair path, we trigger the fixup of the broken sectors in ->process_bio, and then we skip that part if we successfully repair the sector in ->process_bio once we get to the endio.

---

v7 changes:
* Follow upstream fscrypt cleanup and use byte offsets instead of
logical block numbers in the new api. As a result remove the btrfs_set_bio_crypt_ctx_from_extent() and btrfs_mergeable_encrypted_bio()
helpers and directly use fscrypt_set_bio_crypt_ctx_from_extent()
and fscrypt_mergeable_extent_bio().
v6 changes:
* Fixed UAF bug with !ordered case doing bbio->end_io(bbio) >>> fscrypt_put_extent_info(bbio->fscrypt_info).
- We can simply put the fscrypt_info first and then end the bio.
- Also no need to clear the bbio->fscrypt_info pointer as bbio is
just going to be freed. That cleans up the code a bit.
* Adapted to bs > ps changes.
* Updated and re-wrap the comments.
* Moved the dio-related changes from inode.c to direct-io.c
as upstream refactored in the meantime.
v5: https://lore.kernel.org/linux-btrfs/310c0ebdc78613b6f379595e160206013f75b6dc.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/bio.c         | 76 +++++++++++++++++++++++++++++++++++++-----
 fs/btrfs/bio.h         | 10 +++++-
 fs/btrfs/compression.c |  2 ++
 fs/btrfs/direct-io.c   |  2 ++
 fs/btrfs/extent_io.c   |  2 ++
 5 files changed, 83 insertions(+), 9 deletions(-)
fs/btrfs/bio.c +68 -8
index 729c5aff5c3d..3a8f32c5157f 100644
@@ -98,6 +98,9 @@ static struct btrfs_bio *btrfs_split_bio(struct btrfs_fs_info *fs_info,
 		bbio->ordered = orig_bbio->ordered;
 		bbio->orig_logical = orig_bbio->orig_logical;
 		orig_bbio->orig_logical += map_length;
+	} else if (is_data_bbio(bbio)) {
+		bbio->fscrypt_info = fscrypt_get_extent_info(orig_bbio->fscrypt_info);
+		bbio->orig_start = orig_bbio->orig_start;
 	}
 
 	bbio->csum_search_commit_root = orig_bbio->csum_search_commit_root;
@@ -125,6 +128,8 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status)
 		/* Free bio that was never submitted to the underlying device. */
 		if (bbio_has_ordered_extent(bbio))
 			btrfs_put_ordered_extent(bbio->ordered);
+		else if (is_data_bbio(bbio))
+			fscrypt_put_extent_info(bbio->fscrypt_info);
 		bio_put(&bbio->bio);
 
 		bbio = orig_bbio;
@@ -148,6 +153,8 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status)
 			bbio->end_io(bbio);
 			btrfs_put_ordered_extent(ordered);
 		} else {
+			if (is_data_bbio(bbio))
+				fscrypt_put_extent_info(bbio->fscrypt_info);
 			bbio->end_io(bbio);
 		}
 	}
@@ -175,6 +182,23 @@ static void btrfs_repair_done(struct btrfs_failed_bio *fbio)
 	}
 }
 
+static void handle_repair(struct btrfs_bio *repair_bbio, phys_addr_t *paddrs)
+{
+	struct btrfs_failed_bio *fbio = repair_bbio->private;
+	struct btrfs_inode *inode = repair_bbio->inode;
+	struct btrfs_fs_info *fs_info = inode->root->fs_info;
+	const u32 step = min(fs_info->sectorsize, PAGE_SIZE);
+	const u64 logical = repair_bbio->saved_iter.bi_sector << SECTOR_SHIFT;
+	int mirror = repair_bbio->mirror_num;
+
+	do {
+		mirror = prev_repair_mirror(fbio, mirror);
+		btrfs_repair_io_failure(fs_info, btrfs_ino(inode),
+				  repair_bbio->file_offset, fs_info->sectorsize,
+				  logical, paddrs, step, mirror);
+	} while (mirror != fbio->bbio->mirror_num);
+}
+
 static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio,
 				 struct btrfs_device *dev)
 {
@@ -187,7 +211,6 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio,
 	 */
 	struct bvec_iter saved_iter = repair_bbio->saved_iter;
 	const u32 step = min(fs_info->sectorsize, PAGE_SIZE);
-	const u64 logical = repair_bbio->saved_iter.bi_sector << SECTOR_SHIFT;
 	const u32 nr_steps = repair_bbio->saved_iter.bi_size / step;
 	int mirror = repair_bbio->mirror_num;
 	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
@@ -197,6 +220,13 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio,
 	/* Repair bbio should be eaxctly one block sized. */
 	ASSERT(repair_bbio->saved_iter.bi_size == fs_info->sectorsize);
 
+	/*
+	 * If we got here from the encrypted path with ->csum_ok set then
+	 * we've already csumed and repaired this sector, we're all done.
+	 */
+	if (repair_bbio->csum_ok)
+		goto done;
+
 	btrfs_bio_for_each_block(paddr, &repair_bbio->bio, &saved_iter, step) {
 		ASSERT(slot < nr_steps);
 		paddrs[slot] = paddr;
@@ -215,17 +245,17 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio,
 			goto done;
 		}
 
+		fscrypt_set_bio_crypt_ctx_from_extent(&repair_bbio->bio,
+						       repair_bbio->fscrypt_info,
+						       repair_bbio->file_offset -
+						       repair_bbio->orig_start,
+						       GFP_NOFS);
+
 		btrfs_submit_bbio(repair_bbio, mirror);
 		return;
 	}
 
-	do {
-		mirror = prev_repair_mirror(fbio, mirror);
-		btrfs_repair_io_failure(fs_info, btrfs_ino(inode),
-				  repair_bbio->file_offset, fs_info->sectorsize,
-				  logical, paddrs, step, mirror);
-	} while (mirror != fbio->bbio->mirror_num);
-
+	handle_repair(repair_bbio, paddrs);
 done:
 	btrfs_repair_done(fbio);
 	bio_put(&repair_bbio->bio);
@@ -294,6 +324,14 @@ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio,
 	repair_bbio = btrfs_bio(repair_bio);
 	btrfs_bio_init(repair_bbio, failed_bbio->inode, failed_bbio->file_offset + bio_offset,
 		       NULL, fbio);
+	repair_bbio->fscrypt_info = fscrypt_get_extent_info(failed_bbio->fscrypt_info);
+	repair_bbio->orig_start = failed_bbio->orig_start;
+
+	fscrypt_set_bio_crypt_ctx_from_extent(repair_bio,
+					      failed_bbio->fscrypt_info,
+					      repair_bbio->file_offset -
+					      failed_bbio->orig_start,
+					      GFP_NOFS);
 
 	mirror = next_repair_mirror(fbio, failed_bbio->mirror_num);
 	btrfs_debug(fs_info, "submitting repair read to mirror %d", mirror);
@@ -331,7 +369,29 @@ blk_status_t btrfs_check_encrypted_read_bio(struct btrfs_bio *bbio, struct bio *
 		}
 	}
 
+	/*
+	 * Read repair is slightly different for encrypted bio's.  This
+	 * callback is before we decrypt the bio in the block crypto layer,
+	 * we're not actually in the endio handler.
+	 *
+	 * We don't trigger the repair process here either, that is handled
+	 * in the actual endio path because we don't want to create another
+	 * pseudo endio path through this callback.  This is because when we
+	 * call btrfs_repair_done() we want to call the endio for the original
+	 * bbio. Short circuiting that for the encrypted case would be ugly.
+	 * We really want to the repair case to be handled generically.
+	 *
+	 * However for the actual repair part we need to use this page
+	 * pre-decrypted, which is why we call the btrfs_repair_io_failure()
+	 * code from this path.  The repair path is synchronous so we are
+	 * safe there.  Then we simply mark the repair bbio as completed so
+	 * the actual btrfs_end_repair_bio() code can skip the repair part.
+	 */
+	if (bbio->bio.bi_pool == &btrfs_repair_bioset)
+		handle_repair(bbio, paddrs);
 	bbio->csum_ok = true;
+	fscrypt_put_extent_info(bbio->fscrypt_info);
+	bbio->fscrypt_info = NULL;
 	return BLK_STS_OK;
 }
 
fs/btrfs/bio.h +9 -1
index 456d32db9e9e..7a8ff4378cba 100644
@@ -15,6 +15,7 @@
 struct btrfs_bio;
 struct btrfs_fs_info;
 struct btrfs_inode;
+struct fscrypt_extent_info;
 
 #define BTRFS_BIO_INLINE_CSUM_SIZE	64
 
@@ -38,13 +39,20 @@ struct btrfs_bio {
 	union {
 		/*
 		 * For data reads: checksumming and original I/O information.
-		 * (for internal use in the btrfs_submit_bbio() machinery only)
+		 * (for internal use in the btrfs_submit_bbio() machinery only).
+		 *
+		 * The fscrypt context is used for read repair, this is the
+		 * only thing not internal to btrfs_submit_bbio() machinery.
 		 */
 		struct {
 			u8 *csum;
 			u8 csum_inline[BTRFS_BIO_INLINE_CSUM_SIZE];
 			bool csum_ok;
 			struct bvec_iter saved_iter;
+
+			/* Used for read repair. */
+			struct fscrypt_extent_info *fscrypt_info;
+			u64 orig_start;
 		};
 
 		/*
fs/btrfs/compression.c +2 -0
index e235a2ac5838..8269258d0dc4 100644
@@ -592,6 +592,8 @@ void btrfs_submit_compressed_read(struct btrfs_bio *bbio)
 	cb->compress_type = btrfs_extent_map_compression(em);
 	cb->orig_bbio = bbio;
 	cb->bbio.csum_search_commit_root = bbio->csum_search_commit_root;
+	cb->bbio.fscrypt_info = fscrypt_get_extent_info(em->fscrypt_info);
+	cb->bbio.orig_start = 0;
 
 	fscrypt_set_bio_crypt_ctx_from_extent(&cb->bbio.bio, em->fscrypt_info, 0, GFP_NOFS);
 	btrfs_free_extent_map(em);
fs/btrfs/direct-io.c +2 -0
index 4891bf233536..bef4e2f953e4 100644
@@ -764,6 +764,8 @@ static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio,
 	} else {
 		fscrypt_info = dio_data->fscrypt_info;
 		offset = file_offset - dio_data->orig_start;
+		bbio->fscrypt_info = fscrypt_get_extent_info(fscrypt_info);
+		bbio->orig_start = dio_data->orig_start;
 	}
 
 	fscrypt_set_bio_crypt_ctx_from_extent(&bbio->bio, fscrypt_info, offset, GFP_NOFS);
fs/btrfs/extent_io.c +2 -0
index 5e9cdcdc996a..32e39837294b 100644
@@ -795,6 +795,8 @@ static void alloc_new_bio(struct btrfs_inode *inode,
 	} else {
 		fscrypt_info = bio_ctrl->fscrypt_info;
 		offset = file_offset - bio_ctrl->orig_start;
+		bbio->fscrypt_info = fscrypt_get_extent_info(fscrypt_info);
+		bbio->orig_start = bio_ctrl->orig_start;
 	}
 
 	fscrypt_set_bio_crypt_ctx_from_extent(&bbio->bio, fscrypt_info, offset, GFP_NOFS);
Signature · 1 line
2.53.0
#69 lore raw

PATCH v7 34/43 btrfs: add test_dummy_encryption support

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

In order to enable more thorough testing of fscrypt enable the test_dummy_encryption mount option. This is used by fscrypt users to easily enable fscrypt on the file system for testing without needing to do the key setup and everything.

The only deviation from other file systems we make is we only support the fsparam_flag version of this mount option, as it defaults to v2. We don't want to have to bother with rejecting v1 related mount options.

---

v5: https://lore.kernel.org/linux-btrfs/77449ee5a882db2945429946c74ea7e796122328.1706116485.git.josef@toxicpanda.com/
* No changes since. Just re-wrapping. We now accept longer lines.

---
 fs/btrfs/disk-io.c |  1 +
 fs/btrfs/fs.h      |  3 +++
 fs/btrfs/fscrypt.c |  6 +++++
 fs/btrfs/super.c   | 58 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 68 insertions(+)
fs/btrfs/disk-io.c +1 -0
index 8a11be02eeb9..1f0fe29dd549 100644
@@ -1230,6 +1230,7 @@ void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
 	btrfs_extent_buffer_leak_debug_check(fs_info);
 	kfree(fs_info->super_copy);
 	kfree(fs_info->super_for_commit);
+	fscrypt_free_dummy_policy(&fs_info->dummy_enc_policy);
 	kvfree(fs_info);
 }
 
fs/btrfs/fs.h +3 -0
index dbdb73722c14..b21909d37b56 100644
@@ -28,6 +28,7 @@
 #include <linux/rbtree.h>
 #include <linux/xxhash.h>
 #include <linux/fserror.h>
+#include <linux/fscrypt.h>
 #include <uapi/linux/btrfs.h>
 #include <uapi/linux/btrfs_tree.h>
 #include "extent-io-tree.h"
@@ -270,6 +271,7 @@ enum {
 	BTRFS_MOUNT_IGNOREMETACSUMS		= (1ULL << 31),
 	BTRFS_MOUNT_IGNORESUPERFLAGS		= (1ULL << 32),
 	BTRFS_MOUNT_REF_TRACKER			= (1ULL << 33),
+	BTRFS_MOUNT_TEST_DUMMY_ENCRYPTION	= (1ULL << 34),
 };
 
 /* These mount options require a full read-only fs, no new transaction is allowed. */
@@ -958,6 +960,7 @@ struct btrfs_fs_info {
 	spinlock_t eb_leak_lock;
 	struct list_head allocated_ebs;
 #endif
+	struct fscrypt_dummy_policy dummy_enc_policy;
 };
 
 #define folio_to_inode(_folio)	(BTRFS_I(_Generic((_folio),			\
fs/btrfs/fscrypt.c +6 -0
index 924ee3df7f32..111ca92a3450 100644
@@ -240,6 +240,11 @@ static blk_status_t btrfs_process_encrypted_bio(struct bio *orig_bio,
 	return btrfs_csum_one_bio(bbio, enc_bio, false);
 }
 
+static const union fscrypt_policy *btrfs_get_dummy_policy(struct super_block *sb)
+{
+	return btrfs_sb(sb)->dummy_enc_policy.policy;
+}
+
 int btrfs_fscrypt_load_extent_info(struct btrfs_inode *inode,
 				   struct btrfs_path *path,
 				   struct btrfs_key *key,
@@ -356,4 +361,5 @@ const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.empty_dir = btrfs_fscrypt_empty_dir,
 	.get_devices = btrfs_fscrypt_get_devices,
 	.process_bio = btrfs_process_encrypted_bio,
+	.get_dummy_policy = btrfs_get_dummy_policy,
 };
fs/btrfs/super.c +58 -0

124 lines not on this page · raw message

Signature · 1 line
2.53.0
#70 lore raw

PATCH v7 35/43 btrfs: make btrfs_ref_to_path handle encrypted filenames

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We use this helper for inode-resolve and path resolution in send, so update this helper to properly decrypt any encrypted names it finds.

---

v7 changes:
* Fix eb leak in failure case as suggested by Chris' AI review.
v6 changes:
* Adapted to btrfs_iget() now returning binode instead of vfs inode
as before.
* Adapted to crypt info being moved from vfs inode to FS specific inode.
v5: https://lore.kernel.org/linux-btrfs/365d4f820f70b7cf69b1b9cae9b949a15c3350b0.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/backref.c | 43 ++++++++++++++++++++++++++++++++++++++----
 fs/btrfs/fscrypt.c | 47 ++++++++++++++++++++++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h | 10 ++++++++++
 3 files changed, 96 insertions(+), 4 deletions(-)
fs/btrfs/backref.c +39 -4
index 273924ca912c..33d5df99be8e 100644
@@ -20,6 +20,7 @@
 #include "extent-tree.h"
 #include "relocation.h"
 #include "tree-checker.h"
+#include "fscrypt.h"
 
 /* Just arbitrary numbers so we can be sure one of these happened. */
 #define BACKREF_FOUND_SHARED     6
@@ -2104,6 +2105,39 @@ int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
 	return ret;
 }
 
+static int copy_resolved_iref_to_buf(struct btrfs_root *fs_root,
+				     struct extent_buffer *eb, char *dest,
+				     u64 parent, unsigned long name_off,
+				     u32 name_len, s64 *bytes_left)
+{
+	struct btrfs_fs_info *fs_info = fs_root->fs_info;
+	struct fscrypt_str fname = FSTR_INIT(NULL, 0);
+	int ret;
+
+	/* No encryption, just copy the name in. */
+	if (!btrfs_fs_incompat(fs_info, ENCRYPT)) {
+		*bytes_left -= name_len;
+		if (*bytes_left >= 0)
+			read_extent_buffer(eb, dest + *bytes_left, name_off, name_len);
+		return 0;
+	}
+
+	ret = fscrypt_fname_alloc_buffer(BTRFS_NAME_LEN, &fname);
+	if (ret)
+		return ret;
+
+	ret = btrfs_decrypt_name(fs_root, eb, name_off, name_len, parent, &fname);
+	if (ret)
+		goto out;
+
+	*bytes_left -= fname.len;
+	if (*bytes_left >= 0)
+		memcpy(dest + *bytes_left, fname.name, fname.len);
+out:
+	fscrypt_fname_free_buffer(&fname);
+	return ret;
+}
+
 /*
  * this iterates to turn a name (from iref/extref) into a full filesystem path.
  * Elements of the path are separated by '/' and the path is guaranteed to be
@@ -2135,15 +2169,16 @@ char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
 		dest[bytes_left] = '\0';
 
 	while (1) {
-		bytes_left -= name_len;
-		if (bytes_left >= 0)
-			read_extent_buffer(eb, dest + bytes_left,
-					   name_off, name_len);
+		ret = copy_resolved_iref_to_buf(fs_root, eb, dest, parent,
+						name_off, name_len, &bytes_left);
 		if (eb != eb_in) {
 			if (!path->skip_locking)
 				btrfs_tree_read_unlock(eb);
 			free_extent_buffer(eb);
 		}
+		if (ret)
+			break;
+
 		ret = btrfs_find_item(fs_root, path, parent, 0,
 				BTRFS_INODE_REF_KEY, &found_key);
 		if (ret > 0)
fs/btrfs/fscrypt.c +47 -0

53 lines not on this page · raw message

fs/btrfs/fscrypt.h +10 -0
index f7ce2b2e6639..4a1daed90d06 100644
@@ -25,6 +25,9 @@ ssize_t btrfs_fscrypt_context_for_new_extent(struct btrfs_inode *inode,
 					     struct fscrypt_extent_info *info,
 					     u8 *ctx);
 int btrfs_fscrypt_bio_length(struct bio *bio, u64 map_length);
+int btrfs_decrypt_name(struct btrfs_root *root, struct extent_buffer *eb,
+		       unsigned long name_off, u32 name_len,
+		       u64 parent_ino, struct fscrypt_str *name);
 
 #else
 static inline void btrfs_fscrypt_save_extent_info(struct btrfs_path *path,
@@ -69,6 +72,13 @@ static inline u64 btrfs_fscrypt_bio_length(struct bio *bio, u64 map_length)
 	return map_length;
 }
 
+static inline int btrfs_decrypt_name(struct btrfs_root *root, struct extent_buffer *eb,
+				     unsigned long name_off, u32 name_len,
+				     u64 parent_ino, struct fscrypt_str *name)
+{
+	return -EINVAL;
+}
+
 #endif /* CONFIG_FS_ENCRYPTION */
 
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
Signature · 1 line
2.53.0
#71 lore raw

PATCH v7 36/43 btrfs: deal with encrypted symlinks in send

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Send needs to send the decrypted value of the symlinks, handle the case where the inode is encrypted and decrypt the symlink name into a buffer and copy this buffer into our fs_path struct.

---

No changes in v7.
v6 changes:
* read_symlink_encrypted() reworked from using pages to using folios.
v5: https://lore.kernel.org/linux-btrfs/4d97f35d6f85ff041b09bed33b63446a92b7a20c.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/send.c | 45 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 42 insertions(+), 3 deletions(-)
fs/btrfs/send.c +42 -3
index 89d72d8cb85f..d5256c22fe7a 100644
@@ -1701,9 +1701,7 @@ static int find_extent_clone(struct send_ctx *sctx,
 	return ret;
 }
 
-static int read_symlink(struct btrfs_root *root,
-			u64 ino,
-			struct fs_path *dest)
+static int read_symlink_unencrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
 {
 	int ret;
 	BTRFS_PATH_AUTO_FREE(path);
@@ -1764,6 +1762,47 @@ static int read_symlink(struct btrfs_root *root,
 	return fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
 }
 
+static int read_symlink_encrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
+{
+	DEFINE_DELAYED_CALL(done);
+	const char *buf;
+	struct folio *folio;
+	struct btrfs_inode *inode;
+	int ret = 0;
+
+	inode = btrfs_iget(ino, root);
+	if (IS_ERR(inode))
+		return PTR_ERR(inode);
+
+	folio = read_mapping_folio(inode->vfs_inode.i_mapping, 0, NULL);
+	if (IS_ERR(folio)) {
+		iput(&inode->vfs_inode);
+		return PTR_ERR(folio);
+	}
+
+	buf = fscrypt_get_symlink(&inode->vfs_inode, folio_address(folio),
+				  BTRFS_MAX_INLINE_DATA_SIZE(root->fs_info),
+				  &done);
+	folio_put(folio);
+	iput(&inode->vfs_inode);
+
+	if (IS_ERR(buf))
+		return PTR_ERR(buf);
+
+	ret = fs_path_add(dest, buf, strlen(buf));
+	do_delayed_call(&done);
+	return ret;
+}
+
+
+static int read_symlink(struct btrfs_root *root, u64 ino,
+			struct fs_path *dest)
+{
+	if (btrfs_fs_incompat(root->fs_info, ENCRYPT))
+		return read_symlink_encrypted(root, ino, dest);
+	return read_symlink_unencrypted(root, ino, dest);
+}
+
 /*
  * Helper function to generate a file name that is unique in the root of
  * send_root and parent_root. This is used to generate names for orphan inodes.
Signature · 1 line
2.53.0
maintainer
#72 lore raw

Re: [PATCH v7 36/43] btrfs: deal with encrypted symlinks in send

Quoted 67 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Send needs to send the decrypted value of the symlinks, handle the case where the inode is encrypted and decrypt the symlink name into a buffer and copy this buffer into our fs_path struct.

---

No changes in v7.
v6 changes:
* read_symlink_encrypted() reworked from using pages to using folios.
v5: https://lore.kernel.org/linux-btrfs/4d97f35d6f85ff041b09bed33b63446a92b7a20c.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/send.c | 45 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 42 insertions(+), 3 deletions(-)
fs/btrfs/send.c +31 -3
index 89d72d8cb85f..d5256c22fe7a 100644
@@ -1701,9 +1701,7 @@ static int find_extent_clone(struct send_ctx *sctx,
 	return ret;
 }
 
-static int read_symlink(struct btrfs_root *root,
-			u64 ino,
-			struct fs_path *dest)
+static int read_symlink_unencrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
 {
 	int ret;
 	BTRFS_PATH_AUTO_FREE(path);
@@ -1764,6 +1762,47 @@ static int read_symlink(struct btrfs_root *root,
 	return fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
 }
 
+static int read_symlink_encrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
+{
+	DEFINE_DELAYED_CALL(done);
+	const char *buf;
+	struct folio *folio;
+	struct btrfs_inode *inode;
+	int ret = 0;
+
+	inode = btrfs_iget(ino, root);
+	if (IS_ERR(inode))
+		return PTR_ERR(inode);
+
+	folio = read_mapping_folio(inode->vfs_inode.i_mapping, 0, NULL);
+	if (IS_ERR(folio)) {
+		iput(&inode->vfs_inode);
+		return PTR_ERR(folio);
+	}
+
+	buf = fscrypt_get_symlink(&inode->vfs_inode, folio_address(folio),
+				  BTRFS_MAX_INLINE_DATA_SIZE(root->fs_info),
+				  &done);
+	folio_put(folio);
+	iput(&inode->vfs_inode);
+
+	if (IS_ERR(buf))
+		return PTR_ERR(buf);
+
+	ret = fs_path_add(dest, buf, strlen(buf));
+	do_delayed_call(&done);
+	return ret;

fs/btrfs/send.c static int read_symlink(struct btrfs_root *root, · line 1804

Quoted 10 lines
fs/btrfs/send.c +10 -0
+}
+
+
+static int read_symlink(struct btrfs_root *root, u64 ino,
+			struct fs_path *dest)
+{
+	if (btrfs_fs_incompat(root->fs_info, ENCRYPT))
+		return read_symlink_encrypted(root, ino, dest);
+	return read_symlink_unencrypted(root, ino, dest);
+}

This just assumes that all the symlinks on the filesystem are encrypted, without checking the actual encrypt flag in the inode.

Of course, looking at the Sashiko review for this patch, it already found this, as well as a use-after-free.

I don't know why I'm even reviewing this.

- Eric

#73 lore raw

Re: [PATCH v7 36/43] btrfs: deal with encrypted symlinks in send

Quoted 82 lines · Eric Biggers
Quoted 67 lines · Daniel Vacek

From: Josef Bacik <[email protected]>

Send needs to send the decrypted value of the symlinks, handle the case where the inode is encrypted and decrypt the symlink name into a buffer and copy this buffer into our fs_path struct.

---

No changes in v7.
v6 changes:
* read_symlink_encrypted() reworked from using pages to using folios.
v5: https://lore.kernel.org/linux-btrfs/4d97f35d6f85ff041b09bed33b63446a92b7a20c.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/send.c | 45 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 42 insertions(+), 3 deletions(-)
fs/btrfs/send.c +31 -3
index 89d72d8cb85f..d5256c22fe7a 100644
@@ -1701,9 +1701,7 @@ static int find_extent_clone(struct send_ctx *sctx,
      return ret;
 }
 
-static int read_symlink(struct btrfs_root *root,
-                     u64 ino,
-                     struct fs_path *dest)
+static int read_symlink_unencrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
 {
      int ret;
      BTRFS_PATH_AUTO_FREE(path);
@@ -1764,6 +1762,47 @@ static int read_symlink(struct btrfs_root *root,
      return fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
 }
 
+static int read_symlink_encrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
+{
+     DEFINE_DELAYED_CALL(done);
+     const char *buf;
+     struct folio *folio;
+     struct btrfs_inode *inode;
+     int ret = 0;
+
+     inode = btrfs_iget(ino, root);
+     if (IS_ERR(inode))
+             return PTR_ERR(inode);
+
+     folio = read_mapping_folio(inode->vfs_inode.i_mapping, 0, NULL);
+     if (IS_ERR(folio)) {
+             iput(&inode->vfs_inode);
+             return PTR_ERR(folio);
+     }
+
+     buf = fscrypt_get_symlink(&inode->vfs_inode, folio_address(folio),
+                               BTRFS_MAX_INLINE_DATA_SIZE(root->fs_info),
+                               &done);
+     folio_put(folio);
+     iput(&inode->vfs_inode);
+
+     if (IS_ERR(buf))
+             return PTR_ERR(buf);
+
+     ret = fs_path_add(dest, buf, strlen(buf));
+     do_delayed_call(&done);
+     return ret;

fs/btrfs/send.c static int read_symlink(struct btrfs_root *root, · line 1804

Quoted 10 lines
fs/btrfs/send.c +10 -0
+}
+
+
+static int read_symlink(struct btrfs_root *root, u64 ino,
+                     struct fs_path *dest)
+{
+     if (btrfs_fs_incompat(root->fs_info, ENCRYPT))
+             return read_symlink_encrypted(root, ino, dest);
+     return read_symlink_unencrypted(root, ino, dest);
+}

This just assumes that all the symlinks on the filesystem are encrypted, without checking the actual encrypt flag in the inode.

Quoted 4 lines

Of course, looking at the Sashiko review for this patch, it already found this, as well as a use-after-free.

I don't know why I'm even reviewing this.

This is unrelated to fscrypt; it is internal to btrfs. Btrfs encryption is experimental and under development. Not all features are ready.
For now, btrfs send is not implemented or supported and it returns EINVAL with an error message in the log before the code even reaches this point. So far read_symlink() is never called on encrypted FS. Yes, it can be improved, but it was not a priority right now. I am really grateful for your insight as I am not familiar with all the fscrypt internals. And don't get me wrong, for the next version I'm also addressing the points Sashiko raised. I am sure we can all work together to get btrfs encryption into a usable state.

--nX

Quoted 1 line

- Eric

#74 lore raw

PATCH v7 37/43 btrfs: decrypt file names for send

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

In send we're going to be looking up file names from back references and putting them into the send stream. If we are encrypted use the helper for decrypting names and copy the decrypted name into the buffer.

---

No changes in v7.
v6 changes:
* Simplified the error return logic in fs_path_add_from_encrypted().
v5: https://lore.kernel.org/linux-btrfs/fd8b1d5f395a890dbdf8281a52fbaaa920c7b726.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/send.c | 47 +++++++++++++++++++++++++++++++++++++----------
 1 file changed, 37 insertions(+), 10 deletions(-)
fs/btrfs/send.c +37 -10
index d5256c22fe7a..3d9764aa4a25 100644
@@ -32,6 +32,7 @@
 #include "ioctl.h"
 #include "verity.h"
 #include "lru_cache.h"
+#include "fscrypt.h"
 
 /*
  * Maximum number of references an extent can have in order for us to attempt to
@@ -579,13 +580,39 @@ static inline int fs_path_add_path(struct fs_path *p, const struct fs_path *p2)
 	return fs_path_add(p, p2->start, fs_path_len(p2));
 }
 
-static int fs_path_add_from_extent_buffer(struct fs_path *p,
+static int fs_path_add_from_encrypted(struct btrfs_root *root,
+				      struct fs_path *p,
+				      struct extent_buffer *eb,
+				      unsigned long off, int len,
+				      u64 parent_ino)
+{
+	struct fscrypt_str fname = FSTR_INIT(NULL, 0);
+	int ret;
+
+	ret = fscrypt_fname_alloc_buffer(BTRFS_NAME_LEN, &fname);
+	if (ret)
+		return ret;
+
+	ret = btrfs_decrypt_name(root, eb, off, len, parent_ino, &fname);
+	if (!ret)
+		ret = fs_path_add(p, fname.name, fname.len);
+
+	fscrypt_fname_free_buffer(&fname);
+	return ret;
+}
+
+static int fs_path_add_from_extent_buffer(struct btrfs_root *root,
+					  struct fs_path *p,
 					  struct extent_buffer *eb,
-					  unsigned long off, int len)
+					  unsigned long off, int len,
+					  u64 parent_ino)
 {
 	int ret;
 	char *prepared;
 
+	if (root && btrfs_fs_incompat(root->fs_info, ENCRYPT))
+		return fs_path_add_from_encrypted(root, p, eb, off, len, parent_ino);
+
 	ret = fs_path_prepare_for_add(p, len, &prepared);
 	if (ret < 0)
 		return ret;
@@ -1062,8 +1089,7 @@ static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
 			}
 			p->start = start;
 		} else {
-			ret = fs_path_add_from_extent_buffer(p, eb, name_off,
-							     name_len);
+			ret = fs_path_add_from_extent_buffer(root, p, eb, name_off, name_len, dir);
 			if (ret < 0)
 				goto out;
 		}
@@ -1759,7 +1785,7 @@ static int read_symlink_unencrypted(struct btrfs_root *root, u64 ino, struct fs_
 	off = btrfs_file_extent_inline_start(ei);
 	len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
 
-	return fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
+	return fs_path_add_from_extent_buffer(NULL, dest, path->nodes[0], off, len, 0);
 }
 
 static int read_symlink_encrypted(struct btrfs_root *root, u64 ino, struct fs_path *dest)
@@ -2034,18 +2060,19 @@ static int get_first_ref(struct btrfs_root *root, u64 ino,
 		iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
 				      struct btrfs_inode_ref);
 		len = btrfs_inode_ref_name_len(path->nodes[0], iref);
-		ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
-						     (unsigned long)(iref + 1),
-						     len);
 		parent_dir = found_key.offset;
+		ret = fs_path_add_from_extent_buffer(root, name, path->nodes[0],
+						     (unsigned long)(iref + 1),
+						     len, parent_dir);
 	} else {
 		struct btrfs_inode_extref *extref;
 		extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
 					struct btrfs_inode_extref);
 		len = btrfs_inode_extref_name_len(path->nodes[0], extref);
-		ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
-					(unsigned long)&extref->name, len);
 		parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
+		ret = fs_path_add_from_extent_buffer(root, name, path->nodes[0],
+					(unsigned long)&extref->name, len,
+					parent_dir);
 	}
 	if (ret < 0)
 		return ret;
Signature · 1 line
2.53.0
#75 lore raw

PATCH v7 38/43 btrfs: load the inode context before sending writes

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

For send we will read the pages and copy them into our buffer. Use the fscrypt_inode_open helper to make sure the key is loaded properly before trying to read from the inode so the contents are properly decrypted.

---

No changes in v7.
v6 changes:
* btrfs_iget() returns binode now.
v5: https://lore.kernel.org/linux-btrfs/a307def01bf28c3ed99398868a142180c6088527.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/send.c | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
fs/btrfs/send.c +36 -0
index 3d9764aa4a25..1e80a3db1df2 100644
@@ -5331,6 +5331,38 @@ static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
 	return ret;
 }
 
+static int load_fscrypt_context(struct send_ctx *sctx)
+{
+	struct btrfs_root *root = sctx->send_root;
+	struct name_cache_entry *nce;
+	struct btrfs_inode *dir;
+	int ret;
+
+	if (!btrfs_fs_incompat(root->fs_info, ENCRYPT))
+		return 0;
+
+	/*
+	 * If we're encrypted we need to load the parent inode in order to make
+	 * sure the encryption context is loaded.  We have to do this even if
+	 * we're not encrypted, as we need to make sure that we don't violate
+	 * the rule about encrypted children with non-encrypted parents, which
+	 * is enforced by __fscrypt_file_open.
+	 */
+	nce = name_cache_search(sctx, sctx->cur_ino, sctx->cur_inode_gen);
+	if (!nce) {
+		ASSERT(nce);
+		return -EINVAL;
+	}
+
+	dir = btrfs_iget(nce->parent_ino, root);
+	if (IS_ERR(dir))
+		return PTR_ERR(dir);
+
+	ret = __fscrypt_file_open(&dir->vfs_inode, sctx->cur_inode);
+	iput(&dir->vfs_inode);
+	return ret;
+}
+
 /*
  * Read some bytes from the current inode/file and send a write command to
  * user space.
@@ -5348,6 +5380,10 @@ static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
 	if (ret < 0)
 		return ret;
 
+	ret = load_fscrypt_context(sctx);
+	if (ret < 0)
+		return ret;
+
 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
 	ret = put_file_data(sctx, offset, len);
Signature · 1 line
2.53.0
#76 lore raw

PATCH v7 39/43 btrfs: set the appropriate free space settings in reconfigure

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

btrfs/330 uncovered a problem where we were accidentally turning off the free space tree when we do the transition from ro->rw. This happens because we don't update

---

No changes in v7.
v6 changes:
* Re-wrapped comments.
* Fixed argument type. mount_opt is now ull.
v5: https://lore.kernel.org/linux-btrfs/325598eeb1d23f9ae04f675b4ee218f7e98e3ff0.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/disk-io.c |  2 +-
 fs/btrfs/super.c   | 28 +++++++++++++++-------------
 fs/btrfs/super.h   |  3 ++-
 3 files changed, 18 insertions(+), 15 deletions(-)
fs/btrfs/disk-io.c +1 -1
index 1f0fe29dd549..4bfd851e1e9b 100644
@@ -3412,7 +3412,7 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
 	 * Handle the space caching options appropriately now that we have the
 	 * super block loaded and validated.
 	 */
-	btrfs_set_free_space_cache_settings(fs_info);
+	btrfs_set_free_space_cache_settings(fs_info, &fs_info->mount_opt);
 
 	if (!btrfs_check_options(fs_info, &fs_info->mount_opt, sb->s_flags)) {
 		ret = -EINVAL;
fs/btrfs/super.c +15 -13
index 2c033c68f052..7ec07d0bb473 100644
@@ -745,10 +745,10 @@ bool btrfs_check_options(const struct btrfs_fs_info *info,
 }
 
 /*
- * This is subtle, we only call this during open_ctree().  We need to pre-load
- * the mount options with the on-disk settings.  Before the new mount API took
- * effect we would do this on mount and remount.  With the new mount API we'll
- * only do this on the initial mount.
+ * Because we have an odd set of behavior with turning on and off the space cache
+ * and free space tree we have to call this before we start the mount operation
+ * after we load the super, or before we start remount.  This is to make sure we
+ * have the proper free space settings in place if the user didn't specify any.
  *
  * This isn't a change in behavior, because we're using the current state of the
  * file system to set the current mount options.  If you mounted with special
@@ -756,21 +756,22 @@ bool btrfs_check_options(const struct btrfs_fs_info *info,
  * settings, because mounting without these features cleared the on-disk
  * settings, so this being called on re-mount is not needed.
  */
-void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info)
+void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info,
+					 unsigned long long *mount_opt)
 {
-	if (fs_info->sectorsize != PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
+	if (fs_info->sectorsize != PAGE_SIZE && btrfs_raw_test_opt(*mount_opt, SPACE_CACHE)) {
 		btrfs_info(fs_info,
 			   "forcing free space tree for sector size %u with page size %lu",
 			   fs_info->sectorsize, PAGE_SIZE);
-		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
-		btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
+		btrfs_clear_opt(*mount_opt, SPACE_CACHE);
+		btrfs_set_opt(*mount_opt, FREE_SPACE_TREE);
 	}
 
 	/*
 	 * At this point our mount options are populated, so we only mess with
 	 * these settings if we don't have any settings already.
 	 */
-	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE))
+	if (btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE))
 		return;
 
 	if (btrfs_is_zoned(fs_info) &&
@@ -780,10 +781,10 @@ void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info)
 		return;
 	}
 
-	if (btrfs_test_opt(fs_info, SPACE_CACHE))
+	if (btrfs_raw_test_opt(*mount_opt, SPACE_CACHE))
 		return;
 
-	if (btrfs_test_opt(fs_info, NOSPACECACHE))
+	if (btrfs_raw_test_opt(*mount_opt, NOSPACECACHE))
 		return;
 
 	/*
@@ -791,9 +792,9 @@ void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info)
 	 * them ourselves based on the state of the file system.
 	 */
 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
-		btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
+		btrfs_set_opt(*mount_opt, FREE_SPACE_TREE);
 	else if (btrfs_free_space_cache_v1_active(fs_info))
-		btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
+		btrfs_set_opt(*mount_opt, SPACE_CACHE);
 }
 
 static void set_device_specific_options(struct btrfs_fs_info *fs_info)
@@ -1573,6 +1574,7 @@ static int btrfs_reconfigure(struct fs_context *fc)
 
 	sync_filesystem(sb);
 	set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
+	btrfs_set_free_space_cache_settings(fs_info, &ctx->mount_opt);
 
 	if (!btrfs_check_options(fs_info, &ctx->mount_opt, fc->sb_flags))
 		return -EINVAL;
fs/btrfs/super.h +2 -1
index f85f8a8a7bfe..84a30b82a3ce 100644
@@ -16,7 +16,8 @@ bool btrfs_check_options(const struct btrfs_fs_info *info,
 int btrfs_sync_fs(struct super_block *sb, int wait);
 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
 					  u64 subvol_objectid);
-void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info);
+void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info,
+					 unsigned long long *mount_opt);
 
 static inline struct btrfs_fs_info *btrfs_sb(const struct super_block *sb)
 {
Signature · 1 line
2.53.0
#77 lore raw

PATCH v7 40/43 btrfs: support encryption with log replay

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

Log replay needs a few tweaks in order to make sure everything works with encryption.

1. Copy in the fscrypt context if we find one in the log.
2. Set NEEDS_FULL_SYNC when we update the inode context so all of the items are copied into the log at fsync time.

This makes replay of encrypted files work properly.

---

No changes in v7.
v6 changes:
* Adapted to the redesigned encryption context storing.
- No need to specially handle the extent item now.
It is not any different to before and the
new context items are simply copied.
v5: https://lore.kernel.org/linux-btrfs/d1ada7ac632c2ab554a840c7ba29b53a93b9855f.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/fscrypt.c  | 1 +
 fs/btrfs/tree-log.c | 4 +++-
 2 files changed, 4 insertions(+), 1 deletion(-)
fs/btrfs/fscrypt.c +1 -0
index a972c8eadfef..b57d2b0ca9fa 100644
@@ -145,6 +145,7 @@ static int btrfs_fscrypt_set_context(struct inode *inode, const void *ctx,
 			goto out_err;
 	}
 
+	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
 	leaf = path->nodes[0];
 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
 
fs/btrfs/tree-log.c +3 -1
index f3b839950855..4336f90e3223 100644
@@ -2929,7 +2929,9 @@ static int replay_one_buffer(struct extent_buffer *eb,
 			continue;
 
 		/* these keys are simply copied */
-		if (wc->log_key.type == BTRFS_XATTR_ITEM_KEY) {
+		if (wc->log_key.type == BTRFS_XATTR_ITEM_KEY ||
+		    wc->log_key.type == BTRFS_FSCRYPT_INODE_CTX_KEY ||
+		    wc->log_key.type == BTRFS_FSCRYPT_CTX_KEY) {
 			ret = overwrite_item(wc);
 			if (ret)
 				break;
Signature · 1 line
2.53.0
#78 lore raw

PATCH v7 41/43 btrfs: disable auto defrag on encrypted files

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

We will drop the inode and re-look it up to do defrag with auto defrag, which means we could lose the encryption policy.

Auto defrag needs to be reworked to just hold onto the inode for scheduling later so we don't lose the context. For now just disable it if the file is encrypted.

---

v5: https://lore.kernel.org/linux-btrfs/b717912bf88797b3044a3c2724b59b1ecc17ea78.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/defrag.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/btrfs/defrag.c +8 -0
index a828ec45bb5f..652b8423f01e 100644
@@ -126,6 +126,14 @@ void btrfs_add_inode_defrag(struct btrfs_inode *inode, u32 extent_thresh)
 	if (!need_auto_defrag(fs_info))
 		return;
 
+	/*
+	 * Since we have to read the inode at defrag time disable auto defrag
+	 * for encrypted inodes until we have code to read the parent and load
+	 * the encryption context.
+	 */
+	if (IS_ENCRYPTED(&inode->vfs_inode))
+		return;
+
 	if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
 		return;
 
Signature · 1 line
2.53.0
#79 lore raw

PATCH v7 42/43 btrfs: disable encryption on RAID5/6

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

The RAID5/6 code will re-arrange bios and submit them through a different mechanism. This is problematic with inline encryption as we have to get the bio and csum it after it's been encrypted, and the raid5/6 bio's don't have the btrfs_bio embedded, so we have no way to get the csums put on disk.

This isn't an unsolvable problem, but would require a bit of reworking. Since we discourage users from using this code currently simply don't allow encryption on RAID5/6 setups. If there's sufficient demand in the future we can add the support for this.

---

v7 changes:
* Prevent converting to RAID5/6 if encryption is already enabled as
suggested by Chris' AI review.
No changes in v6.
v5: https://lore.kernel.org/linux-btrfs/941f02bb923edadae1aea4ae3e5aa6ba05d1215a.1706116485.git.josef@toxicpanda.com/

---
 fs/btrfs/ioctl.c   | 4 ++++
 fs/btrfs/super.c   | 6 ++++++
 fs/btrfs/volumes.c | 5 +++++
 3 files changed, 15 insertions(+)
fs/btrfs/ioctl.c +4 -0
index 2e0b79f41197..873fe08cd19c 100644
@@ -5165,6 +5165,10 @@ long btrfs_ioctl(struct file *file, unsigned int
 			return -EOPNOTSUPP;
 		if (sb_rdonly(fs_info->sb))
 			return -EROFS;
+		if (btrfs_fs_incompat(fs_info, RAID56)) {
+			btrfs_warn(fs_info, "can't enable encryption with RAID5/6");
+			return -EINVAL;
+		}
 		/*
 		 *  If we crash before we commit, nothing encrypted could have
 		 * been written so it doesn't matter whether the encrypted
fs/btrfs/super.c +6 -0
index 7ec07d0bb473..5072ead57d49 100644
@@ -734,6 +734,12 @@ bool btrfs_check_options(const struct btrfs_fs_info *info,
 	if (btrfs_check_mountopts_zoned(info, mount_opt))
 		ret = false;
 
+	if (btrfs_fs_incompat(info, RAID56) &&
+	    btrfs_raw_test_opt(*mount_opt, TEST_DUMMY_ENCRYPTION)) {
+		btrfs_err(info, "cannot use test_dummy_encryption with RAID5/6");
+		ret = false;
+	}
+
 	if (!test_bit(BTRFS_FS_STATE_REMOUNTING, &info->fs_state)) {
 		if (btrfs_raw_test_opt(*mount_opt, SPACE_CACHE)) {
 			btrfs_warn(info,
fs/btrfs/volumes.c +5 -0
index a88e68f90564..d70735d501c4 100644
@@ -6053,6 +6053,11 @@ struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
 
 	lockdep_assert_held(&info->chunk_mutex);
 
+	if (type & BTRFS_BLOCK_GROUP_RAID56_MASK && btrfs_fs_incompat(info, ENCRYPT)) {
+		btrfs_warn(info, "RAID5/6 not yet supported on encrypted filesystem");
+		return ERR_PTR(-EINVAL);
+	}
+
 	if (!alloc_profile_is_valid(type, 0)) {
 		DEBUG_WARN("invalid alloc profile for type %llu", type);
 		return ERR_PTR(-EINVAL);
Signature · 1 line
2.53.0
#80 lore raw

PATCH v7 43/43 btrfs: disable send if we have encryption enabled

In reply to Daniel Vacek

From: Josef Bacik <[email protected]>

send needs to track the dir item values to see if files were renamed when doing an incremental send. There is code to decrypt the names, but this breaks the code that checks to see if something was overwritten. Until this gap is closed we need to disable send on encrypted file systems. Fixing this is straightforward, but a medium sized project.

---

v5: https://lore.kernel.org/linux-btrfs/62ce86b38e2575c542eed7fbe8d986e68496b1d7.1706116485.git.josef@toxicpanda.com/
* No changes since.

---
 fs/btrfs/send.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/btrfs/send.c +6 -0
index 1e80a3db1df2..11a3e928a4c2 100644
@@ -8095,6 +8095,12 @@ long btrfs_ioctl_send(struct btrfs_root *send_root, const struct btrfs_ioctl_sen
 	if (!capable(CAP_SYS_ADMIN))
 		return -EPERM;
 
+	if (btrfs_fs_incompat(fs_info, ENCRYPT)) {
+		btrfs_err(fs_info,
+		  "send with encryption enabled isn't currently suported");
+		return -EINVAL;
+	}
+
 	/*
 	 * The subvolume must remain read-only during send, protect against
 	 * making it RW. This also protects against deletion.
Signature · 1 line
2.53.0
#81 lore raw
In reply to Daniel Vacek
Quoted 14 lines · Daniel Vacek

Hello,

These are the remaining parts from former series [1] from Omar, Sweet Tea and Josef. Some bits of it were split into the separate set [2] before.

Notably, at this stage encryption is not supported with RAID5/6 setup and send is also disabled for now.

For straight git access you can find this series as the fscrypt-v7 tag e85358ef9fba here:

[0] https://github.com/dvacek/linux-btrfs/tree/fscrypt-v7

Quoted 11 lines

Changes since v6 [3]
* Rebased onto linux v7.1-rc3.
* Adapted to the v7.0 fscrypt API changes, mostly following commit bb8e2019ad613 ("blk-crypto: handle the fallback above the block layer")
* Addressed all the review feedback, thanks to Eric Biggers, Chris Mason
(and his LLM review prompts) and Neal Gompa.
* Adapted to the v7.1 fscrypt API cleanups, using byte offsets as function arguments instead of logical block numbers for newly introduced functions. This should match https://lore.kernel.org/linux-fscrypt/[email protected]/
As a result btrfs_set_bio_crypt_ctx_from_extent() and btrfs_mergeable_encrypted_bio() helpers were no longer needed and they got removed.

Hi Eric,

This is just a gentle ping.
I was wondering if you had a chance to look at this version? I believe all your previous feedback has been addressed and this version is solid.
Please, let me know your thoughts.

Regards,
Daniel

Quoted 132 lines

There are a few changes since v5 [1]:
* Rebased to btrfs/for-next branch. Couple things changed in the last years. A few patches were dropped as the code cleaned up or refactored. More details in the patches themselves.
* As suggested by Qu and Dave, the on-disk format of storing the extent encryption context was re-designed. Now, a new tree item with dedicated key is inserted instead of extending the file extent item. As a result a special care needs to be taken when removing the encrypted extents to also remove the related encryption context item.
* Fixed bugs found during testing.

Have a nice day,
Daniel

[1] v5 https://lore.kernel.org/linux-btrfs/[email protected]/
[2] https://lore.kernel.org/linux-btrfs/[email protected]/
[3] v6 https://lore.kernel.org/linux-btrfs/[email protected]/

Josef Bacik (33):
fscrypt: add per-extent encryption support
fscrypt: allow inline encryption for extent based encryption
fscrypt: add a __fscrypt_file_open helper
fscrypt: conditionally don't wipe mk secret until the last active user
is done
blk-crypto: add a process bio callback
fscrypt: add a process_bio hook to fscrypt_operations
fscrypt: add documentation about extent encryption
btrfs: add infrastructure for safe em freeing
btrfs: select encryption dependencies if FS_ENCRYPTION
btrfs: add fscrypt_info and encryption_type to ordered_extent
btrfs: plumb through setting the fscrypt_info for ordered extents
btrfs: populate the ordered_extent with the fscrypt context
btrfs: keep track of fscrypt info and orig_start for dio reads
btrfs: add extent encryption context tree item type
btrfs: pass through fscrypt_extent_info to the file extent helpers
btrfs: implement the fscrypt extent encryption hooks
btrfs: setup fscrypt_extent_info for new extents
btrfs: populate ordered_extent with the orig offset
btrfs: set the bio fscrypt context when applicable
btrfs: add a bio argument to btrfs_csum_one_bio
btrfs: limit encrypted writes to 256 segments
btrfs: implement process_bio cb for fscrypt
btrfs: implement read repair for encryption
btrfs: add test_dummy_encryption support
btrfs: make btrfs_ref_to_path handle encrypted filenames
btrfs: deal with encrypted symlinks in send
btrfs: decrypt file names for send
btrfs: load the inode context before sending writes
btrfs: set the appropriate free space settings in reconfigure
btrfs: support encryption with log replay
btrfs: disable auto defrag on encrypted files
btrfs: disable encryption on RAID5/6
btrfs: disable send if we have encryption enabled

Omar Sandoval (6):
fscrypt: expose fscrypt_nokey_name
btrfs: start using fscrypt hooks
btrfs: add inode encryption contexts
btrfs: add new FEATURE_INCOMPAT_ENCRYPT flag
btrfs: adapt readdir for encrypted and nokey names
btrfs: implement fscrypt ioctls

Sweet Tea Dorminy (4):
btrfs: handle nokey names
btrfs: add get_devices hook for fscrypt
btrfs: set file extent encryption excplicitly
btrfs: add fscrypt_info and encryption_type to extent_map

 Documentation/filesystems/fscrypt.rst |  41 +++
 block/blk-crypto-fallback.c           |  41 +++
 block/blk-crypto-internal.h           |   8 +
 block/blk-crypto-profile.c            |   2 +
 block/blk-crypto.c                    |   6 +-
 fs/btrfs/Kconfig                      |   4 +
 fs/btrfs/Makefile                     |   1 +
 fs/btrfs/accessors.h                  |   2 +
 fs/btrfs/backref.c                    |  43 ++-
 fs/btrfs/bio.c                        | 155 +++++++++-
 fs/btrfs/bio.h                        |  14 +-
 fs/btrfs/btrfs_inode.h                |   7 +-
 fs/btrfs/compression.c                |   6 +
 fs/btrfs/ctree.h                      |   3 +
 fs/btrfs/defrag.c                     |  14 +
 fs/btrfs/delayed-inode.c              |  25 +-
 fs/btrfs/delayed-inode.h              |   5 +-
 fs/btrfs/dir-item.c                   | 110 ++++++-
 fs/btrfs/dir-item.h                   |  10 +-
 fs/btrfs/direct-io.c                  |  28 +-
 fs/btrfs/disk-io.c                    |   3 +-
 fs/btrfs/extent_io.c                  | 115 ++++++-
 fs/btrfs/extent_io.h                  |   3 +
 fs/btrfs/extent_map.c                 | 102 ++++++-
 fs/btrfs/extent_map.h                 |  26 ++
 fs/btrfs/file-item.c                  |  28 +-
 fs/btrfs/file-item.h                  |   2 +-
 fs/btrfs/file.c                       |  79 +++++
 fs/btrfs/fs.h                         |   6 +-
 fs/btrfs/fscrypt.c                    | 413 ++++++++++++++++++++++++++
 fs/btrfs/fscrypt.h                    |  86 ++++++
 fs/btrfs/inode.c                      | 404 +++++++++++++++++++------
 fs/btrfs/ioctl.c                      |  41 ++-
 fs/btrfs/ordered-data.c               |  35 ++-
 fs/btrfs/ordered-data.h               |  14 +
 fs/btrfs/reflink.c                    |  43 ++-
 fs/btrfs/root-tree.c                  |   9 +-
 fs/btrfs/root-tree.h                  |   2 +-
 fs/btrfs/send.c                       | 134 ++++++++-
 fs/btrfs/super.c                      |  99 +++++-
 fs/btrfs/super.h                      |   3 +-
 fs/btrfs/sysfs.c                      |   6 +
 fs/btrfs/tree-checker.c               |  64 +++-
 fs/btrfs/tree-log.c                   |  34 ++-
 fs/btrfs/volumes.c                    |   5 +
 fs/crypto/crypto.c                    |  10 +-
 fs/crypto/fname.c                     |  36 ---
 fs/crypto/fscrypt_private.h           |  51 +++-
 fs/crypto/hooks.c                     |  38 ++-
 fs/crypto/inline_crypt.c              |  91 +++++-
 fs/crypto/keyring.c                   |  18 +-
 fs/crypto/keysetup.c                  | 164 ++++++++++
 fs/crypto/policy.c                    |  47 +++
 include/linux/blk-crypto.h            |  15 +-
 include/linux/fscrypt.h               | 127 ++++++++
 include/uapi/linux/btrfs.h            |   1 +
 include/uapi/linux/btrfs_tree.h       |  26 +-
 57 files changed, 2665 insertions(+), 240 deletions(-)
 create mode 100644 fs/btrfs/fscrypt.c
 create mode 100644 fs/btrfs/fscrypt.h

--
2.53.0

maintainer
#82 lore raw
Quoted 10 lines · Daniel Vacek

Hi Eric,

This is just a gentle ping.
I was wondering if you had a chance to look at this version? I believe all your previous feedback has been addressed and this version is solid.
Please, let me know your thoughts.

Regards,
Daniel

It's been really hard to find time to review this huge patchset. I've started going through it and will try to leave comments next week.

In the mean time it would be really helpful if you went through the Sashiko reviews
(https://sashiko.dev/#/patchset/20260513085340.3673127-1-neelx%40suse.com)
and address the ones that make sense to. It found 93 issues including 16 critical ones, which is kind of a lot. Some of them are the same things I'm noticing already. Same for the issue that Christoph noticed where new devices can be added; Sashiko had already found that too.

If I'm going to have to use my limited human review time to point out issues that were already found, that's not a great use of time.

I also don't see any information about how this was tested (and will continue to be tested in the future).

- Eric

#83 lore raw
Quoted 4 lines · Eric Biggers

On Fri, May 22, 2026 at 09:00:46AM +0200, Daniel Vacek wrote:

It's been really hard to find time to review this huge patchset. I've started going through it and will try to leave comments next week.

Thank you. The patchset is huge but we'd like your feedback namely on the crypto layer changes, i.e. the first 8 patches. As this is outside of btrfs code we can't fix it incrementally later on. The current size of btrfs-only can be slightly reduced but a lot of must stay so it's clear how the fscrypt API is used.

I'm not sure if it was mentioned before wrt how to get this merged. My preferred way is to get your Ack for the crypto changes and then we can add it to linux-next via our btrfs git.

It's too late for 7.2 also because you've asked for some changes. So the target is 7.3, hopefully giving all of us enough time to have the mergeable version in ~7.2-rc3 timeframe.

If you have other ideas how to proceed with the merge process, please let me know.

Quoted 8 lines

In the mean time it would be really helpful if you went through the Sashiko reviews
(https://sashiko.dev/#/patchset/20260513085340.3673127-1-neelx%40suse.com)
and address the ones that make sense to. It found 93 issues including 16 critical ones, which is kind of a lot. Some of them are the same things I'm noticing already. Same for the issue that Christoph noticed where new devices can be added; Sashiko had already found that too.

Quoted 5 lines

If I'm going to have to use my limited human review time to point out issues that were already found, that's not a great use of time.

I also don't see any information about how this was tested (and will continue to be tested in the future).

The testing is not straightforward as it needs 3 projects to synchronize, kernel, fstests and btrfs-progs. Testing may need to use custom git branches for all of them. For btrfs-progs the changes will ge it in soon. For fstests it can be a chicken-egg problem, as they don't accept tests for unmerged code. We've been using our fstests [1] with additional fixups (not upstreamable, related to CI workarounds). Though I'm not sure if Daniel has updated the branch with his most recent version.

[1] https://github.com/btrfs/fstests branch staging

maintainer
#84 lore raw
Quoted 8 lines · David Sterba
Quoted 4 lines · Eric Biggers

On Fri, May 22, 2026 at 09:00:46AM +0200, Daniel Vacek wrote:

It's been really hard to find time to review this huge patchset. I've started going through it and will try to leave comments next week.

Thank you. The patchset is huge but we'd like your feedback namely on the crypto layer changes, i.e. the first 8 patches.

I know, but properly reviewing those patches requires reviewing their usage in btrfs too. Plus the whole feature needs to be solid: if there's a problem with it that's my problem too. And some problems, e.g. any in the on-disk format, would be unfixable later, so we have to get them right from the beginning.

Quoted 1 line

It's too late for 7.2 also because you've asked for some changes.

I think the Sashiko reviews alone make it very clear that this needs some more work. So if you're considering this to be ready and just waiting for me, I don't think that's the best way to move this forwards.

Quoted 3 lines

I'm not sure if it was mentioned before wrt how to get this merged. My preferred way is to get your Ack for the crypto changes and then we can add it to linux-next via our btrfs git.

That will be fine once it's ready.

- Eric

maintainer
#85 lore raw
In reply to David Sterba
Quoted 10 lines · David Sterba

The testing is not straightforward as it needs 3 projects to synchronize, kernel, fstests and btrfs-progs. Testing may need to use custom git branches for all of them. For btrfs-progs the changes will ge it in soon. For fstests it can be a chicken-egg problem, as they don't accept tests for unmerged code. We've been using our fstests [1] with additional fixups (not upstreamable, related to CI workarounds). Though I'm not sure if Daniel has updated the branch with his most recent version.

[1] https://github.com/btrfs/fstests branch staging

Where are the btrfs-progs changes, then? I'd like to try this out, but there's no way to do it without the btrfs-progs changes.

- Eric

maintainer
#86 lore raw
Quoted 10 lines · Eric Biggers
Quoted 9 lines · David Sterba

The testing is not straightforward as it needs 3 projects to synchronize, kernel, fstests and btrfs-progs. Testing may need to use custom git branches for all of them. For btrfs-progs the changes will ge it in soon. For fstests it can be a chicken-egg problem, as they don't accept tests for unmerged code. We've been using our fstests [1] with additional fixups (not upstreamable, related to CI workarounds). Though I'm not sure if Daniel has updated the branch with his most recent version.

Quoted 4 lines
Quoted 1 line

[1] https://github.com/btrfs/fstests branch staging

Where are the btrfs-progs changes, then? I'd like to try this out, but there's no way to do it without the btrfs-progs changes.

Please make sure to test with debugging options enabled as well. Trying it with KASAN enabled, right away there's an out-of-bounds write in base64_encode(), because btrfs_real_readdir() has an incorrect buffer size calculation:

    nokey_len = DIV_ROUND_UP(name_len * 4, 3);

The other filesystems do it right by using fscrypt_fname_alloc_buffer().

Of course it turns out this is in the Sashiko comments as well, quoted below:

Is it possible for this check to allow a heap buffer overflow in the filldir buffer?

The length check estimates the fscrypt nokey name size using DIV_ROUND_UP(name_len * 4, 3). However, fscrypt_fname_disk_to_usr() prepends an 8-byte dirhash before base64 encoding. Furthermore, if the name length exceeds 149 bytes, it hashes the name and encodes exactly 189 bytes, yielding a 252-byte output.

If the remaining buffer space is large enough to pass this nokey_len check but smaller than the actual bytes produced by fscrypt_fname_disk_to_usr(), it looks like fscrypt_fname_disk_to_usr() could write past the end of the PAGE_SIZE allocation.

I think I've done enough with this series for now. I'll take a look again once it's in a better shape.

- Eric

#87 lore raw
In reply to Eric Biggers
Quoted 10 lines · Eric Biggers
Quoted 8 lines · Daniel Vacek

Hi Eric,

This is just a gentle ping.
I was wondering if you had a chance to look at this version? I believe all your previous feedback has been addressed and this version is solid.
Please, let me know your thoughts.

Quoted 5 lines
Quoted 2 lines

Regards,
Daniel

It's been really hard to find time to review this huge patchset. I've started going through it and will try to leave comments next week.

Hi Eric,

First, thank you for looking into this.

Quoted 10 lines

In the mean time it would be really helpful if you went through the Sashiko reviews
(https://sashiko.dev/#/patchset/20260513085340.3673127-1-neelx%40suse.com)
and address the ones that make sense to. It found 93 issues including 16 critical ones, which is kind of a lot. Some of them are the same things I'm noticing already. Same for the issue that Christoph noticed where new devices can be added; Sashiko had already found that too.

If I'm going to have to use my limited human review time to point out issues that were already found, that's not a great use of time.

I already went through some of the Sashiko reviews (they were slowly coming up one by one) before leaving for my vacation. And I found them mostly confusing or misleading. I'm gonna have a look into the rest I haven't seen yet to see if there are any useful points. And I'll compare it to your notes to see if it was Sashiko being confused or if it was me.

Quoted 2 lines

I also don't see any information about how this was tested (and will continue to be tested in the future).

I'm using the encrypt group of xfstests as the acceptance criteria and the full test run to ensure no regressions.

General support for btrfs had to be added. And since we only support the v2 fscrypt policy, some tests had to be split into two tests - one testing v1 and the other testing v2 policy.
There are also additional new btrfs specific tests (reflinks, snapshots). xfstests also need fscrypt support in btrfs-progs with related changes to export nonces and other metadata like device offsets of encrypted blocks for validation.

I'll send the fscrypt updated btrfs-progs and xfstests next. I just need to clean them up a bit first. I'm sorry about the delay, but I only managed to post the kernel part before my vacation. I was hoping it would give you all more time to review.

Thanks,
Daniel

Quoted 1 line

- Eric