git: b2e3ab898cd2 - stable/12 - msdosfs deextend: validate pages of the partial buffer

From: Ed Maste <emaste_at_FreeBSD.org>
Date: Mon, 11 Sep 2023 18:50:27 UTC
The branch stable/12 has been updated by emaste:

URL: https://cgit.FreeBSD.org/src/commit/?id=b2e3ab898cd2a8517858f32cc7397cf026013548

commit b2e3ab898cd2a8517858f32cc7397cf026013548
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2023-02-11 18:09:30 +0000
Commit:     Ed Maste <emaste@FreeBSD.org>
CommitDate: 2023-09-11 18:04:59 +0000

    msdosfs deextend: validate pages of the partial buffer
    
    PR:     269341
    
    (cherry picked from commit 0152d453a08fa2bad694dc04a8184fce2b7faa10)
    (cherry picked from commit c2ee668306bbe3edf4a05246ed3a88f52dfc94ae)
---
 sys/fs/msdosfs/msdosfs_denode.c | 36 +++++++++++++++++++++++++++++++-----
 1 file changed, 31 insertions(+), 5 deletions(-)

diff --git a/sys/fs/msdosfs/msdosfs_denode.c b/sys/fs/msdosfs/msdosfs_denode.c
index b251c2797467..57d1c96a561b 100644
--- a/sys/fs/msdosfs/msdosfs_denode.c
+++ b/sys/fs/msdosfs/msdosfs_denode.c
@@ -476,6 +476,7 @@ deextend(struct denode *dep, u_long length, struct ucred *cred)
 {
 	struct msdosfsmount *pmp = dep->de_pmp;
 	struct vnode *vp = DETOV(dep);
+	struct buf *bp;
 	u_long count;
 	int error;
 
@@ -502,16 +503,41 @@ deextend(struct denode *dep, u_long length, struct ucred *cred)
 		if (count > pmp->pm_freeclustercount)
 			return (ENOSPC);
 		error = extendfile(dep, count, NULL, NULL, DE_CLEAR);
-		if (error) {
-			/* truncate the added clusters away again */
-			(void) detrunc(dep, dep->de_FileSize, 0, cred);
-			return (error);
-		}
+		if (error != 0)
+			goto rewind;
 	}
+
+	/*
+	 * For the case of cluster size larger than the page size, we
+	 * need to ensure that the possibly dirty partial buffer at
+	 * the old end of file is not filled with invalid pages by
+	 * extension.  Otherwise it has a contradictory state of
+	 * B_CACHE | B_DELWRI but with invalid pages, and cannot be
+	 * neither written out nor validated.
+	 *
+	 * Fix it by proactively clearing extended pages.
+	 */
+	error = bread(vp, de_cluster(pmp, dep->de_FileSize), pmp->pm_bpcluster,
+	    NOCRED, &bp);
+	if (error != 0)
+		goto rewind;
+	vfs_bio_clrbuf(bp);
+	if (!DOINGASYNC(vp))
+		(void)bwrite(bp);
+	else if (vm_page_count_severe() || buf_dirty_count_severe())
+		bawrite(bp);
+	else
+		bdwrite(bp);
+
 	vnode_pager_setsize(vp, length);
 	dep->de_FileSize = length;
 	dep->de_flag |= DE_UPDATE | DE_MODIFIED;
 	return (deupdat(dep, !DOINGASYNC(vp)));
+
+rewind:
+	/* truncate the added clusters away again */
+	(void)detrunc(dep, dep->de_FileSize, 0, cred);
+	return (error);
 }
 
 /*