Skip to contentSkip to conversation

btrfs: add fscrypt integration

PATCH Superseded Sweet Tea Dorminy 5 participants 30 messages Oct 25, 2022 – Oct 31, 2022

Subsystems (3)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#1 lore raw

PATCH v4 1/21 fscrypt: expose fscrypt_nokey_name

In reply to Sweet Tea Dorminy

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.

---
 fs/crypto/fname.c       | 39 +--------------------------------------
 include/linux/fscrypt.h | 37 +++++++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+), 38 deletions(-)
fs/crypto/fname.c +1 -38
index 12bd61d20f69..6c092a1533f7 100644
@@ -14,7 +14,6 @@
 #include <linux/namei.h>
 #include <linux/scatterlist.h>
 #include <crypto/hash.h>
-#include <crypto/sha2.h>
 #include <crypto/skcipher.h>
 #include "fscrypt_private.h"
 
@@ -26,43 +25,7 @@
 #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
+ * Decoded size of max-size nokey name, i.e. a name that was abbreviated using
  * the strong hash and thus includes the 'sha256' field.  This isn't simply
  * sizeof(struct fscrypt_nokey_name), as the padding at the end isn't included.
  */
include/linux/fscrypt.h +37 -0
index cad78b569c7e..4cdff7c15544 100644
@@ -16,6 +16,7 @@
 #include <linux/fs.h>
 #include <linux/mm.h>
 #include <linux/slab.h>
+#include <crypto/sha2.h>
 #include <uapi/linux/fscrypt.h>
 
 /*
@@ -54,6 +55,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[SHA256_DIGEST_SIZE];
+}; /* 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.35.1
#0 lore raw

v4 cover btrfs: add fscrypt integration

This is a changeset adding encryption to btrfs.

Last October, Omar Sandoval sent out a design document for having fscrypt integration with btrfs [1]. In summary, it proposes btrfs storing its own encryption IVs on a per-file-extent basis. fscrypt usually encrypts files using an IV derived from per-inode information; this would prevent snapshotting or reflinking or data relocation for btrfs. We have refined this into a fscrypt extent context object, opaque to the filesystem, which fscrypt uses to generate an IV associated with each block in an extent. Thus, all the inodes sharing a particular key and file extent may decrypt the extent.

This series implements this integration for the simple case, non-compressed data extents, and for verity items. Followup changes will allow encryption of compressed extents, inline extents, and will add tests around subvolume encryption. This series should provide encryption for the simplest cases, but this series should not be used in production, as there are likely bugs.

This set hopefully reflects all of the feedback given on v3.

I apologize if I missed any past feedback.

[1]
https://lore.kernel.org/linux-btrfs/[email protected]/

Changelog:
v4:
- Dropped the partial directory encryption trio of patches, as it's an easy and orthogonal followon.
- fscrypt: Changed extent-based encryption to require a direct key policy.
- fscrypt: Changed to allow direct key policies with mixed filename/contents encryption modes, to enable usage of existing AES modes with btrfs.
- fscrypt: Changed terminology used for extent context contents to 'nonce' instead of 'IV', to match the nonces used in direct-key policies elsewhere.
- fscrypt: Changed IV generation for extent-based encryption to generate 16-byte IVs (if needed) from a 16-byte nonce plus extent offset, hopefully as discussed.
- fscrypt: Updated documentation change to remove partial directory encryption.
- fscrypt: Fixed another place to refer to 'inode-based' encryption instead of a more generic term.
- btrfs: Factored btrfs_fscrypt_set_extent_context() as per Josef's feedback.
- btrfs: Fixed a couple of style nits.
- https://lore.kernel.org/linux-btrfs/[email protected]

v3:
- fscrypt: changed to generate extent contexts the same way as IVs are generated for inode-based encryption, allowing use of any existing policy and making the difference in encryption more minimal.
- Changed to use qstr's, then fscrypt_strs, then fscrypt_names only where absolutely necessary, rather than fscrypt_names everywhere.
- Reordered changes to put partially-encrypted directories, and no-key name handling, in their own sections at the end of the patchset.
- Expanded on descriptions of how no-key name handling works.
- Added encryption of verity items (but see notes in change about outstanding questions there)
- Stylistic fixes
- Renamed flags from FSCRYPT to ENCRYPT in multiple instances.
- Made the incompat encrypt superblock flag be set the first time a directory is set to be encrypted, so there isn't a need for a mkfs option.
- Hopefully addressed all other minor feedback points.
- https://lore.kernel.org/linux-btrfs/[email protected]

v2:
- Amended the fscrypt side to generically add extent contexts,
hopefully as per Eric Biggers' past comments. IVs are now entirely abstracted within an extent context, and there is no longer a new encryption policy, as DIRECT_KEY sufficiently encapsulates the
needs of extent-based encryption. Documented its usage in btrfs
briefly in the documentation.
- Adjusted the btrfs side to deal in opaque extent contexts. Improved optimization to skip storing inode contexts if they are the same as
the inode's root item's inode context.
- Combined 'add fscrypt operation table to superblock' into 'start
using fscrypt hooks'.
- https://lore.kernel.org/linux-btrfs/[email protected]
- progs: https://lore.kernel.org/linux-btrfs/[email protected]
- tests: https://lore.kernel.org/linux-btrfs/[email protected]

v1:
- Recombined the fscrypt changes back into this patchset.
- Fixed several races and incorrectly ordered operations.
- Improved IV retrieval to correctly distinguish between
filename/symlink encryption and encryption of block 0 of a file.
- https://lore.kernel.org/linux-btrfs/[email protected]
- progs: https://lore.kernel.org/linux-btrfs/[email protected]
- tests: https://lore.kernel.org/linux-btrfs/[email protected]

RFC v2:
- Fixed all warnings and known incorrectnesses.
- Split fscrypt changes into their own patchset:

    https://lore.kernel.org/linux-fscrypt/[email protected]

- Combined and reordered changes so that enabling fscrypt is the last change.
- Removed unnecessary factoring.
- Split a cleanup change off.
- https://lore.kernel.org/linux-btrfs/[email protected]

RFC v1:
- https://lore.kernel.org/linux-btrfs/[email protected]

Omar Sandoval (11):
fscrypt: expose fscrypt_nokey_name
fscrypt: add fscrypt_have_same_policy() to check inode compatibility
btrfs: store directory encryption state
btrfs: disable various operations on encrypted inodes
btrfs: start using fscrypt hooks
btrfs: add fscrypt_context items
btrfs: translate btrfs encryption flags and encrypted inode flag
btrfs: encrypt normal file extent data if appropriate
btrfs: Add new FEATURE_INCOMPAT_ENCRYPT feature flag.
btrfs: implement fscrypt ioctls
btrfs: permit searching for nokey names for removal

Sweet Tea Dorminy (10):
fscrypt: allow fscrypt_generate_iv() to distinguish filenames
fscrypt: add extent-based encryption
fscrypt: direct key policies for extent-based encryption
fscrypt: document btrfs' fscrypt quirks.
btrfs: use struct qstr instead of name and namelen
btrfs: setup qstrings from dentrys using fscrypt helper
btrfs: use struct fscrypt_str instead of struct qstr
btrfs: store a fscrypt extent context per normal file extent
btrfs: use correct name hash for nokey names
btrfs: encrypt verity items

 Documentation/filesystems/fscrypt.rst |  31 +-
 fs/btrfs/Makefile                     |   1 +
 fs/btrfs/accessors.h                  |  44 +-
 fs/btrfs/btrfs_inode.h                |   3 +
 fs/btrfs/ctree.h                      |  46 ++-
 fs/btrfs/delayed-inode.c              |  36 +-
 fs/btrfs/delayed-inode.h              |   6 +-
 fs/btrfs/dir-item.c                   | 170 ++++++--
 fs/btrfs/extent_io.c                  |  94 ++++-
 fs/btrfs/extent_io.h                  |   3 +
 fs/btrfs/extent_map.c                 |   7 +
 fs/btrfs/extent_map.h                 |   4 +
 fs/btrfs/file-item.c                  |  25 +-
 fs/btrfs/file.c                       |  11 +-
 fs/btrfs/fs.h                         |   5 +-
 fs/btrfs/fscrypt.c                    | 287 +++++++++++++
 fs/btrfs/fscrypt.h                    |  63 +++
 fs/btrfs/inode-item.c                 |  73 ++--
 fs/btrfs/inode-item.h                 |  20 +-
 fs/btrfs/inode.c                      | 560 +++++++++++++++++++-------
 fs/btrfs/ioctl.c                      |  55 ++-
 fs/btrfs/ordered-data.c               |  11 +-
 fs/btrfs/ordered-data.h               |   4 +-
 fs/btrfs/print-tree.c                 |   4 +-
 fs/btrfs/reflink.c                    |   8 +
 fs/btrfs/root-tree.c                  |  21 +-
 fs/btrfs/send.c                       |  13 +-
 fs/btrfs/super.c                      |  10 +-
 fs/btrfs/transaction.c                |  40 +-
 fs/btrfs/tree-checker.c               |  51 ++-
 fs/btrfs/tree-log.c                   | 304 +++++++-------
 fs/btrfs/tree-log.h                   |   4 +-
 fs/btrfs/verity.c                     | 114 +++++-
 fs/crypto/crypto.c                    |  40 +-
 fs/crypto/fname.c                     |  43 +-
 fs/crypto/fscrypt_private.h           |  23 +-
 fs/crypto/inline_crypt.c              |  28 +-
 fs/crypto/policy.c                    |  96 +++++
 include/linux/fscrypt.h               |  91 +++++
 include/uapi/linux/btrfs.h            |   1 +
 include/uapi/linux/btrfs_tree.h       |  28 ++
 41 files changed, 1935 insertions(+), 543 deletions(-)
 create mode 100644 fs/btrfs/fscrypt.c
 create mode 100644 fs/btrfs/fscrypt.h

base-commit: cc159678aee59042e24fd1b039405b4fdf7b0538

Signature · 1 line
2.35.1
#5 lore raw

PATCH v4 4/21 fscrypt: add extent-based encryption

Some filesystems need to encrypt data based on extents, rather than on inodes, due to features incompatible with inode-based encryption. For instance, btrfs can have multiple inodes referencing a single block of data, and moves logical data blocks to different physical locations on disk in the background; these two features mean traditional inode-based file contents encryption will not work for btrfs.

This change introduces fscrypt_extent_context objects, in analogy to existing context objects based on inodes. For a filesystem which opts to use extent-based encryption, a new hook provides a new fscrypt_extent_context. During file content encryption/decryption, the existing fscrypt_context object provides key information, while the new fscrypt_extent_context provides nonce information. For filename encryption, the existing IV generation methods are still used, since filenames are not stored in extents.

Only direct key policies are allowed, but any encryption mode is allowed within that constraint.

---
 fs/crypto/crypto.c          | 20 +++++++++--
 fs/crypto/fscrypt_private.h | 25 +++++++++++++-
 fs/crypto/inline_crypt.c    | 28 ++++++++++++----
 fs/crypto/policy.c          | 66 +++++++++++++++++++++++++++++++++++++
 include/linux/fscrypt.h     | 47 ++++++++++++++++++++++++++
 5 files changed, 176 insertions(+), 10 deletions(-)
fs/crypto/crypto.c +17 -3
index 7fe5979fbea2..08b495dc5c0c 100644
@@ -81,8 +81,22 @@ void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 			 const struct fscrypt_info *ci)
 {
 	u8 flags = fscrypt_policy_flags(&ci->ci_policy);
+	struct inode *inode = ci->ci_inode;
+	const struct fscrypt_operations *s_cop = inode->i_sb->s_cop;
 
-	memset(iv, 0, ci->ci_mode->ivsize);
+	memset(iv, 0, sizeof(*iv));
+	if (s_cop->get_extent_context && lblk_num != U64_MAX) {
+		size_t extent_offset;
+		union fscrypt_extent_context ctx;
+		int ret;
+
+		ret = fscrypt_get_extent_context(inode, lblk_num, &ctx,
+						 &extent_offset, NULL);
+		WARN_ON_ONCE(ret);
+		memcpy(iv->raw, ctx.v1.iv.raw, sizeof(*iv));
+		iv->lblk_num += cpu_to_le64(extent_offset);
+		return;
+	}
 
 	/*
 	 * Filename encryption. For inode-based policies, filenames are
@@ -93,8 +107,8 @@ void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 
 	if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
 		WARN_ON_ONCE(lblk_num > U32_MAX);
-		WARN_ON_ONCE(ci->ci_inode->i_ino > U32_MAX);
-		lblk_num |= (u64)ci->ci_inode->i_ino << 32;
+		WARN_ON_ONCE(inode->i_ino > U32_MAX);
+		lblk_num |= (u64)inode->i_ino << 32;
 	} else if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
 		WARN_ON_ONCE(lblk_num > U32_MAX);
 		lblk_num = (u32)(ci->ci_hashed_ino + lblk_num);
fs/crypto/fscrypt_private.h +24 -1
index d5f68a0c5d15..9c4cae2580de 100644
@@ -280,7 +280,6 @@ fscrypt_msg(const struct inode *inode, const char *level, const char *fmt, ...);
 	fscrypt_msg((inode), KERN_ERR, fmt, ##__VA_ARGS__)
 
 #define FSCRYPT_MAX_IV_SIZE	32
-
 union fscrypt_iv {
 	struct {
 		/* logical block number within the file */
@@ -293,6 +292,27 @@ union fscrypt_iv {
 	__le64 dun[FSCRYPT_MAX_IV_SIZE / sizeof(__le64)];
 };
 
+
+/*
+ * fscrypt_extent_context - the encryption context for an extent
+ *
+ * For filesystems that support extent encryption, this context provides the
+ * necessary randomly-initialized IV in order to encrypt/decrypt the data
+ * stored in the extent. It is stored alongside each extent, and is
+ * insufficient to decrypt the extent: the extent's owning inode(s) provide the
+ * policy information (including key identifier) necessary to decrypt.
+ */
+struct fscrypt_extent_context_v1 {
+	u8 version;
+	union fscrypt_iv iv;
+} __packed;
+
+union fscrypt_extent_context {
+	u8 version;
+	struct fscrypt_extent_context_v1 v1;
+};
+
+
 void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 			 const struct fscrypt_info *ci);
 
@@ -662,5 +682,8 @@ int fscrypt_policy_from_context(union fscrypt_policy *policy_u,
 				const union fscrypt_context *ctx_u,
 				int ctx_size);
 const union fscrypt_policy *fscrypt_policy_to_inherit(struct inode *dir);
+int fscrypt_get_extent_context(const struct inode *inode, u64 lblk_num,
+			       union fscrypt_extent_context *ctx,
+			       size_t *extent_offset, size_t *extent_length);
 
 #endif /* _FSCRYPT_PRIVATE_H */
fs/crypto/inline_crypt.c +22 -6
index cea8b14007e6..6adb72c52ce2 100644
@@ -460,6 +460,7 @@ EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
  */
 u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
 {
+	const struct fscrypt_operations *s_cop = inode->i_sb->s_cop;
 	const struct fscrypt_info *ci;
 	u32 dun;
 
@@ -470,14 +471,29 @@ u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
 		return nr_blocks;
 
 	ci = inode->i_crypt_info;
-	if (!(fscrypt_policy_flags(&ci->ci_policy) &
-	      FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
-		return nr_blocks;
 
-	/* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
+	if (s_cop->get_extent_context) {
+		size_t extent_offset, extent_length;
+		int ret = fscrypt_get_extent_context(inode, lblk, NULL,
+						     &extent_offset,
+						     &extent_length);
+		if (ret < 0) {
+			WARN_ON_ONCE(ret < 0);
+			return 1;
+		}
+		return extent_length - extent_offset;
+	}
 
-	dun = ci->ci_hashed_ino + lblk;
+	if ((fscrypt_policy_flags(&ci->ci_policy) &
+	      FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)) {
+		/*
+		 * With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to
+		 * 0.
+		 */
+		dun = ci->ci_hashed_ino + lblk;
+		return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
+	}
 
-	return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
+	return nr_blocks;
 }
 EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);
fs/crypto/policy.c +66 -0

78 lines not on this page · raw message

include/linux/fscrypt.h +47 -0

71 lines not on this page · raw message

Signature · 1 line
2.35.1
#2 lore raw

PATCH v4 2/21 fscrypt: add fscrypt_have_same_policy() to check inode compatibility

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

Btrfs will need to check whether inode policies are identical for various purposes: if two inodes want to share an extent, they must have the same policy, including key identifier; symlinks must not span the encrypted/unencrypted border; and certain encryption policies will allow btrfs to store one fscrypt_context for multiple objects. Therefore, add a function which allows checking the encryption policies of two inodes to ensure they are identical.

---
 fs/crypto/policy.c      | 26 ++++++++++++++++++++++++++
 include/linux/fscrypt.h |  7 +++++++
 2 files changed, 33 insertions(+)
fs/crypto/policy.c +26 -0
index 46757c3052ef..b7c4820a8001 100644
@@ -415,6 +415,32 @@ static int fscrypt_get_policy(struct inode *inode, union fscrypt_policy *policy)
 	return fscrypt_policy_from_context(policy, &ctx, ret);
 }
 
+/**
+ * fscrypt_have_same_policy() - check whether two inodes have the same policy
+ * @inode1: the first inode
+ * @inode2: the second inode
+ *
+ * Return: %true if they are definitely equal, else %false
+ */
+int fscrypt_have_same_policy(struct inode *inode1, struct inode *inode2)
+{
+	union fscrypt_policy policy1, policy2;
+	int err;
+
+	if (!IS_ENCRYPTED(inode1) && !IS_ENCRYPTED(inode2))
+		return true;
+	else if (!IS_ENCRYPTED(inode1) || !IS_ENCRYPTED(inode2))
+		return false;
+	err = fscrypt_get_policy(inode1, &policy1);
+	if (err)
+		return false;
+	err = fscrypt_get_policy(inode2, &policy2);
+	if (err)
+		return false;
+	return fscrypt_policies_equal(&policy1, &policy2);
+}
+EXPORT_SYMBOL(fscrypt_have_same_policy);
+
 static int set_encryption_policy(struct inode *inode,
 				 const union fscrypt_policy *policy)
 {
include/linux/fscrypt.h +7 -0
index 4cdff7c15544..9cc5a61c1200 100644
@@ -313,6 +313,7 @@ static inline struct page *fscrypt_pagecache_page(struct page *bounce_page)
 void fscrypt_free_bounce_page(struct page *bounce_page);
 
 /* policy.c */
+int fscrypt_have_same_policy(struct inode *inode1, struct inode *inode2);
 int fscrypt_ioctl_set_policy(struct file *filp, const void __user *arg);
 int fscrypt_ioctl_get_policy(struct file *filp, void __user *arg);
 int fscrypt_ioctl_get_policy_ex(struct file *filp, void __user *arg);
@@ -490,6 +491,12 @@ static inline void fscrypt_free_bounce_page(struct page *bounce_page)
 }
 
 /* policy.c */
+static inline int fscrypt_have_same_policy(struct inode *inode1,
+					   struct inode *inode2)
+{
+	return 1;
+}
+
 static inline int fscrypt_ioctl_set_policy(struct file *filp,
 					   const void __user *arg)
 {
Signature · 1 line
2.35.1
#4 lore raw

PATCH v4 3/21 fscrypt: allow fscrypt_generate_iv() to distinguish filenames

In reply to Sweet Tea Dorminy

For extent-based file contents encryption, filenames will need to generate an IV based on the inode context, while file contents will need to generate an IV based on the extent context. Currently filenames and the first block of file contents both pass fscrypt_generate_iv() a block number of 0, making it hard to distinguish the two cases.

To enable distinguishing these two cases for extent-based encryption, this change adjusts all callers to pass U64_MAX when requesting an IV for filename encryption, and then changes fscrypt_generate_iv() to convert U64_MAX to 0 for traditional inode-context encryption. For extent-based encryption, any block number other than U64_MAX will get an IV from the extent context, while U64_MAX will indicate falling back to inode contexts.

---
 fs/crypto/crypto.c | 9 ++++++++-
 fs/crypto/fname.c  | 4 ++--
 2 files changed, 10 insertions(+), 3 deletions(-)
fs/crypto/crypto.c +8 -1
index e78be66bbf01..7fe5979fbea2 100644
@@ -71,7 +71,7 @@ EXPORT_SYMBOL(fscrypt_free_bounce_page);
 
 /*
  * Generate the IV for the given logical block number within the given file.
- * For filenames encryption, lblk_num == 0.
+ * For filenames encryption, lblk_num == U64_MAX.
  *
  * Keep this in sync with fscrypt_limit_io_blocks().  fscrypt_limit_io_blocks()
  * needs to know about any IV generation methods where the low bits of IV don't
@@ -84,6 +84,13 @@ void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 
 	memset(iv, 0, ci->ci_mode->ivsize);
 
+	/*
+	 * Filename encryption. For inode-based policies, filenames are
+	 * encrypted as though they are lblk 0.
+	 */
+	if (lblk_num == U64_MAX)
+		lblk_num = 0;
+
 	if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
 		WARN_ON_ONCE(lblk_num > U32_MAX);
 		WARN_ON_ONCE(ci->ci_inode->i_ino > U32_MAX);
fs/crypto/fname.c +2 -2
index 6c092a1533f7..b3e7e3a66312 100644
@@ -79,7 +79,7 @@ int fscrypt_fname_encrypt(const struct inode *inode, const struct qstr *iname,
 	memset(out + iname->len, 0, olen - iname->len);
 
 	/* Initialize the IV */
-	fscrypt_generate_iv(&iv, 0, ci);
+	fscrypt_generate_iv(&iv, U64_MAX, ci);
 
 	/* Set up the encryption request */
 	req = skcipher_request_alloc(tfm, GFP_NOFS);
@@ -134,7 +134,7 @@ static int fname_decrypt(const struct inode *inode,
 		crypto_req_done, &wait);
 
 	/* Initialize IV */
-	fscrypt_generate_iv(&iv, 0, ci);
+	fscrypt_generate_iv(&iv, U64_MAX, ci);
 
 	/* Create decryption request */
 	sg_init_one(&src_sg, iname->name, iname->len);
Signature · 1 line
2.35.1
#6 lore raw

PATCH v4 5/21 fscrypt: direct key policies for extent-based encryption

In reply to Sweet Tea Dorminy

For inode-based direct key encryption policies, the inode provides a nonce, and the encryption IV is generated by concatenating the nonce and the offset into the inode. For extent-based direct key policies, however, we would like to use 16-byte nonces in combination with various AES modes with 16-byte IVs. Additionally, since contents and filenames are encrypted with different context items in this case, we don't need to require the encryption modes match in the two cases.

This change allows extent-based encryption to use 16-byte IVs with direct key policies, and allows a mismatch of modes (under the usual compatible modes constraints).

---
 fs/crypto/crypto.c          | 15 +++++++++++++--
 fs/crypto/fscrypt_private.h |  4 +---
 fs/crypto/policy.c          |  4 ++++
 3 files changed, 18 insertions(+), 5 deletions(-)
fs/crypto/crypto.c +13 -2
index 08b495dc5c0c..144a3a59ce51 100644
@@ -93,8 +93,19 @@ void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 		ret = fscrypt_get_extent_context(inode, lblk_num, &ctx,
 						 &extent_offset, NULL);
 		WARN_ON_ONCE(ret);
-		memcpy(iv->raw, ctx.v1.iv.raw, sizeof(*iv));
-		iv->lblk_num += cpu_to_le64(extent_offset);
+		if (ci->ci_mode->ivsize < offsetofend(union fscrypt_iv, nonce)) {
+			/*
+			 *  We need a 16 byte IV, but our nonce is 16 bytes.
+			 *  Copy to the start of the buffer and add the extent
+			 *  offset manually.
+			 */
+			memcpy(iv->raw, ctx.v1.nonce, FSCRYPT_FILE_NONCE_SIZE);
+			iv->lblk_num = cpu_to_le64(extent_offset +
+						   le64_to_cpu(iv->lblk_num));
+			return;
+		}
+		memcpy(iv->nonce, ctx.v1.nonce, FSCRYPT_FILE_NONCE_SIZE);
+		iv->lblk_num = cpu_to_le64(extent_offset);
 		return;
 	}
 
fs/crypto/fscrypt_private.h +1 -3
index 9c4cae2580de..bb2a18c83e56 100644
@@ -292,7 +292,6 @@ union fscrypt_iv {
 	__le64 dun[FSCRYPT_MAX_IV_SIZE / sizeof(__le64)];
 };
 
-
 /*
  * fscrypt_extent_context - the encryption context for an extent
  *
@@ -304,7 +303,7 @@ union fscrypt_iv {
  */
 struct fscrypt_extent_context_v1 {
 	u8 version;
-	union fscrypt_iv iv;
+	u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
 } __packed;
 
 union fscrypt_extent_context {
@@ -312,7 +311,6 @@ union fscrypt_extent_context {
 	struct fscrypt_extent_context_v1 v1;
 };
 
-
 void fscrypt_generate_iv(union fscrypt_iv *iv, u64 lblk_num,
 			 const struct fscrypt_info *ci);
 
fs/crypto/policy.c +4 -0
index 4a86b80e7c0b..15653933f19e 100644
@@ -91,6 +91,10 @@ static bool supported_direct_key_modes(const struct inode *inode,
 {
 	const struct fscrypt_mode *mode;
 
+	/* Extent-based encryption allows any mixed mode and IV size */
+	if (inode->i_sb->s_cop->get_extent_context)
+		return true;
+
 	if (contents_mode != filenames_mode) {
 		fscrypt_warn(inode,
 			     "Direct key flag not allowed with different contents and filenames modes");
Signature · 1 line
2.35.1
#7 lore raw

PATCH v4 6/21 fscrypt: document btrfs' fscrypt quirks.

In reply to Sweet Tea Dorminy

As btrfs has a couple of quirks in its encryption compared to other filesystems, they should be documented like ext4's quirks. Additionally, extent-based contents encryption, being wholly new, deserves its own section to compare against inode-based contents encryption.

---
 Documentation/filesystems/fscrypt.rst | 31 +++++++++++++++++++++------
 1 file changed, 25 insertions(+), 6 deletions(-)
Documentation/filesystems/fscrypt.rst +25 -6
index 5ba5817c17c2..2ced42afd58b 100644
@@ -31,7 +31,7 @@ However, except for filenames, fscrypt does not encrypt filesystem
 metadata.
 
 Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
-directly into supported filesystems --- currently ext4, F2FS, and
+directly into supported filesystems --- currently btrfs, ext4, F2FS, and
 UBIFS.  This allows encrypted files to be read and written without
 caching both the decrypted and encrypted pages in the pagecache,
 thereby nearly halving the memory used and bringing it in line with
@@ -280,6 +280,11 @@ included in the IV.  Moreover:
   key derived using the KDF.  Users may use the same master key for
   other v2 encryption policies.
 
+For filesystems with extent-based content encryption (e.g. btrfs),
+this is the only choice. Data shared among multiple inodes must share
+the exact same key, therefore necessitating inodes using the same key
+for contents encryption.
+
 IV_INO_LBLK_64 policies
 -----------------------
 
@@ -374,12 +379,12 @@ to individual filesystems.  However, authenticated encryption (AE)
 modes are not currently supported because of the difficulty of dealing
 with ciphertext expansion.
 
-Contents encryption
--------------------
+Inode-based contents encryption
+------------------------------
 
-For file contents, each filesystem block is encrypted independently.
-Starting from Linux kernel 5.5, encryption of filesystems with block
-size less than system's page size is supported.
+For most filesystems, each filesystem block within each file is
+encrypted independently.  Starting from Linux kernel 5.5, encryption of
+filesystems with block size less than system's page size is supported.
 
 Each block's IV is set to the logical block number within the file as
 a little endian number, except that:
@@ -403,6 +408,20 @@ Note that because file logical block numbers are included in the IVs,
 filesystems must enforce that blocks are never shifted around within
 encrypted files, e.g. via "collapse range" or "insert range".
 
+Extent-based contents encryption
+--------------------------------
+
+For certain filesystems (currently only btrfs), data is encrypted on a
+per-extent basis. Each filesystem block in a data extent is encrypted
+independently. Multiple files may refer to the extent, as long as they
+all share the same key.  The filesystem may relocate the extent on disk,
+as long as the encrypted data within the extent retains its offset
+within the data extent.
+
+Each extent stores a nonce; each block within the extent has an IV
+based on this nonce and the logical block number within the extent as a
+little endian number.
+
 Filenames encryption
 --------------------
 
Signature · 1 line
2.35.1
#9 lore raw

PATCH v4 7/21 btrfs: use struct qstr instead of name and namelen

In reply to Sweet Tea Dorminy

Many functions throughout btrfs take name buffer and name length arguments. Most of these functions at the highest level are usually called with these arguments extracted from a supplied dentry's name. But the entire name can be passed instead, making each function a little more elegant.

Each function whose arguments are currently the name and length extracted from a dentry is herein converted to instead take a pointer to the name in the dentry. The couple of calls to these calls without a struct dentry are converted to create an appropriate qstr to pass in. Additionally, every function which is only called with a name/len extracted directly from a qstr is also converted.

---
 fs/btrfs/ctree.h       |  26 ++--
 fs/btrfs/dir-item.c    |  50 ++++----
 fs/btrfs/inode-item.c  |  73 ++++++------
 fs/btrfs/inode-item.h  |  20 ++--
 fs/btrfs/inode.c       | 128 +++++++++-----------
 fs/btrfs/ioctl.c       |   7 +-
 fs/btrfs/root-tree.c   |  19 ++-
 fs/btrfs/send.c        |  11 +-
 fs/btrfs/super.c       |   3 +-
 fs/btrfs/transaction.c |  11 +-
 fs/btrfs/tree-log.c    | 263 +++++++++++++++++++----------------------
 fs/btrfs/tree-log.h    |   4 +-
 12 files changed, 283 insertions(+), 332 deletions(-)
fs/btrfs/ctree.h +12 -14
index f5beb0dff2be..d80ebd5b1a83 100644
@@ -1516,11 +1516,11 @@ int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
 
 /* root-item.c */
 int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
-		       u64 ref_id, u64 dirid, u64 sequence, const char *name,
-		       int name_len);
+		       u64 ref_id, u64 dirid, u64 sequence,
+		       const struct qstr *name);
 int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
-		       u64 ref_id, u64 dirid, u64 *sequence, const char *name,
-		       int name_len);
+		       u64 ref_id, u64 dirid, u64 *sequence,
+		       const struct qstr *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,
@@ -1549,25 +1549,23 @@ int btrfs_uuid_tree_iterate(struct btrfs_fs_info *fs_info);
 
 /* dir-item.c */
 int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,
-			  const char *name, int name_len);
-int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, const char *name,
-			  int name_len, struct btrfs_inode *dir,
+			  const struct qstr *name);
+int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,
+			  const struct qstr *name, struct btrfs_inode *dir,
 			  struct btrfs_key *location, u8 type, u64 index);
 struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
 					     struct btrfs_root *root,
 					     struct btrfs_path *path, u64 dir,
-					     const char *name, int name_len,
-					     int mod);
+					     const struct qstr *name, int mod);
 struct btrfs_dir_item *
 btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
 			    struct btrfs_root *root,
 			    struct btrfs_path *path, u64 dir,
-			    u64 index, const char *name, int name_len,
-			    int mod);
+			    u64 index, const struct qstr *name, int mod);
 struct btrfs_dir_item *
 btrfs_search_dir_index_item(struct btrfs_root *root,
 			    struct btrfs_path *path, u64 dirid,
-			    const char *name, int name_len);
+			    const struct qstr *name);
 int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans,
 			      struct btrfs_root *root,
 			      struct btrfs_path *path,
@@ -1648,10 +1646,10 @@ 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 char *name, int name_len);
+		       const struct qstr *name);
 int btrfs_add_link(struct btrfs_trans_handle *trans,
 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
-		   const char *name, int name_len, int add_backref, u64 index);
+		   const struct qstr *name, int add_backref, u64 index);
 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry);
 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
 			 int front);
fs/btrfs/dir-item.c +24 -26

140 lines not on this page · raw message

fs/btrfs/inode-item.c +36 -37

246 lines not on this page · raw message

fs/btrfs/inode-item.h +9 -11
index a8fc16d0147f..3c657c670cfd 100644
@@ -64,33 +64,31 @@ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
 			       struct btrfs_root *root,
 			       struct btrfs_truncate_control *control);
 int btrfs_insert_inode_ref(struct btrfs_trans_handle *trans,
-			   struct btrfs_root *root,
-			   const char *name, int name_len,
+			   struct btrfs_root *root, const struct qstr *name,
 			   u64 inode_objectid, u64 ref_objectid, u64 index);
 int btrfs_del_inode_ref(struct btrfs_trans_handle *trans,
-			   struct btrfs_root *root,
-			   const char *name, int name_len,
-			   u64 inode_objectid, u64 ref_objectid, u64 *index);
+			struct btrfs_root *root, const struct qstr *name,
+			u64 inode_objectid, u64 ref_objectid, u64 *index);
 int btrfs_insert_empty_inode(struct btrfs_trans_handle *trans,
 			     struct btrfs_root *root,
 			     struct btrfs_path *path, u64 objectid);
-int btrfs_lookup_inode(struct btrfs_trans_handle *trans, struct btrfs_root
-		       *root, struct btrfs_path *path,
+int btrfs_lookup_inode(struct btrfs_trans_handle *trans,
+		       struct btrfs_root *root, struct btrfs_path *path,
 		       struct btrfs_key *location, int mod);
 
 struct btrfs_inode_extref *btrfs_lookup_inode_extref(
 			  struct btrfs_trans_handle *trans,
 			  struct btrfs_root *root,
 			  struct btrfs_path *path,
-			  const char *name, int name_len,
+			  const struct qstr *name,
 			  u64 inode_objectid, u64 ref_objectid, int ins_len,
 			  int cow);
 
 struct btrfs_inode_ref *btrfs_find_name_in_backref(struct extent_buffer *leaf,
-						   int slot, const char *name,
-						   int name_len);
+						   int slot,
+						   const struct qstr *name);
 struct btrfs_inode_extref *btrfs_find_name_in_ext_backref(
 		struct extent_buffer *leaf, int slot, u64 ref_objectid,
-		const char *name, int name_len);
+		const struct qstr *name);
 
 #endif
fs/btrfs/inode.c +53 -75

382 lines not on this page · raw message

fs/btrfs/ioctl.c +4 -3
index bf30e48a28a8..32dd1e654846 100644
@@ -951,6 +951,7 @@ static noinline int btrfs_mksubvol(const struct path *parent,
 	struct inode *dir = d_inode(parent->dentry);
 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
 	struct dentry *dentry;
+	struct qstr name_str = QSTR_INIT(name, namelen);
 	int error;
 
 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
@@ -971,8 +972,7 @@ static noinline int btrfs_mksubvol(const struct path *parent,
 	 * check for them now when we can safely fail
 	 */
 	error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
-					       dir->i_ino, name,
-					       namelen);
+					       dir->i_ino, &name_str);
 	if (error)
 		goto out_dput;
 
@@ -3776,6 +3776,7 @@ static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
 	struct btrfs_trans_handle *trans;
 	struct btrfs_path *path = NULL;
 	struct btrfs_disk_key disk_key;
+	struct qstr name = QSTR_INIT("default", 7);
 	u64 objectid = 0;
 	u64 dir_id;
 	int ret;
@@ -3819,7 +3820,7 @@ static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
 
 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
 	di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
-				   dir_id, "default", 7, 1);
+				   dir_id, &name, 1);
 	if (IS_ERR_OR_NULL(di)) {
 		btrfs_release_path(path);
 		btrfs_end_transaction(trans);
fs/btrfs/root-tree.c +9 -10
index 74cfbbc30572..9f324b3e3990 100644
@@ -331,9 +331,8 @@ 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 char *name,
-		       int name_len)
-
+		       u64 ref_id, u64 dirid, u64 *sequence,
+		       const struct qstr *name)
 {
 	struct btrfs_root *tree_root = trans->fs_info->tree_root;
 	struct btrfs_path *path;
@@ -360,8 +359,8 @@ int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 				     struct btrfs_root_ref);
 		ptr = (unsigned long)(ref + 1);
 		if ((btrfs_root_ref_dirid(leaf, ref) != dirid) ||
-		    (btrfs_root_ref_name_len(leaf, ref) != name_len) ||
-		    memcmp_extent_buffer(leaf, name, ptr, name_len)) {
+		    (btrfs_root_ref_name_len(leaf, ref) != name->len) ||
+		    memcmp_extent_buffer(leaf, name->name, ptr, name->len)) {
 			ret = -ENOENT;
 			goto out;
 		}
@@ -404,8 +403,8 @@ int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
  * Will return 0, -ENOMEM, or anything from the CoW path
  */
 int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
-		       u64 ref_id, u64 dirid, u64 sequence, const char *name,
-		       int name_len)
+		       u64 ref_id, u64 dirid, u64 sequence,
+		       const struct qstr *name)
 {
 	struct btrfs_root *tree_root = trans->fs_info->tree_root;
 	struct btrfs_key key;
@@ -424,7 +423,7 @@ int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 	key.offset = ref_id;
 again:
 	ret = btrfs_insert_empty_item(trans, tree_root, path, &key,
-				      sizeof(*ref) + name_len);
+				      sizeof(*ref) + name->len);
 	if (ret) {
 		btrfs_abort_transaction(trans, ret);
 		btrfs_free_path(path);
@@ -435,9 +434,9 @@ int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
 	btrfs_set_root_ref_dirid(leaf, ref, dirid);
 	btrfs_set_root_ref_sequence(leaf, ref, sequence);
-	btrfs_set_root_ref_name_len(leaf, ref, name_len);
+	btrfs_set_root_ref_name_len(leaf, ref, name->len);
 	ptr = (unsigned long)(ref + 1);
-	write_extent_buffer(leaf, name, ptr, name_len);
+	write_extent_buffer(leaf, name->name, ptr, name->len);
 	btrfs_mark_buffer_dirty(leaf);
 
 	if (key.type == BTRFS_ROOT_BACKREF_KEY) {
fs/btrfs/send.c +7 -4
index eb1f13b230a5..3c7a23d48bec 100644
@@ -1597,13 +1597,16 @@ static int gen_unique_name(struct send_ctx *sctx,
 		return -ENOMEM;
 
 	while (1) {
+		struct qstr tmp_name;
 		len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
 				ino, gen, idx);
 		ASSERT(len < sizeof(tmp));
+		tmp_name.name = tmp;
+		tmp_name.len = strlen(tmp);
 
 		di = btrfs_lookup_dir_item(NULL, sctx->send_root,
 				path, BTRFS_FIRST_FREE_OBJECTID,
-				tmp, strlen(tmp), 0);
+				&tmp_name, 0);
 		btrfs_release_path(path);
 		if (IS_ERR(di)) {
 			ret = PTR_ERR(di);
@@ -1623,7 +1626,7 @@ static int gen_unique_name(struct send_ctx *sctx,
 
 		di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
 				path, BTRFS_FIRST_FREE_OBJECTID,
-				tmp, strlen(tmp), 0);
+				&tmp_name, 0);
 		btrfs_release_path(path);
 		if (IS_ERR(di)) {
 			ret = PTR_ERR(di);
@@ -1753,13 +1756,13 @@ static int lookup_dir_item_inode(struct btrfs_root *root,
 	struct btrfs_dir_item *di;
 	struct btrfs_key key;
 	struct btrfs_path *path;
+	struct qstr name_str = QSTR_INIT(name, name_len);
 
 	path = alloc_path_for_send();
 	if (!path)
 		return -ENOMEM;
 
-	di = btrfs_lookup_dir_item(NULL, root, path,
-			dir, name, name_len, 0);
+	di = btrfs_lookup_dir_item(NULL, root, path, dir, &name_str, 0);
 	if (IS_ERR_OR_NULL(di)) {
 		ret = di ? PTR_ERR(di) : -ENOENT;
 		goto out;
fs/btrfs/super.c +2 -1
index c02fcdb9c7c4..2e3a5ba2910e 100644
@@ -1423,6 +1423,7 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
 	struct btrfs_dir_item *di;
 	struct btrfs_path *path;
 	struct btrfs_key location;
+	struct qstr name = QSTR_INIT("default", 7);
 	u64 dir_id;
 
 	path = btrfs_alloc_path();
@@ -1435,7 +1436,7 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
 	 * to mount.
 	 */
 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
-	di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0);
+	di = btrfs_lookup_dir_item(NULL, root, path, dir_id, &name, 0);
 	if (IS_ERR(di)) {
 		btrfs_free_path(path);
 		return PTR_ERR(di);
fs/btrfs/transaction.c +5 -6
index 25e6b504edb4..7db9612f4d0e 100644
@@ -1678,8 +1678,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	/* check if there is a file/dir which has the same name. */
 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
 					 btrfs_ino(BTRFS_I(parent_inode)),
-					 dentry->d_name.name,
-					 dentry->d_name.len, 0);
+					 &dentry->d_name, 0);
 	if (dir_item != NULL && !IS_ERR(dir_item)) {
 		pending->error = -EEXIST;
 		goto dir_item_existed;
@@ -1774,7 +1773,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	ret = btrfs_add_root_ref(trans, objectid,
 				 parent_root->root_key.objectid,
 				 btrfs_ino(BTRFS_I(parent_inode)), index,
-				 dentry->d_name.name, dentry->d_name.len);
+				 &dentry->d_name);
 	if (ret) {
 		btrfs_abort_transaction(trans, ret);
 		goto fail;
@@ -1806,9 +1805,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	if (ret < 0)
 		goto fail;
 
-	ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
-				    dentry->d_name.len, BTRFS_I(parent_inode),
-				    &key, BTRFS_FT_DIR, index);
+	ret = btrfs_insert_dir_item(trans, &dentry->d_name,
+				    BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
+				    index);
 	/* We have check then name at the beginning, so it is impossible. */
 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
 	if (ret) {
fs/btrfs/tree-log.c +120 -143

664 lines not on this page · raw message

fs/btrfs/tree-log.h +2 -2
index f5770829d075..8c9a387151b0 100644
@@ -87,11 +87,11 @@ int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
 			  struct btrfs_log_ctx *ctx);
 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
 				  struct btrfs_root *root,
-				  const char *name, int name_len,
+				  const struct qstr *name,
 				  struct btrfs_inode *dir, u64 index);
 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
 				struct btrfs_root *root,
-				const char *name, int name_len,
+				const struct qstr *name,
 				struct btrfs_inode *inode, u64 dirid);
 void btrfs_end_log_trans(struct btrfs_root *root);
 void btrfs_pin_log_trans(struct btrfs_root *root);
Signature · 1 line
2.35.1
#10 lore raw

PATCH v4 8/21 btrfs: setup qstrings from dentrys using fscrypt helper

In reply to Sweet Tea Dorminy

Most places where we get a struct qstr, we are doing so from a dentry. With fscrypt, the dentry's name may be encrypted on-disk, so fscrypt provides a helper to convert a dentry name to the appropriate disk name if necessary. Convert each of the dentry name accesses to use fscrypt_setup_filename(), then convert the resulting fscrypt_name back to an unencrypted qstr. This does not work for nokey names, but the specific locations that could spawn nokey names are noted.

At present, since there are no encrypted directories, nothing goes down the filename encryption paths.

---
 fs/btrfs/ctree.h       |   3 +
 fs/btrfs/inode.c       | 187 ++++++++++++++++++++++++++++++++---------
 fs/btrfs/transaction.c |  40 ++++++---
 fs/btrfs/tree-log.c    |  11 ++-
 4 files changed, 186 insertions(+), 55 deletions(-)
fs/btrfs/ctree.h +3 -0
index d80ebd5b1a83..6653972d7c01 100644
@@ -28,6 +28,7 @@
 #include <linux/refcount.h>
 #include <linux/crc32c.h>
 #include <linux/iomap.h>
+#include <linux/fscrypt.h>
 #include "extent-io-tree.h"
 #include "extent_io.h"
 #include "extent_map.h"
@@ -1674,6 +1675,8 @@ struct btrfs_new_inode_args {
 	 */
 	struct posix_acl *default_acl;
 	struct posix_acl *acl;
+	struct fscrypt_name fname;
+	struct qstr name;
 };
 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
 			    unsigned int *trans_num_items);
fs/btrfs/inode.c +145 -42

476 lines not on this page · raw message

fs/btrfs/transaction.c +28 -12
index 7db9612f4d0e..c2883d2b7111 100644
@@ -6,6 +6,7 @@
 #include <linux/fs.h>
 #include <linux/slab.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/writeback.h>
 #include <linux/pagemap.h>
 #include <linux/blkdev.h>
@@ -1611,10 +1612,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	struct btrfs_root *root = pending->root;
 	struct btrfs_root *parent_root;
 	struct btrfs_block_rsv *rsv;
-	struct inode *parent_inode;
+	struct inode *parent_inode = pending->dir;
 	struct btrfs_path *path;
 	struct btrfs_dir_item *dir_item;
-	struct dentry *dentry;
 	struct extent_buffer *tmp;
 	struct extent_buffer *old;
 	struct timespec64 cur_time;
@@ -1623,6 +1623,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	u64 index = 0;
 	u64 objectid;
 	u64 root_flags;
+	unsigned int mem_flags;
+	struct fscrypt_name fname;
+	struct qstr name;
 
 	ASSERT(pending->path);
 	path = pending->path;
@@ -1630,9 +1633,23 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	ASSERT(pending->root_item);
 	new_root_item = pending->root_item;
 
+	/*
+	 * Since this is during btrfs_commit_transaction() and more items
+	 * joining the transaction at this point would be bad, use NOFS
+	 * allocations so that no new writes are kicked off.
+	 */
+	mem_flags = memalloc_nofs_save();
+	pending->error = fscrypt_setup_filename(parent_inode,
+						&pending->dentry->d_name, 0,
+						&fname);
+	memalloc_nofs_restore(mem_flags);
+	if (pending->error)
+		goto free_pending;
+	name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
 	pending->error = btrfs_get_free_objectid(tree_root, &objectid);
 	if (pending->error)
-		goto no_free_objectid;
+		goto free_fname;
 
 	/*
 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
@@ -1661,8 +1678,6 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	trace_btrfs_space_reservation(fs_info, "transaction",
 				      trans->transid,
 				      trans->bytes_reserved, 1);
-	dentry = pending->dentry;
-	parent_inode = pending->dir;
 	parent_root = BTRFS_I(parent_inode)->root;
 	ret = record_root_in_trans(trans, parent_root, 0);
 	if (ret)
@@ -1678,7 +1693,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	/* check if there is a file/dir which has the same name. */
 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
 					 btrfs_ino(BTRFS_I(parent_inode)),
-					 &dentry->d_name, 0);
+					 &name, 0);
 	if (dir_item != NULL && !IS_ERR(dir_item)) {
 		pending->error = -EEXIST;
 		goto dir_item_existed;
@@ -1773,7 +1788,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	ret = btrfs_add_root_ref(trans, objectid,
 				 parent_root->root_key.objectid,
 				 btrfs_ino(BTRFS_I(parent_inode)), index,
-				 &dentry->d_name);
+				 &name);
 	if (ret) {
 		btrfs_abort_transaction(trans, ret);
 		goto fail;
@@ -1805,9 +1820,8 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	if (ret < 0)
 		goto fail;
 
-	ret = btrfs_insert_dir_item(trans, &dentry->d_name,
-				    BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
-				    index);
+	ret = btrfs_insert_dir_item(trans, &name, BTRFS_I(parent_inode), &key,
+				    BTRFS_FT_DIR, index);
 	/* We have check then name at the beginning, so it is impossible. */
 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
 	if (ret) {
@@ -1816,7 +1830,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	}
 
 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
-					 dentry->d_name.len * 2);
+						  name.len * 2);
 	parent_inode->i_mtime = current_time(parent_inode);
 	parent_inode->i_ctime = parent_inode->i_mtime;
 	ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
@@ -1848,7 +1862,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	trans->bytes_reserved = 0;
 clear_skip_qgroup:
 	btrfs_clear_skip_qgroup(trans);
-no_free_objectid:
+free_fname:
+	fscrypt_free_filename(&fname);
+free_pending:
 	kfree(new_root_item);
 	pending->root_item = NULL;
 	btrfs_free_path(path);
fs/btrfs/tree-log.c +10 -1
index d6c0bce7569a..f9ed05285a97 100644
@@ -7395,9 +7395,16 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
 	if (old_dir && old_dir->logged_trans == trans->transid) {
 		struct btrfs_root *log = old_dir->root->log_root;
 		struct btrfs_path *path;
+		struct fscrypt_name fname;
+		struct qstr name;
 
 		ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
 
+		ret = fscrypt_setup_filename(&old_dir->vfs_inode,
+					     &old_dentry->d_name, 0, &fname);
+		if (ret)
+			goto out;
+		name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
 		/*
 		 * We have two inodes to update in the log, the old directory and
 		 * the inode that got renamed, so we must pin the log to prevent
@@ -7417,6 +7424,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
 		path = btrfs_alloc_path();
 		if (!path) {
 			ret = -ENOMEM;
+			fscrypt_free_filename(&fname);
 			goto out;
 		}
 
@@ -7432,7 +7440,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
 		 */
 		mutex_lock(&old_dir->log_mutex);
 		ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
-					&old_dentry->d_name, old_dir_index);
+					&name, old_dir_index);
 		if (ret > 0) {
 			/*
 			 * The dentry does not exist in the log, so record its
@@ -7446,6 +7454,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
 		mutex_unlock(&old_dir->log_mutex);
 
 		btrfs_free_path(path);
+		fscrypt_free_filename(&fname);
 		if (ret < 0)
 			goto out;
 	}
Signature · 1 line
2.35.1
#14 lore raw

PATCH v4 10/21 btrfs: store directory encryption state

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

For directories with encrypted files/filenames, we need to store a flag indicating this fact. There's no room in other fields, so we'll need to borrow a bit from dir_type. Since it's now a combination of type and flags, we rename it to dir_flags to reflect its new usage.

The new flag, FT_ENCRYPTED, indicates a directory containing encrypted data, which is orthogonal to file type; therefore, add the new flag, and make conversion from directory type to file type strip the flag.

---
 fs/btrfs/accessors.h            | 15 +++++++++++++--
 fs/btrfs/delayed-inode.c        |  6 +++---
 fs/btrfs/delayed-inode.h        |  2 +-
 fs/btrfs/dir-item.c             |  7 +++++--
 fs/btrfs/inode.c                | 13 +++++++------
 fs/btrfs/print-tree.c           |  4 ++--
 fs/btrfs/send.c                 |  2 +-
 fs/btrfs/tree-checker.c         |  2 +-
 fs/btrfs/tree-log.c             | 20 ++++++++++----------
 include/uapi/linux/btrfs_tree.h |  7 +++++++
 10 files changed, 50 insertions(+), 28 deletions(-)
fs/btrfs/accessors.h +13 -2
index 18504c205b01..157f5712c7ac 100644
@@ -493,10 +493,10 @@ BTRFS_SETGET_FUNCS(root_ref_name_len, struct btrfs_root_ref, name_len, 16);
 
 /* struct btrfs_dir_item */
 BTRFS_SETGET_FUNCS(dir_data_len, struct btrfs_dir_item, data_len, 16);
-BTRFS_SETGET_FUNCS(dir_type, struct btrfs_dir_item, type, 8);
+BTRFS_SETGET_FUNCS(dir_flags, struct btrfs_dir_item, type, 8);
 BTRFS_SETGET_FUNCS(dir_name_len, struct btrfs_dir_item, name_len, 16);
 BTRFS_SETGET_FUNCS(dir_transid, struct btrfs_dir_item, transid, 64);
-BTRFS_SETGET_STACK_FUNCS(stack_dir_type, struct btrfs_dir_item, type, 8);
+BTRFS_SETGET_STACK_FUNCS(stack_dir_flags, struct btrfs_dir_item, type, 8);
 BTRFS_SETGET_STACK_FUNCS(stack_dir_data_len, struct btrfs_dir_item,
 			 data_len, 16);
 BTRFS_SETGET_STACK_FUNCS(stack_dir_name_len, struct btrfs_dir_item,
@@ -504,6 +504,17 @@ BTRFS_SETGET_STACK_FUNCS(stack_dir_name_len, struct btrfs_dir_item,
 BTRFS_SETGET_STACK_FUNCS(stack_dir_transid, struct btrfs_dir_item,
 			 transid, 64);
 
+static inline u8 btrfs_dir_ftype(const struct extent_buffer *eb,
+				 const struct btrfs_dir_item *item)
+{
+	return btrfs_dir_flags_to_ftype(btrfs_dir_flags(eb, item));
+}
+
+static inline u8 btrfs_stack_dir_ftype(const struct btrfs_dir_item *item)
+{
+	return btrfs_dir_flags_to_ftype(btrfs_stack_dir_flags(item));
+}
+
 static inline void btrfs_dir_item_key(const struct extent_buffer *eb,
 				      const struct btrfs_dir_item *item,
 				      struct btrfs_disk_key *key)
fs/btrfs/delayed-inode.c +3 -3
index 74ef2db1b2ec..a935709f2a29 100644
@@ -1417,7 +1417,7 @@ void btrfs_balance_delayed_items(struct btrfs_fs_info *fs_info)
 int btrfs_insert_delayed_dir_index(struct btrfs_trans_handle *trans,
 				   const char *name, int name_len,
 				   struct btrfs_inode *dir,
-				   struct btrfs_disk_key *disk_key, u8 type,
+				   struct btrfs_disk_key *disk_key, u8 flags,
 				   u64 index)
 {
 	struct btrfs_fs_info *fs_info = trans->fs_info;
@@ -1448,7 +1448,7 @@ int btrfs_insert_delayed_dir_index(struct btrfs_trans_handle *trans,
 	btrfs_set_stack_dir_transid(dir_item, trans->transid);
 	btrfs_set_stack_dir_data_len(dir_item, 0);
 	btrfs_set_stack_dir_name_len(dir_item, name_len);
-	btrfs_set_stack_dir_type(dir_item, type);
+	btrfs_set_stack_dir_flags(dir_item, flags);
 	memcpy((char *)(dir_item + 1), name, name_len);
 
 	data_len = delayed_item->data_len + sizeof(struct btrfs_item);
@@ -1758,7 +1758,7 @@ int btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
 		name = (char *)(di + 1);
 		name_len = btrfs_stack_dir_name_len(di);
 
-		d_type = fs_ftype_to_dtype(di->type);
+		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,
fs/btrfs/delayed-inode.h +1 -1
index 0163ca637a96..4f21daa3dbc7 100644
@@ -113,7 +113,7 @@ static inline void btrfs_init_delayed_root(
 int btrfs_insert_delayed_dir_index(struct btrfs_trans_handle *trans,
 				   const char *name, int name_len,
 				   struct btrfs_inode *dir,
-				   struct btrfs_disk_key *disk_key, u8 type,
+				   struct btrfs_disk_key *disk_key, u8 flags,
 				   u64 index);
 
 int btrfs_delete_delayed_dir_index(struct btrfs_trans_handle *trans,
fs/btrfs/dir-item.c +5 -2
index 23777021b331..ca69fb35a2cc 100644
@@ -83,7 +83,7 @@ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans,
 	leaf = path->nodes[0];
 	btrfs_cpu_key_to_disk(&disk_key, &location);
 	btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
-	btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR);
+	btrfs_set_dir_flags(leaf, dir_item, BTRFS_FT_XATTR);
 	btrfs_set_dir_name_len(leaf, dir_item, name_len);
 	btrfs_set_dir_transid(leaf, dir_item, trans->transid);
 	btrfs_set_dir_data_len(leaf, dir_item, data_len);
@@ -140,9 +140,12 @@ int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,
 		goto out_free;
 	}
 
+	if (IS_ENCRYPTED(&dir->vfs_inode))
+		type |= BTRFS_FT_ENCRYPTED;
+
 	leaf = path->nodes[0];
 	btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
-	btrfs_set_dir_type(leaf, dir_item, type);
+	btrfs_set_dir_flags(leaf, dir_item, type);
 	btrfs_set_dir_data_len(leaf, dir_item, 0);
 	btrfs_set_dir_name_len(leaf, dir_item, name->len);
 	btrfs_set_dir_transid(leaf, dir_item, trans->transid);
fs/btrfs/inode.c +7 -6
index b4f5e90c674d..c41ae611767c 100644
@@ -5595,7 +5595,7 @@ static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
 			   location->objectid, location->type, location->offset);
 	}
 	if (!ret)
-		*type = btrfs_dir_type(path->nodes[0], di);
+		*type = btrfs_dir_ftype(path->nodes[0], di);
 out:
 	fscrypt_free_filename(&fname);
 	btrfs_free_path(path);
@@ -6045,6 +6045,7 @@ static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
 	btrfs_for_each_slot(root, &key, &found_key, path, ret) {
 		struct dir_entry *entry;
 		struct extent_buffer *leaf = path->nodes[0];
+		u8 ftype;
 
 		if (found_key.objectid != key.objectid)
 			break;
@@ -6068,13 +6069,13 @@ static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
 			goto again;
 		}
 
+		ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
 		entry = addr;
-		put_unaligned(name_len, &entry->name_len);
 		name_ptr = (char *)(entry + 1);
-		read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
-				   name_len);
-		put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
-				&entry->type);
+		read_extent_buffer(leaf, name_ptr,
+				   (unsigned long)(di + 1), name_len);
+		put_unaligned(name_len, &entry->name_len);
+		put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
 		put_unaligned(location.objectid, &entry->ino);
 		put_unaligned(found_key.offset, &entry->offset);
fs/btrfs/print-tree.c +2 -2
index aab7d30eed55..1a2350fd68be 100644
@@ -242,9 +242,9 @@ void btrfs_print_leaf(struct extent_buffer *l)
 		case BTRFS_DIR_ITEM_KEY:
 			di = btrfs_item_ptr(l, i, struct btrfs_dir_item);
 			btrfs_dir_item_key_to_cpu(l, di, &found_key);
-			pr_info("\t\tdir oid %llu type %u\n",
+			pr_info("\t\tdir oid %llu flags %u\n",
 				found_key.objectid,
-				btrfs_dir_type(l, di));
+				btrfs_dir_flags(l, di));
 			break;
 		case BTRFS_ROOT_ITEM_KEY:
 			ri = btrfs_item_ptr(l, i, struct btrfs_root_item);
fs/btrfs/send.c +1 -1
index 4de7e2157c2b..cc9580232c9f 100644
@@ -1094,7 +1094,7 @@ static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
 		data_len = btrfs_dir_data_len(eb, di);
 		btrfs_dir_item_key_to_cpu(eb, di, &di_key);
 
-		if (btrfs_dir_type(eb, di) == BTRFS_FT_XATTR) {
+		if (btrfs_dir_ftype(eb, di) == BTRFS_FT_XATTR) {
 			if (name_len > XATTR_NAME_MAX) {
 				ret = -ENAMETOOLONG;
 				goto out;
fs/btrfs/tree-checker.c +1 -1
index 11cafc520b47..1c2d418dda6a 100644
@@ -531,7 +531,7 @@ static int check_dir_item(struct extent_buffer *leaf,
 		}
 
 		/* dir type check */
-		dir_type = btrfs_dir_type(leaf, di);
+		dir_type = btrfs_dir_ftype(leaf, di);
 		if (unlikely(dir_type >= BTRFS_FT_MAX)) {
 			dir_item_err(leaf, slot,
 			"invalid dir item type, have %u expect [0, %u)",
fs/btrfs/tree-log.c +10 -10
index 3cb490d604e4..f261f8589033 100644
@@ -1799,7 +1799,7 @@ static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
 					struct btrfs_path *path,
 					struct btrfs_dir_item *dst_di,
 					const struct btrfs_key *log_key,
-					u8 log_type,
+					u8 log_flags,
 					bool exists)
 {
 	struct btrfs_key found_key;
@@ -1809,7 +1809,7 @@ static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
 	if (found_key.objectid == log_key->objectid &&
 	    found_key.type == log_key->type &&
 	    found_key.offset == log_key->offset &&
-	    btrfs_dir_type(path->nodes[0], dst_di) == log_type)
+	    btrfs_dir_flags(path->nodes[0], dst_di) == log_flags)
 		return 1;
 
 	/*
@@ -1853,7 +1853,7 @@ static noinline int replay_one_name(struct btrfs_trans_handle *trans,
 	struct btrfs_key log_key;
 	struct btrfs_key search_key;
 	struct inode *dir;
-	u8 log_type;
+	u8 log_flags;
 	bool exists;
 	int ret;
 	bool update_size = true;
@@ -1867,7 +1867,7 @@ static noinline int replay_one_name(struct btrfs_trans_handle *trans,
 	if (ret)
 		goto out;
 
-	log_type = btrfs_dir_type(eb, di);
+	log_flags = btrfs_dir_flags(eb, di);
 	btrfs_dir_item_key_to_cpu(eb, di, &log_key);
 	ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
 	btrfs_release_path(path);
@@ -1883,8 +1883,8 @@ static noinline int replay_one_name(struct btrfs_trans_handle *trans,
 		goto out;
 	} else if (dir_dst_di) {
 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
-						   dir_dst_di, &log_key, log_type,
-						   exists);
+						   dir_dst_di, &log_key,
+						   log_flags, exists);
 		if (ret < 0)
 			goto out;
 		dir_dst_matches = (ret == 1);
@@ -1901,7 +1901,7 @@ static noinline int replay_one_name(struct btrfs_trans_handle *trans,
 	} else if (index_dst_di) {
 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
 						   index_dst_di, &log_key,
-						   log_type, exists);
+						   log_flags, exists);
 		if (ret < 0)
 			goto out;
 		index_dst_matches = (ret == 1);
@@ -2010,7 +2010,7 @@ static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
 	 * to ever delete the parent directory has it would result in stale
 	 * dentries that can never be deleted.
 	 */
-	if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
+	if (ret == 1 && btrfs_dir_ftype(eb, di) != BTRFS_FT_DIR) {
 		struct btrfs_path *fixup_path;
 		struct btrfs_key di_key;
 
@@ -5401,7 +5401,7 @@ static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
 			}
 
 			di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
-			type = btrfs_dir_type(leaf, di);
+			type = btrfs_dir_ftype(leaf, di);
 			if (btrfs_dir_transid(leaf, di) < trans->transid)
 				continue;
 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
@@ -6241,7 +6241,7 @@ static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
 			continue;
 		}
 
-		if (btrfs_stack_dir_type(dir_item) == BTRFS_FT_DIR)
+		if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
 			log_mode = LOG_INODE_ALL;
 
 		ctx->log_new_dentries = false;
include/uapi/linux/btrfs_tree.h +7 -0
index f6eb8a0aee6e..10c3c41329bc 100644
@@ -375,6 +375,13 @@ enum btrfs_csum_type {
 #define BTRFS_FT_SYMLINK	7
 #define BTRFS_FT_XATTR		8
 #define BTRFS_FT_MAX		9
+/* Directory contains encrypted data */
+#define BTRFS_FT_ENCRYPTED	0x80
+
+static inline __u8 btrfs_dir_flags_to_ftype(__u8 flags)
+{
+	return flags & ~BTRFS_FT_ENCRYPTED;
+}
 
 /*
  * Inode flags
Signature · 1 line
2.35.1
#17 lore raw

PATCH v4 13/21 btrfs: add fscrypt_context items

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

In order to store per-inode information such as the inode nonce and the key identifier, fscrypt stores a context item with each encrypted inode. This can be implemented as a new item type, as fscrypt provides an arbitrary blob for the filesystem to store.

This also provides a good place to implement full-subvolume encryption:
a subvolume flag permits setting one context for the whole subvolume. However, since an unencrypted subvolume would be unable to read encrypted data, encrypted subvolumes should only be snapshottable to other encrypted subvolumes.

---
 fs/btrfs/ctree.h                |   1 +
 fs/btrfs/fscrypt.c              | 182 ++++++++++++++++++++++++++++++++
 fs/btrfs/inode.c                |  39 +++++++
 fs/btrfs/ioctl.c                |   7 +-
 fs/btrfs/tree-checker.c         |   1 +
 include/uapi/linux/btrfs_tree.h |  12 +++
 6 files changed, 241 insertions(+), 1 deletion(-)
fs/btrfs/ctree.h +1 -0
index 58774c378452..f4e6ff5da1f7 100644
@@ -32,6 +32,7 @@
 #include "extent-io-tree.h"
 #include "extent_io.h"
 #include "extent_map.h"
+#include "fscrypt.h"
 #include "async-thread.h"
 #include "block-rsv.h"
 #include "locking.h"
fs/btrfs/fscrypt.c +182 -0

189 lines not on this page · raw message

fs/btrfs/inode.c +39 -0
index 960e3ff092e6..548ffc8ed98e 100644
@@ -6284,6 +6284,34 @@ 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 (IS_ENCRYPTED(dir) &&
+	    !(BTRFS_I(dir)->flags & BTRFS_INODE_FSCRYPT_CONTEXT)) {
+		struct inode *root_inode;
+		bool encrypt;
+
+		root_inode = btrfs_iget(inode->i_sb, BTRFS_FIRST_FREE_OBJECTID,
+					BTRFS_I(dir)->root);
+		if (IS_ERR(root_inode))
+			return PTR_ERR(root_inode);
+		/*
+		 * TODO: perhaps instead of faking making a new dir to get a
+		 * new context, it would be better to expose
+		 * fscrypt_setup_encryption_info() for our use.
+		 */
+		ret = fscrypt_prepare_new_inode(root_inode, dir, &encrypt);
+		if (!ret) {
+			ret = fscrypt_set_context(dir, NULL);
+			if (ret)
+				fscrypt_put_encryption_info(dir);
+		}
+		iput(root_inode);
+		if (ret)
+			return ret;
+	}
+
 	if (!args->orphan) {
 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
 					     &args->fname);
@@ -6317,6 +6345,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)++;
@@ -6570,6 +6601,14 @@ int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
 		}
 	}
 
+	if (args->encrypt) {
+		ret = fscrypt_set_context(inode, trans);
+		if (ret) {
+			btrfs_abort_transaction(trans, ret);
+			goto discard;
+		}
+	}
+
 	inode_tree_add(inode);
 
 	trace_btrfs_inode_new(inode);
fs/btrfs/ioctl.c +6 -1
index ea735904ee43..b28b7588f651 100644
@@ -660,7 +660,8 @@ static noinline int create_subvol(struct user_namespace *mnt_userns,
 				     fs_info->nodesize);
 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
 
-	btrfs_set_root_flags(root_item, 0);
+	btrfs_set_root_flags(root_item, new_inode_args.encrypt ?
+			     BTRFS_ROOT_SUBVOL_FSCRYPT : 0);
 	btrfs_set_root_limit(root_item, 0);
 	btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
 
@@ -789,6 +790,10 @@ static int create_snapshot(struct btrfs_root *root, struct inode *dir,
 		return -ETXTBSY;
 	}
 
+	if ((btrfs_root_flags(&root->root_item) & BTRFS_ROOT_SUBVOL_FSCRYPT) &&
+	    !IS_ENCRYPTED(dir))
+		return -EXDEV;
+
 	pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
 	if (!pending_snapshot)
 		return -ENOMEM;
fs/btrfs/tree-checker.c +1 -0
index 1c2d418dda6a..77e678efef65 100644
@@ -1123,6 +1123,7 @@ static int check_root_item(struct extent_buffer *leaf, struct btrfs_key *key,
 	struct btrfs_fs_info *fs_info = leaf->fs_info;
 	struct btrfs_root_item ri = { 0 };
 	const u64 valid_root_flags = BTRFS_ROOT_SUBVOL_RDONLY |
+				     BTRFS_ROOT_SUBVOL_FSCRYPT |
 				     BTRFS_ROOT_SUBVOL_DEAD;
 	int ret;
 
include/uapi/linux/btrfs_tree.h +12 -0
index 10c3c41329bc..fe112f55a1d2 100644
@@ -160,6 +160,8 @@
 #define BTRFS_VERITY_DESC_ITEM_KEY	36
 #define BTRFS_VERITY_MERKLE_ITEM_KEY	37
 
+#define BTRFS_FSCRYPT_CTXT_ITEM_KEY	41
+
 #define BTRFS_ORPHAN_ITEM_KEY		48
 /* reserve 2-15 close to the inode for later flexibility */
 
@@ -398,6 +400,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_FSCRYPT_CONTEXT	(1U << 12)
 
 #define BTRFS_INODE_ROOT_ITEM_INIT	(1U << 31)
 
@@ -414,6 +417,7 @@ static inline __u8 btrfs_dir_flags_to_ftype(__u8 flags)
 	 BTRFS_INODE_NOATIME |						\
 	 BTRFS_INODE_DIRSYNC |						\
 	 BTRFS_INODE_COMPRESS |						\
+	 BTRFS_INODE_FSCRYPT_CONTEXT |					\
 	 BTRFS_INODE_ROOT_ITEM_INIT)
 
 #define BTRFS_INODE_RO_VERITY		(1U << 0)
@@ -858,6 +862,8 @@ struct btrfs_dir_item {
 } __attribute__ ((__packed__));
 
 #define BTRFS_ROOT_SUBVOL_RDONLY	(1ULL << 0)
+/* Top-level subvolume directory is encrypted with fscrypt. */
+#define BTRFS_ROOT_SUBVOL_FSCRYPT	(1ULL << 1)
 
 /*
  * Internal in-memory flag that a subvolume has been marked for deletion but
@@ -1013,6 +1019,12 @@ enum {
 	BTRFS_NR_FILE_EXTENT_TYPES = 3,
 };
 
+enum {
+	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.35.1
#16 lore raw

PATCH v4 12/21 btrfs: start using fscrypt hooks

In reply to Sweet Tea Dorminy

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.

---
 fs/btrfs/Makefile  |  1 +
 fs/btrfs/ctree.h   |  1 +
 fs/btrfs/file.c    |  3 ++
 fs/btrfs/fscrypt.c |  7 ++++
 fs/btrfs/fscrypt.h | 10 +++++
 fs/btrfs/inode.c   | 91 ++++++++++++++++++++++++++++++++++++++++------
 fs/btrfs/super.c   |  2 +
 7 files changed, 103 insertions(+), 12 deletions(-)
 create mode 100644 fs/btrfs/fscrypt.c
 create mode 100644 fs/btrfs/fscrypt.h
fs/btrfs/Makefile +1 -0
index 76f90dcfb14d..916d7ab95632 100644
@@ -38,6 +38,7 @@ btrfs-$(CONFIG_BTRFS_FS_CHECK_INTEGRITY) += check-integrity.o
 btrfs-$(CONFIG_BTRFS_FS_REF_VERIFY) += 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/ctree.h +1 -0
index fda22e5c7a6b..58774c378452 100644
@@ -1676,6 +1676,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,
 			    unsigned int *trans_num_items);
fs/btrfs/file.c +3 -0
index 97d098b3c2e6..769a2a27941c 100644
@@ -4011,6 +4011,9 @@ static int btrfs_file_open(struct inode *inode, struct file *filp)
 	int ret;
 
 	filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC | FMODE_BUF_WASYNC;
+	ret = fscrypt_file_open(inode, filp);
+	if (ret)
+		return ret;
 
 	ret = fsverity_file_open(inode, filp);
 	if (ret)
fs/btrfs/fscrypt.c new file +7 -0
new file mode 100644
index 000000000000..48ab99dfe48d
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include "ctree.h"
+#include "fscrypt.h"
+
+const struct fscrypt_operations btrfs_fscrypt_ops = {
+};
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 +79 -12

200 lines not on this page · raw message

fs/btrfs/super.c +2 -0
index 863804751b06..8ab5171d07e8 100644
@@ -48,6 +48,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"
@@ -1475,6 +1476,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;
 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
 	sb->s_flags |= SB_POSIXACL;
Signature · 1 line
2.35.1
#24 lore raw

PATCH v4 17/21 btrfs: Add new FEATURE_INCOMPAT_ENCRYPT feature flag.

In reply to Sweet Tea Dorminy

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.

---
 fs/btrfs/fs.h              | 5 +++--
 fs/btrfs/super.c           | 5 +++++
 include/uapi/linux/btrfs.h | 1 +
 3 files changed, 9 insertions(+), 2 deletions(-)
fs/btrfs/fs.h +3 -2
index 2bd1b9e03d30..8eeb1918aa1c 100644
@@ -159,7 +159,7 @@ enum {
 
 #ifdef CONFIG_BTRFS_DEBUG
 /*
- * Extent tree v2 supported only with CONFIG_BTRFS_DEBUG
+ * Extent tree v2 and encryption supported only with CONFIG_BTRFS_DEBUG
  */
 #define BTRFS_FEATURE_INCOMPAT_SUPP			\
 	(BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF |		\
@@ -175,7 +175,8 @@ enum {
 	 BTRFS_FEATURE_INCOMPAT_METADATA_UUID	|	\
 	 BTRFS_FEATURE_INCOMPAT_RAID1C34	|	\
 	 BTRFS_FEATURE_INCOMPAT_ZONED		|	\
-	 BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2)
+	 BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2	|	\
+	 BTRFS_FEATURE_INCOMPAT_ENCRYPT)
 #else
 #define BTRFS_FEATURE_INCOMPAT_SUPP			\
 	(BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF |		\
fs/btrfs/super.c +5 -0
index 8ab5171d07e8..c1075db7bfc7 100644
@@ -2751,6 +2751,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
 			;
 	pr_info("Btrfs loaded, crc32c=%s%s\n", crc32c_impl(), options);
include/uapi/linux/btrfs.h +1 -0
index 5655e89b962b..1d29f0df995b 100644
@@ -316,6 +316,7 @@ struct btrfs_ioctl_fs_info_args {
 #define BTRFS_FEATURE_INCOMPAT_RAID1C34		(1ULL << 11)
 #define BTRFS_FEATURE_INCOMPAT_ZONED		(1ULL << 12)
 #define BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2	(1ULL << 13)
+#define BTRFS_FEATURE_INCOMPAT_ENCRYPT		(1ULL << 14)
 
 struct btrfs_ioctl_feature_flags {
 	__u64 compat_flags;
Signature · 1 line
2.35.1
#27 lore raw

PATCH v4 20/21 btrfs: use correct name hash for nokey names

In reply to Sweet Tea Dorminy

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.

---
 fs/btrfs/dir-item.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
fs/btrfs/dir-item.c +6 -2
index d5275475e69e..11236ebdb07f 100644
@@ -256,8 +256,12 @@ 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)
Signature · 1 line
2.35.1
#25 lore raw

PATCH v4 18/21 btrfs: implement fscrypt ioctls

In reply to Sweet Tea Dorminy

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.

---
 fs/btrfs/ioctl.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
fs/btrfs/ioctl.c +28 -0
index 9cd59ab5a8a9..aa5845d95f7d 100644
@@ -5450,6 +5450,34 @@ 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);
+	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);
 	case FITRIM:
 		return btrfs_ioctl_fitrim(fs_info, argp);
 	case BTRFS_IOC_SNAP_CREATE:
Signature · 1 line
2.35.1
#28 lore raw

PATCH v4 21/21 btrfs: encrypt verity items

In reply to Sweet Tea Dorminy

Verity items are deemed to have sensitive information about the file contents, so verity items for a encrypted file should be encrypted. This change uses the fscrypt inplace encryption helper to do so, which should be similar to what is used for inline extents.

This change has two related holes. Currently, this reuses the fscrypt extent context from the data in the file for encryption: if there are not yet any extents for the file when verity is enabled thereon, there is no fscrypt extent context yet and encryption fails. Additionally, IVs shouldn't be reused. I think the best solution here is to somehow pack the 33-byte fscrypt extent contexts into the 16 bytes reserved for encryption in verity items, and use that in some in-memory-only extent maps set up to cover the file indexes after the actual data.

But maybe a better solution is to move fscrypt extent contexts into their own items with offsets past the end of the file, and then there's no risk of in-memory-only extent maps accidentally making it to disk or confusing some other part of the system.

---
 fs/btrfs/verity.c | 114 ++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 99 insertions(+), 15 deletions(-)
fs/btrfs/verity.c +99 -15
index d02fa354fc2b..d9dff9e31da2 100644
@@ -8,6 +8,7 @@
 #include <linux/security.h>
 #include <linux/posix_acl_xattr.h>
 #include <linux/iversion.h>
+#include <linux/fscrypt.h>
 #include <linux/fsverity.h>
 #include <linux/sched/mm.h>
 #include "messages.h"
@@ -221,14 +222,52 @@ static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 	struct btrfs_key key;
 	unsigned long copy_bytes;
 	unsigned long src_offset = 0;
-	void *data;
+	void *data_pos;
 	int ret = 0;
+#ifdef CONFIG_FS_ENCRYPTION
+	struct page *ciphertext_page = NULL;
+	char *ciphertext_buf;
+
+	if (IS_ENCRYPTED(&inode->vfs_inode)) {
+		ciphertext_page = alloc_page(GFP_NOFS);
+		if (!ciphertext_page)
+			return -ENOMEM;
+		ciphertext_buf = kmap_local_page(ciphertext_page);
+	}
+#endif /* CONFIG_FS_ENCRYPTION */
 
 	path = btrfs_alloc_path();
 	if (!path)
 		return -ENOMEM;
 
 	while (len > 0) {
+		const char *data = src + src_offset;
+		/*
+		 * Insert 2K at a time mostly to be friendly for smaller leaf
+		 * size filesystems
+		 */
+		copy_bytes = min_t(u64, len, 2048);
+
+#ifdef CONFIG_FS_ENCRYPTION
+		if (ciphertext_page) {
+			struct btrfs_fs_info *fs_info = inode->root->fs_info;
+			u64 lblk_num = offset >> fs_info->sectorsize_bits;
+
+			memset(ciphertext_buf, 0, PAGE_SIZE);
+			memcpy(ciphertext_buf, data, copy_bytes);
+			copy_bytes = ALIGN(copy_bytes,
+					   FSCRYPT_CONTENTS_ALIGNMENT);
+			ret = fscrypt_encrypt_block_inplace(&inode->vfs_inode,
+							    ciphertext_page,
+							    copy_bytes, 0,
+							    lblk_num,
+							    GFP_NOFS);
+			if (ret)
+				break;
+			data = ciphertext_buf;
+		}
+#endif /* CONFIG_FS_ENCRYPTION */
+
 		/* 1 for the new item being inserted */
 		trans = btrfs_start_transaction(root, 1);
 		if (IS_ERR(trans)) {
@@ -240,12 +279,6 @@ static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 		key.type = key_type;
 		key.offset = offset;
 
-		/*
-		 * Insert 2K at a time mostly to be friendly for smaller leaf
-		 * size filesystems
-		 */
-		copy_bytes = min_t(u64, len, 2048);
-
 		ret = btrfs_insert_empty_item(trans, root, path, &key, copy_bytes);
 		if (ret) {
 			btrfs_end_transaction(trans);
@@ -254,18 +287,25 @@ static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 
 		leaf = path->nodes[0];
 
-		data = btrfs_item_ptr(leaf, path->slots[0], void);
-		write_extent_buffer(leaf, src + src_offset,
-				    (unsigned long)data, copy_bytes);
+		data_pos = btrfs_item_ptr(leaf, path->slots[0], void);
+		write_extent_buffer(leaf, data,
+				    (unsigned long)data_pos, copy_bytes);
 		offset += copy_bytes;
 		src_offset += copy_bytes;
-		len -= copy_bytes;
+		len -= min_t(u64, copy_bytes, len);
 
 		btrfs_release_path(path);
 		btrfs_end_transaction(trans);
 	}
 
 	btrfs_free_path(path);
+#ifdef CONFIG_FS_ENCRYPTION
+	if (ciphertext_page) {
+		kunmap_local(ciphertext_buf);
+		__free_page(ciphertext_page);
+	}
+#endif /* CONFIG_FS_ENCRYPTION */
+
 	return ret;
 }
 
@@ -307,6 +347,17 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 	void *data;
 	char *kaddr = dest;
 	int ret;
+#ifdef CONFIG_FS_ENCRYPTION
+	char *ciphertext_buf;
+	struct page *ciphertext_page = NULL;
+
+	if (dest && IS_ENCRYPTED(&inode->vfs_inode)) {
+		ciphertext_page = alloc_page(GFP_NOFS);
+		if (!ciphertext_page)
+			return -ENOMEM;
+		ciphertext_buf = kmap_local_page(ciphertext_page);
+	}
+#endif /* CONFIG_FS_ENCRYPTION */
 
 	path = btrfs_alloc_path();
 	if (!path)
@@ -368,14 +419,41 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 		/* Offset from the start of item for copying */
 		copy_offset = offset - key.offset;
 
+		data = btrfs_item_ptr(leaf, path->slots[0], void);
 		if (dest) {
+#ifdef CONFIG_FS_ENCRYPTION
+			if (ciphertext_page) {
+				struct btrfs_fs_info *fs_info =
+					inode->root->fs_info;
+				u64 lblk_num = offset >> fs_info->sectorsize_bits;
+
+				read_extent_buffer(leaf, ciphertext_buf,
+						   (unsigned long)data + copy_offset,
+						   item_end - offset);
+				ret = fscrypt_decrypt_block_inplace(&inode->vfs_inode,
+								    ciphertext_page,
+								    item_end - offset, 0,
+								    lblk_num);
+				if (ret)
+					break;
+			}
+#endif /* CONFIG_FS_ENCRYPTION */
+
 			if (dest_page)
 				kaddr = kmap_local_page(dest_page);
 
-			data = btrfs_item_ptr(leaf, path->slots[0], void);
-			read_extent_buffer(leaf, kaddr + dest_offset,
-					   (unsigned long)data + copy_offset,
-					   copy_bytes);
+			if (IS_ENABLED(CONFIG_FS_ENCRYPTION) &&
+			    IS_ENCRYPTED(&inode->vfs_inode)) {
+#ifdef CONFIG_FS_ENCRYPTION
+				memcpy(kaddr + dest_offset,
+				       ciphertext_buf + copy_offset,
+				       copy_bytes);
+#endif /* CONFIG_FS_ENCRYPTION */
+			} else {
+				read_extent_buffer(leaf, kaddr + dest_offset,
+						   (unsigned long)data + copy_offset,
+						   copy_bytes);
+			}
 
 			if (dest_page)
 				kunmap_local(kaddr);
@@ -402,6 +480,12 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
 		}
 	}
 out:
+#ifdef CONFIG_FS_ENCRYPTION
+	if (ciphertext_page) {
+		kunmap_local(ciphertext_buf);
+		__free_page(ciphertext_page);
+	}
+#endif /* CONFIG_FS_ENCRYPTION */
 	btrfs_free_path(path);
 	if (!ret)
 		ret = copied;
Signature · 1 line
2.35.1
#13 lore raw

PATCH v4 9/21 btrfs: use struct fscrypt_str instead of struct qstr

In reply to Sweet Tea Dorminy

While struct qstr is more natural without fscrypt, since it's provided by dentries, struct fscrypt_str is provided by the fscrypt handlers processing dentries, and is thus more natural in the fscrypt world. Replace all of the struct qstr uses with struct fscrypt_str.

---
 fs/btrfs/ctree.h       | 19 +++++----
 fs/btrfs/dir-item.c    | 10 ++---
 fs/btrfs/inode-item.c  | 14 +++----
 fs/btrfs/inode-item.h  | 10 ++---
 fs/btrfs/inode.c       | 89 +++++++++++++++++-------------------------
 fs/btrfs/ioctl.c       |  4 +-
 fs/btrfs/root-tree.c   |  4 +-
 fs/btrfs/send.c        |  4 +-
 fs/btrfs/super.c       |  2 +-
 fs/btrfs/transaction.c | 13 +++---
 fs/btrfs/tree-log.c    | 42 ++++++++++----------
 fs/btrfs/tree-log.h    |  4 +-
 12 files changed, 97 insertions(+), 118 deletions(-)
fs/btrfs/ctree.h +9 -10
index 6653972d7c01..fda22e5c7a6b 100644
@@ -1518,10 +1518,10 @@ int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
 /* root-item.c */
 int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 		       u64 ref_id, u64 dirid, u64 sequence,
-		       const struct qstr *name);
+		       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 qstr *name);
+		       const struct fscrypt_str *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,
@@ -1550,23 +1550,23 @@ int btrfs_uuid_tree_iterate(struct btrfs_fs_info *fs_info);
 
 /* dir-item.c */
 int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,
-			  const struct qstr *name);
+			  const struct fscrypt_str *name);
 int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,
-			  const struct qstr *name, struct btrfs_inode *dir,
+			  const struct fscrypt_str *name, struct btrfs_inode *dir,
 			  struct btrfs_key *location, u8 type, u64 index);
 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 qstr *name, int mod);
+					     const struct fscrypt_str *name, int mod);
 struct btrfs_dir_item *
 btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
 			    struct btrfs_root *root,
 			    struct btrfs_path *path, u64 dir,
-			    u64 index, const struct qstr *name, int mod);
+			    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 qstr *name);
+			    const struct fscrypt_str *name);
 int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans,
 			      struct btrfs_root *root,
 			      struct btrfs_path *path,
@@ -1647,10 +1647,10 @@ 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 qstr *name);
+		       const struct fscrypt_str *name);
 int btrfs_add_link(struct btrfs_trans_handle *trans,
 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
-		   const struct qstr *name, int add_backref, u64 index);
+		   const struct fscrypt_str *name, int add_backref, u64 index);
 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry);
 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
 			 int front);
@@ -1676,7 +1676,6 @@ struct btrfs_new_inode_args {
 	struct posix_acl *default_acl;
 	struct posix_acl *acl;
 	struct fscrypt_name fname;
-	struct qstr name;
 };
 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
 			    unsigned int *trans_num_items);
fs/btrfs/dir-item.c +5 -5
index 48a15af4ec57..23777021b331 100644
@@ -106,7 +106,7 @@ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans,
  * Will return 0 or -ENOMEM
  */
 int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,
-			  const struct qstr *name, struct btrfs_inode *dir,
+			  const struct fscrypt_str *name, struct btrfs_inode *dir,
 			  struct btrfs_key *location, u8 type, u64 index)
 {
 	int ret = 0;
@@ -208,7 +208,7 @@ static struct btrfs_dir_item *btrfs_lookup_match_dir(
 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 qstr *name,
+					     const struct fscrypt_str *name,
 					     int mod)
 {
 	struct btrfs_key key;
@@ -227,7 +227,7 @@ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
 }
 
 int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,
-				   const struct qstr *name)
+				   const struct fscrypt_str *name)
 {
 	int ret;
 	struct btrfs_key key;
@@ -304,7 +304,7 @@ struct btrfs_dir_item *
 btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
 			    struct btrfs_root *root,
 			    struct btrfs_path *path, u64 dir,
-			    u64 index, const struct qstr *name, int mod)
+			    u64 index, const struct fscrypt_str *name, int mod)
 {
 	struct btrfs_dir_item *di;
 	struct btrfs_key key;
@@ -323,7 +323,7 @@ btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
 
 struct btrfs_dir_item *
 btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path,
-			    u64 dirid, const struct qstr *name)
+			    u64 dirid, const struct fscrypt_str *name)
 {
 	struct btrfs_dir_item *di;
 	struct btrfs_key key;
fs/btrfs/inode-item.c +7 -7
index 577e39cfc411..d66bdbae5585 100644
@@ -15,7 +15,7 @@
 
 struct btrfs_inode_ref *btrfs_find_name_in_backref(struct extent_buffer *leaf,
 						   int slot,
-						   const struct qstr *name)
+						   const struct fscrypt_str *name)
 {
 	struct btrfs_inode_ref *ref;
 	unsigned long ptr;
@@ -42,7 +42,7 @@ struct btrfs_inode_ref *btrfs_find_name_in_backref(struct extent_buffer *leaf,
 
 struct btrfs_inode_extref *btrfs_find_name_in_ext_backref(
 		struct extent_buffer *leaf, int slot, u64 ref_objectid,
-		const struct qstr *name)
+		const struct fscrypt_str *name)
 {
 	struct btrfs_inode_extref *extref;
 	unsigned long ptr;
@@ -81,7 +81,7 @@ struct btrfs_inode_extref *
 btrfs_lookup_inode_extref(struct btrfs_trans_handle *trans,
 			  struct btrfs_root *root,
 			  struct btrfs_path *path,
-			  const struct qstr *name,
+			  const struct fscrypt_str *name,
 			  u64 inode_objectid, u64 ref_objectid, int ins_len,
 			  int cow)
 {
@@ -104,7 +104,7 @@ btrfs_lookup_inode_extref(struct btrfs_trans_handle *trans,
 
 static int btrfs_del_inode_extref(struct btrfs_trans_handle *trans,
 				  struct btrfs_root *root,
-				  const struct qstr *name,
+				  const struct fscrypt_str *name,
 				  u64 inode_objectid, u64 ref_objectid,
 				  u64 *index)
 {
@@ -174,7 +174,7 @@ static int btrfs_del_inode_extref(struct btrfs_trans_handle *trans,
 }
 
 int btrfs_del_inode_ref(struct btrfs_trans_handle *trans,
-			struct btrfs_root *root, const struct qstr *name,
+			struct btrfs_root *root, const struct fscrypt_str *name,
 			u64 inode_objectid, u64 ref_objectid, u64 *index)
 {
 	struct btrfs_path *path;
@@ -251,7 +251,7 @@ int btrfs_del_inode_ref(struct btrfs_trans_handle *trans,
  */
 static int btrfs_insert_inode_extref(struct btrfs_trans_handle *trans,
 				     struct btrfs_root *root,
-				     const struct qstr *name,
+				     const struct fscrypt_str *name,
 				     u64 inode_objectid, u64 ref_objectid,
 				     u64 index)
 {
@@ -306,7 +306,7 @@ static int btrfs_insert_inode_extref(struct btrfs_trans_handle *trans,
 
 /* Will return 0, -ENOMEM, -EMLINK, or -EEXIST or anything from the CoW path */
 int btrfs_insert_inode_ref(struct btrfs_trans_handle *trans,
-			   struct btrfs_root *root, const struct qstr *name,
+			   struct btrfs_root *root, const struct fscrypt_str *name,
 			   u64 inode_objectid, u64 ref_objectid, u64 index)
 {
 	struct btrfs_fs_info *fs_info = root->fs_info;
fs/btrfs/inode-item.h +5 -5
index 3c657c670cfd..b80aeb715701 100644
@@ -64,10 +64,10 @@ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
 			       struct btrfs_root *root,
 			       struct btrfs_truncate_control *control);
 int btrfs_insert_inode_ref(struct btrfs_trans_handle *trans,
-			   struct btrfs_root *root, const struct qstr *name,
+			   struct btrfs_root *root, const struct fscrypt_str *name,
 			   u64 inode_objectid, u64 ref_objectid, u64 index);
 int btrfs_del_inode_ref(struct btrfs_trans_handle *trans,
-			struct btrfs_root *root, const struct qstr *name,
+			struct btrfs_root *root, const struct fscrypt_str *name,
 			u64 inode_objectid, u64 ref_objectid, u64 *index);
 int btrfs_insert_empty_inode(struct btrfs_trans_handle *trans,
 			     struct btrfs_root *root,
@@ -80,15 +80,15 @@ struct btrfs_inode_extref *btrfs_lookup_inode_extref(
 			  struct btrfs_trans_handle *trans,
 			  struct btrfs_root *root,
 			  struct btrfs_path *path,
-			  const struct qstr *name,
+			  const struct fscrypt_str *name,
 			  u64 inode_objectid, u64 ref_objectid, int ins_len,
 			  int cow);
 
 struct btrfs_inode_ref *btrfs_find_name_in_backref(struct extent_buffer *leaf,
 						   int slot,
-						   const struct qstr *name);
+						   const struct fscrypt_str *name);
 struct btrfs_inode_extref *btrfs_find_name_in_ext_backref(
 		struct extent_buffer *leaf, int slot, u64 ref_objectid,
-		const struct qstr *name);
+		const struct fscrypt_str *name);
 
 #endif
fs/btrfs/inode.c +36 -53

340 lines not on this page · raw message

fs/btrfs/ioctl.c +2 -2
index 32dd1e654846..ea735904ee43 100644
@@ -951,7 +951,7 @@ static noinline int btrfs_mksubvol(const struct path *parent,
 	struct inode *dir = d_inode(parent->dentry);
 	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
 	struct dentry *dentry;
-	struct qstr name_str = QSTR_INIT(name, namelen);
+	struct fscrypt_str name_str = FSTR_INIT((char *)name, namelen);
 	int error;
 
 	error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
@@ -3776,7 +3776,7 @@ static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
 	struct btrfs_trans_handle *trans;
 	struct btrfs_path *path = NULL;
 	struct btrfs_disk_key disk_key;
-	struct qstr name = QSTR_INIT("default", 7);
+	struct fscrypt_str name = FSTR_INIT("default", 7);
 	u64 objectid = 0;
 	u64 dir_id;
 	int ret;
fs/btrfs/root-tree.c +2 -2
index 9f324b3e3990..8009724b8b2b 100644
@@ -332,7 +332,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 qstr *name)
+		       const struct fscrypt_str *name)
 {
 	struct btrfs_root *tree_root = trans->fs_info->tree_root;
 	struct btrfs_path *path;
@@ -404,7 +404,7 @@ int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
  */
 int btrfs_add_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 		       u64 ref_id, u64 dirid, u64 sequence,
-		       const struct qstr *name)
+		       const struct fscrypt_str *name)
 {
 	struct btrfs_root *tree_root = trans->fs_info->tree_root;
 	struct btrfs_key key;
fs/btrfs/send.c +2 -2
index 3c7a23d48bec..4de7e2157c2b 100644
@@ -1597,7 +1597,7 @@ static int gen_unique_name(struct send_ctx *sctx,
 		return -ENOMEM;
 
 	while (1) {
-		struct qstr tmp_name;
+		struct fscrypt_str tmp_name;
 		len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
 				ino, gen, idx);
 		ASSERT(len < sizeof(tmp));
@@ -1756,7 +1756,7 @@ static int lookup_dir_item_inode(struct btrfs_root *root,
 	struct btrfs_dir_item *di;
 	struct btrfs_key key;
 	struct btrfs_path *path;
-	struct qstr name_str = QSTR_INIT(name, name_len);
+	struct fscrypt_str name_str = FSTR_INIT((char *)name, name_len);
 
 	path = alloc_path_for_send();
 	if (!path)
fs/btrfs/super.c +1 -1
index 2e3a5ba2910e..863804751b06 100644
@@ -1423,7 +1423,7 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
 	struct btrfs_dir_item *di;
 	struct btrfs_path *path;
 	struct btrfs_key location;
-	struct qstr name = QSTR_INIT("default", 7);
+	struct fscrypt_str name = FSTR_INIT("default", 7);
 	u64 dir_id;
 
 	path = btrfs_alloc_path();
fs/btrfs/transaction.c +6 -7
index c2883d2b7111..00521669b8eb 100644
@@ -1625,7 +1625,6 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	u64 root_flags;
 	unsigned int mem_flags;
 	struct fscrypt_name fname;
-	struct qstr name;
 
 	ASSERT(pending->path);
 	path = pending->path;
@@ -1645,7 +1644,6 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	memalloc_nofs_restore(mem_flags);
 	if (pending->error)
 		goto free_pending;
-	name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
 
 	pending->error = btrfs_get_free_objectid(tree_root, &objectid);
 	if (pending->error)
@@ -1693,7 +1691,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	/* check if there is a file/dir which has the same name. */
 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
 					 btrfs_ino(BTRFS_I(parent_inode)),
-					 &name, 0);
+					 &fname.disk_name, 0);
 	if (dir_item != NULL && !IS_ERR(dir_item)) {
 		pending->error = -EEXIST;
 		goto dir_item_existed;
@@ -1788,7 +1786,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	ret = btrfs_add_root_ref(trans, objectid,
 				 parent_root->root_key.objectid,
 				 btrfs_ino(BTRFS_I(parent_inode)), index,
-				 &name);
+				 &fname.disk_name);
 	if (ret) {
 		btrfs_abort_transaction(trans, ret);
 		goto fail;
@@ -1820,8 +1818,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	if (ret < 0)
 		goto fail;
 
-	ret = btrfs_insert_dir_item(trans, &name, BTRFS_I(parent_inode), &key,
-				    BTRFS_FT_DIR, index);
+	ret = btrfs_insert_dir_item(trans, &fname.disk_name,
+				    BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
+				    index);
 	/* We have check then name at the beginning, so it is impossible. */
 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
 	if (ret) {
@@ -1830,7 +1829,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
 	}
 
 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
-						  name.len * 2);
+						  fname.disk_name.len * 2);
 	parent_inode->i_mtime = current_time(parent_inode);
 	parent_inode->i_ctime = parent_inode->i_mtime;
 	ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
fs/btrfs/tree-log.c +20 -22

174 lines not on this page · raw message

fs/btrfs/tree-log.h +2 -2
index 8c9a387151b0..85b43075ac58 100644
@@ -87,11 +87,11 @@ int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
 			  struct btrfs_log_ctx *ctx);
 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
 				  struct btrfs_root *root,
-				  const struct qstr *name,
+				  const struct fscrypt_str *name,
 				  struct btrfs_inode *dir, u64 index);
 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
 				struct btrfs_root *root,
-				const struct qstr *name,
+				const struct fscrypt_str *name,
 				struct btrfs_inode *inode, u64 dirid);
 void btrfs_end_log_trans(struct btrfs_root *root);
 void btrfs_pin_log_trans(struct btrfs_root *root);
Signature · 1 line
2.35.1
#15 lore raw

PATCH v4 11/21 btrfs: disable various operations on encrypted inodes

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

Initially, only normal data extents, using the normal (non-direct) IO path, will be encrypted. This change forbids various other bits:
- allows reflinking only if both inodes have the same encryption status
- disables compressing encrypted inodes
- disables direct IO on encrypted inodes
- disable inline data on encrypted inodes

---
 fs/btrfs/btrfs_inode.h | 3 +++
 fs/btrfs/file.c        | 4 ++--
 fs/btrfs/inode.c       | 3 ++-
 fs/btrfs/reflink.c     | 7 +++++++
 4 files changed, 14 insertions(+), 3 deletions(-)
fs/btrfs/btrfs_inode.h +3 -0
index 530a0ebfab3f..af23bd1fde36 100644
@@ -385,6 +385,9 @@ static inline bool btrfs_inode_in_log(struct btrfs_inode *inode, u64 generation)
  */
 static inline bool btrfs_inode_can_compress(const struct btrfs_inode *inode)
 {
+	if (IS_ENCRYPTED(&inode->vfs_inode))
+		return false;
+
 	if (inode->flags & BTRFS_INODE_NODATACOW ||
 	    inode->flags & BTRFS_INODE_NODATASUM)
 		return false;
fs/btrfs/file.c +2 -2
index a30ddd2697de..97d098b3c2e6 100644
@@ -1808,7 +1808,7 @@ static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
 		goto relock;
 	}
 
-	if (check_direct_IO(fs_info, from, pos)) {
+	if (IS_ENCRYPTED(inode) || check_direct_IO(fs_info, from, pos)) {
 		btrfs_inode_unlock(inode, ilock_flags);
 		goto buffered;
 	}
@@ -4045,7 +4045,7 @@ static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
 	ssize_t read = 0;
 	ssize_t ret;
 
-	if (fsverity_active(inode))
+	if (IS_ENCRYPTED(inode) || fsverity_active(inode))
 		return 0;
 
 	if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
fs/btrfs/inode.c +2 -1
index c41ae611767c..55a8fe278435 100644
@@ -432,7 +432,8 @@ static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
 	 * compressed) data fits in a leaf and the configured maximum inline
 	 * size.
 	 */
-	if (size < i_size_read(&inode->vfs_inode) ||
+	if (IS_ENCRYPTED(&inode->vfs_inode) ||
+	    size < i_size_read(&inode->vfs_inode) ||
 	    size > fs_info->sectorsize ||
 	    data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
 	    data_len > fs_info->max_inline)
fs/btrfs/reflink.c +7 -0
index f0243eb33df7..4143ebf22d7f 100644
@@ -808,6 +808,13 @@ static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in,
 		ASSERT(inode_in->i_sb == inode_out->i_sb);
 	}
 
+	/*
+	 * Can only reflink encrypted files if both files are encrypted.
+	 */
+	if (!fscrypt_have_same_policy(inode_in, inode_out)) {
+		return -EINVAL;
+	}
+
 	/* Don't make the dst file partly checksummed */
 	if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) !=
 	    (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) {
Signature · 1 line
2.35.1
#18 lore raw

PATCH v4 14/21 btrfs: translate btrfs encryption flags and encrypted inode flag

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

In btrfs, a file can be encrypted either if its directory is encrypted or its root subvolume is encrypted, so translate both to the standard flags.

---
 fs/btrfs/ioctl.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
fs/btrfs/ioctl.c +11 -2
index b28b7588f651..9cd59ab5a8a9 100644
@@ -7,6 +7,7 @@
 #include <linux/bio.h>
 #include <linux/file.h>
 #include <linux/fs.h>
+#include <linux/fscrypt.h>
 #include <linux/fsnotify.h>
 #include <linux/pagemap.h>
 #include <linux/highmem.h>
@@ -149,6 +150,10 @@ static unsigned int btrfs_inode_flags_to_fsflags(struct btrfs_inode *binode)
 		iflags |= FS_NOCOW_FL;
 	if (ro_flags & BTRFS_INODE_RO_VERITY)
 		iflags |= FS_VERITY_FL;
+	if ((binode->flags & BTRFS_INODE_FSCRYPT_CONTEXT) ||
+	    (btrfs_root_flags(&binode->root->root_item) &
+	     BTRFS_ROOT_SUBVOL_FSCRYPT))
+		iflags |= FS_ENCRYPT_FL;
 
 	if (flags & BTRFS_INODE_NOCOMPRESS)
 		iflags |= FS_NOCOMP_FL;
@@ -178,10 +183,14 @@ void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
 		new_fl |= S_DIRSYNC;
 	if (binode->ro_flags & BTRFS_INODE_RO_VERITY)
 		new_fl |= S_VERITY;
+	if ((binode->flags & BTRFS_INODE_FSCRYPT_CONTEXT) ||
+	    (btrfs_root_flags(&binode->root->root_item) &
+	     BTRFS_ROOT_SUBVOL_FSCRYPT))
+		new_fl |= S_ENCRYPTED;
 
 	set_mask_bits(&inode->i_flags,
 		      S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC |
-		      S_VERITY, new_fl);
+		      S_VERITY | S_ENCRYPTED, new_fl);
 }
 
 /*
@@ -194,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 */
Signature · 1 line
2.35.1
#19 lore raw

PATCH v4 15/21 btrfs: store a fscrypt extent context per normal file extent

In reply to Sweet Tea Dorminy

In order to encrypt data, each file extent must have its own persistent fscrypt_extent_context, which is then provided to fscrypt upon request. This is only needed for encrypted extents and is of variable size on disk, so file extents must additionally keep track of their actual length.

This puts the long-preserved 1-byte encryption field to work. Right now we don't anticipate very many encryption policies, so 2 bits should be ample; similarly right now we can't imagine a extent context larger than fscrypt's current inode contexts, which are 40 bytes, so 6 bits is ample to store the extent context's size; and therefore we can pack these together into the one-byte encryption field without touching other space reserved for future use.

---
 fs/btrfs/accessors.h            | 29 ++++++++++
 fs/btrfs/ctree.h                |  3 ++
 fs/btrfs/extent_map.c           |  7 +++
 fs/btrfs/extent_map.h           |  4 ++
 fs/btrfs/file-item.c            | 16 ++++++
 fs/btrfs/file.c                 |  4 +-
 fs/btrfs/fscrypt.c              | 22 ++++++++
 fs/btrfs/fscrypt.h              | 35 ++++++++++++
 fs/btrfs/inode.c                | 94 ++++++++++++++++++++++++++-------
 fs/btrfs/ordered-data.c         | 11 +++-
 fs/btrfs/ordered-data.h         |  4 +-
 fs/btrfs/reflink.c              |  1 +
 fs/btrfs/tree-checker.c         | 37 ++++++++++---
 fs/btrfs/tree-log.c             | 13 ++++-
 include/uapi/linux/btrfs_tree.h |  9 ++++
 15 files changed, 255 insertions(+), 34 deletions(-)
fs/btrfs/accessors.h +29 -0
index 157f5712c7ac..b35e57cf4c49 100644
@@ -963,6 +963,16 @@ 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);
+static inline u8 btrfs_stack_file_extent_encryption_ctxsize(
+	struct btrfs_file_extent_item *e)
+{
+	u8 ctxsize;
+
+	btrfs_unpack_encryption(e->encryption, NULL, &ctxsize);
+	return ctxsize;
+}
 
 static inline unsigned long
 btrfs_file_extent_inline_start(const struct btrfs_file_extent_item *e)
@@ -995,6 +1005,25 @@ BTRFS_SETGET_FUNCS(file_extent_encryption, struct btrfs_file_extent_item,
 BTRFS_SETGET_FUNCS(file_extent_other_encoding, struct btrfs_file_extent_item,
 		   other_encoding, 16);
 
+static inline u8
+btrfs_file_extent_encryption_ctxsize(const struct extent_buffer *eb,
+				     struct btrfs_file_extent_item *e)
+{
+	u8 ctxsize;
+
+	btrfs_unpack_encryption(btrfs_file_extent_encryption(eb, e),
+				NULL, &ctxsize);
+	return ctxsize;
+}
+
+static inline u8
+btrfs_file_extent_ctxsize_from_item(const struct extent_buffer *leaf,
+				    const struct btrfs_path *path)
+{
+	return (btrfs_item_size(leaf, path->slots[0]) -
+		sizeof(struct btrfs_file_extent_item));
+}
+
 /*
  * this returns the number of bytes used by the item on disk, minus the
  * size of any extent headers.  If a file is compressed on disk, this is
fs/btrfs/ctree.h +3 -0
index f4e6ff5da1f7..89de35779fd5 100644
@@ -37,6 +37,7 @@
 #include "block-rsv.h"
 #include "locking.h"
 #include "misc.h"
+#include "fscrypt.h"
 
 struct btrfs_trans_handle;
 struct btrfs_transaction;
@@ -1088,6 +1089,8 @@ struct btrfs_replace_extent_info {
 	u64 file_offset;
 	/* Pointer to a file extent item of type regular or prealloc. */
 	char *extent_buf;
+	/* The length of @extent_buf */
+	u32 extent_buf_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/extent_map.c +7 -0
index f97508afb659..2fdd1d4d3cb1 100644
@@ -216,6 +216,13 @@ static int mergable_maps(struct extent_map *prev, struct extent_map *next)
 	if (!list_empty(&prev->list) || !list_empty(&next->list))
 		return 0;
 
+	/*
+	 * Don't merge adjacent maps with different fscrypt_contexts.
+	 */
+	if (!memcmp(&prev->fscrypt_context, &next->fscrypt_context,
+		    sizeof(next->fscrypt_context)))
+		return 0;
+
 	ASSERT(next->block_start != EXTENT_MAP_DELALLOC &&
 	       prev->block_start != EXTENT_MAP_DELALLOC);
 
fs/btrfs/extent_map.h +4 -0
index 68d3f2c9ea1d..3fa70d6b4750 100644
@@ -5,6 +5,7 @@
 
 #include <linux/rbtree.h>
 #include <linux/refcount.h>
+#include "fscrypt.h"
 
 #define EXTENT_MAP_LAST_BYTE ((u64)-4)
 #define EXTENT_MAP_HOLE ((u64)-3)
@@ -27,6 +28,8 @@ enum {
 	EXTENT_FLAG_FS_MAPPING,
 	/* This em is merged from two or more physically adjacent ems */
 	EXTENT_FLAG_MERGED,
+	/* This em has a fscrypt extent context */
+	EXTENT_FLAG_ENCRYPTED,
 };
 
 struct extent_map {
@@ -50,6 +53,7 @@ struct extent_map {
 	 */
 	u64 generation;
 	unsigned long flags;
+	struct btrfs_fscrypt_extent_context fscrypt_context;
 	/* Used for chunk mappings, flag EXTENT_FLAG_FS_MAPPING must be set */
 	struct map_lookup *map_lookup;
 	refcount_t refs;
fs/btrfs/file-item.c +16 -0
index bce6c8d31bc0..a173097b5022 100644
@@ -1232,6 +1232,7 @@ void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
 	em->generation = btrfs_file_extent_generation(leaf, fi);
 	if (type == BTRFS_FILE_EXTENT_REG ||
 	    type == BTRFS_FILE_EXTENT_PREALLOC) {
+		u8 ctxsize;
 		em->start = extent_start;
 		em->len = extent_end - extent_start;
 		em->orig_start = extent_start -
@@ -1247,6 +1248,10 @@ void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
 			em->compress_type = compress_type;
 			em->block_start = bytenr;
 			em->block_len = em->orig_block_len;
+		} else if (btrfs_file_extent_encryption(leaf, fi)) {
+			set_bit(EXTENT_FLAG_ENCRYPTED, &em->flags);
+			em->block_start = bytenr;
+			em->block_len = em->orig_block_len;
 		} else {
 			bytenr += btrfs_file_extent_offset(leaf, fi);
 			em->block_start = bytenr;
@@ -1254,6 +1259,17 @@ void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
 			if (type == BTRFS_FILE_EXTENT_PREALLOC)
 				set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
 		}
+
+		ctxsize = btrfs_file_extent_ctxsize_from_item(leaf, path);
+		ASSERT(ctxsize == btrfs_file_extent_encryption_ctxsize(leaf, fi));
+
+#ifdef CONFIG_FS_ENCRYPTION
+		em->fscrypt_context.len = ctxsize;
+
+		read_extent_buffer(leaf, em->fscrypt_context.buffer,
+				   (unsigned long)fi->fscrypt_context,
+				   ctxsize);
+#endif /* CONFIG_FS_ENCRYPTION */
 	} else if (type == BTRFS_FILE_EXTENT_INLINE) {
 		em->block_start = EXTENT_MAP_INLINE;
 		em->start = extent_start;
fs/btrfs/file.c +2 -2
index 769a2a27941c..5beb08e3a9ad 100644
@@ -2554,14 +2554,14 @@ static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
 	key.type = BTRFS_EXTENT_DATA_KEY;
 	key.offset = extent_info->file_offset;
 	ret = btrfs_insert_empty_item(trans, root, path, &key,
-				      sizeof(struct btrfs_file_extent_item));
+				      extent_info->extent_buf_size);
 	if (ret)
 		return ret;
 	leaf = path->nodes[0];
 	slot = path->slots[0];
 	write_extent_buffer(leaf, extent_info->extent_buf,
 			    btrfs_item_ptr_offset(leaf, slot),
-			    sizeof(struct btrfs_file_extent_item));
+			    extent_info->extent_buf_size);
 	extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
 	ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
 	btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
fs/btrfs/fscrypt.c +22 -0
index 1d80043df17c..62c2108a2c07 100644
@@ -10,6 +10,7 @@
 #include "messages.h"
 #include "transaction.h"
 #include "xattr.h"
+#include "fscrypt.h"
 
 static int btrfs_fscrypt_get_context(struct inode *inode, void *ctx, size_t len)
 {
@@ -181,9 +182,30 @@ static bool btrfs_fscrypt_empty_dir(struct inode *inode)
 	return inode->i_size == BTRFS_EMPTY_DIR_SIZE;
 }
 
+static int btrfs_fscrypt_get_extent_context(const struct inode *inode,
+					    u64 lblk_num, void *ctx,
+					    size_t len,
+					    size_t *extent_offset,
+					    size_t *extent_length)
+{
+	return len;
+}
+
+static int btrfs_fscrypt_set_extent_context(void *extent, void *ctx,
+					    size_t len)
+{
+	struct btrfs_fscrypt_extent_context *extent_context = extent;
+
+	memcpy(extent_context->buffer, ctx, len);
+	extent_context->len = len;
+	return 0;
+}
+
 const struct fscrypt_operations btrfs_fscrypt_ops = {
 	.key_prefix = "btrfs:",
 	.get_context = btrfs_fscrypt_get_context,
 	.set_context = btrfs_fscrypt_set_context,
 	.empty_dir = btrfs_fscrypt_empty_dir,
+	.get_extent_context = btrfs_fscrypt_get_extent_context,
+	.set_extent_context = btrfs_fscrypt_set_extent_context,
 };
fs/btrfs/fscrypt.h +35 -0
index 7f4e6888bd43..86dc0e0b91b9 100644
@@ -5,6 +5,41 @@
 
 #include <linux/fscrypt.h>
 
+#define BTRFS_ENCRYPTION_POLICY_BITS 2
+#define BTRFS_ENCRYPTION_CTXSIZE_BITS 6
+
+#define BTRFS_ENCRYPTION_POLICY_MASK ((1 << BTRFS_ENCRYPTION_POLICY_BITS) - 1)
+#define BTRFS_ENCRYPTION_CTXSIZE_MASK \
+	(((1 << BTRFS_ENCRYPTION_CTXSIZE_BITS) - 1) << \
+		BTRFS_ENCRYPTION_POLICY_BITS)
+
+#ifdef CONFIG_FS_ENCRYPTION
+struct btrfs_fscrypt_extent_context {
+	u8 buffer[FSCRYPT_EXTENT_CONTEXT_MAX_SIZE];
+	u8 len;
+};
+#else
+struct btrfs_fscrypt_extent_context {
+	u8 len;
+};
+#endif
+
+static inline void btrfs_unpack_encryption(u8 encryption,
+					   u8 *policy,
+					   u8 *ctxsize)
+{
+	if (policy)
+		*policy = encryption & BTRFS_ENCRYPTION_POLICY_MASK;
+	if (ctxsize)
+		*ctxsize = ((encryption & BTRFS_ENCRYPTION_CTXSIZE_MASK) >>
+			    BTRFS_ENCRYPTION_POLICY_BITS);
+}
+
+static inline u8 btrfs_pack_encryption(u8 policy, u8 ctxsize)
+{
+	return policy | (ctxsize << BTRFS_ENCRYPTION_POLICY_BITS);
+}
+
 extern const struct fscrypt_operations btrfs_fscrypt_ops;
 
 #endif /* BTRFS_FSCRYPT_H */
fs/btrfs/inode.c +74 -20

242 lines not on this page · raw message

fs/btrfs/ordered-data.c +9 -2
index 1cbaacdc50da..ad37636c91bc 100644
@@ -165,7 +165,8 @@ static inline struct rb_node *tree_search(struct btrfs_ordered_inode_tree *tree,
 int btrfs_add_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 flags,
-			     int compress_type)
+			     int compress_type,
+			     struct btrfs_fscrypt_extent_context *fscrypt_context)
 {
 	struct btrfs_root *root = inode->root;
 	struct btrfs_fs_info *fs_info = root->fs_info;
@@ -200,6 +201,11 @@ int btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offset,
 	entry->disk_bytenr = disk_bytenr;
 	entry->disk_num_bytes = disk_num_bytes;
 	entry->offset = offset;
+#ifdef CONFIG_FS_ENCRYPTION
+	if (fscrypt_context && fscrypt_context->len)
+		memcpy(&entry->fscrypt_context, fscrypt_context,
+		       sizeof(*fscrypt_context));
+#endif /* CONFIG_FS_ENCRYPTION */
 	entry->bytes_left = num_bytes;
 	entry->inode = igrab(&inode->vfs_inode);
 	entry->compress_type = compress_type;
@@ -1107,7 +1113,8 @@ static int clone_ordered_extent(struct btrfs_ordered_extent *ordered, u64 pos,
 	WARN_ON_ONCE(flags & (1 << BTRFS_ORDERED_COMPRESSED));
 	return btrfs_add_ordered_extent(BTRFS_I(inode), file_offset, len, len,
 					disk_bytenr, len, 0, flags,
-					ordered->compress_type);
+					ordered->compress_type,
+					&ordered->fscrypt_context);
 }
 
 int btrfs_split_ordered_extent(struct btrfs_ordered_extent *ordered, u64 pre,
fs/btrfs/ordered-data.h +3 -1
index 89f82b78f590..a25c63dea8e0 100644
@@ -99,6 +99,7 @@ struct btrfs_ordered_extent {
 	u64 disk_bytenr;
 	u64 disk_num_bytes;
 	u64 offset;
+	struct btrfs_fscrypt_extent_context fscrypt_context;
 
 	/* number of bytes that still need writing */
 	u64 bytes_left;
@@ -182,7 +183,8 @@ bool btrfs_dec_test_ordered_pending(struct btrfs_inode *inode,
 int btrfs_add_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 flags,
-			     int compress_type);
+			     int compress_type,
+			     struct btrfs_fscrypt_extent_context *fscrypt_context);
 void btrfs_add_ordered_sum(struct btrfs_ordered_extent *entry,
 			   struct btrfs_ordered_sum *sum);
 struct btrfs_ordered_extent *btrfs_lookup_ordered_extent(struct btrfs_inode *inode,
fs/btrfs/reflink.c +1 -0
index 4143ebf22d7f..a58bcb56a023 100644
@@ -498,6 +498,7 @@ static int btrfs_clone(struct inode *src, struct inode *inode,
 			clone_info.data_len = datal;
 			clone_info.file_offset = new_key.offset;
 			clone_info.extent_buf = buf;
+			clone_info.extent_buf_size = size;
 			clone_info.is_new_extent = false;
 			clone_info.update_times = !no_time_update;
 			ret = btrfs_replace_file_extents(BTRFS_I(inode), path,
fs/btrfs/tree-checker.c +29 -8
index 77e678efef65..e72c8176f7bc 100644
@@ -207,6 +207,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,
@@ -258,10 +259,12 @@ 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))) {
+	btrfs_unpack_encryption(btrfs_file_extent_encryption(leaf, fi),
+				&policy, NULL);
+	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) {
@@ -290,12 +293,30 @@ static int check_extent_data_item(struct extent_buffer *leaf,
 		return 0;
 	}
 
-	/* Regular or preallocated extent has fixed item size */
-	if (unlikely(item_size != sizeof(*fi))) {
-		file_extent_err(leaf, slot,
+	if (policy == BTRFS_ENCRYPTION_FSCRYPT) {
+		u8 ctxsize = btrfs_file_extent_encryption_ctxsize(leaf, fi);
+
+		if (unlikely(item_size != sizeof(*fi) + ctxsize)) {
+			file_extent_err(leaf, slot,
+	"invalid item size for encrypted file extent, have %u expect = %zu + context of size %u",
+					item_size, sizeof(*fi), ctxsize);
+			return -EUCLEAN;
+		}
+		/* Only regular extents should be encrypted. */
+		if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG) {
+			file_extent_err(leaf, slot,
+		"invalid type for encrypted file extent, have %u expect %u",
+					btrfs_file_extent_type(leaf, fi),
+					BTRFS_FILE_EXTENT_REG);
+			return -EUCLEAN;
+		}
+	} else {
+		if (unlikely(item_size != sizeof(*fi))) {
+			file_extent_err(leaf, slot,
 	"invalid item size for reg/prealloc file extent, have %u expect %zu",
-			item_size, sizeof(*fi));
-		return -EUCLEAN;
+					item_size, sizeof(*fi));
+			return -EUCLEAN;
+		}
 	}
 	if (unlikely(CHECK_FE_ALIGNED(leaf, slot, fi, ram_bytes, sectorsize) ||
 		     CHECK_FE_ALIGNED(leaf, slot, fi, disk_bytenr, sectorsize) ||
fs/btrfs/tree-log.c +12 -1
index f261f8589033..02f9966a66e7 100644
@@ -4604,6 +4604,9 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	u64 extent_offset = em->start - em->orig_start;
 	u64 block_len;
 	int ret;
+	u8 encryption = btrfs_pack_encryption(IS_ENCRYPTED(&inode->vfs_inode) ?
+					      BTRFS_ENCRYPTION_FSCRYPT : 0,
+					      em->fscrypt_context.len);
 
 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
 	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
@@ -4625,6 +4628,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, em->compress_type);
+	btrfs_set_stack_file_extent_encryption(&fi, encryption);
 
 	ret = log_extent_csums(trans, inode, log, em, ctx);
 	if (ret)
@@ -4656,7 +4660,8 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 		key.offset = em->start;
 
 		ret = btrfs_insert_empty_item(trans, log, path, &key,
-					      sizeof(fi));
+					      sizeof(fi) +
+					      em->fscrypt_context.len);
 		if (ret)
 			return ret;
 	}
@@ -4664,6 +4669,12 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
 	write_extent_buffer(leaf, &fi,
 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
 			    sizeof(fi));
+#ifdef CONFIG_FS_ENCRYPTION
+	write_extent_buffer(leaf, &em->fscrypt_context.buffer,
+			    btrfs_item_ptr_offset(leaf, path->slots[0]) +
+			    sizeof(fi), em->fscrypt_context.len);
+#endif /* CONFIG_FS_ENCRYPTION */
+
 	btrfs_mark_buffer_dirty(leaf);
 
 	btrfs_release_path(path);
include/uapi/linux/btrfs_tree.h +9 -0
index fe112f55a1d2..f2424374748f 100644
@@ -1047,6 +1047,10 @@ struct btrfs_file_extent_item {
 	 * but not for stat.
 	 */
 	__u8 compression;
+	/*
+	 * This field contains 2 bits of encryption type in the lower bits,
+	 * 6 bits of context size in the upper bits. The unencrypted value is 0.
+	 */
 	__u8 encryption;
 	__le16 other_encoding; /* spare for later use */
 
@@ -1075,6 +1079,11 @@ struct btrfs_file_extent_item {
 	 */
 	__le64 num_bytes;
 
+	/*
+	 * Fscrypt extent encryption context. Only present if extent is
+	 * encrypted (stored in the encryption field).
+	 */
+	__u8 fscrypt_context[0];
 } __attribute__ ((__packed__));
 
 struct btrfs_csum_item {
Signature · 1 line
2.35.1
#23 lore raw

PATCH v4 16/21 btrfs: encrypt normal file extent data if appropriate

In reply to Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

Add in the necessary calls to encrypt and decrypt data to achieve encryption of normal data.

Since these are all page cache pages being encrypted, we can't encrypt them in place and must encrypt/decrypt into a new page. fscrypt provides a pool of pages for this purpose, which it calls bounce pages. For IO of encrypted data, we use a bounce page for the actual IO, and encrypt/decrypt from/to the actual page cache page on either side of the IO.

---
 fs/btrfs/extent_io.c    | 56 ++++++++++++++++++++++++++++++++++++-----
 fs/btrfs/file-item.c    |  9 +++++--
 fs/btrfs/fscrypt.c      | 33 +++++++++++++++++++++++-
 fs/btrfs/tree-checker.c | 11 +++++---
 4 files changed, 97 insertions(+), 12 deletions(-)
fs/btrfs/extent_io.c +50 -6
index 4b47bb8c590f..329936df0cb0 100644
@@ -115,6 +115,7 @@ static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
 {
 	struct bio *bio;
 	struct bio_vec *bv;
+	struct page *first_page;
 	struct inode *inode;
 	int mirror_num;
 
@@ -123,13 +124,17 @@ static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
 
 	bio = bio_ctrl->bio;
 	bv = bio_first_bvec_all(bio);
-	inode = bv->bv_page->mapping->host;
+	first_page = bio_first_page_all(bio);
+	if (fscrypt_is_bounce_page(first_page))
+		inode = fscrypt_pagecache_page(first_page)->mapping->host;
+	else
+		inode = first_page->mapping->host;
 	mirror_num = bio_ctrl->mirror_num;
 
 	/* Caller should ensure the bio has at least some range added */
 	ASSERT(bio->bi_iter.bi_size);
 
-	btrfs_bio(bio)->file_offset = page_offset(bv->bv_page) + bv->bv_offset;
+	btrfs_bio(bio)->file_offset = page_offset(first_page) + bv->bv_offset;
 
 	if (!is_data_inode(inode))
 		btrfs_submit_metadata_bio(inode, bio, mirror_num);
@@ -1016,9 +1021,19 @@ static void end_bio_extent_writepage(struct btrfs_bio *bbio)
 	ASSERT(!bio_flagged(bio, BIO_CLONED));
 	bio_for_each_segment_all(bvec, bio, iter_all) {
 		struct page *page = bvec->bv_page;
-		struct inode *inode = page->mapping->host;
-		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
-		const u32 sectorsize = fs_info->sectorsize;
+		struct inode *inode;
+		struct btrfs_fs_info *fs_info;
+		u32 sectorsize;
+		struct page *bounce_page = NULL;
+
+		if (fscrypt_is_bounce_page(page)) {
+			bounce_page = page;
+			page = fscrypt_pagecache_page(bounce_page);
+		}
+
+		inode = page->mapping->host;
+		fs_info = btrfs_sb(inode->i_sb);
+		sectorsize = fs_info->sectorsize;
 
 		/* Our read/write should always be sector aligned. */
 		if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
@@ -1039,7 +1054,7 @@ static void end_bio_extent_writepage(struct btrfs_bio *bbio)
 		}
 
 		end_extent_writepage(page, error, start, end);
-
+		fscrypt_free_bounce_page(bounce_page);
 		btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
 	}
 
@@ -1231,6 +1246,17 @@ static void end_bio_extent_readpage(struct btrfs_bio *bbio)
 			}
 		}
 
+		if (likely(uptodate)) {
+			if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
+				int ret = fscrypt_decrypt_pagecache_blocks(page,
+									   bvec->bv_len,
+									   bvec->bv_offset);
+				if (ret) {
+					error_bitmap = (unsigned int) -1;
+					uptodate = false;
+				}
+			}
+		}
 		if (likely(uptodate)) {
 			loff_t i_size = i_size_read(inode);
 			pgoff_t end_index = i_size >> PAGE_SHIFT;
@@ -1565,11 +1591,29 @@ static int submit_extent_page(blk_opf_t opf,
 			      bool force_bio_submit)
 {
 	int ret = 0;
+	struct page *bounce_page = NULL;
 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
 	unsigned int cur = pg_offset;
 
 	ASSERT(bio_ctrl);
 
+	if ((opf & REQ_OP_MASK) == REQ_OP_WRITE &&
+	    fscrypt_inode_uses_fs_layer_crypto(&inode->vfs_inode)) {
+		gfp_t gfp_flags = GFP_NOFS;
+
+		if (bio_ctrl->bio)
+			gfp_flags = GFP_NOWAIT | __GFP_NOWARN;
+		else
+			gfp_flags = GFP_NOFS;
+		bounce_page = fscrypt_encrypt_pagecache_blocks(page, size,
+							       pg_offset,
+							       gfp_flags);
+		if (IS_ERR(bounce_page))
+			return PTR_ERR(bounce_page);
+		page = bounce_page;
+		pg_offset = 0;
+	}
+
 	ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
 	       pg_offset + size <= PAGE_SIZE);
 
fs/btrfs/file-item.c +7 -2
index a173097b5022..ee4168417714 100644
@@ -679,8 +679,13 @@ blk_status_t btrfs_csum_one_bio(struct btrfs_inode *inode, struct bio *bio,
 	shash->tfm = fs_info->csum_shash;
 
 	bio_for_each_segment(bvec, bio, iter) {
-		if (use_page_offsets)
-			offset = page_offset(bvec.bv_page) + bvec.bv_offset;
+		if (use_page_offsets) {
+			struct page *page = bvec.bv_page;
+
+			if (fscrypt_is_bounce_page(page))
+				page = fscrypt_pagecache_page(page);
+			offset = page_offset(page) + bvec.bv_offset;
+		}
 
 		if (!ordered) {
 			ordered = btrfs_lookup_ordered_extent(inode, offset);
fs/btrfs/fscrypt.c +32 -1
index 62c2108a2c07..68c250eb4338 100644
@@ -188,7 +188,38 @@ static int btrfs_fscrypt_get_extent_context(const struct inode *inode,
 					    size_t *extent_offset,
 					    size_t *extent_length)
 {
-	return len;
+	u64 offset = lblk_num << inode->i_blkbits;
+	struct extent_map *em;
+	int ret;
+
+	/* Since IO must be in progress on this extent, this must succeed */
+	em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, offset, PAGE_SIZE);
+	if (!em)
+		return -EINVAL;
+
+	if (em->block_start == EXTENT_MAP_HOLE) {
+		btrfs_info(BTRFS_I(inode)->root->fs_info,
+			   "extent context requested for block %llu of inode %lu without an extent",
+			   lblk_num, inode->i_ino);
+		free_extent_map(em);
+		return -ENOENT;
+	}
+
+	ret = ctx ? em->fscrypt_context.len : 0;
+
+	if (ctx)
+		memcpy(ctx, em->fscrypt_context.buffer,
+		       em->fscrypt_context.len);
+
+	if (extent_offset)
+		*extent_offset
+			 = (offset - em->start) >> inode->i_blkbits;
+
+	if (extent_length)
+		*extent_length = em->len >> inode->i_blkbits;
+
+	free_extent_map(em);
+	return ret;
 }
 
 static int btrfs_fscrypt_set_extent_context(void *extent, void *ctx,
fs/btrfs/tree-checker.c +8 -3
index e72c8176f7bc..84bdd6ca3d2b 100644
@@ -276,9 +276,14 @@ static int check_extent_data_item(struct extent_buffer *leaf,
 			return -EUCLEAN;
 		}
 
-		/* Compressed inline extent has no on-disk size, skip it */
-		if (btrfs_file_extent_compression(leaf, fi) !=
-		    BTRFS_COMPRESS_NONE)
+		/*
+		 * Compressed inline extent has no on-disk size; encrypted has
+		 * variable size; skip them
+		 */
+		if ((btrfs_file_extent_compression(leaf, fi) !=
+		     BTRFS_COMPRESS_NONE) ||
+		    (btrfs_file_extent_encryption(leaf, fi) !=
+		     BTRFS_ENCRYPTION_NONE))
 			return 0;
 
 		/* Uncompressed inline extent size must match item size */
Signature · 1 line
2.35.1
#26 lore raw

PATCH v4 19/21 btrfs: permit searching for nokey names for removal

In reply to Sweet Tea Dorminy

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.

While it's tempting to try to factor the two callsites of fscrypt_fname_disk_to_usr() together, I can't see a useful way to factor their surrounding logic together.

---
 fs/btrfs/ctree.h         |  19 +++++-
 fs/btrfs/delayed-inode.c |  30 ++++++++-
 fs/btrfs/delayed-inode.h |   4 +-
 fs/btrfs/dir-item.c      | 113 ++++++++++++++++++++++++++++---
 fs/btrfs/extent_io.c     |  38 +++++++++++
 fs/btrfs/extent_io.h     |   3 +
 fs/btrfs/fscrypt.c       |  45 +++++++++++++
 fs/btrfs/fscrypt.h       |  18 +++++
 fs/btrfs/inode.c         | 142 ++++++++++++++++++++++++++-------------
 fs/btrfs/root-tree.c     |   8 ++-
 fs/btrfs/tree-log.c      |   3 +-
 11 files changed, 357 insertions(+), 66 deletions(-)
fs/btrfs/ctree.h +16 -3
index 89de35779fd5..adb33e3b5dfb 100644
@@ -1525,7 +1525,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,
@@ -1563,14 +1563,24 @@ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans,
 					     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,
 			    struct btrfs_path *path, u64 dir,
 			    u64 index, const struct fscrypt_str *name, int mod);
 struct btrfs_dir_item *
+btrfs_lookup_dir_index_item_fname(struct btrfs_trans_handle *trans,
+				  struct btrfs_root *root,
+				  struct btrfs_path *path, u64 dir,
+				  u64 index, struct fscrypt_name *name);
+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,
@@ -1585,6 +1595,9 @@ struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans,
 					  struct btrfs_path *path, u64 dir,
 					  const char *name, u16 name_len,
 					  int mod);
+struct btrfs_dir_item *btrfs_match_dir_item_fname(struct btrfs_fs_info *fs_info,
+						 struct btrfs_path *path,
+						 struct fscrypt_name *name);
 struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_fs_info *fs_info,
 						 struct btrfs_path *path,
 						 const char *name,
@@ -1651,7 +1664,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, int add_backref, u64 index);
fs/btrfs/delayed-inode.c +27 -3
index a935709f2a29..490d20a50378 100644
@@ -1497,6 +1497,7 @@ int btrfs_insert_delayed_dir_index(struct btrfs_trans_handle *trans,
 
 	ret = __btrfs_add_delayed_item(delayed_node, delayed_item);
 	if (unlikely(ret)) {
+		// TODO: It would be nice to print the base64encoded name here maybe?
 		btrfs_err(trans->fs_info,
 			  "err add delayed dir index item(name: %.*s) into the insertion tree of the delayed node(root id: %llu, inode id: %llu, errno: %d)",
 			  name_len, name, delayed_node->root->root_key.objectid,
@@ -1724,7 +1725,9 @@ int btrfs_should_delete_dir_index(struct list_head *del_list,
  * btrfs_readdir_delayed_dir_index - read dir info stored in the delayed tree
  *
  */
-int btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
+int btrfs_readdir_delayed_dir_index(struct inode *inode,
+				    struct fscrypt_str *fstr,
+				    struct dir_context *ctx,
 				    struct list_head *ins_list)
 {
 	struct btrfs_dir_item *di;
@@ -1734,6 +1737,7 @@ int btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
 	int name_len;
 	int over = 0;
 	unsigned char d_type;
+	size_t fstr_len = fstr->len;
 
 	if (list_empty(ins_list))
 		return 0;
@@ -1761,8 +1765,28 @@ int 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 ret;
+			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 +3 -1
index 4f21daa3dbc7..a4f9fa27b126 100644
@@ -155,7 +155,9 @@ void btrfs_readdir_put_delayed_items(struct inode *inode,
 				     struct list_head *del_list);
 int btrfs_should_delete_dir_index(struct list_head *del_list,
 				  u64 index);
-int btrfs_readdir_delayed_dir_index(struct dir_context *ctx,
+int btrfs_readdir_delayed_dir_index(struct inode *inode,
+				    struct fscrypt_str *fstr,
+				    struct dir_context *ctx,
 				    struct list_head *ins_list);
 
 /* Used during directory logging. */
fs/btrfs/dir-item.c +104 -9

161 lines not on this page · raw message

fs/btrfs/extent_io.c +38 -0
index 329936df0cb0..2c1dd67b9489 100644
@@ -5330,6 +5330,44 @@ static void assert_eb_page_uptodate(const struct extent_buffer *eb,
 	}
 }
 
+/* Take a sha256 of a portion of an extent buffer. */
+void extent_buffer_sha256(const struct extent_buffer *eb,
+			  unsigned long start,
+			  unsigned long len, u8 *out)
+{
+	size_t cur;
+	size_t offset;
+	struct page *page;
+	char *kaddr;
+	unsigned long i = get_eb_page_index(start);
+	struct sha256_state sctx;
+
+	if (check_eb_range(eb, start, len))
+		return;
+
+	offset = get_eb_offset_in_page(eb, start);
+
+	/*
+	 * 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.
+	 */
+	sha256_init(&sctx);
+	while (len > 0) {
+		page = eb->pages[i];
+		assert_eb_page_uptodate(eb, page);
+
+		cur = min(len, PAGE_SIZE - offset);
+		kaddr = page_address(page);
+		sha256_update(&sctx, (u8 *)(kaddr + offset), cur);
+
+		len -= cur;
+		offset = 0;
+		i++;
+	}
+	sha256_final(&sctx, out);
+}
+
 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
 		const void *srcv)
 {
fs/btrfs/extent_io.h +3 -0
index a5ec1475988f..0a82604b0feb 100644
@@ -203,6 +203,9 @@ static inline int 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 +45 -0

51 lines not on this page · raw message

fs/btrfs/fscrypt.h +18 -0
index 86dc0e0b91b9..4dd536611cd5 100644
@@ -24,6 +24,24 @@ struct btrfs_fscrypt_extent_context {
 };
 #endif
 
+#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 */
+
 static inline void btrfs_unpack_encryption(u8 encryption,
 					   u8 *policy,
 					   u8 *ctxsize)
fs/btrfs/inode.c +96 -46

343 lines not on this page · raw message

fs/btrfs/root-tree.c +5 -3
index 8009724b8b2b..3f1c199a6140 100644
@@ -10,6 +10,7 @@
 #include "messages.h"
 #include "transaction.h"
 #include "disk-io.h"
+#include "fscrypt.h"
 #include "print-tree.h"
 #include "qgroup.h"
 #include "space-info.h"
@@ -332,7 +333,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;
 	struct btrfs_path *path;
@@ -354,13 +355,14 @@ int btrfs_del_root_ref(struct btrfs_trans_handle *trans, u64 root_id,
 	if (ret < 0) {
 		goto out;
 	} 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)) {
 			ret = -ENOENT;
 			goto out;
 		}
fs/btrfs/tree-log.c +2 -1
index 02f9966a66e7..1a5e8196e2b0 100644
@@ -918,9 +918,10 @@ static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
 				       struct btrfs_inode *inode,
 				       const struct fscrypt_str *name)
 {
+	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)
 		return ret;
 	/*
Signature · 1 line
2.35.1
#29 lore raw
In reply to Sweet Tea Dorminy
Quoted 7 lines · Sweet Tea Dorminy

Omar Sandoval (11):
btrfs: store directory encryption state

Sweet Tea Dorminy (10):
btrfs: use struct qstr instead of name and namelen
btrfs: setup qstrings from dentrys using fscrypt helper
btrfs: use struct fscrypt_str instead of struct qstr

FYI, the patches listed above have been addded to misc-next as they're preparatory (no fscrypt related code there except using fscrypt_name). There are some fixups so you may encounter minor conflicts when rebasing.

#11 lore raw

Re: [PATCH v4 08/21] btrfs: setup qstrings from dentrys using fscrypt helper

In reply to Sweet Tea Dorminy
Quoted 212 lines · Sweet Tea Dorminy

Most places where we get a struct qstr, we are doing so from a dentry. With fscrypt, the dentry's name may be encrypted on-disk, so fscrypt provides a helper to convert a dentry name to the appropriate disk name if necessary. Convert each of the dentry name accesses to use fscrypt_setup_filename(), then convert the resulting fscrypt_name back to an unencrypted qstr. This does not work for nokey names, but the specific locations that could spawn nokey names are noted.

At present, since there are no encrypted directories, nothing goes down the filename encryption paths.

---
 fs/btrfs/ctree.h       |   3 +
 fs/btrfs/inode.c       | 187 ++++++++++++++++++++++++++++++++---------
 fs/btrfs/transaction.c |  40 ++++++---
 fs/btrfs/tree-log.c    |  11 ++-
 4 files changed, 186 insertions(+), 55 deletions(-)
fs/btrfs/ctree.h +3 -0
index d80ebd5b1a83..6653972d7c01 100644
@@ -28,6 +28,7 @@
 #include <linux/refcount.h>
 #include <linux/crc32c.h>
 #include <linux/iomap.h>
+#include <linux/fscrypt.h>
 #include "extent-io-tree.h"
 #include "extent_io.h"
 #include "extent_map.h"
@@ -1674,6 +1675,8 @@ struct btrfs_new_inode_args {
         */
        struct posix_acl *default_acl;
        struct posix_acl *acl;
+       struct fscrypt_name fname;
+       struct qstr name;
 };
 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
                            unsigned int *trans_num_items);
fs/btrfs/inode.c +50 -13
index 32beee9d9d85..5607d05c309b 100644
@@ -4428,16 +4428,27 @@ static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
        struct btrfs_trans_handle *trans;
        struct inode *inode = d_inode(dentry);
        int ret;
+       struct fscrypt_name fname;
+       struct qstr name;
+
+       ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
+       if (ret)
+               return ret;
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
+       /* This needs to handle no-key deletions later on */
 
        trans = __unlink_start_trans(dir);
-       if (IS_ERR(trans))
-               return PTR_ERR(trans);
+       if (IS_ERR(trans)) {
+               ret = PTR_ERR(trans);
+               goto out;
+       }
 
        btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
                        0);
 
        ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
-                                &dentry->d_name);
+                                &name);
        if (ret)
                goto out;
 
@@ -4448,6 +4459,7 @@ static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
        }
 
 out:
+       fscrypt_free_filename(&fname);
        btrfs_end_transaction(trans);
        btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
        return ret;
@@ -4462,11 +4474,19 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
        struct extent_buffer *leaf;
        struct btrfs_dir_item *di;
        struct btrfs_key key;
-       const struct qstr *name = &dentry->d_name;
+       struct qstr name;
        u64 index;
        int ret;
        u64 objectid;
        u64 dir_ino = btrfs_ino(BTRFS_I(dir));
+       struct fscrypt_name fname;
+
+       ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
+       if (ret)
+               return ret;
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
+       /* This needs to handle no-key deletions later on */
 
        if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
                objectid = inode->root->root_key.objectid;
@@ -4474,15 +4494,18 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
                objectid = inode->location.objectid;
        } else {
                WARN_ON(1);
+               fscrypt_free_filename(&fname);
                return -EINVAL;
        }
 
        path = btrfs_alloc_path();
-       if (!path)
-               return -ENOMEM;
+       if (!path) {
+               ret = -ENOMEM;
+               goto out;
+       }
 
        di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
-                                  name, -1);
+                                  &name, -1);
        if (IS_ERR_OR_NULL(di)) {
                ret = di ? PTR_ERR(di) : -ENOENT;
                goto out;
@@ -4508,7 +4531,7 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
         * call btrfs_del_root_ref, and it _shouldn't_ fail.
         */
        if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
-               di = btrfs_search_dir_index_item(root, path, dir_ino, name);
+               di = btrfs_search_dir_index_item(root, path, dir_ino, &name);
                if (IS_ERR_OR_NULL(di)) {
                        if (!di)
                                ret = -ENOENT;
@@ -4525,7 +4548,7 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
        } else {
                ret = btrfs_del_root_ref(trans, objectid,
                                         root->root_key.objectid, dir_ino,
-                                        &index, name);
+                                        &index, &name);
                if (ret) {
                        btrfs_abort_transaction(trans, ret);
                        goto out;
@@ -4538,7 +4561,7 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
                goto out;
        }
 
-       btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name->len * 2);
+       btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name.len * 2);
        inode_inc_iversion(dir);
        dir->i_mtime = current_time(dir);
        dir->i_ctime = dir->i_mtime;
@@ -4547,6 +4570,7 @@ static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
                btrfs_abort_transaction(trans, ret);
 out:
        btrfs_free_path(path);
+       fscrypt_free_filename(&fname);
        return ret;
 }
 
@@ -4810,6 +4834,8 @@ static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
        int err = 0;
        struct btrfs_trans_handle *trans;
        u64 last_unlink_trans;
+       struct fscrypt_name fname;
+       struct qstr name;
 
        if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
                return -ENOTEMPTY;
@@ -4822,9 +4848,18 @@ static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
                return btrfs_delete_subvolume(dir, dentry);
        }
 
+       err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
+       if (err)
+               return err;
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
+       /* This needs to handle no-key deletions later on */
+
        trans = __unlink_start_trans(dir);
-       if (IS_ERR(trans))
-               return PTR_ERR(trans);
+       if (IS_ERR(trans)) {
+               err = PTR_ERR(trans);
+               goto out_notrans;
+       }
 
        if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
                err = btrfs_unlink_subvol(trans, dir, dentry);
@@ -4839,7 +4874,7 @@ static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
 
        /* now the directory is empty */
        err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
-                                &dentry->d_name);
+                                &name);
        if (!err) {
                btrfs_i_size_write(BTRFS_I(inode), 0);
                /*
@@ -4858,7 +4893,9 @@ static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
        }
 out:
        btrfs_end_transaction(trans);
+out_notrans:
        btrfs_btree_balance_dirty(fs_info);
+       fscrypt_free_filename(&fname);
 
        return err;
 }

fs/btrfs/inode.c void btrfs_evict_inode(struct inode *inode) · line 5563

Quoted 5 lines
fs/btrfs/inode.c +1 -1
@@ -5523,7 +5560,7 @@ void btrfs_evict_inode(struct inode *inode)
 
 /*
  * Return the key found in the dir entry in the location pointer, fill @type
- * with BTRFS_FT_*, and return 0.
+ * with BTRFS_FT_*, and return 0. Used only for lookups, not removals.

This is a bit confusing. What removals?
Isn't it clear the function is used only for lookups?

Quoted 378 lines
fs/btrfs/inode.c +94 -28
  *
  * If no dir entries were found, returns -ENOENT.
  * If found a corrupted location in dir entry, returns -EUCLEAN.
@@ -5531,18 +5568,27 @@ void btrfs_evict_inode(struct inode *inode)
 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
                               struct btrfs_key *location, u8 *type)
 {
-       const struct qstr *name = &dentry->d_name;
+       struct qstr name;
        struct btrfs_dir_item *di;
        struct btrfs_path *path;
        struct btrfs_root *root = BTRFS_I(dir)->root;
        int ret = 0;
+       struct fscrypt_name fname;
 
        path = btrfs_alloc_path();
        if (!path)
                return -ENOMEM;
 
+       ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
+       if (ret)
+               goto out;
+
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
+       /* This needs to handle no-key deletions later on */
+
        di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
-                                  name, 0);
+                                  &name, 0);
        if (IS_ERR_OR_NULL(di)) {
                ret = di ? PTR_ERR(di) : -ENOENT;
                goto out;
@@ -5554,12 +5600,13 @@ static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
                ret = -EUCLEAN;
                btrfs_warn(root->fs_info,
 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
-                          __func__, name->name, btrfs_ino(BTRFS_I(dir)),
+                          __func__, name.name, btrfs_ino(BTRFS_I(dir)),
                           location->objectid, location->type, location->offset);
        }
        if (!ret)
                *type = btrfs_dir_type(path->nodes[0], di);
 out:
+       fscrypt_free_filename(&fname);
        btrfs_free_path(path);
        return ret;
 }
@@ -5582,6 +5629,14 @@ static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
        struct btrfs_key key;
        int ret;
        int err = 0;
+       struct fscrypt_name fname;
+       struct qstr name;
+
+       ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
+       if (ret)
+               return ret;
+
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
 
        path = btrfs_alloc_path();
        if (!path) {
@@ -5604,12 +5659,11 @@ static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
        leaf = path->nodes[0];
        ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
        if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
-           btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
+           btrfs_root_ref_name_len(leaf, ref) != name.len)
                goto out;
 
-       ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
-                                  (unsigned long)(ref + 1),
-                                  dentry->d_name.len);
+       ret = memcmp_extent_buffer(leaf, name.name, (unsigned long)(ref + 1),
+                                  name.len);
        if (ret)
                goto out;
 
@@ -5628,6 +5682,7 @@ static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
        err = 0;
 out:
        btrfs_free_path(path);
+       fscrypt_free_filename(&fname);
        return err;
 }
 
@@ -6236,9 +6291,19 @@ int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
        struct inode *inode = args->inode;
        int ret;
 
+       if (!args->orphan) {
+               ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
+                                            &args->fname);
+               if (ret)
+                       return ret;
+               args->name = (struct qstr)FSTR_TO_QSTR(&args->fname.disk_name);
+       }
+
        ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
-       if (ret)
+       if (ret) {
+               fscrypt_free_filename(&args->fname);
                return ret;
+       }
 
        /* 1 to add inode item */
        *trans_num_items = 1;
@@ -6278,6 +6343,7 @@ void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
 {
        posix_acl_release(args->acl);
        posix_acl_release(args->default_acl);
+       fscrypt_free_filename(&args->fname);
 }
 
 /*
@@ -6703,6 +6769,8 @@ static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
        struct btrfs_root *root = BTRFS_I(dir)->root;
        struct inode *inode = d_inode(old_dentry);
        struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
+       struct fscrypt_name fname;
+       struct qstr name;
        u64 index;
        int err;
        int drop_inode = 0;
@@ -6714,6 +6782,12 @@ static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
        if (inode->i_nlink >= BTRFS_LINK_MAX)
                return -EMLINK;
 
+       err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
+       if (err)
+               goto fail;
+
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
        err = btrfs_set_inode_index(BTRFS_I(dir), &index);
        if (err)
                goto fail;
@@ -6740,7 +6814,7 @@ static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
        set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
 
        err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
-                            &dentry->d_name, 1, index);
+                            &name, 1, index);
 
        if (err) {
                drop_inode = 1;
@@ -6764,6 +6838,7 @@ static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
        }
 
 fail:
+       fscrypt_free_filename(&fname);
        if (trans)
                btrfs_end_transaction(trans);
        if (drop_inode) {
@@ -8995,6 +9070,8 @@ static int btrfs_rename_exchange(struct inode *old_dir,
        int ret;
        int ret2;
        bool need_abort = false;
+       struct fscrypt_name old_fname, new_fname;
+       struct qstr old_name, new_name;
 
        /*
         * For non-subvolumes allow exchange only within one subvolume, in the
@@ -9006,6 +9083,19 @@ static int btrfs_rename_exchange(struct inode *old_dir,
             new_ino != BTRFS_FIRST_FREE_OBJECTID))
                return -EXDEV;
 
+       ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
+       if (ret)
+               return ret;
+
+       ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
+       if (ret) {
+               fscrypt_free_filename(&old_fname);
+               return ret;
+       }
+
+       old_name = (struct qstr)FSTR_TO_QSTR(&old_fname.disk_name);
+       new_name = (struct qstr)FSTR_TO_QSTR(&new_fname.disk_name);
+
        /* close the race window with snapshot create/destroy ioctl */
        if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
            new_ino == BTRFS_FIRST_FREE_OBJECTID)
@@ -9073,8 +9163,7 @@ static int btrfs_rename_exchange(struct inode *old_dir,
                /* force full log commit if subvolume involved. */
                btrfs_set_log_full_commit(trans);
        } else {
-               ret = btrfs_insert_inode_ref(trans, dest, &new_dentry->d_name,
-                                            old_ino,
+               ret = btrfs_insert_inode_ref(trans, dest, &new_name, old_ino,
                                             btrfs_ino(BTRFS_I(new_dir)),
                                             old_idx);
                if (ret)
@@ -9087,8 +9176,7 @@ static int btrfs_rename_exchange(struct inode *old_dir,
                /* force full log commit if subvolume involved. */
                btrfs_set_log_full_commit(trans);
        } else {
-               ret = btrfs_insert_inode_ref(trans, root, &old_dentry->d_name,
-                                            new_ino,
+               ret = btrfs_insert_inode_ref(trans, root, &old_name, new_ino,
                                             btrfs_ino(BTRFS_I(old_dir)),
                                             new_idx);
                if (ret) {
@@ -9123,8 +9211,7 @@ static int btrfs_rename_exchange(struct inode *old_dir,
        } else { /* src is an inode */
                ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
                                           BTRFS_I(old_dentry->d_inode),
-                                          &old_dentry->d_name,
-                                          &old_rename_ctx);
+                                          &old_name, &old_rename_ctx);
                if (!ret)
                        ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
        }
@@ -9139,8 +9226,7 @@ static int btrfs_rename_exchange(struct inode *old_dir,
        } else { /* dest is an inode */
                ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
                                           BTRFS_I(new_dentry->d_inode),
-                                          &new_dentry->d_name,
-                                          &new_rename_ctx);
+                                          &new_name, &new_rename_ctx);
                if (!ret)
                        ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
        }
@@ -9150,14 +9236,14 @@ static int btrfs_rename_exchange(struct inode *old_dir,
        }
 
        ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
-                            &new_dentry->d_name, 0, old_idx);
+                            &new_name, 0, old_idx);
        if (ret) {
                btrfs_abort_transaction(trans, ret);
                goto out_fail;
        }
 
        ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
-                            &old_dentry->d_name, 0, new_idx);
+                            &old_name, 0, new_idx);
        if (ret) {
                btrfs_abort_transaction(trans, ret);
                goto out_fail;
@@ -9200,6 +9286,8 @@ static int btrfs_rename_exchange(struct inode *old_dir,
            old_ino == BTRFS_FIRST_FREE_OBJECTID)
                up_read(&fs_info->subvol_sem);
 
+       fscrypt_free_filename(&new_fname);
+       fscrypt_free_filename(&old_fname);
        return ret;
 }
 
@@ -9239,6 +9327,8 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
        int ret;
        int ret2;
        u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
+       struct fscrypt_name old_fname, new_fname;
+       struct qstr old_name, new_name;
 
        if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
                return -EPERM;
@@ -9255,21 +9345,32 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
            new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
                return -ENOTEMPTY;
 
+       ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
+       if (ret)
+               return ret;
+
+       ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
+       if (ret) {
+               fscrypt_free_filename(&old_fname);
+               return ret;
+       }
+
+       old_name = (struct qstr)FSTR_TO_QSTR(&old_fname.disk_name);
+       new_name = (struct qstr)FSTR_TO_QSTR(&new_fname.disk_name);
 
        /* check for collisions, even if the  name isn't there */
-       ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
-                                            &new_dentry->d_name);
+       ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_name);
 
        if (ret) {
                if (ret == -EEXIST) {
                        /* we shouldn't get
                         * eexist without a new_inode */
                        if (WARN_ON(!new_inode)) {
-                               return ret;
+                               goto out_fscrypt_names;
                        }
                } else {
                        /* maybe -EOVERFLOW */
-                       return ret;
+                       goto out_fscrypt_names;
                }
        }
        ret = 0;
@@ -9352,8 +9453,7 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
                /* force full log commit if subvolume involved. */
                btrfs_set_log_full_commit(trans);
        } else {
-               ret = btrfs_insert_inode_ref(trans, dest, &new_dentry->d_name,
-                                            old_ino,
+               ret = btrfs_insert_inode_ref(trans, dest, &new_name, old_ino,
                                             btrfs_ino(BTRFS_I(new_dir)), index);
                if (ret)
                        goto out_fail;
@@ -9377,7 +9477,7 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
        } else {
                ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
                                           BTRFS_I(d_inode(old_dentry)),
-                                          &old_dentry->d_name, &rename_ctx);
+                                          &old_name, &rename_ctx);
                if (!ret)
                        ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
        }
@@ -9396,7 +9496,7 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
                } else {
                        ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
                                                 BTRFS_I(d_inode(new_dentry)),
-                                                &new_dentry->d_name);
+                                                &new_name);
                }
                if (!ret && new_inode->i_nlink == 0)
                        ret = btrfs_orphan_add(trans,
@@ -9408,7 +9508,7 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
        }
 
        ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
-                            &new_dentry->d_name, 0, index);
+                            &new_name, 0, index);
        if (ret) {
                btrfs_abort_transaction(trans, ret);
                goto out_fail;
@@ -9443,6 +9543,9 @@ static int btrfs_rename(struct user_namespace *mnt_userns,
 out_whiteout_inode:
        if (flags & RENAME_WHITEOUT)
                iput(whiteout_args.inode);
+out_fscrypt_names:
+       fscrypt_free_filename(&old_fname);
+       fscrypt_free_filename(&new_fname);
        return ret;
 }
 
fs/btrfs/transaction.c +5 -2
index 7db9612f4d0e..c2883d2b7111 100644
@@ -6,6 +6,7 @@
 #include <linux/fs.h>
 #include <linux/slab.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/writeback.h>
 #include <linux/pagemap.h>
 #include <linux/blkdev.h>
@@ -1611,10 +1612,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        struct btrfs_root *root = pending->root;
        struct btrfs_root *parent_root;
        struct btrfs_block_rsv *rsv;
-       struct inode *parent_inode;
+       struct inode *parent_inode = pending->dir;
        struct btrfs_path *path;
        struct btrfs_dir_item *dir_item;
-       struct dentry *dentry;
        struct extent_buffer *tmp;
        struct extent_buffer *old;
        struct timespec64 cur_time;
@@ -1623,6 +1623,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        u64 index = 0;
        u64 objectid;
        u64 root_flags;
+       unsigned int mem_flags;
+       struct fscrypt_name fname;
+       struct qstr name;
 
        ASSERT(pending->path);
        path = pending->path;

fs/btrfs/transaction.c static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans, · line 1640

Quoted 8 lines
fs/btrfs/transaction.c +5 -0
@@ -1630,9 +1633,23 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        ASSERT(pending->root_item);
        new_root_item = pending->root_item;
 
+       /*
+        * Since this is during btrfs_commit_transaction() and more items
+        * joining the transaction at this point would be bad, use NOFS
+        * allocations so that no new writes are kicked off.
+        */

This comment makes no sense to me.

The reason we have to use NOFS it's because when a memory allocation triggers reclaim it may recurse into the filesystem and trigger transaction start/join/attach, which would result in a deadlock (see below why exactly).

The "more items joining the transaction at this point would be bad" makes no sense because it's simply not possible.
At this point the transaction is in the state TRANS_STATE_COMMIT_DOING, so no one can join it and use it for further modifying the fs - anyone trying to start a new transaction, join or attach this one will block until the transaction state becomes >= TRANS_STATE_UNBLOCKED and after that it will have to start a new transaction (can't reuse the former).

Thanks.

Quoted 124 lines
fs/btrfs/transaction.c +18 -10
+       mem_flags = memalloc_nofs_save();
+       pending->error = fscrypt_setup_filename(parent_inode,
+                                               &pending->dentry->d_name, 0,
+                                               &fname);
+       memalloc_nofs_restore(mem_flags);
+       if (pending->error)
+               goto free_pending;
+       name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
+
        pending->error = btrfs_get_free_objectid(tree_root, &objectid);
        if (pending->error)
-               goto no_free_objectid;
+               goto free_fname;
 
        /*
         * Make qgroup to skip current new snapshot's qgroupid, as it is
@@ -1661,8 +1678,6 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        trace_btrfs_space_reservation(fs_info, "transaction",
                                      trans->transid,
                                      trans->bytes_reserved, 1);
-       dentry = pending->dentry;
-       parent_inode = pending->dir;
        parent_root = BTRFS_I(parent_inode)->root;
        ret = record_root_in_trans(trans, parent_root, 0);
        if (ret)
@@ -1678,7 +1693,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        /* check if there is a file/dir which has the same name. */
        dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
                                         btrfs_ino(BTRFS_I(parent_inode)),
-                                        &dentry->d_name, 0);
+                                        &name, 0);
        if (dir_item != NULL && !IS_ERR(dir_item)) {
                pending->error = -EEXIST;
                goto dir_item_existed;
@@ -1773,7 +1788,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        ret = btrfs_add_root_ref(trans, objectid,
                                 parent_root->root_key.objectid,
                                 btrfs_ino(BTRFS_I(parent_inode)), index,
-                                &dentry->d_name);
+                                &name);
        if (ret) {
                btrfs_abort_transaction(trans, ret);
                goto fail;
@@ -1805,9 +1820,8 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        if (ret < 0)
                goto fail;
 
-       ret = btrfs_insert_dir_item(trans, &dentry->d_name,
-                                   BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
-                                   index);
+       ret = btrfs_insert_dir_item(trans, &name, BTRFS_I(parent_inode), &key,
+                                   BTRFS_FT_DIR, index);
        /* We have check then name at the beginning, so it is impossible. */
        BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
        if (ret) {
@@ -1816,7 +1830,7 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        }
 
        btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
-                                        dentry->d_name.len * 2);
+                                                 name.len * 2);
        parent_inode->i_mtime = current_time(parent_inode);
        parent_inode->i_ctime = parent_inode->i_mtime;
        ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
@@ -1848,7 +1862,9 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        trans->bytes_reserved = 0;
 clear_skip_qgroup:
        btrfs_clear_skip_qgroup(trans);
-no_free_objectid:
+free_fname:
+       fscrypt_free_filename(&fname);
+free_pending:
        kfree(new_root_item);
        pending->root_item = NULL;
        btrfs_free_path(path);
fs/btrfs/tree-log.c +10 -2
index d6c0bce7569a..f9ed05285a97 100644
@@ -7395,9 +7395,16 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
        if (old_dir && old_dir->logged_trans == trans->transid) {
                struct btrfs_root *log = old_dir->root->log_root;
                struct btrfs_path *path;
+               struct fscrypt_name fname;
+               struct qstr name;
 
                ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
 
+               ret = fscrypt_setup_filename(&old_dir->vfs_inode,
+                                            &old_dentry->d_name, 0, &fname);
+               if (ret)
+                       goto out;
+               name = (struct qstr)FSTR_TO_QSTR(&fname.disk_name);
                /*
                 * We have two inodes to update in the log, the old directory and
                 * the inode that got renamed, so we must pin the log to prevent
@@ -7417,6 +7424,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
                path = btrfs_alloc_path();
                if (!path) {
                        ret = -ENOMEM;
+                       fscrypt_free_filename(&fname);
                        goto out;
                }
 
@@ -7432,7 +7440,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
                 */
                mutex_lock(&old_dir->log_mutex);
                ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
-                                       &old_dentry->d_name, old_dir_index);
+                                       &name, old_dir_index);
                if (ret > 0) {
                        /*
                         * The dentry does not exist in the log, so record its
@@ -7446,6 +7454,7 @@ void btrfs_log_new_name(struct btrfs_trans_handle *trans,
                mutex_unlock(&old_dir->log_mutex);
 
                btrfs_free_path(path);
+               fscrypt_free_filename(&fname);
                if (ret < 0)
                        goto out;
        }
--

2.35.1

#20 lore raw

Re: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent

In reply to Sweet Tea Dorminy
Thank you for the patch! Yet something to improve:

Hi Sweet,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on cc159678aee59042e24fd1b039405b4fdf7b0538]

url:    https://github.com/intel-lab-lkp/linux/commits/Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
base:   cc159678aee59042e24fd1b039405b4fdf7b0538
patch link:    https://lore.kernel.org/r/014e0e48e9c00aedf7f3473948e569008c87541d.1666651724.git.sweettea-kernel%40dorminy.me
patch subject: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent
config: i386-randconfig-a001-20221024 (attached as .config)
compiler: clang version 14.0.6 (https://github.com/llvm/llvm-project f28c006a5895fc0e329fe15fead81e37457cb1d1)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/624387a6ab9097f87c31b9d9bc2df1b1111f4684
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435 git checkout 624387a6ab9097f87c31b9d9bc2df1b1111f4684
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=i386 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All errors (new ones prefixed by >>):

>> ld.lld: error: undefined symbol: __udivdi3
   >>> referenced by inode.c:7546 (fs/btrfs/inode.c:7546)
   >>>               fs/btrfs/inode.o:(cow_file_range) in archive vmlinux.a
   >>> referenced by inode.c:7546 (fs/btrfs/inode.c:7546)
   >>>               fs/btrfs/inode.o:(create_io_em) in archive vmlinux.a
   >>> referenced by inode.c:7546 (fs/btrfs/inode.c:7546)
   >>>               fs/btrfs/inode.o:(btrfs_get_blocks_direct_write) in archive vmlinux.a

pahole: .tmp_vmlinux.btf: No such file or directory ld.lld: error: .btf.vmlinux.bin.o: unknown file type

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#21 lore raw

Re: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent

In reply to Sweet Tea Dorminy
Thank you for the patch! Yet something to improve:

Hi Sweet,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on cc159678aee59042e24fd1b039405b4fdf7b0538]

url:    https://github.com/intel-lab-lkp/linux/commits/Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
base:   cc159678aee59042e24fd1b039405b4fdf7b0538
patch link:    https://lore.kernel.org/r/014e0e48e9c00aedf7f3473948e569008c87541d.1666651724.git.sweettea-kernel%40dorminy.me
patch subject: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent
config: m68k-randconfig-r001-20221023 (attached as .config)
compiler: m68k-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/624387a6ab9097f87c31b9d9bc2df1b1111f4684
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435 git checkout 624387a6ab9097f87c31b9d9bc2df1b1111f4684
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=m68k SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All errors (new ones prefixed by >>):

m68k-linux-ld: m68k-linux-ld: DWARF error: could not find abbrev number 2779421099 fs/btrfs/inode.o: in function `create_io_em':

>> inode.c:(.text+0x26a): undefined reference to `__udivdi3'

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for VIDEO_MEDIATEK_VPU
Depends on [n]: MEDIA_SUPPORT [=y] && MEDIA_PLATFORM_SUPPORT [=y] && MEDIA_PLATFORM_DRIVERS [=y] && V4L_MEM2MEM_DRIVERS [=n] && VIDEO_DEV [=y] && (ARCH_MEDIATEK || COMPILE_TEST [=y])
Selected by [y]:
- VIDEO_MEDIATEK_MDP3 [=y] && MEDIA_SUPPORT [=y] && MEDIA_PLATFORM_SUPPORT [=y] && MEDIA_PLATFORM_DRIVERS [=y] && (MTK_IOMMU [=n] || COMPILE_TEST [=y]) && VIDEO_DEV [=y] && (ARCH_MEDIATEK || COMPILE_TEST [=y]) && HAS_DMA [=y] && REMOTEPROC [=y]

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#22 lore raw

Re: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent

In reply to Sweet Tea Dorminy
Thank you for the patch! Yet something to improve:

Hi Sweet,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on cc159678aee59042e24fd1b039405b4fdf7b0538]

url:    https://github.com/intel-lab-lkp/linux/commits/Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
base:   cc159678aee59042e24fd1b039405b4fdf7b0538
patch link:    https://lore.kernel.org/r/014e0e48e9c00aedf7f3473948e569008c87541d.1666651724.git.sweettea-kernel%40dorminy.me
patch subject: [PATCH v4 15/21] btrfs: store a fscrypt extent context per normal file extent
config: i386-randconfig-c021 (attached as .config)
compiler: gcc-11 (Debian 11.3.0-8) 11.3.0
reproduce (this is a W=1 build):
        # https://github.com/intel-lab-lkp/linux/commit/624387a6ab9097f87c31b9d9bc2df1b1111f4684
        git remote add linux-review https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
        git checkout 624387a6ab9097f87c31b9d9bc2df1b1111f4684
        # save the config file
        mkdir build_dir && cp config build_dir/.config
        make W=1 O=build_dir ARCH=i386 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All errors (new ones prefixed by >>):

ld: fs/btrfs/inode.o: in function `create_io_em':

>> fs/btrfs/inode.c:7545: undefined reference to `__udivdi3'

pahole: .tmp_vmlinux.btf: No such file or directory .btf.vmlinux.bin.o: file not recognized: file format not recognized

vim +7545 fs/btrfs/inode.c

7507
7508 /* The callers of this must take lock_extent() */
7509 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,

  7510					       u64 len, u64 orig_start, u64 block_start,
  7511					       u64 block_len, u64 orig_block_len,
  7512					       u64 ram_bytes, int compress_type,
  7513					       int type)
  7514	{
  7515		struct extent_map *em;
  7516		struct btrfs_fs_info *fs_info = inode->root->fs_info;
  7517		int ret;
  7518	
  7519		ASSERT(type == BTRFS_ORDERED_PREALLOC ||
  7520		       type == BTRFS_ORDERED_COMPRESSED ||
  7521		       type == BTRFS_ORDERED_NOCOW ||
  7522		       type == BTRFS_ORDERED_REGULAR);
  7523	
  7524		em = alloc_extent_map();
  7525		if (!em)
  7526			return ERR_PTR(-ENOMEM);
  7527	
  7528		em->start = start;
  7529		em->orig_start = orig_start;
  7530		em->len = len;
  7531		em->block_len = block_len;
  7532		em->block_start = block_start;
  7533		em->orig_block_len = orig_block_len;
  7534		em->ram_bytes = ram_bytes;
  7535		em->generation = -1;
  7536		set_bit(EXTENT_FLAG_PINNED, &em->flags);
  7537		if (type == BTRFS_ORDERED_PREALLOC) {
  7538			set_bit(EXTENT_FLAG_FILLING, &em->flags);
  7539		} else if (type == BTRFS_ORDERED_COMPRESSED) {
  7540			set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  7541			em->compress_type = compress_type;
  7542		}
  7543	
  7544		if (IS_ENCRYPTED(&inode->vfs_inode)) {
> 7545			ret = fscrypt_set_extent_context(&inode->vfs_inode,

7546 em->start / fs_info->sectorsize,
7547 &em->fscrypt_context);
7548 if (ret < 0) {
7549 free_extent_map(em);
7550 return ERR_PTR(ret);
7551 }
7552 }
7553
7554 ret = btrfs_replace_extent_map_range(inode, em, true);
7555 if (ret) {
7556 free_extent_map(em);
7557 return ERR_PTR(ret);
7558 }
7559
7560 /* em got 2 refs now, callers needs to do free_extent_map once. */
7561 return em;
7562 }
7563

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#8 lore raw

Re: [PATCH v4 06/21] fscrypt: document btrfs' fscrypt quirks.

In reply to Sweet Tea Dorminy
Thank you for the patch! Perhaps something to improve:

Hi Sweet,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on cc159678aee59042e24fd1b039405b4fdf7b0538]

url:    https://github.com/intel-lab-lkp/linux/commits/Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
base:   cc159678aee59042e24fd1b039405b4fdf7b0538
patch link:    https://lore.kernel.org/r/686fce255e979bd8805e194c7288b80f2ceddbe0.1666651724.git.sweettea-kernel%40dorminy.me
patch subject: [PATCH v4 06/21] fscrypt: document btrfs' fscrypt quirks.
reproduce:
        # https://github.com/intel-lab-lkp/linux/commit/3d980bfe498cfe3250cb3df16d0c26f688af916a
        git remote add linux-review https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review Sweet-Tea-Dorminy/btrfs-add-fscrypt-integration/20221025-084435
        git checkout 3d980bfe498cfe3250cb3df16d0c26f688af916a
        make menuconfig
        # enable CONFIG_COMPILE_TEST, CONFIG_WARN_MISSING_DOCUMENTS, CONFIG_WARN_ABI_ERRORS
        make htmldocs

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> Documentation/filesystems/fscrypt.rst:383: WARNING: Title underline too short.

vim +383 Documentation/filesystems/fscrypt.rst

381
382 Inode-based contents encryption

 > 383	------------------------------

384

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#3 lore raw

Re: [PATCH v4 02/21] fscrypt: add fscrypt_have_same_policy() to check inode compatibility

In reply to Sweet Tea Dorminy
Quoted 37 lines · Sweet Tea Dorminy

From: Omar Sandoval <[email protected]>

Btrfs will need to check whether inode policies are identical for various purposes: if two inodes want to share an extent, they must have the same policy, including key identifier; symlinks must not span the encrypted/unencrypted border; and certain encryption policies will allow btrfs to store one fscrypt_context for multiple objects. Therefore, add a function which allows checking the encryption policies of two inodes to ensure they are identical.

---
 fs/crypto/policy.c      | 26 ++++++++++++++++++++++++++
 include/linux/fscrypt.h |  7 +++++++
 2 files changed, 33 insertions(+)
fs/crypto/policy.c +12 -0
index 46757c3052ef..b7c4820a8001 100644
@@ -415,6 +415,32 @@ static int fscrypt_get_policy(struct inode *inode, union fscrypt_policy *policy)
 	return fscrypt_policy_from_context(policy, &ctx, ret);
 }
 
+/**
+ * fscrypt_have_same_policy() - check whether two inodes have the same policy
+ * @inode1: the first inode
+ * @inode2: the second inode
+ *
+ * Return: %true if they are definitely equal, else %false
+ */
+int fscrypt_have_same_policy(struct inode *inode1, struct inode *inode2)
+{
+	union fscrypt_policy policy1, policy2;
+	int err;
+

fs/crypto/policy.c static int fscrypt_get_policy(struct inode *inode, union fscrypt_policy *policy) · line 439

Quoted 10 lines
fs/crypto/policy.c +10 -0
+	if (!IS_ENCRYPTED(inode1) && !IS_ENCRYPTED(inode2))
+		return true;
+	else if (!IS_ENCRYPTED(inode1) || !IS_ENCRYPTED(inode2))
+		return false;
+	err = fscrypt_get_policy(inode1, &policy1);
+	if (err)
+		return false;
+	err = fscrypt_get_policy(inode2, &policy2);
+	if (err)
+		return false;

Should we bubble up the errors here instead of squashing them down to false? (I noticed this because Josef had another comment about returning int vs bool in this function.)

Quoted 3 lines
fs/crypto/policy.c +3 -0
+	return fscrypt_policies_equal(&policy1, &policy2);
+}
+EXPORT_SYMBOL(fscrypt_have_same_policy);
#12 lore raw

Re: [PATCH v4 08/21] btrfs: setup qstrings from dentrys using fscrypt helper

In reply to Filipe Manana
Quoted 11 lines · Filipe Manana

fs/btrfs/inode.c void btrfs_evict_inode(struct inode *inode) · line 5563

Quoted 6 lines · Sweet Tea Dorminy
fs/btrfs/inode.c +1 -1
@@ -5523,7 +5560,7 @@ void btrfs_evict_inode(struct inode *inode)
 
 /*
  * Return the key found in the dir entry in the location pointer, fill @type
- * with BTRFS_FT_*, and return 0.
+ * with BTRFS_FT_*, and return 0. Used only for lookups, not removals.

This is a bit confusing. What removals?
Isn't it clear the function is used only for lookups?

Agreed, update removed.

Quoted 23 lines
Quoted 7 lines
fs/btrfs/inode.c +0 -0
  *
  * If no dir entries were found, returns -ENOENT.
  * If found a corrupted location in dir entry, returns -EUCLEAN.
@@ -5531,18 +5568,27 @@ void btrfs_evict_inode(struct inode *inode)
 

fs/btrfs/inode.c static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans, · line 1640

Quoted 8 lines
fs/btrfs/inode.c +5 -0
@@ -1630,9 +1633,23 @@ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
        ASSERT(pending->root_item);
        new_root_item = pending->root_item;
 
+       /*
+        * Since this is during btrfs_commit_transaction() and more items
+        * joining the transaction at this point would be bad, use NOFS
+        * allocations so that no new writes are kicked off.
+        */

This comment makes no sense to me.

The reason we have to use NOFS it's because when a memory allocation triggers reclaim it may recurse into the filesystem and trigger transaction start/join/attach, which would result in a deadlock (see below why exactly).

Quoted 8 lines

The "more items joining the transaction at this point would be bad" makes no sense because it's simply not possible.
At this point the transaction is in the state TRANS_STATE_COMMIT_DOING, so no one can join it and use it for further modifying the fs - anyone trying to start a new transaction, join or attach this one will block until the transaction state becomes >= TRANS_STATE_UNBLOCKED and after that it will have to start a new transaction (can't reuse the former).

I've updated the commit so it says why whe need the NOFS protection similar to what we have elsewhere. There's one GFP_KERNEL allocation in fscrypt_setup_filename so the protection is needed.