git: 7e4ebe43721f - releng/14.0 - linuxkpi: fix iteration in __sg_alloc_table_from_pages

From: Bjoern A. Zeeb <bz_at_FreeBSD.org>
Date: Tue, 10 Oct 2023 14:34:21 UTC
The branch releng/14.0 has been updated by bz:

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

commit 7e4ebe43721f24b78d9bd736988798bb46c54f71
Author:     Austin Shafer <ashafer@badland.io>
AuthorDate: 2023-09-06 14:08:05 +0000
Commit:     Bjoern A. Zeeb <bz@FreeBSD.org>
CommitDate: 2023-10-10 14:33:54 +0000

    linuxkpi: fix iteration in __sg_alloc_table_from_pages
    
    Commit 3f686532c9b4 tried to fix an issue with not properly starting
    at the first page in the sg list to prevent a panic. This worked but
    with the side effect of incrementing "s" during the final iteration
    causing it to be NULL since the list had ended.
    In cases non-DEBUG kernels this causes a panic with drm-5.15, since
    "s" is NULL when we later pass it to sg_mark_end().
    This change decouples the iteration sg from the return value so that
    it is never incremented past the final page in the chain.
    
    Approved by:    re (gjb)
    Reviewed by:    manu
    Differential Revision: https://reviews.freebsd.org/D41574
    
    (cherry picked from commit 09b0401e91a92bcb58ea1873857b42f8211f660f)
    (cherry picked from commit 2709483a725e1da2d443d9e391bfaa0f223099be)
---
 sys/compat/linuxkpi/common/include/linux/scatterlist.h | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/sys/compat/linuxkpi/common/include/linux/scatterlist.h b/sys/compat/linuxkpi/common/include/linux/scatterlist.h
index 0e4cc90e57a5..e462d5c649f1 100644
--- a/sys/compat/linuxkpi/common/include/linux/scatterlist.h
+++ b/sys/compat/linuxkpi/common/include/linux/scatterlist.h
@@ -343,7 +343,7 @@ __sg_alloc_table_from_pages(struct sg_table *sgt,
 {
 	unsigned int i, segs, cur, len;
 	int rc;
-	struct scatterlist *s;
+	struct scatterlist *s, *sg_iter;
 
 #if defined(LINUXKPI_VERSION) && LINUXKPI_VERSION >= 51300
 	if (prv != NULL) {
@@ -377,10 +377,18 @@ __sg_alloc_table_from_pages(struct sg_table *sgt,
 #endif
 
 	cur = 0;
-	for (i = 0, s = sgt->sgl; i < sgt->orig_nents; i++) {
+	for_each_sg(sgt->sgl, sg_iter, sgt->orig_nents, i) {
 		unsigned long seg_size;
 		unsigned int j;
 
+		/*
+		 * We need to make sure that when we exit this loop "s" has the
+		 * last sg in the chain so we can call sg_mark_end() on it.
+		 * Only set this inside the loop since sg_iter will be iterated
+		 * until it is NULL.
+		 */
+		s = sg_iter;
+
 		len = 0;
 		for (j = cur + 1; j < count; ++j) {
 			len += PAGE_SIZE;
@@ -394,8 +402,6 @@ __sg_alloc_table_from_pages(struct sg_table *sgt,
 		size -= seg_size;
 		off = 0;
 		cur = j;
-
-		s = sg_next(s);
 	}
 	KASSERT(s != NULL, ("s is NULL after loop in __sg_alloc_table_from_pages()"));