diff mbox series

[12/16] tmpfs: refuse memlock when fallocated beyond i_size

Message ID 3e5b2999-a27d-3590-46d9-80841b9427a9@google.com (mailing list archive)
State New
Headers show
Series tmpfs: HUGEPAGE and MEM_LOCK fcntls and memfds | expand

Commit Message

Hugh Dickins July 30, 2021, 8 a.m. UTC
F_MEM_LOCK is accounted by i_size, but fallocate(,FALLOC_FL_KEEP_SIZE,,)
could have added many pages beyond i_size, which would also be held as
Unevictable from memory. The mlock_ucounts check in shmem_fallocate() is
fine, but shmem_memlock_fcntl() needs to check fallocend too. We could
change F_MEM_LOCK accounting to use the max of i_size and fallocend, but
fallocend is obscure: I think it's better just to refuse the F_MEM_LOCK
(with EPERM) if fallocend exceeds (page-rounded) i_size.

Signed-off-by: Hugh Dickins <hughd@google.com>
---
 mm/shmem.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
diff mbox series

Patch

diff --git a/mm/shmem.c b/mm/shmem.c
index 6e53dabe658b..35c0f5c7120e 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -2304,7 +2304,10 @@  static int shmem_memlock_fcntl(struct file *file, unsigned int cmd)
 
 	inode_lock(inode);
 	if (cmd == F_MEM_LOCK) {
-		if (!info->mlock_ucounts) {
+		if (info->fallocend > DIV_ROUND_UP(inode->i_size, PAGE_SIZE)) {
+			/* locking is accounted by i_size: disallow excess */
+			retval = -EPERM;
+		} else if (!info->mlock_ucounts) {
 			struct ucounts *ucounts = current_ucounts();
 			/* capability/rlimit check is down in user_shm_lock */
 			retval = shmem_lock(file, 1, ucounts);
@@ -2854,9 +2857,10 @@  static long shmem_fallocate(struct file *file, int mode, loff_t offset,
 	spin_unlock(&inode->i_lock);
 
 	/*
-	 * info->fallocend is only relevant when huge pages might be
+	 * info->fallocend is mostly relevant when huge pages might be
 	 * involved: to prevent split_huge_page() freeing fallocated
 	 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
+	 * But it is also checked in F_MEM_LOCK validation.
 	 */
 	undo_fallocend = info->fallocend;
 	if (info->fallocend < end)