audit: fix potential integer overflow in audit_log_n_string()
audit_log_n_string() computes new_len as "slen + 3" (enclosing quotes
plus the NUL terminator) and stores it into an int, while slen is a
size_t. For a sufficiently large slen the addition can overflow and/or
the result be truncated when assigned to the int new_len, so the
"new_len > avail" check can be bypassed and the subsequent
memcpy(ptr, string, slen) can write past the skb tail.
This is the same class of bug that was fixed for the hex sibling in
commit 65dfde57d1e2 ("audit: fix potential integer overflow in
audit_log_n_hex()"); both helpers are reached through
audit_log_n_untrustedstring() with the same length source.
Make new_len a size_t and use check_add_overflow() to catch the
overflow, mirroring the audit_log_n_hex() fix. No functional change for
the in-tree callers, which all pass bounded lengths.
Cc: stable@vger.kernel.org Fixes: 168b7173959f ("AUDIT: Clean up logging of untrusted strings") Signed-off-by: Zhan Xusheng <zhanxusheng@xiaomi.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
tracing/filters: Fix false positive match in regex_match_full()
regex_match_full() calls strncmp(str, r->pattern, len) where len is the
target field buffer size. When len is smaller than r->len (the filter
pattern length), strncmp() checks only len bytes of r->pattern against
str. If those len bytes match, strncmp() returns 0, resulting in a
false-positive match where a shorter string in a fixed-size field
matches a longer filter pattern.
For example, a 4-byte static string field containing "abcd" matched the
filter pattern "abcdefgh" because strncmp("abcd", "abcdefgh", 4)
returned 0. In this case, @len does NOT include '\0' because it is
fixed-size array.
Fix this by returning 0 (no match) early when len < r->len.
tracing: Check return value of __register_event() in trace_module_add_events()
trace_module_add_events() ignores the return value of __register_event()
and unconditionally calls __add_event_to_tracers() for each event.
If __register_event() fails (for example, if event_init() fails), the
trace_event_call is not added to ftrace_events list, but
__add_event_to_tracers() still creates a trace_event_file pointing to it.
If module loading subsequently fails and module memory is freed, tracing
state retains a stale trace_event_call pointer in trace_event_file,
leading to a use-after-free when tracefs or tracing subsystem operations
are later executed.
Fix this by checking the return value of __register_event() and only
calling __add_event_to_tracers() if event registration succeeded.
Fixes: ae63b31e4d0e ("tracing: Separate out trace events from global variables") Cc: stable@vger.kernel.org Link: https://patch.msgid.link/178528487878.124250.14170824576025743236.stgit@devnote2 Assisted-by: Antigravity:gemini-3.5-flash Signed-off-by: Masami Hiramatsu (Google) <mhiramat@kernel.org> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
tracing/mmiotrace: Add NULL check for mmio_trace_array in logging functions
mmio_trace_rw() and mmio_trace_mapping() retrieve mmio_trace_array into
tr and pass it to __trace_mmiotrace_rw() and __trace_mmiotrace_map().
If these functions are invoked while mmio_trace_array is NULL (e.g. before
initialization or after disabled), accessing tr->array_buffer.buffer will
result in a NULL pointer dereference crash.
Fix this by adding an explicit NULL check for tr at the beginning of
__trace_mmiotrace_rw() and __trace_mmiotrace_map().
tracing/mmiotrace: Reset dropped_count in mmio_reset_data()
mmio_reset_data() is called during tracer initialization, reset, and
start. While it resets overrun_detected and prev_overruns, it neglects
to reset dropped_count. Consequently, dropped event counts from prior
tracing sessions persist in dropped_count and corrupt overrun reports
in subsequent runs.
Fix this by explicitly calling atomic_set(&dropped_count, 0) in
mmio_reset_data().
Link: https://patch.msgid.link/178524299122.56416.16277704230639425172.stgit@devnote2 Fixes: 173ed24ee2d6 ("mmiotrace: count events lost due to not recording") Assisted-by: Antigravity:gemini-3.6-flash Signed-off-by: Masami Hiramatsu (Google) <mhiramat@kernel.org> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
hwmon: (npcm750-pwm-fan): stop fan timer on device detach
When a fan tach channel is present, npcm7xx_pwm_fan_probe() starts
fan_timer. The timer callback polls tach state and rearms the timer, but
the driver has no remove callback or devm cleanup action to stop it. On
device detach, the devm-managed driver data and I/O mappings can be
released while the timer is still pending or running.
Register a devm cleanup action before starting the timer and shut the
timer down synchronously from that action.
iface_fw_to_cpu_addr() only checks that the firmware-provided MCU virtual
address points inside the shared section. The returned pointer is later
used as a full firmware interface structure, so accepting an address near
the end of the shared section can still lead to out-of-bounds accesses.
Pass the expected object size to iface_fw_to_cpu_addr() and reject ranges
that do not fit entirely in the shared section.
Fixes: 2718d91816ee ("drm/panthor: Add the FW logical block") Cc: stable@vger.kernel.org Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com> Reviewed-by: Steven Price <steven.price@arm.com> Signed-off-by: Steven Price <steven.price@arm.com> Link: https://patch.msgid.link/20260720114918.15973-1-osama.abdelkader@gmail.com
fprobe: Fix module reference count leak on error in register_fprobe()
In register_fprobe(), get_ips_from_filter() resolves target function
addresses and increments module reference counts via try_module_get() for
symbols in kernel modules. If get_ips_from_filter() fails on the second
pass and returns an error, register_fprobe() returned directly without
releasing module references acquired up to that point.
Fix this by ensuring the cleanup loop executing module_put() runs even when
get_ips_from_filter() returns a negative error.
drm/xe/pt: check no-DMA huge-pte cases before DMA segment test
On a non-range clear, curs.size is never set, so the segment test
(next - va_curs_start > curs->size) returns false for every level > 0
before the clear_pt short-circuit is reached. The clear then descends to
level 0 instead of forming a huge zero-leaf, wasting page tables and
risking -ENOMEM on unbind.
Move the null-VMA, purged-BO and clear_pt short-circuits above the
curs->size test. The bind path always sets curs.size, so it is unaffected.
v2
- Also set curs.size on the clear path so the cursor stays meaningful
during the walk. clear_pt is only reached with range == NULL, so assert
that invariant. (Matthew Brost)
Cc: Matthew Brost <matthew.brost@intel.com> Fixes: 5b658b7e89c3 ("drm/xe: Clear scratch page on vm_bind") Reported-by: Sashiko <sashiko-bot@kernel.org> Reviewed-by: Matthew Brost <matthew.brost@intel.com> Link: https://patch.msgid.link/20260728055916.593707-2-himal.prasad.ghimiray@intel.com Signed-off-by: Himal Prasad Ghimiray <himal.prasad.ghimiray@intel.com>
(cherry picked from commit 04eeeb45cb61b8a3e9d785003457e550c920ba49) Signed-off-by: Rodrigo Vivi <rodrigo.vivi@intel.com>
drm/imagination: Update the trace point pvr_job_submit_fw()
Trace point pvr_job_submit_fw() is used to trace job submission to
the FW. Currently it is recorded when a command is written to the Client
circular buffer.
Move trace recording after writing command to the Kernel circular buffer to
better represent command submission to the FW.
Fixes: c1079aebb4de ("drm/imagination: Add support for trace points") Signed-off-by: Brajesh Gupta <brajesh.gupta@imgtec.com> Reviewed-by: Alessio Belle <alessio.belle@imgtec.com> Link: https://patch.msgid.link/20260724-b4-tracepoint-fix-v3-1-8f8e5e8179d3@imgtec.com Signed-off-by: Alessio Belle <alessio.belle@imgtec.com>
Alexander Kaplan [Sat, 18 Jul 2026 10:52:07 +0000 (12:52 +0200)]
drm/i915/dp: Ignore the sink's DSC max FRL rate without a PCON DSC encoder
intel_dp_hdmi_sink_max_frl() limits the sink's max FRL rate by its
DSC max FRL rate whenever the sink supports DSC 1.2.
However, the DSC max FRL rate (HF-VSDB DSC_Max_FRL_Rate) only applies
to compressed video transport, which requires a DSC 1.2 encoder in
the PCON (configured via intel_dp_pcon_dsc_configure()).
Without such an encoder the HDMI link always carries uncompressed
video, for which the regular Max_FRL_Rate is the correct limit.
Applying the DSC limit unconditionally trains the FRL link at a lower
rate than both the PCON and the sink support.
E.g. an LG OLED G4 (Max_FRL_Rate 48 Gbps, DSC_Max_FRL_Rate 24 Gbps)
behind a Synaptics VMM7100 PCON (PCON max FRL bw 48 Gbps, no DSC
encoder):
Sink max rate from EDID = 24 Gbps
FRL trained with : 24 Gbps
while Windows/macOS train the same hardware at 40/48 Gbps.
The too low FRL rate needlessly constrains the formats available to
the sink.
Only apply the sink's DSC max FRL rate if the PCON has a DSC 1.2
encoder, matching the gate in intel_dp_pcon_dsc_configure().
PCONs with a DSC encoder keep the current conservative behavior,
since the link is trained once and compressed transport may be used
for any subsequent mode.
With this the setup above trains at 48 Gbps.
Tested on PTL (xe) with the above PCON/sink combo.
Fixes: 10fec80b48c5 ("drm/i915/display: Configure PCON for DSC1.1 to DSC1.2 encoding") Cc: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Cc: Ville Syrjälä <ville.syrjala@linux.intel.com> Reviewed-by: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Signed-off-by: Alexander Kaplan <alexander.kaplan@sms-medipool.de> Signed-off-by: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Link: https://patch.msgid.link/20260718105207.5565-3-alexander.kaplan@sms-medipool.de
(cherry picked from commit 71b57dd92f94569dca4bdf883fbd8ca5d4ed4bae) Signed-off-by: Rodrigo Vivi <rodrigo.vivi@intel.com>
The OVL adaptor registers both an aggregate driver for its child devices
and a component for the main DRM aggregate. Probe currently ignores an
error from registering the child aggregate and leaves that aggregate
registered if registering the DRM component fails. The remove callback
also leaves the DRM component registered.
These imbalances can leave component framework entries referring to a
device whose probe failed or whose driver has been detached. The aggregate
unbind callback also fails to undo component_bind_all(), leaving its child
components marked as bound when the aggregate is removed.
Check the aggregate registration result, unwind it when the component
registration fails, and unregister the component before the aggregate on
remove. Keep runtime PM enabled until both framework registrations have
been removed, and unbind all child components from the aggregate unbind
callback.
Fixes: 453c3364632a ("drm/mediatek: Add ovl_adaptor support for MT8195") Cc: stable@vger.kernel.org # 6.4+ Co-developed-by: Ijae Kim <ae878000@gmail.com> Signed-off-by: Ijae Kim <ae878000@gmail.com> Signed-off-by: Myeonghun Pak <mhun512@gmail.com> Reviewed-by: CK Hu <ck.hu@mediatek.com> Link: https://patchwork.kernel.org/project/linux-mediatek/patch/20260721152242.47138-1-mhun512@gmail.com/ Signed-off-by: Chun-Kuang Hu <chunkuang.hu@kernel.org>
drm/mediatek: mtk_dsi: Enable HS clock only at pre-enable
Commit 76255024cadb ("drm/mediatek: mtk_dsi: enable hs clock
during pre-enable") rightfully moves the HS clock enablement to
before atomic_enable(), but it's moving it to mtk_dsi_poweron(),
which is not only called in the .atomic_pre_enable() callback
for the DRM bridge, but also in the MediaTek DRM's .ddp_start()
callback, which happens way before the bridge ones.
The HS clock enablement should be done at just the right time,
otherwise some bridge chips (or some Display Driver ICs) may
not work correctly: this is seen at least with a Parade DSI to
eDP bridge (PS8640) on the MT8173 Elm Chromebook.
This resolves a regression that was seen on the aforementioned
machine, which was happening only after a suspend-resume cycle.
Alexander Kaplan [Wed, 10 Jun 2026 19:38:25 +0000 (21:38 +0200)]
drm/dp: Read the PCON max FRL bandwidth only for HDMI DFPs
The PCON max FRL bandwidth field lives in byte 2 of the DFP Detailed
Capability Info (DPCD 0x82 for the first DFP).
The DP standard defines the meaning of descriptor bytes 1-3 strictly
per DFP type, and for a DisplayPort type DFP all of them are
reserved, with "read all 0s" semantics (DP v2.0, section 2.12.3,
Table 2-183).
The FRL bandwidth field is an HDMI DFP extension added by the VESA
DP-to-HDMI PCON specification.
drm_dp_get_pcon_max_frl_bw() however parses the byte without checking
the DFP type, the branch presence or DETAILED_CAP_INFO_AVAILABLE.
Without the latter the port descriptors are one byte wide and
port_cap[2] is not even the right register.
All neighbouring helpers parsing the same descriptor are scoped by
the DFP type already, see for instance drm_dp_downstream_max_bpc()
reading the same byte and returning 0 for a DP type DFP.
amdgpu's DC parses the field only for HDMI(/DP++) detailed types as
well.
This is not theoretical.
A Synaptics VMM7100 based USB-C to HDMI adapter with a macOS targeted
firmware advertises a DisplayPort type DFP with the type byte
replicated across the whole descriptor (08 08 08 08).
i915 decodes that as "PCON limited to 18 Gbps FRL" and prunes every
mode above ~750 MHz dotclock, including all the 4k@100/120 modes the
sink EDID offers, while macOS drives 4k@120 through the same adapter
just fine via DP DSC (and amdgpu's type-scoped parser would ignore
the bogus field as well).
Only parse the field for an HDMI DFP behind a DPCD 1.1+ branch
device that reports detailed cap info, matching the type-scoped
field layout of the spec and the rest of the helpers.
Fixes: ce32a6239de6 ("drm/dp_helper: Add Helpers for FRL Link Training support for DP-HDMI2.1 PCON") Cc: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Cc: Uma Shankar <uma.shankar@intel.com> (v2) Cc: Jani Nikula <jani.nikula@intel.com> Cc: Maarten Lankhorst <maarten.lankhorst@linux.intel.com> Cc: dri-devel@lists.freedesktop.org Cc: <stable@vger.kernel.org> # v5.12+ Signed-off-by: Alexander Kaplan <alexander.kaplan@sms-medipool.de> Reviewed-by: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Signed-off-by: Ankit Nautiyal <ankit.k.nautiyal@intel.com> Link: https://patch.msgid.link/20260610193825.2933-1-alexander.kaplan@sms-medipool.de
Chao Shi [Mon, 27 Jul 2026 20:12:57 +0000 (16:12 -0400)]
block: stop the timeout timer when releasing a never added disk
disk_release() undoes blk_mq_init_allocated_queue() for a disk whose
probe failed before add_disk(), but it only calls blk_mq_exit_queue().
Nothing there stops q->timeout, and that timer rolls forward: it stays
pending until it next expires, not until the last request completes.
So if the driver issued any I/O before adding the disk, the
request_queue is freed while still linked into a timer wheel bucket.
Commit 6f8191fdf41d ("block: simplify disk shutdown") dropped the
blk_cleanup_queue() call that used to stop it. __del_gendisk() and
blk_mq_destroy_queue() still do; only the probe failure path lost it.
nvme gets there because nvme_update_ns_info() submits Report Zones or
FDP io-mgmt-recv on ns->queue before the disk is added, so a later
failure - a concurrent reset setting NVME_CTRL_FROZEN, or
device_add_disk() failing - lands in put_disk() with the timer armed:
BUG: KASAN: slab-use-after-free in detach_if_pending+0x30c/0x340
Write of size 8 at addr ffff888004d71310 by task kworker/u8:2/37
__timer_delete_sync+0x156/0x240 kernel/time/timer.c:1621
blk_sync_queue+0x22/0x40 block/blk-core.c:222
nvme_sync_queues+0x100/0x150 drivers/nvme/host/core.c:5362
nvme_reset_work+0x138/0x930 drivers/nvme/host/pci.c:3264
Allocated by task 34:
__blk_mq_alloc_disk+0x33/0x100 block/blk-mq.c:4462
nvme_alloc_ns+0x290/0x3870 drivers/nvme/host/core.c:4146
Freed by task 0:
blk_free_queue_rcu+0x3a/0x50 block/blk-core.c:254
rcu_core+0xc10/0x1730 kernel/rcu/tree.c:2857
The queue being synced there is ctrl->admin_q, only a victim sharing a
timer wheel bucket with the freed queue's dangling entry; other runs
tripped in enqueue_timer(), __run_timers() or blk_mq_timeout_work().
Failing nvme_alloc_ns() with a debug patch makes it deterministic: one
leaked timer trips KASAN within seconds, while 1987 patched releases
produced no splat.
Stop the timer and the queue work items before blk_mq_exit_queue(), like
blk_mq_destroy_queue() does.
Found by FuzzNvme.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown") Acked-by: Weidong Zhu <weizhu@fiu.edu> Signed-off-by: Chao Shi <coshi036@gmail.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Link: https://patch.msgid.link/20260727201257.211635-1-coshi036@gmail.com Signed-off-by: Jens Axboe <axboe@kernel.dk>
ems_usb_read_bulk_callback() walks CPC messages packed in one USB
receive buffer.
Check that each declared message fits in the URB payload. Also require the
type-specific payload to cover the fields used by the CAN, state, error and
overrun handlers.
Signed-off-by: Pengpeng Hou <pengpeng@iscas.ac.cn> Link: https://patch.msgid.link/20260706092752.79600-1-pengpeng@iscas.ac.cn Fixes: 702171adeed3 ("ems_usb: Added support for EMS CPC-USB/ARM7 CAN/USB interface") Cc: stable@vger.kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
es58x_read_bulk_callback() resubmits the RX URB after processing a received
packet. If the resubmit succeeds, the URB remains anchored and will be
handled by the normal RX path or by teardown.
However, if usb_submit_urb() fails, the callback unanchors the URB and then
returns directly. This skips the existing free_urb path, so the coherent
transfer buffer allocated with usb_alloc_coherent() is not released.
Reuse the existing free_urb path after a resubmit failure so that the RX
coherent buffer is freed before leaving the callback.
Fixes: 5eaad4f76826 ("can: usb: etas_es58x: correctly anchor the urb in the read bulk callback") Signed-off-by: Guangshuo Li <lgs201920130244@gmail.com> Reviewed-by: Vincent Mailhol <mailhol@kernel.org> Link: https://patch.msgid.link/20260706014601.415445-1-lgs201920130244@gmail.com Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
can: gs_usb: gs_usb_receive_bulk_callback(): resubmit URB on skb allocation failure
If the allocation of the SKB in gs_usb_receive_bulk_callback() fails, the
driver returns from the callback without resubmitting the URB in order to
receive further USB in URBs.
This results in a silent performance degradation which, if it occurs
repeatedly, results in starvation of USB in traffic.
Instead of returning immediately, try to resend the URB. If this also
fails, this is logged as an info message.
can: c_can: c_can_chip_config(): keep controller in init mode until bittiming is configured
c_can_chip_config() was programming C_CAN_CTRL_REG without CONTROL_INIT,
which may allow the controller to become active before
c_can_set_bittiming() finishes.
That creates a short timing window where the peripheral can interact with
the bus using a different/default bitrate, potentially generating bus
errors and corrupting traffic.
Set CONTROL_INIT together with the control-mode writes in
c_can_chip_config() (normal, loopback and listen-only paths), so the
controller stays halted until bit timing is fully programmed.
This prevents transient bus disturbance during startup when the configured
bitrate differs from the active bus bitrate.
Signed-off-by: Lucas Martins Alves <lucas.alves@lumal21.com.br> Link: https://patch.msgid.link/20260714164839.771123-1-lucas.alves@lumal21.com.br Fixes: 881ff67ad450 ("can: c_can: Added support for Bosch C_CAN controller") Cc: stable@kernel.org
[mkl: remove space before close parenthesis] Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
can: softing: fw_parse(): validate firmware record spans
fw_parse() reads a fixed record header, a firmware-provided payload,
and a trailing checksum without knowing the end of the firmware blob. A
truncated record can therefore make those reads exceed the blob.
The same record also supplies addresses and lengths for writes into
DPRAM. The generic loader uses wrap-prone mixed signed arithmetic for its
bounds check, while the application loader does not bound the staging
copy at all.
Pass the firmware end to the parser and validate the full source record.
Use a signed wide offset for generic DPRAM records and validate the
application staging span against the mapped DPRAM before copying.
Tu Nguyen [Thu, 25 Jun 2026 13:51:51 +0000 (14:51 +0100)]
can: rcar_canfd: change the initializing flow for clocks and resets
Testing CANFD on RZ/G3E shows that many registers do not reset to their
initial values with the current flow of deasserting resets first and then
enabling clocks.
Based on the HW manual, clocks should be supplied first and the
resets deasserted afterward.
section 7.4.3 Procedure for Activating Modules: RZ/G2L
section 4.4.9.3 Procedure for Starting up Units: RZ/G3E
So, update the order of the initializing flow for resets and clocks
to match the hardware manual, resetting all CANFD registers to their
initial values. Also update rcar_canfd_global_deinit() to assert
resets before disabling clocks, so the teardown path mirrors the new
init ordering.
Fixes: 76e9353a80e9 ("can: rcar_canfd: Add support for RZ/G2L family") Signed-off-by: Tu Nguyen <tu.nguyen.xg@renesas.com> Signed-off-by: Biju Das <biju.das.jz@bp.renesas.com> Tested-by: Claudiu Beznea <claudiu.beznea.uj@bp.renesas.com> Reviewed-by: Geert Uytterhoeven <geert+renesas@glider.be> Reviewed-by: Vincent Mailhol <mailhol@kernel.org> Link: https://patch.msgid.link/20260625135216.130450-1-biju.das.jz@bp.renesas.com Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
can: kvaser_usb_leaf: kvaser_usb_leaf_wait_cmd(): validate received command extents
The wait and bulk receive paths walk variable-length commands from a
USB buffer. A nonzero command shorter than CMD_HEADER_LEN can still be
dispatched, and the wait path copies a matching command into a fixed
caller-owned struct kvaser_cmd using the device-provided length.
Reject nonzero commands that do not contain the fixed header or that
extend beyond the current USB buffer item. In the wait path, also reject
a matching command that exceeds the destination before copying it.
Fixes: 080f40a6fa28 ("can: kvaser_usb: Add support for Kvaser CAN/USB devices") Signed-off-by: Pengpeng Hou <pengpeng@iscas.ac.cn> Link: https://patch.msgid.link/20260722042221.44066-1-pengpeng@iscas.ac.cn Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
can: kvaser_usb: kvaser_usb_hydra_get_busparams(): fix memory leak in kvaser_usb_hydra_get_busparams()
The memory allocated for cmd is not freed after the call to
kvaser_usb_send_cmd() in both the normal and error paths.
Fix that by adding a kfree() immediately after the call.
Fixes: 39d3df6b0ea8 ("can: kvaser_usb: Compare requested bittiming parameters with actual parameters in do_set_{,data}_bittiming") Cc: stable@vger.kernel.org Signed-off-by: Abdun Nihaal <nihaal@cse.iitm.ac.in> Link: https://patch.msgid.link/20260722103906.108571-1-nihaal@cse.iitm.ac.in Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
can: peak_usb: validate uCAN receive record lengths
pcan_usb_fd_decode_buf() walks uCAN records packed in one USB
receive buffer.
Require each record to contain the fixed header for its type, and verify
CAN payload bytes before copying them into the skb.
Signed-off-by: Pengpeng Hou <pengpeng@iscas.ac.cn> Link: https://patch.msgid.link/20260706092836.79754-1-pengpeng@iscas.ac.cn Fixes: 0a25e1f4f185 ("can: peak_usb: add support for PEAK new CANFD USB adapters") Cc: stable@vger.kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Maoyi Xie [Tue, 16 Jun 2026 18:15:31 +0000 (02:15 +0800)]
can: peak_usb: peak_usb_start(): fix double free of transfer buffer on URB submit error
In peak_usb_start(), each RX URB transfer buffer is allocated with kmalloc()
and the URB is flagged URB_FREE_BUFFER so that the final usb_free_urb() also
frees the transfer buffer.
If usb_submit_urb() fails, the error path frees the buffer explicitly with
kfree(buf) and then calls usb_free_urb(urb). Because URB_FREE_BUFFER is set,
usb_free_urb() -> urb_destroy() frees the same buffer a second time, a double
free of the transfer buffer.
BUG: KASAN: double-free in usb_free_urb.part.0+0x91/0xb0
Free of addr ffff8881069ccb80 by task trigger.sh/285
Drop the redundant kfree(buf); usb_free_urb() already releases the transfer
buffer. This mirrors commit 03819abbeb11 ("net: usb: lan78xx: Fix double free
issue with interrupt buffer allocation").
Fixes: bb4785551f64 ("can: usb: PEAK-System Technik USB adapters driver core") Closes: https://lore.kernel.org/linux-can/178159320216.2154888.16953451793788581739@maoyixie.com/T/#u Cc: stable@vger.kernel.org Signed-off-by: Maoyi Xie <maoyixie.tju@gmail.com> Reviewed-by: Vincent Mailhol <mailhol@kernel.org> Link: https://patch.msgid.link/178163373110.2507866.216458825145756798@maoyixie.com Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
James Gao [Wed, 20 May 2026 05:40:03 +0000 (13:40 +0800)]
can: peak_usb: add bounds check for USB channel index
The channel control index ctrl_idx is derived from rx->len which comes
directly from a device USB payload. The mask 0x0f allows values 0-15, but
the array size of usb_if->dev[] is only 2. Values 2-15 cause heap
out-of-bounds read, eventually causing kernel panic in the IRQ context.
Add bounds checking for ctrl_idx before the array access in both
pcan_usb_pro_handle_canmsg() and pcan_usb_pro_handle_error().
The driver has a match table for the pci bus wired into its driver
structure, but the table is not exported with MODULE_DEVICE_TABLE().
Add the missing MODULE_DEVICE_TABLE() entry so module alias information
is generated for automatic module loading.
This is a source-level fix. It does not claim dynamic hardware
reproduction; the evidence is the driver-owned match table, its use by
the driver registration structure, and the missing module alias
publication.
Signed-off-by: Pengpeng Hou <pengpeng@iscas.ac.cn> Acked-by: Pavel Pisa <pisa@fel.cvut.cz> Link: https://patch.msgid.link/20260704151957.48194-1-pengpeng@iscas.ac.cn Fixes: 792a5b678e81 ("can: ctucanfd: CTU CAN FD open-source IP core - PCI bus support.") Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Avi Weiss [Wed, 22 Jul 2026 19:27:26 +0000 (22:27 +0300)]
can: ctucanfd: use self-test mode for PRESUME_ACK
Use self-test mode for CAN_CTRLMODE_PRESUME_ACK so transmitted
frames can complete without receiving an ACK.
ACK forbidden mode prevents the controller from acknowledging
received frames and does not implement the presume-ack behavior.
Fixes: 2dcb8e8782d8 ("can: ctucanfd: add support for CTU CAN FD open-source IP core - bus independent part.") Signed-off-by: Avi Weiss <thnkslprpt@gmail.com> Acked-by: Pavel Pisa <pisa@fel.cvut.cz> Link: https://patch.msgid.link/20260722192726.230729-1-thnkslprpt@gmail.com Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Avi Weiss [Thu, 23 Jul 2026 07:44:03 +0000 (10:44 +0300)]
can: ctucanfd: handle bus error interrupts
Include REG_INT_STAT_BEI in the top-level error interrupt condition.
BEI is enabled when CAN_CTRLMODE_BERR_REPORTING is requested and
ctucan_err_interrupt() already handles it. Without checking and
clearing BEI in the top-level handler, bus error interrupts are not
handled or acknowledged.
Fixes: 2dcb8e8782d8 ("can: ctucanfd: add support for CTU CAN FD open-source IP core - bus independent part.") Signed-off-by: Avi Weiss <thnkslprpt@gmail.com> Acked-by: Pavel Pisa <pisa@fel.cvut.cz> Link: https://patch.msgid.link/20260723074403.131575-1-thnkslprpt@gmail.com Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Avi Weiss [Thu, 23 Jul 2026 09:59:34 +0000 (12:59 +0300)]
can: ctucanfd: unmap BAR0 using base address
BAR0 is mapped into bar0_base, while cra_addr points to an offset
within that mapping and is used for other purposes.
Pass bar0_base to pci_iounmap(), instead of cra_addr, on the probe error
path so the address returned by pci_iomap() is used for unmapping.
Fixes: 792a5b678e81 ("can: ctucanfd: CTU CAN FD open-source IP core - PCI bus support.") Signed-off-by: Avi Weiss <thnkslprpt@gmail.com> Acked-by: Pavel Pisa <pisa@fel.cvut.cz> Link: https://patch.msgid.link/20260723095934.181042-1-thnkslprpt@gmail.com Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Minhong He [Wed, 29 Jul 2026 08:56:56 +0000 (16:56 +0800)]
can: isotp: check register_netdevice_notifier() error in module init
Register the netdevice notifier before can_proto_register() and check the
return value. If protocol registration fails, unregister the notifier
before returning the error.
Align isotp_module_init() with the reordering already done for raw.c
(commit c28b3bffe49e ("can: raw: process optimization in raw_init()")) and
bcm.c (commit edd1a7e42f1d ("can: bcm: registration process optimization
in bcm_module_init()")).
net: sxgbe: check descriptor ring allocation failures
sxgbe_open() ignores the return value of init_dma_desc_rings() and
continues to program DMA with invalid ring addresses when allocation
fails. Check the return value and disconnect the PHY on failure.
Fixes: 1edb9ca69e8a ("net: sxgbe: add basic framework for Samsung 10Gb ethernet driver") Signed-off-by: Chenguang Zhao <zhaochenguang@kylinos.cn> Reviewed-by: Vadim Fedorenko <vadim.fedorenko@linux.dev> Signed-off-by: David S. Miller <davem@davemloft.net>
net: sxgbe: free TX rings on RX allocation failure
When RX descriptor ring allocation fails, init_dma_desc_rings() only
frees the partially allocated RX rings and returns. The TX rings that
were allocated earlier in the same function are leaked.
Rearrange error labels to clean up TX rings upon RX failures.
Fixes: 1edb9ca69e8a ("net: sxgbe: add basic framework for Samsung 10Gb ethernet driver") Signed-off-by: Chenguang Zhao <zhaochenguang@kylinos.cn> Reviewed-by: Vadim Fedorenko <vadim.fedorenko@linux.dev> Signed-off-by: David S. Miller <davem@davemloft.net>
This patch is a follow-up to commit cf070fe33bfb ("can: isotp: serialize
TX state transitions under so->rx_lock") which addresses following
sashiko-bot findings:
- isotp_sendmsg(): drain so->txfrtimer first so a stale callback can't
re-arm echotimer after the claim
- isotp_release(): wake so->wait after forcing ISOTP_SHUTDOWN so a
sleeping sendmsg() claim isn't stranded
- isotp_sendmsg(): have both wait_event_interruptible() calls in
isotp_sendmsg() also wake on ISOTP_SHUTDOWN and do not return claim to
IDLE to avoid corrupting a concurrent isotp_release() process.
- isotp_sendmsg(): handle potential claim of a new transfer when
the wait_event_interruptible() call returns in CAN_ISOTP_WAIT_TX_DONE
mode. Don't touch timers and states of the new transfer if a new thread
incremented so->tx_gen before getting the lock at err_event_drop.
- isotp_sendmsg(): handle a stuck can_send() and omit timer and state
changes if a new transfer was claimed. wait_tx_done() returns the error
recorded in so->tx_result[], tagged with the caller's own generation.
- isotp_tx_timeout(): on a claimed timeout, record the ECOMM error for
the timed-out transfer's own generation in so->tx_result[]; sk->sk_err
is raised unconditionally, same as every other error path here.
- isotp_tx_gen_done()/isotp_tx_timeout(): always read tx.state (acquire)
before tx_gen - the reverse order let a weakly ordered CPU pair a fresh
tx.state with a stale tx_gen/tx_result slot.
- isotp_sendmsg(): wait_tx_done: drain sk_err via sock_error() once we
have read the result from so->tx_result[], so an already-reported error
doesn't stay latched for a later poll()/SO_ERROR.
Also align the remaining lock-free so->tx.state/rx.state/cfecho accesses
and use skb->hash as unique loopback echo frame indicator.
Fixes: cf070fe33bfb ("can: isotp: serialize TX state transitions under so->rx_lock") Signed-off-by: Oliver Hartkopp <socketcan@hartkopp.net> Link: https://patch.msgid.link/20260724181525.43556-1-socketcan@hartkopp.net Cc: stable@kernel.org Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
Merge patch series "can: j1939: resend lost patches for buffer init and netdevice tracking"
Oleksij Rempel <o.rempel@pengutronix.de> says:
This series collects and resends two j1939 patches that were previously
lost on their way upstream. They address different, unconnected issues in
the stack:
- Patch 1 prevents residual data leaks by zeroing the allocated receive
buffer in j1939_session_fresh_new().
- Patch 2 implements netdevice_tracker for j1939_{priv,session,ecu}
management to help investigate a dev_hold()/dev_put() refcount
leak (unregister_netdevice() waiting for vcan0) reported by syzbot.
Zero the allocated buffer in j1939_session_fresh_new() to ensure it
contains no residual data.
While there is a potential performance impact if users allocate maximum
sized ETP buffers, most real-world use cases are not noticeably affected
since the maximum known buffer size is typically around 65K.
Fixes: 9d71dd0c7009 ("can: add support of SAE J1939 protocol") Reported-by: Ji'an Zhou <eilaimemedsnaimel@gmail.com>
Message-ID: <CAPAUci5dykCLjoijqkUtFqJFesgncrD7+S6y_V=gjbFkY2Tifg@mail.gmail.com> Signed-off-by: Oleksij Rempel <o.rempel@pengutronix.de> Link: https://patch.msgid.link/20260728055835.1151785-3-o.rempel@pengutronix.de Cc: stable@kernel.org
[mkl: add Message-ID] Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>
This refcount leak in j1939_priv might be caused by a refcount leak in
j1939_{session,ecu} because j1939_{session,ecu} holds a ref on j1939_priv.
For further investigation using upstream kernels, enable netdevice_tracker
in j1939_{priv,session,ecu} management.
André Pragosa [Tue, 28 Jul 2026 22:11:25 +0000 (23:11 +0100)]
ALSA: hda/realtek: Add mute LED quirk for HP Victus 16-e0xxx (MB 88ED)
Add subsystem ID 103c:88ed to the existing HP Victus 16-e0xxx
mute LED quirk list.
The HP Victus 16-e0xxx with subsystem ID 103c:88ed uses the same
mute LED coefficient configuration as the already supported
103c:88eb variant.
The mute LED was verified by manually toggling coefficient index
0x0b (bit 3) using hda-verb. After adding the quirk, the LED is
registered as hda::mute and follows the audio mute state.
ALSA: usb-audio: Add GET_SAMPLE_RATE quirk for C-Media CM6206
The C-Media CM6206 (0d8c:0102) truncates the three-byte sample rate it
returns for UAC_GET_CUR to its two low bytes. After the rate has been
set to 96000 (0x017700) the device reports back 30464 (0x007700).
At probe time the driver initializes every altsetting to its maximum
rate, so altsetting 5 is set to 96000 and the warning appears on each
plug-in, before anything has opened the device:
usb 3-1.3: 1:5 Set sample rate 96000, clock 0
usb 3-1.3: current rate 30464 is different from the runtime rate 96000
That altsetting is the one parse_audio_format_rates_v1() already fixes
up for this chip, so this affects every CM6206.
Only the read-back is broken, the rate itself is applied: a 1 kHz sine
rendered at 96 kHz is recovered at 1000.2 Hz, and a silent fallback to
48000 would have been reported as 0x00bb80 rather than as the low half
of the requested rate.
Add a QUIRK_FLAG_GET_SAMPLE_RATE entry for the device so the read-back
is skipped. Setting the same flag through the quirk_flags module
parameter makes the warning disappear while the 96000 init still
happens.
ALSA: usb-audio: Clamp frame size in implicit-feedback mode
snd_usb_handle_sync_urb() scales received sync packet sizes by the sender's
stride and stores the result directly in out_packet->packet_size[i]. If a
connected USB device sends an oversized sync packet, this frame count can
exceed ep->maxframesize.
The un-clamped frame count then propagates to the playback endpoint queue,
potentially driving packet transfers beyond the endpoint's hardware frame
limits.
Cap the calculated frame count against ep->maxframesize in
snd_usb_handle_sync_urb() to prevent oversized packets from entering the
playback queue.
ALSA: usb-audio: Fix DMA buffer out-of-bounds write when fill_max is set
When a USB audio endpoint requests full packet transfers via the fill_max
descriptor flag, data_ep_set_params() promotes ep->curpacksize to
ep->maxpacksize. However, maxsize is left at the original sample-rate
derived value.
Since u->buffer_size is allocated as maxsize * packets, the resulting
DMA buffer is far too small for the requested transfer length. When the
USB host controller streams up to curpacksize bytes per packet, it writes
past the end of the buffer via DMA, corrupting kernel heap memory.
Update maxsize to curpacksize when fill_max is set so that the allocated
DMA buffer size matches the actual transfer request size.
[ changed to reassign maxsize only when ep->fill_max is set -- tiwai ]
octeontx2-af: Block VFs from clobbering special CGX PKIND state
PF and VF NIX LFs that share a CGX LMAC reuse the same hardware PKIND
programming. When HiGig2 or EDSA parsing is enabled, a VF NIX LF alloc must
not reset the LMAC RX PKIND or default TX parse config over the PF setup.
Add cgx_get_pkind() and rvu_cgx_is_pkind_config_permitted() so VFs skip
cgx_set_pkind(), rvu_npc_set_pkind(), and NIX_AF_LFX_TX_PARSE_CFG updates
when the LMAC is using NPC_RX_HIGIG_PKIND or NPC_RX_EDSA_PKIND.
Damien Le Moal [Thu, 9 Jul 2026 07:02:23 +0000 (16:02 +0900)]
scsi: libsas: terminate deferred commands on time out
If a command times out while we have deferred non-NCQ commands waiting to
be issued, the SCSI EH task is not immediately woken up as the waiting
deferred commands are never issued nor completed, thus leaving the SCSI
host in a busy state (shost->host_failed != scsi_host_busy(shost)) which
prevents the SCSI EH task from being woken up. Eventually, when the
deferred commands also time out, the SCSI EH task is woken up and the
timeout processing occurs.
Avoid this unnecessary additional SCSI EH wake up time with the same
method as implemented in libata-scsi, using the eh_timed_out SCSI host
template operation. The function sas_eh_timed_out() implements this
operation and executes the function ata_scsi_retry_deferred_qc()
for SATA devices.
Co-developed-by: Igor Pylypiv <ipylypiv@google.com> Signed-off-by: Igor Pylypiv <ipylypiv@google.com> Fixes: 0ea84089dbf6 ("ata: libata-scsi: avoid Non-NCQ command starvation") Cc: stable@vger.kernel.org Signed-off-by: Damien Le Moal <dlemoal@kernel.org> Reviewed-by: John Garry <john.g.garry@oracle.com> Reviewed-by: Hannes Reinecke <hare@kernel.org> Tested-by: Igor Pylypiv <ipylypiv@google.com> Reviewed-by: Niklas Cassel <cassel@kernel.org> Reviewed-by: Martin K. Petersen <martin.petersen@oracle.com>
Damien Le Moal [Wed, 22 Jul 2026 22:42:26 +0000 (07:42 +0900)]
ata: libata-scsi: schedule deferred atapi command
Modify atapi_qc_complete() to call ata_scsi_schedule_deferred_qc() to
ensure that any deferred queued command can execute. This is similar to
ata_scsi_qc_complete() function for regular ATA devices.
Fixes: 0ea84089dbf6 ("ata: libata-scsi: avoid Non-NCQ command starvation") Cc: stable@vger.kernel.org Signed-off-by: Damien Le Moal <dlemoal@kernel.org>
Damien Le Moal [Thu, 9 Jul 2026 01:01:33 +0000 (10:01 +0900)]
ata: libata-scsi: terminate deferred commands on time out
If a command times out while we have deferred non-NCQ commands waiting to
be issued, the SCSI EH task is not immediately woken up as the waiting
deferred commands are never issued nor completed, thus leaving the SCSI
host in a busy state (shost->host_failed != scsi_host_busy(shost)) which
prevents the SCSI EH task from being woken up. Eventually, when the
deferred commands also time out, the SCSI EH task is woken up and the
timeout processing occurs.
Avoid this unnecessary SCSI EH task wake-up additional time by scheduling
a retry of all waiting deferred QCs, using the eh_timed_out SCSI host
template operation. The function ata_scsi_eh_timed_out() is introduced to
implement this operation.
However, terminating deferred commands with DID_REQUEUE to force a retry
by calling the function ata_scsi_requeue_deferred_qc() may still keep the
SCSI host in a busy state because the block layer may immediately re-issue
these commands. The solution to this is to schedule libata EH for the
port which suffered the command timeout to prevent accepting any new
command. ata_scsi_requeue_deferred_qc() is modified to add a call to
ata_port_schedule_eh() for this purpose.
In addition to this change, ata_scsi_requeue_deferred_qc() is also
modified to take a new timedout_scmd scsi command argument which indicates
the SCSI command that timed out. With this additional argument,
ata_scsi_requeue_deferred_qc() can now also terminate with DID_TIME_OUT
any timed out deferred qc, which simplifies ata_scsi_cmd_error_handler().
In this case, ata_scsi_requeue_deferred_qc() returns SCSI_EH_DONE, with
this return value propagated back to the ata_scsi_eh_timed_out() operation
to indicate to scsi_timeout() that the timed out command was handled and
no further processing is needed.
For non-timed out deferred qc that need to be retried,
ata_scsi_requeue_deferred_qc() returns SCSI_EH_NOT_HANDLED, thus
indicating to scsi_timeout() that the timed out command needs to go
through the SCSI EH (and libata EH) processing by adding it to the EH work
queue with scsi_eh_scmd_add().
One side effect of these changes is that the function atapi_qc_complete()
needs to be modified to ensure that a deferred ATAPI command that needs
to be retried is completed with DID_REQUEUE instead of the default
SAM_STAT_GOOD status, and a command that timed out is completed with
DID_TIME_OUT instead of SAM_STAT_CHECK_CONDITION.
Fixes: 0ea84089dbf6 ("ata: libata-scsi: avoid Non-NCQ command starvation") Cc: stable@vger.kernel.org Signed-off-by: Damien Le Moal <dlemoal@kernel.org> Reviewed-by: Igor Pylypiv <ipylypiv@google.com> Tested-by: Igor Pylypiv <ipylypiv@google.com> Reviewed-by: Niklas Cassel <cassel@kernel.org> Reviewed-by: Martin K. Petersen <martin.petersen@oracle.com>
net: phylink: put link_gpio if phylink_create fails
In phylink_create() if phylink_register_sfp() returns an error, link_gpio
obtained by phylink_parse_fixedlink() is never released. While this is a
very unlikely scenario, it's worth to fix/handle this.
This was present from the very first implementation of phylink but got
relevant only with the introduction of ce0aa27ff3f6 ("sfp: add sfp-bus to
bridge between network devices and sfp cages") where additional function
were added after phylink_parse_fixedlink() making the release of link_gpio
needed if such additional function errored out.
While at it, restructure the exit condition of phylink_create() with the
goto pattern to reduce code duplication on handling error conditions.
Fixes: ce0aa27ff3f6 ("sfp: add sfp-bus to bridge between network devices and sfp cages") Signed-off-by: Christian Marangi <ansuelsmth@gmail.com> Reviewed-by: Andrew Lunn <andrew@lunn.ch> Link: https://patch.msgid.link/20260726150806.2437-1-ansuelsmth@gmail.com Signed-off-by: Jakub Kicinski <kuba@kernel.org>
Chris Gellermann [Wed, 22 Jul 2026 13:02:46 +0000 (15:02 +0200)]
selftests/mm: fix potential wild pointer access of getline due to missing init
This is another occurrence of using getline where the code assumes that
getline allocates memory to store the line, but the pointer passed to it
is uninitialized and potentially a non-null pointer. This violates the
Open Group Spec[1] and caused a segfault in a similar situation in
selftest/clone3/clone3_set_tid. Fix it by initializing the line pointer
to NULL.
The issue has been found by simply grepping through the selftest code
after running into the issue in clone3_set_tid. Whether it segfaults in
its current state is unknown to me. But it's good to be addressed due to
defensive reasons.
Link: https://lore.kernel.org/20260722130246.2135563-3-christian.gellermann@codasip.com Link: https://pubs.opengroup.org/onlinepubs/9799919799/functions/getline.html Fixes: 26b4224d9961 ("selftests: expanding more mlock selftest") Signed-off-by: Chris Gellermann <christian.gellermann@codasip.com> Acked-by: David Hildenbrand (arm) <david@kernel.org> Reviewed-by: Lorenzo Stoakes <ljs@kernel.org> Cc: Christian Brauner <brauner@kernel.org> Cc: Liam R. Howlett <liam@infradead.org> Cc: Michal Hocko <mhocko@suse.com> Cc: Mike Rapoport <rppt@kernel.org> Cc: Shuah Khan <shuah@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Vlastimil Babka <vbabka@kernel.org> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Chris Gellermann [Wed, 22 Jul 2026 13:02:45 +0000 (15:02 +0200)]
selftests/clone3: fix wild pointer access of getline due to missing init
Patch series "selftests: Add missing initalization of pointer passed to
getline", v2.
This patch (of 2):
Clone3_set_tid uses getline(&line, ...) in a loop to read the child's
process status. The code expects that getline allocates the buffer for
the line on the first loop iteration. According to the Open Group
Spec[1], char *line has to be null pointer for this:
> ssize_t getline(char **restrict lineptr, ...);
> If *lineptr is a null pointer or if the object pointed to by *lineptr
> is of insufficient size, an object shall be allocated as if by
malloc()
> or the object shall be reallocated as if by realloc()[...].
However, char *line is only declared, leading to an undefined value that
is potentially non-null. In an example run with Musl v1.2.6, the realloc
call[2] of getdelim, which implements getline, triggers a segfault:
./run_kselftest.sh --test clone3:clone3_set_tid
[ 1366.165898] kselftest: Running tests in clone3
...
[ 1367.799244] clone3_set_tid[811]: unhandled signal 11 code 0x1 at
0x0000000000000000 in libc.so[68184,3fbf69f000+4c000]
[ 1367.802808] CPU: 0 UID: 0 PID: 811 Comm: clone3_set_tid Not tainted
..
[ 1367.804188] epc: 0x0000003fbf6b0184
[ 1367.804188] ra : 0x0000003fbf6d4664
[ 1367.804188] sp : 0x0000003fce5f2e40
[ 1367.805314] gp : 0x0000002aaab0dfb8
[ 1367.805314] tp : 0x0000003fbf6f14a8
[ 1367.805314] t0 : 0x0000003fbf63d000
...
Looking at the realloc implementation, Musl mallocs for a null pointer
memory. But for a non-null pointer, it assumes it's passed a valid
pointer to the heap and tries to access its meta-data. This leads to the
segfault we see:
void *realloc(void *p, size_t n)
{
if (!p) return malloc(n);
if (size_overflows(n)) return 0;
struct meta *g = get_meta(p);
...
}
Fix this by properly initializing the line pointer to NULL.
Link Lin [Tue, 21 Jul 2026 00:55:33 +0000 (00:55 +0000)]
mm/page_reporting: use system_freezable_wq to fix UAF during suspend
During PM freeze (e.g. S3 suspend or S4 hibernation), device drivers like
virtio_balloon reset their underlying virtio devices and delete their
virtqueues via vdev->config->del_vqs().
However, page reporting work (page_reporting_process) was scheduled on the
global system_wq. Because system_wq lacks the WQ_FREEZABLE flag, the PM
freezer skips it, leaving page_reporting_process active during suspend.
If pages are freed into the buddy allocator while suspending (for example,
when core MM invokes the balloon shrinker during S4 hibernation image
saving), page reporting triggers virtballoon_free_page_report() on deleted
virtqueues, resulting in a Use-After-Free / General Protection Fault:
Fix this by switching page reporting work to system_freezable_wq. This
ensures that the PM freezer pauses page_reporting_process before device
drivers destroy their reporting virtqueues. Because the reporting worker
is frozen, memory reclamation/freeing (e.g. via shrinker execution) can
safely return pages to MM during freeze without triggering unfrozen
reporting work on deleted virtqueues.
This aligns with the driver's existing design. The comment in
virtballoon_freeze() states:
/*
* The workqueue is already frozen by the PM core before this
* function is called.
*/
Testing:
I have verified these fixes using Google’s virtualization infrastructure
by running continuous suspend/resume iterations (40+ cycles) while
churning memory using stress-ng (`stress-ng --vm 4 --vm-bytes 60%
--timeout 1`) to constantly create free pages for the buddy allocator. We
also set the `page_reporting_order` parameter to 0 to make the page
reporting worker highly sensitive, forcing it to pick up any 4K free
pages. This confirmed that the UAF crashes are no longer reproducible.
Link: https://lore.kernel.org/20260721005603.1710551-1-linkl@google.com Fixes: 36e66c554b5c ("mm: introduce Reported pages") Signed-off-by: Link Lin <linkl@google.com> Suggested-by: David Hildenbrand (Arm) <david@kernel.org> Suggested-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: David Rientjes <rientjes@google.com> Acked-by: David Hildenbrand (Arm) <david@kernel.org> Acked-by: Michael S. Tsirkin <mst@redhat.com> Cc: Alexander Duyck <alexander.duyck@gmail.com> Cc: Greg Thelen <gthelen@google.com> Cc: James Houghton <jthoughton@google.com> Cc: Jason Wang <jasowang@redhat.com> Cc: Jiaqi Yan <jiaqiyan@google.com> Cc: Vlastimil Babka <vbabka@kernel.org> Cc: Xuan Zhuo <xuanzhuo@linux.alibaba.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Richard Chang [Mon, 20 Jul 2026 04:41:03 +0000 (04:41 +0000)]
mm: vmscan: abort proactive reclaim early when freezing for suspend
Proactive reclaim (triggered via memory.reclaim or node sysfs) checks for
pending signals in its outer loop in user_proactive_reclaim(). However,
the inner reclaim loops—specifically scanning cgroups in shrink_many()
and evicting/aging folios in try_to_shrink_lruvec()—can run for a long
time before returning to the outer loop, especially on systems with many
cgroups or large memory sizes.
During system suspend, the PM freezer attempts to freeze all tasks by
sending fake signals (setting TIF_SIGPENDING). Because the inner loops do
not check for pending signals, the proactive reclaim task can remain stuck
in kernel space for seconds, failing to enter the refrigerator in a timely
manner. This leads to suspend failures due to freeze timeouts, a behavior
observed on Android devices.
This latency issue is specific to proactive reclaim because of its large,
user-defined reclaim targets (could be gigabytes). Since commit 287d5fedb377 ("mm: memcg: use larger batches for proactive reclaim"),
proactive reclaim uses larger decaying batch sizes (starting at 1/4 of the
remaining target) to maintain throughput. This keeps the task in the
inner reclaim loop for extended periods. In contrast, reactive reclaim
(global/memcg) uses small targets (SWAP_CLUSTER_MAX, typically 32 pages),
allowing it to return to the outer loop and check signals frequently.
To fix this, add a signal_pending() check to should_abort_scan() for
proactive reclaim paths. Since should_abort_scan() is called within the
inner scanning and eviction loops, this allows proactive reclaim to abort
early and return to the outer loop in user_proactive_reclaim().
Additionally, return -ERESTARTSYS instead of -EINTR in
user_proactive_reclaim(). When interrupted by system suspend, returning
-ERESTARTSYS allows the task to enter the refrigerator and automatically
restart the syscall upon resume, making the freezer transparent to
userspace. For real signals, the signal layer will either restart the
syscall (if SA_RESTART is set) or return -EINTR to userspace.
This fix specifically targets Multi-Gen LRU (MGLRU). Classic LRU's scan
targets per iteration are strictly bounded by get_scan_count(), which
ensures it returns to the outer loop more frequently.
The check in should_abort_scan() is limited to proactive reclaim
(sc->proactive) to avoid inadvertently affecting reactive reclaim paths,
and is wrapped in unlikely() as it is a slow path.
Link: https://lore.kernel.org/20260720044103.905191-1-richardycc@google.com Fixes: 287d5fedb377 ("mm: memcg: use larger batches for proactive reclaim") Fixes: 94968384dde1 ("memcg: introduce per-memcg reclaim interface") Suggested-by: Michal Hocko <mhocko@suse.com> Suggested-by: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Richard Chang <richardycc@google.com> Acked-by: Michal Hocko <mhocko@suse.com> Cc: Axel Rasmussen <axelrasmussen@google.com> Cc: Barry Song <baohua@kernel.org> Cc: David Hildenbrand <david@kernel.org> Cc: Johannes Weiner <hannes@cmpxchg.org> Cc: Kairui Song <kasong@tencent.com> Cc: Lorenzo Stoakes <ljs@kernel.org> Cc: Martin Liu <liumartin@google.com> Cc: Minchan Kim <minchan@kernel.org> Cc: Shakeel Butt <shakeel.butt@linux.dev> Cc: Suren Baghdasaryan <surenb@google.com> Cc: T.J. Mercier <tjmercier@google.com> Cc: Wei Xu <weixugc@google.com> Cc: Yuanchu Xie <yuanchu@google.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
arm64, mailmap: update email address for Peter Collingbourne
I am no longer at Google.
Link: https://lore.kernel.org/20260718172923.8297-1-peter@pcc.me.uk Signed-off-by: Peter Collingbourne <peter@pcc.me.uk> Cc: Catalin Marinas <catalin.marinas@arm.com> Cc: Ian Rogers <irogers@google.com> Cc: Jakub Kacinski <kuba@kernel.org> Cc: Martin Kepplinger <martink@posteo.de> Cc: Nick Desaulniers <ndesaulniers@google.com> Cc: Will Deacon <will@kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
mm/huge_memory: unlock i_mmap_rwsem before releasing after-split folios
__folio_split() keeps dereferencing the mapping after the split:
shmem_uncharge(mapping->host) and remap_page() while the folios are still
frozen/locked, and i_mmap_unlock_read(mapping) at the very end, after the
after-split folios have been unlocked and freed.
Nothing holds an inode reference across that. The split relies on @folio
-- which the beyond-EOF drop loop never removes, as it starts at
folio_next(folio) -- staying locked and in the page cache to hold off
eviction. But the unlock loop unlocks @folio before i_mmap_unlock_read()
runs. If the caller's @lock_at is a tail beyond EOF, as memory_failure()
passes when splitting a poisoned tail of a shmem THP that reaches past
i_size during truncation, it too is gone from the page cache; so once
@folio is unlocked no locked, in-cache folio pins the inode, and a
concurrent final iput() can evict and RCU-free it before
i_mmap_unlock_read() touches i_mmap_rwsem:
Freed by task 4601:
shmem_free_in_core_inode+0x54/0xb0 mm/shmem.c:5177
evict+0x57f/0xac0 fs/inode.c:870
Do every mapping dereference while @folio still pins the inode: drop
i_mmap_rwsem right after remap_page(), before the loop that unlocks and
frees the after-split folios, and clear @mapping so the exit path does not
unlock it again. shmem_uncharge() and remap_page() already run before
that point, so after this nothing past the unlock loop touches the inode
or the mapping.
This is now a rule the split depends on, alongside keeping @folio frozen
until the page cache is updated: no inode or mapping dereference once the
after-split folios start being unlocked.
Link: https://lore.kernel.org/20260716095424.471052-1-kirill@shutemov.name Fixes: baa355fd3314 ("thp: file pages support for split_huge_page()") Signed-off-by: Kiryl Shutsemau (Meta) <kas@kernel.org> Reported-by: Hao Zhang <zhanghao1@kylinos.cn> Closes: https://lore.kernel.org/linux-mm/20260710071344.GA106129@zh-pc Co-developed-by: Hao Zhang <zhanghao1@kylinos.cn> Signed-off-by: Hao Zhang <zhanghao1@kylinos.cn> Acked-by: David Hildenbrand (Arm) <david@kernel.org> Reviewed-by: Zi Yan <ziy@nvidia.com> Reviewed-by: Baolin Wang <baolin.wang@linux.alibaba.com> Reviewed-by: Miaohe Lin <linmiaohe@huawei.com> Cc: Baolin Wang <baolin.wang@linux.alibaba.com> Cc: Barry Song <baohua@kernel.org> Cc: Dev Jain <dev.jain@arm.com> Cc: Lance Yang <lance.yang@linux.dev> Cc: Liam R. Howlett <liam@infradead.org> Cc: Lorenzo Stoakes <ljs@kernel.org> Cc: Naoya Horiguchi <nao.horiguchi@gmail.com> Cc: Nico Pache <npache@redhat.com> Cc: Ryan Roberts <ryan.roberts@arm.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
riscv/mm: use physical alignment for vmemmap_start_pfn
RISC-V computes vmemmap_start_pfn by rounding phys_ram_base down to
VMEMMAP_ADDR_ALIGN. That alignment must therefore be expressed in the
physical-address domain.
Commit 476849b0fba4 ("riscv/mm: align vmemmap to maximal folio size")
attempted to account for the maximal folio alignment by feeding
MAX_FOLIO_VMEMMAP_ALIGN directly into VMEMMAP_ADDR_ALIGN. However,
MAX_FOLIO_VMEMMAP_ALIGN is measured in bytes of struct page storage,
whereas VMEMMAP_ADDR_ALIGN is used to align a physical address.
The mask-based compound_info encoding requires pfn_to_page(0) to be
naturally aligned to MAX_FOLIO_VMEMMAP_ALIGN. Commit 9f94db4c7eaa
("mm/sparse: check memmap alignment for compound_info_has_mask()") added a
check for that requirement and exposed the unit mismatch on systems such
as QEMU virt, where the DRAM base is not aligned to MAX_FOLIO_NR_PAGES *
PAGE_SIZE.
Convert MAX_FOLIO_VMEMMAP_ALIGN to the equivalent physical alignment
before using it in VMEMMAP_ADDR_ALIGN. This keeps the existing
round_down() logic while making the resulting vmemmap base satisfy the
mask-alignment requirement.
Link: https://lore.kernel.org/20260716115326.3466926-1-xujiakai2025@iscas.ac.cn Fixes: 476849b0fba4 ("riscv/mm: align vmemmap to maximal folio size") Signed-off-by: Jiakai Xu <xujiakai2025@iscas.ac.cn> Reviewed-by: Kiryl Shutsemau (Meta) <kas@kernel.org> Cc: Albert Ou <aou@eecs.berkeley.edu> Cc: Alexandre Ghiti <alex@ghiti.fr> Cc: David Hildenbrand <david@kernel.org> Cc: Guo Ren <guoren@kernel.org> Cc: Mike Rapoport <rppt@kernel.org> Cc: Muchun Song <muchun.song@linux.dev> Cc: Nam Cao <namcao@linutronix.de> Cc: Palmer Dabbelt <palmer@dabbelt.com> Cc: Vishal Moola (Oracle) <vishal.moola@gmail.com> Assisted-by: YuanSheng:DeepSeek-V4-Flash Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
mm/migrate: exclude hugetlb folios from MTHP_STAT_NR_ANON accounting
__folio_migrate_mapping() increments MTHP_STAT_NR_ANON for the destination
folio when `folio_test_anon(folio) && folio_test_large(folio)` is true.
However, hugetlb folios satisfy both conditions despite having a
completely separate accounting system — they use hugetlb_add_anon_rmap()
which does not touch mTHP stats, and their free path also bypasses the
mTHP decrement in __free_pages_prepare().
This causes MTHP_STAT_NR_ANON to be incremented on each hugetlb migration
without a corresponding decrement, permanently inflating the nr_anon
counter.
Add a !folio_test_hugetlb() check to __folio_migrate_mapping() so that
only actual mTHP folios are counted.
Link: https://lore.kernel.org/20260717064502.1980173-3-npache@redhat.com Fixes: 5d65c8d758f2 ("mm: count the number of anonymous THPs per size") Co-developed-by: David Hildenbrand <david@kernel.org> Signed-off-by: David Hildenbrand <david@kernel.org> Signed-off-by: Nico Pache <npache@redhat.com> Reviewed-by: Zi Yan <ziy@nvidia.com> Reviewed-by: Baolin Wang <baolin.wang@linux.alibaba.com> Cc: Alistair Popple <apopple@nvidia.com> Cc: Barry Song <baohua@kernel.org> Cc: Byungchul Park <byungchul@sk.com> Cc: Gregory Price <gourry@gourry.net> Cc: "Huang, Ying" <ying.huang@linux.alibaba.com> Cc: Joshua Hahn <joshua.hahnjy@gmail.com> Cc: Lorenzo Stoakes <ljs@kernel.org> Cc: Matthew Brost <matthew.brost@intel.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Oscar Salvador <osalvador@suse.de> Cc: Rakie Kim <rakie.kim@sk.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
mm: decrement MTHP_STAT_NR_ANON in free_zone_device_folio()
Patch series "mm: fix PMD level mTHP accounting bugs", v2.
While running selftests I noticed the PMD level per-mTHP stats (nr_anon)
remained elevated after each run. After further investigation I noticed
this accounting error occurs for both the migration.private_anon_htlb_test
and the HMM tests.
In the HMM case this is due to folio_add_new_anon_rmap() incrementing the
mTHP stats, but never containing a corresponding decrement in
free_zone_device_folio(). We solve this by making sure to decrement the
counter when freeing device memory.
In the migration case, we are incrementing this counter without first
checking whether this folio is a hugetlb folio, which relies on a separate
accounting system. We solve this by adding the proper hugetlb check
before incrementing this counter.
With these changes in place, the two tests no longer cause elevated PMD
level accounting issues.
This patch (of 2):
When a zone device folio is mapped as anonymous, folio_add_new_anon_rmap()
increments MTHP_STAT_NR_ANON. The corresponding decrement lives in
__free_pages_prepare() in page_alloc.c, but zone device folios are freed
via free_zone_device_folio() which never calls __free_pages_prepare().
This causes nr_anon to remain permanently elevated after zone device
folios are freed.
Add the missing mod_mthp_stat() decrement to free_zone_device_folio() so
that the counter is properly balanced.
Link: https://lore.kernel.org/20260717064502.1980173-1-npache@redhat.com Link: https://lore.kernel.org/20260717064502.1980173-2-npache@redhat.com Fixes: 5d65c8d758f2 ("mm: count the number of anonymous THPs per size") Co-developed-by: David Hildenbrand <david@kernel.org> Signed-off-by: David Hildenbrand <david@kernel.org> Signed-off-by: Nico Pache <npache@redhat.com> Reviewed-by: Zi Yan <ziy@nvidia.com> Cc: Alistair Popple <apopple@nvidia.com> Cc: Barry Song <baohua@kernel.org> Cc: Byungchul Park <byungchul@sk.com> Cc: Gregory Price <gourry@gourry.net> Cc: "Huang, Ying" <ying.huang@linux.alibaba.com> Cc: Joshua Hahn <joshua.hahnjy@gmail.com> Cc: Lorenzo Stoakes <ljs@kernel.org> Cc: Matthew Brost <matthew.brost@intel.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Oscar Salvador <osalvador@suse.de> Cc: Rakie Kim <rakie.kim@sk.com> Cc: Baolin Wang <baolin.wang@linux.alibaba.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
mm: memcg: initialize *locked in memcg1_oom_prepare() stub
mem_cgroup_oom() passes an uninitialized "locked" to memcg1_oom_prepare()
and reads it back in memcg1_oom_finish():
bool locked, ret;
...
if (!memcg1_oom_prepare(memcg, &locked))
return false;
ret = mem_cgroup_out_of_memory(memcg, mask, order);
memcg1_oom_finish(memcg, locked);
This relies on memcg1_oom_prepare() setting *locked whenever it returns
true. The CONFIG_MEMCG_V1=y version does, but the stub used when
CONFIG_MEMCG_V1=n returns true without touching *locked, so
memcg1_oom_finish() consumes an uninitialized value. On a memcg OOM this
is reported by UBSAN:
UBSAN: invalid-load in mm/memcontrol.c:1932:27
load of value 0 is not a valid value for type 'bool' (aka '_Bool')
Initialize *locked to false in the stub; with cgroup v1 compiled out there
is no OOM lock to take.
Link: https://lore.kernel.org/20260716-memcg-oom-uninit-locked-v2-1-63631d878eb4@debian.org Fixes: e93d4166b40a ("mm: memcg: put cgroup v1-specific code under a config option") Signed-off-by: Breno Leitao <leitao@debian.org> Reviewed-by: Joshua Hahn <joshua.hahnjy@gmail.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Reviewed-by: SeongJae Park <sj@kernel.org> Acked-by: Shakeel Butt <shakeel.butt@linux.dev> Cc: Michal Hocko <mhocko@kernel.org> Cc: Muchun Song <muchun.song@linux.dev> Cc: Roman Gushchin <roman.gushchin@linux.dev> Cc: Shakeel Butt <shakeel.butt@linux.dev> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Jakub Kicinski [Wed, 29 Jul 2026 00:30:21 +0000 (17:30 -0700)]
Merge tag 'for-net-2026-07-28' of git://git.kernel.org/pub/scm/linux/kernel/git/bluetooth/bluetooth
Luiz Augusto von Dentz says:
====================
bluetooth pull request for net:
- hci_sync: Fix advertising data UAFs
- hci_conn: hold conn reference fixes
- L2CAP: fix UAF in l2cap_le_connect_rsp
- RFCOMM: validate skb length in rfcomm_recv_frame
- ISO: Locking fixes
- SCO: give the socket its own sco_conn reference
- MGMT: fix UAF in pair command cancellation
- MGMT: fix pending command UAF in EIR updates
- HIDP: reject frames without a transaction header
- HIDP: validate numbered report payloads
- btmtk: Fix short read errors in btmtk_usb_uhw_reg_read()
- btmtk: Fix short read errors in btmtk_usb_reg_read()
- btusb: Fix short read errors in btusb_qca_send_vendor_req()
- btintel: Validate length before parsing diagnostics TLV
* tag 'for-net-2026-07-28' of git://git.kernel.org/pub/scm/linux/kernel/git/bluetooth/bluetooth: (31 commits)
Bluetooth: SCO: give the socket its own sco_conn reference
Bluetooth: btusb: Fix short read errors in btusb_qca_send_vendor_req()
Bluetooth: btmtk: Fix short read errors in btmtk_usb_reg_read()
Bluetooth: btmtk: Fix short read errors in btmtk_usb_uhw_reg_read()
Bluetooth: hci_sync: remove unnecessary hci_conn_get in create_conn_sync
Bluetooth: hci_sync: fix hci_conn_del() use in hci_le_create_conn_sync
Bluetooth: hci_sync: hold conn in hci_past_sync() callback
Bluetooth: hci_sync: hold conn in hci_connect_pa_sync() callback
Bluetooth: hci_sync: hold conn in hci_connect_big_sync() callback
Bluetooth: hci_sync: hold conn in hci_connect_acl/le_sync() callbacks
Bluetooth: hci_conn: hold conn reference in abort_conn_sync()
Bluetooth: btintel: Validate length before parsing diagnostics TLV
Bluetooth: ISO: fix race of kfree vs kref_get_unless_zero
Bluetooth: ISO: fix refcounting of iso_conn
Bluetooth: ISO: ensure no dangling hcon references in iso_conn
Bluetooth: ISO: avoid deadlocks in iso_sock_timeout
Bluetooth: ISO: fix leaking sk after socket release
Bluetooth: ISO: hold sk properly in iso_conn_ready
Bluetooth: ISO: validate sockaddr_iso first in iso_sock_rebind_bis()
Bluetooth: ISO: fix timeout vs sync_timeout typo in check_bcast_qos
...
====================
The same as the rest of the code, get_ss_info_from_atombios() uses
calc_pll_cs->ctx->logger for logging. But calc_pll_cs->ctx is
initialized only later in calc_pll_max_vco_construct(). Therefore, any
output using DC_LOG_SYNC() leads to a NULL pointer deference in
get_ss_info_from_atombios().
According to Sashiko, the very same problem exists in
dce112_get_pix_clk_dividers() and dcn3_get_pix_clk_dividers() too.
To avoid accessing the NULL context, use clk_src->base.ctx->logger
everywhere. That context in base is initialized earlier in
dce110_clk_src_construct() and dce112_clk_src_construct(). Before
get_ss_info_from_atombios() or Sashiko's get_pix_clk_dividers functions
above are actually called. This is done by redefining DC_LOGGER to
CTX->logger.
On APUs, the GTT pool is backed by system RAM, but its size is not bound
to the non-carveout memory that actually backs it. A user can end up
with GTT + VRAM exceeding total physical memory through the following
sequence:
- Have a large non-carveout memory space (~128GB) and accordingly set a
large GTT (~100GB) via the ttm module parameter.
- Lower the non-carveout memory space in BIOS by increasing the UMA
Frame Buffer Size (VRAM) to 64GB.
- The previously set GTT value (~100GB) persists, even though the new
non-carveout space (64GB) can no longer back it.
This leads to a case where kernel reports GTT (100GB) + VRAM (64GB)
despite the sum being greater than total physical memory (128GB).
Cap the GTT size to totalram_pages() on APUs. totalram_pages() already
excludes the VRAM carveout, so the resulting GTT can never exceed the
system RAM that actually backs it.
Signed-off-by: Harkirat Gill <harkirat.gill@amd.com> Reviewed-by: David Francis <David.Francis@amd.com> Assisted-by: Claude:claude-opus-4 Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 5dafdd649280c7dc6c22c8f877da3f54fcc441e1) Cc: stable@vger.kernel.org
Yang Wang [Mon, 27 Jul 2026 04:23:17 +0000 (12:23 +0800)]
drm/amd/pm: use milliwatts for GPU power sensors
GPU average and input power backends report a mix of whole watts,
milliwatts, Q24.8 watts and decimal-packed fractions. Q24.8 is inherited
from the legacy PowerPlay sensor format. Milliwatts are a more natural unit
for the hwmon and pm_info consumers in amdgpu_pm.c. A common decoder cannot
distinguish these formats, and converting native milliwatts through Q24.8
also loses precision.
Use milliwatts as the internal unit across all PPT and PowerPlay backends.
Decode Q24.8 only at the legacy smu7 input boundary and encode it only for
the raw amdgpu_sensors debugfs interface. This gives hwmon, pm_info and the
sensor ioctl one unambiguous unit while preserving the format used by UMR.
Fixes: 5b79d0482f3c ("drm/amd/pp: Remove struct pp_gpu_power") Fixes: 01992b121fb6 ("drm/amd/pm: fix amdgpu_pm_info power display units") Signed-off-by: Yang Wang <kevinyang.wang@amd.com> Reviewed-by: Kenneth Feng <kenneth.feng@amd.com> Reported-by: Lars Nieradzik <l.nieradzik@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 757ba0790bafec47a507e9662bf380f2e027d420) Cc: stable@vger.kernel.org
Candice Li [Tue, 21 Jul 2026 13:38:58 +0000 (21:38 +0800)]
drm/amdgpu: restore UMD profile pstate after runtime resume
Runtime suspend runs GFX hw_fini and clears perfmon clock gating while
the UMD profile DPM level remains set in software. Re-apply stable
pstate after a successful runtime resume when a profile mode is active.
Signed-off-by: Candice Li <candice.li@amd.com> Reviewed-by: Hawking Zhang <Hawking.Zhang@amd.com> Reviewed-by: Yang Wang <kevinyang.wang@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 138531c8850cc247aa12b104bb29ea387bcdcbb1) Cc: stable@vger.kernel.org
Commit a4f01bf729b2 ("drm/amd/display: Refactor and fix link_dpms I2C")
had also changed the "Set retimer failed" messages from DC_LOG_DEBUG()
to DC_LOG_ERROR(). This unfortunately can create log spam.
Change those back to DC_LOG_DEBUG() only.
Fixes: a4f01bf729b2 ("drm/amd/display: Refactor and fix link_dpms I2C") Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/5520 Signed-off-by: Alan Swanson <reiver@improbability.net> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit da8609eef18b0a3490d0e1fa9440659fadc8194d) Cc: stable@vger.kernel.org
William Palacek [Wed, 22 Jul 2026 15:20:56 +0000 (11:20 -0400)]
drm/amdkfd: hold event_mutex while checkpointing CRIU events
kfd_criu_checkpoint_events() counts the entries in p->event_idr via
kfd_get_num_events(), allocates an array sized to that count, and then
walks the same IDR to fill it. Neither the count nor the walk holds
p->event_mutex.
The CRIU checkpoint caller holds only p->mutex. Event create and destroy
(kfd_event_create()/kfd_event_destroy()) take p->event_mutex and do not
take p->mutex, so a second thread in the same process can insert or remove
events between the count and the walk. If an event is inserted, the walk
iterates more entries than were counted and writes past the end of the
ev_privs allocation; if an event is removed, the walk dereferences an
entry that is being freed.
Hold p->event_mutex across the count and the walk so both observe a
consistent view of p->event_idr. The lock is released before
copy_to_user(), which only touches the local buffer. The caller already
holds p->mutex and the create/destroy paths never take p->mutex, so the
p->mutex -> p->event_mutex order is not inverted and no deadlock is
introduced.
Fixes: 40e8a766a761 ("drm/amdkfd: CRIU checkpoint and restore events") Signed-off-by: William Palacek <William.Palacek@amd.com> Reviewed-by: Alysa Liu <Alysa.Liu@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit ff57e223ab105795b05d3ef3f3c35a5a441bcbaa) Cc: stable@vger.kernel.org
George Zhang [Thu, 16 Jul 2026 21:00:01 +0000 (17:00 -0400)]
drm/amd/display: Fix divide-by-zero in calculate_mcache_setting on zero viewport
If a plane reaches calculate_mcache_setting with a zero-area viewport,
calculate_mcache_setting exits early with num_mcaches == 0 and
mvmpg_width/height == 0. This will cause a divide-by-zero panic and can
also cause an underflow on num_mcaches.
Fix this by changing calculate_mcache_setting to bool and adding guards
after each calculate_mcache_row_bytes call. If num_mcaches or
mvmpg_width/height is zero, return a false. Callers will propagate the
failure as a rejected mode, which prevents the panic.
Closes: https://gitlab.freedesktop.org/drm/amd/-/issues/5302 Reviewed-by: Sun peng (Leo) Li <sunpeng.li@amd.com> Reviewed-by: Dillon Varone <dillon.varone@amd.com> Signed-off-by: George Zhang <george.zhang@amd.com> Signed-off-by: Fangzhi Zuo <jerry.zuo@amd.com> Tested-by: Dan Wheeler <daniel.wheeler@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 29c0f7c655f47bcbd575ff75e58480df6ec3c9da) Cc: stable@vger.kernel.org
Ray Wu [Mon, 13 Jul 2026 14:23:34 +0000 (22:23 +0800)]
drm/amd/display: Add AV mute wait frames to dce110_set_avmute
Port the three-frame wait logic from dcn30_set_avmute to
dce110_set_avmute so that older DCN versions (1.0, 2.0) also
wait for GCP packets to be sent out before proceeding.
This ensures HDMI sinks properly process the mute state,
preventing garbled display after link re-establishment.
Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/5167 Reviewed-by: Wayne Lin <wayne.lin@amd.com> Signed-off-by: Ray Wu <ray.wu@amd.com> Signed-off-by: Fangzhi Zuo <jerry.zuo@amd.com> Tested-by: Dan Wheeler <daniel.wheeler@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 414da24137ace80d8c59fefd43ba3ec9f5f854ba) Cc: stable@vger.kernel.org
Yang Wang [Thu, 23 Jul 2026 15:18:33 +0000 (23:18 +0800)]
drm/amd/pm: fix torn gpu metrics reads
amdgpu_dpm_get_gpu_metrics() returns a pointer to the shared metrics cache
after dropping adev->pm.mutex. The sysfs path then copies from that pointer.
Another reader can refresh the cache in place during the copy and return a
snapshot containing data from two generations.
Pass caller-provided storage through the DPM interface and copy the metrics
while the mutex is held. This keeps the cache pointer private and makes each
sysfs read observe one complete sample.
Fixes: 25c933b1c4fc ("drm/amd/powerplay: add new sysfs interface for retrieving gpu metrics(V2)") Signed-off-by: Yang Wang <kevinyang.wang@amd.com> Reviewed-by: Kenneth Feng <kenneth.feng@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 862333bb48693ecafcae25af0c9d9ec31015ac77) Cc: stable@vger.kernel.org
Yang Wang [Thu, 23 Jul 2026 23:41:29 +0000 (07:41 +0800)]
drm/amd/pm: fix pptable use-after-free
amdgpu_dpm_get_pp_table() returns a pointer to a driver-owned power table
after dropping adev->pm.mutex. The sysfs path then copies from that pointer.
A concurrent pp_table write can replace and free the allocation during the
copy, causing a use-after-free.
Change the DPM interface to copy into caller-provided storage while the mutex
is held. Keep the size-only query for attribute discovery without exposing
the driver-owned pointer.
Fixes: 1684d3ba4885 ("drm/amd/amdgpu: change pptable output format from ASCII to binary") Signed-off-by: Yang Wang <kevinyang.wang@amd.com> Reviewed-by: Kenneth Feng <kenneth.feng@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit f6eed7acfd30099ef7baeb6ba45bb59daad80631) Cc: stable@vger.kernel.org
William Palacek [Mon, 20 Jul 2026 16:51:34 +0000 (12:51 -0400)]
drm/amdkfd: fix uint32_t overflow in EOP ring buffer size alignment
eop_ring_buffer_size in struct queue_properties is a u32. In
kfd_queue_acquire_buffers() the expected EOP buffer size is computed as
ALIGN(eop_ring_buffer_size, PAGE_SIZE); ALIGN uses typeof(x), so the
addition is done in 32-bit. A user-supplied size of 0xFFFFF001 wraps to
0, causing kfd_queue_buffer_get() to skip its exact-size check (gated on
size != 0) and accept any BO mapped at the address. On GFX8/GFX9 the MQD
cp_hqd_eop_control is then programmed for an 8KB EOP ring backed by a 4KB
BO, so CP EOP writes can land past the buffer and fault the GPU.
Cast the operand to u64 so the alignment is computed in 64-bit; the size
check in kfd_queue_buffer_get() then rejects the oversized request.
Fixes: 42ea9cf2f16b ("drm/amdkfd: Relax size checking during queue buffer get") Signed-off-by: William Palacek <William.Palacek@amd.com> Reviewed-by: Alysa Liu <Alysa.Liu@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit ae443117b742c357bfef3a7bddabf76fcf86e9ef) Cc: stable@vger.kernel.org
Gang Ba [Tue, 14 Jul 2026 19:08:57 +0000 (15:08 -0400)]
drm/amdkfd: Fix missing authorization check in KFD_IOC_DBG_TRAP_DISABLE
Prevent unauthorized termination of active GPU debug sessions.
Previously, users with /dev/kfd access could terminate another process's
debug session without proper ownership or ptrace authorization.
Signed-off-by: Gang Ba <Gang.Ba@amd.com> Reviewed-by: Kent Russell <kent.russell@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 4db4c5ffd5585b72622ecf6ffedf2da258ee23f5) Cc: stable@vger.kernel.org
drm/amdgpu: move debug_vm handling to amdgpu_cs_parser_fini
The commit referenced below restarts the CS if the validation is
still in progress. When debug_vm is enabled, all BOs from the CS
are invalidated so we will hit an infinite loop.
To avoid that, defer BO invalidation to amdgpu_cs_parser_fini.
Fixes: 59720bfd8c6d ("drm/amdgpu: restart the CS if some parts of the VM are still invalidated") Signed-off-by: Pierre-Eric Pelloux-Prayer <pierre-eric.pelloux-prayer@amd.com> Reviewed-by: Christian König <christian.koenig@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 8c990ee9daa295462df24982ce6878db997a380a) Cc: stable@vger.kernel.org
David Francis [Tue, 21 Jul 2026 13:30:07 +0000 (09:30 -0400)]
drm/amdkfd: Handle invalid event type in CRIU event restore
In kfd_criu_restore_event, there was no handling for
the event priv data having an invalid event type. The priv
data here is untrusted and can be invalid.
In that case, fail with EINVAL.
Signed-off-by: David Francis <David.Francis@amd.com> Reviewed-by: Kent Russell <kent.russell@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 2e8e9963cd5c41aa14fd5316bf9ec92e7a0e3097) Cc: stable@vger.kernel.org
drm/amdgpu: Update message IDs to PMFW to correctly gather GFXOFF residency logs
Updates PPSMC_MSGs and set/get functions for gathering GFXOFF logs
on Van Gogh. Logs are now gathered live rather than starting then
stopping logging and reading an average value afterwards. This is
in accordance to changes made in PMFW.
In regards to messageID 0x52, the old interface uses a start/stop
parameter, and the new one doesn't. The firmware is checked to
determine which method to use.
v2: added firmware guard to new interface, old interface kept as
fallback
Signed-off-by: Fares Soliman <Fares.Soliman@amd.com> Acked-by: Alex Deucher <alexander.deucher@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 482e2cadea8c34ae4e733f269a640d6b04fc9262)
Alex Hung [Thu, 9 Jul 2026 22:33:12 +0000 (16:33 -0600)]
drm/amdgpu: Pack nested ucode_info struct
Building for ARCH=um with W=1 C=1 makes the "amd_sriov_msg_vf2pf_info
must be 1 KB" static assertion in amdgv_sriovmsg.h fail under sparse,
exposed after UML builds were enabled.
Sparse does not honor #pragma pack(push, 1) for the nested ucode_info
struct, so it sizes each element as 8 bytes instead of 5 and computes
the surrounding structure as larger than 1 KB. The compilers get this
right via the enclosing pragma, but the annotation should be explicit.
Fixes: af3f2f5db265 ("drm/amdgpu: Remove UML build exclusion from Kconfig") Reported-by: kernel test robot <lkp@intel.com> Closes: https://lore.kernel.org/oe-kbuild-all/202607091659.SHEscT0c-lkp@intel.com/ Cc: Harry Wentland <harry.wentland@amd.com> Assisted-by: Copilot:Claude-Opus-4.8 Signed-off-by: Alex Hung <alex.hung@amd.com> Reviewed-by: Harry Wentland <harry.wentland@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 1d8cfeb69daa863a70134b8ed6df8055c418a5b0)
Alex Hung [Thu, 9 Jul 2026 22:33:11 +0000 (16:33 -0600)]
drm/amdgpu: Fix __rcu fence pointer accesses
Building for ARCH=um with W=1 C=1 makes sparse report "incompatible
types in comparison expression (different address spaces)" warnings in
the KFD code, exposed after UML builds were enabled:
- amdgpu_amdkfd_fence.c compares the __rcu-annotated dma_fence.ops
pointer directly in to_amdgpu_amdkfd_fence().
- amdgpu_amdkfd_gpuvm.c compares the __rcu eviction fence pointer
directly in amdgpu_amdkfd_gpuvm_restore_process_bos().
Fixes: af3f2f5db265 ("drm/amdgpu: Remove UML build exclusion from Kconfig") Reported-by: kernel test robot <lkp@intel.com> Closes: https://lore.kernel.org/oe-kbuild-all/202607091659.SHEscT0c-lkp@intel.com/ Cc: Harry Wentland <harry.wentland@amd.com> Assisted-by: Copilot:Claude-Opus-4.8 Signed-off-by: Alex Hung <alex.hung@amd.com> Reviewed-by: Christian König <christian.koenig@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 764f241ad227bb942e5b0b8b4d9898f1a4175605)
drm/amdkfd: fix QID bit leak in pqm_create_queue()
When MES is enabled and amdgpu_amdkfd_alloc_kernel_mem() fails during
the first queue creation for a process, pqm_create_queue() returns
early via 'return retval' without going through the err_create_queue
cleanup label.
This means clear_bit(*qid, pqm->queue_slot_bitmap) is never called,
leaving the reserved QID bit permanently set in queue_slot_bitmap.
Over time this leaks QID slots, potentially exhausting all available
queue slots.
Fix this by replacing 'return retval' with 'goto err_allocate_pqn'
so that clear_bit() is always called on the error path without
touching the uninitialized pqn pointer.
AILIKFD-813
Reported-by: Deucher, Alexander <alexander.deucher@amd.com> Signed-off-by: Vladimir Marioukhine <Vladimir.Marioukhine@amd.com> Reviewed-by: Kent Russell <kent.russell@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit a107f74c38edbb80d6ab64dcaeeb292c14e9779f) Cc: stable@vger.kernel.org
Ray Wu [Fri, 3 Jul 2026 01:14:49 +0000 (09:14 +0800)]
drm/amd/display: Increase HDMI AV mute wait from 2 to 3 frames
Some HDMI sinks need additional GCP packets to properly process the
mute state before the timing generator is disabled, especially after
link re-establishment with HDMI 2.0 scrambling enabled. Waiting for
only 2 frames is insufficient for certain monitor firmware, resulting
in garbled display output on resume from suspend.
Increase the AV mute wait in dcn30_set_avmute() from 2 to 3 frames
to ensure the sink receives enough GCP packets.
Closes: https://gitlab.freedesktop.org/drm/amd/-/work_items/5167 Assisted-by: Cursor:Claude-Opus-4.6 Reviewed-by: Wayne Lin <wayne.lin@amd.com> Signed-off-by: Ray Wu <ray.wu@amd.com> Tested-by: Dan Wheeler <daniel.wheeler@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 0c0d5174b09640d8b560764aa5a177630e076e93) Cc: stable@vger.kernel.org
Bob Zhou [Thu, 16 Jul 2026 02:44:36 +0000 (10:44 +0800)]
drm/amdgpu: skip clearing empty freed VM list on GEM close
amdgpu_vm_clear_freed() allocates an amdgpu_sync object and walks the VM
reservation fences via amdgpu_sync_resv() before checking whether vm->freed
has anything to clear. Return early when the list is empty to skip this
overhead on a hot path (every GEM close and command submission).
Signed-off-by: Bob Zhou <bobzhou2@amd.com> Reviewed-by: Felix Kuehling <felix.kuehling@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 8ba869e852d4f1b1c0e5ae9225c77f7ceccbe056)
drm/amdgpu: dont pin wptr bo instead use eviction fence
Instead of pinning the wptr bo attach the eviction fence to
the bo to make sure it remains valid all the time.
Signed-off-by: Sunil Khatri <sunil.khatri@amd.com> Reviewed-by: Christian König <christian.koenig@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 7264bc10c7c657a54603c7fc058bf8e15f18ce12)
William Palacek [Mon, 6 Jul 2026 14:25:58 +0000 (10:25 -0400)]
drm/amdkfd: Add bounds check for CRAT subtype length
The CRAT parser validates that the subtype header fits within the image,
but does not verify that the advertised subtype length fits. A malformed
CRAT table with an oversized length field causes out-of-bounds reads when
kfd_parse_subtype() casts the header to specific subtype structures.
Add validation that sub_type_hdr + length does not exceed the image
boundary before parsing the subtype contents.
Signed-off-by: William Palacek <William.Palacek@amd.com> Reviewed-by: Alysa Liu <Alysa.Liu@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
(cherry picked from commit 48e1d1e6e8798aef0312e68d8e586021b5b3cf4d) Cc: stable@vger.kernel.org
Wenmeng Liu [Thu, 25 Jun 2026 09:42:45 +0000 (17:42 +0800)]
i2c: qcom-cci: drop custom suspend/resume and rely on runtime PM helpers
cci_resume() unconditionally calls cci_resume_runtime() regardless of
the runtime PM state.
If the device is already runtime-suspended before system suspend,
the clock is re-enabled while runtime_status remains RPM_SUSPENDED.
As a result, pm_request_autosuspend() does not arm the timer,
leaving the clock permanently enabled.
Fixes: e517526195de ("i2c: Add Qualcomm CCI I2C driver") Signed-off-by: Wenmeng Liu <wenmeng.liu@oss.qualcomm.com> Cc: <stable@vger.kernel.org> # v5.8+ Reviewed-by: Vladimir Zapolskiy <vladimir.zapolskiy@linaro.org> Reviewed-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Reviewed-by: Loic Poulain <loic.poulain@oss.qualcomm.com> Signed-off-by: Andi Shyti <andi.shyti@kernel.org> Link: https://lore.kernel.org/r/20260625-cci-v1-1-a100cda673ce@oss.qualcomm.com
Liem [Mon, 29 Jun 2026 02:38:29 +0000 (10:38 +0800)]
i2c: imx: Cancel hrtimer before clearing slave pointer
In i2c_imx_unreg_slave(), the slave pointer is set to NULL after
disabling interrupts. However, a pending interrupt might already
have started the hrtimer (i2c_imx_slave_timeout) before the pointer
was cleared. If the hrtimer fires after i2c_imx->slave is set to
NULL, the timer callback i2c_imx_slave_finish_op() will call
i2c_imx_slave_event() with a NULL slave pointer, which results in a
use-after-free / NULL pointer dereference.
Fix by canceling the hrtimer and waiting for it to complete after
disabling interrupts, before clearing the slave pointer.
Fixes: f7414cd6923f ("i2c: imx: support slave mode for imx I2C driver") Signed-off-by: Liem <liem16213@gmail.com> Cc: <stable@vger.kernel.org> # v5.11+ Acked-by: Carlos Song <carlos.song@nxp.com> Reviewed-by: Frank Li <Frank.Li@nxp.com> Signed-off-by: Andi Shyti <andi.shyti@kernel.org> Link: https://lore.kernel.org/r/20260629023829.152651-3-liem16213@gmail.com
Liem [Mon, 29 Jun 2026 02:38:28 +0000 (10:38 +0800)]
i2c: imx: Fix slave registration race and error handling
In i2c_imx_reg_slave(), the slave pointer was assigned before
pm_runtime_resume_and_get(). If pm_runtime_resume_and_get() failed,
the error path returned without clearing i2c_imx->slave, leaving it
non-NULL and causing all subsequent registration attempts to fail
with -EBUSY.
Additionally, because this driver uses a shared IRQ, the interrupt
handler i2c_imx_isr() can execute concurrently and, after acquiring
slave_lock, dereference i2c_imx->slave. The previous fix attempt
added a lockless i2c_imx->slave = NULL on the error path, but that
could race with the ISR under the lock and still cause a NULL pointer
dereference.
Fix both issues by deferring the assignment of i2c_imx->slave and
i2c_imx->last_slave_event to after a successful resume, and by
performing the assignment inside the slave_lock critical section.
This guarantees that the slave pointer is never left stale on the
error path and is always valid when observed by the interrupt handler.
Fixes: f7414cd6923f ("i2c: imx: support slave mode for imx I2C driver") Signed-off-by: Liem <liem16213@gmail.com> Cc: <stable@vger.kernel.org> # v5.11+ Reviewed-by: Frank Li <Frank.Li@nxp.com> Acked-by: Carlos Song <carlos.song@nxp.com> Signed-off-by: Andi Shyti <andi.shyti@kernel.org> Link: https://lore.kernel.org/r/20260629023829.152651-2-liem16213@gmail.com
Merge tag 'platform-drivers-x86-v7.2-4' of git://git.kernel.org/pub/scm/linux/kernel/git/pdx86/platform-drivers-x86
Pull x86 platform driver fix from Ilpo Järvinen:
- Fix ACPI _DSM function index and bitmask usage for Dell DW5826e
* tag 'platform-drivers-x86-v7.2-4' of git://git.kernel.org/pub/scm/linux/kernel/git/pdx86/platform-drivers-x86:
platform/x86: dell-dw5826e: fix ACPI _DSM function index and bitmask usage
Jonas Gorski [Fri, 17 Jul 2026 08:55:07 +0000 (10:55 +0200)]
i2c: iproc: reset bus after timeout if START_BUSY is stuck
If a transaction times out, the START_BUSY signal can stay up, and
subsequent transactaction attempts will fail as the bus is still
considered busy.
I can easily trigger this by attempting to read from an address with no
device, e.g. when running i2cdetect. After the first read times out, all
subsequent read attempts return busy.
To get to a working state again, the controller needs to be reset to
clear the START_BUSY signal. So check for START_BUSY still asserted on a
timeout, and do reset in case it is,
This is also done by the original non-upstream iproc-smbus driver
implementation [1].
Works around situations like:
bcm-iproc-2c 1803b000.i2c: transaction timed out
bcm-iproc-2c 1803b000.i2c: bus is busy
bcm-iproc-2c 1803b000.i2c: bus is busy
bcm-iproc-2c 1803b000.i2c: bus is busy
bcm-iproc-2c 1803b000.i2c: bus is busy
bcm-iproc-2c 1803b000.i2c: bus is busy
...
* tag 'hardening-v7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux:
selftests/seccomp: Fix pointer type mismatch build error
selftests/lkdtm: rename STACKLEAK_ERASING to KSTACK_ERASE
fortify: Disable -Wstringop-overread in tests
Bluetooth: SCO: give the socket its own sco_conn reference
sco_conn_del() drops a reference it does not own. It takes one transient
reference via sco_conn_hold_unless_zero() and releases it with the
sco_conn_put() that follows sco_sock_hold(); the additional put in the
!sk branch releases a second one:
conn = sco_conn_hold_unless_zero(conn);
...
sk = sco_sock_hold(conn);
sco_conn_unlock(conn);
sco_conn_put(conn);
if (!sk) {
sco_conn_put(conn);
return;
}
When close() races the controller's Disconnection Complete, sco_chan_del()
clears conn->sk and drops the socket's reference while sco_conn_del() is
running. sco_conn_del() then sees sk == NULL, its own put drops the count
to zero and frees the conn, and the second put writes to the freed kref:
BUG: KASAN: slab-use-after-free in sco_conn_put.part.0+0x1a/0x190
Write of size 4 at addr ffff8881099dec74 by task kworker/u17:3/413
Workqueue: hci1 hci_rx_work
Call Trace:
sco_conn_put.part.0+0x1a/0x190
hci_disconn_complete_evt+0x1ee/0x3e0
hci_event_packet+0x54a/0x650
hci_rx_work+0x321/0x3d0
Allocated by task 413:
sco_conn_add+0x72/0x1a0
sco_connect_cfm+0x88/0x670
Freed by task 413:
sco_conn_del.isra.0+0x3f/0xf0
hci_disconn_complete_evt+0x1ee/0x3e0
refcount_t: underflow; use-after-free.
The root cause is that the socket stores the connection without holding a
reference of its own. __sco_chan_add() does:
sco_pi(sk)->conn = conn;
so the socket borrows whatever reference its caller happened to hold, and
the callers paper over that with ad-hoc holds and puts. Give the socket a
counted reference instead: __sco_chan_add() takes one and it is released
together with the channel (sco_chan_del()) and in sco_sock_destruct().
With the socket holding its own reference, sco_conn_del() no longer needs
the extra put and the redundant hold in sco_conn_ready() goes away.
Making the socket own its reference means the connection is now actually
freed on the error paths of sco_connect() where it used to leak, which in
turn runs sco_conn_free() and its hci_conn_drop(conn->hcon). To keep the
hci_conn accounting balanced, make that ownership explicit as well:
sco_conn_add() consumes one hci_conn reference and the sco_conn owns it for
its lifetime. sco_connect() hands over the reference returned by
hci_connect_sco() and no longer drops it on the error paths;
sco_connect_cfm(), which is not given a reference, takes one with
hci_conn_hold() before handing it to sco_conn_add() (and drops it again if
the allocation fails); and the explicit hci_conn_hold() in sco_conn_ready()
is removed. Every reference then has a single, clear owner.
Fixes: e6720779ae61 ("Bluetooth: SCO: Use kref to track lifetime of sco_conn") Cc: stable@vger.kernel.org Suggested-by: Pauli Virtanen <pav@iki.fi> Signed-off-by: Aldo Ariel Panzardo <qwe.aldo@gmail.com> Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>