7.3.4-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 1091/1257 mm/truncate: fix the zeroing end of pagecache_isize_extended()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
[ Upstream commit 8f9039840588dd618c72a726c192126bb7b98228 ]
A process that extends a file by 4 GiB or more past a dirty folio, on a file system whose block size is smaller than the page size (ext4 with 1k blocks), reads back the bytes it wrote through a shared mapping beyond the old end of file instead of zeroes, and a later write into that block carries them to the disk. With the example of commit 52aecaee1c26 ("mm:
zero range of eof folio exposed by inode size extension") and the truncate taken 4 GiB further (pwrite 2k at 0, mmap the first page and write 'X' over [2k, 4k), truncate(2) to 4 GiB + 2k), the read of [2k, 4k) returns the 2048 'X' bytes, and a pwrite of 16 bytes at 3k followed by fsync() and a remount leaves 1008 'X' bytes on the disk in [3k+16, 4k). No privilege is needed, and every size extension of 4 GiB or more reaches it:
truncate(2)/ftruncate(2) through truncate_setsize(), writes beyond the end of file through generic_write_end(), ext4, iomap, btrfs, exfat, ntfs, afs and orangefs. Affected since v6.13.
pagecache_isize_extended() zeroes the part of the dirty folio straddling the old end of file that the size extension exposes, from the old size to the new size or the end of the folio, whichever comes first:
end = min_t(unsigned int, to - folio_pos(folio), folio_size(folio));
min_t() converts both operands to unsigned int before comparing, so the loff_t difference to - folio_pos(folio) is reduced modulo 2^32 first. When the file grows by 4 GiB or more past the folio, end is that residue instead of folio_size(folio): below offset nothing is zeroed, above it only [offset, end) is. The bytes beyond the old end of file stay in the dirty folio and, now inside i_size, are file data.
Compare in loff_t; the result is at most folio_size(folio) and fits end.
Found while formally verifying pagecache_isize_extended() against the kernel binary.
--- mm/truncate.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
mm/truncate.c +1 -2
@@ -880,8 +880,7 @@ void pagecache_isize_extended(struct inode *inode, loff_t from, loff_t to)unsigned int offset, end; offset = from -folio_pos (folio); - end = min_t(unsigned int, to - folio_pos(folio), -folio_size (folio)); + end =min_t (loff_t, to -folio_pos (folio),folio_size (folio));folio_zero_segment (folio, offset, end); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1092/1257 mm/page_vma_mapped: continue past nonmatching huge PMDs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
[ Upstream commit 1a2993227e8a27fc4cdea305bbdae82d290bc885 ]
A PTE-mapped large folio can straddle PMD boundaries after an unaligned mremap(). If the first part is discarded and replaced with an unrelated huge PMD, page_vma_mapped_walk() stops instead of looking for the rest of the folio in subsequent PMDs.
This also affects migration entries. A walk that stops at an unrelated huge PMD can leave migration PTEs behind when migration or an anonymous folio split restores the mappings. Those entries do not hold mapping references and can outlive the source folio.
This issue can lead to memory corruption and I have a reproducer for it.
Skip the current PMD rather than ending the walk on a flag or PFN mismatch. Do the same if the PMD became nonpresent before the locked recheck. Release the PMD lock, clear the per-PMD state and advance with step_forward(), so the existing range limit controls termination. This covers present, migration and device-private huge PMDs while preserving the matching-PMD and split-to-PTE paths.
--- mm/page_vma_mapped.c | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-)
mm/page_vma_mapped.c +19 -9
@@ -258,28 +258,28 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)softleaf_t entry;if (!(pvmw->flags &PVMW_MIGRATION )) -return not_found (pvmw); + goto next_pmd; entry =softleaf_from_pmd (pmde);if (!check_pmd (softleaf_to_pfn (entry), pvmw)) -return not_found (pvmw); + goto next_pmd;return true; }else if (pmd_is_device_private_entry (pmde)) {softleaf_t entry;if (pvmw->flags &PVMW_MIGRATION ) -return not_found (pvmw); + goto next_pmd; entry =softleaf_from_pmd (pmde);if (!check_pmd (softleaf_to_pfn (entry), pvmw)) -return not_found (pvmw); + goto next_pmd;return true; }else if (!pmd_present (pmde)) { -return not_found (pvmw); + goto next_pmd; }if (likely (pmd_trans_huge (pmde))) {if (pvmw->flags &PVMW_MIGRATION ) -return not_found (pvmw); + goto next_pmd;if (!check_pmd (pmd_pfn (pmde), pvmw)) -return not_found (pvmw); + goto next_pmd;return true; }/* THP/device-private pmd was split under us: handle on pte level */
@@ -292,8 +292,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) (pvmw->nr_pages >= HPAGE_PMD_NR))sync_with_folio_pmd_zap (mm, pvmw->pmd); -step_forward (pvmw,PMD_SIZE ); -continue ; + goto next_pmd; }if (!map_pte (pvmw, &pmde, &ptl)) {if (!pvmw->pte)
@@ -336,6 +335,17 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) pvmw->ptl = ptl; } goto this_pte; +next_pmd: +/* +* A large folio can be PTE-mapped across PMDs, so a +* nonmatching PMD does not end the walk. +*/ +if (pvmw->ptl) { +spin_unlock (pvmw->ptl); + pvmw->ptl =NULL ; + } + pvmw->pmd =NULL ; +step_forward (pvmw,PMD_SIZE ); }while (pvmw->address < end);return false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1093/1257 mm/mremap: populate calculated fields in vrm state correctly
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 34e753f8d927069785f6b675f5769da5da4ef78e ]
Commit d5c8aec0542e ("mm/mremap: initial refactor of move_vma()") introduced the vma_remap_struct helper to pass state sanely through mremap() logic.
Part of this state is vrm->delta - equal to the absolute difference between vrm->old_len and vrm->new_len (the old and new lengths of the VMA, respectively).
This value is used to correctly charge accounted VMAs.
When shrinking a VMA, mremap_to() sets vrm->old_len equal to vrm->new_len having performed the shrink of the VMA first, prior to any potential move (e.g. MREMAP_FIXED | MREMAP_MAYMOVE specified).
However it does not recalculate vrm->delta, which results in incorrectly overcharging the VMA when both moving and shrinking a VMA.
The charge leaks to Committed_AS globally, meaning a mischievous user can cause allocations to fail across the system in strict overcommit mode.
Resolve the issue by abstracting the update of vrm->delta to vrm_populate_calculated() and invoking this from mremap_to() when vrm->old_len is changed.
Additionally, update vrm->remap_type whose value depends on vrm->delta. The field is not read again after the shrink, but it is the logically correct thing to do and protects against future changes which break this.
--- mm/mremap.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-)
mm/mremap.c +9 -8
@@ -887,12 +887,6 @@ unsigned long move_page_tables(struct pagetable_move_control *pmc)return pmc_progress (pmc); } -/* Set vrm->delta to the difference in VMA size specified by user. */ -static void vrm_set_delta (struct vma_remap_struct *vrm) -{ - vrm->delta =abs_diff (vrm->old_len, vrm->new_len); -} -/* Determine what kind of remap this is - shrink, expand or no resize at all. */ static enum mremap_type vrm_remap_type (struct vma_remap_struct *vrm) {
@@ -905,6 +899,13 @@ static enum mremap_type vrm_remap_type(struct vma_remap_struct *vrm)return MREMAP_EXPAND ; } +/* Populate calculated fields. */ +static void vrm_populate_calculated (struct vma_remap_struct *vrm) +{ + vrm->delta =abs_diff (vrm->old_len, vrm->new_len); + vrm->remap_type =vrm_remap_type (vrm); +} +/* * When moving a VMA to vrm->new_adr, does this result in the new and old VMAs * overlapping?
@@ -1523,6 +1524,7 @@ static unsigned long mremap_to(struct vma_remap_struct *vrm)/* Set up for the move now shrink has been executed. */ vrm->old_len = vrm->new_len; +vrm_populate_calculated (vrm); }/* MREMAP_DONTUNMAP expands by old_len since old_len == new_len */
@@ -1795,8 +1797,7 @@ static int check_prep_vma(struct vma_remap_struct *vrm)if (is_vm_hugetlb_page (vma) && !align_hugetlb (vrm))return -EINVAL ; -vrm_set_delta (vrm); - vrm->remap_type =vrm_remap_type (vrm); +vrm_populate_calculated (vrm);/* For convenience, we set new_addr even if VMA won't move. */ if (!vrm_implies_new_addr (vrm)) vrm->new_addr = addr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1094/1257 mm/mremap: correctly uncharge accountable VMAs in error path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 65e722a74df992719676ead85a9e93fb2b5a0983 ]
The mremap error path is a fragile and unwieldy beast - it reverses the page table move then updates vma_remap_struct state to swap VMA, length and address between old and new VMAs in copy_vma_and_data().
If the mremap() operation didn't specify MREMAP_DONTUNMAP then its caller, move_vma(), invokes unmap_source_vma(), which unmaps the new VMA rather than the old one.
For accountable VMAs when MREMAP_DONTUNMAP is not specified, unmap_source_vma() unsets VMA_ACCOUNT_BIT during this unmap in order that only the delta of a VMA expansion is charged (performed by vrm_calc_charge() earlier).
Therefore nothing uncharges the expanded VMA size, and there is a permanent leak in global Committed_AS.
Resolve the issue by uncharging when MREMAP_DONTUNMAP is not specified.
--- mm/mremap.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
mm/mremap.c +14 -0
@@ -1339,6 +1339,20 @@ static int copy_vma_and_data(struct vma_remap_struct *vrm, pmc_revert.need_rmap_locks = true;move_page_tables (&pmc_revert); +/* +* When copy_vma_and_data() returns, the new VMA will be +* unmapped rather than the old one. +* +* When an accountable move is being performed, this unmapping +* will not uncharge any expansion, so do that now. +* +* A move is accountable if the VMA is accountable and +* MREMAP_DONTUNMAP is not specified, so only do so if the +* latter is true. +*/ +if (!(vrm->flags &MREMAP_DONTUNMAP )) +vrm_uncharge (vrm); + vrm->vma = new_vma; vrm->old_len = vrm->new_len; vrm->addr = vrm->new_addr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1095/1257 mm/vmscan: reclaim every zone in per-node proactive reclaim
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
[ Upstream commit d0a12d80d2f7e9f4ed2030b6f04c8a897956bf84 ]
user_proactive_reclaim() limits per-node reclaim to gfp_zone(GFP_KERNEL), which is ZONE_NORMAL. Proactive reclaim serves no allocation, but that limit makes shrink_node() skip every ZONE_MOVABLE folio, so writing to /sys/devices/system/node/nodeN/reclaim never reclaims a node's movable memory. A movable-only node, such as dax/kmem or hotplugged memory onlined movable, reclaims nothing and fails with -EAGAIN.
To reproduce, fill a movable-only node with clean page cache and write 200M to its nodeN/reclaim: the write fails with -EAGAIN and the page cache stays. The same write to a ZONE_NORMAL node frees 200MB.
Scan every zone, as memory.reclaim does.
--- mm/vmscan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c +1 -1
@@ -8041,7 +8041,7 @@ int user_proactive_reclaim(char *buf, }else {struct scan_control sc = { .gfp_mask =current_gfp_context (gfp_mask), - .reclaim_idx =gfp_zone (gfp_mask), + .reclaim_idx =MAX_NR_ZONES -1 , .proactive_swappiness = swappiness ==-1 ?NULL : &swappiness, .priority =DEF_PRIORITY , .may_writepage = 1,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1096/1257 mm/mempolicy: apply bind policies against the scoped allocation zone
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
[ Upstream commit d4ea410ce4b8aa46a316476ea2624a357bf31fa9 ]
QEMU fails to start a guest with a VFIO device when guest RAM comes from a memory backend bound to a movable-only node:
vfio_container_dma_map(0x55b1b1317800, 0x0, 0x10000000,
0x7f39a2200000)
= -12 (Cannot allocate memory)
VFIO pins guest RAM when the device is realized, and the pin faults the pages in. io_uring fixed buffers fail the same way. Faulting the range in before pinning lets the same pin succeed, since resident pages are migrated off the node instead.
A long-term pin faults under memalloc_pin_save(). PF_MEMALLOC_PIN makes current_gfp_context() clear __GFP_MOVABLE, but policy_nodemask() tests apply_policy_zone() against the caller's gfp.
The bind keeps its movable-only nodemask, and the allocation finds no usable zone:
page allocation failure:
order:0,
mode:0x140dc2(GFP_HIGHUSER|__GFP_ZERO|__GFP_COMP),
nodemask=1,cpuset=/,mems_allowed=0-1Call Trace: warn_alloc+0x136/0x150 __alloc_frozen_pages_noprof+0xed8/0x1720 alloc_pages_mpol+0xaa/0x170 vma_alloc_folio_noprof+0x65/0xd0 __handle_mm_fault+0x137b/0x1ac0 handle_mm_fault+0xa0/0x270 __get_user_pages+0x250/0xfd0 __gup_longterm_locked+0x116/0x870 gup_fast_fallback+0xcfc/0xdf0 pin_user_pages_fast+0x47/0x60 io_pin_pages+0x9a/0x110
Base page faults fail with -ENOMEM.
hugetlb faults fail with -EFAULT.
Check the policy zone against current_gfp_context(gfp), so a pin-scoped fault falls back off the movable-only nodemask, like any other non-movable allocation under the same bind.
Tested in qemu with a dax/kmem movable-only node 1. io_uring and VFIO pins of unfaulted base pages and 2MB hugetlb pages now succeed and land on node 0 (correct). QEMU now starts with the same backend binding.
--- mm/mempolicy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mempolicy.c +1 -1
@@ -2276,7 +2276,7 @@ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,break ;case MPOL_BIND :/* Restrict to nodemask (but not on lower zones) */ -if (apply_policy_zone (pol,gfp_zone (gfp)) && +if (apply_policy_zone (pol,gfp_zone (current_gfp_context (gfp))) &&cpuset_nodemask_valid_mems_allowed (&pol->nodes)) nodemask = &pol->nodes;if (pol->home_node !=NUMA_NO_NODE )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1097/1257 mm/damon/core: filter out damos address filter-split failed region
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: SJ Park <[email protected]>
[ Upstream commit bbeec2d8324d7aac438bb12dd2d22b184e0a8d43 ]
When an address type DAMOS filter is configured, DAMOS tries to split the region for the filter range, and apply DAMOS action to the filter-in region. The split operation (damon_split_region_at()) could fail from allocation failure under extreme memory pressure. In the case, DAMOS action could be applied more or less than expected, ignoring the address filter.
The issue only rarely happens under extreme memory pressure. No crash or leak happens. Occasionally not applying the action to a few regions shouldn't be a real problem. But applying the action to a region that the user has excluded via address filter could be a surprise depending on the use case. It is only theoretical. No such real case is found yet.
Filter out the entire region if the split is failed. Update damos_filter_match() signature to receive the error from split. Also update kunit tests for the updated signature.
The issue was discovered [1] by sashiko.
--- mm/damon/core.c | 16 ++++++++++++---- mm/damon/tests/core-kunit.h | 11 ++++++----- 2 files changed, 18 insertions(+), 9 deletions(-)
mm/damon/core.c +12 -4
@@ -2423,13 +2423,14 @@ static void damos_update_stat(struct damos *s,static bool damos_filter_match (struct damon_ctx *ctx,struct damon_target *t,struct damon_region *r,struct damos_filter *filter, -unsigned long min_region_sz) +unsigned long min_region_sz,int *err) {bool matched = false;struct damon_target *ti;int target_idx =0 ;unsigned long start, end; + *err =0 ;switch (filter->type) {case DAMOS_FILTER_TYPE_TARGET :damon_for_each_target (ti, ctx) {
@@ -2455,12 +2456,13 @@ static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t, }/* start before the range and overlap */ if (r->ar.start < start) { -damon_split_region_at (t, r, start - r->ar.start); + *err =damon_split_region_at (t, r, + start - r->ar.start); matched = false;break ; }/* start inside the range */ -damon_split_region_at (t, r, end - r->ar.start); + *err =damon_split_region_at (t, r, end - r->ar.start); matched = true;break ;default :
@@ -2474,10 +2476,16 @@ static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t, struct damon_region *r, struct damos *s) { struct damos_filter *filter; +bool matching; +int err; s->core_filters_allowed = false;damos_for_each_core_filter (filter, s) { -if (damos_filter_match (ctx, t, r, filter, ctx->min_region_sz)) { + matching =damos_filter_match (ctx, t, r, filter, + ctx->min_region_sz, &err); +if (err) +return true; +if (matching) {if (filter->allow) s->core_filters_allowed = true;return !filter->allow;
mm/damon/tests/core-kunit.h +6 -5
@@ -1360,6 +1360,7 @@ static void damos_test_filter_out(struct kunit *test)struct damon_target *t;struct damon_region *r, *r2;struct damos_filter *f; +int err; f =damos_new_filter (DAMOS_FILTER_TYPE_ADDR , true, false);if (!f)
@@ -1380,27 +1381,27 @@ static void damos_test_filter_out(struct kunit *test)damon_add_region (r, t);/* region in the range */ -KUNIT_EXPECT_TRUE (test,damos_filter_match (NULL , t, r, f,1 )); +KUNIT_EXPECT_TRUE (test,damos_filter_match (NULL , t, r, f,1 , &err));KUNIT_EXPECT_EQ (test,damon_nr_regions (t),1 );/* region before the range */ r->ar.start =1 ; r->ar.end =2 ;KUNIT_EXPECT_FALSE (test, -damos_filter_match (NULL , t, r, f,1 )); +damos_filter_match (NULL , t, r, f,1 , &err));KUNIT_EXPECT_EQ (test,damon_nr_regions (t),1 );/* region after the range */ r->ar.start =6 ; r->ar.end =8 ;KUNIT_EXPECT_FALSE (test, -damos_filter_match (NULL , t, r, f,1 )); +damos_filter_match (NULL , t, r, f,1 , &err));KUNIT_EXPECT_EQ (test,damon_nr_regions (t),1 );/* region started before the range */ r->ar.start =1 ; r->ar.end =4 ; -KUNIT_EXPECT_FALSE (test,damos_filter_match (NULL , t, r, f,1 )); +KUNIT_EXPECT_FALSE (test,damos_filter_match (NULL , t, r, f,1 , &err));/* filter should have split the region */ KUNIT_EXPECT_EQ (test, r->ar.start,1 );KUNIT_EXPECT_EQ (test, r->ar.end,2 );
@@ -1416,7 +1417,7 @@ static void damos_test_filter_out(struct kunit *test) r->ar.start =2 ; r->ar.end =8 ;KUNIT_EXPECT_TRUE (test, -damos_filter_match (NULL , t, r, f,1 )); +damos_filter_match (NULL , t, r, f,1 , &err));/* filter should have split the region */ KUNIT_EXPECT_EQ (test, r->ar.start,2 );KUNIT_EXPECT_EQ (test, r->ar.end,6 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1098/1257 riscv: mm: exclude invalid THP PMDs from page table check
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yunhui Cui <[email protected]>
[ Upstream commit bdda2887cbf3937c2d0f56589c2124c4167324e1 ]
RISC-V THP splitting uses a temporary invalid PMD state where pmd_mkinvalid() clears _PAGE_PRESENT and _PAGE_PROT_NONE but leaves _PAGE_LEAF set so the MM code can still recognize the PMD as a THP split in-progress entry.
That temporary state no longer describes a user-accessible mapping, but page_table_check currently treats it as one because the RISC-V PMD user-accessibility test only checks whether the PMD is a leaf and has user permissions.
As a result, when a PMD-sized anonymous THP is split during a COW fault, page_table_check can account the invalid intermediate PMD as a live PMD mapping, and then account the replacement PTE mappings again when the split installs the PTE table. This leaves stale PMD accounting behind and later triggers page_table_check failures such as a non-zero anon_map_count when the folio is freed.
Fix this by tightening pmd_user_accessible_page() so PMD page-table-check accounting only considers leaf PMDs that still carry either _PAGE_PRESENT or _PAGE_PROT_NONE. This preserves the THP split semantics required by the MM code while preventing page_table_check from treating invalid split PMDs as live user mappings.
With CONFIG_PAGE_TABLE_CHECK=y and CONFIG_PAGE_TABLE_CHECK_ENFORCED=y, tools/testing/selftests/mm/cow completes successfully on RISC-V after this change.
--- arch/riscv/include/asm/pgtable.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
arch/riscv/include/asm/pgtable.h +8 -1
@@ -993,7 +993,14 @@ static inline bool pte_user_accessible_page(struct mm_struct *mm, unsigned longstatic inline bool pmd_user_accessible_page (struct mm_struct *mm,unsigned long addr,pmd_t pmd) { -return pmd_leaf (pmd) &&pmd_user (pmd); +/* +* page_table_check() must ignore THP split invalidation entries created by +* pmd_mkinvalid(). These retain _PAGE_LEAF so pmd_present()/pmd_leaf() stay +* true during the split, but they no longer describe a user-accessible +* mapping once both _PAGE_PRESENT and _PAGE_PROT_NONE are cleared. +*/ +return (pmd_val (pmd) & (_PAGE_PRESENT | _PAGE_PROT_NONE)) && + (pmd_val (pmd) & _PAGE_LEAF) &&pmd_user (pmd); }static inline bool pud_user_accessible_page (struct mm_struct *mm,unsigned long addr,pud_t pud)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1099/1257 mm/vma: avoid broken uffd merge on mremap
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 68cb098eadda190783f8f8bdf9fe764df59f7d32 ]
Userfaultfd often causes unexpected interactions within mm, and does so at the intersection of uffd, mremap() and VMA merging.
When an mremap of a VMA occurs, copy_vma_and_data() calls mremap_userfaultfd_prep() to notify uffd of this.
However, mremap_userfaultfd_prep() simply drops the UFFD context for the VMA if the user did not register it for remap, i.e. didn't specify the UFFD_FEATURE_EVENT_REMAP flag.
This is OK for the VMA itself, as upon page table move, move_ptes() clears UFFD page table flags, using vma_has_uffd_without_event_remap() to determine whether to do so.
However, this doesn't account for merging with adjacent VMAs, whose page tables won't have received this treatment, and thus latent UFFD markers will be left around.
Worse, it'll break UFFD for any VMAs it is merged with. This is very surprising behaviour for a user, who will then simply not receive UFFD events for VMAs they ought to.
Resolve the issue by explicitly checking for this case via vma_has_uffd_without_event_remap() in vma_merge_copied_range(), the merge function explicitly designated for mremap() operations.
Also update the userland VMA tests accordingly.
--- mm/vma.c | 5 +++++ tools/testing/vma/include/stubs.h | 5 +++++ 2 files changed, 10 insertions(+)
mm/vma.c +5 -0
@@ -1225,6 +1225,11 @@ static struct vm_area_struct *vma_merge_copied_range(struct vma_merge_struct *vm vmg->copied_from = vmg->middle; vmg->middle =NULL ; + +/* If not registered for remap, uffd context will be cleared. */ +if (vma_has_uffd_without_event_remap (vmg->copied_from)) +return NULL ; +return vma_merge_new_range (vmg); }
tools/testing/vma/include/stubs.h +5 -0
@@ -356,6 +356,11 @@ static inline bool is_mergeable_vm_userfaultfd_ctx(struct vm_area_struct *vma,return true; } +static inline bool vma_has_uffd_without_event_remap (struct vm_area_struct *vma) +{ +return false; +} +static inline bool anon_vma_name_eq (struct anon_vma_name *anon_name1,struct anon_vma_name *anon_name2) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1100/1257 mm: multi-gen LRU: fix NULL lruvec->pgdat deref with memcg disabled on cmdline
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Siddharth Chintamaneni <[email protected]>
[ Upstream commit 183895979c441e52dbd651b388553b09eaa35cfa ]
When CONFIG_MEMCG=y, lruvec_pgdat() returns lruvec->pgdat, which for the per-node pgdat->__lruvec is left NULL by lruvec_init() and only filled in lazily by mem_cgroup_lruvec(). Normally that happens early, e.g. on the first folio_add_lru().
With cgroup_disable=memory, lru_gen_shrink_node() passes &pgdat->__lruvec directly to shrink_one(). If direct reclaim runs before anything has called mem_cgroup_lruvec() for the node, which can happen during early boot under memory pressure (e.g. a kdump kernel), get_swappiness() ends up dereferencing a NULL pgdat:
Unable to handle kernel NULL pointer dereference at virtual address 0000000000005040 pc : get_swappiness+0x68/0xb0 lr : try_to_shrink_lruvec+0x54/0x2c0 Call trace: get_swappiness+0x68/0xb0 (P) try_to_shrink_lruvec+0x54/0x2c0 shrink_one+0x8c/0x240 shrink_node+0xc6c/0xe08 do_try_to_free_pages+0xdc/0x570 try_to_free_pages+0x124/0x278 __alloc_frozen_pages_noprof+0x6e8/0xf78 alloc_pages_mpol+0xc4/0x1c0 alloc_frozen_pages_noprof+0x54/0xe8 alloc_pages_noprof+0x1c/0x40 atomic_pool_expand+0x98/0x300 __dma_atomic_pool_init+0x58/0xd8 dma_atomic_pool_init+0x154/0x170 do_one_initcall+0x64/0x350 kernel_init_freeable+0x214/0x430 kernel_init+0x2c/0x208 ret_from_fork+0x10/0x20
The classic LRU path and MGLRU before per-node lru_gen_folio lists obtained the lruvec through mem_cgroup_lruvec(), which sets lruvec->pgdat.
The above was hit on an arm64 kdump kernel (6.18-based) booted with cgroup_disable=memory nr_cpus=4. It also reproduces on mainline on an arm64 VM with CONFIG_ARM64_64K_PAGES=y, CONFIG_MEMCG=y, CONFIG_LRU_GEN_ENABLED=y and:
mem=160M nr_cpus=4 coherent_pool=512M cgroup_disable=memory
These options only serve to force direct reclaim early in boot; with 160M the boot eventually ends in OOM regardless. On mainline the first LRU reclaim happens while unpacking the initramfs, and faults the same way:
Unable to handle kernel NULL pointer dereference at virtual address 0000000000005040 pc : get_swappiness+0xd4/0x150 Call trace: get_swappiness+0xd4/0x150 (P) try_to_shrink_lruvec+0x44/0x2b8 shrink_one+0x80/0x1a0 shrink_node+0xd98/0xea8 do_try_to_free_pages+0xf4/0x4b0 try_to_free_pages+0x110/0x360 __alloc_frozen_pages_noprof+0x8b0/0x1718 ... __filemap_get_folio_mpol+0x2ac/0x548 simple_write_begin+0x44/0xf8 page_symlink+0x178/0x198 ... do_populate_rootfs+0x13c/0x200
--- mm/vmscan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c +1 -1
@@ -5258,7 +5258,7 @@ static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control * sc->nr_reclaimed =0 ;if (mem_cgroup_disabled ()) -shrink_one (&pgdat->__lruvec, sc); +shrink_one (mem_cgroup_lruvec (NULL , pgdat), sc);else shrink_many (pgdat, sc);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1101/1257 fscrypt: Fix missing barrier in fscrypt_find_mode_key()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baokun Li <[email protected]>
[ Upstream commit cf66375465b9ca531f5c294f468db1df293c178c ]
fscrypt_find_mode_key() walks an RCU list and hands out a per-mode key without an acquire:
setup task
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
setup_per_mode_enc_key()
├─ fscrypt_prepare_key() │ └─ fscrypt_prepare_inline_crypt_key() │ └─ blk_crypto_start_using_key() │ └─ blk_crypto_fallback_start_using_mode() │ ├─ init profile, keyslots, tfms[] │ └─ smp_store_release(tfms_inited[mode]) # init order └─ list_add_tail_rcu(&new_node->link, ...) # release -> finder
finding task (later submits the I/O itself)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fscrypt_find_mode_key()
├─ list_for_each_entry_rcu(node, ...) └─ return &node->key # no acquire, chain breaks ... blk_crypto_fallback_bio_prep() # WRITE path ├─ tfms_inited[mode] # addr-dep, reads true ├─ blk_crypto_fallback_profile # no dependency ├─ blk_crypto_keyslots # no dependency └─ slotp->tfms[mode] # no dependency
RCU publishes the node and the key reachable from it, so tfms_inited[mode] reads true through the address dependency. The independent fallback globals are not covered by it and can be read as uninitialized.
On a weakly ordered machine, a WRITE bio can crash in blk_crypto_get_keyslot() or crypto_sync_skcipher_setkey().
Other tasks reach the key through fscrypt_inode_info's cmpxchg_release()/smp_load_acquire(), which is already ordered after the list walk; only the finding task's own later I/O was not.
Fix this by upgrading the control dependency to an acquire with smp_acquire__after_ctrl_dep() once a matching entry has been found.
--- fs/crypto/keysetup.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
fs/crypto/keysetup.c +7 -1
@@ -205,8 +205,14 @@ fscrypt_find_mode_key(struct fscrypt_master_key *mk, u8 hkdf_context,if (node->hkdf_context == hkdf_context && node->mode_num == mode_num && node->data_unit_bits == ci->ci_data_unit_bits && -fscrypt_is_key_prepared (&node->key, ci)) +fscrypt_is_key_prepared (&node->key, ci)) { +/* +* Upgrade the RCU dereference to a full ACQUIRE, so +* that blk-crypto global state is seen as initialized. +*/ +smp_acquire__after_ctrl_dep ();return &node->key; + } }return NULL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1102/1257 ext4: refuse encryption when block size > page size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alberto Garcia <[email protected]>
[ Upstream commit 0e341d1d29db11c29211d2b8870a515c26589d5a ]
Encryption is not supported when a filesystem's block size is larger than the page size, and commit 709f0f1f1bf5 ("ext4: add checks for large folio incompatibilities when BS > PS") added a check to refuse mounting such a filesystem.
However, it is also possible to enable the "encrypt" feature on a filesystem that is already mounted (with tune2fs -O encrypt). Once that happens it won't be possible to mount the filesystem again in the future, but there is nothing preventing the user from setting an encryption policy while the filesystem is still mounted.
Fix this by refusing to set an fscrypt context in ext4_set_context() when the block size is larger than the page size.
--- fs/ext4/crypto.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/ext4/crypto.c +9 -0
@@ -156,6 +156,15 @@ static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,if (ext4_test_inode_flag (inode,EXT4_INODE_DAX ))return -EOPNOTSUPP ; +/* +* Encryption is not supported when the block size is larger +* than the page size. This is rejected at mount time by +* ext4_check_large_folio(), and this check here is for the case +* when the 'encrypt' feature is enabled on a mounted filesystem. +*/ +if (inode->i_sb->s_blocksize >PAGE_SIZE ) +return -EOPNOTSUPP ; + res =ext4_convert_inline_data (inode);if (res)return res;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1103/1257 ext4: reject encrypted inodes when block size > page size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alberto Garcia <[email protected]>
[ Upstream commit a5e894bc87b76fd980075892ba77e6bdeeb5e4d0 ]
Encryption is not supported when a filesystem's block size is larger than the page size. ext4_check_large_folio() refuses to mount a filesystem like that if the "encrypt" feature is already enabled, and ext4_set_context() refuses to create encrypted inodes if the feature is enabled after mounting.
However, a corrupted or hand-crafted filesystem can still have encrypted inodes even if the "encrypt" feature is not set, and those inodes can be unlocked if they're using v1 policies.
Check this in __ext4_iget() and reject them as corrupted.
--- fs/ext4/inode.c | 6 ++++++ 1 file changed, 6 insertions(+)
fs/ext4/inode.c +6 -0
@@ -5671,6 +5671,12 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, ret = -EFSCORRUPTED ; goto bad_inode; } +if (IS_ENCRYPTED (inode) && sb->s_blocksize >PAGE_SIZE ) { +ext4_error_inode (inode, function, line,0 , +"encrypted inode with block size larger than page size" ); + ret = -EFSCORRUPTED ; + goto bad_inode; + }ext4_set_inode_mapping_order (inode);
Signature · 1 line
2.53.0
Re: [PATCH 7.3 1103/1257] ext4: reject encrypted inodes when block size > page size
Quoted 39 lines · Greg Kroah-Hartman
7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alberto Garcia <[email protected]>
[ Upstream commit
a5e894bc87b76fd980075892ba77e6bdeeb5e4d0]Encryption is not supported when a filesystem's block size is larger than the page size.
ext4_check_large_folio()refuses to mount a filesystem like that if the "encrypt" feature is already enabled, andext4_set_context()refuses to create encrypted inodes if the feature is enabled after mounting.However, a corrupted or hand-crafted filesystem can still have encrypted inodes even if the "encrypt" feature is not set, and those inodes can be unlocked if they're using v1 policies.
Check this in
__ext4_iget()and reject them as corrupted.Fixes 709f0f1f1bf5 ("ext4: add checks for large folio incompatibilities when BS > PS")Suggested-by Eric Biggers <[email protected]>Cc [email protected] # v6.19+Signed-off-by Alberto Garcia <[email protected]>Reviewed-by Baokun Li <[email protected]>Reviewed-by Eric Biggers <[email protected]>Link https://patch.msgid.link/aeb8efa8beb72721fb4b13cffe6eb22c795ec33f.1790343958.git.berto@igalia.com open hereSigned-off-by Eric Biggers <[email protected]>Signed-off-by Sasha Levin <[email protected]>--- fs/ext4/inode.c | 6 ++++++ 1 file changed, 6 insertions(+)fs/ext4/inode.c +0
-0@@ -5671,6 +5671,12 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, ret = -EFSCORRUPTED ;
fs/ext4/inode.c struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, · line 5681
Quoted 10 lines
fs/ext4/inode.c +6
-0goto bad_inode; } +if (IS_ENCRYPTED (inode) && sb->s_blocksize >PAGE_SIZE ) { +ext4_error_inode (inode, function, line,0 , +"encrypted inode with block size larger than page size" ); + ret = -EFSCORRUPTED ; + goto bad_inode; + }ext4_set_inode_mapping_order (inode);
This particular patch should be fine, but I have a question about whether it's guaranteed that the diffs in these stable-review emails will match the ones that actually get released.
As we know
(https://lore.kernel.org/linux-crypto/20261021164836.GB1879@quark/), the cherry-pick process used by the stable maintainers doesn't actually use 'git cherry-pick' as expected, but rather formats the upstream patch as a patch file with 3 lines of context, then applies it with a fuzz of 2. That means only 1 line of context has to match for the patch to apply.
For this patch, those context lines are just a closing brace and an empty line. Those are very common! So there are actually quite a few other places in the file that the patch could have been applied to; it seems the only thing that saves us in most cases is chance and the line numbers not having shifted too much.
So my question is this: let's suppose the upstream commit did get applied to the wrong place in the file that happened to share the same 1 line of context. Of course, this email is being sent out with the standard 3 lines of context. Is this email the original patch file that was applied (and thus the context doesn't necessarily match the context in the commit that actually gets released), or is a new patch file generated after application and that is what is sent out for review?
- Eric
Greg Kroah-Hartman
maintainerPATCH 1104/1257 fbdev: atmel_lcdfb: fix list_first_entry() on possibly empty modelist in probe
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wang Haoran <[email protected]>
[ Upstream commit 01d1204582f16e8b7bfce29648e5cf77a585d962 ]
list_first_entry() does not return NULL on an empty list; it returns a bogus pointer computed by container_of() from the list head. atmel_lcdfb_probe() initializes info->modelist with INIT_LIST_HEAD() and later takes its first entry with list_first_entry(), assuming atmel_lcdfb_of_init() populated it. However, atmel_lcdfb_of_init() drops the return value of fb_add_videomode() — unlike every other fallible call in the same function — so if fb_add_videomode() fails (its internal kmalloc can return -ENOMEM under memory pressure or fault injection), the list stays empty while of_init() reports success. The probe path then dereferences the bogus pointer in fb_videomode_to_var(&info->var, &modelist->mode). Because the bogus pointer lands inside the contiguous fb_info allocation, this may not fault immediately; instead it silently reads adjacent memory as a struct fb_videomode and programs garbage timing parameters into the LCD controller. This was found by code audit; we do not have Atmel hardware to reproduce it.
Fix this on two levels: check the return value of fb_add_videomode() in atmel_lcdfb_of_init() so the failure is propagated (root cause), and use list_first_entry_or_null() in atmel_lcdfb_probe() with a NULL check that fails probe gracefully with -EINVAL (defense in depth), consistent with the surrounding error handling which bails out to stop_clk.
--- drivers/video/fbdev/atmel_lcdfb.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +10 -3
@@ -1007,7 +1007,9 @@ static int atmel_lcdfb_of_init(struct atmel_lcdfb_info *sinfo)if (ret <0 ) goto put_display_node; -fb_add_videomode (&fb_vm, &info->modelist); + ret =fb_add_videomode (&fb_vm, &info->modelist); +if (ret <0 ) + goto put_display_node; put_display_node:of_node_put (display_np);
@@ -1075,8 +1077,13 @@ static int atmel_lcdfb_probe(struct platform_device *pdev) }atmel_lcdfb_start_clock (sinfo); - modelist =list_first_entry (&info->modelist, - struct fb_modelist, list); + modelist =list_first_entry_or_null (&info->modelist, + struct fb_modelist, list); +if (!modelist) { +dev_err (dev,"no video mode available\n" ); + ret = -EINVAL ; + goto stop_clk; + }fb_videomode_to_var (&info->var, &modelist->mode);atmel_lcdfb_check_var (&info->var, info);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1105/1257 erofs: hold real inodes for shared files
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gao Xiang <[email protected]>
[ Upstream commit 7259fb011c14977661b7a4680886b466a3089ea7 ]
EROFS page cache sharing uses shared inodes. However, a mmaped VMA keeps the shared file even after the corresponding fd is closed, while currently the real inode is never held by any reference associated with the shared file.
As a result, the real inode could be evicted and removed from the shared inode's list while the page fault can still invoke on the shared inode's address space, which causes no candidate is successfully acquired by erofs_real_inode().
Fix this by simply keeping the original inode in the shared backing file's private data.
Also replace confusing "realfile"/"rf" names with "sf" (sharedfile) to unify the terms as well as nullify realinode in erofs_real_inode() to avoid returning an uninitialized pointer.
--- fs/erofs/ishare.c | 43 ++++++++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 13 deletions(-)
fs/erofs/ishare.c +30 -13
@@ -30,9 +30,18 @@ static int erofs_ishare_iget5_set(struct inode *inode, void *data)return 0 ; } +static int erofs_ishare_backing_release (struct inode *inode,struct file *file) +{ +iput (file->private_data); + file->private_data =NULL ; +return 0 ; +} +bool erofs_ishare_fill_inode (struct inode *inode) { -static const struct file_operations empty_fops = {}; +static const struct file_operations backing_fops = { + .release = erofs_ishare_backing_release, + };struct erofs_sb_info *sbi =EROFS_SB (inode->i_sb);const struct address_space_operations *aops;struct erofs_inode *vi =EROFS_I (inode);
@@ -50,7 +59,7 @@ bool erofs_ishare_fill_inode(struct inode *inode)xxh32 (fp.opaque, fp.size,0 ), erofs_ishare_iget5_eq, erofs_ishare_iget5_set, &fp);if (si && (inode_state_read_once (si) &I_NEW )) { - si->i_fop = &empty_fops; + si->i_fop = &backing_fops; si->i_mapping->a_ops = aops; si->i_mode =0444 |S_IFREG ; si->i_size = inode->i_size;
@@ -100,16 +109,24 @@ static int erofs_ishare_file_open(struct inode *inode, struct file *file) .mnt = erofs_ishare_mnt, .dentry = EROFS_I(inode)->sharedentry, }; -struct file *rf; +struct file *sf;if (file->f_flags &O_DIRECT )return -EINVAL ; - rf =backing_file_open (file, file->f_flags |O_NOATIME , + sf =backing_file_open (file, file->f_flags |O_NOATIME , &sharedpath,current_cred ()); -if (IS_ERR (rf)) -return PTR_ERR (rf); - file->private_data = rf; +if (IS_ERR (sf)) +return PTR_ERR (sf); +/* +* A VMA only holds a reference to the shared file so that the original +* file may be released: the shared file must therefore hold a reference +* to one of the real inodes ("inode" passed here), and that reference +* will be released by erofs_ishare_backing_release(). +*/ +ihold (inode); + sf->private_data = inode; + file->private_data = sf;return 0 ; }
@@ -123,13 +140,13 @@ static int erofs_ishare_file_release(struct inode *inode, struct file *file)static ssize_t erofs_ishare_file_read_iter (struct kiocb *iocb,struct iov_iter *to) { -struct file *realfile = iocb->ki_filp->private_data; +struct file *sf = iocb->ki_filp->private_data;struct kiocb dedup_iocb;ssize_t nread;if (!iov_iter_count (to))return 0 ; -kiocb_clone (&dedup_iocb, iocb, realfile); +kiocb_clone (&dedup_iocb, iocb, sf); nread =filemap_read (&dedup_iocb, to,0 ); iocb->ki_pos = dedup_iocb.ki_pos;return nread;
@@ -137,12 +154,12 @@ static ssize_t erofs_ishare_file_read_iter(struct kiocb *iocb,static int erofs_ishare_mmap (struct file *file,struct vm_area_struct *vma) { -struct file *realfile = file->private_data; +struct file *sf = file->private_data;int err; -vma_set_file (vma, realfile); +vma_set_file (vma, sf); - err =security_mmap_backing_file (vma, realfile, file); + err =security_mmap_backing_file (vma, sf, file);if (err)return err;
@@ -176,7 +193,7 @@ const struct file_operations erofs_ishare_fops = {struct inode *erofs_real_inode (struct inode *inode,bool *need_iput) {struct erofs_inode *vi, *vi_share; -struct inode *realinode; +struct inode *realinode =NULL ; *need_iput = false;if (inode->i_sb != erofs_ishare_mnt->mnt_sb)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1106/1257 posix-timers: Accept NULL clock_getres() output in stubs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit 5b819071e4346256c4edbae5cc2095dff25694fc ]
With CONFIG_POSIX_TIMERS disabled, clock_getres() returns -EFAULT for a supported clock when the result pointer is NULL. POSIX permits a NULL result pointer to suppress returning the clock resolution.
Only copy the result when a destination is provided, in both the native and time32 stubs. This matches the full POSIX timer implementation and preserves clock ID validation.
--- kernel/time/posix-stubs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/time/posix-stubs.c +2 -2
@@ -83,7 +83,7 @@ SYSCALL_DEFINE2(clock_getres, const clockid_t, which_clock, struct __kernel_timecase CLOCK_REALTIME :case CLOCK_MONOTONIC :case CLOCK_BOOTTIME : -if (put_timespec64 (&rtn_tp, tp)) +if (tp &&put_timespec64 (&rtn_tp, tp))return -EFAULT ;return 0 ;default :
@@ -166,7 +166,7 @@ SYSCALL_DEFINE2(clock_getres_time32, clockid_t, which_clock,case CLOCK_REALTIME :case CLOCK_MONOTONIC :case CLOCK_BOOTTIME : -if (put_old_timespec32 (&rtn_tp, tp)) +if (tp &&put_old_timespec32 (&rtn_tp, tp))return -EFAULT ;return 0 ;default :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1107/1257 timers/itimer: Keep a nonzero value at CPU timer expiry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit ef60f61208a30eb5b941b707debdf04517271b4f ]
get_cpu_itimer() returns a zero remaining time when the sampled CPU time is exactly equal to the nonzero expiry. This makes an armed ITIMER_VIRTUAL or ITIMER_PROF timer appear disarmed.
The cputime cleanup replaced cputime_le(), which implements <=, with <. Restore the inclusive comparison so the equality case returns TICK_NSEC, like the overdue case and set_process_cpu_timer().
--- kernel/time/itimer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/time/itimer.c +1 -1
@@ -60,7 +60,7 @@ static void get_cpu_itimer(struct task_struct *tsk, unsigned int clock_id,thread_group_sample_cputime (tsk, samples); t = samples[clock_id]; -if (val < t) +if (val <= t)/* about to fire */ val =TICK_NSEC ;else
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1108/1257 time/namespace: Fix overflow when converting absolute deadlines
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
[ Upstream commit d69cfd33b5a8d176124c564513b9ceb933595d93 ]
do_timens_ktime_to_host() subtracts the namespace offset from an absolute deadline and clamps the result to [0, KTIME_MAX]. A negative offset can make a large deadline overflow to a negative value. Since ktime_t is signed and KTIME_MAX is its maximum value, the subsequent comparison against KTIME_MAX can never detect this overflow.
For example, with a -1 second boottime offset, an absolute CLOCK_BOOTTIME timerfd deadline of KTIME_MAX can expire immediately. An absolute clock_nanosleep() using the same clock and deadline can also return immediately instead of waiting.
The earlier tim < offset check already handles the lower bound. A negative subtraction result in the remaining branch therefore indicates overflow. Detect that result and clamp it to KTIME_MAX.
--- kernel/time/namespace.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/time/namespace.c +1 -1
@@ -51,7 +51,7 @@ ktime_t do_timens_ktime_to_host(clockid_t clockid, ktime_t tim, tim =0 ; }else { tim =ktime_sub (tim, offset); -if (unlikely (tim >KTIME_MAX )) +if (unlikely (tim <0 )) tim =KTIME_MAX ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1109/1257 posix-timers: Report zero remaining time for disarmed SIGEV_NONE timers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hung-Jui Lin <[email protected]>
[ Upstream commit 141a27750ec3d91ad9d1ad1764ebb5e51b963478 ]
SIGEV_NONE timers are never queued. common_timer_get() emulates their expiry by computing the remaining time from the stored expiry value. Because an armed SIGEV_NONE oneshot timer is not queued, its it_status stays POSIX_TIMER_DISARMED. So common_timer_get() cannot use it_status to skip a disarmed SIGEV_NONE timer and evaluates the stored expiry value for all SIGEV_NONE timers.
Disarming a timer with timer_settime() and a zero it_value cancels the timer and sets it_status to POSIX_TIMER_DISARMED, but leaves the expiry value unchanged. As a consequence, timer_gettime() on a disarmed SIGEV_NONE timer reports the remaining time of the previous arming until that time has passed, instead of zero as POSIX requires for a disarmed timer. Example with a CLOCK_MONOTONIC timer armed with it_value = 10ms and it_interval = 100ms, then disarmed with an all-zero itimerspec:
armed: it_value = 0.009999000 it_interval = 0.100000000
disarmed: it_value = 0.008700792 it_interval = 0.000000000
SIGEV_SIGNAL timers and SIGEV_NONE CPU timers report zero in the same situation. All clocks which use common_timer_get() are affected, including the alarm timer clocks.
Mark SIGEV_NONE timers as POSIX_TIMER_ARMED when they are armed, so that common_timer_get() returns early for every disarmed timer. Forward SIGEV_NONE interval timers in common_timer_get() regardless of it_status, as they are never queued and therefore never forwarded by the expiry code.
After the change the disarmed timer above reports zero. Armed SIGEV_NONE oneshot and interval timers on CLOCK_MONOTONIC, CLOCK_REALTIME, CLOCK_BOOTTIME and CLOCK_BOOTTIME_ALARM still report their remaining time, and the posix_timers selftest passes.
--- kernel/time/posix-timers.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-)
kernel/time/posix-timers.c +12 -13
@@ -694,16 +694,8 @@ void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)if (iv) { cur_setting->it_interval =ktime_to_timespec64 (iv); }else if (timr->it_status ==POSIX_TIMER_DISARMED ) { -/* -* SIGEV_NONE oneshot timers are never queued and therefore -* timr->it_status is always DISARMED. The check below -* vs. remaining time will handle this case. -* -* For all other timers there is nothing to update here, so -* return. -*/ -if (!sig_none) -return ; +/* Nothing to update for a disarmed timer */ +return ; } now = kc->clock_get_ktime (timr->it_clock);
@@ -713,7 +705,7 @@ void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)* is a SIGEV_NONE timer move the expiry time forward by intervals, * so expiry is > now. */ -if (iv && timr->it_status !=POSIX_TIMER_ARMED ) +if (iv && (sig_none || timr->it_status !=POSIX_TIMER_ARMED )) timr->it_overrun += kc->timer_forward (timr, now); remaining = kc->timer_remaining (timr, now);
@@ -915,8 +907,15 @@ int common_timer_set(struct k_itimer *timr, int flags, sigev_none = timr->it_sigev_notify ==SIGEV_NONE ;if (kc->timer_arm (timr, expires, flags &TIMER_ABSTIME , sigev_none)) { -if (!sigev_none) - timr->it_status =POSIX_TIMER_ARMED ; +/* +* SIGEV_NONE timers are not queued, but mark them armed +* so that common_timer_get() can tell them apart from +* disarmed timers. An expired SIGEV_NONE timer stays +* armed, which is harmless: common_timer_get() reports +* zero remaining time for it and it never reaches the +* signal delivery code. +*/ + timr->it_status =POSIX_TIMER_ARMED ; }else {/* Timer was already expired, queue the signal */ posix_timer_queue_signal (timr);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1110/1257 tick/nohz: Reevaluate the tick for kicks flushed outside hardirq
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peng Wang <[email protected]>
[ Upstream commit e389ae428847a2e6a3b698b5967df68ccf90361c ]
The nohz full kick relies on interrupt exit to reevaluate the tick. However, a remote kick can also be flushed from task context without an interrupt exit guaranteed to follow. If a tick dependency is set or an earlier timer is queued after the idle-exit reevaluation, the required tick update can be delayed until another interrupt.
Reevaluate the tick directly from the callback outside hardirq context. Keep the existing interrupt exit handling for hardirq callbacks. The offline flush remains harmless because tick_sched_timer_dying() has already cleared TS_FLAG_NOHZ.
--- kernel/time/tick-sched.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/time/tick-sched.c +13 -1
@@ -400,9 +400,21 @@ static bool can_stop_full_tick(int cpu, struct tick_sched *ts)return true; } +static void tick_nohz_full_update_tick (struct tick_sched *ts); +static void nohz_full_kick_func (struct irq_work *work) { -/* Empty, the tick restart happens on tick_nohz_irq_exit() */ +struct tick_sched *ts =this_cpu_ptr (&tick_cpu_sched); + +if (WARN_ON_ONCE (!tick_nohz_full_cpu (smp_processor_id ()))) +return ; + +/* Task-context flushes may not be followed by an IRQ exit. */ +if (!in_hardirq ()) { +if (WARN_ON_ONCE (tick_sched_flag_test (ts,TS_FLAG_INIDLE ))) +return ; +tick_nohz_full_update_tick (ts); + } } static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) =
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1111/1257 KVM: arm64: Set HCR_EL2.BSU to Inner Shareable for guests
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fuad Tabba <[email protected]>
[ Upstream commit 00e73757518020273ccf6308a51f214e58c21ad5 ]
KVM sets HCR_EL2.BSU to Inner Shareable for guests, so that a guest's barriers cover the TLB and I-cache invalidations that HCR_EL2.FB broadcasts. However, since HCR_BSU_IS became an alias of the generated HCR_EL2_BSU_IS, it is the unshifted field value 0b01, which sets bit 0 (VM, already set) and leaves BSU at 0b00. A guest's DSB NSH is then not required to wait for a broadcast TLBI to complete on other CPUs.
Build the field with SYS_FIELD_PREP_ENUM().
--- arch/arm64/include/asm/kvm_arm.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/include/asm/kvm_arm.h +1 -1
@@ -98,7 +98,7 @@* TID1: Trap REVIDR_EL1, AIDR_EL1, and SMIDR_EL1 */ #define HCR_GUEST_FLAGS (HCR_TSC | HCR_TSW | HCR_TWE | HCR_TWI | HCR_VM | \ - HCR_BSU_IS | HCR_FB | HCR_TACR | \ + SYS_FIELD_PREP_ENUM(HCR_EL2, BSU, IS) | HCR_EL2_FB | HCR_EL2_TACR | \ HCR_AMO | HCR_SWIO | HCR_TIDCP | HCR_RW | HCR_TLOR | \ HCR_FMO | HCR_IMO | HCR_PTW | HCR_TID3 | HCR_TID1)#define HCR_HOST_NVHE_FLAGS (HCR_RW | HCR_API | HCR_APK)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1112/1257 tracing/remotes: Fix TRACE_REMOTE build when TRACING=n
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vincent Donnefort <[email protected]>
[ Upstream commit 3bb853ad84244f0b86ab12f029bc4a0c9c7100e8 ]
TRACE_REMOTE relies on tracefs, eventfs and ring-buffer which are only built and declared when TRACING is enabled. It is however possible for a config to have FTRACE=y TRACING=n and TRACE_REMOTE=y.
To fix this configuration, have TRACE_REMOTE select TRACING directly, just like other FTRACE options do and drop the TRACING dependency from NVHE_EL2_TRACING to avoid a circular Kconfig dependency.
--- arch/arm64/kvm/Kconfig | 2 +- kernel/trace/Kconfig | 1 + 2 files changed, 2 insertions(+), 1 deletion(-)
arch/arm64/kvm/Kconfig +1 -1
@@ -74,7 +74,7 @@ if NVHE_EL2_DEBUG config NVHE_EL2_TRACING bool - depends on TRACING && FTRACE + depends on FTRACE select TRACE_REMOTE default y
kernel/trace/Kconfig +1 -0
@@ -1329,6 +1329,7 @@ source "kernel/trace/rv/Kconfig" config TRACE_REMOTE bool + select TRACING config SIMPLE_RING_BUFFER bool
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1113/1257 KVM: arm64: Sanitise ID_AA64MMFR3_EL1.S1P[IO]E
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
[ Upstream commit 68c11eed4f8097ef1b71c30679e96eb654df29e0 ]
KVM uses the VM's ID registers as the source of truth for what the guest has, but userspace can expose S1PIE or S1POE without the features they imply. As per the architecture, both imply TCR2 and ATS1A, and S1POE also implies HPDS. With TCR2 hidden, the world switch skips PIR_EL1, PIRE0_EL1 and POR_EL1 while KVM doesn't trap them, so the guest accesses registers that are neither trapped nor switched. Under VHE, that leaks values between guests. On nVHE and hVHE, pKVM included, the host kernel resumes with the guest's PIR_EL1 and PIRE0_EL1.
On first run, clear S1PIE and S1POE from the VM's ID registers when the features they imply are missing, before anything derives state from them. The guest and userspace then see neither feature, and the guest's accesses to their registers UNDEF.
--- arch/arm64/include/asm/kvm_host.h | 1 + arch/arm64/kvm/config.c | 78 +++++++++++++++++++++++++++++++ arch/arm64/kvm/sys_regs.c | 2 + 3 files changed, 81 insertions(+)
arch/arm64/include/asm/kvm_host.h +1 -0
@@ -1658,6 +1658,7 @@ static inline bool kvm_arch_has_irq_bypass(void)return true; } +void kvm_idregs_enforce_dependencies (struct kvm *kvm);void compute_fgu (struct kvm *kvm,enum fgt_group_id fgt);struct resx get_reg_fixed_bits (struct kvm *kvm,enum vcpu_sysreg reg);void check_feature_map (void );
arch/arm64/kvm/config.c +78 -0
114 lines not on this page · raw message
arch/arm64/kvm/sys_regs.c +2 -0
@@ -5884,6 +5884,8 @@ int kvm_finalize_sys_regs(struct kvm_vcpu *vcpu)if (kvm_vm_has_ran_once (kvm))return 0 ; +kvm_idregs_enforce_dependencies (kvm); +/* * This hacks into the ID registers, so only perform it when the * first vcpu runs, or the kvm_set_vm_id_reg() helper will scream.
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1114/1257 ceph: avoid pending truncate during nonblocking cap acquire
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Max Kellermann <[email protected]>
[ Upstream commit 979b7ed4457a04c5a41c36f86052ecc6b76c67d9 ]
Readahead acquires caps while the folios are locked. This can deadlock when processing a pending truncate; truncate_pagecache() can then attempt to a folio that is already locked.
Return -EAGAIN instead when NON_BLOCKING is set, causing the readahead to be abandoned.
--- fs/ceph/caps.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/ceph/caps.c +4 -0
@@ -2889,6 +2889,10 @@ static int try_get_cap_refs(struct inode *inode, int need, int want, }/* finish pending truncate */ +if (ci->i_truncate_pending && (flags &NON_BLOCKING )) { + ret = -EAGAIN ; + goto out_unlock; + }while (ci->i_truncate_pending) {spin_unlock (&ci->i_ceph_lock);if (snap_rwsem_locked) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1115/1257 ceph: fix longname buffer overflow in ceph_fname_to_usr()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiangshan Yi <[email protected]>
[ Upstream commit 71975d6e0db17646102488cf54480fda9de0f7a7 ]
Snapshot longname reconstruction formats "_<name>_<inode>" via snprintf() and memcpy()s the result into oname->name. Checking the length against NAME_MAX only protects the LOOKUPNAME/export callers, whose buffer is allocated with fscrypt_fname_alloc_buffer(NAME_MAX). The readdir path points oname->name straight at the altname in the MDS reply, whose capacity is altname_len; the reconstructed name can exceed that while still fitting under NAME_MAX, overflowing the in-place destination.
Save the actual oname->len before the decryption overwrites it, and fail with -ENAMETOOLONG when the reconstructed name would not fit.
--- fs/ceph/crypto.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ceph/crypto.c +8 -0
@@ -313,6 +313,7 @@ int ceph_fname_to_usr(const struct ceph_fname *fname, unsigned char *tname,struct fscrypt_str iname;char *name = fname->name;int name_len = fname->name_len; +int dst_len;int ret;if (WARN_ON_ONCE (tname &&is_vmalloc_addr (tname)))
@@ -387,6 +388,9 @@ int ceph_fname_to_usr(const struct ceph_fname *fname, unsigned char *tname, iname.len = fname->ctext_len; } +/* oname->len is overwritten by the decryption below */ + dst_len = oname->len; + _oname.name =unlikely (is_vmalloc_addr (oname->name)) ? tname : oname->name; _oname.len = oname->len;
@@ -403,6 +407,10 @@ int ceph_fname_to_usr(const struct ceph_fname *fname, unsigned char *tname, name_len =snprintf (tmp_buf,sizeof (tmp_buf),"_%.*s_%llu" , oname->len, oname->name, dir->i_ino); +if (name_len > dst_len) { + ret = -ENAMETOOLONG ; + goto out; + }memcpy (oname->name, tmp_buf, name_len); oname->len = name_len; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1116/1257 ceph: fix out-of-bounds read in ceph_netfs_issue_op_inline()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guanglei Zhu <[email protected]>
[ Upstream commit cdbb60f00f87297a9db2652847dfc0eaaf3c45aa ]
The read offset is validated against i_size but never against inline_len, and the two fields come from the MDS independently. When a read starts past the end of the inline data, the subtraction
len = min_t(size_t, iinfo->inline_len - subreq->start, subreq->len);
underflows and min_t() ends up with subreq->len, so copy_to_iter() reads past the end of the inline buffer straight into the user buffer. A malicious or buggy MDS reporting a short inline payload together with an inflated i_size can thus leak kernel heap memory to userspace.
Bail out with -ENODATA when the offset is not within the inline data.
--- fs/ceph/addr.c | 6 ++++++ 1 file changed, 6 insertions(+)
fs/ceph/addr.c +6 -0
@@ -322,6 +322,12 @@ static bool ceph_netfs_issue_op_inline(struct netfs_io_subrequest *subreq)return false; } +if (subreq->start >= iinfo->inline_len) { +ceph_mdsc_put_request (req); + err = -ENODATA ; + goto out; + } + len =min_t (size_t, iinfo->inline_len - subreq->start, subreq->len); err =copy_to_iter (iinfo->inline_data + subreq->start, len, &subreq->io_iter);if (err ==0 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1117/1257 ceph: reject mdsmaps that claim more than CEPH_MAX_MDS ranks
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
[ Upstream commit c1742590d2b2fc5fb217e1a9b520108f1fe282e5 ]
check_new_map() sizes its export-target bitmap from CEPH_MAX_MDS but walks it with newmap->possible_max_rank, which comes straight off the wire:ceph_mdsmap_decode() sets it to max(m_num_active_mds, m_max_mds), then overwrites it with the size of the "in" set. Neither is bounded by CEPH_MAX_MDS, only by m_info allocating, so a monitor announcing more ranks than the bitmap holds makes test_bit() read past the end of targets[]. The clear_bit() loop above indexes the same bitmap, though it is additionally bounded by mdsc->max_sessions. The map arrives on the monitor connection, which is unauthenticated in legacy msgr mode.
CEPH_MAX_MDS is a protocol constant from src/mds/mdstypes.h, and the reserved inode ranges in super.h are laid out one rank apart over that span, so a map claiming more ranks is corrupt. Reject it where the rank space is established rather than letting the count reach check_new_map().
BUG: KASAN: stack-out-of-bounds in check_new_map (fs/ceph/mds_client.c:5968) Read of size 8 at addr ffffc90000ac7798 by task kworker/1:2/127 Workqueue: ceph-msgr ceph_con_workfn Call Trace: <TASK> dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120) print_report (mm/kasan/report.c:378 mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) kasan_check_range (mm/kasan/generic.c:186 mm/kasan/generic.c:200) check_new_map (fs/ceph/mds_client.c:5968) ceph_mdsc_handle_mdsmap (fs/ceph/mds_client.c:7060) extra_mon_dispatch (fs/ceph/super.c:802) mon_dispatch (net/ceph/mon_client.c:1483) ceph_con_process_message (net/ceph/messenger.c:1424) ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430) ceph_con_workfn (net/ceph/messenger.c:1576) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) </TASK> The buggy address belongs to stack of task kworker/1:2/127 and is located at offset 288 in frame: check_new_map (fs/ceph/mds_client.c:5846) This frame has 1 object: [32, 288) 'targets'
--- fs/ceph/mdsmap.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ceph/mdsmap.c +8 -0
@@ -170,6 +170,10 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,* and the mds rank >= m_num_active_mds. */ m->possible_max_rank =max (m->m_num_active_mds, m->m_max_mds); +if (m->possible_max_rank >CEPH_MAX_MDS ) { + err = -EIO ; + goto corrupt; + } m->m_info =kzalloc_objs (*m->m_info, m->possible_max_rank,GFP_NOFS );if (!m->m_info)
@@ -316,6 +320,10 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p, {int num_laggy =0 ;ceph_decode_32_safe (p, end, n, bad_ext); +if (n >CEPH_MAX_MDS ) { + err = -EIO ; + goto corrupt; + }ceph_decode_need (p, end,sizeof (u32) * n, bad_ext);for (i =0 ; i < n; i++) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1118/1257 ceph: require the dentry lease record to cover struct ceph_mds_reply_lease
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
[ Upstream commit 7286b2ffe04d4b39b4e9884f714792589d94f316 ]
parse_reply_info_lease() reads a 32-bit struct_len off the wire and only checks that many bytes are present, without requiring struct_len to cover sizeof(struct ceph_mds_reply_lease) (10 bytes). A malicious MDS can declare a shorter record and still get the pointer published: the following *p += sizeof(**lease) overshoot is undone by *p = lend, so nothing downstream rejects the reply. ceph_fill_trace() -> update_dentry_lease() then reads 10 bytes through that pointer on any lookup on a mounted CephFS, running past the end of the message front.
Require the record to cover the structure, matching the sibling parse_reply_info_dir(). A conforming MDS always encodes the full 10 bytes.
BUG: KASAN: slab-out-of-bounds in __update_dentry_lease.constprop.0 (fs/ceph/inode.c:1459) Read of size 4 at addr ffff888026c63d65 by task kworker/0:3/2366 Workqueue: ceph-msgr ceph_con_workfn Call Trace: __update_dentry_lease.constprop.0 (fs/ceph/inode.c:1459) ceph_fill_trace (fs/ceph/inode.c:1474 fs/ceph/inode.c:1823) mds_dispatch (fs/ceph/mds_client.c:4229 fs/ceph/mds_client.c:7225) ceph_con_process_message (net/ceph/messenger.c:1424) ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430) ceph_con_workfn (net/ceph/messenger.c:1576) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
The buggy address is located 357 bytes inside of
allocated 360-byte region [ffff888026c63c00, ffff888026c63d68)
--- fs/ceph/mds_client.c | 2 ++ 1 file changed, 2 insertions(+)
fs/ceph/mds_client.c +2 -0
@@ -380,6 +380,8 @@ static int parse_reply_info_lease(void **p, void *end, lend = *p + struct_len;ceph_decode_need (p, end, struct_len, bad); +if (struct_len <sizeof (**lease)) + goto bad; *lease = *p; *p +=sizeof (**lease);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1119/1257 libceph: only set read_from_replica on read requests
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiubo Li <[email protected]>
[ Upstream commit d6c7a5fcd08873c45a2dcd645a0690fd1443af50 ]
ceph_osdc_alloc_request() ORs the mount option's read_from_replica flag into r_flags for every request, writes included. The flag is meant for reads: calc_target() skips the replica choice for any request that has CEPH_OSD_FLAG_WRITE, and the OSDs only know BALANCE_READS on read ops. Sending it on writes is at best ignored; with read_from_replica=balance a buffered write that fell back to ceph_sync_write() after losing BUFFER to a revoke failed with -EIO, while the same run without the option works fine.
Gate the flag on CEPH_OSD_FLAG_READ.
--- net/ceph/osd_client.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
net/ceph/osd_client.c +3 -1
@@ -1108,7 +1108,9 @@ struct ceph_osd_request *ceph_osdc_new_request(struct ceph_osd_client *osdc, req->r_base_oloc.pool = layout->pool_id; req->r_base_oloc.pool_ns =ceph_try_get_string (layout->pool_ns);ceph_oid_printf (&req->r_base_oid,"%llx.%08llx" , vino.ino, objnum); - req->r_flags = flags | osdc->client->options->read_from_replica; + req->r_flags = flags; +if (flags &CEPH_OSD_FLAG_READ ) + req->r_flags |= osdc->client->options->read_from_replica; req->r_snapid = vino.snap;if (flags &CEPH_OSD_FLAG_WRITE )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1120/1257 libceph: Fix unsafe decode in ceph_redirect_decode()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Raphael Zimmer <[email protected]>
[ Upstream commit 0405670e50f213594366ab7eddc07002bd7f84c0 ]
ceph_redirect_decode handles unchecked data received over the network from an OSD. Currently, there is only a bounds check covering the first three decode operations. After decoding the first len field from the message, the only remaining check ensures there is enough buffer space to hold len bytes. However, there is no guarantee that this value is large enough to hold the subsequently decoded fields. The decoding of the second len field is missing an explicit bounds check. Consequently, a corrupted message can trigger an out-of-bounds read.
This patch fixes the issue by switching the decoding from ceph_decode_32() to the bounds-checked version ceph_decode_32_safe().
--- net/ceph/osd_client.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ceph/osd_client.c +1 -1
@@ -3639,7 +3639,7 @@ static int ceph_redirect_decode(void **p, void *end,if (ret) goto out; - len =ceph_decode_32 (p); +ceph_decode_32_safe (p, end, len, e_inval);if (len >0 ) {pr_warn ("ceph_request_redirect::object_name is set\n" ); goto e_inval;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1121/1257 libceph: Fix multiple unsafe decodes in ceph_oloc_decode()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Raphael Zimmer <[email protected]>
[ Upstream commit 10655007b9b679e46a9e383202c7bb791e5d1d13 ]
ceph_oloc_decode handles unchecked data received over the network from an OSD. Currently, there are multiple decode operations that aren't covered by any bounds check. Decoding these fields can therefore result in out-of-bounds reads if a corrupted message is received.
This patch fixes the issue by adding bounds checks covering all previously uncovered decode operations.
[ idryomov: use ceph_decode_64_safe() for hash ]
--- net/ceph/osd_client.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
net/ceph/osd_client.c +5 -2
@@ -3567,6 +3567,7 @@ static int ceph_oloc_decode(void **p, void *end,ceph_decode_need (p, end, len, e_inval); struct_end = *p + len; +ceph_decode_need (p, end,8 +4 +4 , e_inval); oloc->pool =ceph_decode_64 (p); *p +=4 ;/* skip preferred */
@@ -3579,7 +3580,7 @@ static int ceph_oloc_decode(void **p, void *end,if (struct_v >=5 ) {bool changed = false; - len =ceph_decode_32 (p); +ceph_decode_32_safe (p, end, len, e_inval);if (len >0 ) {ceph_decode_need (p, end, len, e_inval); if (!oloc->pool_ns ||
@@ -3598,7 +3599,9 @@ static int ceph_oloc_decode(void **p, void *end, }if (struct_v >=6 ) { -s64 hash =ceph_decode_64 (p); +s64 hash; + +ceph_decode_64_safe (p, end, hash, e_inval);if (hash !=-1 ) {pr_warn ("ceph_object_locator::hash is set\n" ); goto e_inval;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1122/1257 libceph: reject mismatched CRUSH weight-set sizes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Hoffmann <[email protected]>
[ Upstream commit d8fc89b5bfe4cb3aebe4c8a818247d11291b841c ]
A CEPH_MSG_OSD_MAP message can contain CRUSH choose args with replacement weight vectors for straw2 buckets. decode_choose_args() validates the optional IDs vector against the referenced bucket, but does not validate the size of any replacement-weight vector.
The CRUSH mapper assumes that each replacement vector has exactly as many entries as the bucket. A zero-length vector for a nonempty bucket makes bucket_straw2_choose() dereference NULL, while a shorter nonzero vector causes an out-of-bounds read. An authenticated monitor or OSD can deliver such a map and crash a kernel client when it performs placement for an ordinary request.
Reject a nonempty collection of weight sets for an absent bucket and require every replacement-weight vector to match its bucket size.
--- net/ceph/osdmap.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
net/ceph/osdmap.c +12 -2
@@ -376,7 +376,9 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c)ceph_decode_32_safe (p, end, num_buckets, e_inval);while (num_buckets--) {struct crush_choose_arg *arg; +struct crush_bucket *bucket;u32 bucket_index; +u32 i;ceph_decode_32_safe (p, end, bucket_index, e_inval);if (bucket_index >= arg_map->size)
@@ -387,10 +389,18 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c)if (ret) goto fail; + bucket = c->buckets[bucket_index];if (arg->ids_size && - (!c->buckets[bucket_index] || - arg->ids_size != c->buckets[bucket_index]->size)) + (!bucket || arg->ids_size != bucket->size)) goto e_inval; + +if (arg->weight_set_size && !bucket) + goto e_inval; + +for (i =0 ; i < arg->weight_set_size; i++) { +if (arg->weight_set[i].size != bucket->size) + goto e_inval; + } }if (!__insert_choose_arg_map (&c->choose_args, arg_map)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1123/1257 libceph: reject an initial monmap with no monitors
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yogesh Gaur <[email protected]>
[ Upstream commit 94dbce2ae4fdb57bdb53ffa3456da777a5cfb981 ]
build_initial_monmap() takes the monitor count straight from ceph_options::num_mon and builds a monmap with that many entries without checking that there is at least one. ceph_parse_ips() writes *count only after it has parsed an address successfully, so a ceph_options that went through a failed parse still has num_mon == 0 and the resulting monmap has no monitors in it at all.
The first thing the client does with that monmap is open a session, and pick_new_mon() asserts the invariant that it is non-empty:
kernel BUG at net/ceph/mon_client.c:211!
RIP: 0010:pick_new_mon net/ceph/mon_client.c:211 [inline] RIP: 0010:__open_session+0x60f/0x740 net/ceph/mon_client.c:245 Call Trace: ceph_monc_open_session+0x46/0x60 net/ceph/mon_client.c:534 __ceph_open_session+0x135/0x590 net/ceph/ceph_common.c:798 ceph_real_mount fs/ceph/super.c:1173 [inline] ceph_get_tree+0xd98/0x1fd0 fs/ceph/super.c:1362 vfs_get_tree+0x92/0x320 fs/super.c:1947 vfs_cmd_create+0xd7/0x2a0 fs/fsopen.c:231 __do_sys_fsconfig+0x55a/0xcb0 fs/fsopen.c:463
The reproducer gets there through the new device syntax: an fsconfig() mon_addr= that does not resolve ("libceph: resolve '127.0.0.' (ret=-3):
failed") leaves fsopt->mon_addr set but num_mon at 0, so the "No monitor address" check in ceph_get_tree() passes and the mount proceeds with an empty monmap. The next patch stops that string from being kept, but the assertion should not be reachable from a mount option in the first place.
Commit 40480eee361e ("libceph: Reject monmaps advertising zero monitors") made the same BUG_ON() unreachable from the wire by rejecting num_mon == 0 in ceph_monmap_decode(). Apply the same rule to the initial monmap, which is the only other way one gets built, and fail the mount with -EINVAL rather than assert afterwards.
--- net/ceph/mon_client.c | 3 +++ 1 file changed, 3 insertions(+)
net/ceph/mon_client.c +3 -0
@@ -1141,6 +1141,9 @@ static int build_initial_monmap(struct ceph_mon_client *monc)int num_mon = opt->num_mon;int i; +if (num_mon <1 || num_mon >CEPH_MAX_MON ) +return -EINVAL ; +/* build initial monmap */ monc->monmap =kzalloc_flex (*monc->monmap, mon_inst, num_mon);if (!monc->monmap)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1124/1257 ceph: fix integer overflow in the snap trace bounds check
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
[ Upstream commit b3bf89767e3ca9506f1c7167cac97c41ec254d42 ]
ceph_update_snap_trace() bounds the two encoded snapid arrays that follow a struct ceph_mds_snap_realm with sizeof(u64) * (num_snaps + num_prior_parent_snaps). Both counts come straight off the wire as __le32, so the addition is evaluated in unsigned int and wraps before sizeof(u64) promotes it to size_t: an MDS sending num_snaps = 1 and num_prior_parent_snaps = 0xffffffff makes the sum zero and the check degenerates to ceph_decode_need(&p, e, 0, bad), which always passes. dup_array() then reads num_snaps * 8 bytes past the end of the message front, which ceph_msg_new2() allocates at exactly front_len bytes. An unsolicited CEPH_MSG_CLIENT_SNAP reaches this from a malicious or compromised MDS with no client-side action, as do the snaptraces carried in an MDS reply and in a cap import.
Compute the length with size_add()/size_mul() so it saturates at SIZE_MAX instead of wrapping, in the style fs/ceph/mdsmap.c already uses for num_export_targets.
BUG: KASAN: slab-out-of-bounds in dup_array (include/linux/unaligned.h:28 fs/ceph/snap.c:500) Read of size 8 at addr ffff8880102a16c8 by task kworker/1:2/129 Workqueue: ceph-msgr ceph_con_workfn Call Trace: dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120) print_report (mm/kasan/report.c:378 mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) dup_array (include/linux/unaligned.h:28 fs/ceph/snap.c:500) ceph_update_snap_trace (fs/ceph/snap.c:836) ceph_handle_snap (fs/ceph/snap.c:1155) mds_dispatch (fs/ceph/mds_client.c:7234) ceph_con_process_message (net/ceph/messenger.c:1424) ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430) ceph_con_workfn (net/ceph/messenger.c:1576) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 0 bytes to the right of allocated 72-byte region [ffff8880102a1680, ffff8880102a16c8)
--- fs/ceph/snap.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
fs/ceph/snap.c +5 -2
@@ -788,6 +788,7 @@ int ceph_update_snap_trace(struct ceph_mds_client *mdsc,struct ceph_snap_realm *first_realm =NULL ;struct ceph_snap_realm *realm_to_rebuild =NULL ;struct ceph_client *client = mdsc->fsc->client; +size_t snaps_len;int rebuild_snapcs;int err = -ENOMEM ;int ret;
@@ -802,8 +803,10 @@ int ceph_update_snap_trace(struct ceph_mds_client *mdsc,ceph_decode_need (&p, e,sizeof (*ri), bad); ri = p; p +=sizeof (*ri); -ceph_decode_need (&p, e,sizeof (u64)*(le32_to_cpu (ri->num_snaps) + -le32_to_cpu (ri->num_prior_parent_snaps)), bad); + snaps_len =size_mul (size_add (le32_to_cpu (ri->num_snaps), +le32_to_cpu (ri->num_prior_parent_snaps)), +sizeof (u64)); +ceph_decode_need (&p, e, snaps_len, bad); snaps = p; p +=sizeof (u64) *le32_to_cpu (ri->num_snaps); prior_parent_snaps = p;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1125/1257 ceph: Fix xattr buffer leak in __send_cap()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
[ Upstream commit e51cf76e7275d1bb5ad2d529bb00feade632dadc ]
__prep_cap() takes a reference on the xattr blob via ceph_buffer_get() and also grabs a reference to the old xattr blob returned by __ceph_build_xattrs_blob(). These references are normally dropped in __send_cap() after the cap message has been sent, but when ceph_msg_new() fails, __send_cap() requeues the cap and returns early without dropping them, leaking both buffers on every allocation failure.
Release arg->old_xattr_buf and arg->xattr_buf on the ceph_msg_new() failure path before returning.
--- fs/ceph/caps.c | 2 ++ 1 file changed, 2 insertions(+)
fs/ceph/caps.c +2 -0
@@ -1569,6 +1569,8 @@ static void __send_cap(struct cap_msg_args *arg, struct ceph_inode_info *ci)spin_lock (&ci->i_ceph_lock);__cap_delay_requeue (arg->session->s_mdsc, ci);spin_unlock (&ci->i_ceph_lock); +ceph_buffer_put (arg->old_xattr_buf); +ceph_buffer_put (arg->xattr_buf);return ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1126/1257 ceph: Fix mds session leak in __open_export_target_session()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
[ Upstream commit 6c80207392fdb86107d7acbdbf4c86cac38da1af ]
__open_export_target_session() holds a reference on the target session, either from __ceph_lookup_mds_session() or from register_session(), which the caller is expected to drop. When __open_session() fails, the helper returns ERR_PTR(ret) without dropping that reference, leaking one session reference on every open failure.
Drop the session reference before returning the error.
--- fs/ceph/mds_client.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/ceph/mds_client.c +3 -1
@@ -1805,8 +1805,10 @@ __open_export_target_session(struct ceph_mds_client *mdsc, int target)if (session->s_state ==CEPH_MDS_SESSION_NEW || session->s_state ==CEPH_MDS_SESSION_CLOSING ) { ret =__open_session (mdsc, session); -if (ret) +if (ret) { +ceph_put_mds_session (session);return ERR_PTR (ret); + } }return session;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1127/1257 ceph: fix 32-bit overflow in readdir reply count check
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
[ Upstream commit 52913831ba56efceaafd80b501d68fa00f79bde6 ]
parse_reply_info_readdir() checks how many entries are in a readdir reply by computing the end pointer of the decoded array. That pointer addition can wrap on 32-bit kernels and let an oversized count pass the check. For example, a count of 0x40000000 with 156-byte entries wraps to a zero offset, so the decoder can write past the preallocated buffer.
Check the count against the number of entries that fit in the allocation before publishing dir_nr. Reject oversized replies through the existing error path.
--- fs/ceph/mds_client.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
fs/ceph/mds_client.c +1 -3
@@ -481,10 +481,8 @@ static int parse_reply_info_readdir(void **p, void *end, goto done;BUG_ON (!info->dir_entries); -if ((unsigned long )(info->dir_entries + num) > - (unsigned long )info->dir_entries + info->dir_buf_size) { +if (num > info->dir_buf_size /sizeof (*info->dir_entries)) {pr_err_client (cl,"dir contents are larger than expected\n" ); -WARN_ON (1 ); goto bad; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1128/1257 libceph: fix out-of-bounds reads from repeated CRUSH bucket entries
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
[ Upstream commit 569a9bb1e5615c2b88b8d76f03a4ab82e65a673e ]
decode_choose_arg() assumes that its destination is zero-initialized. Although decode_choose_args() zeroes the argument array, it does not reject a repeated bucket_index and can decode into an already populated entry.
Repeating a bucket with weight_set_size=0 preserves its existing weight_set pointer but clears the count. Placement then reads weight_set[-1].weights and dereferences the resulting pointer.
A malformed monitor OSDMap triggers this during RBD placement:
BUG: KASAN: slab-out-of-bounds in crush_bucket_choose+0xdd1/0xf90 Read of size 8 at addr ffff88800290df70 by task init/75
Reject populated arguments before decoding another entry, so the error path can free their original allocations.
--- net/ceph/osdmap.c | 2 ++ 1 file changed, 2 insertions(+)
net/ceph/osdmap.c +2 -0
@@ -385,6 +385,8 @@ static int decode_choose_args(void **p, void *end, struct crush_map *c) goto e_inval; arg = &arg_map->args[bucket_index]; +if (arg->ids || arg->weight_set) + goto e_inval; ret =decode_choose_arg (p, end, arg);if (ret) goto fail;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1129/1257 libceph: initialize CRUSH choose argument weights
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darong Lu <[email protected]>
[ Upstream commit c3a995ff0782587789333c621e1f6bd5e574371e ]
Initialize the CRUSH choose argument weight-set array before decoding so entries start in a defined state while the decoder fills them.
--- net/ceph/osdmap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ceph/osdmap.c +1 -1
@@ -319,7 +319,7 @@ static int decode_choose_arg(void **p, void *end, struct crush_choose_arg *arg)if (arg->weight_set_size) {u32 i; - arg->weight_set =kmalloc_objs (*arg->weight_set, + arg->weight_set =kzalloc_objs (*arg->weight_set, arg->weight_set_size,GFP_NOIO );if (!arg->weight_set)return -ENOMEM ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1130/1257 ceph: clamp MDS reply result code to the errno range
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuanfu Xie <[email protected]>
[ Upstream commit ec8d583469ed64b4973192a21b5a41c33219721f ]
ceph_mdsc_wait_request() returns the reply head result code of the MDS request to its callers as a plain int errno. The value is a server-controlled u32 and nothing checks that it actually is an errno; several callers pass it straight to ERR_PTR(), e.g. ceph_finish_lookup() on the atomic open path:
err = ceph_mdsc_wait_request(...) /* e.g. +0x50fc00 */ ... if (err) dentry = ERR_PTR(err);
IS_ERR() only recognizes the [-MAX_ERRNO, -1] window, so an out-of-range value is not caught anywhere and survives as a "struct dentry *". On the open path the positive error travels ceph_finish_lookup() -> ceph_atomic_open() -> ERR_PTR() in fs/namei.c's atomic_open() wrapper -> step_into(), which dereferences it as a dentry and oopses (mainline 7.3-rc3-135-g4982d3552a3b, the value in R12 is the server-supplied result):
BUG: KASAN: probably user-memory-access in range [0x000000000050fc00-0x000000000050fc07] RIP: 0010:step_into_slowpath+0x3e3/0xe60 R12: 000000000050fc00 Call Trace: <TASK> ? __pfx_ceph_atomic_open+0x10/0x10 path_openat+0xf41/0x2440 do_file_open+0x228/0x480 do_sys_openat2+0x103/0x1d0 __x64_sys_openat+0x141/0x200 do_syscall_64+0xe8/0x4f0 entry_SYSCALL_64_after_hwframe+0x77/0x79 </TASK>
(0xdffffc00000a1f80 in the full report is the KASAN shadow of 0x50fc00; without KASAN the raw value is read.) Values with the top bit set fare no better: 0xd8000000 sign-extends through the int conversion into the kernel address range and takes a page fault instead.
Clamp the result at the single read and return -EIO for anything outside the errno range, which is what a malformed reply means there. net/9p does the same to server errno values with safe_errno(). This is the path the reported crash takes; the other readers of head->result, including the ceph_async_create_cb() and ceph_async_unlink_cb() callbacks, are not covered by this patch.
Each of the six crashing opens was run on a build of 7.3-rc3-135-g4982d3552a3bf with only this change applied: it crashes the unpatched kernel on the first openat() (verified on the same tree without the patch), and with the patch the open fails cleanly without an oops. A few hundred normal file operations on the patched kernel also completed without a crash; valid errno values pass through unchanged.
--- fs/ceph/mds_client.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ceph/mds_client.c +8 -0
@@ -3987,6 +3987,14 @@ int ceph_mdsc_wait_request(struct ceph_mds_client *mdsc,/* only abort if we didn't race with a real reply */ if (test_bit (CEPH_MDS_R_GOT_RESULT , &req->r_req_flags)) { err =le32_to_cpu (req->r_reply_info.head->result); +if (err >0 || err < -MAX_ERRNO ) { +/* +* The result is server-controlled. Values outside +* the errno range are turned into bogus pointers by +* the ERR_PTR() users among the callers. +*/ + err = -EIO ; + } }else if (err <0 ) {doutc (cl,"aborted request %lld with %d\n" , req->r_tid, err);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1131/1257 ceph: dont fail write_begin with -EAGAIN after flushing old snapc
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Venky Shankar <[email protected]>
[ Upstream commit 6ff7920ca78f6edcabc26c63d20f681d938027c7 ]
When ceph_netfs_check_write_begin() finds the folio dirty in an older snap context, it drops the folio, waits for that snap context to be flushed and then returns -EAGAIN so that the write is retried.
However, since commit fac47b43c760 ("netfs: do not unlock and put the folio twice"), netfs_write_begin() retries only when ->check_write_begin() returns 0 with *foliop cleared -- every error, -EAGAIN included, is returned as is. The -EAGAIN thus propagates up to write(2), which fails with "Resource temporarily unavailable" once the dirty data has been flushed, rather than being retried.
This is easily hit by buffered writers rewriting dirty pages while snapshots are being taken, e.g. a kernel build linking vmlinux into a directory under a snapshot schedule:
ld: final link failed: Resource temporarily unavailable
Return the wait_event_killable() result as is so that netfs re-gets the folio and retries on success.
--- fs/ceph/addr.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/ceph/addr.c +6 -1
@@ -1895,7 +1895,12 @@ static int ceph_netfs_check_write_begin(struct file *file, loff_t pos, unsigned r =wait_event_killable (ci->i_cap_wq,context_is_writeable_or_written (inode, snapc));ceph_put_snap_context (snapc); -return r ==0 ? -EAGAIN : r; +/* +* *foliop is cleared, so a return of 0 makes +* netfs_write_begin() grab the folio again and call us again +* to recheck it. Any error (fatal signal) fails the write. +*/ +return r; }return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1132/1257 ceph: validate fscrypt auth blob length
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: sung byeongchan <[email protected]>
[ Upstream commit bc418e234e5be14b97dec90e84a680e615b4134e ]
ceph_crypt_get_context() trusts cfa_blob_len after checking only that the inode-owned fscrypt_auth allocation contains the fixed header and one byte. An MDS can therefore place a larger inner length in a shorter outer object, causing memcpy() to read beyond the allocation when a caller requests the encryption nonce.
Require the complete blob to fit in the inode-owned allocation before using the inner length.
On the tested baseline, the malformed reply produced the same KASAN slab-out-of-bounds read twice. An ordinary UID obtained sixteen wire-absent SLUB redzone bytes in two non-KASAN production-path runs. The input was rejected twice after this change, while a complete context still worked.
--- fs/ceph/crypto.c | 3 +++ 1 file changed, 3 insertions(+)
fs/ceph/crypto.c +3 -0
@@ -30,6 +30,9 @@ static int ceph_crypt_get_context(struct inode *inode, void *ctx, size_t len)return -ENOBUFS ; ctxlen =le32_to_cpu (cfa->cfa_blob_len); +if (ctxlen > ci->fscrypt_auth_len - + offsetof(struct ceph_fscrypt_auth , cfa_blob)) +return -ENOBUFS ;if (len < ctxlen)return -ERANGE ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1133/1257 ceph: bound name skips in ceph_mdsmap_decode() by the message end
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: sung byeongchan <[email protected]>
[ Upstream commit 7f702e1703c9648fcb02a217d66c880d00417150 ]
ceph_mdsmap_decode() reads two remote u32 name lengths and advances its parser cursor without checking that either string remains in the message. On a 32-bit client, a sufficiently large length can wrap the cursor below end. The following numerical bounds check then succeeds and dereferences the wrapped address.
Use ceph_decode_skip_n() for both names so the remaining bytes are checked before the cursor advances.
The issue produced a page fault in ceph_mdsmap_decode twice on the tested i386 baseline. The same frame was rejected without a fault twice after this change, while a normal MDSMap continued to be accepted.
--- fs/ceph/mdsmap.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ceph/mdsmap.c +2 -2
@@ -209,7 +209,7 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p,ceph_decode_need (p, end,sizeof (u64) +sizeof (u32), bad); *p +=sizeof (u64); namelen =ceph_decode_32 (p);/* skip mds name */ - *p += namelen; +ceph_decode_skip_n (p, end, namelen, bad);ceph_decode_32_safe (p, end, mds, bad);ceph_decode_32_safe (p, end, inc, bad);
@@ -227,7 +227,7 @@ struct ceph_mdsmap *ceph_mdsmap_decode(struct ceph_mds_client *mdsc, void **p, laggy = laggy_since.tv_sec !=0 || laggy_since.tv_nsec !=0 ; *p +=sizeof (u32);ceph_decode_32_safe (p, end, namelen, bad); - *p += namelen; +ceph_decode_skip_n (p, end, namelen, bad);if (info_v >=2 ) {ceph_decode_32_safe (p, end, num_export_targets, bad); export_targets_len = size_mul(num_export_targets,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1134/1257 ceph: validate MDS reply fragtree split array length
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: sung byeongchan <[email protected]>
[ Upstream commit 8cab7e7461f81ea1e0fd45082b50bb3c04c0bb10 ]
parse_reply_info_in() advances over the fragtree split array using an unchecked count multiplication. On a 32-bit client, nsplits=0x20000000 wraps the byte length to zero, so the reply is accepted and ceph_fill_fragtree() sorts far beyond the message front.
Compute the split length with size_mul() and require the complete array to remain in the inode record before advancing the cursor.
The malformed reply faulted in frag_tree_split_cmp() twice on the tested i386 baseline. It was rejected without a fault twice after this change, while a normal reply and a one-split control remained functional.
--- fs/ceph/mds_client.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ceph/mds_client.c +7 -3
@@ -15,6 +15,7 @@#include <linux/ktime.h> #include <linux/bitmap.h> #include <linux/mnt_idmapping.h> +#include <linux/overflow.h> #include "super.h" #include "mds_client.h"
@@ -120,6 +121,7 @@ static int parse_reply_info_in(void **p, void *end, struct ceph_mds_client *mdsc) {int err =0 ; +size_t splits_len;u8 struct_v =0 ;u8 struct_compat =0 ;u32 struct_len =0 ;
@@ -140,9 +142,11 @@ static int parse_reply_info_in(void **p, void *end,ceph_decode_need (p, end,sizeof (struct ceph_mds_reply_inode ), bad); info->in = *p; - *p +=sizeof (struct ceph_mds_reply_inode ) + -sizeof (*info->in->fragtree.splits) * -le32_to_cpu (info->in->fragtree.nsplits); + splits_len =size_mul (sizeof (*info->in->fragtree.splits), +le32_to_cpu (info->in->fragtree.nsplits)); + *p +=sizeof (struct ceph_mds_reply_inode ); +ceph_decode_need (p, end, splits_len, bad); + *p += splits_len;ceph_decode_32_safe (p, end, info->symlink_len, bad);ceph_decode_need (p, end, info->symlink_len, bad);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1135/1257 ceph: validate encoded xattr name lengths
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: sung byeongchan <[email protected]>
[ Upstream commit 166375898d29fea050a9abec855da6075050d5c9 ]
__build_xattrs() advances over an MDS-provided name length before checking that the name remains in the encoded xattr blob. On 32-bit clients, UINT_MAX wraps the cursor and is stored as a negative internal name length. A later ordinary listxattr() converts it back to a UINT_MAX memcpy size and corrupts kernel memory.
Check the name range before advancing and reject name, value, or aggregate sizes that overflow the signed internal accounting.
The malformed blob corrupted kernel state in two baseline boots. It was rejected cleanly twice with this change, while normal and length-only controls remained safe.
--- fs/ceph/xattr.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
fs/ceph/xattr.c +10 -0
@@ -11,6 +11,7 @@#include <linux/security.h> #include <linux/posix_acl_xattr.h> #include <linux/slab.h> +#include <linux/overflow.h> #define XATTR_CEPH_PREFIX "ceph."#define XATTR_CEPH_PREFIX_LEN (sizeof (XATTR_CEPH_PREFIX) - 1)
@@ -843,14 +844,23 @@ static int __build_xattrs(struct inode *inode) } err = -EIO ;while (numattr--) { +int names_size, vals_size; +ceph_decode_32_safe (&p, end, len, bad); namelen = len; name = p; +ceph_decode_need (&p, end, namelen, bad); p += len;ceph_decode_32_safe (&p, end, len, bad);ceph_decode_need (&p, end, len, bad); val = p; p += len; +if (namelen >INT_MAX || len >INT_MAX || +check_add_overflow (ci->i_xattrs.names_size, + (int )namelen, &names_size) || +check_add_overflow (ci->i_xattrs.vals_size, + (int )len, &vals_size)) + goto bad; err =__set_xattr (ci, name, namelen, val, len,0 ,0 , &xattrs[numattr]);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1136/1257 ceph: fix uninitialized err in ceph_netfs_issue_read()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Markuze <[email protected]>
[ Upstream commit 823d21c78453fcdf58dbd8ecefbb41f4f3eb6540 ]
ceph_netfs_issue_read() declares err without an initializer. On the unencrypted, non-sparse success path nothing assigns it, then the
out: label does if (err) netfs_read_subreq_terminated(subreq).
With CONFIG_INIT_STACK_ALL_PATTERN, err is 0xaaaaaaaa (nonzero), so the subrequest is terminated while the OSD READ is still in flight. netfs then frees the rolling buffer that the OSD iterator still points at, causing a KASAN UAF / oops, and finish_netfs_read() terminates the same subrequest a second time. CONFIG_INIT_STACK_ALL_ZERO hides it because err happens to be 0.
Restore the err = 0 initializer so a successful submit leaves completion to finish_netfs_read() only.
--- fs/ceph/addr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ceph/addr.c +1 -1
@@ -370,7 +370,7 @@ static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq)struct ceph_client *cl = fsc->client;struct ceph_osd_request *req =NULL ;struct ceph_vino vino =ceph_vino (inode); -int err; +int err =0 ;u64 len;bool sparse =IS_ENCRYPTED (inode) ||ceph_test_mount_opt (fsc,SPARSEREAD );u64 off = subreq->start;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1137/1257 f2fs: fix to update superblock crc in sanity_check_area_boundary()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chao Yu <[email protected]>
[ Upstream commit f8f956c7ec8c0285d7a80bed497d2f7adcbded15 ]
This patch fixes the bug reported by Sashiko:
We should update superblock crc along w/ raw_super->segment_count in sanity_check_area_boundary() if sb_checksum feature is enabled.
--- fs/f2fs/super.c | 6 ++++++ 1 file changed, 6 insertions(+)
fs/f2fs/super.c +6 -0
@@ -4047,6 +4047,12 @@ static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi,/* fix in-memory information all the time */ raw_super->segment_count =cpu_to_le32 ((main_end_blkaddr - segment0_blkaddr) >> log_blocks_per_seg); +if (__F2FS_HAS_FEATURE (raw_super,F2FS_FEATURE_SB_CHKSUM )) { +__u32 crc =f2fs_crc32 (raw_super, + offsetof(struct f2fs_super_block , crc)); + + raw_super->crc =cpu_to_le32 (crc); + }if (f2fs_readonly (sb) ||f2fs_hw_is_readonly (sbi)) {set_sbi_flag (sbi,SBI_NEED_SB_WRITE );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1138/1257 ASoC: qcom: qdsp6: q6afe: fix clk vote response type mismatch
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Val Packett <[email protected]>
[ Upstream commit f3c7bee984aa0ba2b48a44e16a6f3ec2c27f851e ]
The response sent by the firmware when requesting a clock vote (opcode AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST) does not actually have the same opcode + status payload as APR_BASIC_RSP_RESULT. Rather, it returns one single u32 which is the client_handle that must be used in future unvote requests for the same clock.
As a result of this type confusion, the status returned by the callback to q6afe_vote_lpass_core_hw was actually an out-of-bounds read. It was only interpreted as success (0) most of the time due to luck, but there are some reports of random errors such as:
[ 20.961100] qcom-q6afe aprsvc:service:4:4: AFE failed to vote (3) [ 20.961131] Failed to prepare clk 'core': -110
Fix by correctly interpreting the response as a single u32, and actually store it as the client_handle to ensure unvote would work correctly.
--- sound/soc/qcom/qdsp6/q6afe.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
sound/soc/qcom/qdsp6/q6afe.c +8 -2
@@ -393,6 +393,7 @@ struct q6afe {struct q6core_svc_api_info ainfo;struct mutex lock;struct aprv2_ibasic_rsp_result_t result; +uint32_t vote_result;wait_queue_head_t wait;struct list_head port_list;spinlock_t port_list_lock;
@@ -1010,13 +1011,14 @@ static int q6afe_callback(struct apr_device *adev, const struct apr_resp_pkt *daconst struct aprv2_ibasic_rsp_result_t *res;const struct apr_hdr *hdr = &data->hdr;struct q6afe_port *port; +uint32_t *vote_res;if (!data->payload_size)return 0 ; - res = data->payload;switch (hdr->opcode) {case APR_BASIC_RSP_RESULT : { + res = data->payload;if (res->status) {dev_err (afe->dev,"cmd = 0x%x returned error = 0x%x\n" , res->opcode, res->status);
@@ -1043,8 +1045,10 @@ static int q6afe_callback(struct apr_device *adev, const struct apr_resp_pkt *da }break ;case AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST : + vote_res = data->payload; afe->result.opcode = hdr->opcode; - afe->result.status = res->status; + afe->result.status =0 ; + afe->vote_result = *vote_res;wake_up (&afe->wait);break ;default :
@@ -1955,6 +1959,8 @@ int q6afe_vote_lpass_core_hw(struct device *dev, uint32_t hw_block_id, AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST);if (ret)dev_err (afe->dev,"AFE failed to vote (%d)\n" , hw_block_id); +else + *client_handle = afe->vote_result;return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1139/1257 ASoC: qcom: q6apm: Fix unmap regions response handling
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit 4b832a2af523cbf857a977414c0f07d7f90a4c9d ]
The DSP acknowledges APM_CMD_SHARED_MEM_UNMAP_REGIONS with a GPR_BASIC_RSP_RESULT packet whose payload carries the acknowledged opcode and the status. apm_callback() stores hdr->opcode, i.e. GPR_BASIC_RSP_RESULT itself, as the result opcode, so audioreach_send_cmd_sync(), which waits for 0x0100100d, never sees a match and gives up after five seconds even though the DSP has already processed the command:
qcom-apm gprsvc:service:2:1: CMD timeout for [100100d] opcode
Each mapped graph costs a five second stall on unmap, and the forced status of 0 also hides real DSP failures from the caller.
Record the opcode and status from the response payload, like the other basic-result commands do, and only drop the cached mapping handle when the DSP reports success.
--- sound/soc/qcom/qdsp6/q6apm.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-)
sound/soc/qcom/qdsp6/q6apm.c +6 -7
@@ -953,16 +953,15 @@ static int apm_callback(const struct gpr_resp_pkt *data, void *priv, int op)wake_up (&apm->wait);break ;case APM_CMD_SHARED_MEM_UNMAP_REGIONS : - apm->result.opcode = hdr->opcode; - apm->result.status =0 ; - rsp = data->payload; + apm->result.opcode = result->opcode; + apm->result.status = result->status; +if (result->status) +dev_err (dev,"Error (%d) Processing 0x%08x cmd\n" , result->status, + result->opcode); info =idr_find (&apm->graph_info_idr, hdr->token); -if (info) +if (info && !result->status) info->mem_map_handle =0 ; -else -dev_err (dev,"Error (%d) Processing 0x%08x cmd\n" , result->status, - result->opcode);wake_up (&apm->wait);break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1140/1257 ASoC: qcom: q6apm: Clear the right handle on pos buffer unmap
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit 43c69604271d8b54c494fde70bd4a9eaab7a974d ]
Push/pull graphs map two shared-memory regions per graph, the circular buffer and the position buffer, and keep a separate DSP handle for each. The map path tags its token with APM_MMAP_TOKEN_MAP_TYPE_POS_BUF so the response lands in the right handle, but the unmap path sends a bare graph ID and the response handler always clears mem_map_handle.
Unmapping the position buffer therefore wipes the circular buffer's handle and leaves pos_buf_mem_map_handle set. A subsequent unmap of the circular buffer is skipped, leaking that DSP mapping, and a remap of the position buffer is skipped because the stale handle looks valid.
Tag the unmap token the same way as the map token and decode it in the response handler to clear the matching handle.
--- sound/soc/qcom/qdsp6/q6apm.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
sound/soc/qcom/qdsp6/q6apm.c +12 -4
@@ -327,8 +327,9 @@ static int __q6apm_unmap_memory_fixed_region(struct device *dev, unsigned int grstruct q6apm *apm =dev_get_drvdata (dev->parent);struct audioreach_graph_info *info;uint32_t mem_map_handle; +uint32_t pos_mask = is_pos_buf ?APM_MMAP_TOKEN_MAP_TYPE_POS_BUF :0 ; struct gpr_pkt *pkt __free(kfree) = audioreach_alloc_apm_cmd_pkt(sizeof(*cmd), -APM_CMD_SHARED_MEM_UNMAP_REGIONS , graph_id); +APM_CMD_SHARED_MEM_UNMAP_REGIONS , (graph_id | pos_mask));if (IS_ERR (pkt))return PTR_ERR (pkt);
@@ -959,9 +960,16 @@ static int apm_callback(const struct gpr_resp_pkt *data, void *priv, int op)dev_err (dev,"Error (%d) Processing 0x%08x cmd\n" , result->status, result->opcode); - info =idr_find (&apm->graph_info_idr, hdr->token); -if (info && !result->status) - info->mem_map_handle =0 ; + graph_id = hdr->token &APM_MMAP_TOKEN_GID_MASK ; + is_pos_buf = hdr->token &APM_MMAP_TOKEN_MAP_TYPE_POS_BUF ; + + info =idr_find (&apm->graph_info_idr, graph_id); +if (info && !result->status) { +if (is_pos_buf) + info->pos_buf_mem_map_handle =0 ; +else + info->mem_map_handle =0 ; + }wake_up (&apm->wait);break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1141/1257 ASoC: qcom: q6apm: Unmap DSP buffers before removing the topology
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Guo <[email protected]>
[ Upstream commit a51c5dd7f7fc7cdf4ae28fec4a013d8418d1cb53 ]
Since buffers are mapped once in pcm_new() and unmapped in pcm_free(), the unmap relies on the graph info still being registered. During card teardown, however, soc_cleanup_card_resources() removes the components before it frees the PCM runtimes. q6apm-audio's remove callback unloads the topology, which frees every audioreach_graph_info, so by the time q6apm_dai_pcm_free() runs the idr lookup fails and the unmap silently returns -ENODEV. The DSP keeps the old mapping.
When the card is bound again, for example after unbinding and binding any codec on it, pcm_new() maps the same buffer once more, the DSP rejects it and the front-end PCM is not created:
qcom-apm gprsvc:service:2:1: Error (1) Processing 0x0100100c cmd qcom-apm gprsvc:service:2:1: DSP returned error[100100c] 1 q6apm-dai ...: Audio Start: Buffer Allocation failed rc = -22 snd-sc8280xp sound: ASoC: can't create pcm MultiMedia1 Playback :-22
Release the circular and position buffer mappings of all graphs in q6apm_audio_remove() while the graph info still exists. The unmap helper now takes the q6apm instance directly, since it is called from the APM component rather than from a q6apm-dai child device.
--- sound/soc/qcom/qdsp6/q6apm.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-)
sound/soc/qcom/qdsp6/q6apm.c +20 -4
@@ -320,11 +320,10 @@ int q6apm_alloc_fragments(struct q6apm_graph *graph, unsigned int dir, phys_addr }EXPORT_SYMBOL_GPL (q6apm_alloc_fragments); -static int __q6apm_unmap_memory_fixed_region (struct device *dev,unsigned int graph_id, +static int __q6apm_unmap_memory_fixed_region (struct q6apm *apm,unsigned int graph_id,bool is_pos_buf) {struct apm_cmd_shared_mem_unmap_regions *cmd; -struct q6apm *apm =dev_get_drvdata (dev->parent);struct audioreach_graph_info *info;uint32_t mem_map_handle;uint32_t pos_mask = is_pos_buf ?APM_MMAP_TOKEN_MAP_TYPE_POS_BUF :0 ;
@@ -356,13 +355,15 @@ static int __q6apm_unmap_memory_fixed_region(struct device *dev, unsigned int grint q6apm_unmap_memory_fixed_region (struct device *dev,unsigned int graph_id) { -return __q6apm_unmap_memory_fixed_region (dev, graph_id, false); +return __q6apm_unmap_memory_fixed_region (dev_get_drvdata (dev->parent), + graph_id, false); }EXPORT_SYMBOL_GPL (q6apm_unmap_memory_fixed_region);int q6apm_unmap_pos_buffer (struct device *dev,unsigned int graph_id) { -return __q6apm_unmap_memory_fixed_region (dev, graph_id, true); +return __q6apm_unmap_memory_fixed_region (dev_get_drvdata (dev->parent), + graph_id, true); }EXPORT_SYMBOL_GPL (q6apm_unmap_pos_buffer);
@@ -845,6 +846,21 @@ static int q6apm_audio_probe(struct snd_soc_component *component)static void q6apm_audio_remove (struct snd_soc_component *component) { +struct q6apm *apm =dev_get_drvdata (component->dev); +struct audioreach_graph_info *info; +int id; + +/* +* The card core removes components before freeing the PCMs, so +* q6apm-dai's pcm_free() runs after the topology (and graph_info) +* is gone and can no longer unmap. Release the DSP mappings here, +* otherwise the next pcm_new() fails to map the same buffer again. +*/ +idr_for_each_entry (&apm->graph_info_idr, info, id) { +__q6apm_unmap_memory_fixed_region (apm, id, false); +__q6apm_unmap_memory_fixed_region (apm, id, true); + } +/* remove topology */ snd_soc_tplg_component_remove (component); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1142/1257 ASoC: qcom: audioreach: fix module cfg blob size handling
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ravi Hothi <[email protected]>
[ Upstream commit e21fb64a8c4aecae31ec63f994423ac944705c3e ]
audioreach_get_module_priv_data() passes mod_array->size, a byte count, as the element count of the __le32 data[] flex array. The allocation and the copy are four times too large, and the memcpy() can read past the end of the topology firmware buffer. The size is also never checked against the private data it must lie within, and a zero size makes the loop spin forever.
Convert the size to a word count, bound the blob by the remaining private data and reject a zero size. Also check the returned pointer before storing it in mod->data, as an error pointer there is dereferenced when the graph is opened.
--- sound/soc/qcom/qdsp6/topology.c | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-)
sound/soc/qcom/qdsp6/topology.c +26 -5
@@ -312,22 +312,37 @@ audioreach_get_module_priv_data(const struct snd_soc_tplg_private *private)for (sz =0 ; sz <le32_to_cpu (private->size); ) {const struct snd_soc_tplg_vendor_array *mod_array; +u32 array_size; mod_array = (struct snd_soc_tplg_vendor_array *)((u8 *)private->array + sz); + array_size =le32_to_cpu (mod_array->size); +if (le32_to_cpu (mod_array->type) ==SND_SOC_AR_TPLG_MODULE_CFG_TYPE ) {struct audioreach_module_priv_data *pdata; +u32 nwords; + +/* size is the byte count of the __le32 data[] */ + nwords = array_size /sizeof (__le32); + +/* the blob must lie within the private data */ +if (sizeof (*pdata) + (u64 )array_size > +le32_to_cpu (private->size) - sz) +return ERR_PTR (-EINVAL ); - pdata =kzalloc_flex (*pdata, data, -le32_to_cpu (mod_array->size)); + pdata =kzalloc_flex (*pdata, data, nwords);if (!pdata)return ERR_PTR (-ENOMEM ); -memcpy (pdata, ((u8 *)private->data + sz),struct_size (pdata, data, -le32_to_cpu (mod_array->size))); +memcpy (pdata, ((u8 *)private->data + sz), +struct_size (pdata, data, nwords));return pdata; } - sz = sz +le32_to_cpu (mod_array->size); +/* a zero size would never advance the walk */ +if (!array_size) +return ERR_PTR (-EINVAL ); + + sz = sz + array_size; }return NULL ;
@@ -611,6 +626,12 @@ static int audioreach_widget_load_module_common(struct snd_soc_component *componreturn mod ?PTR_ERR (mod) : -ENODEV ; mod->data =audioreach_get_module_priv_data (&tplg_w->priv); +if (IS_ERR (mod->data)) { +int rc =PTR_ERR (mod->data); + + mod->data =NULL ; +return rc; + } dobj = &w->dobj; dobj->private = mod;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1143/1257 ASoC: codecs: wsa884x: Accept temperatures across the full trim range
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivas Kandagatla <[email protected]>
[ Upstream commit 00535515e3c14fbee20de4a1aa61cfb3390f0f50 ]
wsa884x_get_temp() rejects any reading outside 5..45 degC with -EAGAIN. A speaker that has been playing, or sits in a warm laptop, easily runs above 45 degC, so its temperature becomes unreadable when it matters.
The check only needs to drop bogus conversions, such as the all-zero reading before the PA is first enabled. Bound it by the -10..150 degC two-point trim range instead.
--- sound/soc/codecs/wsa884x.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
sound/soc/codecs/wsa884x.c +6 -5
@@ -720,10 +720,11 @@/* * Device will report senseless data in many cases, so discard any measurements -* outside of valid range. +* outside of the two-point trim range. Do not narrow this to ambient: a +* speaker that has been playing easily runs well above 45 degC. */ -#define WSA884X_LOW_TEMP_THRESHOLD 5 -#define WSA884X_HIGH_TEMP_THRESHOLD 45 +#define WSA884X_LOW_TEMP_THRESHOLD WSA884X_T1_TEMP +#define WSA884X_HIGH_TEMP_THRESHOLD WSA884X_T2_TEMPstruct wsa884x_priv {struct regmap *regmap;
@@ -1929,8 +1930,8 @@ static int wsa884x_get_temp(struct wsa884x_priv *wsa884x, long *temp)dev_dbg (wsa884x->dev,"Measured temp %ld (dmeas=%d, d1=%d, d2=%d)\n" , val, dmeas, d1, d2); -if ((val >WSA884X_LOW_TEMP_THRESHOLD ) && - (val <WSA884X_HIGH_TEMP_THRESHOLD )) { +if (val >=WSA884X_LOW_TEMP_THRESHOLD && + val <=WSA884X_HIGH_TEMP_THRESHOLD ) { wsa884x->temperature = val; *temp = val *1000 ; ret =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1144/1257 ASoC: codecs: wsa883x: Accept temperatures across the full trim range
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivas Kandagatla <[email protected]>
[ Upstream commit 6a55cf0d9dd2e2493a5030a4f7b0413d31165e45 ]
wsa883x_get_temp() rejects any reading outside 5..45 degC with -EAGAIN, so a speaker that has been playing, or sits in a warm chassis, becomes unreadable above 45 degC.
Bound the check by the -10..150 degC two-point trim range instead, and use inclusive comparisons, as in_range() excludes the upper bound.
--- sound/soc/codecs/wsa883x.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
sound/soc/codecs/wsa883x.c +7 -6
@@ -456,10 +456,11 @@/* * Device will report senseless data in many cases, so discard any measurements -* outside of valid range. +* outside of the two-point trim range. Do not narrow this to ambient: a +* speaker that has been playing easily runs well above 45 degC. */ -#define WSA883X_LOW_TEMP_THRESHOLD 5 -#define WSA883X_HIGH_TEMP_THRESHOLD 45 +#define WSA883X_LOW_TEMP_THRESHOLD WSA883X_T1_TEMP +#define WSA883X_HIGH_TEMP_THRESHOLD WSA883X_T2_TEMPstruct wsa883x_priv {struct regmap *regmap;
@@ -1430,7 +1431,7 @@ static int wsa883x_get_temp(struct wsa883x_priv *wsa883x, long *temp)unsigned int dmeas_msb =0 , dmeas_lsb =0 ;int d1, d2, dmeas;unsigned int mask; -int ret, range; +int ret;long val;guard (mutex)(&wsa883x->sp_lock);
@@ -1493,8 +1494,8 @@ static int wsa883x_get_temp(struct wsa883x_priv *wsa883x, long *temp) } val =WSA883X_T1_TEMP + (((dmeas - d1) * (WSA883X_T2_TEMP -WSA883X_T1_TEMP )) / (d2 - d1)); - range =WSA883X_HIGH_TEMP_THRESHOLD -WSA883X_LOW_TEMP_THRESHOLD ; -if (in_range (val,WSA883X_LOW_TEMP_THRESHOLD , range)) { +if (val >=WSA883X_LOW_TEMP_THRESHOLD && + val <=WSA883X_HIGH_TEMP_THRESHOLD ) { wsa883x->temperature = val; *temp = val *1000 ; ret =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1145/1257 ASoC: SDCA: propagate sdw_slave_read_prop() failure in class_read_prop
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivas Kandagatla <[email protected]>
[ Upstream commit 79cfb5aebbf0417418c2ac25669fade7f3e58ef2 ]
sdw_slave_read_prop() can fail with -ENOMEM; propagate the return instead of leaving slave->prop partially initialised.
--- sound/soc/sdca/sdca_class.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
sound/soc/sdca/sdca_class.c +4 -1
@@ -27,8 +27,11 @@static int class_read_prop (struct sdw_slave *sdw) {struct sdw_slave_prop *prop = &sdw->prop; +int ret; -sdw_slave_read_prop (sdw); + ret =sdw_slave_read_prop (sdw); +if (ret) +return ret; prop->use_domain_irq = true; prop->scp_int1_mask = SDW_SCP_INT1_BUS_CLASH | SDW_SCP_INT1_PARITY |
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1146/1257 ASoC: SDCA: drop pm_runtime reference on probe failure path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivas Kandagatla <[email protected]>
[ Upstream commit 86331b76b32d7a83fb3e64641a5111746bf0f50c ]
sdca_class_probe() takes an extra usage count with pm_runtime_get_noresume() to keep the device powered on until the deferred boot work has run. If devm_pm_runtime_enable() then fails, that reference is never dropped.
Drop it on the error path.
--- sound/soc/sdca/sdca_class.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/sdca/sdca_class.c +3 -1
@@ -181,8 +181,10 @@ static int class_sdw_probe(struct sdw_slave *sdw, const struct sdw_device_id *idpm_runtime_get_noresume (dev); ret =devm_pm_runtime_enable (dev); -if (ret) +if (ret) { +pm_runtime_put_sync (dev);return ret; + }queue_work (system_long_wq, &drv->boot_work);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1147/1257 net: usb: pegasus: check rx pkt_len against the received length
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wei Jie Law <[email protected]>
[ Upstream commit efee699f6de06611234ef9b0abd52db1340e5452 ]
read_bulk_callback() takes the frame length from the device, from the receive header on the 0x8513 and from the trailing status bytes on the other chips, and only checks it against PEGASUS_MTU before passing that many bytes up the stack. In two cases the stack then uses bytes that the device did not send:
- A device that sends a short transfer but claims a long frame gets the stale or uninitialized remainder of the receive skb delivered as packet data.
- A device that claims a frame shorter than an Ethernet header gets past the check as well. eth_type_trans() takes pkt_type from h_dest and the protocol from h_proto without checking skb->len. If the transfer is also short, those come from bytes left in the skb by an earlier transfer, or from uninitialized memory.
Drop frames shorter than ETH_HLEN, and frames whose claimed length, plus the 0x8513 header, does not fit in the bytes actually received, and count them as length errors. urb->actual_length never exceeds the PEGASUS_MTU sized transfer buffer, so this also covers the existing PEGASUS_MTU check. Valid Ethernet frames are at least 60 bytes long without the FCS, so they are not affected.
Found by code review with LLM assistance. With an emulated USB device, a 101-byte transfer claiming a 1500-byte frame was passed up as a 1500-byte packet before this change and is dropped after it, and frames claiming 0, 4 and 13 bytes were passed up and are now dropped and counted in rx_length_errors. The extra bytes happened to be zero in the first test, so disclosure of actual kernel data was not demonstrated.
--- drivers/net/usb/pegasus.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/net/usb/pegasus.c +9 -3
@@ -520,11 +520,17 @@ static void read_bulk_callback(struct urb *urb) }/* -* If the packet is unreasonably long, quietly drop it rather than -* kernel panicing by calling skb_put. +* Drop frames shorter than an Ethernet header, because +* eth_type_trans() reads the header whatever the length, and frames +* longer than what was actually received. Passing either up would +* expose stale buffer contents, and skb_put() could panic on the +* latter. count is at most PEGASUS_MTU. */ -if (pkt_len >PEGASUS_MTU - rx_offset) +if (pkt_len <ETH_HLEN || pkt_len + rx_offset > count) { + net->stats.rx_errors++; + net->stats.rx_length_errors++; goto goon; + }/* * at this point we are sure pegasus->rx_skb != NULL
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1148/1257 bonding: fix out-of-bounds read of arp_ip_target
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiayuan Chen <[email protected]>
[ Upstream commit a81513bf5bdf29cf00c0a11f56be515c1ec260f4 ]
arp_ip_target is a module parameter array with BOND_MAX_ARP_TARGETS entries. In the loop parsing it in bond_check_params(), arp_ip_count is the number of accepted targets, while i is the index into arp_ip_target. Invalid and duplicate entries are skipped without bumping arp_ip_count, so bounding the loop with arp_ip_count lets i run past the end of arp_ip_target, e.g. 16 targets with one duplicate:
BUG: KASAN: global-out-of-bounds in bond_check_params.constprop.0+0x1148/0x1440 Read of size 8 at addr ffffffff96e9ee00 by task swapper/0/1 Call Trace: <TASK> dump_stack_lvl+0x91/0xf0 print_report+0xd1/0x630 kasan_report+0xf3/0x130 __asan_report_load8_noabort+0x14/0x30 bond_check_params.constprop.0+0x1148/0x1440 bonding_init+0x13/0xe0 do_one_initcall+0xe7/0x5b0 kernel_init_freeable+0xa91/0x1120 kernel_init+0x24/0x220 ret_from_fork+0x5b3/0x820 ret_from_fork_asm+0x1a/0x30 </TASK> The buggy address belongs to the variable: arp_ip_target+0x80/0xa0
Bound the loop with i instead. arp_ip_count never exceeds i, so it stays within BOND_MAX_ARP_TARGETS too.
--- drivers/net/bonding/bond_main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/bonding/bond_main.c +1 -1
@@ -6273,7 +6273,7 @@ static int __init bond_check_params(struct bond_params *params) }for (arp_ip_count =0 , i =0 ; - (arp_ip_count <BOND_MAX_ARP_TARGETS ) && arp_ip_target[i]; i++) { + (i <BOND_MAX_ARP_TARGETS ) && arp_ip_target[i]; i++) {__be32 ip;/* not a complete check, but good enough to catch mistakes */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1149/1257 ipmr: fully initialize the synthetic IP header in ipmr_get_route()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ido Schimmel <[email protected]>
[ Upstream commit 134351edc28e083c61012b6c69e8e54dd7fa5bcc ]
For an unresolved multicast route query, ipmr_get_route() builds a synthetic IP header in the headroom obtained from skb_realloc_headroom(), which does not zero the memory it allocates. Only a few fields are initialized, leaving others as stale heap contents.
ipmr_cache_report() copies this header into the IGMPMSG_NOCACHE report that is queued to the mroute socket, so a recvmsg() on that socket leaks the uninitialized bytes to user space: the 'tos' field [1] and the 'id' and 'frag_off' fields [2].
Fix by zeroing the IP header before filling in the few fields that are used, so that the entire header is initialized, as in ip6mr_get_route().
[1]
BUG: KMSAN: kernel-infoleak in _copy_to_iter raw_recvmsg
Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route
Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route
Byte 1 of 28 is uninitialized
[2]
BUG: KMSAN: kernel-infoleak in _copy_to_iter raw_recvmsg
Uninit was stored to memory at:
ipmr_cache_report
ipmr_cache_unresolved
ipmr_get_route
Uninit was created at:
pskb_expand_head
skb_realloc_headroom
ipmr_get_route
Bytes 4-7 of 28 are uninitialized
--- net/ipv4/ipmr.c | 1 + 1 file changed, 1 insertion(+)
net/ipv4/ipmr.c +1 -0
@@ -2500,6 +2500,7 @@ int ipmr_get_route(struct net *net, struct sk_buff *skb,skb_push (skb2,sizeof (struct iphdr ));skb_reset_network_header (skb2); iph =ip_hdr (skb2); +memset (iph,0 ,sizeof (*iph)); iph->ihl =sizeof (struct iphdr ) >>2 ; iph->saddr = saddr; iph->daddr = daddr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1150/1257 ipmr, ip6mr: validate packets injected into the register vif on xmit
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ido Schimmel <[email protected]>
[ Upstream commit aa1799e93f5ebb973252aec649d84d12d9c7fd1c ]
reg_vif_xmit() passes the packet to ipmr_cache_report() which copies its IP header into the IGMPMSG_WHOLEPKT report that is queued to the mroute socket. Nothing guarantees that the packet contains a full IP header, so when a short packet is injected on the register device (e.g., using AF_PACKET), the copy reads past the end of the packet and a recvmsg() on the mroute socket leaks the uninitialized bytes to user space [1].
IPv6 has the same problem [2]. Its reg_vif_xmit() does call pskb_inet_may_pull(), but the helper keys off skb->protocol and does not pull anything when the protocol is neither IPv4 nor IPv6.
Fix by dropping packets whose protocol does not match the address family of the register device or that do not contain a full network header.
[1]
BUG: KMSAN: kernel-infoleak in _copy_to_iter raw_recvmsg
Uninit was stored to memory at:
ipmr_cache_report
reg_vif_xmit
packet_sendmsg
Uninit was created at:
__alloc_skb
sock_alloc_send_pskb
packet_sendmsg
Bytes 1-3 of 21 are uninitialized
[2]
BUG: KMSAN: kernel-infoleak in _copy_to_iter rawv6_recvmsg
Uninit was stored to memory at:
ip6mr_cache_report
reg_vif_xmit
packet_sendmsg
Uninit was created at:
__alloc_skb
sock_alloc_send_pskb
packet_sendmsg
Bytes 8-23 of 41 are uninitialized
--- net/ipv4/ipmr.c | 6 ++++++ net/ipv6/ip6mr.c | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-)
net/ipv4/ipmr.c +6 -0
@@ -537,6 +537,12 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev) };int err; +if (skb->protocol !=htons (ETH_P_IP ) || !pskb_inet_may_pull (skb)) { +DEV_STATS_INC (dev, tx_errors); +kfree_skb (skb); +return NETDEV_TX_OK ; + } +rcu_read_lock (); err =ipmr_fib_lookup (net, &fl4, &mrt);if (err <0 ) {
net/ipv6/ip6mr.c +1 -1
@@ -641,7 +641,7 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, .flowi6_mark = skb->mark, }; -if (!pskb_inet_may_pull (skb)) +if (skb->protocol !=htons (ETH_P_IPV6 ) || !pskb_inet_may_pull (skb)) goto tx_err;rcu_read_lock ();
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1151/1257 ipmr: drop packets with unknown ingress VIF
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhiling Zou <[email protected]>
[ Upstream commit 09280680f2ea060514be2a39ea84209fb6d721d4 ]
A packet can race with VIF publication and make ipmr_find_vif() return -1 even though the VIF device pointer is already visible. The parent VIF device check can then pass with an invalid ingress VIF. For (*,G) entries, this can also let the packet be forwarded back out its ingress VIF.
Drop packets whose ingress VIF lookup fails in both IPv4 and IPv6 forwarding, before checking the MFC parent device. This prevents forwarding with an unknown ingress VIF and avoids the (*,G) hairpin.
Without the early check, the negative index can reach the IPv4 offload lookup only for an skb marked for L3 forwarding offload, currently done by mlxsw. The race is rare; the supplied PoC reports only the UBSAN negative-index diagnostic.
--- net/ipv4/ipmr.c | 3 ++- net/ipv6/ip6mr.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-)
net/ipv4/ipmr.c +2 -1
@@ -2078,7 +2078,8 @@ static void ip_mr_forward(struct net *net, struct mr_table *mrt, }/* Wrong interface: drop packet and (maybe) send PIM assert. */ -if (rcu_access_pointer (mrt->vif_table[vif].dev) != dev) { +if (true_vifi <0 || +rcu_access_pointer (mrt->vif_table[vif].dev) != dev) {if (rt_is_output_route (skb_rtable (skb))) {/* It is our own packet, looped back. * Very complicated situation...
net/ipv6/ip6mr.c +2 -1
@@ -2218,7 +2218,8 @@ static void ip6_mr_forward(struct net *net, struct mr_table *mrt,/* * Wrong interface: drop packet and (maybe) send PIM assert. */ -if (rcu_access_pointer (mrt->vif_table[vif].dev) != dev) { +if (true_vifi <0 || +rcu_access_pointer (mrt->vif_table[vif].dev) != dev) {atomic_long_inc (&c->_c.mfc_un.res.wrong_if); if (true_vifi >= 0 && READ_ONCE(mrt->mroute_do_assert) &&
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1152/1257 dt-bindings: clock: ma35d1: Document the missing crystal inputs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Miquel Raynal <[email protected]>
[ Upstream commit ea1f41802312e77b58113146a060fb0546b2234d ]
The MA35D1 clock controller takes two crystal oscillator inputs from the board:
- HXT, a high-speed 24 MHz crystal for most of the system
- LXT, a low-speed 32.768 kHz crytal for the RTC and low power modes
So far the binding was expecting a single crystal. The example named it HXT, but no real definition for it was given. LXT was not even described. In order to remain backward compatible, we will continue to allow either one (HXT) or two (HXT then LXT) input clocks. I propose to give those phandles a name to clarify what these entries expect, but I'm not listing the clock-names property in the required block, for backward compatibility. The rates are fixed by the TRM, so even if the second oscillator is not described, the OS can make an educated guess.
--- .../bindings/clock/nuvoton,ma35d1-clk.yaml | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
Documentation/devicetree/bindings/clock/nuvoton,ma35d1-clk.yaml +14 -2
@@ -29,7 +29,18 @@ properties: const: 1 clocks: - maxItems: 1 + minItems: 1 + maxItems: 2 + description: + The controller takes 2 crystal oscillator inputs from the board. + HXT is a 24 MHz crystal feeding the internal PLLs. LXT is a 32.768 + kHz crystal, for RTC and low power operations. + + clock-names: + minItems: 1 + items: + - const: hxt + - const: lxt nuvoton,pll-mode: description:
@@ -58,6 +69,7 @@ examples: compatible = "nuvoton,ma35d1-clk"; reg = <0x40460200 0x100>; #clock-cells = <1>; - clocks = <&clk_hxt>; + clocks = <&clk_hxt>, <&clk_lxt>; + clock-names = "hxt", "lxt"; }; ...
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1153/1257 tcp: limit tcp_tso_rtt_log to a valid shift count
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
[ Upstream commit 850a7225bc61cdfaf0c4b02ff341ae7cb54902f5 ]
tcp_tso_autosize() right-shifts the u32 returned by tcp_min_rtt() by sysctl_tcp_tso_rtt_log. The sysctl uses proc_dou8vec_minmax() without an upper bound, so it accepts values through 255. Values above 31 make the shift undefined.
A process with CAP_NET_ADMIN in the target network namespace can set the per-netns sysctl. With CONFIG_UBSAN_SHIFT=y, setting it to 32 and sending TCP data over loopback triggers:
UBSAN: shift-out-of-bounds in net/ipv4/tcp_output.c:2264:30 shift exponent 32 is too large for 32-bit type 'unsigned int' Call Trace: __ubsan_handle_shift_out_of_bounds tcp_tso_segs tcp_write_xmit __tcp_push_pending_frames tcp_push tcp_sendmsg_locked
Limit the sysctl to 31, the largest valid shift count for a u32, and document the accepted range. Writes of larger values now fail with -EINVAL.
On a UBSAN/KASAN build of the net tree, values 0 and 31 remained accepted, values 32 and 255 returned -EINVAL, and TCP traffic with the valid boundary values produced no sanitizer diagnostics.
--- Documentation/networking/ip-sysctl.rst | 2 ++ net/ipv4/sysctl_net_ipv4.c | 2 ++ 2 files changed, 4 insertions(+)
Documentation/networking/ip-sysctl.rst +2 -0
@@ -1128,6 +1128,8 @@ tcp_tso_rtt_log - INTEGER If you want to use the old autosizing, set this sysctl to 0. + Possible values are [0, 31], inclusive. + Default: 9 (2^9 = 512 usec) tcp_pacing_ss_ratio - INTEGER
net/ipv4/sysctl_net_ipv4.c +2 -0
@@ -26,6 +26,7 @@ static int ip_local_port_range_max[] = { 65535, 65535 };static int tcp_adv_win_scale_min =-31 ;static int tcp_adv_win_scale_max =31 ;static int tcp_app_win_max =31 ; +static int tcp_tso_rtt_log_max =31 ;static int tcp_min_snd_mss_min =TCP_MIN_SND_MSS ;static int tcp_min_snd_mss_max =65535 ;static int tcp_rto_max_max =TCP_RTO_MAX_SEC *MSEC_PER_SEC ;
@@ -1406,6 +1407,7 @@ static const struct ctl_table ipv4_net_table[] = { .maxlen = sizeof(u8), .mode = 0644, .proc_handler = proc_dou8vec_minmax, + .extra2 = &tcp_tso_rtt_log_max, }, { .procname = "tcp_min_rtt_wlen",
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1154/1257 xsk: restore UMEM flags after failed pool assignment
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paul Moses <[email protected]>
[ Upstream commit b88b826ec54a06f48a42580c609ba81293ebec8e ]
xp_assign_dev() sets XDP_UMEM_SG_FLAG before checking whether the device supports multibuffer zero-copy. If assignment fails, xsk_bind() destroys the pool but retains the registered UMEM. A subsequent bind without XDP_USE_SG inherits the stale flag.
The flag also changes RX buffer sizing after DMA mapping. On igc, a failed SG bind followed by a non-SG retry with 4096-byte chunks and 1792 bytes of headroom passes admission with 2048 bytes, but programs a 1024-byte RX buffer. On I225-V hardware, an ordinary 1514-byte frame is truncated to 1024 bytes or 1008 with RX timestamps enabled. Restoring the original flags eliminates the truncation in both cases.
Save the UMEM flags before assignment and restore them on failure.
Discovered during development of AF_XDP changes for igc.
--- net/xdp/xsk_buff_pool.c | 2 ++ 1 file changed, 2 insertions(+)
net/xdp/xsk_buff_pool.c +2 -0
@@ -166,6 +166,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool, {u32 needed = netdev->mtu +ETH_PAD_LEN ;u32 segs = netdev->xdp_zc_max_segs; +u8 umem_flags = pool->umem->flags;bool mbuf = flags &XDP_USE_SG ;bool force_zc, force_copy;struct netdev_bpf bpf;
@@ -264,6 +265,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,if (!force_zc) err =0 ;/* fallback to copy mode */ if (err) { + pool->umem->flags = umem_flags;xsk_clear_pool_at_qid (netdev, queue_id);dev_put (netdev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1155/1257 loop: check for read-write open mode on LOOP_SET_STATUS in lo_compat_ioctl()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dominik Maier <[email protected]>
[ Upstream commit 87409eedc543d288cdd49c2174f7d61eca7b8db5 ]
lo_ioctl() checks for (mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN) before allowing LOOP_SET_STATUS or LOOP_SET_STATUS64, but not lo_compat_ioctl(), the handler used by 32-bit user space on 64-bit kernels.
As a result, on 64-bit kernels with CONFIG_COMPAT=y, a 32-bit unprivileged user-space process holding a read-only (O_RDONLY) file descriptor to an active /dev/loopN device can issue a compat LOOP_SET_STATUS ioctl to modify lo_offset, clear lo_sizelimit to 0 (exposing backing-file data past the configured limit), or alter lo_flags.
Enforce the same (mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN) check on LOOP_SET_STATUS in lo_compat_ioctl().
--- drivers/block/loop.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/block/loop.c +4 -2
@@ -1708,8 +1708,10 @@ static int lo_compat_ioctl(struct block_device *bdev, blk_mode_t mode,switch (cmd) {case LOOP_SET_STATUS : - err =loop_set_status_compat (lo, - (const struct compat_loop_info __user *)arg); + err = -EPERM ; +if ((mode &BLK_OPEN_WRITE ) ||capable (CAP_SYS_ADMIN )) + err =loop_set_status_compat (lo, + (const struct compat_loop_info __user *)arg);break ;case LOOP_GET_STATUS : err = loop_get_status_compat(lo,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1156/1257 ALSA: usb-audio: Bound packet copies by the PCM buffer size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sinan Turunc <[email protected]>
[ Upstream commit 06be918062adc1a5a76dc346803b136b20bdb5ae ]
retire_capture_urb() and prepare_playback_urb() assume that one USB packet never carries more data than the whole ALSA ring buffer. Nothing enforces that: the packet size comes from the device (wMaxPacketSize, and curpacksize == maxpacksize when the class-specific endpoint descriptor sets MaxPacketsOnly), while the PCM hardware constraints only require 64-byte periods, two periods and a period time of one data interval. An 8 kHz mono U8 stream on a 128-byte buffer is legal, and a full-speed device can send 1023-byte packets into it.
On the first oversized packet hwptr_done is wrapped once and stays beyond buffer_bytes (895 for 1023 bytes into 128). On the next packet the wrap arithmetic in the copy path computes
bytes1 = subs->buffer_bytes - oldptr
with oldptr > buffer_bytes, so bytes1 wraps to about 4 GB and memcpy() runs off the end of the URB buffer and of the vmalloc'd DMA buffer:
BUG: KASAN: slab-out-of-bounds in retire_capture_urb+0x251/0x870 Read of size 4294966529 at addr ffff88800c1e2800 by task vhci_rx/82
and for playback, where copy_to_urb() has the same shape:
BUG: KASAN: vmalloc-out-of-bounds in copy_to_urb.isra.0+0x188/0x430 Read of size 4294966529 at addr ffffc9000004537f by task vhci_rx/79 prepare_playback_urb+0x98a/0x1fc0
Truncate an oversized capture packet to the buffer size, and stop filling a playback URB once it holds a whole buffer. With bytes <= buffer_bytes the single wrap of hwptr_done and the two-part memcpy() in both copy paths stay inside the buffer. A device whose packets do not fit the buffer at all was never going to play correctly anyway.
Reproduced on 7.3-rc7 with a USB/IP device (dummy_hcd cannot carry isochronous data) advertising a UAC1 endpoint with MaxPacketsOnly and wMaxPacketSize 1023, and a PCM client using period_size 64, periods 2.
--- sound/usb/pcm.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
sound/usb/pcm.c +19 -1
@@ -1343,6 +1343,18 @@ static void retire_capture_urb(struct snd_usb_substream *subs, bytes -= adj; subs->stream_offset_adj -= adj; } +/* +* A packet can be as large as the endpoint's maxpacksize, which +* the device chooses, while the ring buffer can be as small as +* two 64-byte periods. The hwptr_done wrap below handles one +* wrap only, so never take more than one buffer from a packet. +*/ +if (unlikely (bytes > subs->buffer_bytes)) { +dev_warn_ratelimited (&subs->dev->dev, +"%u-byte packet exceeds %u-byte buffer, truncating\n" , + bytes, subs->buffer_bytes); + bytes = subs->buffer_bytes; + } frames = bytes / stride;if (!subs->txfr_quirk) bytes = frames * stride;
@@ -1553,8 +1565,14 @@ static int prepare_playback_urb(struct snd_usb_substream *subs,for (i =0 ; i < ctx->packets; i++) { counts =snd_usb_endpoint_next_packet_size (ep, ctx, i, avail); +/* +* Bound by the ring buffer as well as by the URB: +* copy_to_urb() wraps hwptr_done once, so one URB must +* never carry more than the whole buffer. +*/ if (counts <0 || - (frames + counts) * stride > ctx->buffer_size) + (frames + counts) * stride > ctx->buffer_size || + (frames + counts) * stride > subs->buffer_bytes)break ;/* set up descriptor */ urb->iso_frame_desc[i].offset = frames * stride;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1157/1257 ALSA: ua101: Bound packet copies by the PCM buffer size
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sinan Turunc <[email protected]>
[ Upstream commit 493a77a9f20fca07ca5654f61c1b03bef035df25 ]
copy_capture_data() and copy_playback_data() wrap the ring buffer position once and split the memcpy() in two at the buffer end, which is only correct when one packet holds at most buffer_size frames. The capture packet size is the device's (actual_length up to wMaxPacketSize, divided by 3 * bNrChannels from its own descriptor), the playback packet size is taken from the capture packets, and set_stream_hw() lets the PCM client pick period_bytes_min 1, periods_min 2 and a period time of 1.5 packet intervals: 9 frames at 44.1 kHz high speed, an 18-frame buffer. A device sending 672-byte mono 24-bit packets delivers 224 frames per packet.
After the first packet buffer_pos is 206 and stays beyond buffer_size. On the next packet frames1 = buffer_size - buffer_pos wraps and memcpy() runs away:
snd-ua101 2-1:1.0: invalid position: , pos = 206, buffer size = 18,
period size = 9
BUG: KASAN: slab-out-of-bounds in capture_urb_complete+0x9eb/0xcb0 Read of size 4294966732 at addr ffff88800d73e7e0 by task vhci_rx/81
and for playback:
BUG: KASAN: vmalloc-out-of-bounds in playback_work+0x789/0xac0 Read of size 4294966732 at addr ffffc9000002626a by task kworker/0:1H/80
Clamp the capture copy to buffer_size. On playback, copy at most one buffer and fill the rest of the packet with silence, so the URB length, the delay accounting and the data sent stay consistent. With that bound the single wrap and both memcpy() halves stay inside the buffer. A device whose packets do not fit the buffer never played correctly anyway.
Reproduced on 7.3-rc7 with a USB/IP device presenting the UA-101 interface layout and a 672-byte isochronous endpoint.
--- sound/usb/misc/ua101.c | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-)
sound/usb/misc/ua101.c +26 -3
@@ -285,13 +285,29 @@ static void playback_work(struct work_struct *work)/* fill packet with data or silence */ urb->iso_frame_desc[0 ].length = frames * ua->playback.frame_bytes; -if (test_bit (ALSA_PLAYBACK_RUNNING , &ua->states)) +if (test_bit (ALSA_PLAYBACK_RUNNING , &ua->states)) { +/* +* The packet size comes from the capture stream, +* i.e. from the device, while the ring buffer can +* be as small as two tiny periods. The single wrap +* in copy_playback_data() is only valid for +* frames <= buffer_size, so copy at most one +* buffer and send silence for the rest. +*/ +unsigned int copy_frames =min (frames, + ua->playback.substream->runtime->buffer_size); + do_period_elapsed |=copy_playback_data (&ua->playback, urb, - frames); -else + copy_frames); +memset (urb->transfer_buffer + + copy_frames * ua->playback.frame_bytes,0 , + (frames - copy_frames) * + ua->playback.frame_bytes); + }else {memset (urb->transfer_buffer,0 , urb->iso_frame_desc[0 ].length); + }/* and off you go ... */ err =usb_submit_urb (urb,GFP_ATOMIC );
@@ -320,6 +336,13 @@ static bool copy_capture_data(struct ua101_stream *stream, struct urb *urb, runtime = stream->substream->runtime; frame_bytes = stream->frame_bytes; +/* +* A packet can carry up to max_packet_bytes, the device's +* wMaxPacketSize, which may exceed the whole ring buffer; keep what +* fits so the single wrap below stays valid. +*/ +if (unlikely (frames > runtime->buffer_size)) + frames = runtime->buffer_size; dest = runtime->dma_area + stream->buffer_pos * frame_bytes;if (stream->buffer_pos + frames <= runtime->buffer_size) {memcpy (dest, urb->transfer_buffer, frames * frame_bytes);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1158/1257 sched_ext: Fix the stall watchdog testing and blaming the wrong sched under bypass
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tejun Heo <[email protected]>
[ Upstream commit 93b1512ca69fbe3da66bbd2bab76e9ed74277679 ]
While a sched is bypassing, its tasks are run by its host, the nearest ancestor that isn't bypassing. check_rq_for_timeouts() tests a runnable task against its owner's timeout. Since 2c91169377f4 ("sched_ext: Blame the DSQ's owning scheduler for a runnable stall"), it ejects the sched owning the DSQ the task waits on. The sched tested, the sched ejected and the sched running the task can all differ.
- Timeouts are per sched. A bypassing sub-scheduler with a 2s timeout under a root with the default 30s has its tasks on the root's bypass DSQ. The root, not bypassing itself, consumes that DSQ before calling ops.dispatch() only on every other pass, and on the others only after ops.dispatch() yields nothing. A task that waits 2s there ejects the root, disabling all of sched_ext.
- A bypassing owner's task on the local DSQ is blamed on the owner, which places nothing while bypassing. If the owner is already exiting, e.g. during its own disable, the exit is a no-op and nothing is ejected. If the host isn't running the task, the owner's disable, which waits on it, may never finish.
- The wait isn't restarted when bypass moves a task. The time it waited under its owner counts against the host once it is on the host's bypass DSQ, and its time there against the owner once bypass lifts.
The sched running a task is its owner, or the host while the owner is bypassing. Test the task against that sched's timeout and blame it. A bypass requeue can change the sched running a task, so restart the wait of every task scx_bypass() requeues except the root's own, which the root runs bypassing or not. Single-scheduler behavior is unchanged.
A task that migrates while scx_bypass() works through the cpus, leaving one before its requeue and arriving on another after it, is requeued by neither and keeps its wait, which then counts against the sched now running it. That is what happened to every task before this patch. This might be worth addressing in the future, but the race is rare and the real-world implications should be limited.
--- kernel/sched/ext/ext.c | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-)
kernel/sched/ext/ext.c +23 -15
@@ -2235,7 +2235,8 @@ static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)/* * Don't reset runnable_at. If @p is waiting, the wait continues across * temporary dequeues, e.g. for a migration or an attribute change. -* scx_disable_task() ends it if @p leaves its scheduler. +* scx_disable_task() ends it if @p leaves its scheduler. scx_bypass() +* restarts it when its requeue can change the sched running @p. */ clr_task_runnable (p, false);
@@ -3844,24 +3845,17 @@ static bool check_rq_for_timeouts(struct rq *rq) goto out_unlock;list_for_each_entry (p, &rq->scx.runnable_list, scx.runnable_node) { -struct scx_sched *sch =scx_task_sched (p); +/* +* @p's owner schedules @p, or its host while the owner is +* bypassing. Test @p against that sched's timeout and blame it. +*/ +struct scx_sched *sch =scx_exec_sched (scx_task_sched (p),cpu_of (rq));unsigned long last_runnable = p->scx.runnable_at;if (unlikely (time_after (jiffies, last_runnable +READ_ONCE (sch->watchdog_timeout)))) { -struct scx_dispatch_q *dsq =READ_ONCE (p->scx.dsq);u32 dur_ms =jiffies_to_msecs (jiffies - last_runnable); -/* -* A task can be stuck on a DSQ that a sched other than -* its owner is responsible for draining, e.g. an -* ancestor's bypass DSQ while the owner is bypassing. -* Blame the drainer. The local DSQ is consumed by the -* cpu itself and keeps blame on the owner. -*/ -if (dsq && dsq->sched && dsq->id !=SCX_DSQ_LOCAL ) - sch = dsq->sched; - __scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, cpu_of(rq), "%s[%d] failed to run for %u.%03us", p->comm, p->pid, dur_ms / 1000,
@@ -6369,7 +6363,9 @@ void scx_bypass(struct scx_sched *sch, bool bypass)*/ list_for_each_entry_safe_reverse (p, n, &rq->scx.runnable_list, scx.runnable_node) { -if (!scx_is_descendant (scx_task_sched (p), sch)) +struct scx_sched *owner =scx_task_sched (p); + +if (!scx_is_descendant (owner, sch))continue ;/*
@@ -6381,7 +6377,19 @@ void scx_bypass(struct scx_sched *sch, bool bypass)/* cycling deq/enq is enough, see the function comment */ scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { -/* nothing */ ; +/* +* The requeue can change the sched running @p, +* and the watchdog counts @p's wait against +* that sched. Restart the wait unless @owner is +* the root, which runs its own tasks bypassing +* or not. +* +* A dispatch in flight writes p->scx.flags +* without @p's rq lock. The dequeue waits it +* out, so set the flag after it. +*/ +if (scx_parent (owner)) + p->scx.flags |=SCX_TASK_RESET_RUNNABLE_AT ; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1159/1257 ALSA: hda: Reject codec reset on ASoC (ext_ops) buses
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Ujfalusi <[email protected]>
[ Upstream commit a4311e9447bbb219044db38897f95be112f46a8a ]
Writing to the reconfig or clear sysfs nodes of a codec handled by ASoC (SOF via hdac_hda, AVS via codecs/hda) hangs the writer.
snd_hda_codec_reset() sets card->shutdown and calls device_release_driver(). With ext_ops the driver unbind unregisters the ASoC component, which unbinds and frees the whole ASoC card:
- snd_card_disconnect() returns early as card->shutdown is already set, so the card's child devices are not removed and snd_card_free() waits for the card release forever.
- Even without that, freeing the card removes the codec's hwdep device, which owns the sysfs node the reset was issued from, deadlocking in kernfs while waiting for the active write to finish.
The legacy HDA driver keeps the card across a driver rebind, ASoC does not, so the reset cannot be supported there. Return -EOPNOTSUPP and skip the misleading "codec is being used" messages in the callers.
--- sound/hda/common/codec.c | 6 ++++++ sound/hda/common/sysfs.c | 4 ++++ 2 files changed, 10 insertions(+)
sound/hda/common/codec.c +6 -0
@@ -1800,6 +1800,12 @@ int snd_hda_codec_reset(struct hda_codec *codec) {struct hda_bus *bus = codec->bus; +/* ASoC: driver unbind frees the card, incl. the hwdep issuing the reset */ +if (bus->core.ext_ops) { +codec_err (codec,"Codec reset is not supported with ASoC\n" ); +return -EOPNOTSUPP ; + } +if (snd_hda_lock_devices (bus) <0 )return -EBUSY ;
sound/hda/common/sysfs.c +4 -0
@@ -117,6 +117,8 @@ static int clear_codec(struct hda_codec *codec)int err; err =snd_hda_codec_reset (codec); +if (err == -EOPNOTSUPP ) +return err;if (err <0 ) {codec_err (codec,"The codec is being used, can't free.\n" );return err;
@@ -132,6 +134,8 @@ static int reconfig_codec(struct hda_codec *codec)CLASS (snd_hda_power, pm)(codec);codec_info (codec,"hda-codec: reconfiguring\n" ); err =snd_hda_codec_reset (codec); +if (err == -EOPNOTSUPP ) +return err;if (err <0 ) {codec_err (codec,"The codec is being used, can't reconfigure.\n" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1160/1257 ixgbe: reserve TX timestamp after skb preparation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit f75062536e2d45ee182828f0e47e0124be2fdc8d ]
ixgbe_xmit_frame_ring() takes an extra skb reference with skb_get() for the pending TX timestamp before preparing the skb for transmit. Several of the following steps may need to reallocate the skb head:
- ixgbe_tso() calls skb_cow_head(), which reaches pskb_expand_head() when the header is cloned (e.g. a packet tap holds a clone).
- ixgbe_tx_csum() falls back to skb_checksum_help() for unsupported checksum offsets, which can call pskb_expand_head() through skb_ensure_writable().
- With DCB and a software VLAN tag, skb_cow_head() is called to rewrite the VLAN priority.
pskb_expand_head() used to BUG() on shared skbs. Since commit c7d8bc3dd511 ("net: skbuff: don't BUG() on bad arguments to pskb_expand_head()") it returns -EINVAL instead, so these packets are dropped (TSO, DCB) or sent with an unfinished checksum (skb_checksum_help() errors are ignored by ixgbe_tx_csum()).
Reserve the TX timestamp right before ixgbe_tx_map(), after all skb preparation, as i40e and ice already do. The timestamp request remains covered on the FCoE path, and the cleanup on ixgbe_tx_map() failure is unchanged.
--- drivers/net/ethernet/intel/ixgbe/ixgbe_main.c | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-)
drivers/net/ethernet/intel/ixgbe/ixgbe_main.c +23 -17
@@ -9444,23 +9444,6 @@ netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *skb, } protocol =vlan_get_protocol (skb); -if (unlikely (skb_shinfo (skb)->tx_flags &SKBTX_HW_TSTAMP ) && - adapter->ptp_clock) { -if (adapter->tstamp_config.tx_type ==HWTSTAMP_TX_ON && - !test_and_set_bit_lock (__IXGBE_PTP_TX_IN_PROGRESS, - &adapter->state)) { -skb_shinfo (skb)->tx_flags |=SKBTX_IN_PROGRESS ; - tx_flags |=IXGBE_TX_FLAGS_TSTAMP ; - -/* schedule check for Tx timestamp */ - adapter->ptp_tx_skb =skb_get (skb); - adapter->ptp_tx_start = jiffies; -schedule_work (&adapter->ptp_tx_work); - }else { - adapter->tx_hwtstamp_skipped++; - } - } -#ifdef CONFIG_PCI_IOV /* * Use the l2switch_enable flag - would be false if the DMA
@@ -9525,6 +9508,29 @@ netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *skb,#ifdef IXGBE_FCOE xmit_fcoe:#endif /* IXGBE_FCOE */ +/* Reserve the Tx timestamp only after all skb preparation: +* skb_get() makes the skb shared, and pskb_expand_head() +* (reached from skb_cow_head() or skb_checksum_help()) +* refuses shared skbs. +*/ +if (unlikely (skb_shinfo (skb)->tx_flags &SKBTX_HW_TSTAMP ) && + adapter->ptp_clock) { +if (adapter->tstamp_config.tx_type ==HWTSTAMP_TX_ON && + !test_and_set_bit_lock (__IXGBE_PTP_TX_IN_PROGRESS, + &adapter->state)) { +skb_shinfo (skb)->tx_flags |=SKBTX_IN_PROGRESS ; + tx_flags |=IXGBE_TX_FLAGS_TSTAMP ; + first->tx_flags |=IXGBE_TX_FLAGS_TSTAMP ; + +/* schedule check for Tx timestamp */ + adapter->ptp_tx_skb =skb_get (skb); + adapter->ptp_tx_start = jiffies; +schedule_work (&adapter->ptp_tx_work); + }else { + adapter->tx_hwtstamp_skipped++; + } + } +if (ixgbe_tx_map (tx_ring, first, hdr_len)) goto cleanup_tx_timestamp;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1161/1257 ASoC: hdac_hda: Balance the runtime PM disable in codec remove
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Ujfalusi <[email protected]>
[ Upstream commit f26c0d5f91d918bb66cbbc8916f41836adb38346 ]
hdac_hda_codec_remove() disables runtime PM of the codec device before releasing the HDA link and calling the codec driver's remove callback, so that no runtime resume can race with the teardown and access the link or the already freed codec driver data. snd_hda_codec_cleanup_for_unbind() then disables runtime PM again.
On the next probe snd_hda_codec_register() enables runtime PM only once, leaving it disabled after the ASoC card or the codec driver has been unbound and bound again: the codec stays powered and runtime_status reads 'unsupported'.
Re-enable runtime PM at the end of hdac_hda_codec_remove() to balance its own disable. The codec remains disabled until it is registered again.
--- sound/soc/codecs/hdac_hda.c | 4 ++++ 1 file changed, 4 insertions(+)
sound/soc/codecs/hdac_hda.c +4 -0
@@ -554,6 +554,7 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)return ; } +/* prevent runtime PM callbacks while the link and the codec are torn down */ pm_runtime_disable (&hdev->dev);snd_hdac_ext_bus_link_put (hdev->bus, hlink);
@@ -561,6 +562,9 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component) driver->ops->remove (codec);snd_hda_codec_cleanup_for_unbind (codec); + +/* Balances the disable above, cleanup_for_unbind keeps runtime PM disabled */ +pm_runtime_enable (&hdev->dev); }static const struct snd_soc_dapm_route hdac_hda_dapm_routes[] = {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1162/1257 LoongArch: Call cpu_final_simd() with pure_initcall()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Huacai Chen <[email protected]>
[ Upstream commit 9b56c3659a7e5d930ab3c07ea74cc46af65b6d20 ]
After commit 35ebc4de105989034f12 ("xor: remove macro abuse for XOR implementation registrations"), using "simd=128" to limit SIMD on a platform with 256bit SIMD instructions causes a boot failure.
Because cpu_final_simd() is called with arch_initcall() now, which is after xor_init(), LASX flavors are selected but not workable.
Call cpu_final_simd() with pure_initcall() which is before xor_init().
--- arch/loongarch/kernel/cpu-probe.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kernel/cpu-probe.c +1 -1
@@ -93,7 +93,7 @@ static int __init cpu_final_simd(void)return 0 ; } -arch_initcall (cpu_final_simd); +pure_initcall (cpu_final_simd);static inline void set_elf_platform (int cpu,const char *plat) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1163/1257 LoongArch: Dont init & online empty nodes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Huacai Chen <[email protected]>
[ Upstream commit 87c6d144bc7bbed0c4573848b9c92006edca7848 ]
Don't init & online empty nodes without any CPU cores (and memory), in this way "lscpu" will not display confusing empty nodes.
Modify fake_numa_init() to make sure at least Node-0 isn't empty for the FDT booting case.
--- arch/loongarch/kernel/numa.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
arch/loongarch/kernel/numa.c +6 -2
@@ -216,6 +216,8 @@ static int __init fake_numa_init(void)phys_addr_t start =memblock_start_of_DRAM ();phys_addr_t end =memblock_end_of_DRAM () -1 ; +set_cpuid_to_node (0 ,0 ); +early_numa_add_cpu (0 ,0 );pr_info ("Faking a node at [mem %pap-%pap]\n" , &start, &end);return numa_add_memblk (0 , start, end +1 );
@@ -244,8 +246,10 @@ int __init init_numa_memory(void)return -EINVAL ;for_each_node_mask (node, node_possible_map) { -node_mem_init (node); -node_set_online (node); +if (!cpumask_empty (&cpus_on_node[node])) { +node_mem_init (node); +node_set_online (node); + } } max_pfn =PFN_DOWN (memblock_end_of_DRAM ()); max_low_pfn =min (PFN_DOWN (HIGHMEM_START ), max_pfn);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1164/1257 LoongArch: Use pa_to_nid()/nid_to_addrbase() rather than hard-code
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Huacai Chen <[email protected]>
[ Upstream commit 244eb26bbd152896f976db6415550993cd60b46d ]
NODE_ADDRSPACE_SHIFT is 44 now but may be changed in future, so use pa_to_nid()/nid_to_addrbase() rather than hard-code.
--- arch/loongarch/include/asm/numa.h | 2 +- arch/loongarch/kernel/irq.c | 3 ++- arch/loongarch/pci/pci.c | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-)
arch/loongarch/include/asm/numa.h +1 -1
@@ -14,7 +14,7 @@#define NODE_ADDRSPACE_SHIFT 44#define pa_to_nid (addr) (((addr) & 0xf00000000000) >> NODE_ADDRSPACE_SHIFT) -#define nid_to_addrbase (nid) (_ULCAST_(nid) << NODE_ADDRSPACE_SHIFT) +#define nid_to_addrbase (nid) (_U64CAST_(nid) << NODE_ADDRSPACE_SHIFT)#ifdef CONFIG_NUMA
arch/loongarch/kernel/irq.c +2 -1
@@ -20,6 +20,7 @@#include <asm/irq.h> #include <asm/loongson.h> +#include <asm/numa.h> #include <asm/setup.h> DEFINE_PER_CPU(unsigned long, irq_stack);
@@ -69,7 +70,7 @@ static int __init early_pci_mcfg_parse(struct acpi_table_header *header)for (i =0 ; i < n; i++, mptr++) { msi_group[i].pci_segment = mptr->pci_segment; - pch_group[i].node = msi_group[i].node = (mptr->address >>44 ) &0xf ; + pch_group[i].node = msi_group[i].node =pa_to_nid (mptr->address); }return 0 ;
arch/loongarch/pci/pci.c +2 -1
@@ -12,6 +12,7 @@#include <linux/io-64-nonatomic-lo-hi.h> #include <asm/cacheflush.h> #include <asm/loongson.h> +#include <asm/numa.h> #define PCI_DEVICE_ID_LOONGSON_HOST 0x7a00#define PCI_DEVICE_ID_LOONGSON_DC1 0x7a06
@@ -43,7 +44,7 @@ int raw_pci_write(unsigned int domain, unsigned int bus, unsigned int devfn,phys_addr_t mcfg_addr_init (int node) { -return (((u64 )node <<44 ) |MCFG_EXT_PCICFG_BASE ); +return (nid_to_addrbase (node) |MCFG_EXT_PCICFG_BASE ); }static int __init pcibios_init (void )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1165/1257 LoongArch: Remove arch-specific __smp_mb__{before,after}_atomic()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit 85cebdfee765e92e748e71b9b91889eef5988282 ]
When running BPF selftest "test_progs -t timer_lockup" on a LoongArch machine, the kernel intermittently experiences soft lockups and panics in hrtimer_cancel().
The root cause is that the bpf_timer_cancel() implementation relies on smp_mb__after_atomic() to provide a full data barrier after a relaxed atomic_inc() to ensure the proper store-load ordering before performing lockless dependency checks on weakly-ordered architectures, such as on LoongArch, but the current definition of smp_mb__after_atomic() is just a plain compiler barrier.
This allows a subsequent read to bypass the prior write due to store- load reordering, enabling concurrent CPUs to simultaneously bypass the software deadlock detection, enter hrtimer_cancel(), and then trigger a severe ABBA deadlock in the hrtimer core.
Moreover, there are hundreds of smp_mb__after_atomic() call sites across the core kernel (kernel/, drivers/, mm/, net/, fs/) that currently lack necessary full data barriers on LoongArch, which have potential risks.
To comply with the LKMM specification, fix this by removing the arch- specific definition of __smp_mb__after_atomic(), so that this macro can automatically fall back to the generic definition in asm-generic that maps to __smp_mb() and emits the required hardware DBAR instruction.
While at it, do the same thing for __smp_mb__before_atomic().
With this patch the BPF timer_lockup selftest was stressed for millions consecutive loops on a physical LoongArch machine, without encountering any further lockups.
--- arch/loongarch/include/asm/barrier.h | 3 --- 1 file changed, 3 deletions(-)
arch/loongarch/include/asm/barrier.h +0 -3
@@ -57,9 +57,6 @@#define __WEAK_LLSC_MB " \n"#endif -#define __smp_mb__before_atomic () barrier() -#define __smp_mb__after_atomic () barrier() -/** * array_index_mask_nospec() - generate a ~0 mask when index < size, 0 otherwise * @index: array element index
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1166/1257 LoongArch: Remove redundant call in update_bp_registers()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit 23534c6efeb718e8a4d9107fa7d6707b5b1f5859 ]
In update_bp_registers(), there is a duplicate call to write_wb_reg() when enabling an execute breakpoint:
write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);
write_wb_reg(CSR_CFG_CTRL, i, 0, CTRL_PLV_ENABLE);The two lines are completely identical. Remove the redundant call to clean up the code and eliminate unnecessary register writes.
--- arch/loongarch/kernel/hw_breakpoint.c | 1 - 1 file changed, 1 deletion(-)
arch/loongarch/kernel/hw_breakpoint.c +0 -1
@@ -453,7 +453,6 @@ static void update_bp_registers(struct pt_regs *regs, int enable, int type)if (enable) {if ((info->ctrl.type ==LOONGARCH_BREAKPOINT_EXECUTE ) && (type ==0 )) {write_wb_reg (CSR_CFG_CTRL , i,0 ,CTRL_PLV_ENABLE ); -write_wb_reg (CSR_CFG_CTRL , i,0 ,CTRL_PLV_ENABLE ); }else { ctrl =read_wb_reg (CSR_CFG_CTRL , i,1 );if (info->ctrl.type ==LOONGARCH_BREAKPOINT_LOAD )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1167/1257 LoongArch: Fix bitmask corruption in update_bp_registers()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit 30c52672bf456decf675c11f3c65acd73a6bcca8 ]
In update_bp_registers(), when disabling a LOAD or STORE watchpoint, the code attempts to clear the bit of LoadEn or StoreEn by using the standard bit-clearing pattern.
However, due to the omission of parentheses, the bitwise NOT operator '~' takes higher precedence than the left shift operator '<<'. Then:
(1) ~0x1 << MWPnCFG3_LoadEn evaluates to "(~0x1) << 8 = 0xFFFFFE00",
(2) ~0x1 << MWPnCFG3_StoreEn evaluates to "(~0x1) << 9 = 0xFFFFFC00", that incorrectly clears all configuration fields in the lower 8 bits.
These fields in the lower 8 bits contain critical configurations such as DSOnly (bit 0), PLV0-PLV3 privilege levels (bits 1-4), and LCL (bit 7). Writing back these corrupted values severely breaks configuration isolation and ruins the hardware watchpoint states.
Add parentheses to ensure the correct evaluation order, so that only the targeted LoadEn/StoreEn bit is cleared while preserving the other crucial configuration bits in the lower 8 bits.
--- arch/loongarch/kernel/hw_breakpoint.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/loongarch/kernel/hw_breakpoint.c +2 -2
@@ -468,9 +468,9 @@ static void update_bp_registers(struct pt_regs *regs, int enable, int type) }else { ctrl =read_wb_reg (CSR_CFG_CTRL , i,1 );if (info->ctrl.type ==LOONGARCH_BREAKPOINT_LOAD ) - ctrl &= ~0x1 << MWPnCFG3_LoadEn; + ctrl &= ~(0x1 << MWPnCFG3_LoadEn);if (info->ctrl.type ==LOONGARCH_BREAKPOINT_STORE ) - ctrl &= ~0x1 << MWPnCFG3_StoreEn; + ctrl &= ~(0x1 << MWPnCFG3_StoreEn);write_wb_reg (CSR_CFG_CTRL , i,1 , ctrl); } regs->csr_prmd &= ~CSR_PRMD_PWE ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1168/1257 LoongArch: Fix architectural naming typo for CSR_FWPS_SKIP
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit f322ebfdfda2bce91fb1d3fb0072c735051fed85 ]
According to the LoongArch Reference Manual, the single-step 'Skip' bit resides in the instruction breakpoint status register (CSR.FWPS), rather than the configuration register (CSR.FWPC).
Furthermore, the kernel code comments also explicitly document it as "CSR.FWPS.Skip", yet the macro was erroneously defined as CSR_FWPC_SKIP and used as such in traps.c and hw_breakpoint.c. This mismatch creates architectural naming confusion.
Fix this by renaming the macro from CSR_FWPC_SKIP to CSR_FWPS_SKIP to precisely match the manual and comments. Also, update all call sites to align with the rectified definition.
--- arch/loongarch/include/asm/loongarch.h | 4 ++-- arch/loongarch/kernel/hw_breakpoint.c | 2 +- arch/loongarch/kernel/traps.c | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-)
arch/loongarch/include/asm/loongarch.h +2 -2
@@ -1130,8 +1130,8 @@#define LOONGARCH_CSR_DERA 0x501/* debug era */ #define LOONGARCH_CSR_DESAVE 0x502/* debug save */ -#define CSR_FWPC_SKIP_SHIFT 16 -#define CSR_FWPC_SKIP (_ULCAST_(1) << CSR_FWPC_SKIP_SHIFT) +#define CSR_FWPS_SKIP_SHIFT 16 +#define CSR_FWPS_SKIP (_ULCAST_(1) << CSR_FWPS_SKIP_SHIFT)/* * CSR_ECFG IM
arch/loongarch/kernel/hw_breakpoint.c +1 -1
@@ -550,7 +550,7 @@ void hw_breakpoint_thread_switch(struct task_struct *next) addr =read_wb_reg (CSR_CFG_ADDR ,0 ,0 ); mask =read_wb_reg (CSR_CFG_MASK ,0 ,0 );if (!((regs->csr_era ^ addr) & ~mask)) -csr_write32 (CSR_FWPC_SKIP ,LOONGARCH_CSR_FWPS ); +csr_write32 (CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS ); regs->csr_prmd |=CSR_PRMD_PWE ; }else {/* Update breakpoints */
arch/loongarch/kernel/traps.c +2 -2
@@ -829,7 +829,7 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)* instruction. So don't clear llbit and reset CSR.FWPS.Skip until * the llsc execution is completed. */ -csr_write32 (CSR_FWPC_SKIP ,LOONGARCH_CSR_FWPS ); +csr_write32 (CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS );csr_write32 (CSR_LLBCTL_KLO ,LOONGARCH_CSR_LLBCTL ); goto out; }
@@ -846,7 +846,7 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)* current pc, If yes, then we should not set the CSR.FWPS.SKIP * bit to break the original instruction stream. */ -csr_write32 (CSR_FWPC_SKIP ,LOONGARCH_CSR_FWPS ); +csr_write32 (CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS ); goto out; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1169/1257 LoongArch: Only send SIGTRAP signal if necessary in do_watch()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit f087903018e35d38b8932e18b010ee2e8699d1a1 ]
In do_watch(), the kernel unconditionally forces a SIGTRAP signal at the end of the handler via force_sig(SIGTRAP). This is essential for ptrace operations, but it severely disrupts standard perf_event usage.
Under normal perf usage, it is not necessary to force a SIGTRAP signal on every hit. Forcing it unnecessarily aborts the target process if no user-space signal handler is registered, which violates performance monitoring behaviors and injects context switch overheads.
However, a conditional check using only 'current->ptrace' would block legitimate user-requested signals when a perf_event is configured with 'attr.sigtrap = 1' for asynchronous user-space tracking.
Fix this by refactoring breakpoint_handler() and watchpoint_handler() to return a boolean status indicating whether any triggered breakpoint explicitly requires a signal notification. Update do_watch() to enforce the SIGTRAP signal only when the process is actively being debugged via ptrace, or when the underlying perf_event infrastructure specifically demands it via 'attr.sigtrap'.
--- arch/loongarch/include/asm/hw_breakpoint.h | 4 ++-- arch/loongarch/kernel/hw_breakpoint.c | 18 ++++++++++++++++-- arch/loongarch/kernel/traps.c | 9 ++++++--- 3 files changed, 24 insertions(+), 7 deletions(-)
arch/loongarch/include/asm/hw_breakpoint.h +2 -2
@@ -116,8 +116,8 @@ extern void arch_uninstall_hw_breakpoint(struct perf_event *bp);extern int hw_breakpoint_slots (int type);extern void hw_breakpoint_pmu_read (struct perf_event *bp); -void breakpoint_handler (struct pt_regs *regs); -void watchpoint_handler (struct pt_regs *regs); +bool breakpoint_handler (struct pt_regs *regs); +bool watchpoint_handler (struct pt_regs *regs);#ifdef CONFIG_HAVE_HW_BREAKPOINT extern void ptrace_hw_copy_thread (struct task_struct *task);
arch/loongarch/kernel/hw_breakpoint.c +16 -2
@@ -482,9 +482,10 @@ NOKPROBE_SYMBOL(update_bp_registers);/* * Debug exception handlers. */ -void breakpoint_handler (struct pt_regs *regs) +bool breakpoint_handler (struct pt_regs *regs) {int i; +bool need_sigtrap = false;struct perf_event *bp, **slots; slots =this_cpu_ptr (bp_on_reg);
@@ -494,17 +495,24 @@ void breakpoint_handler(struct pt_regs *regs) bp = slots[i];if (bp ==NULL )continue ; +perf_bp_event (bp, regs); +if (bp->attr.sigtrap) + need_sigtrap = true; +csr_write32 (0x1 << i,LOONGARCH_CSR_FWPS );update_bp_registers (regs,0 ,0 ); } } + +return need_sigtrap; }NOKPROBE_SYMBOL (breakpoint_handler); -void watchpoint_handler (struct pt_regs *regs) +bool watchpoint_handler (struct pt_regs *regs) {int i; +bool need_sigtrap = false;struct perf_event *wp, **slots; slots =this_cpu_ptr (wp_on_reg);
@@ -514,11 +522,17 @@ void watchpoint_handler(struct pt_regs *regs) wp = slots[i];if (wp ==NULL )continue ; +perf_bp_event (wp, regs); +if (wp->attr.sigtrap) + need_sigtrap = true; +csr_write32 (0x1 << i,LOONGARCH_CSR_MWPS );update_bp_registers (regs,0 ,1 ); } } + +return need_sigtrap; }NOKPROBE_SYMBOL (watchpoint_handler);
arch/loongarch/kernel/traps.c +6 -3
@@ -815,6 +815,8 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs)#ifndef CONFIG_HAVE_HW_BREAKPOINT pr_warn ("Hardware watch point handler not implemented!\n" );#else +bool need_sigtrap = !!current->ptrace; +if (kgdb_breakpoint_handler (regs)) goto out;
@@ -851,11 +853,12 @@ asmlinkage void noinstr do_watch(struct pt_regs *regs) } } }else { -breakpoint_handler (regs); -watchpoint_handler (regs); + need_sigtrap |=breakpoint_handler (regs); + need_sigtrap |=watchpoint_handler (regs); } -force_sig (SIGTRAP ); +if (need_sigtrap) +force_sig (SIGTRAP ); out: #endifirqentry_exit (regs, state);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1170/1257 LoongArch: Fix perf hardware breakpoint failure via installation
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit f5c0f8427469e703465c719c4304ce91282a32eb ]
In hw_breakpoint_control(), the logic to enable CSR_PRMD_PWE (global watchpoint enable) incorrectly relies on TIF_LOAD_WATCH. This thread flag is only set during ptrace operations, meaning that the standard hardware breakpoints created via perf_event_open() will never have this flag set.
As a result, the CSR_PRMD_PWE switch is skipped, leaving the hardware breakpoint completely inactive in perf usage.
Fix this by decoupling the CSR_PRMD_PWE from the ptrace specific flag TIF_LOAD_WATCH, which ensures that CSR_PRMD_PWE is enabled whenever a hardware breakpoint is installed.
Here is a user-space reproducer to demonstrate the issue:
(1) Test program (test_perf_install.c):
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
static int var = 0;
int main(void)
{
size_t count = 0;
struct perf_event_attr attr = {
.type = PERF_TYPE_BREAKPOINT,
.size = sizeof(attr),
.bp_type = HW_BREAKPOINT_W,
.bp_addr = (unsigned long)&var,
.bp_len = HW_BREAKPOINT_LEN_1,
.exclude_kernel = 1,
};
int fd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
asm volatile("st.b %1, %0" : "=m"(var) : "r"(11) : "memory");
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(size_t));
printf("Watchpoint counts: expected = 1, actual = %zu\n", count);
close(fd);
return 0;
}(2) Test steps:
$ gcc test_perf_install.c -o test_perf_install $ ./test_perf_install
(3) Test results:
Without this patch:
Watchpoint counts: expected = 1, actual = 0
With this patch:
Watchpoint counts: expected = 1, actual = 1
--- arch/loongarch/kernel/hw_breakpoint.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kernel/hw_breakpoint.c +1 -1
@@ -233,7 +233,7 @@ static int hw_breakpoint_control(struct perf_event *bp, } enable =csr_read64 (LOONGARCH_CSR_CRMD );csr_write64 (CSR_CRMD_WE | enable,LOONGARCH_CSR_CRMD ); -if (bp->hw.target &&test_tsk_thread_flag (bp->hw.target,TIF_LOAD_WATCH )) +if (bp->hw.target) regs->csr_prmd |=CSR_PRMD_PWE ;break ;case HW_BREAKPOINT_UNINSTALL :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1171/1257 LoongArch: Fix one-shot limitation for perf hardware breakpoints
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
[ Upstream commit 5e0b00fd000a53a5428fed6c96be74019bd0ad17 ]
In breakpoint_handler() and watchpoint_handler(), the code disables the hardware slot by executing update_bp_registers(regs, 0, ...). This design forces the active hardware breakpoint configuration to be wiped out upon its first hit, turning standard perf hardware breakpoints into "one-shot" events.
Furthermore, while the ptrace single-step path in do_watch() executes a hardware single-step skip mechanism to advance the PC, the standard perf path lacks any mechanism to bypass the original triggering instruction.
To maintain the long-term persistence of hardware breakpoints for perf usage, eliminate the disruptive calls to update_bp_registers() within the handler loops to keep the breakpoint configuration enabled.
Concurrently, execute a single, unified register write outside the loop to atomize the state transition and explicitly enforce the hardware skip mechanism once per exception return, ensuring the processor safely steps forward without lockups.
Meanwhile, in order to prevent status contamination during single-core context switches or cross-core thread migrations, the hardware register skip state of the previous thread is saved first. Then, the skip state is restored and its software skip flag is also cleared only if the next thread has the skip flag; otherwise, 0 is written to clear the FWPS and MWPS registers, which explicitly clears the skip bit according to the architectural specification.
Additionally, explicitly clear hbp_break_skip and hbp_watch_skip inside ptrace_hw_copy_thread() which is called by copy_thread() during the task creation. This guarantees that a newly cloned child task starts with a clean slate.
Here is a user-space reproducer to demonstrate the issue.
(1) Test program (test_perf_continuous.c):
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
static int var = 0;
int main(void)
{
size_t count = 0;
struct perf_event_attr attr = {
.type = PERF_TYPE_BREAKPOINT,
.size = sizeof(attr),
.bp_type = HW_BREAKPOINT_W,
.bp_addr = (unsigned long)&var,
.bp_len = HW_BREAKPOINT_LEN_1,
.exclude_kernel = 1,
};
int fd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
asm volatile("st.b %1, %0" : "=m"(var) : "r"(11) : "memory");
asm volatile("st.b %1, %0" : "=m"(var) : "r"(22) : "memory");
asm volatile("st.b %1, %0" : "=m"(var) : "r"(33) : "memory");
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(size_t));
printf("Watchpoint counts: expected = 3, actual = %zu\n", count);
close(fd);
return 0;
}(2) Test steps:
$ gcc test_perf_continuous.c -o test_perf_continuous $ ./test_perf_continuous
(3) Test results:
Without this patch:
Watchpoint counts: expected = 3, actual = 1
With this patch:
Watchpoint counts: expected = 3, actual = 3
--- arch/loongarch/include/asm/hw_breakpoint.h | 4 +-- arch/loongarch/include/asm/loongarch.h | 3 ++ arch/loongarch/include/asm/processor.h | 1 + arch/loongarch/include/asm/switch_to.h | 2 +- arch/loongarch/kernel/hw_breakpoint.c | 39 +++++++++++++++++++--- 5 files changed, 41 insertions(+), 8 deletions(-)
arch/loongarch/include/asm/hw_breakpoint.h +2 -2
@@ -121,12 +121,12 @@ bool watchpoint_handler(struct pt_regs *regs);#ifdef CONFIG_HAVE_HW_BREAKPOINT extern void ptrace_hw_copy_thread (struct task_struct *task); -extern void hw_breakpoint_thread_switch (struct task_struct *next); +extern void hw_breakpoint_thread_switch (struct task_struct *prev,struct task_struct *next);#else static inline void ptrace_hw_copy_thread (struct task_struct *task) { } -static inline void hw_breakpoint_thread_switch (struct task_struct *next) +static inline void hw_breakpoint_thread_switch (struct task_struct *prev,struct task_struct *next) { }#endif
arch/loongarch/include/asm/loongarch.h +3 -0
@@ -1133,6 +1133,9 @@#define CSR_FWPS_SKIP_SHIFT 16#define CSR_FWPS_SKIP (_ULCAST_(1) << CSR_FWPS_SKIP_SHIFT) +#define CSR_MWPS_SKIP_SHIFT 16 +#define CSR_MWPS_SKIP (_ULCAST_(1) << CSR_MWPS_SKIP_SHIFT) +/* * CSR_ECFG IM */
arch/loongarch/include/asm/processor.h +1 -0
@@ -138,6 +138,7 @@ struct thread_struct {struct loongarch_lbt lbt;/* Also conditionally copied */ /* Hardware breakpoints pinned to this task. */ +bool hbp_break_skip, hbp_watch_skip;struct perf_event *hbp_break[LOONGARCH_MAX_BRP ];struct perf_event *hbp_watch[LOONGARCH_MAX_WRP ]; };
arch/loongarch/include/asm/switch_to.h +1 -1
@@ -34,7 +34,7 @@ extern asmlinkage struct task_struct *__switch_to(struct task_struct *prev, do { \ lose_fpu_inatomic(1, prev); \ lose_lbt_inatomic(1, prev); \ - hw_breakpoint_thread_switch(next); \ + hw_breakpoint_thread_switch(prev, next); \ set_current(next); \ (last) = __switch_to(prev, next, \ __builtin_return_address(0), __builtin_frame_address(0)); \
arch/loongarch/kernel/hw_breakpoint.c +34 -5
@@ -156,6 +156,9 @@ static int hw_breakpoint_slot_setup(struct perf_event **slots, int max_slots,void ptrace_hw_copy_thread (struct task_struct *tsk) { + tsk->thread.hbp_break_skip =0 ; + tsk->thread.hbp_watch_skip =0 ; +memset (tsk->thread.hbp_break,0 ,sizeof (tsk->thread.hbp_break));memset (tsk->thread.hbp_watch,0 ,sizeof (tsk->thread.hbp_watch)); }
@@ -485,6 +488,7 @@ NOKPROBE_SYMBOL(update_bp_registers);bool breakpoint_handler (struct pt_regs *regs) {int i; +unsigned int clear_mask =0 ;bool need_sigtrap = false;struct perf_event *bp, **slots;
@@ -500,11 +504,13 @@ bool breakpoint_handler(struct pt_regs *regs)if (bp->attr.sigtrap) need_sigtrap = true; -csr_write32 (0x1 << i,LOONGARCH_CSR_FWPS ); -update_bp_registers (regs,0 ,0 ); + clear_mask |= (0x1 << i); } } +if (clear_mask) +csr_write32 (clear_mask |CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS ); +return need_sigtrap; }NOKPROBE_SYMBOL (breakpoint_handler);
@@ -512,6 +518,7 @@ NOKPROBE_SYMBOL(breakpoint_handler);bool watchpoint_handler (struct pt_regs *regs) {int i; +unsigned int clear_mask =0 ;bool need_sigtrap = false;struct perf_event *wp, **slots;
@@ -527,11 +534,13 @@ bool watchpoint_handler(struct pt_regs *regs)if (wp->attr.sigtrap) need_sigtrap = true; -csr_write32 (0x1 << i,LOONGARCH_CSR_MWPS ); -update_bp_registers (regs,0 ,1 ); + clear_mask |= (0x1 << i); } } +if (clear_mask) +csr_write32 (clear_mask |CSR_MWPS_SKIP ,LOONGARCH_CSR_MWPS ); +return need_sigtrap; }NOKPROBE_SYMBOL (watchpoint_handler);
@@ -555,7 +564,7 @@ static int __init arch_hw_breakpoint_init(void) }arch_initcall (arch_hw_breakpoint_init); -void hw_breakpoint_thread_switch (struct task_struct *next) +void hw_breakpoint_thread_switch (struct task_struct *prev,struct task_struct *next) {u64 addr, mask;struct pt_regs *regs =task_pt_regs (next);
@@ -567,6 +576,26 @@ void hw_breakpoint_thread_switch(struct task_struct *next)csr_write32 (CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS ); regs->csr_prmd |=CSR_PRMD_PWE ; }else { +unsigned int fwps =csr_read32 (LOONGARCH_CSR_FWPS ); +unsigned int mwps =csr_read32 (LOONGARCH_CSR_MWPS ); + + prev->thread.hbp_break_skip = !!(fwps &CSR_FWPS_SKIP ); + prev->thread.hbp_watch_skip = !!(mwps &CSR_MWPS_SKIP ); + +if (!next->thread.hbp_break_skip) +csr_write32 (0 ,LOONGARCH_CSR_FWPS ); +else { +csr_write32 (CSR_FWPS_SKIP ,LOONGARCH_CSR_FWPS ); + next->thread.hbp_break_skip =0 ; + } + +if (!next->thread.hbp_watch_skip) +csr_write32 (0 ,LOONGARCH_CSR_MWPS ); +else { +csr_write32 (CSR_MWPS_SKIP ,LOONGARCH_CSR_MWPS ); + next->thread.hbp_watch_skip =0 ; + } +/* Update breakpoints */ update_bp_registers (regs,1 ,0 );/* Update watchpoints */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1172/1257 cpufreq: stats: Fix potential out-of-bounds access in deferred reset
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhongqiu Han <[email protected]>
[ Upstream commit 8a702989677216489e471a6f27599da53f753567 ]
cpufreq_stats_create_table() sets stats->last_index to -1 if policy->cur is not in the frequency table. It then stays at -1, because cpufreq_stats_record_transition() returns early on old_index == -1 before it gets to update last_index.
Commit 46a310b80bc2 ("[CPUFREQ] Don't set stat->last_index to -1 if the pol->cur has incorrect value.") added that check. However, since commit 40c3bd4cfa6f ("cpufreq: stats: Defer stats update to cpufreq_stats_record_transition()"), the stats reset is deferred to the beginning of cpufreq_stats_record_transition(), before that check, and cpufreq_stats_reset_table() ends with an unconditional cpufreq_stats_update(). So if the "reset" attribute is written while last_index is -1, the next frequency transition accesses time_in_state[-1].
Fix it by also returning early on last_index == -1 in cpufreq_stats_reset_table().
--- drivers/cpufreq/cpufreq_stats.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/cpufreq/cpufreq_stats.c +4 -0
@@ -52,6 +52,10 @@ static void cpufreq_stats_reset_table(struct cpufreq_stats *stats)* reset_pending accesses in cpufreq_stats_record_transition(). */ smp_rmb (); + +if (stats->last_index ==-1 ) +return ; +cpufreq_stats_update (stats,READ_ONCE (stats->reset_time)); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1173/1257 arm64/mm: restrict transparent contpte mappings to valid PTEs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Gongyi <[email protected]>
[ Upstream commit 486d396b19e93f6e56e0a0ba96c14a9ccc1a5977 ]
The transparent contpte layer treats PTE_CONT as software grouping state. When a valid PTE has PTE_CONT set, the contpte helpers may align an operation to a CONT_PTE_SIZE block and operate on the whole block. The current single-PTE helpers use pte_valid_cont() to identify such groups; this is a helper contract, not an architectural restriction on using PTE_CONT with present-invalid descriptors. Explicit users such as hugetlb manage their contiguous encodings separately.
contpte_set_ptes() currently sets PTE_CONT from alignment alone. Batched set_ptes() users can therefore install present-invalid PTEs with PTE_CONT set, for example mprotect(PROT_NONE), NUMA hinting through modify_prot_commit_ptes(), fork() copying a PROT_NONE large folio, or a PMD split installing PAGE_NONE PTEs.
This is not a hardware programming problem: invalid descriptors are not translated, so the hardware ignores descriptor bits such as PTE_CONT. It is a software-state problem. Some arm64 fast paths, such as test_and_clear_young_ptes(), test pte_cont() directly instead of pte_valid_cont().
In the observed failure, mprotect(PROT_NONE) installed a full CONT_PTE_SIZE range of present-invalid PTEs with PTE_CONT set. MADV_GUARD_INSTALL then zapped one PTE. The nr == 1 clear_full_ptes() path only unfolds pte_valid_cont() entries, so the neighbouring present-invalid entries kept PTE_CONT while the target entry became a guard marker.
clear_refs_pte_range() then reached the marker through:
ptep_test_and_clear_young()
test_and_clear_young_ptes()
contpte_test_and_clear_young_ptes()
contpte_align_addr_ptep()
__ptep_test_and_clear_young()
The marker changed from old_pte=0x00000000000047c0 to new_pte=0x00000000000043c0 by clearing PTE_AF. For swap PTEs, bit 10 is part of the swap type field, bits 6-10: 0x47c0 is SWP_PTE_MARKER with offset 4, while 0x43c0 has type 15 and is decoded as an ordinary swap entry. Zap later warned in swap_put_entries_direct() with a bad swap entry.
Present-invalid PTEs could retain PTE_CONT as software grouping state, but their single-PTE modification paths would then need to recognize and unfold those groups consistently. Since current helpers mostly use pte_valid_cont() for membership, avoid creating present-invalid transparent contpte groups in contpte_set_ptes(). They bring no hardware benefit while invalid, and eligible valid ranges can be grouped again when they are installed.
The public set_ptes() wrapper already clears PTE_CONT before calling contpte_set_ptes(). Return invalid PTEs through __set_ptes() directly, and warn if a future direct caller unexpectedly passes an invalid PTE with PTE_CONT set.
This is triggerable by a user process against its own address space. On systems running with panic_on_warn, the warning becomes a denial of service.
--- arch/arm64/include/asm/pgtable.h | 3 +++ arch/arm64/mm/contpte.c | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-)
arch/arm64/include/asm/pgtable.h +3 -0
@@ -1651,6 +1651,9 @@ extern void modify_prot_commit_ptes(struct vm_area_struct *vma, unsigned long ad* The contpte APIs are used to transparently manage the contiguous bit in ptes * where it is possible and makes sense to do so. The PTE_CONT bit is considered * a private implementation detail of the public ptep API (see below). +* Single-PTE transparent contpte helpers use pte_valid_cont() to identify +* grouped PTEs; explicit contiguous-encoding users such as hugetlb manage +* their entries separately. */ extern void __contpte_try_fold (struct mm_struct *mm,unsigned long addr,pte_t *ptep,pte_t pte);
arch/arm64/mm/contpte.c +3 -1
@@ -460,8 +460,10 @@ void contpte_set_ptes(struct mm_struct *mm, unsigned long addr,*/ VM_WARN_ON (nr ==1 ); -if (!mm_is_user (mm)) +if (!mm_is_user (mm) || !pte_valid (pte)) { +VM_WARN_ON_ONCE (!pte_valid (pte) &&pte_cont (pte));return __set_ptes (mm, addr, ptep, pte, nr); + } end = addr + (nr <<PAGE_SHIFT ); pfn =pte_pfn (pte);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1174/1257 clocksource: Prevent immediate watchdog rerun after a delay
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit f322d7f7ae56bce728ba03a387e35380bc4ad939 ]
The watchdog rewrite made the clocksource check handle long intervals between two measurements, but missed that the timer expiry needs to be rebased after such a delay.
When a watchdog invocation is delayed by more than one interval, adding WATCHDOG_INTERVAL to the previous expiry leaves the timer expiry in the past. That causes an immediate second invocation. The resulting short measurement interval can mark a clocksource unstable.
Cure this by rearming the timer based on jiffies, which places the next expiry one full watchdog interval into the future.
--- kernel/time/clocksource.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/time/clocksource.c +1 -1
@@ -673,7 +673,7 @@ static void clocksource_watchdog(struct timer_list *unused)/* Could have been rearmed by a stop/start cycle */ if (!timer_pending (&watchdog_timer)) { - watchdog_timer.expires +=WATCHDOG_INTERVAL ; + watchdog_timer.expires = jiffies +WATCHDOG_INTERVAL ;add_timer_local (&watchdog_timer); } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1175/1257 perf machine: Fix NULL deref in thread__resolve_callchain_sample()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: lvyating <[email protected]>
[ Upstream commit 4626d370ae89b8af4d46a45372b269f926ec662d ]
When recording with -j stack, resolve_lbr_callchain_sample() can dereference a NULL 'chain' pointer while resolving the branch stack.
$ perf record -j stack -e branches:u uname perf: Segmentation fault
Fix it by checking 'chain' for NULL before dereferencing it.
--- tools/perf/util/machine.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/util/machine.c +1 -1
@@ -2858,7 +2858,7 @@ static int thread__resolve_callchain_sample(struct thread *thread,if (chain) chain_nr = chain->nr; -if (evsel__has_branch_callstack (evsel)) { +if (chain &&evsel__has_branch_callstack (evsel)) {struct perf_env *env =evsel__env (evsel); err = resolve_lbr_callchain_sample(thread, cursor, sample, parent,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1176/1257 drm/amdkfd: Validate the control stack of a restored queue
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: William Palacek <[email protected]>
[ Upstream commit 90d91a192751cd9a7d9d2286299bc72ec1c28179 ]
kfd_criu_restore_queue() takes the control stack size from the checkpoint image without the topology check create-queue does in kfd_queue_acquire_buffers(), which restore stopped calling in commit 1cafa8b29e02 ("drm/amdkfd: Don't acquire buffers during CRIU queue restore."). An image size of 0x300000 is accepted and sizes the MQD allocation, and 0xFFFFFFFF trips a page allocator warning in kmalloc().
restore_mqd() also keeps the image's cp_hqd_cntl_stack_size, cp_hqd_cntl_stack_offset and cp_hqd_wg_state_offset. With offset > size or wave state offset < size, get_wave_state() returns wrapped sizes.
Take the per-XCC size from topology, 0 for queues without a control stack, and reject larger images. In restore_mqd(), set the size to it and bound both offsets as init_mqd() does.
--- drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager.h | 9 ++++++ .../gpu/drm/amd/amdkfd/kfd_mqd_manager_v10.c | 2 ++ .../gpu/drm/amd/amdkfd/kfd_mqd_manager_v11.c | 2 ++ .../gpu/drm/amd/amdkfd/kfd_mqd_manager_v12.c | 2 ++ .../drm/amd/amdkfd/kfd_mqd_manager_v12_1.c | 2 ++ .../gpu/drm/amd/amdkfd/kfd_mqd_manager_v9.c | 2 ++ .../gpu/drm/amd/amdkfd/kfd_mqd_manager_vi.c | 2 ++ .../amd/amdkfd/kfd_process_queue_manager.c | 30 +++++++++++++------ 8 files changed, 42 insertions(+), 9 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager.h +9 -0
@@ -138,6 +138,15 @@ struct mqd_manager {uint32_t ctl_stack_size; }; +/* Keep offset <= size <= wave state offset, as init_mqd() and CP do */ +static inline void kfd_mqd_restore_ctl_stack (u32 *size,u32 *offset,u32 *wg_offset, +u32 ctl_stack_size) +{ + *size = ctl_stack_size; + *offset =min (*offset, ctl_stack_size); + *wg_offset =max (*wg_offset, ctl_stack_size); +} +struct mqd_user_context_save_area_header {/* Byte offset from start of user context * save area to the last saved top (lowest
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v10.c +2 -0
@@ -305,6 +305,8 @@ static void restore_mqd(struct mqd_manager *mm, void **mqd, addr = mqd_mem_obj->gpu_addr;memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size); *mqd = m;if (gart_addr)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v11.c +2 -0
@@ -340,6 +340,8 @@ static void restore_mqd(struct mqd_manager *mm, void **mqd, addr = mqd_mem_obj->gpu_addr;memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size); *mqd = m;if (gart_addr)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v12.c +2 -0
@@ -393,6 +393,8 @@ static void restore_mqd(struct mqd_manager *mm, void **mqd,memset (m,0 ,AMDGPU_MQD_SIZE_ALIGN (mm->mqd_size));memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size);/* Update MQD base address to the newly allocated location */ m->cp_mqd_base_addr_lo =lower_32_bits (addr);
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v12_1.c +2 -0
@@ -663,6 +663,8 @@ static void restore_mqd_v12_1(struct mqd_manager *mm, void **mqd,memset (m,0 ,AMDGPU_MQD_SIZE_ALIGN (mm->mqd_size) *NUM_XCC (mm->dev->xcc_mask));memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size);/* Update MQD base address to the newly allocated location */ m->cp_mqd_base_addr_lo =lower_32_bits (addr);
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_v9.c +2 -0
@@ -462,6 +462,8 @@ static void restore_mqd(struct mqd_manager *mm, void **mqd, addr = mqd_mem_obj->gpu_addr;memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size); *mqd = m;if (gart_addr)
drivers/gpu/drm/amd/amdkfd/kfd_mqd_manager_vi.c +2 -0
@@ -317,6 +317,8 @@ static void restore_mqd(struct mqd_manager *mm, void **mqd, addr = mqd_mem_obj->gpu_addr;memcpy (m, mqd_src,sizeof (*m)); +kfd_mqd_restore_ctl_stack (&m->cp_hqd_cntl_stack_size, &m->cp_hqd_cntl_stack_offset, + &m->cp_hqd_wg_state_offset, qp->ctl_stack_size); *mqd = m;if (gart_addr)
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +21 -9
@@ -26,6 +26,7 @@#include <linux/list.h> #include "kfd_device_queue_manager.h" #include "kfd_priv.h" +#include "kfd_topology.h" #include "kfd_kernel_queue.h" #include "amdgpu_amdkfd.h" #include "amdgpu_reset.h"
@@ -981,7 +982,7 @@ int kfd_criu_checkpoint_queues(struct kfd_process *p, }static void set_queue_properties_from_criu (struct queue_properties *qp, -struct kfd_criu_queue_priv_data *q_data,uint32_t num_xcc) +struct kfd_criu_queue_priv_data *q_data) { qp->is_interop = false; qp->queue_percent = q_data->q_percent;
@@ -994,11 +995,6 @@ static void set_queue_properties_from_criu(struct queue_properties *qp, qp->eop_ring_buffer_size = q_data->eop_ring_buffer_size; qp->ctx_save_restore_area_address = q_data->ctx_save_restore_area_address; qp->ctx_save_restore_area_size = q_data->ctx_save_restore_area_size; -if (q_data->type ==KFD_QUEUE_TYPE_COMPUTE ) - qp->ctl_stack_size = q_data->ctl_stack_size / num_xcc; -else - qp->ctl_stack_size = q_data->ctl_stack_size; - qp->type = q_data->type; qp->format = q_data->format; }
@@ -1010,6 +1006,7 @@ int kfd_criu_restore_queue(struct kfd_process *p, {uint8_t *mqd, *ctl_stack, *q_extra_data =NULL ;struct kfd_criu_queue_priv_data *q_data; +struct kfd_topology_device *topo_dev;struct kfd_process_device *pdd;uint64_t q_extra_data_size;struct queue_properties qp;
@@ -1046,6 +1043,24 @@ int kfd_criu_restore_queue(struct kfd_process *p, goto exit; } +memset (&qp,0 ,sizeof (qp)); +set_queue_properties_from_criu (&qp, q_data); + +/* Per-XCC control stack size from topology, as create-queue requires */ +if (qp.type ==KFD_QUEUE_TYPE_COMPUTE && pdd->dev->kfd->cwsr_enabled) { + topo_dev =kfd_topology_device_by_id (pdd->dev->id); +if (!topo_dev) { + ret = -EINVAL ; + goto exit; + } + qp.ctl_stack_size = topo_dev->node_props.ctl_stack_size; + } + +if (q_data->ctl_stack_size > (u64 )qp.ctl_stack_size *NUM_XCC (pdd->dev->xcc_mask)) { + ret = -EINVAL ; + goto exit; + } + *priv_data_offset +=sizeof (*q_data); q_extra_data_size = (uint64_t )q_data->ctl_stack_size + q_data->mqd_size;
@@ -1075,9 +1090,6 @@ int kfd_criu_restore_queue(struct kfd_process *p, mqd = q_extra_data; ctl_stack = mqd + q_data->mqd_size; -memset (&qp,0 ,sizeof (qp)); -set_queue_properties_from_criu (&qp, q_data,NUM_XCC (pdd->dev->xcc_mask)); -print_queue_properties (&qp); ret =pqm_create_queue (&p->pqm, pdd->dev, &qp, &queue_id, q_data, mqd, ctl_stack,NULL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1177/1257 drm/amdkfd: tear down KFD processes before early fini_sw on disconnect
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Olivier Kaloudoff <[email protected]>
[ Upstream commit 1233dd17f99c75787a31035656ecfeff80522421 ]
On surprise removal, amdgpu_device_fini_hw() calls amdgpu_amdkfd_device_fini_sw() when pci_dev_is_disconnected() is true. fini_sw frees kfd.dev, but KFD processes may still be alive and hold references to it: kfd_process_destroy() dereferences kfd.dev via kfd_processes_remove(), and svm_range_list_fini() / kfd_process_free_outstanding_kfd_bos() touch per-device SVM state.
The kfd_processes_count wait only happens later in kgd2kfd_teardown_processes(), called from the top-half remove path well after fini_sw. In the observed failure the killed KFD process (SIGBUS on unplug) stuck in D state on its exit path, so kfd_processes_count never drained and the PCIe removal thread wedged permanently in cond_resched(), producing soft-lockup and hung-task splats.
Tear KFD processes down before freeing kfd.dev on the disconnect path, and guard kgd2kfd_teardown_processes() against kfd.dev already being gone when it runs a second time.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 5 ++++- drivers/gpu/drm/amd/amdkfd/kfd_device.c | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +4 -1
@@ -4319,8 +4319,11 @@ void amdgpu_device_fini_hw(struct amdgpu_device *adev)* before ip_fini_early to prevent kfd locking refcount issues by calling * amdgpu_amdkfd_suspend() */ -if (pci_dev_is_disconnected (adev->pdev)) +if (pci_dev_is_disconnected (adev->pdev)) { +/* Drain KFD processes while kfd.dev is still valid */ +amdgpu_amdkfd_teardown_processes (adev);amdgpu_amdkfd_device_fini_sw (adev); + }amdgpu_coredump_fini (adev);amdgpu_device_ip_fini_early (adev);
drivers/gpu/drm/amd/amdkfd/kfd_device.c +8 -1
@@ -1801,7 +1801,14 @@ void kgd2kfd_teardown_processes(struct amdgpu_device *adev)mutex_unlock (&kfd_processes_mutex); -/* wait all kfd processes use adev terminate */ +/* kfd.dev may already be freed on surprise removal */ +if (!adev->kfd.dev) +return ; + +/* +* Wait for all KFD processes using adev to terminate. Must be +* unbounded: device state is freed once they are gone. +*/ while (!!atomic_read (&adev->kfd.dev->kfd_processes_count))cond_resched (); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1178/1257 drm/amdkfd: stop restore retries on device unplug
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Olivier Kaloudoff <[email protected]>
[ Upstream commit 3254ed0b15f2fe656c9cb36ccb59b92422440bf8 ]
amdgpu_amdkfd_restore_userptr_worker() and svm_range_restore_work() reschedule themselves when validation fails with evicted objects pending. After a surprise removal the restore paths fail with -ENODEV permanently, so rescheduling just spins the worker uselessly until cancel_delayed_work_sync() in fini finally stops it - which can take a while, since process teardown itself is delayed by the dead device.
Treat -ENODEV as terminal in both workers.
--- .../gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 18 +++++++++++++----- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 8 +++++--- 2 files changed, 18 insertions(+), 8 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +13 -5
@@ -2854,6 +2854,7 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)struct task_struct *usertask;struct mm_struct *mm;uint32_t evicted_bos; +int ret;mutex_lock (&process_info->notifier_lock); evicted_bos = process_info->evicted_bos;
@@ -2873,14 +2874,16 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)mutex_lock (&process_info->lock); -if (update_invalid_user_pages (process_info, mm)) + ret =update_invalid_user_pages (process_info, mm); +if (ret) goto unlock_out;/* userptr_inval_list can be empty if all evicted userptr BOs * have been freed. In that case there is nothing to validate * and we can just restart the queues. */ if (!list_empty (&process_info->userptr_inval_list)) { -if (validate_invalid_user_pages (process_info)) + ret =validate_invalid_user_pages (process_info); +if (ret) goto unlock_out; }/* Final check for concurrent evicton and atomic update. If
@@ -2889,11 +2892,14 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)* reference counting inside KFD will handle this case. */ mutex_lock (&process_info->notifier_lock); -if (process_info->evicted_bos != evicted_bos) +if (process_info->evicted_bos != evicted_bos) { + ret = -EAGAIN ; goto unlock_notifier_out; + }if (confirm_valid_user_pages_locked (process_info)) {WARN (1 ,"User pages unexpectedly invalid" ); + ret = -EINVAL ; goto unlock_notifier_out; }
@@ -2911,8 +2917,10 @@ static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work) unlock_out:mutex_unlock (&process_info->lock); -/* If validation failed, reschedule another attempt */ -if (evicted_bos) { +/* If validation failed, reschedule another attempt, unless the +* device is gone for good +*/ +if (evicted_bos && ret != -ENODEV ) {queue_delayed_work (system_freezable_wq, &process_info->restore_userptr_work,msecs_to_jiffies (AMDGPU_USERPTR_RESTORE_DELAY_MS ));
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +5 -3
@@ -1942,7 +1942,7 @@ static void svm_range_restore_work(struct work_struct *work)struct mm_struct *mm;int evicted_ranges;int invalid; -int r; +int r =0 ; svms = container_of(dwork, struct svm_range_list, restore_work); evicted_ranges =atomic_read (&svms->evicted_ranges);
@@ -2016,8 +2016,10 @@ static void svm_range_restore_work(struct work_struct *work)mmap_write_unlock (mm);mutex_unlock (&process_info->lock); -/* If validation failed, reschedule another attempt */ -if (evicted_ranges) { +/* If validation failed, reschedule another attempt, unless the +* device is gone for good +*/ +if (evicted_ranges && r != -ENODEV ) {pr_debug ("reschedule to restore svm range\n" );queue_delayed_work (system_freezable_wq, &svms->restore_work,msecs_to_jiffies (AMDGPU_SVM_RANGE_RESTORE_DELAY_MS ));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1179/1257 drm/amdgpu: guard VCE/UVD sched entity teardown on failed probe
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Olivier Kaloudoff <[email protected]>
[ Upstream commit c3fed6272bb4771a849c33c781af99afa90e90ad ]
Since commit 037b98a2312e ("drm/amdgpu: move UVD and VCE sched entity init after sched init"), drm_sched_entity_init() for the VCE and UVD kernel entities runs in the scheduler-init phase, well after the IP-block sw_init phase has allocated the vcpu_bos.
If probe fails between the two phases, amdgpu_device_fini_sw() still runs the per-IP sw_fini callbacks for blocks that did complete sw_init. Both amdgpu_vce_sw_fini() and amdgpu_uvd_sw_fini() then call drm_sched_entity_destroy() on an entity that was never initialized:entity->rq is NULL and drm_sched_entity_flush() dereferences it, oopsing in whatever context drove the failed probe.
The hole was latent-but-safe until commit 2df5efb45425 ("drm/sched:
Remove redundant entity->rq initialization and checks") removed the if (!entity->rq) early return that commit 1decbf6bb0b4 ("drm/sched:
Fix entities with 0 rqs.") had put in drm_sched_entity_flush(), on the grounds that entity->rq can never be NULL. That holds only for entities that completed drm_sched_entity_init() — not for the never-initialized entity this teardown path reaches.
Observed on real hardware: MI50 (Vega20, VCE 4.0 / UVD 7.2) behind a Thunderbolt link — a pciehp presence/link-change event re-probes the device; when the re-probe fails (-EINVAL here), the cleanup path NULL-derefs inside drm_sched_entity_flush() in the pciehp IRQ thread and takes the whole machine down (panic_on_oops, EFI pstore capture). Reproduced twice on 7.3-rc5, 2026-10-06 and 2026-10-09, identical signature; the faulting instruction is mov (%rax),%r15 on rax = entity->rq == NULL, i.e. sched = entity->rq->sched:
BUG: kernel NULL pointer dereference RIP: drm_sched_entity_flush+0x34/0x2d0 [gpu_sched] drm_sched_entity_destroy amdgpu_vce_sw_fini vce_v4_0_sw_fini amdgpu_device_fini_sw ... pciehp_configure_device pciehp_handle_presence_or_link_change
Guard the entity teardown on entity->rq, which is set only by drm_sched_entity_init(). amdgpu_ring_fini() already self-guards via the rings[] registration, and the vcpu_bo/firmware cleanup still runs as before.
v2: retarget Fixes: at commit 2df5efb45425 ("drm/sched: Remove redundant entity->rq initialization and checks") — the !entity->rq check from commit 1decbf6bb0b4 ("drm/sched: Fix entities with 0 rqs.") that Alex pointed to was removed by it in the 7.3 window, so this is a regression there, not a pre-existing hole.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c | 3 ++- drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c +2 -1
@@ -377,7 +377,8 @@ int amdgpu_uvd_sw_fini(struct amdgpu_device *adev)void *addr =amdgpu_bo_kptr (adev->uvd.ib_bo);int i, j; -drm_sched_entity_destroy (&adev->uvd.entity); +if (adev->uvd.entity.rq) +drm_sched_entity_destroy (&adev->uvd.entity);for (j =0 ; j < adev->uvd.num_uvd_inst; ++j) {if (adev->uvd.harvest_config & (1 << j))
drivers/gpu/drm/amd/amdgpu/amdgpu_vce.c +2 -1
@@ -253,7 +253,8 @@ int amdgpu_vce_sw_fini(struct amdgpu_device *adev)if (adev->vce.vcpu_bo ==NULL )return 0 ; -drm_sched_entity_destroy (&adev->vce.entity); +if (adev->vce.entity.rq) +drm_sched_entity_destroy (&adev->vce.entity);for (i =0 ; i < adev->vce.num_rings; i++)amdgpu_ring_fini (&adev->vce.ring[i]);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1180/1257 drm/amd/display: take a runtime PM reference only when a CRTC turns on
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luigi Lauro <[email protected]>
[ Upstream commit b456f591f925fbd6b33770d0eec1b51c2f9d41c1 ]
amdgpu_dm_commit_streams() takes a runtime PM reference for every active CRTC that needs a modeset and has a new stream, but amdgpu_dm_atomic_commit_tail() drops one only for each CRTC that goes from active to inactive. A modeset of a CRTC that is already active (a mode change, or anything else that needs a full modeset) therefore leaks one reference. Once that has happened, the usage count no longer returns to zero with every CRTC off, and the device cannot runtime suspend again until reboot. The two also disagree the other way when a CRTC turns on without a stream ("Failed to create new stream"): no reference is taken, but one is dropped when it turns off.
Take the reference in the loop that counts the disabled CRTCs, on the mirror condition: when the CRTC goes from inactive to active, which is what the commit that added it intended ("every time we enable a previously disabled CRTC"). Each active CRTC then holds exactly one reference.
Tested on an RX 9070 XT (Navi 48) over OCuLink, with the change backported to 7.2.9: an unplugged connector forced on, then mode A on a CRTC, mode B on the same active CRTC, and the CRTC off, three rounds in a row. The usage count rose by 3 with the stock module, by 0 with this patch, and by 3 again after reloading the stock module.
--- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +7 -4
@@ -4597,8 +4597,6 @@ static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,if (dm_old_crtc_state->stream)remove_stream (adev, acrtc, dm_old_crtc_state->stream); -pm_runtime_get_noresume (dev->dev); - acrtc->enabled = true; acrtc->hw_mode = new_crtc_state->mode; crtc->hwmode = new_crtc_state->mode;
@@ -5178,8 +5176,13 @@ static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)#ifdef CONFIG_DEBUG_FS enum amdgpu_dm_pipe_crc_source cur_crc_src;#endif -/* Count number of newly disabled CRTCs for dropping PM refs later. */ -if (old_crtc_state->active && !new_crtc_state->active) +/* +* One runtime PM reference per active CRTC: take it when the +* CRTC turns on, count it when it turns off for dropping later. +*/ +if (!old_crtc_state->active && new_crtc_state->active) +pm_runtime_get_noresume (dev->dev); +else if (old_crtc_state->active && !new_crtc_state->active) crtc_disable_count++; dm_new_crtc_state =to_dm_crtc_state (new_crtc_state);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1181/1257 drm/amdgpu: reject CS chunks too large for kvmalloc()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit ba4c3c202919405f461a393e823e4b72c8518494 ]
The CS ioctl copies every chunk with vmemdup_array_user() before it looks at it, for whatever length_dw userspace gives. kvmalloc() warns about allocations above INT_MAX when called without __GFP_NOWARN, so any process with the render node can trigger a warning. On navi31, a CS with a chunk of length_dw 0x20000000 returns -ENOMEM after:
WARNING: mm/slub.c:6841 at __kvmalloc_node_noprof+0x5a5/0x7d0
Reject such chunks with -EINVAL before trying to copy them.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c +6 -0
@@ -217,6 +217,12 @@ static int amdgpu_cs_pass1(struct amdgpu_cs_parser *p, size = p->chunks[i].length_dw; +if (size >INT_MAX /sizeof (uint32_t )) { + ret = -EINVAL ; + i--; + goto free_partial_kdata; + } + p->chunks[i].kdata =vmemdup_array_user (u64_to_user_ptr (user_chunk.chunk_data), size,sizeof (uint32_t ));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1182/1257 drm/amdkfd: split vram_pages of SVM ranges prefetched without a GPU mapping
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit 52957e813f2f025c86e4aa6e86cb4963ef94fd00 ]
When an SVM range is split, svm_range_split_pages() gives the new range the number of VRAM pages counted in its part of the dma_addr arrays and subtracts it from the old range. Pages migrated to VRAM by a prefetch have no dma_addr entries until the range is mapped on a GPU, e.g. with no ACCESS attribute, or with XNACK off before the delayed restore worker mapped it, so the new range gets 0 and the old one keeps the count for both.
Migrating the parts back to system memory then gets the accounting
wrong: the old part keeps a VRAM page count after all its pages are gone, so its svm_bo is never freed, and the new part underflows. On navi31, as an unprivileged process: prefetch 4 MiB to the GPU, prefetch the upper 2 MiB and then the lower 2 MiB back to system memory:
Recorded vram pages(0x0) should not be less than migration pages(0x200).
WARNING: ../amdkfd/kfd_migrate.c:922 at svm_migrate_vram_to_ram+0xbdc/0xcd0 [amdgpu]
and /sys/class/kfd/kfd/proc/<pid>/vram_<gpu_id> stays at 4194304 until the process exits.
Without dma_addr arrays, the split is still exact when the old range is completely in VRAM, which is what a prefetch of the whole range leaves. Give the new range all its pages in that case. The warning is gone and the VRAM usage drops back to 0.
This doesn't cover a range that is only partly in VRAM without dma_addr arrays, e.g. after a partial migration, since svm_migrate_ram_to_vram() only counts the pages it actually migrated. That would need VRAM residency to be tracked per page independently of dma_addr.
v2:
- Rename counted to has_dma_addr and compare against old->npages (Philip)
- Mention the XNACK off case and the partial migration limitation (Philip)
--- drivers/gpu/drm/amd/amdkfd/kfd_svm.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdkfd/kfd_svm.c +12 -1
@@ -1019,9 +1019,12 @@ svm_range_split_pages(struct svm_range *new, struct svm_range *old, uint64_t start, uint64_t last) { uint64_t npages = last - start + 1; +bool has_dma_addr = false;int i, r; for (i = 0; i < MAX_GPU_INSTANCE; i++) { + if (old->dma_addr[i]) + has_dma_addr = true; r = svm_range_split_array(&new->dma_addr[i], &old->dma_addr[i], sizeof(*old->dma_addr[i]), old->start, npages, new->start, new->npages,
@@ -1029,8 +1032,16 @@ svm_range_split_pages(struct svm_range *new, struct svm_range *old,if (r)return r; } -if (old->actual_loc) +if (old->actual_loc) { +/* +* Pages migrated by prefetch have no dma_addr until they are +* mapped on a GPU. A fully resident range still splits exactly, +* old->npages isn't adjusted yet here. +*/ +if (!has_dma_addr && old->vram_pages == old->npages) + new->vram_pages = new->npages; old->vram_pages -= new->vram_pages; + }return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1183/1257 drm/amd/display: Initialize missing TD-LUT programming inputs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
[ Upstream commit 167df3b94680b8670c4cacc08af232e3bfcab5ff ]
dml_core_mode_programming() memsets (clears) its scratch structure before calculating TD-LUT settings, but does not initialize tdlut_mpc_width_flag or is_gfx11.
Both inputs therefore remain false regardless of the plane configuration which can result in incorrect calculations.
Initialize both fields using the same sources as the mode support path (now both paths are aligned).
--- .../dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn4_calcs.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn4_calcs.c +2 -0
@@ -11074,6 +11074,8 @@ static bool dml_core_mode_programming(struct dml2_core_calcs_mode_programming_ex calculate_tdlut_setting_params->cursor_buffer_size = mode_lib->ip.cursor_buffer_size; calculate_tdlut_setting_params->gpuvm_enable = display_cfg->gpuvm_enable; calculate_tdlut_setting_params->gpuvm_page_size_kbytes = display_cfg->plane_descriptors[k].overrides.gpuvm_min_page_size_kbytes; + calculate_tdlut_setting_params->tdlut_mpc_width_flag = display_cfg->plane_descriptors[k].tdlut.tdlut_mpc_width_flag; + calculate_tdlut_setting_params->is_gfx11 =dml_get_gfx_version (display_cfg->plane_descriptors[k].surface.tiling);// output calculate_tdlut_setting_params->tdlut_pte_bytes_per_frame = &s->tdlut_pte_bytes_per_frame[k];
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1184/1257 drm/amd/pm: preserve committed OD features for SMU 13.0.0/13.0.7
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kevin Wang <[email protected]>
[ Upstream commit 6027db7db773714f2e05df82093276f2a52a1fba ]
PMFW treats FeatureCtrlMask as the complete set of active OD features. Uploads containing only newly edited bits can drop earlier settings.
Fix the OD state handling to:
- preserve committed features across later commits
- keep staged OD settings out of power-cap writes
- update cached state only after successful uploads
- clear restored features only after they return to defaults
- restore PPT for the current AC/DC source after resume
--- .../drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c | 193 +++++++++++++----- .../drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c | 193 +++++++++++++----- 2 files changed, 293 insertions(+), 93 deletions(-)
drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c +147 -46
@@ -63,6 +63,9 @@ static void smu_v13_0_0_get_od_setting_limits(struct smu_context *smu,int od_feature_bit, int32_t *min, int32_t *max);static int smu_v13_0_0_init_ppt_limits (struct smu_context *smu); +static int +smu_v13_0_0_upload_overdrive_table (struct smu_context *smu, +OverDriveTableExternal_t *od_table);static const struct smu_feature_bits smu_v13_0_0_dpm_features = { .bits = {
@@ -1079,6 +1082,93 @@ static bool smu_v13_0_0_is_od_feature_supported(struct smu_context *smu,return feature_enabled; } +static u32 +smu_v13_0_0_filter_od_feature_mask (struct smu_context *smu,u32 feature_mask) +{ +PPTable_t *pptable = smu->smu_table.driver_pptable; +u32 supported_mask = + pptable->SkuTable.OverDriveLimitsBasicMax.FeatureCtrlMask; + +return feature_mask & supported_mask; +} + +static bool smu_v13_0_0_fan_is_default (const OverDriveTable_t *od, +const OverDriveTable_t *boot) +{ +return !memcmp (od->FanLinearPwmPoints, boot->FanLinearPwmPoints, +sizeof (od->FanLinearPwmPoints)) && + !memcmp (od->FanLinearTempPoints, boot->FanLinearTempPoints, +sizeof (od->FanLinearTempPoints)) && + od->FanMinimumPwm == boot->FanMinimumPwm && + od->AcousticTargetRpmThreshold == boot->AcousticTargetRpmThreshold && + od->AcousticLimitRpmThreshold == boot->AcousticLimitRpmThreshold && + od->FanTargetTemperature == boot->FanTargetTemperature && + od->FanMode == boot->FanMode; +} + +static bool smu_v13_0_0_zero_fan_is_default (const OverDriveTable_t *od, +const OverDriveTable_t *boot) +{ +return od->FanZeroRpmEnable == boot->FanZeroRpmEnable && + od->FanZeroRpmStopTemp == boot->FanZeroRpmStopTemp; +} + +static u32 smu_v13_0_0_normalize_feature_mask (const OverDriveTable_t *od, +const OverDriveTable_t *boot, +u32 feature_mask) +{ +if (od->GfxclkFmin == boot->GfxclkFmin && + od->GfxclkFmax == boot->GfxclkFmax) + feature_mask &= ~BIT (PP_OD_FEATURE_GFXCLK_BIT ); +if (od->UclkFmin == boot->UclkFmin && + od->UclkFmax == boot->UclkFmax) + feature_mask &= ~BIT (PP_OD_FEATURE_UCLK_BIT ); +if (!memcmp (od->VoltageOffsetPerZoneBoundary, + boot->VoltageOffsetPerZoneBoundary, +sizeof (od->VoltageOffsetPerZoneBoundary))) + feature_mask &= ~BIT (PP_OD_FEATURE_GFX_VF_CURVE_BIT ); +if (smu_v13_0_0_fan_is_default (od, boot)) + feature_mask &= ~BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); +if (smu_v13_0_0_zero_fan_is_default (od, boot)) + feature_mask &= ~BIT (PP_OD_FEATURE_ZERO_FAN_BIT ); +if (!od->Ppt) + feature_mask &= ~BIT (PP_OD_FEATURE_PPT_BIT ); + +return feature_mask; +} + +static int +smu_v13_0_0_upload_ppt_overdrive_table (struct smu_context *smu,s16 ppt) +{ +struct smu_table_context *table_context = &smu->smu_table; +OverDriveTableExternal_t *od_table = table_context->overdrive_table; +OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; +OverDriveTableExternal_t upload_table; +u32 next_mask = table_context->user_od_feature_mask; +int ret; + +/* Do not commit OD settings staged after the last c operation. */ +memcpy (&upload_table, user_od_table,sizeof (upload_table)); + upload_table.OverDriveTable.Ppt = ppt; +if (ppt) + next_mask |=BIT (PP_OD_FEATURE_PPT_BIT ); +else + next_mask &= ~BIT (PP_OD_FEATURE_PPT_BIT ); + upload_table.OverDriveTable.FeatureCtrlMask = +smu_v13_0_0_filter_od_feature_mask (smu, next_mask); + + ret =smu_v13_0_0_upload_overdrive_table (smu, &upload_table); +if (ret) +return ret; + + table_context->user_od_feature_mask = + upload_table.OverDriveTable.FeatureCtrlMask; + od_table->OverDriveTable.Ppt = ppt; + user_od_table->OverDriveTable.Ppt = ppt; + +return 0 ; +} + static void smu_v13_0_0_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min,
@@ -1514,41 +1604,30 @@ static int smu_v13_0_0_od_restore_table_single(struct smu_context *smu, long inp boot_overdrive_table->OverDriveTable.FanLinearPwmPoints[i]; } od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_ACOUSTIC_LIMIT : od_table->OverDriveTable.AcousticLimitRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticLimitRpmThreshold; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_ACOUSTIC_TARGET : od_table->OverDriveTable.AcousticTargetRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticTargetRpmThreshold; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_FAN_TARGET_TEMPERATURE : od_table->OverDriveTable.FanTargetTemperature = boot_overdrive_table->OverDriveTable.FanTargetTemperature; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_FAN_MINIMUM_PWM : od_table->OverDriveTable.FanMinimumPwm = boot_overdrive_table->OverDriveTable.FanMinimumPwm; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_FAN_ZERO_RPM_ENABLE : od_table->OverDriveTable.FanZeroRpmEnable = boot_overdrive_table->OverDriveTable.FanZeroRpmEnable; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_ZERO_FAN_BIT );break ;case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP : od_table->OverDriveTable.FanZeroRpmStopTemp = boot_overdrive_table->OverDriveTable.FanZeroRpmStopTemp; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_ZERO_FAN_BIT );break ;default :dev_info (adev->dev,"Invalid table index: %ld\n" , input);
@@ -1566,9 +1645,17 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu,struct smu_table_context *table_context = &smu->smu_table;OverDriveTableExternal_t *od_table = (OverDriveTableExternal_t *)table_context->overdrive_table; +OverDriveTableExternal_t *user_od_table = + (OverDriveTableExternal_t *)table_context->user_overdrive_table; +OverDriveTableExternal_t *boot_od_table = + (OverDriveTableExternal_t *)table_context->boot_overdrive_table; +OverDriveTableExternal_t upload_table; +OverDriveTable_t *od = &od_table->OverDriveTable; +OverDriveTable_t *boot = &boot_od_table->OverDriveTable;struct amdgpu_device *adev = smu->adev;uint32_t offset_of_voltageoffset;int32_t minimum, maximum; +u32 next_mask;int i, ret =0 ;switch (type) {
@@ -1892,36 +1979,41 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu, }else {memcpy (od_table, table_context->boot_overdrive_table, -sizeof (OverDriveTableExternal_t)); +sizeof (OverDriveTableExternal_t)); od_table->OverDriveTable.FeatureCtrlMask =0 ; - table_context->user_od_feature_mask =0 ; } fallthrough;case PP_OD_COMMIT_DPM_TABLE : - table_context->user_od_feature_mask = - od_table->OverDriveTable.FeatureCtrlMask; offset_of_voltageoffset = offsetof(OverDriveTable_t , VoltageOffsetPerZoneBoundary); -if (memcmp ((u8 *)od_table + offset_of_voltageoffset, - table_context->user_overdrive_table + offset_of_voltageoffset, -sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset)) { -smu_v13_0_0_dump_od_table (smu, od_table); + next_mask =smu_v13_0_0_filter_od_feature_mask (smu, + table_context->user_od_feature_mask | + od->FeatureCtrlMask); + next_mask =smu_v13_0_0_normalize_feature_mask (od, boot, + next_mask); - ret =smu_v13_0_0_upload_overdrive_table (smu, od_table); +if (memcmp ((u8 *)od_table + offset_of_voltageoffset, + (u8 *)user_od_table + offset_of_voltageoffset, +sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset) || + next_mask != table_context->user_od_feature_mask) { +memcpy (&upload_table, od_table,sizeof (upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; +smu_v13_0_0_dump_od_table (smu, &upload_table); + + ret =smu_v13_0_0_upload_overdrive_table (smu, &upload_table);if (ret) {dev_err (adev->dev,"Failed to upload overdrive table!\n" );return ret; } -memcpy (table_context->user_overdrive_table + offset_of_voltageoffset, + table_context->user_od_feature_mask = next_mask; + od_table->OverDriveTable.FeatureCtrlMask =0 ; +memcpy ((u8 *)user_od_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset,sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset); + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; -if (!memcmp (table_context->user_overdrive_table, - table_context->boot_overdrive_table, -sizeof (OverDriveTableExternal_t))) - smu->user_dpm_profile.user_od = false; -else - smu->user_dpm_profile.user_od = true; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT (PP_OD_FEATURE_PPT_BIT )); }break ;
@@ -2184,6 +2276,7 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu)memcpy (od_table, boot_od_table,sizeof (OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask =0 ;/* * For S3/S4/Runpm resume, we need to setup those overdrive tables again,
@@ -2193,6 +2286,7 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu)memcpy (user_od_table, boot_od_table,sizeof (OverDriveTableExternal_t)); + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; smu->user_dpm_profile.user_od = false; smu->smu_table.user_od_feature_mask =0 ; }else if (smu->user_dpm_profile.user_od) {
@@ -2231,6 +2325,14 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu) user_od_table_bak.OverDriveTable.FanZeroRpmEnable; user_od_table->OverDriveTable.FanZeroRpmStopTemp = user_od_table_bak.OverDriveTable.FanZeroRpmStopTemp; + user_od_table->OverDriveTable.FanMode = + user_od_table_bak.OverDriveTable.FanMode; + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; + } +if (smu->adev->in_suspend) { + user_od_table->OverDriveTable.Ppt =0 ; + smu->smu_table.user_od_feature_mask &= + ~BIT (PP_OD_FEATURE_PPT_BIT ); }smu_v13_0_0_set_supported_od_feature_mask (smu);
@@ -2243,13 +2345,22 @@ static int smu_v13_0_0_restore_user_od_settings(struct smu_context *smu)struct smu_table_context *table_context = &smu->smu_table;OverDriveTableExternal_t *od_table = table_context->overdrive_table;OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; +OverDriveTableExternal_t upload_table; +u32 next_mask;int res; - user_od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - res =smu_v13_0_0_upload_overdrive_table (smu, user_od_table); - user_od_table->OverDriveTable.FeatureCtrlMask =0 ; -if (res ==0 ) + + next_mask =smu_v13_0_0_filter_od_feature_mask (smu, + table_context->user_od_feature_mask); +memcpy (&upload_table, user_od_table,sizeof (upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + res =smu_v13_0_0_upload_overdrive_table (smu, &upload_table); +if (res ==0 ) { + table_context->user_od_feature_mask = next_mask; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT (PP_OD_FEATURE_PPT_BIT ));memcpy (od_table, user_od_table,sizeof (OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask =0 ; + }return res; }
@@ -3043,10 +3154,8 @@ static int smu_v13_0_0_set_ppt_limit(struct smu_context *smu,SkuTable_t *skutable = &pptable->SkuTable;uint32_t msg_limit = skutable->MsgLimits.Power [PPT_THROTTLER_PPT0 ][POWER_SOURCE_AC ]; -struct smu_table_context *table_context = &smu->smu_table; -OverDriveTableExternal_t *od_table = - (OverDriveTableExternal_t *)table_context->overdrive_table;OverDriveTableExternal_t current_od_table; +s16 ppt;int ret =0 ;if (limit_type !=SMU_PPT_LIMIT_PPT0 )
@@ -3058,12 +3167,7 @@ static int smu_v13_0_0_set_ppt_limit(struct smu_context *smu,return ret;if (current_od_table.OverDriveTable.Ppt) { - od_table->OverDriveTable.Ppt =0 ; - table_context->user_od_feature_mask &= - ~(1U <<PP_OD_FEATURE_PPT_BIT ); - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - ret =smu_v13_0_0_upload_overdrive_table (smu, od_table); + ret =smu_v13_0_0_upload_ppt_overdrive_table (smu,0 );if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );return ret;
@@ -3075,11 +3179,8 @@ static int smu_v13_0_0_set_ppt_limit(struct smu_context *smu,if (ret)return ret; - od_table->OverDriveTable.Ppt = (limit *100 ) / msg_limit -100 ; - table_context->user_od_feature_mask |=1U <<PP_OD_FEATURE_PPT_BIT ; - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - ret =smu_v13_0_0_upload_overdrive_table (smu, od_table); + ppt = (limit *100 ) / msg_limit -100 ; + ret =smu_v13_0_0_upload_ppt_overdrive_table (smu, ppt);if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );return ret;
drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c +146 -47
316 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1185/1257 drm/amd/pm: preserve committed OD features for SMU 14.0.2
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kevin Wang <[email protected]>
[ Upstream commit 9b0890e72d19b0c430fe62bad290c7c79baa78e4 ]
PMFW treats FeatureCtrlMask as the complete set of active OD features. Uploads containing only newly edited bits can drop earlier settings.
Fix the OD state handling to:
- preserve committed features across later commits
- keep fan-curve and legacy-fan bits mutually exclusive
- keep staged OD settings out of power-cap writes
- update cached state only after successful uploads
- clear restored features only after they return to defaults
- restore PPT for the current AC/DC source after resume
--- .../drm/amd/pm/swsmu/smu14/smu_v14_0_2_ppt.c | 230 +++++++++++++----- 1 file changed, 171 insertions(+), 59 deletions(-)
drivers/gpu/drm/amd/pm/swsmu/smu14/smu_v14_0_2_ppt.c +171 -59
@@ -91,6 +91,10 @@ static const struct smu_feature_bits smu_v14_0_2_dpm_features = {#define PP_OD_FEATURE_FAN_ZERO_RPM_ENABLE 11#define PP_OD_FEATURE_FAN_ZERO_RPM_STOP_TEMP 12 +#define SMU_14_0_2_OD_FAN_FEATURE_MASK \ + (BIT(PP_OD_FEATURE_FAN_CURVE_BIT) | \ + BIT(PP_OD_FEATURE_FAN_LEGACY_BIT)) +static struct cmn2asic_msg_mapping smu_v14_0_2_message_map[SMU_MSG_MAX_COUNT ] = {MSG_MAP (TestMessage, PPSMC_MSG_TestMessage,1 ),MSG_MAP (GetSmuVersion, PPSMC_MSG_GetSmuVersion,1 ),
@@ -963,6 +967,84 @@ static bool smu_v14_0_2_is_od_feature_supported(struct smu_context *smu,return feature_enabled; } +static u32 +smu_v14_0_2_filter_od_feature_mask (struct smu_context *smu,u32 feature_mask) +{ +PPTable_t *pptable = smu->smu_table.driver_pptable; +u32 supported_mask = + pptable->SkuTable.OverDriveLimitsBasicMax.FeatureCtrlMask; + +return feature_mask & supported_mask; +} + +static u32 +smu_v14_0_2_get_od_feature_mask (struct smu_context *smu,u32 pending_mask) +{ +u32 supported_mask =smu_v14_0_2_filter_od_feature_mask (smu, ~0U ); +u32 fan_mask = supported_mask &SMU_14_0_2_OD_FAN_FEATURE_MASK ; +u32 mask = smu->smu_table.user_od_feature_mask; + +if (pending_mask & fan_mask) + mask &= ~fan_mask; + mask |= pending_mask; + +return smu_v14_0_2_filter_od_feature_mask (smu, mask); +} + +static bool smu_v14_0_2_fan_is_default (const OverDriveTable_t *od, +const OverDriveTable_t *boot) +{ +return !memcmp (od->FanLinearPwmPoints, boot->FanLinearPwmPoints, +sizeof (od->FanLinearPwmPoints)) && + !memcmp (od->FanLinearTempPoints, boot->FanLinearTempPoints, +sizeof (od->FanLinearTempPoints)) && + od->AcousticTargetRpmThreshold == boot->AcousticTargetRpmThreshold && + od->AcousticLimitRpmThreshold == boot->AcousticLimitRpmThreshold && + od->FanTargetTemperature == boot->FanTargetTemperature && + od->FanMode == boot->FanMode; +} + +static bool smu_v14_0_2_legacy_fan_is_default (const OverDriveTable_t *od, +const OverDriveTable_t *boot) +{ +return od->FanMinimumPwm == boot->FanMinimumPwm && + od->FanMode == boot->FanMode; +} + +static bool smu_v14_0_2_zero_fan_is_default (const OverDriveTable_t *od, +const OverDriveTable_t *boot) +{ +return od->FanZeroRpmEnable == boot->FanZeroRpmEnable && + od->FanZeroRpmStopTemp == boot->FanZeroRpmStopTemp; +} + +static u32 smu_v14_0_2_normalize_feature_mask (const OverDriveTable_t *od, +const OverDriveTable_t *boot, +u32 feature_mask) +{ +if (od->GfxclkFoffset == boot->GfxclkFoffset) + feature_mask &= ~BIT (PP_OD_FEATURE_GFXCLK_BIT ); +if (od->UclkFmin == boot->UclkFmin && + od->UclkFmax == boot->UclkFmax) + feature_mask &= ~BIT (PP_OD_FEATURE_UCLK_BIT ); +if (!memcmp (od->VoltageOffsetPerZoneBoundary, + boot->VoltageOffsetPerZoneBoundary, +sizeof (od->VoltageOffsetPerZoneBoundary))) + feature_mask &= ~BIT (PP_OD_FEATURE_GFX_VF_CURVE_BIT ); +if ((feature_mask &BIT (PP_OD_FEATURE_FAN_CURVE_BIT )) && +smu_v14_0_2_fan_is_default (od, boot)) + feature_mask &= ~BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); +if ((feature_mask &BIT (PP_OD_FEATURE_FAN_LEGACY_BIT )) && +smu_v14_0_2_legacy_fan_is_default (od, boot)) + feature_mask &= ~BIT (PP_OD_FEATURE_FAN_LEGACY_BIT ); +if (smu_v14_0_2_zero_fan_is_default (od, boot)) + feature_mask &= ~BIT (PP_OD_FEATURE_ZERO_FAN_BIT ); +if (!od->Ppt) + feature_mask &= ~BIT (PP_OD_FEATURE_PPT_BIT ); + +return feature_mask; +} + static void smu_v14_0_2_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min,
@@ -2317,6 +2399,38 @@ static int smu_v14_0_2_upload_overdrive_table(struct smu_context *smu,return ret; } +static int +smu_v14_0_2_upload_ppt_overdrive_table (struct smu_context *smu,s16 ppt) +{ +struct smu_table_context *table_context = &smu->smu_table; +OverDriveTableExternal_t *od_table = table_context->overdrive_table; +OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; +OverDriveTableExternal_t upload_table; +u32 next_mask = table_context->user_od_feature_mask; +int ret; + +/* Do not commit OD settings staged after the last c operation. */ +memcpy (&upload_table, user_od_table,sizeof (upload_table)); + upload_table.OverDriveTable.Ppt = ppt; +if (ppt) + next_mask |=BIT (PP_OD_FEATURE_PPT_BIT ); +else + next_mask &= ~BIT (PP_OD_FEATURE_PPT_BIT ); + upload_table.OverDriveTable.FeatureCtrlMask = +smu_v14_0_2_filter_od_feature_mask (smu, next_mask); + + ret =smu_v14_0_2_upload_overdrive_table (smu, &upload_table); +if (ret) +return ret; + + table_context->user_od_feature_mask = + upload_table.OverDriveTable.FeatureCtrlMask; + od_table->OverDriveTable.Ppt = ppt; + user_od_table->OverDriveTable.Ppt = ppt; + +return 0 ; +} +static void smu_v14_0_2_set_supported_od_feature_mask (struct smu_context *smu) {struct amdgpu_device *adev = smu->adev;
@@ -2375,6 +2489,7 @@ static int smu_v14_0_2_set_default_od_settings(struct smu_context *smu)memcpy (od_table, boot_od_table,sizeof (OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask =0 ;/* * For S3/S4/Runpm resume, we need to setup those overdrive tables again,
@@ -2384,6 +2499,7 @@ static int smu_v14_0_2_set_default_od_settings(struct smu_context *smu)memcpy (user_od_table, boot_od_table,sizeof (OverDriveTableExternal_t)); + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; smu->user_dpm_profile.user_od = false; smu->smu_table.user_od_feature_mask =0 ; }else if (smu->user_dpm_profile.user_od) {
@@ -2420,6 +2536,14 @@ static int smu_v14_0_2_set_default_od_settings(struct smu_context *smu) user_od_table_bak.OverDriveTable.FanZeroRpmEnable; user_od_table->OverDriveTable.FanZeroRpmStopTemp = user_od_table_bak.OverDriveTable.FanZeroRpmStopTemp; + user_od_table->OverDriveTable.FanMode = + user_od_table_bak.OverDriveTable.FanMode; + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; + } +if (smu->adev->in_suspend) { + user_od_table->OverDriveTable.Ppt =0 ; + smu->smu_table.user_od_feature_mask &= + ~BIT (PP_OD_FEATURE_PPT_BIT ); }smu_v14_0_2_set_supported_od_feature_mask (smu);
@@ -2432,14 +2556,22 @@ static int smu_v14_0_2_restore_user_od_settings(struct smu_context *smu)struct smu_table_context *table_context = &smu->smu_table;OverDriveTableExternal_t *od_table = table_context->overdrive_table;OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; +OverDriveTableExternal_t upload_table; +u32 next_mask;int res; - user_od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - res =smu_v14_0_2_upload_overdrive_table (smu, user_od_table); - user_od_table->OverDriveTable.FeatureCtrlMask =0 ; -if (res ==0 ) + next_mask =smu_v14_0_2_filter_od_feature_mask (smu, + table_context->user_od_feature_mask); +memcpy (&upload_table, user_od_table,sizeof (upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + res =smu_v14_0_2_upload_overdrive_table (smu, &upload_table); +if (res ==0 ) { + table_context->user_od_feature_mask = next_mask; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT (PP_OD_FEATURE_PPT_BIT ));memcpy (od_table, user_od_table,sizeof (OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask =0 ; + }return res; }
@@ -2463,43 +2595,30 @@ static int smu_v14_0_2_od_restore_table_single(struct smu_context *smu, long inp boot_overdrive_table->OverDriveTable.FanLinearPwmPoints[i]; } od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); - od_table->OverDriveTable.FeatureCtrlMask &= ~BIT (PP_OD_FEATURE_FAN_LEGACY_BIT );break ;case PP_OD_EDIT_FAN_ZERO_RPM_ENABLE : od_table->OverDriveTable.FanZeroRpmEnable = boot_overdrive_table->OverDriveTable.FanZeroRpmEnable; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_ZERO_FAN_BIT );break ;case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP : od_table->OverDriveTable.FanZeroRpmStopTemp = boot_overdrive_table->OverDriveTable.FanZeroRpmStopTemp; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_ZERO_FAN_BIT );break ;case PP_OD_EDIT_ACOUSTIC_LIMIT : od_table->OverDriveTable.AcousticLimitRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticLimitRpmThreshold; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_ACOUSTIC_TARGET : od_table->OverDriveTable.AcousticTargetRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticTargetRpmThreshold; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_FAN_TARGET_TEMPERATURE : od_table->OverDriveTable.FanTargetTemperature = boot_overdrive_table->OverDriveTable.FanTargetTemperature; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;case PP_OD_EDIT_FAN_MINIMUM_PWM : od_table->OverDriveTable.FanMinimumPwm = boot_overdrive_table->OverDriveTable.FanMinimumPwm; - od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; - od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_LEGACY_BIT ); - od_table->OverDriveTable.FeatureCtrlMask &= ~BIT (PP_OD_FEATURE_FAN_CURVE_BIT );break ;default :dev_info (adev->dev,"Invalid table index: %ld\n" , input);
@@ -2517,9 +2636,17 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu,struct smu_table_context *table_context = &smu->smu_table;OverDriveTableExternal_t *od_table = (OverDriveTableExternal_t *)table_context->overdrive_table; +OverDriveTableExternal_t *user_od_table = + (OverDriveTableExternal_t *)table_context->user_overdrive_table; +OverDriveTableExternal_t *boot_od_table = + (OverDriveTableExternal_t *)table_context->boot_overdrive_table; +OverDriveTableExternal_t upload_table; +OverDriveTable_t *od = &od_table->OverDriveTable; +OverDriveTable_t *boot = &boot_od_table->OverDriveTable;struct amdgpu_device *adev = smu->adev;uint32_t offset_of_voltageoffset;int32_t minimum, maximum; +u32 next_mask;int i, ret =0 ;switch (type) {
@@ -2691,6 +2818,7 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu, od_table->OverDriveTable.AcousticLimitRpmThreshold = input[0 ]; od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); + od_table->OverDriveTable.FeatureCtrlMask &= ~BIT (PP_OD_FEATURE_FAN_LEGACY_BIT );break ;case PP_OD_EDIT_ACOUSTIC_TARGET :
@@ -2713,6 +2841,7 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu, od_table->OverDriveTable.AcousticTargetRpmThreshold = input[0 ]; od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); + od_table->OverDriveTable.FeatureCtrlMask &= ~BIT (PP_OD_FEATURE_FAN_LEGACY_BIT );break ;case PP_OD_EDIT_FAN_TARGET_TEMPERATURE :
@@ -2735,6 +2864,7 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu, od_table->OverDriveTable.FanTargetTemperature = input[0 ]; od_table->OverDriveTable.FanMode =FAN_MODE_AUTO ; od_table->OverDriveTable.FeatureCtrlMask |=BIT (PP_OD_FEATURE_FAN_CURVE_BIT ); + od_table->OverDriveTable.FeatureCtrlMask &= ~BIT (PP_OD_FEATURE_FAN_LEGACY_BIT );break ;case PP_OD_EDIT_FAN_MINIMUM_PWM :
@@ -2812,44 +2942,38 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu, table_context->boot_overdrive_table, sizeof(OverDriveTableExternal_t)); od_table->OverDriveTable.FeatureCtrlMask =0 ; - table_context->user_od_feature_mask =0 ; } fallthrough;case PP_OD_COMMIT_DPM_TABLE : -/* -* PMFW interprets FeatureCtrlMask as the complete set of OD -* features that are currently overridden, not as a delta -* describing this single operation. Any feature whose bit is -* clear gets reset to its default on import. od_table's mask -* has accumulated every feature the user touched since the -* last full restore, so record it and keep restating it on -* subsequent uploads. -*/ - table_context->user_od_feature_mask = - od_table->OverDriveTable.FeatureCtrlMask; - offset_of_voltageoffset = offsetof(OverDriveTable_t , VoltageOffsetPerZoneBoundary); -if (memcmp ((u8 *)od_table + offset_of_voltageoffset, - table_context->user_overdrive_table + offset_of_voltageoffset, -sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset)) { -smu_v14_0_2_dump_od_table (smu, od_table); + next_mask =smu_v14_0_2_get_od_feature_mask (smu, + od->FeatureCtrlMask); + next_mask =smu_v14_0_2_normalize_feature_mask (od, boot, + next_mask); - ret =smu_v14_0_2_upload_overdrive_table (smu, od_table); +if (memcmp ((u8 *)od_table + offset_of_voltageoffset, + (u8 *)user_od_table + offset_of_voltageoffset, +sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset) || + next_mask != table_context->user_od_feature_mask) { +memcpy (&upload_table, od_table,sizeof (upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; +smu_v14_0_2_dump_od_table (smu, &upload_table); + + ret =smu_v14_0_2_upload_overdrive_table (smu, &upload_table);if (ret) {dev_err (adev->dev,"Failed to upload overdrive table!\n" );return ret; } -memcpy (table_context->user_overdrive_table + offset_of_voltageoffset, + table_context->user_od_feature_mask = next_mask; + od_table->OverDriveTable.FeatureCtrlMask =0 ; +memcpy ((u8 *)user_od_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset,sizeof (OverDriveTableExternal_t) - offset_of_voltageoffset); + user_od_table->OverDriveTable.FeatureCtrlMask =0 ; -if (!memcmp (table_context->user_overdrive_table, - table_context->boot_overdrive_table, -sizeof (OverDriveTableExternal_t))) - smu->user_dpm_profile.user_od = false; -else - smu->user_dpm_profile.user_od = true; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT (PP_OD_FEATURE_PPT_BIT )); }break ;
@@ -2867,10 +2991,8 @@ static int smu_v14_0_2_set_ppt_limit(struct smu_context *smu,PPTable_t *pptable = smu->smu_table.driver_pptable;uint32_t msg_limit = pptable->SkuTable.MsgLimits.Power [PPT_THROTTLER_PPT0 ][POWER_SOURCE_AC ]; -struct smu_table_context *table_context = &smu->smu_table; -OverDriveTableExternal_t *od_table = - (OverDriveTableExternal_t *)table_context->overdrive_table;OverDriveTableExternal_t current_od_table; +s16 ppt;int ret =0 ;if (limit_type !=SMU_PPT_LIMIT_PPT0 )
@@ -2882,13 +3004,7 @@ static int smu_v14_0_2_set_ppt_limit(struct smu_context *smu,return ret;if (current_od_table.OverDriveTable.Ppt) { - od_table->OverDriveTable.Ppt =0 ; - table_context->user_od_feature_mask &= - ~(1U <<PP_OD_FEATURE_PPT_BIT ); - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - - ret =smu_v14_0_2_upload_overdrive_table (smu, od_table); + ret =smu_v14_0_2_upload_ppt_overdrive_table (smu,0 );if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );return ret;
@@ -2900,12 +3016,8 @@ static int smu_v14_0_2_set_ppt_limit(struct smu_context *smu,if (ret)return ret; - od_table->OverDriveTable.Ppt = (limit *100 ) / msg_limit -100 ; - table_context->user_od_feature_mask |=1U <<PP_OD_FEATURE_PPT_BIT ; - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - - ret =smu_v14_0_2_upload_overdrive_table (smu, od_table); + ppt = (limit *100 ) / msg_limit -100 ; + ret =smu_v14_0_2_upload_ppt_overdrive_table (smu, ppt);if (ret) {dev_err (smu->adev->dev,"Failed to upload overdrive table!\n" );return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1186/1257 drm/amdkfd: validate SRAT subtables before parsing
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
[ Upstream commit 9866cb13ba4d39aa8fed34b765d4aecabe04f02e ]
The KFD SRAT walker reads the first subtable length without checking that a header is present and trusts subsequent lengths when accessing CPU and generic affinity records. Invalid firmware lengths can therefore cause out-of-bounds reads.
Validate the table header, every generic subtable range, and each supported typed record before reading its fields.
--- drivers/gpu/drm/amd/amdkfd/kfd_crat.c | 35 ++++++++++++++++++--------- 1 file changed, 24 insertions(+), 11 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_crat.c +24 -11
@@ -2056,27 +2056,33 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev)return ; } +if (table_header->length <sizeof (struct acpi_table_srat )) + goto invalid_srat; + table_end = (unsigned long )table_header + table_header->length;/* Parse all entries looking for a match. */ sub_header = (struct acpi_subtable_header *) ((unsigned long )table_header +sizeof (struct acpi_table_srat )); - subtable_len = sub_header->length; -while (((unsigned long )sub_header) + subtable_len < table_end) { -/* -* If length is 0, break from this loop to avoid -* infinite loop. -*/ -if (subtable_len ==0 ) { -pr_err ("SRAT invalid zero length\n" ); -break ; - } +while ((unsigned long )sub_header < table_end) { +unsigned long start = (unsigned long )sub_header; + +if (table_end - start <sizeof (*sub_header)) + goto invalid_srat; + + subtable_len = sub_header->length; +if (subtable_len <sizeof (*sub_header) || + subtable_len > table_end - start) + goto invalid_srat;switch (sub_header->type) {case ACPI_SRAT_TYPE_CPU_AFFINITY : cpu = (struct acpi_srat_cpu_affinity *)sub_header; +if (subtable_len <sizeof (*cpu)) + goto invalid_srat; + pxm = *((u32 *)cpu->proximity_domain_hi) <<8 | cpu->proximity_domain_lo;if (pxm > max_pxm)
@@ -2084,6 +2090,9 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev)break ;case ACPI_SRAT_TYPE_GENERIC_AFFINITY : gpu = (struct acpi_srat_generic_affinity *)sub_header; +if (subtable_len <sizeof (*gpu)) + goto invalid_srat; + bdf = *((u16 *)(&gpu->device_handle[0 ])) <<16 | *((u16 *)(&gpu->device_handle[2 ]));if (bdf == pci_id) {
@@ -2100,9 +2109,13 @@ static void kfd_find_numa_node_in_srat(struct kfd_node *kdev) sub_header = (struct acpi_subtable_header *) ((unsigned long )sub_header + subtable_len); - subtable_len = sub_header->length; } + goto out; + +invalid_srat: +pr_err ("SRAT contains an invalid subtable\n" ); +out:acpi_put_table (table_header);/* Workaround bad cpu-gpu binding case */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1187/1257 drm/amdkfd: send SMI process and VM fault events only to allowed clients
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit 2e0f334f5c7140b67f16eff9d93c2ca426848664 ]
Commit 92a8dba246d3 ("drm/amdkfd: fix SMI event cross-process information leak") made the VMFAULT and PROCESS_START/END SMI events carry the pid of the process they are about, so that kfd_smi_ev_enabled() only passes them to clients of that process and to privileged clients. Commit 1142738572ef ("drm/amdkfd: Fix SMI event PID reporting for containers") then switched kfd_smi_event_add() to take a task and passed NULL for these events, i.e. pid 0, which every client receives again.
On navi31, an unprivileged SMI client (uid 1000) subscribed to PROCESS_START/END sees root running rocminfo:
event: c 223a9 rocminfo
event: d 223a9 rocminfo
The same commit also made the filter compare PIDs of different
namespaces: the client stores its PID in its own namespace and events use the PID of the task in the task's namespace, so a client that is PID 1 in one container receives the events of PID 1 in another. And an exited task has no PID in its namespace anymore, which gives pid 0 for PROCESS_END.
Match clients by global TGID, which is unique and stays valid after the task exited, and keep showing the namespace PID in the event text. Pass the TGID of the process for the process and VM fault events again. With this the unprivileged client gets nothing, a root client still gets both events, and an unprivileged client that is PID 1 in its own PID namespace no longer gets the events of rocminfo running as PID 1 in another one.
v2: rename the pid of the clients and of the filter to tgid (Felix)
--- drivers/gpu/drm/amd/amdkfd/kfd_smi_events.c | 60 ++++++++++++--------- 1 file changed, 35 insertions(+), 25 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_smi_events.c +35 -25
@@ -40,7 +40,7 @@ struct kfd_smi_client {struct kfd_node *dev;spinlock_t lock;struct rcu_head rcu; -pid_t pid; +pid_t tgid;bool suser; };
@@ -160,18 +160,18 @@ static int kfd_smi_ev_release(struct inode *inode, struct file *filep)return 0 ; } -static bool kfd_smi_ev_enabled (pid_t pid,struct kfd_smi_client *client, +static bool kfd_smi_ev_enabled (pid_t tgid,struct kfd_smi_client *client,unsigned int event) {uint64_t events =READ_ONCE (client->events); -if (pid && client->pid != pid && !client->suser) +if (tgid && client->tgid != tgid && !client->suser)return false;return events &KFD_SMI_EVENT_MASK_FROM_INDEX (event); } -static void add_event_to_kfifo (pid_t pid,struct kfd_node *dev, +static void add_event_to_kfifo (pid_t tgid,struct kfd_node *dev,unsigned int smi_event,char *event_msg,int len) {struct kfd_smi_client *client;
@@ -179,7 +179,7 @@ static void add_event_to_kfifo(pid_t pid, struct kfd_node *dev,rcu_read_lock ();list_for_each_entry_rcu (client, &dev->smi_clients, list) { -if (!kfd_smi_ev_enabled (pid, client, smi_event)) +if (!kfd_smi_ev_enabled (tgid, client, smi_event))continue ;spin_lock (&client->lock);if (kfifo_avail (&client->fifo) >= len) {
@@ -210,27 +210,33 @@ static inline pid_t kfd_smi_task_to_pid(struct task_struct *task)return task ?task_tgid_nr_ns (task,task_active_pid_ns (task)) :0 ; } +/* +* Clients are matched by global TGID, which is unique across PID namespaces +* and stays valid after the task exited. Events show kfd_smi_task_to_pid(). +*/ +static inline pid_t kfd_smi_task_tgid (struct task_struct *task) +{ +return task ?task_tgid_nr (task) :0 ; +} + __printf(4, 5) -static void kfd_smi_event_add (struct task_struct *task,struct kfd_node *dev, +static void kfd_smi_event_add (pid_t tgid,struct kfd_node *dev,unsigned int event,char *fmt, ...) {char fifo_in[KFD_SMI_EVENT_MSG_SIZE ];int len;va_list args; -pid_t pid;if (list_empty (&dev->smi_clients))return ; - pid =kfd_smi_task_to_pid (task); - len =scnprintf (fifo_in,sizeof (fifo_in),"%x " , event);va_start (args, fmt); len +=vscnprintf (fifo_in + len,sizeof (fifo_in) - len, fmt, args);va_end (args); -add_event_to_kfifo (pid, dev, event, fifo_in, len); +add_event_to_kfifo (tgid, dev, event, fifo_in, len); } void kfd_smi_event_update_gpu_reset(struct kfd_node *dev, bool post_reset,
@@ -252,14 +258,14 @@ void kfd_smi_event_update_gpu_reset(struct kfd_node *dev, bool post_reset,amdgpu_reset_get_desc (reset_context, reset_cause,sizeof (reset_cause)); -kfd_smi_event_add (NULL , dev, event,KFD_EVENT_FMT_UPDATE_GPU_RESET ( +kfd_smi_event_add (0 , dev, event,KFD_EVENT_FMT_UPDATE_GPU_RESET ( dev->reset_seq_num, reset_cause)); }void kfd_smi_event_update_thermal_throttling (struct kfd_node *dev,uint64_t throttle_bitmask) { -kfd_smi_event_add (NULL , dev,KFD_SMI_EVENT_THERMAL_THROTTLE , +kfd_smi_event_add (0 , dev,KFD_SMI_EVENT_THERMAL_THROTTLE ,KFD_EVENT_FMT_THERMAL_THROTTLING ( throttle_bitmask,amdgpu_dpm_get_thermal_throttling_counter (dev->adev)));
@@ -271,10 +277,14 @@ void kfd_smi_event_update_vmfault(struct kfd_node *dev, uint16_t pasid) task_info =amdgpu_vm_get_task_info_pasid (dev->adev, pasid);if (task_info) { -/* Report VM faults from user applications, not retry from kernel */ +/* +* Report VM faults from user applications, not retry from +* kernel, and only to clients allowed to see that process. +*/ if (task_info->task.pid) -kfd_smi_event_add (NULL , dev,KFD_SMI_EVENT_VMFAULT ,KFD_EVENT_FMT_VMFAULT ( - task_info->task.pid, task_info->task.comm)); +kfd_smi_event_add (task_info->tgid, dev,KFD_SMI_EVENT_VMFAULT , +KFD_EVENT_FMT_VMFAULT (task_info->task.pid, + task_info->task.comm));amdgpu_vm_put_task_info (task_info); } }
@@ -283,7 +293,7 @@ void kfd_smi_event_page_fault_start(struct kfd_node *node, struct task_struct *t unsigned long address, bool write_fault, ktime_t ts) { -kfd_smi_event_add (task ,node ,KFD_SMI_EVENT_PAGE_FAULT_START , +kfd_smi_event_add (kfd_smi_task_tgid (task ),node ,KFD_SMI_EVENT_PAGE_FAULT_START ,KFD_EVENT_FMT_PAGEFAULT_START (ktime_to_ns (ts ), kfd_smi_task_to_pid(task), address, node->id, write_fault ? 'W' : 'R'));
@@ -292,7 +302,7 @@ void kfd_smi_event_page_fault_start(struct kfd_node *node, struct task_struct *tvoid kfd_smi_event_page_fault_end (struct kfd_node *node,struct task_struct *task,unsigned long address,bool migration) { -kfd_smi_event_add (task, node,KFD_SMI_EVENT_PAGE_FAULT_END , +kfd_smi_event_add (kfd_smi_task_tgid (task), node,KFD_SMI_EVENT_PAGE_FAULT_END ,KFD_EVENT_FMT_PAGEFAULT_END (ktime_get_boottime_ns (),kfd_smi_task_to_pid (task), address, node->id, migration ?'M' :'U' ));
@@ -304,7 +314,7 @@ void kfd_smi_event_migration_start(struct kfd_node *node, struct task_struct *ta uint32_t prefetch_loc, uint32_t preferred_loc, uint32_t trigger) { -kfd_smi_event_add (task ,node ,KFD_SMI_EVENT_MIGRATE_START , +kfd_smi_event_add (kfd_smi_task_tgid (task ),node ,KFD_SMI_EVENT_MIGRATE_START ,KFD_EVENT_FMT_MIGRATE_START (ktime_get_boottime_ns (), kfd_smi_task_to_pid(task), start, end - start, from,to ,prefetch_loc ,preferred_loc ,trigger ));
@@ -315,7 +325,7 @@ void kfd_smi_event_migration_end(struct kfd_node *node, struct task_struct *task uint32_t from, uint32_t to, uint32_t trigger, int error_code) { -kfd_smi_event_add (task ,node ,KFD_SMI_EVENT_MIGRATE_END , +kfd_smi_event_add (kfd_smi_task_tgid (task ),node ,KFD_SMI_EVENT_MIGRATE_END ,KFD_EVENT_FMT_MIGRATE_END (ktime_get_boottime_ns (), kfd_smi_task_to_pid(task), start, end - start, from,to ,trigger ,error_code ));
@@ -324,14 +334,14 @@ void kfd_smi_event_migration_end(struct kfd_node *node, struct task_struct *taskvoid kfd_smi_event_queue_eviction (struct kfd_node *node,struct task_struct *task,uint32_t trigger) { -kfd_smi_event_add (task, node,KFD_SMI_EVENT_QUEUE_EVICTION , +kfd_smi_event_add (kfd_smi_task_tgid (task), node,KFD_SMI_EVENT_QUEUE_EVICTION ,KFD_EVENT_FMT_QUEUE_EVICTION (ktime_get_boottime_ns (),kfd_smi_task_to_pid (task), node->id, trigger)); }void kfd_smi_event_queue_restore (struct kfd_node *node,struct task_struct *task) { -kfd_smi_event_add (task, node,KFD_SMI_EVENT_QUEUE_RESTORE , +kfd_smi_event_add (kfd_smi_task_tgid (task), node,KFD_SMI_EVENT_QUEUE_RESTORE ,KFD_EVENT_FMT_QUEUE_RESTORE (ktime_get_boottime_ns (),kfd_smi_task_to_pid (task), node->id,'0' )); }
@@ -348,7 +358,7 @@ void kfd_smi_event_queue_restore_rescheduled(struct mm_struct *mm)for (i =0 ; i < p->n_pdds; i++) {struct kfd_process_device *pdd = p->pdds[i]; - kfd_smi_event_add(p->lead_thread, pdd->dev, + kfd_smi_event_add(kfd_smi_task_tgid(p->lead_thread), pdd->dev, KFD_SMI_EVENT_QUEUE_RESTORE, KFD_EVENT_FMT_QUEUE_RESTORE(ktime_get_boottime_ns(), kfd_smi_task_to_pid(p->lead_thread),
@@ -361,7 +371,7 @@ void kfd_smi_event_unmap_from_gpu(struct kfd_node *node, struct task_struct *tas unsigned long address, unsigned long last, uint32_t trigger) { -kfd_smi_event_add (task ,node ,KFD_SMI_EVENT_UNMAP_FROM_GPU , +kfd_smi_event_add (kfd_smi_task_tgid (task ),node ,KFD_SMI_EVENT_UNMAP_FROM_GPU ,KFD_EVENT_FMT_UNMAP_FROM_GPU (ktime_get_boottime_ns (),kfd_smi_task_to_pid (task ),address , last - address + 1, node->id, trigger));
@@ -379,7 +389,7 @@ void kfd_smi_event_process(struct kfd_process_device *pdd, bool start) task_info =amdgpu_vm_get_task_info_vm (avm);if (task_info) { - kfd_smi_event_add(NULL, pdd->dev, + kfd_smi_event_add(kfd_smi_task_tgid(pdd->process->lead_thread), pdd->dev, start ? KFD_SMI_EVENT_PROCESS_START : KFD_SMI_EVENT_PROCESS_END, KFD_EVENT_FMT_PROCESS(task_info->task.pid,
@@ -408,7 +418,7 @@ int kfd_smi_event_open(struct kfd_node *dev, uint32_t *fd)spin_lock_init (&client->lock); client->events =0 ; client->dev = dev; - client->pid =kfd_smi_task_to_pid (current); + client->tgid =kfd_smi_task_tgid (current); client->suser =capable (CAP_SYS_ADMIN );spin_lock (&dev->smi_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1188/1257 drm/amdgpu: drop the gang leader reference when freeing gang jobs
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit c1584e10a7deb655438f21867b2b7a356a9aaf9f ]
Every job of a gang except the leader holds a reference to the scheduled fence of the leader in job->gang_submit. Only amdgpu_job_free(), used for jobs which never ran, drops it, so for every gang submission which completes the scheduler fence of the leader, and with it its hardware fence, is leaked. amdgpu_job_free() in turn checks for the leader only after drm_sched_job_cleanup() cleared the scheduler fence, so a leader freed there drops a reference it never took.
On navi31, 100 submissions of a GFX + COMPUTE gang grow the slab cache drm_sched_fence is merged into by 60 to 180 objects each time, while 100 GFX only submissions don't.
Use amdgpu_job_free() for the jobs the scheduler frees too, and check for the gang leader there before drm_sched_job_cleanup() clears the scheduler fence. As the scheduler clears the entity of the jobs it picked up, check for the scheduler fence instead to tell whether the job needs cleaning up.
Keep freeing the remaining IBs with amdgpu_job_free_resources() after drm_sched_job_cleanup(), so that it frees them with the hardware fence or right away and not with the scheduler fence, which nobody signals for jobs aborted after drm_sched_job_arm(), like a CS returning -EAGAIN.
v2: unify amdgpu_job_free() and amdgpu_job_free_cb() (Christian), don't
free the remaining IBs with the scheduler fence
v3: drop the comments (Christian)
v4: free the IBs with amdgpu_job_free_resources() again (Christian)
--- drivers/gpu/drm/amd/amdgpu/amdgpu_job.c | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_job.c +5 -19
@@ -313,22 +313,7 @@ void amdgpu_job_free_resources(struct amdgpu_job *job)static void amdgpu_job_free_cb (struct drm_sched_job *s_job) { -struct amdgpu_job *job =to_amdgpu_job (s_job); - -drm_sched_job_cleanup (s_job); - -amdgpu_sync_free (&job->explicit_sync); - -if (dma_fence_was_initialized (&job->hw_fence->base)) -dma_fence_put (&job->hw_fence->base); -else -kfree (job->hw_fence); -if (dma_fence_was_initialized (&job->hw_vm_fence->base)) -dma_fence_put (&job->hw_vm_fence->base); -else -kfree (job->hw_vm_fence); - -kfree (job); +amdgpu_job_free (to_amdgpu_job (s_job)); } void amdgpu_job_set_gang_leader(struct amdgpu_job *job,
@@ -349,13 +334,14 @@ void amdgpu_job_set_gang_leader(struct amdgpu_job *job,void amdgpu_job_free (struct amdgpu_job *job) { -if (job->base.entity) +if (job->gang_submit != &job->base.s_fence->scheduled) +dma_fence_put (job->gang_submit); + +if (job->base.s_fence)drm_sched_job_cleanup (&job->base);amdgpu_job_free_resources (job);amdgpu_sync_free (&job->explicit_sync); -if (job->gang_submit != &job->base.s_fence->scheduled) -dma_fence_put (job->gang_submit);if (dma_fence_was_initialized (&job->hw_fence->base))dma_fence_put (&job->hw_fence->base);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1189/1257 drm/amdkfd: evict the queues only once for CRIU PROCESS_INFO
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit 8f3ecda0ab42fb5ba7310fe848013d3eff31b416 ]
criu_process_info() evicts the queues of the process on every call, and each kfd_process_evict_queues() increments qpd->evicted, but CRIU UNPAUSE restores them only once. After PROCESS_INFO twice and UNPAUSE the queues stay evicted for good. On navi31, a barrier-AND packet on an HSA queue completes after PROCESS_INFO + UNPAUSE, but times out after PROCESS_INFO, PROCESS_INFO, UNPAUSE.
The error path has a related problem: when kfd_process_evict_queues() itself fails, it has already rolled back its partial eviction, and the kfd_process_restore_queues() in the error path restores once more.
Evict only when the queues are not paused yet, and on errors only undo an eviction done by this call. The barrier now completes after any number of PROCESS_INFO calls followed by UNPAUSE.
--- drivers/gpu/drm/amd/amdkfd/kfd_chardev.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +10 -5
@@ -2876,6 +2876,7 @@ static int criu_process_info(struct file *filep,struct kfd_process *p, struct kfd_ioctl_criu_args *args) { + bool paused_here = false;int ret =0 ;mutex_lock (&p->mutex);
@@ -2886,11 +2887,15 @@ static int criu_process_info(struct file *filep, goto err_unlock; } - ret =kfd_process_evict_queues (p,KFD_QUEUE_EVICTION_CRIU_CHECKPOINT ); -if (ret) - goto err_unlock; +/* UNPAUSE restores the queues once, so evict them only once */ +if (!p->queues_paused) { + ret =kfd_process_evict_queues (p,KFD_QUEUE_EVICTION_CRIU_CHECKPOINT ); +if (ret) + goto err_unlock; - p->queues_paused = true; + p->queues_paused = true; + paused_here = true; + } args->pid =task_pid_nr_ns (p->lead_thread,task_active_pid_ns (p->lead_thread));
@@ -2905,7 +2910,7 @@ static int criu_process_info(struct file *filep, args->priv_data_size); err_unlock: -if (ret) { +if (ret && paused_here) {kfd_process_restore_queues (p); p->queues_paused = false; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1190/1257 drm/amd/display: Poll passive DVI sinks for EDID readiness
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fangzhi Zuo <[email protected]>
[ Upstream commit e9ddfb93fafa50f92165d2b48c7728720999b117 ]
A passive DP-DVI adapter is identified when the adapter DDC probe does not respond, but the downstream monitor's EDID EEPROM may still need time to become available after resume. Poll the downstream DDC address for passive DP-DVI links before reading and parsing the EDID.
Keep the eDP detection optimization without adding a generic EDID retry delay or a deferred connector reprobe.
Revert commit 3001d2073d65 ("drm/amd/display: Exit IPS before connector detection on resume") and rely on targeted passive DP-DVI EDID readiness polling instead of the generic pre-detection IPS exit.
--- .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 4 ---- .../amd/display/amdgpu_dm/amdgpu_dm_helpers.c | 22 +++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +0 -4
@@ -1979,10 +1979,6 @@ static int dm_resume(struct amdgpu_ip_block *ip_block)/* On resume we need to rewrite the MSTM control bits to enable MST*/ s3_handle_mst (ddev, false); -/* Exit IPS before the detection loop's first AUX/DDC access. */ - scoped_guard(mutex, &dm->dc_lock) -dc_exit_ips_for_hw_access (dm->dc); -/* Do detection*/ drm_connector_list_iter_begin (ddev, &iter);drm_for_each_connector_iter (connector, &iter) {
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c +22 -0
@@ -1218,6 +1218,26 @@ void populate_hdmi_info_from_connector(bool enable_frl, struct drm_hdmi_info *hd }EXPORT_IF_KUNIT (populate_hdmi_info_from_connector); +static void dm_helpers_wait_for_edid_ready (struct dc_link *link, +struct i2c_adapter *ddc) +{ +const unsigned int retry_count =50 ; +const unsigned int retry_interval_ms =20 ; +unsigned int retry; + +if (!ddc || link->dpcd_caps.dongle_type != +DISPLAY_DONGLE_DP_DVI_DONGLE ) +return ; + +for (retry =0 ; retry < retry_count; retry++) { +if (drm_probe_ddc (ddc)) +return ; + +if (retry +1 < retry_count) +msleep (retry_interval_ms); + } +} + enum dc_edid_status dm_helpers_read_local_edid( struct dc_context *ctx, struct dc_link *link,
@@ -1242,6 +1262,8 @@ enum dc_edid_status dm_helpers_read_local_edid(if (link->dc->hwss.prepare_ddc) link->dc->hwss.prepare_ddc (link); +dm_helpers_wait_for_edid_ready (link, ddc); +/* some dongles read edid incorrectly the first time, * do check sum and retry to make sure read correct edid. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1191/1257 net: limit priority VLAN untag depth
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kamil Sawicki <[email protected]>
[ Upstream commit d3ff07f5acc573e5f72bf1c581bae5d05191ba61 ]
The priority VLAN receive path can repeatedly remove VID 0 tags and retry packet processing. Unlike the read-only VLAN protocol parser, this path has no limit on the number of nested tags it consumes.
Each skb_vlan_untag() advances skb->data and resets header offsets. The offsets are stored in 16-bit fields. With enough nested tags, the network or transport offset can wrap. A later protocol handler can then derive a large pull length from the wrapped offsets and access memory outside the skb allocation.
Apply the existing VLAN_MAX_DEPTH limit to the exceptional VID 0 retry. Count the tag already stored in skb VLAN metadata as the first level, then stop before untagging a ninth level. Keep the accounting inside this uncommon branch so the regular VLAN receive path is unaffected.
A single VID 0 priority tag before a real VLAN tag is valid. No normal deployment was found that intentionally emits multiple consecutive VID 0 tags; permitting eight levels is therefore conservative.
The issue was found while researching the Linux network receive path for Google kvmCTF, with OpenAI Codex (gpt-5.6-sol) assisting the analysis. The affected path, reproducer and fix were manually reviewed and tested.
--- net/core/dev.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/core/dev.c +8 -0
@@ -6201,6 +6201,8 @@ static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, }if (unlikely (skb_vlan_tag_present (skb)) && !netdev_uses_dsa (skb->dev)) { +unsigned int priority_tag_depth =1 ; + check_vlan_id:if (skb_vlan_tag_get_id (skb)) {/* Vlan id is non 0 and vlan_do_receive() above couldn't
@@ -6212,6 +6214,12 @@ static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,* 802.1Q or 802.1AD and vlan_do_receive() above could * not find vlan dev for vlan id 0. */ +if (unlikely (priority_tag_depth >=VLAN_MAX_DEPTH )) { + drop_reason =SKB_DROP_REASON_RECURSION_LIMIT ; + goto drop; + } + + priority_tag_depth++;__vlan_hwaccel_clear_tag (skb); skb =skb_vlan_untag (skb);if (unlikely (!skb))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1192/1257 macvlan: fix passthru promiscuity accounting while down
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xia Yan <[email protected]>
[ Upstream commit b6743653d134c9ef8436e2db1be1ad4c1e0d0091 ]
macvlan_changelink() adjusts the lower device's promiscuity count when NOPROMISC changes, even if the passthru macvlan is down. The reference is acquired in macvlan_open() and released in macvlan_stop(), so a down interface has no reference to change.
Clearing NOPROMISC while down leaves an extra reference after the next open/stop cycle. Setting it while down can remove a reference held by another user of the lower device.
Guard the count adjustment with netif_running(dev). Keep storing the requested flags while down so the next open uses the new setting.
Comparing changelink with open/stop exposed the unmatched count changes; the same issue was also described in earlier macvlan reviews. A netlink test on UML reproduced both DOWN cases before the fix and verified the expected counts afterwards. Repeated flag updates, two open/stop cycles, deletion and bidirectional small-frame delivery were also checked.
Full x86_64 builds completed with WERROR disabled for allmodconfig, and WERROR and KASAN disabled for allyesconfig, including the resulting dependency changes. Neither comparison showed new diagnostics.
--- drivers/net/macvlan.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/macvlan.c +2 -1
@@ -1664,7 +1664,8 @@ static int macvlan_changelink(struct net_device *dev,if (data && data[IFLA_MACVLAN_FLAGS ]) {__u16 flags =nla_get_u16 (data[IFLA_MACVLAN_FLAGS ]);bool promisc = (flags ^ vlan->flags) &MACVLAN_FLAG_NOPROMISC ; -if (macvlan_passthru (vlan->port) && promisc) { +if (macvlan_passthru (vlan->port) && promisc && +netif_running (dev)) {int err;if (flags &MACVLAN_FLAG_NOPROMISC )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1193/1257 net: hisilicon: hisi_femac: Stop the receiver before releasing the RX ring
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Yang <[email protected]>
[ Upstream commit d54b21d824302af52d06574870817fbe14774dab ]
hisi_femac_net_close() frees the receive ring while the RX address queue still holds every address that was pushed to IQ_ADDR.
A port that keeps receiving then DMAs arrived frames into buffers that other slab caches have already taken back; on an EC6108V9C (hi3798mv100) the queue still held all 52 armed addresses right after the interface was closed, and had dropped to 43 after 15 s of broadcast traffic.
Reset the port before the buffers are released, so that the receiver no longer holds any of their addresses.
--- drivers/net/ethernet/hisilicon/hisi_femac.c | 1 + 1 file changed, 1 insertion(+)
drivers/net/ethernet/hisilicon/hisi_femac.c +1 -0
@@ -491,6 +491,7 @@ static int hisi_femac_net_close(struct net_device *dev)netif_stop_queue (dev);napi_disable (&priv->napi); +hisi_femac_port_reset (priv);hisi_femac_free_skb_rings (priv);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1194/1257 fs/ntfs3: bound CreateAttribute asize against record_size in do_action
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyeontae Lee <[email protected]>
[ Upstream commit fb0f0ef7b5a6bc761b372ce00764d4b6e0b91a47 ]
In do_action()'s CreateAttribute case (fslog.c:3286), attr2 points into the on-disk log record and asize = le32_to_cpu(attr2->size) is therefore attacker-controlled on mount. The guard bounds asize only against the log record itself,
Add2Ptr(attr2, asize) > Add2Ptr(lrh, rec_len)
where rec_len is the client data length, and separately bounds dlen against the MFT record. Nothing bounds asize against record_size, but all three writes that follow are into rec, a kmalloc(sbi->record_size) buffer allocated by mi_init() (record.c:105):
memmove(Add2Ptr(attr, asize), attr, used - roff); memcpy(attr, attr2, asize); rec->used = cpu_to_le32(used + asize);
With record_size 0x400, roff 0x38, used 0x160 and asize 0x800 the memcpy writes 2048 bytes at rec + 0x38, 0x438 bytes past the allocation, and rec->used is left at 0x960. dlen is 0x18 here, so the existing dlen check passes: dlen bounds nothing about the size of the copy.
The equivalent non-replay path already refuses this. mi_insert_attr() performs the same insert and starts with (record.c:488):
if (used + asize > sbi->record_size) return NULL;
Apply the same bound, spelled as a subtraction to match the neighbouring clause. used <= record_size holds here because check_file_record() validates it (fslog.c:2826) and is called on this record at fslog.c:3172; roff <= used - 4 follows from check_if_attr() together with the ATTR_END check at fslog.c:2844, so bounding used + asize bounds both copies.
The sibling WriteEndOfFileRecordSegment case does the equivalent check against record_size at fslog.c:3277.
Reproduced by mounting a crafted image on v7.2-rc5 under KASAN:
BUG: KASAN: slab-out-of-bounds in do_action.isra.0+0x41f6/0x83a0 Write of size 2048 at addr ffff888005c74838 by task mount/69 CPU: 0 UID: 0 PID: 69 Comm: mount Not tainted 7.2.0-rc5-00300-g8ba098e6b6ff #2 Call Trace: kasan_report+0xce/0x100 kasan_check_range+0x105/0x1b0 __asan_memcpy+0x3c/0x60 do_action.isra.0+0x41f6/0x83a0 log_replay+0x920a/0xd300 ntfs_loadlog_and_replay+0x3ef/0x510 ntfs_fill_super+0x1d23/0x4550 get_tree_bdev_flags+0x2ef/0x550 vfs_get_tree+0x82/0x2f0 fc_mount+0x10/0x1b0 path_mount+0x517/0x1df0 __x64_sys_mount+0x20b/0x270 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f Allocated by task 69: __kasan_kmalloc+0x8f/0xa0 __kmalloc_noprof+0x1b4/0x460 mi_init+0x81/0x110 mi_get+0x6a/0x220 do_action.isra.0+0x1db4/0x83a0 log_replay+0x920a/0xd300 ntfs_loadlog_and_replay+0x3ef/0x510 ntfs_fill_super+0x1d23/0x4550 The buggy address belongs to the object at ffff888005c74800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 56 bytes inside of allocated 1024-byte region [ffff888005c74800, ffff888005c74c00)
--- fs/ntfs3/fslog.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/ntfs3/fslog.c +6 -1
@@ -3320,10 +3320,15 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe, asize =le32_to_cpu (attr2->size); used =le32_to_cpu (rec->used); +/* +* attr2->size is taken from the log record and is bounded only +* by the log record length, not by the MFT record. Refuse an +* attribute that does not fit, as mi_insert_attr() does. +*/ if (!check_if_attr (rec, lrh) || dlen <SIZEOF_RESIDENT || !IS_ALIGNED (asize,8 ) ||Add2Ptr (attr2, asize) >Add2Ptr (lrh, rec_len) || - dlen > record_size - used) { + dlen > record_size - used || asize > record_size - used) { goto dirty_vol; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1195/1257 fs/ntfs3: bound DeleteAttribute asize against rec->used in do_action
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyeontae Lee <[email protected]>
[ Upstream commit 408216b66afd9ddadaba2dce56fd4af6793e95a2 ]
In do_action()'s DeleteAttribute case (fslog.c:3316), attr is Add2Ptr(rec, roff) with roff taken from the on-disk lrh->record_off, and asize = le32_to_cpu(attr->size) is read straight out of the MFT record:
asize = le32_to_cpu(attr->size); used = le32_to_cpu(rec->used); if (!check_if_attr(rec, lrh)) goto dirty_vol; ... memmove(attr, Add2Ptr(attr, asize), used - asize - roff);
check_if_attr() (fslog.c:2869) walks the attribute chain from rec->attr_off and returns o == ro. Its loop breaks on ATTR_END, so ro may legitimately equal the offset of the ATTR_END marker; that is exactly how CreateAttribute appends to a record. But check_file_record()'s walk (fslog.c:2831) also stops at ATTR_END, so check_attr() never inspects the bytes there. When roff is the ATTR_END offset, those never-validated bytes are what gets read as attr->size, and used - asize - roff underflows.
The read itself is also unbounded: roff is a u16 and attr->size is dereferenced at fslog.c:3317, before check_if_attr() has constrained roff at all, so it can be up to ~64K past a record_size-sized object.
Commit 0ca0485e4b2e ("fs/ntfs3: validate rec->used in journal-replay file record check") added at fslog.c:2844
if (used < PtrOffset(rec, attr) + sizeof(attr->type)) return false;
and its changelog names this very memmove. It bounds rec->used against the ATTR_END offset; it does not bound asize. With record_size 0x400, attr_off 0x38, a valid three-attribute chain ending in ATTR_END at 0x158 and used 0x160, a record whose four bytes at 0x15c read 0x100 gives
used - asize - roff = 0x160 - 0x100 - 0x158 = 0xffffff08
i.e. a ~4 GiB memmove whose source and destination both run off the end of rec, a kmalloc(sbi->record_size) object (record.c:105).
The equivalent non-replay path already refuses this. mi_remove_attr() performs the same removal and starts with (record.c:548):
if (aoff + asize > used) return false;
Apply the same bound, spelled as a subtraction to match the neighbouring cases, and move the attr->size read after check_if_attr() so that the header is known to lie inside the record before it is dereferenced. Requiring roff + SIZEOF_RESIDENT <= used rejects the ATTR_END offset without rejecting any real attribute: for an attribute the walk validated, roff + asize <= off(ATTR_END) <= used - 4, and any attribute a DeleteAttribute record can legitimately name carries a full resident header, so roff + SIZEOF_RESIDENT <= roff + asize <= used - 4. check_attr() itself imposes no lower bound on asize, so a crafted sub-header asize can still pass the first test; the second test then bounds it and the memmove stays inside the record.
Reproduced by mounting a crafted image on v7.2-rc5, which already contains 0ca0485e4b2e, under KASAN. The image is an ordinary mkfs.ntfs volume with four bytes of one MFT record changed and a crafted $LogFile:
BUG: KASAN: slab-out-of-bounds in do_action.isra.0+0x3211/0x83c0 Read of size 4294967048 at addr ffff888002423258 by task mount/66 CPU: 1 UID: 0 PID: 66 Comm: mount Not tainted 7.2.0-rc5 #3 Call Trace: kasan_report+0xce/0x100 kasan_check_range+0x105/0x1b0 __asan_memmove+0x23/0x60 do_action.isra.0+0x3211/0x83c0 log_replay+0x920a/0xd300 ntfs_loadlog_and_replay+0x3ef/0x510 ntfs_fill_super+0x1d23/0x4550 get_tree_bdev_flags+0x2ef/0x550 vfs_get_tree+0x82/0x2f0 fc_mount+0x10/0x1b0 path_mount+0x517/0x1df0 __x64_sys_mount+0x20b/0x270 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f Allocated by task 66: __kasan_kmalloc+0x8f/0xa0 __kmalloc_noprof+0x1b4/0x460 mi_init+0x81/0x110 mi_get+0x6a/0x220 do_action.isra.0+0x1dbf/0x83c0 log_replay+0x920a/0xd300 ntfs_loadlog_and_replay+0x3ef/0x510 ntfs_fill_super+0x1d23/0x4550 The buggy address belongs to the object at ffff888002423000 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 600 bytes inside of allocated 1024-byte region [ffff888002423000, ffff888002423400)
KASAN reports the source side because __asan_memmove() (mm/kasan/shadow.c:94) validates src before dest and returns without copying. Both ends are out of bounds, and on a kernel built without KASAN the copy is performed.
rec->used is also left at used - asize by fslog.c:3323 before the memmove, so the record stays inconsistent even when the copy is suppressed; the same mount goes on to report "ino=1a, mi_enum_attr" and marks the volume dirty.
--- fs/ntfs3/fslog.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-)
fs/ntfs3/fslog.c +13 -2
@@ -3351,10 +3351,21 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,break ;case DeleteAttribute: - asize =le32_to_cpu (attr->size); used =le32_to_cpu (rec->used); -if (!check_if_attr (rec, lrh)) +/* +* check_if_attr() accepts a record_off that points at the +* ATTR_END marker, which is how CreateAttribute appends. The +* bytes there are not an attribute and check_attr() never +* validated them, so refuse an offset that cannot hold a +* resident header before reading attr->size, and then bound it +* as mi_remove_attr() does. +*/ +if (!check_if_attr (rec, lrh) || roff +SIZEOF_RESIDENT > used) + goto dirty_vol; + + asize =le32_to_cpu (attr->size); +if (asize > used - roff) goto dirty_vol; rec->used =cpu_to_le32 (used - asize);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1196/1257 ntfs3: fix mapping pairs bounds check for alignment
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hongling Zeng <[email protected]>
[ Upstream commit f517cae6333121783043d9ba5142b50f5d1cf75b ]
In the UpdateMappingPairs action, the expansion check compares the unaligned new attribute size with the available record space. The new size is aligned to an 8-byte boundary before the mapping pairs are updated, so the check can underestimate the required space by up to seven bytes.
Use the aligned size in the expansion check to ensure that the subsequent update cannot exceed the available record space.
--- fs/ntfs3/fslog.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ntfs3/fslog.c +2 -1
@@ -3439,7 +3439,8 @@ static int do_action(struct ntfs_log *log, struct OPEN_ATTR_ENRTY *oe,if (!check_if_attr (rec, lrh) || !attr->non_res || aoff <le16_to_cpu (attr->nres.run_off) || aoff > asize || - (nsize > asize && nsize - asize > record_size - used)) { + (nsize > asize && +ALIGN (nsize,8 ) - asize > record_size - used)) { goto dirty_vol; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1197/1257 soc: loongson: loongson2_pm: Fix build warnings for 32BIT
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Huacai Chen <[email protected]>
[ Upstream commit 48b960ad7057f84a375ae7ec803ea3ba6b038b5c ]
Since loongson_sysconf.suspend_addr is unsigned long, use "unsigned long" instead of "u64" for casting, so as to avoid build warnings for 32BIT:
drivers/soc/loongson/loongson2_pm.c: In function 'loongson2_pm_probe':
Quoted 1 line
Quoted 1 line
drivers/soc/loongson/loongson2_pm.c:178:49: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
178 | loongson_sysconf.suspend_addr = (u64)phys_to_virt(suspend_addr);
|--- drivers/soc/loongson/loongson2_pm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/soc/loongson/loongson2_pm.c +1 -1
@@ -175,7 +175,7 @@ static int loongson2_pm_probe(struct platform_device *pdev)return irq;if (!device_property_read_u64 (dev,"loongson,suspend-address" , &suspend_addr)) - loongson_sysconf.suspend_addr = (u64 )phys_to_virt (suspend_addr); + loongson_sysconf.suspend_addr = (unsigned long )phys_to_virt (suspend_addr);else dev_err (dev,"No loongson,suspend-address, could not support S3!\n" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1198/1257 ASoC: hdac_hda: Keep runtime PM state in sync across codec remove/probe
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Ujfalusi <[email protected]>
[ Upstream commit 99203e8d8968def973e82bb712ea959c6a46c16e ]
After the codec has been removed, its runtime PM status is RPM_SUSPENDED while hdac_hda_codec_probe() powers the codec up via snd_hda_codec_device_new(). The pm_runtime_put()/snd_hda_power_down() calls on probe and registration then see an already suspended device, the codec suspend callback is not called and the codec, its HDA link and the codec_powered bit stay set, preventing the controller from runtime suspending.
The remove has a similar problem with the codec link accounting:hdac_hda_codec_remove() drops the link reference taken in probe without looking at the runtime PM state of the codec. If the codec was already runtime suspended, the link reference has been dropped by the codec suspend callback and the remove drops it a second time.
Resume the codec in hdac_hda_codec_remove() before disabling runtime PM so that the link reference and the codec_powered bit are always in the same state as after the probe, and mark the device active on probe once the codec has been powered up.
Finally mark the codec device suspended at the end of the remove. Its runtime PM is disabled at this point and if only the ASoC card is unbound (e.g. by unbinding the machine driver), a following system suspend would otherwise call the runtime suspend callback on the already cleaned up codec via pm_runtime_force_suspend().
This is a followup patch to address Sashiko reports.
--- sound/soc/codecs/hdac_hda.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
sound/soc/codecs/hdac_hda.c +12 -0
@@ -514,6 +514,9 @@ static int hdac_hda_codec_probe(struct snd_soc_component *component)snd_hdac_display_power (hdev->bus,HDA_CODEC_IDX_CONTROLLER , false); +/* The codec is in D0, the status is RPM_SUSPENDED after a previous unbind */ +pm_runtime_set_active (&hdev->dev); +/* match for forbid call in snd_hda_codec_device_new() */ pm_runtime_allow (&hdev->dev);
@@ -554,6 +557,12 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)return ; } +/* +* Resume the codec to have its link reference (dropped below) and +* codec_powered bit in the same state as after the probe. +*/ +pm_runtime_get_sync (&hdev->dev); +/* prevent runtime PM callbacks while the link and the codec are torn down */ pm_runtime_disable (&hdev->dev);snd_hdac_ext_bus_link_put (hdev->bus, hlink);
@@ -565,6 +574,9 @@ static void hdac_hda_codec_remove(struct snd_soc_component *component)/* Balances the disable above, cleanup_for_unbind keeps runtime PM disabled */ pm_runtime_enable (&hdev->dev); +pm_runtime_put_noidle (&hdev->dev); +/* The codec is cleaned up, system suspend must skip it from now on */ +pm_runtime_set_suspended (&hdev->dev); }static const struct snd_soc_dapm_route hdac_hda_dapm_routes[] = {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1199/1257 inet: frags: prevent acceptance of partially authenticated reassembly
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
[ Upstream commit 6fb4e32f2ce3234ae0c416872e911706a3484430 ]
A reassembled skb retains the secpath from its first fragment, which makes it possible for the final policy check to accept bytes that were not covered by the transform recorded on the skb. This can affect IPsec tunnel traffic, including AH and ESP, and allow a packet to be accepted even though only part of its payload was authenticated.
Reject a fragment when its secpath differs from the fragments already in the queue, and keep overlap statistics limited to actual overlaps.
--- include/net/inet_frag.h | 1 + include/net/xfrm.h | 17 +++++++++++++++++ net/ipv4/inet_fragment.c | 5 +++++ net/ipv4/ip_fragment.c | 3 ++- net/ipv6/reassembly.c | 3 ++- 5 files changed, 27 insertions(+), 2 deletions(-)
include/net/inet_frag.h +1 -0
@@ -171,6 +171,7 @@ extern const u8 ip_frag_ecn_table[16];#define IPFRAG_OK 0#define IPFRAG_DUP 1#define IPFRAG_OVERLAP 2 +#define IPFRAG_MIXED_SECPATH 3int inet_frag_queue_insert (struct inet_frag_queue *q,struct sk_buff *skb,int offset,int end); void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb,
include/net/xfrm.h +17 -0
@@ -1201,6 +1201,23 @@ secpath_reset(struct sk_buff *skb)#endif } +static inline bool +secpath_equal (const struct sk_buff *skb1,const struct sk_buff *skb2) +{ +const struct sec_path *sp1 =skb_sec_path (skb1); +const struct sec_path *sp2 =skb_sec_path (skb2); +int i; + +if (!sp1 || !sp2) +return sp1 == sp2; +if (sp1->len != sp2->len) +return false; +for (i =0 ; i < sp1->len; i++) +if (sp1->xvec[i] != sp2->xvec[i]) +return false; +return true; +} +static inline int xfrm_addr_any (const xfrm_address_t *addr,unsigned short family) {
net/ipv4/inet_fragment.c +5 -0
@@ -23,6 +23,7 @@#include <net/inet_ecn.h> #include <net/ip.h> #include <net/ipv6.h> +#include <net/xfrm.h> /* Use skb->cb to track consecutive/adjacent fragments coming at * the end of the queue. Nodes in the rb-tree queue will
@@ -441,6 +442,10 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, {struct sk_buff *last = q->fragments_tail; +/* The reassembled skb keeps the first fragment's secpath. */ +if (last && !secpath_equal (last, skb)) +return IPFRAG_MIXED_SECPATH ; +/* An IP fragment is never a GSO packet, but an untrusted source * (virtio_net_hdr) may have attached GSO metadata to it. Do not let * that reach the reassembled skb, whose head keeps the first
net/ipv4/ip_fragment.c +2 -1
@@ -378,8 +378,9 @@ static int ip_frag_queue(struct ipq *qp, struct sk_buff *skb, int *refs) err = -EINVAL ; goto err; } +if (err ==IPFRAG_OVERLAP ) +__IP_INC_STATS (net,IPSTATS_MIB_REASM_OVERLAPS ); err = -EINVAL ; -__IP_INC_STATS (net,IPSTATS_MIB_REASM_OVERLAPS ); discard_qp:inet_frag_kill (&qp->q, refs);__IP_INC_STATS (net,IPSTATS_MIB_REASMFAILS );
net/ipv6/reassembly.c +2 -1
@@ -241,8 +241,9 @@ static int ip6_frag_queue(struct net *net, err = -EINVAL ; goto err; } +if (err ==IPFRAG_OVERLAP ) +__IP6_INC_STATS (net, idev,IPSTATS_MIB_REASM_OVERLAPS ); err = -EINVAL ; -__IP6_INC_STATS (net, idev,IPSTATS_MIB_REASM_OVERLAPS ); discard_fq:inet_frag_kill (&fq->q, refs);__IP6_INC_STATS (net, idev,IPSTATS_MIB_REASMFAILS );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1200/1257 ppp: fix stale pointer access after pskb_may_pull in ppp_ccp_peek
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tristan Madani <[email protected]>
[ Upstream commit 1e860f42f41c6fbf3304f6a52be38245b9394982 ]
ppp_ccp_peek() caches a pointer to skb->data in dp after the first pskb_may_pull(), then uses dp after a second pskb_may_pull(skb, len + 2) in the CCP_CONFACK handler. If the second pull triggers pskb_expand_head() due to a cloned skb or frag linearization, skb->head is freed and reallocated, leaving dp stale.
The stale dp is subsequently used in CCP_OPT_LENGTH() and passed to decomp_init()/comp_init() which read from the freed memory.
Re-derive dp from skb->data after the second pskb_may_pull.
--- drivers/net/ppp/ppp_generic.c | 1 + 1 file changed, 1 insertion(+)
drivers/net/ppp/ppp_generic.c +1 -0
@@ -3157,6 +3157,7 @@ ppp_ccp_peek(struct ppp *ppp, struct sk_buff *skb, int inbound) len =CCP_LENGTH (dp);if (!pskb_may_pull (skb, len +2 ))return ;/* too short */ + dp = skb->data +2 ; dp +=CCP_HDRLEN ; len -=CCP_HDRLEN ;if (len <CCP_OPT_MINLEN || len <CCP_OPT_LENGTH (dp))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1201/1257 nvmet-rdma: reject short connection requests
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
[ Upstream commit 635e760169a87abf03874cd4636cd91b580cb427 ]
nvmet_rdma_parse_cm_connect_req() treats RDMA-CM private data as a struct nvme_rdma_cm_req but accepts any nonzero private_data_len. The iWARP path allocates exactly the peer-provided length, so a six-byte MPA request reaches the parser and the hsqsize load reads two bytes past the allocation.
Require the complete request structure before reading any of its fields. The decoded KASAN report is:
BUG: KASAN: slab-out-of-bounds in nvmet_rdma_cm_handler
(drivers/nvme/target/rdma.c:1427 drivers/nvme/target/rdma.c:1475
drivers/nvme/target/rdma.c:1614 drivers/nvme/target/rdma.c:1814)
Read of size 2 at addr ff1100010459d366 by task kworker/u16:1/41
Workqueue: iw_cm_wq cm_work_handler
Call Trace:
<TASK>
dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
print_report (mm/kasan/report.c:378 mm/kasan/report.c:482)
kasan_report (mm/kasan/report.c:595)
nvmet_rdma_cm_handler
(drivers/nvme/target/rdma.c:1427 drivers/nvme/target/rdma.c:1475
drivers/nvme/target/rdma.c:1614 drivers/nvme/target/rdma.c:1814)
cma_cm_event_handler (drivers/infiniband/core/cma.c:2181)
iw_conn_req_handler (drivers/infiniband/core/cma.c:2640)
cm_work_handler
(drivers/infiniband/core/cm.c:2502
drivers/infiniband/core/cm.c:3858)
process_one_work (kernel/workqueue.c:3396)
worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
kthread (kernel/kthread.c:436)
ret_from_fork (arch/x86/kernel/process.c:158)
ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
</TASK>
Allocated by task 12:
__kasan_kmalloc (mm/kasan/common.c:398 mm/kasan/common.c:415)
__kmalloc_node_track_caller_noprof
(mm/slub.c:5414 mm/slub.c:5545)
kmemdup_noprof (mm/util.c:138)
cm_event_handler
(drivers/infiniband/core/iwcm.c:194
drivers/infiniband/core/iwcm.c:1076)
siw_cm_upcall (drivers/infiniband/sw/siw/siw_cm.c:408)
siw_proc_mpareq (drivers/infiniband/sw/siw/siw_cm.c:750)
siw_cm_work_handler (drivers/infiniband/sw/siw/siw_cm.c:1086) The buggy address is located 0 bytes to the right of allocated 6-byte region [ff1100010459d360, ff1100010459d366)
--- drivers/nvme/target/rdma.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/rdma.c +1 -1
@@ -1412,7 +1412,7 @@ nvmet_rdma_parse_cm_connect_req(struct rdma_conn_param *conn,struct nvme_rdma_cm_req *req; req = (struct nvme_rdma_cm_req *)conn->private_data; -if (!req || conn->private_data_len ==0 ) +if (!req || conn->private_data_len <sizeof (*req))return NVME_RDMA_CM_INVALID_LEN ;if (le16_to_cpu (req->recfmt) !=NVME_RDMA_CM_FMT_1_0 )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1202/1257 nvmet-rdma: fix out-of-bounds write in nvmet_rdma_map_sgl_inline()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrew Stellman <[email protected]>
[ Upstream commit d1512773a0d539669440bd9f6d050b8e12923b5f ]
nvmet_rdma_map_sgl_inline() bounds the host-supplied in-capsule SGL offset with "off + len > inline_data_size", evaluated in 64-bit arithmetic. off is taken straight from the host SGL descriptor (le64_to_cpu(sgl->addr)) and len is promoted to 64-bit, so the sum
wraps: an off within len of 2^64 makes it small and the check passes. off is then used as page_idx = off / PAGE_SIZE to index the fixed-size rsp->cmd->inline_sg[] array (NVMET_RDMA_MAX_INLINE_SGE entries), so a crafted offset yields an out-of-bounds scatterlist index that is written through in nvmet_rdma_use_inline_sg().
The mapping runs while handling a received capsule, before the command executes, so a remote RDMA peer can reach it (the Connect capsule is a write and takes this path on a queue that has no controller yet). The host controls only the low bits of the resulting displacement, so the expected impact is an out-of-bounds write that faults the target (remote denial of service).
This wrap was reported, with a KASAN reproduction, on linux-nvme in May, and the check below was suggested in that thread. The fix that was applied, 48c0162f647b, reworked how the offset is mapped but kept the original check, and its page index turns a wrapped offset into an out-of-bounds index into inline_sg[].
Reject the offset before it can wrap.
Found independently by static analysis with AI assistance, not reproduced at runtime.
--- drivers/nvme/target/rdma.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/nvme/target/rdma.c +2 -1
@@ -864,7 +864,8 @@ static u16 nvmet_rdma_map_sgl_inline(struct nvmet_rdma_rsp *rsp)return NVME_SC_INVALID_FIELD |NVME_STATUS_DNR ; } -if (off + len > rsp->queue->dev->inline_data_size) { +if (off > (u64 )rsp->queue->dev->inline_data_size || + len > (u64 )rsp->queue->dev->inline_data_size - off) {pr_err ("invalid inline data offset!\n" );return NVME_SC_SGL_INVALID_OFFSET |NVME_STATUS_DNR ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1203/1257 nvmet-fc: only send read data for successful commands
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
[ Upstream commit 94f93c61b1a5dd08d011be58172ce4392b849008 ]
When a read command completes with an error, __nvmet_fc_fcp_nvme_cmd_done() still pushes the whole data buffer to the host before the response. nvmet_fc_alloc_tgt_pgs() allocates that buffer with sgl_alloc() and no __GFP_ZERO, and a command rejected by nvmet_check_transfer_len() leaves it untouched, so the host receives stale target memory.
The buffer is as large as the data length in the command IU, so the amount of stale memory returned is up to the host.
The tcp and rdma targets send data only when cqe->status is zero (see nvmet_tcp_need_data_out() and nvmet_rdma_need_data_out()), so no nvmet command can rely on returning data with an error status. Do the same for fc. The ERSP then reports a transferred length of fod->offset, which is 0, matching what nvme_fc_fcpio_done() checks on the host.
Tested over nvme-fcloop: a failed read command no longer transfers data and still completes with its error status, and successful reads are unaffected.
--- drivers/nvme/target/fc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/nvme/target/fc.c +4 -4
@@ -2486,11 +2486,11 @@ __nvmet_fc_fcp_nvme_cmd_done(struct nvmet_fc_tgtport *tgtport, }else {/* -* try to push the data even if the SQE status is non-zero. -* There may be a status where data still was intended to -* be moved +* A failed command may not have filled its read buffer, so +* only push data for success, as the tcp and rdma targets do. */ -if ((fod->io_dir ==NVMET_FCP_READ ) && (fod->data_sg_cnt)) { +if (fod->io_dir ==NVMET_FCP_READ && fod->data_sg_cnt && + !cqe->status) {/* push the data over before sending rsp */ nvmet_fc_transfer_fcp_data (tgtport, fod,NVMET_FCOP_READDATA );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1204/1257 nvmet: pci-epf: report transport errors in command completions
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
[ Upstream commit 46ed7310a60029826eedb01081a4556643ed5f3b ]
When the PCI endpoint target fails a command itself, the host receives a successful completion. This happens for a data length above MDTS, malformed PRPs or SGLs, a buffer allocation failure, an SQ that is not live, and a failed DMA of the command data. A write whose data cannot be fetched from the host is thus reported as written, though nothing was executed.
Each of these paths sets iod->status and calls nvmet_pci_epf_complete_iod(), which then reloads iod->status from iod->cqe.status. The nvmet core only fills that field when it completes the request, which these paths never do, so it is still zero and nvmet_pci_epf_cq_work() posts a success status to the host.
Drop the reload. Every path already sets iod->status before completion:nvmet_pci_epf_queue_response() copies it from the request's CQE, and the transport error paths set it themselves.
Found by code inspection.
--- drivers/nvme/target/pci-epf.c | 1 - 1 file changed, 1 deletion(-)
drivers/nvme/target/pci-epf.c +0 -1
@@ -1152,7 +1152,6 @@ static void nvmet_pci_epf_complete_iod(struct nvmet_pci_epf_iod *iod)unsigned long flags;/* Print an error message for failed commands, except AENs. */ - iod->status =le16_to_cpu (iod->cqe.status) >>1 ;if (iod->status && iod->cmd.common.opcode != nvme_admin_async_event) dev_err(iod->ctrl->dev, "CQ[%d]: Command %s (0x%x) status 0x%0x\n",
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1205/1257 nvmet: pci-epf: require SGLs to match the command data length
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
[ Upstream commit 9fb4adbc39751697b9fcf71e45bd5d5119c3f07c ]
The PCI endpoint target sends the host every byte a read command's SGL describes, even when the SGL describes more than the command transfers. The excess is kmalloc() memory the command never wrote, so the host receives stale target memory. Any successful read can do this, including Identify.
nvmet_pci_epf_alloc_iod_data_buf() allocates each segment at the length of its SGL data descriptor, but sets req->transfer_len from iod->data_len, the length the command implies. Once the command completes, nvmet_pci_epf_transfer_iod_data() sends every segment in full. Nothing compares the descriptor lengths with iod->data_len, and the MDTS check only bounds iod->data_len.
Fail the command with Data SGL Length Invalid when the data descriptors do not add up to iod->data_len, before any segment is allocated. The tcp and rdma transports take the data length from the SGL itself, so there most commands already reject a mismatch in nvmet_check_transfer_len(). PRP lists are built from iod->data_len and are unaffected.
Found by code inspection.
--- drivers/nvme/target/pci-epf.c | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-)
drivers/nvme/target/pci-epf.c +27 -2
@@ -1073,10 +1073,22 @@ static int nvmet_pci_epf_iod_parse_sgl_segments(struct nvmet_pci_epf_ctrl *ctrl,return 0 ; } +static u64 nvmet_pci_epf_iod_data_segs_len (struct nvmet_pci_epf_iod *iod) +{ +u64 len =0 ; +int i; + +for (i =0 ; i < iod->nr_data_segs; i++) + len += iod->data_segs[i].length; + +return len; +} +static int nvmet_pci_epf_iod_parse_sgls (struct nvmet_pci_epf_iod *iod) {struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;struct nvme_sgl_desc *sgl = &iod->cmd.common.dptr.sgl; +int ret;if (sgl->type == (NVME_SGL_FMT_DATA_DESC <<4 )) {/* Single data descriptor case. */
@@ -1084,10 +1096,23 @@ static int nvmet_pci_epf_iod_parse_sgls(struct nvmet_pci_epf_iod *iod) iod->data_segs = &iod->data_seg; iod->data_seg.pci_addr =le64_to_cpu (sgl->addr); iod->data_seg.length =le32_to_cpu (sgl->length); -return 0 ; + }else { + ret =nvmet_pci_epf_iod_parse_sgl_segments (ctrl, iod); +if (ret) +return ret; } -return nvmet_pci_epf_iod_parse_sgl_segments (ctrl, iod); +/* +* The command executes on data_len bytes, but each segment is +* allocated and transferred in full, so they must describe exactly +* data_len bytes. +*/ +if (nvmet_pci_epf_iod_data_segs_len (iod) != iod->data_len) { + iod->status =NVME_SC_SGL_INVALID_DATA |NVME_STATUS_DNR ; +return -EINVAL ; + } + +return 0 ; }static int nvmet_pci_epf_alloc_iod_data_buf (struct nvmet_pci_epf_iod *iod)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1206/1257 nvmet-auth: fix error handling on CHALLENGE failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shao Mingyin <[email protected]>
[ Upstream commit 96da408bb4a24bf87b366b13f41c2687d3c05671 ]
In nvmet_execute_auth_receive(), when nvmet_auth_challenge() fails (for example when the initiator-supplied allocation length is shorter than the DH-HMAC-CHAP challenge response, or the challenge nonce allocation fails), the error path sets status = NVME_SC_INTERNAL and breaks out of the switch. The unconditional
status = nvmet_copy_to_sgl(req, 0, d, al);
after the switch then overwrites the error status (nvmet_copy_to_sgl() returns 0 on success), so the AUTH_RECEIVE command incorrectly completes with SUCCESS and the initiator proceeds with a truncated/empty challenge.
Fix this by freeing the buffer and jumping to the common done: label on CHALLENGE failure, skipping the copy_to_sgl() entirely and preserving the NVME_SC_INTERNAL status.
--- drivers/nvme/target/fabrics-cmd-auth.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/nvme/target/fabrics-cmd-auth.c +4 -3
@@ -599,10 +599,11 @@ void nvmet_execute_auth_receive(struct nvmet_req *req)switch (req->sq->dhchap_step) {case NVME_AUTH_DHCHAP_MESSAGE_CHALLENGE :if (nvmet_auth_challenge (req, d, al) <0 ) { -pr_warn ("ctrl %d qid %d: challenge error (%d)\n" , - ctrl->cntlid, req->sq->qid, status); +pr_warn ("ctrl %d qid %d: challenge error\n" , + ctrl->cntlid, req->sq->qid); status =NVME_SC_INTERNAL ; -break ; +kfree (d); + goto done; } req->sq->dhchap_step =NVME_AUTH_DHCHAP_MESSAGE_REPLY ;break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1207/1257 nvmet-fc: Tear down the association when the admin queue allocation fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guixin Liu <[email protected]>
[ Upstream commit 11db8ab55e1a7533e9cfe57687ab142ba67d3c84 ]
When the initial admin queue allocation fails after a new association was created, nvmet_fc_ls_create_association() only drops the association reference, which frees the association. By then the association is already on the target port's assoc_list, though, and removal from that list only happens in nvmet_fc_delete_target_assoc(), which this error path never calls. The freed association stays on the list, where later lookups and the port teardown can access it, and the target port reference taken at allocation time leaks.
A remote host can trigger this reliably with a Create Association LS requesting a queue too large to allocate.
Schedule the regular association teardown instead of dropping the reference directly. The teardown removes the association from the list and releases the target port reference before the final reference drop frees it.
--- drivers/nvme/target/fc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/fc.c +1 -1
@@ -1705,7 +1705,7 @@ nvmet_fc_ls_create_association(struct nvmet_fc_tgtport *tgtport, be16_to_cpu(rqst->assoc_cmd.sqsize));if (!queue) { ret =VERR_QUEUE_ALLOC_FAIL ; -nvmet_fc_tgt_a_put (iod->assoc); +nvmet_fc_schedule_delete_assoc (iod->assoc); } } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1208/1257 nvme-tcp: start error recovery when read_sock fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Martin Belanger <[email protected]>
[ Upstream commit 288cfa187208cc9d0809eb8e1508658151a444dd ]
nvme_tcp_recv_skb() disables the queue and starts error recovery for errors it detects itself. An error returned by the transport reaches nvme_tcp_try_recv() without either action.
nvme_tcp_io_work() returns on a negative result and does not requeue itself, so the queue stops receiving and remains stalled until a command times out.
Report the error and start error recovery when the queue is still enabled, which indicates that the error was not handled by the actor. Do this under the socket lock, as nvme_tcp_recv_skb() does.
--- drivers/nvme/host/tcp.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
drivers/nvme/host/tcp.c +13 -0
@@ -1421,6 +1421,19 @@ static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue)lock_sock (sk); queue->nr_cqe =0 ; consumed = sock->ops->read_sock (sk, &rd_desc, nvme_tcp_recv_skb); +/* +* nvme_tcp_recv_skb() handles its own errors, so a queue that is +* still enabled failed inside read_sock(). Handle it before +* release_sock() processes the backlog. +*/ +if (unlikely (consumed <0 && consumed != -EAGAIN && + queue->rd_enabled)) { +dev_err (queue->ctrl->ctrl.device, +"queue %d: receive failed: %d\n" , +nvme_tcp_queue_id (queue), consumed); + queue->rd_enabled = false; +nvme_tcp_error_recovery (&queue->ctrl->ctrl); + }release_sock (sk);return consumed == -EAGAIN ?0 : consumed; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1209/1257 nvme-tcp: fix io_work priority inversion when send_mutex is held
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Seiji Nishikawa <[email protected]>
[ Upstream commit 5db358f3a7f9c33717622c1597d15c4c91997b19 ]
Commit f42d4796ee10 ("nvme-tcp: fix I/O stalls on congested sockets") added a check in nvme_tcp_io_work() that sets pending to true when the queue has pending requests and the socket is writeable. The check is placed after the mutex_trylock() block, so it also runs when mutex_trylock(&queue->send_mutex) failed and io_work did not send anything.
When .queue_rq sends a request directly from its own context, it holds send_mutex and can give up the CPU in lock_sock_nested() when another task needs the CPU, for example the io_work kworker of the same queue, which runs on the same CPU. Then io_work cannot take send_mutex, but the requests are still on req_list and the socket is writeable, so pending is set to true. io_work loops until the deadline and queues itself again on io_cpu, without sleeping.
This is a priority inversion. io_work runs on the high priority nvme_tcp_wq and cannot make progress until send_mutex is released, but it keeps running. The task holding send_mutex runs at normal priority and needs the CPU to release it. The scheduler keeps giving the CPU to io_work, so the task holding send_mutex may not run again, and the requests on the queue are not sent and time out.
This is the same problem that commit 70f437fb4395 ("nvme-tcp: fix io_work priority inversion") fixed. That commit removed "pending = !llist_empty(&queue->req_list)" from the path where mutex_trylock() fails, and let the task holding send_mutex queue io_work again in nvme_tcp_queue_request() after it releases the mutex. The new check brings back the same behavior in a different form.
Two things make this easier to hit. nvme_tcp_queue_request() sends directly only when it runs on io_cpu, so the task that takes send_mutex is on the same CPU as the io_work kworker of that queue when it takes the mutex. Also, when the tasks are in a cgroup with the cpu controller enabled, the whole group competes with the nice -20 kworker as one entity, so each task in the group gets even less CPU time.
We hit this on a 6 CPU VM running a database on nvme-tcp storage. In the vmcore, 2 tasks held send_mutex of 2 queues and were runnable in lock_sock_nested() for 103 seconds, while the kworkers for those queues kept running io_work on their CPUs. All database tasks were in one cgroup, which got only about 0.3% of the CPU against the nice -20 kworker. Requests timed out, and blk_mq_timeout_work() waited in synchronize_srcu() for the tasks still in .queue_rq.
Only do the pending check if io_work could take send_mutex. If it could not, the task holding send_mutex sends what it can in nvme_tcp_send_all(), and queues io_work again after it releases the mutex if requests are still pending, so no request is left behind.
--- drivers/nvme/host/tcp.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/nvme/host/tcp.c +9 -2
@@ -1446,9 +1446,11 @@ static void nvme_tcp_io_work(struct work_struct *w) do { bool pending = false; + bool got_send_mutex = false; int result; if (mutex_trylock(&queue->send_mutex)) { + got_send_mutex = true; result = nvme_tcp_try_send(queue); mutex_unlock(&queue->send_mutex); if (result > 0)
@@ -1463,8 +1465,13 @@ static void nvme_tcp_io_work(struct work_struct *w)else if (unlikely (result <0 ))return ; -/* did we get some space after spending time in recv? */ -if (nvme_tcp_queue_has_pending (queue) && +/* +* did we get some space after spending time in recv? +* Only check this if we could take send_mutex. Otherwise +* the task holding it sends the requests and queues io_work +* again after it releases the mutex. +*/ +if (got_send_mutex &&nvme_tcp_queue_has_pending (queue) &&sk_stream_is_writeable (queue->sock->sk)) pending = true;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1210/1257 nvmet: Finish the blk plug when integrity allocation fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guixin Liu <[email protected]>
[ Upstream commit 18fc5f6f1ca945630dae5404265de55d65194e22 ]
nvmet_bdev_execute_rw() starts a plug before building the bios, but the two error exits taken when nvmet_bdev_alloc_bip() fails return without calling blk_finish_plug(). current->plug is left pointing at the stack frame of the returned function, so the next blk_flush_plug() walks a stale list.
Route both failures through a common exit that finishes the plug.
--- drivers/nvme/target/io-cmd-bdev.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/nvme/target/io-cmd-bdev.c +3 -2
@@ -316,7 +316,7 @@ static void nvmet_bdev_execute_rw(struct nvmet_req *req) &prot_miter);if (unlikely (rc)) {bio_io_error (bio); -return ; + goto out_plug; } }
@@ -336,11 +336,12 @@ static void nvmet_bdev_execute_rw(struct nvmet_req *req) rc =nvmet_bdev_alloc_bip (req, bio, &prot_miter);if (unlikely (rc)) {bio_io_error (bio); -return ; + goto out_plug; } }submit_bio (bio); +out_plug:blk_finish_plug (&plug); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1211/1257 nvmet: Free the old negotiation state when restarting authentication
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guixin Liu <[email protected]>
[ Upstream commit 5c279fcabb0ea7ba61881c13027b15d8054b8abd ]
Restarting a DH-HMAC-CHAP negotiation with SEND(NEGOTIATE) resets sq->dhchap_step but does not release the previous c1/c2/skey, which are only freed in nvmet_auth_sq_free() at teardown. The next CHALLENGE/REPLY exchange then overwrites those pointers with fresh allocations.
An unauthenticated host can repeat the negotiate message endlessly, leaking a few dozen bytes per round and slowly exhausting target memory.
Clear the old negotiation state with nvmet_auth_sq_free() before setting up the new one. Also reset dhchap_skey_len to zero: if a DH session key was already established, a following round with dhvlen=0 would otherwise pass a NULL skey with a stale non-zero length to the HMAC code and dereference it.
--- drivers/nvme/target/auth.c | 1 + drivers/nvme/target/fabrics-cmd-auth.c | 1 + 2 files changed, 2 insertions(+)
drivers/nvme/target/auth.c +1 -0
@@ -237,6 +237,7 @@ void nvmet_auth_sq_free(struct nvmet_sq *sq) sq->dhchap_c2 =NULL ;kfree (sq->dhchap_skey); sq->dhchap_skey =NULL ; + sq->dhchap_skey_len =0 ; }void nvmet_auth_sq_destroy (struct nvmet_sq *sq)
drivers/nvme/target/fabrics-cmd-auth.c +1 -0
@@ -324,6 +324,7 @@ void nvmet_execute_auth_send(struct nvmet_req *req)/* Restart negotiation */ pr_debug ("%s: ctrl %d qid %d reset negotiation\n" , __func__, ctrl->cntlid, req->sq->qid); +nvmet_auth_sq_free (req->sq);if (!req->sq->qid) { dhchap_status =nvmet_setup_auth (ctrl, req->sq, true);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1212/1257 nvmet-tcp: validate the TLS handshake timeout
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
[ Upstream commit e3e7a85730a4b17efa1e2ff4088443c4753be683 ]
tls_handshake_timeout is writable but stored as a signed int. Multiplying the value by MSEC_PER_SEC and HZ therefore uses signed arithmetic.
With HZ=1000, setting it to 2147484 overflows both multiplications. If the handshake request is accepted and remains pending, the timer wheel treats the jiffies delay as already expired and queues the timeout work on its next advance, while the handshake agent was given about 24.9 days. Negative values such as -1 cause the same immediate kernel-side timeout.
Store the parameter as an unsigned int and reject values that cannot be represented both by tls_handshake_args::ta_timeout_ms and by a safe jiffies delay. Take one snapshot so a concurrent parameter update cannot give the handshake agent and delayed work different timeouts. Document the accepted range for built-in use.
Negative and oversized values now fail with -EINVAL. Keep zero valid, preserving the existing immediate-timeout behavior.
--- .../admin-guide/kernel-parameters.txt | 5 ++++ drivers/nvme/target/tcp.c | 26 ++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +5 -0
@@ -4802,6 +4802,11 @@ Kernel parameters Example: nvme.quirks=7710:2267:bogus_nid,^identify_cns-9900:7711:broken_msi + nvmet_tcp.tls_handshake_timeout= + [NVME] NVMe/TCP target TLS handshake timeout in seconds. + Valid values range from 0 to the smaller of + UINT_MAX / 1000 and MAX_JIFFY_OFFSET / HZ. Default: 10 + ohci1394_dma=early [HW,EARLY] enable debugging via the ohci1394 driver. See Documentation/core-api/debugging-via-ohci1394.rst for more info.
drivers/nvme/target/tcp.c +22 -4
@@ -6,6 +6,7 @@#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <linux/module.h> #include <linux/init.h> +#include <linux/jiffies.h> #include <linux/slab.h> #include <linux/crc32c.h> #include <linux/err.h>
@@ -76,8 +77,24 @@ MODULE_PARM_DESC(idle_poll_period_usecs,/* * TLS handshake timeout */ -static int tls_handshake_timeout =10 ; -module_param (tls_handshake_timeout, int,0644 ); +static unsigned int tls_handshake_timeout =10 ; + +static int tls_handshake_timeout_set (const char *val, +const struct kernel_param *kp) +{ +return param_set_uint_minmax (val, kp,0 , + min_t(unsigned long, UINT_MAX / MSEC_PER_SEC, +MAX_JIFFY_OFFSET /HZ )); +} + +static const struct kernel_param_ops tls_handshake_timeout_ops = { + .set = tls_handshake_timeout_set, + .get = param_get_uint, +}; + +module_param_cb (tls_handshake_timeout, &tls_handshake_timeout_ops, + &tls_handshake_timeout,0644 ); +__MODULE_PARM_TYPE (tls_handshake_timeout,"uint" );MODULE_PARM_DESC (tls_handshake_timeout,"nvme TLS handshake timeout in seconds (default 10)" );#endif
@@ -1904,6 +1921,7 @@ static int nvmet_tcp_tls_handshake(struct nvmet_tcp_queue *queue) {int ret = -EOPNOTSUPP ;struct tls_handshake_args args; +unsigned int timeout =READ_ONCE (tls_handshake_timeout);if (queue->state !=NVMET_TCP_Q_TLS_HANDSHAKE ) {pr_warn ("cannot start TLS in state %d\n" , queue->state);
@@ -1917,7 +1935,7 @@ static int nvmet_tcp_tls_handshake(struct nvmet_tcp_queue *queue) args.ta_done = nvmet_tcp_tls_handshake_done; args.ta_data = queue; args.ta_keyring =key_serial (queue->port->nport->keyring); - args.ta_timeout_ms = tls_handshake_timeout *1000 ; + args.ta_timeout_ms = timeout *MSEC_PER_SEC ; ret =tls_server_hello_psk (&args,GFP_KERNEL );if (ret) {
@@ -1925,7 +1943,7 @@ static int nvmet_tcp_tls_handshake(struct nvmet_tcp_queue *queue)pr_err ("failed to start TLS, err=%d\n" , ret); }else {queue_delayed_work (nvmet_wq, &queue->tls_handshake_tmo_work, - tls_handshake_timeout *HZ ); + (unsigned long )timeout *HZ ); }return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1213/1257 nvme-tcp: validate the TLS handshake timeout
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
[ Upstream commit 799203afd298b1f8e9ee49815eb38f775f211299 ]
tls_handshake_timeout is writable but stored as a signed int. Multiplying the value by MSEC_PER_SEC and HZ therefore uses signed arithmetic.
With HZ=1000, setting it to 2147484 overflows both multiplications. If the handshake request is accepted and its completion remains pending, schedule_timeout() reports a wrong timeout value with a stack dump and returns zero. The handshake then fails immediately with -ETIMEDOUT, while the handshake agent was given about 24.9 days. Negative values such as -1 have the same kernel-side effect.
Store the parameter as an unsigned int and reject values that cannot be represented both by tls_handshake_args::ta_timeout_ms and by a safe jiffies delay. Take one snapshot so a concurrent parameter update cannot give the handshake agent and completion wait different timeouts. Document the accepted range for built-in use.
wait_for_completion_interruptible_timeout() returns the remaining jiffies as a long after a successful completion. Keep that result in a long because an accepted timeout can exceed INT_MAX jiffies on 64-bit systems.
Negative and oversized values now fail with -EINVAL. Keep zero valid, preserving the existing immediate-timeout behavior.
--- .../admin-guide/kernel-parameters.txt | 5 +++ drivers/nvme/host/tcp.c | 34 ++++++++++++++----- 2 files changed, 31 insertions(+), 8 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +5 -0
@@ -4802,6 +4802,11 @@ Kernel parameters Example: nvme.quirks=7710:2267:bogus_nid,^identify_cns-9900:7711:broken_msi + nvme_tcp.tls_handshake_timeout= + [NVME] NVMe/TCP host TLS handshake timeout in seconds. + Valid values range from 0 to the smaller of + UINT_MAX / 1000 and MAX_JIFFY_OFFSET / HZ. Default: 10 + nvmet_tcp.tls_handshake_timeout= [NVME] NVMe/TCP target TLS handshake timeout in seconds. Valid values range from 0 to the smaller of
drivers/nvme/host/tcp.c +26 -8
@@ -6,6 +6,7 @@#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <linux/module.h> #include <linux/init.h> +#include <linux/jiffies.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/crc32.h>
@@ -47,9 +48,24 @@ MODULE_PARM_DESC(wq_unbound, "Use unbound workqueue for nvme-tcp IO context (def/* * TLS handshake timeout */ -static int tls_handshake_timeout =10 ; +static unsigned int tls_handshake_timeout =10 ;#ifdef CONFIG_NVME_TCP_TLS -module_param (tls_handshake_timeout, int,0644 ); +static int tls_handshake_timeout_set (const char *val, +const struct kernel_param *kp) +{ +return param_set_uint_minmax (val, kp,0 , + min_t(unsigned long, UINT_MAX / MSEC_PER_SEC, +MAX_JIFFY_OFFSET /HZ )); +} + +static const struct kernel_param_ops tls_handshake_timeout_ops = { + .set = tls_handshake_timeout_set, + .get = param_get_uint, +}; + +module_param_cb (tls_handshake_timeout, &tls_handshake_timeout_ops, + &tls_handshake_timeout,0644 ); +__MODULE_PARM_TYPE (tls_handshake_timeout,"uint" );MODULE_PARM_DESC (tls_handshake_timeout,"nvme TLS handshake timeout in seconds (default 10)" );#endif
@@ -1804,8 +1820,10 @@ static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl, {int qid =nvme_tcp_queue_id (queue);int ret; +long wait_ret;struct tls_handshake_args args; -unsigned long tmo = tls_handshake_timeout *HZ ; +unsigned int timeout =READ_ONCE (tls_handshake_timeout); +unsigned long tmo = (unsigned long )timeout *HZ ;key_serial_t keyring =nvme_keyring_id (); dev_dbg(nctrl->device, "queue %d: start TLS with key %x\n",
@@ -1819,7 +1837,7 @@ static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl,if (nctrl->opts->keyring) keyring =key_serial (nctrl->opts->keyring); args.ta_keyring = keyring; - args.ta_timeout_ms = tls_handshake_timeout *1000 ; + args.ta_timeout_ms = timeout *MSEC_PER_SEC ; queue->tls_err = -EOPNOTSUPP ;init_completion (&queue->tls_complete); ret =tls_client_hello_psk (&args,GFP_KERNEL );
@@ -1828,10 +1846,10 @@ static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl, qid, ret);return ret; } - ret =wait_for_completion_interruptible_timeout (&queue->tls_complete, tmo); -if (ret <=0 ) { -if (ret ==0 ) - ret = -ETIMEDOUT ; + wait_ret =wait_for_completion_interruptible_timeout (&queue->tls_complete, + tmo); +if (wait_ret <=0 ) { + ret = wait_ret <0 ? -ERESTARTSYS : -ETIMEDOUT ; dev_err(nctrl->device, "queue %d: TLS handshake failed, error %d\n",
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1214/1257 kgdb: Fix buffer overflow in the m packet handler
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fang Xieyan <[email protected]>
[ Upstream commit ac0159129e2cb99a70c4b80cfbf58d03e092dc7b ]
gdb_cmd_memread() passes the length of the 'm' packet straight to kgdb_mem2hex(), which hex-encodes the reply into remcom_out_buffer[BUFMAX] without checking that the reply fits. A client on the KGDB I/O console can ask for a read of any size, and the hex encoding runs off the end of the buffer. kgdb_mem2hex() takes that length as an int count, so 2^31 truncates to a negative value and copy_from_kernel_nofault() is handed buf + count as its destination.
On x86 BUFMAX is 1024, so a read of 512 bytes overruns by the single byte that terminates the hex string:
BUG: KASAN: global-out-of-bounds in kgdb_mem2hex+0x1dd/0x230 Write of size 1 at addr ffffffff87651780 by task sh/1 ... The buggy address belongs to the variable: remcom_out_buffer+0x400/0x420
Bounds check the length before the hex encoding:
if (length > (BUFMAX - 1) / 2) {
error_packet(remcom_out_buffer, -EINVAL);
return;
}gdbstub_msg_write() already bounds the count it hex-encodes against BUFMAX. Reads over the limit never returned valid data, so an error reply loses nothing.
--- kernel/debug/gdbstub.c | 8 ++++++++ 1 file changed, 8 insertions(+)
kernel/debug/gdbstub.c +8 -0
@@ -563,6 +563,14 @@ static void gdb_cmd_memread(struct kgdb_state *ks)if (kgdb_hex2long (&ptr, &addr) >0 && *ptr++ ==',' &&kgdb_hex2long (&ptr, &length) >0 ) { +/* +* The hex-encoded reply needs 2 * length + 1 bytes +* in remcom_out_buffer[BUFMAX]. +*/ +if (length > (BUFMAX -1 ) /2 ) { +error_packet (remcom_out_buffer, -EINVAL ); +return ; + } err =kgdb_mem2hex ((char *)addr, remcom_out_buffer, length);if (!err)error_packet (remcom_out_buffer, -EINVAL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1215/1257 kgdb: Fix buffer overflow in the M and X packet handlers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fang Xieyan <[email protected]>
[ Upstream commit 13962ef7021ef2531a4f6650eca87c363e6c9c32 ]
write_mem_msg() passes the length claimed by an 'M' or 'X' packet directly to kgdb_hex2mem() or kgdb_ebin2mem(). A malformed packet can claim more data than was actually received, causing the decoders to read past remcom_in_buffer.
Record the received payload length in get_packet() and use it to bound the decoders. 'M' carries two hex characters per byte, while 'X' carries one byte per output byte except that a 0x7d escape consumes an additional input byte. Pass the packet end to kgdb_ebin2mem() so both reads are checked against the received data.
Keep zero-length 'X' packets valid, as GDB uses them to probe binary download support.
--- kernel/debug/gdbstub.c | 45 +++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 7 deletions(-)
kernel/debug/gdbstub.c +38 -7
@@ -43,6 +43,8 @@/* Our I/O buffers. */ static char remcom_in_buffer[BUFMAX ];static char remcom_out_buffer[BUFMAX ]; +/* Payload bytes get_packet() stored in remcom_in_buffer, excluding the NUL. */ +static int remcom_in_len;static int gdbstub_use_prev_in_buf;static int gdbstub_prev_in_buf_pos;
@@ -87,7 +89,7 @@ static int gdbstub_read_wait(void) }#endif /* scan for the sequence $<data>#<checksum> */ -static void get_packet (char *buffer) +static int get_packet (char *buffer) {unsigned char checksum;unsigned char xmitcsum;
@@ -135,6 +137,8 @@ static void get_packet(char *buffer) } buffer[count] =0 ; }while (checksum != xmitcsum); + +return count; }/*
@@ -321,16 +325,26 @@ int kgdb_hex2long(char **ptr, unsigned long *long_val)* Copy the binary array pointed to by buf into mem. Fix $, #, and * 0x7d escaped with 0x7d. Return -EFAULT on failure or 0 on success. * The input buf is overwritten with the result to write to mem. +* +* buf_end points one past the last byte received for this packet. Each +* 0x7d escape consumes a second input byte, so decoding count bytes can +* read up to 2 * count input bytes; stop at buf_end rather than running +* off the end of remcom_in_buffer. */ -static int kgdb_ebin2mem (char *buf,char *mem,int count) +static int kgdb_ebin2mem (char *buf,char *mem,int count,char *buf_end) {int size =0 ;char *c = buf;while (count-- >0 ) { +if (buf >= buf_end) +return -EINVAL ; c[size] = *buf++; -if (c[size] ==0x7d ) +if (c[size] ==0x7d ) { +if (buf >= buf_end) +return -EINVAL ; c[size] = *buf++ ^0x20 ; + } size++; }
@@ -367,16 +381,33 @@ void gdb_regs_to_pt_regs(unsigned long *gdb_regs, struct pt_regs *regs)static int write_mem_msg (int binary) {char *ptr = &remcom_in_buffer[1 ]; +char *buf_end = &remcom_in_buffer[remcom_in_len];unsigned long addr;unsigned long length;int err;if (kgdb_hex2long (&ptr, &addr) >0 && *(ptr++) ==',' &&kgdb_hex2long (&ptr, &length) >0 && *(ptr++) ==':' ) { -if (binary) - err =kgdb_ebin2mem (ptr, (char *)addr, length); -else +/* +* Trust only the bytes actually received, not length: the +* client can claim more payload than it sent. 'M' decodes two +* hex chars per byte in place, so it needs 2 * length bytes at +* ptr; 'X' decodes one byte per byte, and kgdb_ebin2mem() bounds +* its extra 0x7d-escape reads against buf_end itself. +*/ +if (ptr >= buf_end) +return -EINVAL ; + +if (binary) { +if (length > (unsigned long )(buf_end - ptr)) +return -EINVAL ; + err =kgdb_ebin2mem (ptr, (char *)addr, length, buf_end); + }else { +if (length > (unsigned long )(buf_end - ptr) /2 ) +return -EINVAL ; err =kgdb_hex2mem (ptr, (char *)addr, length); + } +if (err)return err;if (CACHE_FLUSH_IS_SAFE )
@@ -993,7 +1024,7 @@ int gdb_serial_stub(struct kgdb_state *ks)/* Clear the out buffer. */ memset (remcom_out_buffer,0 ,sizeof (remcom_out_buffer)); -get_packet (remcom_in_buffer); + remcom_in_len =get_packet (remcom_in_buffer);switch (remcom_in_buffer[0 ]) {case '?' :/* gdbserial status */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1216/1257 kgdb: Fix buffer overflow in the qRcmd packet handler
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fang Xieyan <[email protected]>
[ Upstream commit 9ca9e8c857b55a081d5a1f8039b27cbb4d646b49 ]
gdb_cmd_query() decodes the hex payload of a qRcmd packet (the GDB "monitor" command passthrough to kdb) into remcom_out_buffer and hands it to kdb_parse(). It sizes the decode with strlen() of the payload:
int len = strlen(remcom_in_buffer + 6); ... kgdb_hex2mem(remcom_in_buffer + 6, remcom_out_buffer, len); len = len / 2;
kgdb_hex2mem() takes count as the number of bytes to produce and decodes them in place at buf, reading and writing 2 * count bytes there. len here is the hex character count, twice the decoded size, so the decode runs over 2 * len bytes at remcom_in_buffer + 6, off the end of the buffer. On x86 BUFMAX is 1024, so a 256-byte monitor command (512 hex characters) overruns remcom_in_buffer during the in-place decode:
BUG: KASAN: global-out-of-bounds in kgdb_hex2mem+0x131/0x160 Read of size 1 at addr ffffffff8765ef05 by task sh/1 ... kgdb_hex2mem+0x131/0x160 gdb_serial_stub+0x16d4/0x3170 kgdb_cpu_enter+0xb68/0x1520 ... The buggy address belongs to the variable: remcom_in_buffer+0x405/0x420
Halve len before the call so kgdb_hex2mem() gets the decoded byte count. It then reads the len hex characters already in remcom_in_buffer and writes len / 2 bytes, all inside the buffer, and remcom_out_buffer holds the same command as before.
--- kernel/debug/gdbstub.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/debug/gdbstub.c +1 -1
@@ -817,9 +817,9 @@ static void gdb_cmd_query(struct kgdb_state *ks)strscpy (remcom_out_buffer,"E01" );break ; } + len = len /2 ;kgdb_hex2mem (remcom_in_buffer +6 , remcom_out_buffer, len); - len = len /2 ; remcom_out_buffer[len++] =0 ;kdb_common_init_state (ks);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1217/1257 fsverity: Explicitly require FMODE_READ to retrieve hashes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
[ Upstream commit 1acb4fd2d011c4bd6cc961095ae17361c71ff61a ]
The comment in fsverity_ioctl_read_metadata(), which justifies not checking for FMODE_READ, doesn't consider that the nonstandard access mode 3 (ioctl-only) exists.
Opening an ioctl-only fd generally requires read (and write) permission. However, there are gaps with certain LSMs: an ioctl-only fd requests read (and write) permission via security_inode_permission, but not security_file_open. With certain LSMs relying on the latter, such as Landlock and AppArmor, an ioctl-only fd can be opened without the LSM granting read (and write) permission.
Since FS_IOC_READ_VERITY_METADATA returns hashes of file contents blocks, it should require read permission. This also applies to FS_IOC_MEASURE_VERITY, which returns a hash for the whole file.
Meanwhile, ioctl-only fds are a rarely-used feature, not known to be used with either ioctl.
Therefore, just disallow these ioctls on ioctl-only file descriptors, similar to what was already done with FS_IOC_ENABLE_VERITY.
More specifically, explicitly check for FMODE_READ. This also covers write-only fds to non-verity files which otherwise would have failed with ENODATA. This change in error code for write-only fds should be fine too, as these ioctls cannot be usefully used with write-only fds anyway, but it's worth noting as another technicality.
--- Documentation/filesystems/fsverity.rst | 3 +++ fs/verity/measure.c | 10 ++++++++++ fs/verity/read_metadata.c | 14 ++++++++++---- 3 files changed, 23 insertions(+), 4 deletions(-)
Documentation/filesystems/fsverity.rst +3 -0
@@ -170,6 +170,7 @@ fatal signal), no changes are made to the file. FS_IOC_ENABLE_VERITY can fail with the following errors: - ``EACCES``: the process does not have write access to the file +- ``EBADF``: the file descriptor is not open for reading - ``EBADMSG``: the builtin signature is malformed - ``EBUSY``: this ioctl is already running on the file - ``EEXIST``: the file already has verity enabled
@@ -232,6 +233,7 @@ regardless of the size of the file. FS_IOC_MEASURE_VERITY can fail with the following errors: +- ``EBADF``: the file descriptor is not open for reading - ``EFAULT``: the caller provided inaccessible memory - ``ENODATA``: the file is not a verity file - ``ENOTTY``: this type of filesystem does not implement fs-verity
@@ -310,6 +312,7 @@ blocks from disk without actually verifying the path to the root node. FS_IOC_READ_VERITY_METADATA can fail with the following errors: +- ``EBADF``: the file descriptor is not open for reading - ``EFAULT``: the caller provided inaccessible memory - ``EINTR``: the ioctl was interrupted before any data was read - ``EINVAL``: reserved fields were set, or ``offset + length``
fs/verity/measure.c +10 -0
@@ -31,6 +31,16 @@ int fsverity_ioctl_measure(struct file *filp, void __user *_uarg)const struct fsverity_hash_alg *hash_alg;struct fsverity_digest arg; +/* +* This ioctl returns a hash of the file contents, so it should require +* read permission. Disallow it on ioctl-only (i.e., nonstandard access +* mode 3) fds, which can in some cases be acquired without passing all +* LSM read-permission checks. Also disallow write-only fds, which can +* refer only to non-verity files which would fail with ENODATA anyway. +*/ +if (!(filp->f_mode &FMODE_READ )) +return -EBADF ; + vi =fsverity_get_info (inode);if (!vi)return -ENODATA ;/* not a verity file */
fs/verity/read_metadata.c +10 -4
@@ -166,13 +166,19 @@ int fsverity_ioctl_read_metadata(struct file *filp, const void __user *uarg)int length;void __user *buf; +/* +* This ioctl returns file contents block hashes, so it should require +* read permission. Disallow it on ioctl-only (i.e., nonstandard access +* mode 3) fds, which can in some cases be acquired without passing all +* LSM read-permission checks. Also disallow write-only fds, which can +* refer only to non-verity files which would fail with ENODATA anyway. +*/ +if (!(filp->f_mode &FMODE_READ )) +return -EBADF ; + vi =fsverity_get_info (inode);if (!vi)return -ENODATA ;/* not a verity file */ -/* -* Note that we don't have to explicitly check that the file is open for -* reading, since verity files can only be opened for reading. -*/ if (copy_from_user (&arg, uarg,sizeof (arg)))return -EFAULT ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1218/1257 fsverity: Be more careful with return value of ->get_verity_descriptor()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
[ Upstream commit 8f8faec82aa902b1997ae578c46bcc84afbad811 ]
If fsverity_operations::get_verity_descriptor() returns that the verity descriptor has 0 size, then a zero-size buffer is allocated to hold it, and it's called again with bufsize=0.
But bufsize=0 is a special case that says to return the actual size. If in the meantime the filesystem has decided that the size is some actually valid size, it will return that size, and then validate_fsverity_descriptor() will read from ZERO_SIZE_PTR and crash.
Of course, for the filesystem to misbehave in that strange way, it generally would require direct writes to the block device.
Regardless, fsverity_get_descriptor() might as well guard against it. Make it do so. Specifically, validate that the first call to ->get_verity_descriptor() returns at least the minimum descriptor size, and validate that the second call returns the same size as the first.
--- fs/verity/open.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-)
fs/verity/open.c +19 -19
@@ -270,12 +270,6 @@ static bool validate_fsverity_descriptor(struct inode *inode,const struct fsverity_descriptor *desc, size_t desc_size) { - if (desc_size < sizeof(*desc)) { - fsverity_err(inode, "Unrecognized descriptor size: %zu bytes", - desc_size); -return false; - } - if (desc->version != 1) { fsverity_err(inode, "Unrecognized descriptor version: %u", desc->version);
@@ -314,31 +308,37 @@ static bool validate_fsverity_descriptor(struct inode *inode,int fsverity_get_descriptor (struct inode *inode,struct fsverity_descriptor **desc_ret) { -int res; +int size, res;struct fsverity_descriptor *desc; - res = inode->i_sb->s_vop->get_verity_descriptor (inode,NULL ,0 ); -if (res <0 ) { -fsverity_err (inode, -"Error %d getting verity descriptor size" , res); -return res; + size = inode->i_sb->s_vop->get_verity_descriptor (inode,NULL ,0 ); +if (size <0 ) { +fsverity_err (inode,"Error %d getting verity descriptor size" , + size); +return size; } -if (res >FS_VERITY_MAX_DESCRIPTOR_SIZE ) { -fsverity_err (inode,"Verity descriptor is too large (%d bytes)" , - res); +if (size <sizeof (*desc) || size >FS_VERITY_MAX_DESCRIPTOR_SIZE ) { +fsverity_err (inode, +"Verity descriptor has invalid size (%d bytes)" , + size);return -EMSGSIZE ; } - desc =kmalloc (res,GFP_KERNEL ); + desc =kmalloc (size,GFP_KERNEL );if (!desc)return -ENOMEM ; - res = inode->i_sb->s_vop->get_verity_descriptor (inode, desc, res); + res = inode->i_sb->s_vop->get_verity_descriptor (inode, desc, size);if (res <0 ) {fsverity_err (inode,"Error %d reading verity descriptor" , res);kfree (desc);return res; } - -if (!validate_fsverity_descriptor (inode, desc, res)) { +if (res != size) { +fsverity_err (inode,"Verity descriptor size changed (%d => %d)" , + size, res); +kfree (desc); +return -EINVAL ; + } +if (!validate_fsverity_descriptor (inode, desc, size)) {kfree (desc);return -EINVAL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1219/1257 fsverity: Tell LSMs about signature only after verity is enabled
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
[ Upstream commit 28d74059fddbd8ae83c7715056b303c402071f6f ]
FS_IOC_ENABLE_VERITY calls security_inode_setintegrity() before verity has finished being enabled. That's broken because enabling verity can still fail at that point, e.g. due to insufficient xattr space.
Afterwards, arbitrary contents can be written to the file, which doesn't actually have verity enabled. The in-core inode stays the same, so the LSM considers it to have verity enabled with a valid signature. (Or rather, in the case of IPE, which is the only LSM that implements security_inode_setintegrity(), it also checks IS_VERITY(), which can be bypassed by enabling verity with no signature after the file writes.)
Fix this by moving the call to security_inode_setintegrity() out of fsverity_verify_signature() and into a new function that is called from the appropriate places.
--- fs/verity/enable.c | 8 ++++++ fs/verity/fsverity_private.h | 8 ++++++ fs/verity/open.c | 9 ++++++ fs/verity/signature.c | 55 ++++++++++++++++++++++++++---------- 4 files changed, 65 insertions(+), 15 deletions(-)
fs/verity/enable.c +8 -0
@@ -298,6 +298,14 @@ static int enable_verity(struct file *filp, }else if (WARN_ON_ONCE (!IS_VERITY (inode))) {fsverity_remove_info (vi); err = -EINVAL ; + }else { +/* +* Now that verity is enabled, report the signature (if any) to +* LSMs. We tolerate that a process racing with this ioctl can +* briefly see verity enabled with no signature reported yet. +*/ +fsverity_report_valid_sig (inode, desc->signature, +le32_to_cpu (desc->sig_size)); } out:kfree (params.hashstate);
fs/verity/fsverity_private.h +8 -0
@@ -160,6 +160,8 @@ void __init fsverity_init_info_cache(void);extern int fsverity_require_signatures;int fsverity_verify_signature (const struct fsverity_info *vi,const u8 *signature,size_t sig_size); +void fsverity_report_valid_sig (const struct inode *inode,const u8 *signature, +size_t sig_size);void __init fsverity_init_signature (void );#else /* !CONFIG_FS_VERITY_BUILTIN_SIGNATURES */
@@ -170,6 +172,12 @@ fsverity_verify_signature(const struct fsverity_info *vi,return 0 ; } +static inline void fsverity_report_valid_sig (const struct inode *inode, +const u8 *signature, +size_t sig_size) +{ +} +static inline void fsverity_init_signature (void ) { }
fs/verity/open.c +9 -0
@@ -366,6 +366,15 @@ static int ensure_verity_info(struct inode *inode) goto out_free_desc; } +/* +* Now that the signature (if any) has been verified, report it to LSMs. +* Do this before inserting the fsverity_info into the hashtable, so +* that anyone who concurrently retrieves the fsverity_info for the same +* inode is guaranteed to see the LSM's signature status populated. +*/ +fsverity_report_valid_sig (inode, desc->signature, +le32_to_cpu (desc->sig_size)); +/* * Multiple tasks may race to set the inode's verity info, in which case * we might find an existing fsverity_info in the hash table.
fs/verity/signature.c +40 -15
71 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1220/1257 irqchip/riscv-imsic: Report successful hardware retrigger
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
[ Upstream commit a2f482407d33ebe7f12e30d6cf383ffb1c7d709d ]
imsic_irq_retrigger() writes to the IMSIC MSI register to retrigger an interrupt, but returns 0. The IRQ core treats zero as failure and may schedule a software resend despite the hardware retrigger.
Return 1 after the MSI write to report successful hardware retriggering and prevent the unnecessary software resend.
--- drivers/irqchip/irq-riscv-imsic-platform.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/irqchip/irq-riscv-imsic-platform.c +1 -1
@@ -61,7 +61,7 @@ static int imsic_irq_retrigger(struct irq_data *d) local =per_cpu_ptr (imsic->global.local, vec->cpu);writel_relaxed (vec->local_id, local->msi_va); -return 0 ; +return 1 ; }static void imsic_irq_ack (struct irq_data *d)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1221/1257 irqchip/irq-msi-lib: Free wired MSI descriptors
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
[ Upstream commit 1c16bc2b1122f78f9d51c5785f7a78b36d44972b ]
msi_device_domain_alloc_wired() allocates a descriptor for each interrupt, but wired MSI domains do not set MSI_FLAG_FREE_MSI_DESCS. msi_device_domain_free_wired() releases the IRQ without freeing its descriptor, eventually exhausting the domain. Failed allocations also leave descriptors behind.
Set MSI_FLAG_FREE_MSI_DESCS for wired MSI domains so both paths release the descriptors.
--- drivers/irqchip/irq-msi-lib.c | 1 + 1 file changed, 1 insertion(+)
drivers/irqchip/irq-msi-lib.c +1 -0
@@ -75,6 +75,7 @@ bool msi_lib_init_dev_msi_info(struct device *dev, struct irq_domain *domain, info->flags =MSI_FLAG_ALLOC_SIMPLE_MSI_DESCS |MSI_FLAG_FREE_MSI_DESCS ; fallthrough;case DOMAIN_BUS_WIRED_TO_MSI : + info->flags |=MSI_FLAG_FREE_MSI_DESCS ;/* Remove PCI specific flags */ required_flags &= ~MSI_FLAG_PCI_MSI_MASK_PARENT ;break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1222/1257 Revert "net: advertise TCP MSS from the configured MTU, not the learned PMTU"
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yongjian Wang <[email protected]>
[ Upstream commit 564313447e545eea13038f74ada9272ab129b3cb ]
This reverts commit 2640e6419594 ("net: advertise TCP MSS from the configured MTU, not the learned PMTU").
That commit stopped the learned PMTU from lowering the MSS we advertise in SYN and SYN-ACK. For symmetric paths it argued that "the peer runs its own PMTU discovery and usually already knows the real path MTU". That only holds if ICMP "fragmentation needed" can reach the peer. When the peer sits behind a firewall that drops inbound ICMP, its PMTU discovery is a black hole (RFC 2923, section 2.1), and the smaller MSS we advertised was the only thing keeping its full-size segments off the narrow hop.
Inbound ICMP filtering is very common in enterprise and carrier networks, and it is pervasive in mainland China. We hit this in production after the commit was backported to 6.12.111: TCP connections that reach a server through a relay with a smaller-MTU hop complete the handshake, then stall as soon as the client sends full-size segments. Clients on networks that let ICMP through, and connections that bypass the relay, are unaffected, which made it hard to trace back to the kernel.
Reproducer, network namespaces on a single host:
cli --(1500)-- r1 --(1456)-- r2 --(1500)-- srv
r1 drops ICMP frag-needed towards cli. srv has already learned PMTU 1456 towards cli, then cli uploads 1 MB to srv:
kernel SYN-ACK MSS 1 MB upload 6.12.107 1416 OK 6.12.111 1460 stalls, times out 7.3-rc7 1460 stalls, times out 7.3-rc7 + this revert 1416 OK
The asymmetric case the commit was written for does not need a new
default: the advertised MSS can already be set per route with the advmss metric, which takes precedence over default_advmss(). With this revert applied, on an asymmetric path where srv learned PMTU 1456 towards cli while cli->srv is 1500 end to end:
srv route to cli SYN-ACK MSS largest cli->srv segment default 1416 1404 advmss 1460 1460 1448
So DSR-style setups can opt in with "ip route ... advmss <mss>", while hosts whose peers cannot complete PMTU discovery keep working by default.
--- include/net/ip.h | 25 ------------------------- include/net/ip6_route.h | 37 ------------------------------------- net/ipv4/route.c | 4 ++-- net/ipv6/route.c | 2 +- 4 files changed, 3 insertions(+), 65 deletions(-)
include/net/ip.h +0 -25
@@ -513,31 +513,6 @@ static inline unsigned int ip_dst_mtu_maybe_forward(const struct dst_entry *dst,return res; } -/* Configured/administrative MTU of a route, for advertising the TCP MSS. -* -* Unlike ip_dst_mtu_maybe_forward(), this deliberately ignores the -* ICMP-learned path MTU (rt->rt_pmtu). The advertised MSS bounds what the -* peer may send to us and must reflect our receive capability (the device or -* route-configured MTU), not a path MTU learned on the reverse (send) -* direction, which may not apply to the peer->us path and outlives the fnhe -* for the whole connection. See RFC 2923 section 2.3 and the comment above -* tcp_advertise_mss(). -*/ -static inline unsigned int ip_dst_mtu_configured (const struct dst_entry *dst) -{ -unsigned int mtu, res; - -rcu_read_lock (); - mtu =dst_metric_raw (dst,RTAX_MTU ); -if (!mtu) - mtu =READ_ONCE (dst_dev_rcu (dst)->mtu); - mtu = min_t(unsigned int, mtu, IP_MAX_MTU); - res = mtu -lwtunnel_headroom (dst->lwtstate, mtu); -rcu_read_unlock (); - -return res; -} -static inline unsigned int ip_skb_dst_mtu (struct sock *sk,const struct sk_buff *skb) {
include/net/ip6_route.h +0 -37
@@ -389,43 +389,6 @@ static inline unsigned int ip6_dst_mtu_maybe_forward(const struct dst_entry *dstreturn mtu -lwtunnel_headroom (dst->lwtstate, mtu); } -/* Configured/administrative MTU of a route, for advertising the TCP MSS. -* -* Unlike ip6_dst_mtu_maybe_forward(), this ignores any ICMPv6-learned path -* MTU (which is kept on the RTF_CACHE exception route) and returns the MTU of -* the underlying route (fib6_pmtu) or the egress device. The advertised MSS -* bounds what the peer may send to us and must reflect our receive -* capability, not a path MTU learned on the reverse (send) direction. See -* RFC 2923 section 2.3 and the comment above tcp_advertise_mss(). -*/ -static inline unsigned int ip6_dst_mtu_configured (const struct dst_entry *dst) -{ -const struct rt6_info *rt =dst_rt6_info (dst); -const struct fib6_info *from; -struct inet6_dev *idev; -unsigned int mtu =0 ; - -rcu_read_lock (); -/* IPv6 keeps the learned PMTU and the configured MTU in the same -* RTAX_MTU slot: the learned value sits on this (possibly RTF_CACHE) -* dst, the configured one on the underlying route. Reach the latter -* via ->from (fib6_pmtu), populated by ip6_route_info_create(). -*/ - from =rcu_dereference (rt->from); -if (from) - mtu = from->fib6_pmtu; -if (!mtu) { - mtu =IPV6_MIN_MTU ; - idev =__in6_dev_get (dst_dev_rcu (dst)); -if (idev) - mtu = max_t(unsigned int, mtu, READ_ONCE(idev->cnf.mtu6)); - } -rcu_read_unlock (); - - mtu = min_t(unsigned int, mtu, IP6_MAX_MTU); -return mtu -lwtunnel_headroom (dst->lwtstate, mtu); -} -u32 ip6_mtu_from_fib6 (const struct fib6_result *res,const struct in6_addr *daddr,const struct in6_addr *saddr);
net/ipv4/route.c +2 -2
@@ -1365,8 +1365,8 @@ static unsigned int ipv4_default_advmss(const struct dst_entry *dst)rcu_read_lock (); net =dst_dev_net_rcu (dst); - advmss = max_t(unsigned int, ip_dst_mtu_configured(dst) - header_size, - net->ipv4.ip_rt_min_advmss); + advmss = max_t(unsigned int, ipv4_mtu(dst) - header_size, + net->ipv4.ip_rt_min_advmss);rcu_read_unlock ();return min (advmss,IPV4_MAX_PMTU - header_size);
net/ipv6/route.c +1 -1
@@ -3267,7 +3267,7 @@ void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk)static unsigned int ip6_default_advmss (const struct dst_entry *dst) { -unsigned int mtu =ip6_dst_mtu_configured (dst); +unsigned int mtu =dst6_mtu (dst);struct net *net; mtu -=sizeof (struct ipv6hdr ) +sizeof (struct tcphdr );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 1223/1257 apparmor: fix NULL ctx->peer derefs in unix socket ctx updates
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Maxime Bélair <[email protected]>
[ Upstream commit 4de32fd05ce9e63b492899215ea929e7d306cdab ]
aa_unix_file_perm lazily refreshes the AppArmor context cached on a unix socket. Two of the helpers it uses assume ctx->peer has already been set:
update_peer_ctx -> l = aa_label_merge(old, label, GFP_ATOMIC);
update_sk_ctx -> } else if (aa_label_is_subset(plabel, old)) {where @old is ctx->peer. Neither aa_label_merge nor aa_label_is_subset allows NULL. So both fault on the aa_label->size load.
BUG: kernel NULL pointer dereference, address: 000000000000004c RIP: 0010:__aa_label_next_not_in_set+0xb/0xd0 Call Trace: aa_label_is_subset+0x3f/0x70 aa_unix_file_perm+0x5e8/0x9d0 aa_file_perm+0x45a/0x550 apparmor_file_permission+0x44/0xb0 security_file_permission+0x40/0x100 rw_verify_area+0x56/0x180 vfs_write+0x7c/0x480 ksys_write+0xbf/0xf0
ctx->peer is only recorded for stream connections and socket pairs. unix_dgram_connect sets unix_peer(sk) without going through that path, so a connected AF_UNIX datagram socket has unix_peer(sk) set while ctx->peer is still NULL, and the first write that needs revalidation reaches the helpers above.
Both derefs date back to the Fixes: commit, but the update_sk_ctx() one was dormant until commit 4483efe4f215 ("apparmor: fix shadowing of plabel that prevents cache from being updated") stopped @plabel being shadowed, which is why bisecting the oops lands there.
A NULL @old just means no peer label has been recorded yet, so install the label directly instead of merging or comparing against it.
--- security/apparmor/af_unix.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-)
security/apparmor/af_unix.c +12 -8
@@ -682,7 +682,7 @@ static void update_sk_ctx(struct sock *sk, struct aa_label *label,if (old == plabel) {rcu_assign_pointer (ctx->peer_lastupdate,aa_get_label (plabel)); - }else if (aa_label_is_subset (plabel, old)) { + }else if (!old ||aa_label_is_subset (plabel, old)) {rcu_assign_pointer (ctx->peer_lastupdate,aa_get_label (plabel));rcu_assign_pointer (ctx->peer,aa_get_label (plabel));
@@ -700,13 +700,17 @@ static void update_peer_ctx(struct sock *sk, struct aa_sk_ctx *ctx,spin_lock (&unix_sk (sk)->lock); old =rcu_dereference_protected (ctx->peer,lockdep_is_held (&unix_sk (sk)->lock)); - l =aa_label_merge (old, label,GFP_ATOMIC ); -if (l) { -if (l != old) { -rcu_assign_pointer (ctx->peer, l); -aa_put_label (old); - }else -aa_put_label (l); +if (!old) { +rcu_assign_pointer (ctx->peer,aa_get_label (label)); + }else { + l =aa_label_merge (old, label,GFP_ATOMIC ); +if (l) { +if (l != old) { +rcu_assign_pointer (ctx->peer, l); +aa_put_label (old); + }else +aa_put_label (l); + } }spin_unlock (&unix_sk (sk)->lock); }
Signature · 1 line
2.53.0