6.18.66-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 695/990 net/smc: fix lgr/lnk lifetime vs diag reader race
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mahanta Jambigi <[email protected]>
commit d7900fa51642fbc2a5a03354238e71050a7d391d upstream.
The diag dump walks the socket hash table under a read_lock and dereferences conn->lgr and conn->lnk. Several paths expose a window where a hashed socket has freed or partially freed conn/lgr/lnk state.
First, smc_conn_abort() calls smc_conn_free() during early handshake aborts while the socket is still hashed in SMC_INIT, synchronously freeing the lgr on the smc_lgr_cleanup_early() path without holding the hash write_lock. A concurrent diag reader can load a non-NULL conn->lgr and dereference it after the kfree. Skip the connection, link group and DMB attributes in __smc_diag_dump() for sockets in SMC_INIT or SMC_CLOSED or fallen back to TCP, and take diag_mode from an is_smcd flag cached at connection creation.
The state filter alone does not close the race. A connection aborted by a failed handshake can keep its alert token, because smc_conn_free() skips the unregister when smc_lgr_terminate_sched() has emptied lgr->list; close_work may also have been queued before the abort, as the CDC receive path is not excluded by the handshake's socket lock. smc_close_passive_work() would then move the hashed socket from SMC_INIT to SMC_APPCLOSEWAIT1 or SMC_PROCESSABORT, states the filter does not cover, and later run a passive-closing sock_put() that smc_connect_decline_fallback() dropped already. Return early from smc_close_passive_work() when the connection was freed; the check holds the socket lock that every smc_conn_free() caller holds as well, so a hashed socket with a freed connection stays in SMC_INIT or SMC_CLOSED until release.
This changes the sock_diag output for such sockets: the connection, link group and DMB attributes are omitted, which smcss does not read for sockets in these states, while SMC_DIAG_FALLBACK is still reported and an SMC-D socket in SMC_INIT or SMC_CLOSED still reports SMC_DIAG_MODE_SMCD from the cached flag. A fallback socket is a plain TCP socket with no SMC connection state to report; the stale conn fields left behind by smc_conn_abort() must not be read.
Second, in smc_conn_kill() on SMC-D with dmb_nocopy, smcd_buf_detach() NULLs and frees conn->sndbuf_desc while the socket is still hashed. A concurrent diag reader entering the CONNINFO block can dereference the freed descriptor. Unhash the socket right before smcd_buf_detach(). As a result, killed ACTIVE and APPCLOSEWAIT sockets that are still open are no longer visible to smcss on loopback-ism devices.
Third, in the terminal teardown branches of smc_close_active_abort() (PEERCLOSEWAIT and PROCESSABORT groups) and in smc_close_passive_work(), smc_conn_free() drops lgr and lnk references while the socket is still hashed. Unhash immediately before each smc_conn_free() call at those sites. Sockets killed in those close states are therefore unhashed, and their inuse accounting dropped, before close(), even if the fd is still open.
Fourth, use smp_load_acquire() / smp_store_release() on sk_state to order these checks on weakly ordered CPUs. A reader that observes SMC_ACTIVE is guaranteed to see the connection setup that preceded the store; a reader that observes SMC_CLOSED from smc_listen_out_err() skips the connection fields in any case, so that particular store is hardening kept for uniformity, not a required ordering.
Additionally, in __smc_diag_dump(), use the cached link->ibname instead of link->smcibdev->ibdev->name, avoiding a NULL pointer dereference or use-after-free of the IB device when __smcr_link_clear() zeroes the link during concurrent SMC-R link failover. The link data is still read without conns_lock or send_lock, so a dump racing a failover may transiently report zeroed or mixed link fields; this does not affect memory safety and the next dump reports the new link. Like the SMC netlink link dump and the tracepoints, the name is the one cached at link creation time.
--- net/smc/af_smc.c | 10 +++++----- net/smc/smc.h | 1 + net/smc/smc_close.c | 14 ++++++++++++++ net/smc/smc_core.c | 8 +++++++- net/smc/smc_diag.c | 12 ++++++++---- 5 files changed, 35 insertions(+), 10 deletions(-)
net/smc/af_smc.c +5 -5
@@ -976,7 +976,7 @@ static int smc_connect_fallback(struct ssmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; }
@@ -1381,7 +1381,7 @@ static int smc_connect_rdma(struct smc_ssmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; connect_abort:
@@ -1484,7 +1484,7 @@ static int smc_connect_ism(struct smc_sosmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; connect_abort:
@@ -1955,7 +1955,7 @@ static void smc_listen_out_connected(strstruct sock *newsmcsk = &new_smc->sk;if (newsmcsk->sk_state ==SMC_INIT ) - newsmcsk->sk_state =SMC_ACTIVE ; +smp_store_release (&newsmcsk->sk_state,SMC_ACTIVE );smc_listen_out (new_smc); }
@@ -1969,7 +1969,7 @@ static void smc_listen_out_err(struct smthis_cpu_inc (net->smc.smc_stats->srv_hshake_err_cnt);if (newsmcsk->sk_state ==SMC_INIT )sock_put (&new_smc->sk);/* passive closing */ - newsmcsk->sk_state =SMC_CLOSED ; +smp_store_release (&newsmcsk->sk_state,SMC_CLOSED );smc_listen_out (new_smc); }
net/smc/smc.h +1 -0
@@ -196,6 +196,7 @@ struct smc_connection {struct rb_node alert_node;struct smc_link_group *lgr;/* link group of connection */ struct smc_link *lnk;/* assigned SMC-R link */ +bool is_smcd;/* SMC-R or SMC-D connection */ u32 alert_token_local;/* unique conn. id */ u8 peer_rmbe_idx;/* from tcp handshake */ int peer_rmbe_size;/* size of peer rx buffer */
net/smc/smc_close.c +14 -0
@@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_sif (sk->sk_state !=SMC_PEERABORTWAIT )break ; sk->sk_state =SMC_CLOSED ; + sk->sk_prot->unhash (sk);smc_conn_free (&smc->conn); release_clcsock = true;sock_put (sk);/* passive closing */
@@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_sif (sk->sk_state !=SMC_PEERABORTWAIT )break ; sk->sk_state =SMC_CLOSED ; + sk->sk_prot->unhash (sk);smc_conn_free (&smc->conn); release_clcsock = true;break ;
@@ -367,6 +369,17 @@ static void smc_close_passive_work(struclock_sock (sk); old_state = sk->sk_state; +if (conn->freed) { +/* conn->freed is set under the socket lock, which is +* held here as well, so this cannot race with the free; the +* state machine and its postponed sock_put() are not owed +* anymore +*/ +release_sock (sk); +sock_put (sk);/* sock_hold done by schedulers of close_work */ +return ; + } + rxflags = &conn->local_rx_ctrl.conn_state_flags;if (rxflags->peer_conn_abort) {/* peer has not received all data */
@@ -433,6 +446,7 @@ wakeup: sk->sk_state_change (sk);if ((sk->sk_state ==SMC_CLOSED ) && (sock_flag (sk,SOCK_DEAD ) || !sk->sk_socket)) { + sk->sk_prot->unhash (sk);smc_conn_free (conn);if (smc->clcsock) release_clcsock = true;
net/smc/smc_core.c +7 -1
@@ -1516,8 +1516,10 @@ static void smc_conn_kill(struct smc_contasklet_kill (&conn->rx_tsklet); else tasklet_unlock_wait(&conn->rx_tsklet); -if (smc_ism_support_dmb_nocopy (conn->lgr->smcd)) +if (smc_ism_support_dmb_nocopy (conn->lgr->smcd)) { + smc->sk.sk_prot->unhash (&smc->sk);smcd_buf_detach (conn); + } }else {smc_cdc_wait_pend_tx_wr (conn); }
@@ -2037,6 +2039,10 @@ create: goto out; } } +/* cache the connection type: smc_diag reads it after +* smc_conn_free() dropped the link group reference +*/ + conn->is_smcd = conn->lgr->is_smcd;smc_lgr_hold (conn->lgr);/* lgr_put in smc_conn_free() */ if (!conn->lgr->is_smcd)smcr_link_hold (conn->lnk);/* link_put in smc_conn_free() */
net/smc/smc_diag.c +8 -4
@@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock * r =nlmsg_data (nlh);smc_diag_msg_common_fill (r, sk); - r->diag_state = sk->sk_state; + r->diag_state =smp_load_acquire (&sk->sk_state);if (smc->use_fallback) r->diag_mode =SMC_DIAG_MODE_FALLBACK_TCP ; -else if (smc_conn_lgr_valid (&smc->conn) && smc->conn.lgr->is_smcd) +else if (smc->conn.is_smcd) r->diag_mode =SMC_DIAG_MODE_SMCD ;else r->diag_mode =SMC_DIAG_MODE_SMCR ;
@@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *if (nla_put (skb,SMC_DIAG_FALLBACK ,sizeof (fallback), &fallback) <0 ) goto errout; +if (r->diag_state ==SMC_INIT || r->diag_state ==SMC_CLOSED || + smc->use_fallback) + goto out; +if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO -1 ))) && smc->conn.alert_token_local) {struct smc_connection *conn = &smc->conn;
@@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock * .lnk[0].link_id = link->link_id, }; -memcpy (linfo.lnk[0 ].ibname, link->smcibdev->ibdev->name, -sizeof (link->smcibdev->ibdev->name)); +memcpy (linfo.lnk[0 ].ibname, link->ibname,sizeof (link->ibname));smc_gid_be16_convert (linfo.lnk[0 ].gid, link->gid);smc_gid_be16_convert (linfo.lnk[0 ].peer_gid, link->peer_gid);
@@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock * goto errout; } +out:nlmsg_end (skb, nlh);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 696/990 net/smc: fix link group ownership in handshake abort
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mahanta Jambigi <[email protected]>
commit e227b511582828c5a6513f70fc6a71211e5efbf0 upstream.
An aborted first-contact handshake can hang the handshake worker on the socket lock it already holds, reset the clcsock of a socket that has fallen back to TCP, or corrupt the alert-node lookup when the handshake retries with the same connection.
The abort leaves a connection registered in a link group that another context has already unlinked for termination: smc_conn_free() skips the unregister when lgr->list is empty, so the alert token and alert node stay in lgr->conns_all. If the handshake retries another device or SMC version, smc_conn_create() creates a second link group and smc_lgr_register_conn() inserts the same alert node into it: the token loop is skipped, rb_link_node() links a node that is still in the old tree into the new one, and a second sock_hold() is taken where only one sock_put() will follow. The old group's terminator then keeps returning that node from rb_first() and can kill a connection that now belongs to the new group.
smc_lgr_cleanup_early() also starts a second termination of the link group that is already being terminated, which takes lock_sock() on the socket the handshake worker holds; if the termination work wins the race instead, it later kills the freed connection and aborts the clcsock of a socket that has fallen back to TCP. Making the unregister unconditional also lets smc_conn_free() reach the delayed free work on a claimed link group, where the lockless freeing check can arm it after the owner has cancelled it.
Always unregister the connection, claim a link group for termination once under lgr_lock, keep the link group alive across the abort, and arm the delayed free work only under the same lock and cancel it synchronously before the teardown. Drop an already freed connection in smc_conn_kill() without running the connection and socket teardown.
--- net/smc/af_smc.c | 11 ++++--- net/smc/smc_core.c | 78 ++++++++++++++++++++++++++++++++++++++--------------- net/smc/smc_core.h | 6 ++-- 3 files changed, 65 insertions(+), 30 deletions(-)
net/smc/af_smc.c +6 -5
@@ -1009,14 +1009,15 @@ static void smc_conn_abort(struct smc_so {struct smc_connection *conn = &smc->conn;struct smc_link_group *lgr = conn->lgr; -bool lgr_valid = false; - -if (smc_conn_lgr_valid (conn)) - lgr_valid = true; +bool lgr_valid = local_first &&smc_conn_lgr_valid (conn); +if (lgr_valid) +smc_lgr_hold (lgr);/* lgr_put below */ smc_conn_free (conn); -if (local_first && lgr_valid) +if (lgr_valid) {smc_lgr_cleanup_early (lgr); +smc_lgr_put (lgr); + } }/* check if there is a rdma device available for this connection. */
net/smc/smc_core.c +56 -22
143 lines not on this page · raw message
net/smc/smc_core.h +3 -3
@@ -297,9 +297,9 @@ struct smc_link_group {struct delayed_work free_work;/* delayed freeing of an lgr */ struct work_struct terminate_work;/* abnormal lgr termination */ struct workqueue_struct *tx_wq;/* wq for conn. tx workers */ - u8 sync_err : 1; /* lgr no longer fits to peer */ - u8 terminating : 1;/* lgr is terminating */ - u8 freeing : 1; /* lgr is being freed */ +u8 sync_err;/* lgr no longer fits to peer */ +u8 terminating;/* lgr is terminating */ +u8 freeing;/* lgr is being freed */ refcount_t refcnt;/* lgr reference count */ bool is_smcd;/* SMC-R or SMC-D */
Greg Kroah-Hartman
maintainerPATCH 687/990 btrfs: fix bio counter and bioc leak when async checksumming fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mani Tofigh <[email protected]>
commit d27d0039bc1334be8a72c769e14c0b0c3efc317d upstream.
A single failed checksum allocation can make a later device replace hang forever. btrfs_submit_chunk() takes a dev-replace bio counter reference and a bioc before it hands a write to the checksum worker. If the checksum fails there (e.g., its allocation fails), run_one_async_done() ends the bio but drops neither. The counter then never gets back to zero and the next replace waits for it:
[ 8.369] BTRFS info (device ram0): dev_replace from /dev/ram0 (devid 1) to /dev/ram1 finished [41.534] INFO: task btrfscsum:80 blocked for more than 20 seconds. [41.534] btrfs_rm_dev_replace_blocked+0x135/0x180 [41.534] btrfs_dev_replace_finishing+0xefe/0x13b0
The worker is only used when CONFIG_BTRFS_EXPERIMENTAL is off and the checksum isn't a fast one, e.g., sha256. We hit it on a sha256 filesystem.
We put the bioc and drop the counter in that error branch. We also put the bioc on the synchronous error path and on the btrfs_split_bio() error path, which both only drop the counter. With the fix, the replace doesn't hang anymore.
This bug was identified and confirmed with the help of fault-injection testing on a deterministic hypervisor currently under development. Our C reproducer however hits it within about 35s.
--- fs/btrfs/bio.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/btrfs/bio.c +4 -0
@@ -624,6 +624,8 @@ static void run_one_async_done(struct bt/* If an error occurred we just want to clean up the bio and move on. */ if (bio->bi_status) { +btrfs_put_bioc (async->bioc); +btrfs_bio_counter_dec (async->bbio->inode->root->fs_info);btrfs_bio_end_io (async->bbio, bio->bi_status);return ; }
@@ -759,6 +761,7 @@ static bool btrfs_submit_chunk(struct bt split =btrfs_split_bio (fs_info, bbio, map_length);if (IS_ERR (split)) { status =errno_to_blk_status (PTR_ERR (split)); +btrfs_put_bioc (bioc);btrfs_bio_counter_dec (fs_info); goto end_bbio; }
@@ -820,6 +823,7 @@ done:return map_length == length; fail: +btrfs_put_bioc (bioc);btrfs_bio_counter_dec (fs_info);/* * We have split the original bbio, now we have to end both the current
Greg Kroah-Hartman
maintainerPATCH 736/990 perf/hw_breakpoint: Clear stop state in hw_breakpoint_add()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paolo Bertinetti <[email protected]>
commit 6bea5e29daf123a78ae58cb5926023f4705f396f upstream.
Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.
hw_breakpoint_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_bp_event() drops every later hit, so a breakpoint re-armed this way delivers only its first overflow.
Set the state from PERF_EF_START on every add, as perf_swevent_add() does.
--- kernel/events/hw_breakpoint.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/events/hw_breakpoint.c +1 -2
@@ -967,8 +967,7 @@ static int hw_breakpoint_event_init(strustatic int hw_breakpoint_add (struct perf_event *bp,int flags) { -if (!(flags &PERF_EF_START )) - bp->hw.state =PERF_HES_STOPPED ; + bp->hw.state = (flags &PERF_EF_START ) ?0 :PERF_HES_STOPPED ;if (is_sampling_event (bp)) { bp->hw.last_period = bp->hw.sample_period;
Greg Kroah-Hartman
maintainerPATCH 745/990 fs/adfs: bound directory entry name length in adfs_fplus_getnext()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
commit ebf5025b0d989f95542fc9da899b7de2fec499f2 upstream.
adfs_fplus_getnext() reads the per-entry name length bigdirobnamelen straight from the on-disk big directory and passes it to adfs_dir_copyfrom() as the copy length into obj->name[], a fixed ADFS_MAX_NAME_LEN (260) byte buffer. adfs_dir_copyfrom() only bounds the copy against the number of directory buffers, not the size of the destination, so a crafted image with bigdirobnamelen larger than the buffer overflows the stack-allocated object_info::name that adfs_fplus_iterate() passes in.
adfs_object_fixup() may additionally append a four byte ",xyz" filetype suffix, so the accepted length must also leave room for that.
The old-style directory parser (dir_f.c) already clamps names to ADFS_F_NAME_LEN, and adfs_fplus_validate_header() validates the header name fields, but the per-entry name length in the big directory format was never checked. Reject over-long entries, using -EIO as elsewhere in this file for a corrupt big directory.
--- fs/adfs/dir_fplus.c | 2 ++ 1 file changed, 2 insertions(+)
fs/adfs/dir_fplus.c +2 -0
@@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir, obj->indaddr =le32_to_cpu (bde.bigdirindaddr); obj->attr =le32_to_cpu (bde.bigdirattr); obj->name_len =le32_to_cpu (bde.bigdirobnamelen); +if (obj->name_len >ADFS_MAX_NAME_LEN -4 )/* leave room for ,xyz suffix */ +return -EIO ; offset =adfs_fplus_offset (h,le32_to_cpu (h->bigdirentries)); offset +=le32_to_cpu (bde.bigdirobnameptr);
Greg Kroah-Hartman
maintainerPATCH 746/990 fs/proc: fix the write length returned by proc_sys_call_handler()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
commit fbdc020ee1b82079102e493aaa7200de5f497a38 upstream.
proc_sys_call_handler() reads the write length from iov_iter_count() and copies that many bytes from the iterator into kbuf. A cgroup/sysctl BPF program can replace the new value through bpf_sysctl_set_new_value() and update count to the length of the replacement value. The handler then returns that adjusted count as the number of bytes written, even though the iterator originally held a different number of bytes.
If the replacement value is longer than the original input, ->write_iter() reports more bytes than the iterator held. splice(2) passes that value to iter_file_splice_write(), which subtracts it from the pipe length and walks past the pipe head:
Splice Exceeded! ret=7 tot=1 left=0
Oops: general protection fault RIP: 0010:iter_file_splice_write+0xb6f/0x1170
The write path consumes at most the original iterator length in copy_from_iter_full() before the BPF hook runs. Return the smaller of the adjusted and original counts on the write path, so an expanded BPF value cannot exceed the iterator while a handler that reports a shorter parsed length still produces a short write. The read path keeps using the adjusted count for copy_to_iter().
--- fs/proc/proc_sysctl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/proc/proc_sysctl.c +4 -1
@@ -557,6 +557,8 @@ static ssize_t proc_sys_call_handler(strstruct ctl_table_header *head =grab_header (inode);const struct ctl_table *table =PROC_I (inode)->sysctl_entry;size_t count =iov_iter_count (iter); +/* ->write_iter() must never report more than the iterator held */ +size_t orig_count = count;char *kbuf;ssize_t error;
@@ -607,7 +609,8 @@ static ssize_t proc_sys_call_handler(str goto out_free_buf; } - error = count; +/* the write path consumed at most the original iterator length */ + error = write ?min (count, orig_count) : count; out_free_buf:kvfree (kbuf); out:
Greg Kroah-Hartman
maintainerPATCH 747/990 fs/splice: clamp an over-reported write_iter result
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
commit 2d956723e82cddae8ff8e9da99a666217b02065f upstream.
iter_file_splice_write() builds a bvec iterator of at most sd.total_len - left bytes and passes it to ->write_iter(). It then subtracts the returned length from sd.total_len and walks the pipe buffers by that length. A ->write_iter() implementation that reports more bytes than the iterator held makes sd.total_len underflow and the dismissal loop advance pipe->tail past pipe->head, releasing a zeroed pipe buffer:
Splice Exceeded! ret=7 tot=1 left=0
Oops: general protection fault RIP: 0010:iter_file_splice_write+0xb6f/0x1170
Commit a3de58b12ce0 ("netfs: Fix unbuffered write error handling") added the warning for this condition but only reports it. Clamp the return value to the size of the iterator that was actually handed to ->write_iter(), so the pipe accounting stays consistent even when a producer violates the iterator contract.
--- fs/splice.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/splice.c +6 -3
@@ -739,9 +739,12 @@ iter_file_splice_write(struct pipe_inode sd.pos = kiocb.ki_pos;if (ret <=0 )break ; -WARN_ONCE (ret > sd.total_len - left, -"Splice Exceeded! ret=%zd tot=%zu left=%zu\n" , - ret, sd.total_len, left); +if (unlikely (ret > sd.total_len - left)) { +WARN_ONCE (1 , +"Splice Exceeded! ret=%zd tot=%zu left=%zu\n" , + ret, sd.total_len, left); + ret = sd.total_len - left; + } sd.num_spliced += ret; sd.total_len -= ret;
Greg Kroah-Hartman
maintainerPATCH 748/990 arm64/gcs: Ignore attempts to change GCS mode during signal return
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit d395db3dcd4c590d26a2f3d581d8d5b7ddbfa478 upstream.
If userspace tries to update the GCS mode as part of signal return then we update the thread state but don't update GCSCRE0_EL1, meaning the change does not take effect. We may also get issues for other tasks on context switch since we suppress writes of the register if the two tasks have the same mode.
Since no currently known userspace tries to use this functionality close this by ignoring any attempt to change the mode through signal return. The GCS mode for the current thread can be changed using the prctl() interface and will be preserved on signal return, allowing updates to the mode from the signal handler.
--- Documentation/arch/arm64/gcs.rst | 13 ++++--------- arch/arm64/kernel/signal.c | 22 +--------------------- 2 files changed, 5 insertions(+), 30 deletions(-)
Documentation/arch/arm64/gcs.rst +4 -9
@@ -179,9 +179,8 @@ intended to be exhaustive. When returning from a signal handler: -* If there is a gcs_context record in the signal frame then the GCS flags - and GCSPR_EL0 will be restored from that context prior to further - validation. +* If there is a gcs_context record in the signal frame then GCSPR_EL0 + will be restored from that context prior to further validation. * If there is no gcs_context record in the signal frame then the GCS configuration will be unchanged.
@@ -190,12 +189,8 @@ When returning from a signal handler: point to a valid GCS signal cap record, this will be popped from the GCS prior to signal return. -* If the GCS configuration is locked when returning from a signal then any - attempt to change the GCS configuration will be treated as an error. This - is true even if GCS was not enabled prior to signal entry. - -* GCS may be disabled via signal return but any attempt to enable GCS via - signal return will be rejected. +* The features_enabled in the signal return context will be ignored; any + changes made using the prctl() in the signal handler will be preserved. 6. ptrace extensions
arch/arm64/kernel/signal.c +1 -21
@@ -741,36 +741,16 @@ static int preserve_gcs_context(struct gstatic int restore_gcs_context (struct user_ctxs *user) { -u64 gcspr, enabled; +u64 gcspr;int err =0 ;if (user->gcs_size !=sizeof (*user->gcs))return -EINVAL ;__get_user_error (gcspr, &user->gcs->gcspr, err); -__get_user_error (enabled, &user->gcs->features_enabled, err);if (err)return err; -/* Don't allow unknown modes */ -if (enabled & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK ) -return -EINVAL ; - - err =gcs_check_locked (current, enabled); -if (err !=0 ) -return err; - -/* Don't allow enabling */ -if (!task_gcs_el0_enabled (current) && - (enabled &PR_SHADOW_STACK_ENABLE )) -return -EINVAL ; - -/* If we are disabling disable everything */ -if (!(enabled &PR_SHADOW_STACK_ENABLE )) - enabled =0 ; - - current->thread.gcs_el0_mode = enabled; -/* * We let userspace set GCSPR_EL0 to anything here, we will * validate later in gcs_restore_signal().
Greg Kroah-Hartman
maintainerPATCH 749/990 arm64: errata: Add Cortex-A715/A720 AMU core counter workaround
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Beata Michalska <[email protected]>
commit be777145858218f591b4d9d19f3d40d3ecea9de3 upstream.
On Cortex-A715 (erratum 2738462) and Cortex-A720 (erratum 2738461), the AMEVCNTR00 counter may continue incrementing while the core remains in WFE with the clocks being enabled. The resulting core cycle count may become unreliable.
Add a workaround that effectively treats the AMU counter as unavailable.
--- Documentation/arch/arm64/silicon-errata.rst | 4 +++ arch/arm64/Kconfig | 32 ++++++++++++++++++++++++++++ arch/arm64/kernel/cpu_errata.c | 20 +++++++++++++++++ arch/arm64/kernel/cpufeature.c | 3 +- arch/arm64/kernel/topology.c | 3 +- arch/arm64/tools/cpucaps | 1 6 files changed, 61 insertions(+), 2 deletions(-)
Documentation/arch/arm64/silicon-errata.rst +4 -0
@@ -162,8 +162,12 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #2645198 | ARM64_ERRATUM_2645198 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A715 | #2738462 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #3456084 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720 | #2738461 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A720 | #3456091 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A725 | #3456106 | ARM64_ERRATUM_3194386 |
arch/arm64/Kconfig +32 -0
@@ -1057,6 +1057,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONST # making it unreliable. As a result, AMU users should treat it as # unavailable rather than relying on misleading counter values. +config ARM64_WORKAROUND_BROKEN_AMU_CORECNT + bool + # Targeting errata affecting AMEVCNTR00, the AMU core cycle counter. + # On affected CPUs the counter may continue incrementing while core + # remains in WFE with the clocks enabled. + # This may lead to readings of said counter being unreliable. + # How much though depends on the sampling intervals. + +config ARM64_ERRATUM_2738461 + bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly" + depends on ARM64_AMU_EXTN + select ARM64_WORKAROUND_BROKEN_AMU_CORECNT + default y + help + This option adds the workaround for the following errata: + + * ARM Cortex-A715 erratum 2738462 + * ARM Cortex-A720 erratum 2738461 + + On affected cores the AMEVCNTR00 counter (AMU core frequency cycles + counter) may continue incrementing while the core remains in WFE + with the clocks being enabled. + This may result in inaccurate counter readings, with the magnitude + of the discrepancy depending on the sampling interval. + + With this workaround, reads of the affected counter return 0 in + the relevant paths. This causes users of the counter to treat it + as unavailable and is functionally equivalent to firmware disabling + the affected counter. + + If unsure, say Y. + config ARM64_ERRATUM_2457168 bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly" depends on ARM64_AMU_EXTN
arch/arm64/kernel/cpu_errata.c +20 -0
@@ -367,6 +367,18 @@ static const struct midr_range workaroun };#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */ +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT +static const struct midr_range workaround_amu_corecnt_list[] = { +#ifdef CONFIG_ARM64_ERRATUM_2738461 +/* Cortex-A715 r0p0 - r1p3 */ +MIDR_RANGE (MIDR_CORTEX_A715 ,0 ,0 ,1 ,3 ), +/* Cortex-A720 r0p0 - r0p1 */ +MIDR_RANGE (MIDR_CORTEX_A720 ,0 ,0 ,0 ,1 ), +#endif + {} +}; +#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */ +#ifdef CONFIG_CAVIUM_ERRATUM_23154 static const struct midr_range cavium_erratum_23154_cpus[] = { MIDR_ALL_VERSIONS(MIDR_THUNDERX),
@@ -891,6 +903,14 @@ const struct arm64_cpu_capabilities arm6 CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list) },#endif +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT + { + .desc = "Broken AMU AMEVCNTR00 (core cycle counter)", + .capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT, + .type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE, + CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list) + }, +#endif #ifdef CONFIG_ARM64_ERRATUM_2038923 { .desc = "ARM erratum 2038923",
arch/arm64/kernel/cpufeature.c +2 -1
@@ -2054,7 +2054,8 @@ static void cpu_amu_enable(struct arm64_cpumask_set_cpu (smp_processor_id (), &amu_cpus);/* 0 reference values signal broken/disabled counters */ -if (!this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT )) +if (!this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT ) && + !this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CORECNT ))update_freq_counters_refs (); } }
arch/arm64/kernel/topology.c +2 -1
@@ -420,7 +420,8 @@ static void cpu_read_corecnt(void *val)* counter read is properly handled as an error case by the users of the * counter. */ - *(u64 *)val =read_corecnt (); + *(u64 *)val =this_cpu_has_cap (ARM64_WORKAROUND_BROKEN_AMU_CORECNT ) ? +0UL :read_corecnt (); }static void cpu_read_constcnt (void *val)
arch/arm64/tools/cpucaps +1 -0
@@ -122,3 +122,4 @@ WORKAROUND_SPECULATIVE_AT WORKAROUND_SPECULATIVE_SSBS WORKAROUND_SPECULATIVE_UNPRIV_LOAD WORKAROUND_BROKEN_AMU_CONSTCNT +WORKAROUND_BROKEN_AMU_CORECNT
Greg Kroah-Hartman
maintainerPATCH 750/990 arm64: kexec_file: Do not use CMA for images with a non-zero text_offset
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinjie Ruan <[email protected]>
commit 18f2d01bfce99a885511c451cba95234eea190bc upstream.
image_load() adds text_offset to kernel_segment->mem and subtracts it from kernel_segment->memsz. For CMA backed segments this breaks the load path: the payload is copied to page_address(cma), which is the CMA base, while image->start is set to the adjusted address, so kexec jumps into the middle of the kernel. kimage_map_segment() has the same mismatch when a segment has been moved.
The adjusted memsz also breaks the release path: the CMA pages are freed using segment->memsz >> PAGE_SHIFT, which is fewer than were allocated, leaking the tail of the allocation.
Both problems are specific to CMA segments, which are accessed through page_address(cma) and ignore segment->mem. The normal load path uses segment->mem, so the text_offset adjustment stays consistent there. Keep honoring text_offset, but load such images from regular memory by setting image->no_cma: they lose the CMA contiguous allocation, but keep working.
--- arch/arm64/kernel/kexec_image.c | 7 +++++++ 1 file changed, 7 insertions(+)
arch/arm64/kernel/kexec_image.c +7 -0
@@ -82,6 +82,13 @@ static void *image_load(struct kimage *i kbuf.mem =KEXEC_BUF_MEM_UNKNOWN ; kbuf.memsz =le64_to_cpu (h->image_size); text_offset =le64_to_cpu (h->text_offset); +/* +* A CMA segment is loaded and mapped through page_address(cma), which +* is the CMA base and cannot represent the text_offset adjustment +* below. Load images with a non-zero text_offset from normal memory. +*/ +if (text_offset) + image->no_cma = true; kbuf.buf_align =MIN_KIMG_ALIGN ;/* Adjust kernel segment with TEXT_OFFSET */
Greg Kroah-Hartman
maintainerPATCH 751/990 arm64: ptrace: dont warn on missing siginfo in a group-stop
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Gongyi <[email protected]>
commit 5306f124f3171289b2ef5bac1e08aad175f66d1e upstream.
PTRACE_ATTACH to a group-stopped child can enter do_jobctl_trap(), which calls ptrace_stop() without siginfo. If the tracer writes NT_ARM_SYSTEM_CALL, system_call_set() can change syscallno from NO_SYSCALL before update_syscall_orig_x0_after_ptrace() checks last_siginfo. WARN_ON_ONCE(!info) then fires for a valid ptrace stop.
Keep the early return when siginfo is absent, but remove the warning. This leaves orig_x0 untouched at a non-seized group-stop and preserves the existing syscall-exit-stop handling.
--- arch/arm64/kernel/ptrace.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
arch/arm64/kernel/ptrace.c +6 -2
@@ -573,8 +573,12 @@ static void update_syscall_orig_x0_afterif (regs->syscallno ==NO_SYSCALL )return ; -/* We should only be called when target is in a ptrace stop */ -if (WARN_ON_ONCE (!info)) +/* +* For exit-stops, info is always non-NULL, but that's not true for other +* stops such as non-seized group-stops. In those cases, just return early +* as there's no need to update orig_x0 anyway. +*/ +if (!info)return ;/*
Greg Kroah-Hartman
maintainerPATCH 752/990 arm64: suspend: Save POR_EL0 over suspend
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit 2386c3dcf13e39d7576eae821af66537332c02de upstream.
POR_EL0 is a live EL0 register on systems with S1POE but it is not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with an UNKNOWN value. Fix this by saving and restoring the value over suspend.
This increases the size of struct cpu_suspend_ctx.
--- arch/arm64/include/asm/suspend.h | 2 +- arch/arm64/mm/proc.S | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@#ifndef __ASM_SUSPEND_H#define __ASM_SUSPEND_H -#define NR_CTX_REGS 15 +#define NR_CTX_REGS 16#define NR_CALLEE_SAVED_REGS 12/*
arch/arm64/mm/proc.S +8 -0
@@ -108,6 +108,10 @@ alternative_if ARM64_SME mrs_s x2, SYS_TPIDR2_EL0 str x2, [x0, #112] alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + mrs x2, REG_POR_EL0 + str x2, [x0, #120] +alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend)
@@ -150,6 +154,10 @@ alternative_if ARM64_SME ldr x2, [x0, #112] msr_s SYS_TPIDR2_EL0, x2 alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + ldr x2, [x0, #120] + msr REG_POR_EL0, x2 +alternative_else_nop_endif msr sctlr_el1, x12 set_this_cpu_offset x13
Greg Kroah-Hartman
maintainerPATCH 753/990 arm64: suspend: Save GCS state over suspend
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit 7ca488055c69eed71219546deb805811854aca35 upstream.
GCSCRE0_EL1 and GCSPR_EL0 are live registers for EL0 on systems with GCS but are not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with UNKNOWN or incorrect values for GCSPR_EL0 and GCSCRE0_EL1 (many fields in GCSCRE0_EL1 reset to 0). This will in turn lead to ongoing corruption, including not restoring mode until a task with a different GCS mode is run. Fix this by saving and restoring the values over suspend.
This increases the size of struct cpu_suspend_ctx by 16 bytes.
--- arch/arm64/include/asm/suspend.h | 2 +- arch/arm64/mm/proc.S | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@#ifndef __ASM_SUSPEND_H#define __ASM_SUSPEND_H -#define NR_CTX_REGS 16 +#define NR_CTX_REGS 18#define NR_CALLEE_SAVED_REGS 12/*
arch/arm64/mm/proc.S +12 -0
@@ -112,6 +112,12 @@ alternative_if ARM64_HAS_S1POE mrs x2, REG_POR_EL0 str x2, [x0, #120] alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + mrs x2, REG_GCSPR_EL0 + str x2, [x0, #128] + mrs x2, REG_GCSCRE0_EL1 + str x2, [x0, #136] +alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend)
@@ -158,6 +164,12 @@ alternative_if ARM64_HAS_S1POE ldr x2, [x0, #120] msr REG_POR_EL0, x2 alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + ldr x2, [x0, #128] + msr REG_GCSPR_EL0, x2 + ldr x2, [x0, #136] + msr REG_GCSCRE0_EL1, x2 +alternative_else_nop_endif msr sctlr_el1, x12 set_this_cpu_offset x13
Greg Kroah-Hartman
maintainerPATCH 754/990 cpufreq: acpi-cpufreq: fix P-state index mismatch in extract_io()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
commit 6bc092a0fc4d331a4adbbb664078af149c580834 upstream.
When policy->freq_table is built in acpi_cpufreq_cpu_init(), entries that are not lower in frequency than the previous one are skipped. For each remaining entry, freq_table[].driver_data stores the original ACPI P-state index, so the index space of freq_table no longer matches perf->states[].
extract_io() currently walks perf->states[] with index i and uses the same i to index policy->freq_table[i]. When duplicate frequencies exist, this can associate a P-state status with the frequency of a different P-state. It can also access an invalid or sentinel entry in freq_table when the number of entries in perf->states[] is greater than the number of entries remaining in the frequency table.
extract_io() is used on ACPI_ADR_SPACE_SYSTEM_IO platforms by the frequency verification path, which is enabled by the acpi_pstate_strict module parameter. With the mismatched lookup, check_freqs() can fail to match the frequency of the P-state that drv_write() has already programmed. It then sleeps through all 100 iterations - at least ~1 ms of usleep_range() plus 100 cross-CPU calls and I/O port reads, all with policy->rwsem held, and .target_index() returns -EAGAIN, leaving perf->state at its previous value while the hardware is running at the newly requested P-state.
The cpufreq core consequently keeps policy->cur at the old frequency. Since __cpufreq_driver_target() returns early when the requested frequency equals policy->cur, the driver is not called again for that frequency and the control register is not rewritten. The hardware can therefore remain at a frequency that differs from the frequency known to the cpufreq core.
Fix this by iterating over policy->freq_table and using pos->driver_data as the original ACPI P-state index when accessing perf->states[], as extract_msr() already does.
--- drivers/cpufreq/acpi-cpufreq.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/cpufreq/acpi-cpufreq.c +4 -5
@@ -197,14 +197,13 @@ static unsigned extract_io(struct cpufre {struct acpi_cpufreq_data *data = policy->driver_data;struct acpi_processor_performance *perf; -int i; +struct cpufreq_frequency_table *pos; perf =to_perf_data (data); -for (i =0 ; i < perf->state_count; i++) { -if (value == perf->states[i].status) -return policy->freq_table[i].frequency; - } +cpufreq_for_each_entry (pos, policy->freq_table) +if (value == perf->states[pos->driver_data].status) +return pos->frequency;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 737/990 PM: runtime: Update last_busy in rpm_resume() for active devices
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 55b2b8af704f845e01fa2f31ee259b07641ce3a9 upstream.
Setting an autosuspend delay for a device can be expected to cause a runtime suspend of the device after calling, say, pm_runtime_put() to be deferred, so the time between the last successful attempt to resume the device and its subsequent suspend is at least equal to the autosuspend delay.
However, that expectation is only met after the device has been actually resumed in rpm_resume() by invoking its runtime resume callback. If the runtime PM status of the device is already "active" when rpm_resume() runs for it, the device's last_busy timestamp is not updated which may allow a subsequent pm_runtime_put() invocation (or similar) to suspend it right away.
This is arguably inconsistent and confusing, so make rpm_resume() also update the device's last_busy timestamp when it finds that the device is already "active" and it is about to return 1 early.
--- drivers/base/power/runtime.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/base/power/runtime.c +6 -0
@@ -822,6 +822,12 @@ static int rpm_resume(struct device *devpm_runtime_deactivate_timer (dev);if (dev->power.runtime_status ==RPM_ACTIVE ) { +/* +* The attempt to resume the device means that it is needed for +* something, so update its last_busy timestamp as in the case +* in which it actually resumes below. +*/ +pm_runtime_mark_last_busy (dev); retval =1 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 755/990 cpufreq: Improve suspend-resume synchronization
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit eee2a44e4e2b41c0699919a550d41cc38daa4f42 upstream.
The suspend-resume synchronization in the cpufreq core is not perfect because the global cpufreq_suspended variable is set at the end of cpufreq_suspend() after stopping governors for all of the active policies, so the governor .limits() callback may run via cpufreq_governor_limits() after stopping the governor and before setting cpufreq_suspended which is questionable. Likewise, the governor .limits() callback may run between clearing cpufreq_suspended in cpufreq_resume() and starting the governor.
Address this by adding a per-policy "suspended" flag that is always read under the policy rwsem and is updated under it when the governor is stopped in cpufreq_suspend() and when the governor is restarted in cpufreq_resume().
Also make cpufreq_resume() use the cpus_read_lock guard to reflect what is done in cpufreq_suspend() and call cpufreq_exit_governor() for policies that were suspended during a system suspend transition and are inactive during the subsequent system resume (to avoid leaking an inactive policy with a stopped governor that has not exited yet).
--- drivers/cpufreq/cpufreq.c | 86 +++++++++++++++++++++++++++++++++------------- include/linux/cpufreq.h | 3 + 2 files changed, 66 insertions(+), 23 deletions(-)
drivers/cpufreq/cpufreq.c +63 -23
@@ -35,6 +35,9 @@static LIST_HEAD (cpufreq_policy_list);/* Macros to iterate over CPU policies */ +#define for_each_policy (__policy) \ + list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) +#define for_each_suitable_policy (__policy, __active) \ list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \ if ((__active) == !policy_is_inactive(__policy))
@@ -1962,6 +1965,14 @@ int cpufreq_generic_suspend(struct cpufr }EXPORT_SYMBOL (cpufreq_generic_suspend); +static void cpufreq_suspend_policy (struct cpufreq_policy *policy) +{ +guard (cpufreq_policy_write)(policy); + +cpufreq_stop_governor (policy); + policy->suspended = true; +} +/** * cpufreq_suspend() - Suspend CPUFreq governors. *
@@ -1984,11 +1995,8 @@ void cpufreq_suspend(void)pr_debug ("%s: Suspending Governors\n" , __func__);for_each_active_policy (policy) { -if (has_target ()) { - scoped_guard(cpufreq_policy_write, policy) { -cpufreq_stop_governor (policy); - } - } +if (has_target ()) +cpufreq_suspend_policy (policy);if (cpufreq_driver->suspend && cpufreq_driver->suspend (policy)) pr_err("%s: Failed to suspend driver: %s\n", __func__,
@@ -2000,6 +2008,32 @@ suspend:cpus_read_unlock (); } +static void cpufreq_resume_policy (struct cpufreq_policy *policy,bool start) +{ +guard (cpufreq_policy_write)(policy); + +if (!policy->suspended) +return ; + + policy->suspended = false; + +if (policy_is_inactive (policy)) { +/* +* The policy was active when it was suspended, so its governor +* is still there. Let the governor go. +*/ +cpufreq_exit_governor (policy); +return ; + } + +if (!start) +return ; + +if (cpufreq_start_governor (policy)) +pr_err ("%s: Failed to start governor for CPU%u's policy\n" , + __func__, policy->cpu); +} +/** * cpufreq_resume() - Resume CPUFreq governors. *
@@ -2009,11 +2043,12 @@ suspend:void cpufreq_resume (void ) {struct cpufreq_policy *policy; -int ret;if (!cpufreq_driver)return ; +guard (cpus_read_lock)(); +if (unlikely (!cpufreq_suspended))return ;
@@ -2024,19 +2059,18 @@ void cpufreq_resume(void)pr_debug ("%s: Resuming Governors\n" , __func__); -for_each_active_policy (policy) { -if (cpufreq_driver->resume && cpufreq_driver->resume (policy)) { -pr_err ("%s: Failed to resume driver: %s\n" , __func__, - cpufreq_driver->name); - }else if (has_target ()) { - scoped_guard(cpufreq_policy_write, policy) { - ret =cpufreq_start_governor (policy); - } +for_each_policy (policy) { +int ret =0 ; +if (cpufreq_driver->resume && !policy_is_inactive (policy)) { + ret = cpufreq_driver->resume (policy);if (ret) -pr_err ("%s: Failed to start governor for CPU%u's policy\n" , - __func__, policy->cpu); +pr_err ("%s: Failed to resume driver: %s\n" , __func__, + cpufreq_driver->name); } + +if (has_target ()) +cpufreq_resume_policy (policy, ret ==0 ); } }
@@ -2410,12 +2444,17 @@ __weak struct cpufreq_governor *cpufreq_return NULL ; } +static bool cpufreq_is_suspended (struct cpufreq_policy *policy) +{ +return cpufreq_suspended || policy->suspended; +} +static int cpufreq_init_governor (struct cpufreq_policy *policy) {int ret; -/* Don't start any governor operations if we are entering suspend */ -if (cpufreq_suspended) +/* Don't start any governor operations for suspended policies. */ +if (cpufreq_is_suspended (policy))return 0 ;/* * Governor might not be initiated here if ACPI _PPC changed
@@ -2458,7 +2497,7 @@ static int cpufreq_init_governor(structstatic void cpufreq_exit_governor (struct cpufreq_policy *policy) { -if (cpufreq_suspended || !policy->governor) +if (cpufreq_is_suspended (policy) || !policy->governor)return ;pr_debug ("%s: for CPU %u\n" , __func__, policy->cpu);
@@ -2473,7 +2512,7 @@ int cpufreq_start_governor(struct cpufre {int ret; -if (cpufreq_suspended) +if (cpufreq_is_suspended (policy))return 0 ;if (!policy->governor)
@@ -2497,7 +2536,7 @@ int cpufreq_start_governor(struct cpufrevoid cpufreq_stop_governor (struct cpufreq_policy *policy) { -if (cpufreq_suspended || !policy->governor) +if (cpufreq_is_suspended (policy) || !policy->governor)return ;pr_debug ("%s: for CPU %u\n" , __func__, policy->cpu);
@@ -2508,7 +2547,7 @@ void cpufreq_stop_governor(struct cpufrestatic void cpufreq_governor_limits (struct cpufreq_policy *policy) { -if (cpufreq_suspended || !policy->governor) +if (cpufreq_is_suspended (policy) || !policy->governor)return ;pr_debug ("%s: for CPU %u\n" , __func__, policy->cpu);
@@ -2736,7 +2775,8 @@ static void cpufreq_policy_refresh(struc* -> ask driver for current freq and notify governors about a change */ if (cpufreq_driver->get &&has_target () && - (cpufreq_suspended ||WARN_ON (!cpufreq_verify_current_freq (policy, false)))) + (cpufreq_is_suspended (policy) || +WARN_ON (!cpufreq_verify_current_freq (policy, false))))return ;refresh_frequency_limits (policy);
include/linux/cpufreq.h +3 -0
@@ -145,6 +145,9 @@ struct cpufreq_policy {/* Per policy boost supported flag. */ bool boost_supported; +/* The policy has been suspended. */ +bool suspended; +/* Cached frequency lookup from cpufreq_driver_resolve_freq. */ unsigned int cached_target_freq;unsigned int cached_resolved_idx;
Greg Kroah-Hartman
maintainerPATCH 756/990 cpufreq: intel_pstate: Clear last written P-state value on suspend
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 02e77af824d5be3a94fdd885835a352f90d24c5c upstream.
Preserving cpu->pstate.current_pstate across system suspend-resume cycles, when running in the passive mode with HWP disabled, is a mistake because its value from before system suspend may become stale after the subsequent system resume and in some cases it prevents MSR_IA32_PERF_CTL from being updated properly after system resume [1].
Address this by clearing cpu->pstate.current_pstate after the governor has been stopped during system suspend.
--- drivers/cpufreq/intel_pstate.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/cpufreq/intel_pstate.c +13 -1
@@ -3412,10 +3412,11 @@ static void intel_cpufreq_cpu_exit(strucstatic int intel_cpufreq_suspend (struct cpufreq_policy *policy) { +struct cpudata *cpu = all_cpu_data[policy->cpu]; +intel_pstate_suspend (policy);if (hwp_active) { -struct cpudata *cpu = all_cpu_data[policy->cpu];u64 value =READ_ONCE (cpu->hwp_req_cached);/*
@@ -3426,6 +3427,17 @@ static int intel_cpufreq_suspend(struct value &= ~HWP_DESIRED_PERF (~0L );wrmsrq_on_cpu (cpu->cpu,MSR_HWP_REQUEST , value);WRITE_ONCE (cpu->hwp_req_cached, value); + }else { +/* +* Invalidate the cached P-state value that may be stale when +* the governor is started again during resume and may prevent +* MSR_IA32_PERF_CTL from being updated. +* +* This does not require synchronization because the core +* prevents frequency updates for suspended policies from +* occurring. +*/ + cpu->pstate.current_pstate =0 ; }return 0 ;
Greg Kroah-Hartman
maintainerPATCH 757/990 cpufreq: intel_pstate: Use rdmsrq_safe() to read MSR_MISC_PWR_MGMT
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Zhaoxin <[email protected]>
commit 2c0e6f2858d235c99f7ba4621bd176cd67226f00 upstream.
Commit ed7cad0504e3 ("cpufreq: intel_pstate: Relocate platform preference check") moved the intel_pstate_platform_pwr_mgmt_exists() call to the beginning of intel_pstate_init(), right after the vendor check, so it now runs before "no_load" (intel_pstate=disable) and the other checks.
MSR_MISC_PWR_MGMT is model-specific and KVM does not emulate it. In a KVM guest using a CPU model listed in intel_pstate_cpu_oob_ids[] (for example "-cpu host" on Emerald Rapids), reading it raises #GP and the unchecked rdmsrq() emits a warning with a call trace on every boot, even with intel_pstate=disable:
unchecked MSR access error: RDMSR from 0x1aa at rIP: 0xffffffffa4009342 (native_read_msr+0x2/0x50)
Call Trace: <TASK> intel_pstate_platform_pwr_mgmt_exists+0x3b/0x220 intel_pstate_init+0x1e/0x500 do_one_initcall+0x59/0x350 ...
Before that commit, such guests typically returned from intel_pstate_init() earlier, either because of intel_pstate=disable or because intel_pstate_msrs_not_valid() failed on the zero ratios that KVM reports in MSR_PLATFORM_INFO by default, so the MSR was not read.
Use rdmsrq_safe() and treat a failing read as "no OOB mode". The exception fixup already zeroes the result of a failed unchecked read, so apart from the warning going away there is no functional change.
--- drivers/cpufreq/intel_pstate.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/intel_pstate.c +2 -2
@@ -3683,12 +3683,12 @@ static struct acpi_platform_list plat_instatic bool __init intel_pstate_platform_pwr_mgmt_exists (void ) {const struct x86_cpu_id *id; -u64 misc_pwr; +u64 misc_pwr =0 ;int idx; id =x86_match_cpu (intel_pstate_cpu_oob_ids);if (id) { -rdmsrq (MSR_MISC_PWR_MGMT , misc_pwr); +rdmsrq_safe (MSR_MISC_PWR_MGMT , &misc_pwr);if (misc_pwr &BITMASK_OOB ) {pr_debug ("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n" );pr_debug ("P states are controlled in Out of Band mode by the firmware/hardware\n" );
Greg Kroah-Hartman
maintainerPATCH 758/990 cpufreq: Cache post-resolution target frequency in __resolve_freq()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 166207cac45191637c47a457a5c16ca6b6773a16 upstream.
get_next_freq() in the schedutil governor returns the resolved frequency from cpufreq_driver_resolve_freq(), and that resolved value is then passed to cpufreq_driver_fast_switch(). The only reader of cached_target_freq, acpi_cpufreq_fast_switch(), compares it with the post-resolution target frequency, but it holds the pre-resolution clamped frequency, so any request that falls between table entries misses the cache and falls back to a table scan.
Address this by making __resolve_freq() store the post-resolution frequency in cached_target_freq.
--- drivers/cpufreq/cpufreq.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/cpufreq.c +2 -2
@@ -509,8 +509,8 @@ static unsigned int __resolve_freq(struc idx =cpufreq_frequency_table_target (policy, target_freq, min, max, relation); policy->cached_resolved_idx = idx; - policy->cached_target_freq = target_freq; -return policy->freq_table[idx].frequency; + policy->cached_target_freq = policy->freq_table[idx].frequency; +return policy->cached_target_freq; }/**
Greg Kroah-Hartman
maintainerPATCH 759/990 software node: only let the owner release a managed node
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit f8623ce596492d2e96ca57eeec992938d3d79f00 upstream.
device_create_managed_software_node() creates a node whose lifetime is tied to the device it was created for. software_node_notify_remove() is called for every device that has the node as its fwnode (primary OR secondary) and, if the node is managed, unconditionally detaches it from that device and drops the creation reference.
This breaks when the node is shared with another device. Example: the i2c-designware copies the parent's fwnode to the adapter's struct device. When the adapter is deleted, it releases the reference that belongs to the owner and the latter ends up with a dangling pointer.
Record the device's "manager" and only perform the actual release when notify is called for that "owner" device.
Note that it was never the intention that managed software nodes would be shared, but descendants reusing ancestor firmware nodes is not uncommon and such use is hard to predict when allocating software nodes.
[ johan: drop temporary variable; skip clearing owner field;
mention reuse not intended in commit message ]
--- drivers/base/swnode.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/base/swnode.c +4 -3
@@ -29,6 +29,8 @@ struct swnode {struct fwnode_handle fwnode;const struct software_node *node;int id; +/* Device the managed node's lifetime is tied to. */ +struct device *owner;/* hierarchy */ struct ida child_ids;
@@ -37,7 +39,6 @@ struct swnode {struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; };static DEFINE_IDA (swnode_root_ids);
@@ -1060,7 +1061,7 @@ int device_create_managed_software_node(if (IS_ERR (fwnode))return PTR_ERR (fwnode); -to_swnode (fwnode)->managed = true; +to_swnode (fwnode)->owner = dev;set_secondary_fwnode (dev, fwnode);if (device_is_registered (dev))
@@ -1103,7 +1104,7 @@ void software_node_notify_remove(structsysfs_remove_link (&dev->kobj,"software_node" );kobject_put (&swnode->kobj); -if (swnode->managed) { +if (swnode->owner == dev) {set_secondary_fwnode (dev,NULL );kobject_put (&swnode->kobj); }
Greg Kroah-Hartman
maintainerPATCH 760/990 SUNRPC: Fix TCP-with-TLS transport class identification
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit 0502c7e7f171a8c9c892bdef89e6aa6f44d7b2a3 upstream.
xs_setup_tcp_tls() assigns the ordinary TCP transport class to a TCP-with-TLS transport. When rpc_clnt_add_xprt() is called with an unspecified transport type, it inherits the class identifier and can create an unencrypted TCP transport.
Looks like a copy-paste error from the commit 3 years ago.
NFSv4 trunk discovery uses an unspecified transport type when adding server-advertised addresses. If the additional transport passes server-identity validation, it can be admitted to the client's transport switch.
An isolated loopback test reproduced plaintext application RPC transmission for TLS- and mTLS-configured clients, including an unpinned TLS-client RPC that selected the added transport.
Assign the TCP-with-TLS class instead. With the fix, the plaintext-only test peer receives TLS negotiation probes but no application payloads.
--- net/sunrpc/xprtsock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/xprtsock.c +1 -1
@@ -3524,7 +3524,7 @@ static struct rpc_xprt *xs_setup_tcp_tls transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot =IPPROTO_TCP ; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload =RPC_MAX_FRAGMENT_SIZE ; xprt->bind_timeout =XS_BIND_TO ;
Greg Kroah-Hartman
maintainerPATCH 761/990 timekeeping: Read getboottime64() offsets under the sequence counter
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit 385b5ec1f31dd39297578eed42be74b07ae74017 upstream.
getboottime64() computes the wall-clock boot timestamp from offs_real minus offs_boot without checking tk_core.seq. A concurrent timekeeping update can leave the reader with an inconsistent pair of offsets or, on 32-bit systems, a torn 64-bit offset, producing an incorrect boot timestamp.
Read both offsets under tk_core.seq and retry if an update overlaps the sample. Convert the resulting local value to a timespec64 afterward.
--- kernel/time/timekeeping.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +7 -1
@@ -2419,7 +2419,13 @@ void update_wall_time(void)void getboottime64 (struct timespec64 *ts) {struct timekeeper *tk = &tk_core.timekeeper; -ktime_t t =ktime_sub (tk->offs_real, tk->offs_boot); +unsigned int seq; +ktime_t t; + +do { + seq =read_seqcount_begin (&tk_core.seq); + t =ktime_sub (tk->offs_real, tk->offs_boot); + }while (read_seqcount_retry (&tk_core.seq, seq)); *ts =ktime_to_timespec64 (t); }
Greg Kroah-Hartman
maintainerPATCH 762/990 timekeeping: Refresh auxiliary base before offset validation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit c1b96ba87e3caaa701d6dba254e58db7cc3c99be upstream.
timekeeping_forward_now() can advance an auxiliary timekeeper across a second boundary without refreshing tkr_mono.base. The negative-time check in __timekeeping_inject_offset() then uses the stale base and rejects valid ADJ_SETOFFSET adjustments with -EINVAL.
Refresh the derived timekeeper data before calculating the current auxiliary time, as aux_clock_set() already does.
On 7.4-rc1, a valid negative adjustment fails at the first second rollover. The patched kernel accepts all 12 tested rollover adjustments and continues to reject invalid negative offsets.
--- kernel/time/timekeeping.c | 1 + 1 file changed, 1 insertion(+)
kernel/time/timekeeping.c +1 -0
@@ -1503,6 +1503,7 @@ static int __timekeeping_inject_offset(sstruct tk_read_base *tkr_mono = &tks->tkr_mono;ktime_t now, offs; +tk_update_ktime_data (tks);/* Get the current time */ now =ktime_add_ns (tkr_mono->base,timekeeping_get_ns (tkr_mono));/* Add the relative offset change */
Greg Kroah-Hartman
maintainerPATCH 763/990 tpm: acpi: Fix memory leak at tpm_read_log_acpi() error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit 03fcb358249dc715124b3616f814ea0ecc6ec36c upstream.
When devm_add_action() returns an error, tpm_read_log_acpi() clears log->bios_event_log unnecessarily to NULL before calling tpm_bios_log_free(), and it would lead to a memory leak of the allocated log buffer.
Fix it by simply jumping to the err.
--- drivers/char/tpm/eventlog/acpi.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/char/tpm/eventlog/acpi.c +1 -3
@@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *c } ret =devm_add_action (&chip->dev, tpm_bios_log_free, log->bios_event_log); -if (ret) { - log->bios_event_log =NULL ; +if (ret) goto err; - }return format;
Greg Kroah-Hartman
maintainerPATCH 764/990 tpm: Check return value of crypto_kpp_set_secret()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
commit 8cff8f1c89d33e55c9af82177b14f6f9f6a899fe upstream.
crypto_kpp_set_secret() can fail, for example if the kernel is booted with fips=1 and the broken-by-design FIPS RNG used for ECC private key generation doesn't feel like generating random bytes at the moment. Check for error, cancelling the TPM session creation rather than proceeding with a zero or uninitialized private key.
--- drivers/char/tpm/tpm2-sessions.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm2-sessions.c +3 -1
@@ -535,7 +535,9 @@ static int tpm_buf_append_salt(struct tp }crypto_ecdh_encode_key (encoded_key, buf_len, &p);/* this generates a random private key */ -crypto_kpp_set_secret (kpp, encoded_key, buf_len); + rc =crypto_kpp_set_secret (kpp, encoded_key, buf_len); +if (rc) + goto err_free_kpp;/* salt is now the public point of this private key */ req =kpp_request_alloc (kpp,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 738/990 ASoC: SOF: ipc4-topology: Fix pin format leak in process widget setup
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baoli Zhang <[email protected]>
commit e5c09fe3f9c8d9da33b177ee432db15b6ab46884 upstream.
sof_ipc4_widget_setup_comp_process() allocates the input and output pin format arrays via sof_ipc4_get_audio_fmt(). When the following sof_ipc4_widget_setup_msg() fails, e.g. because the firmware does not provide a module matching the widget UUID, the error path jumps to the 'err' label, which frees the process struct and clears swidget->private but skips sof_ipc4_free_audio_fmt(). The arrays are then unreachable and are reported by kmemleak:
sof_ipc4_get_audio_fmt+0xc9/0x420 [snd_sof]
sof_ipc4_widget_setup_comp_process+0x8e/0x200 [snd_sof]
snd_sof_load_topology+0x71a/0x840 [snd_sof]
sof_pcm_probe+0x77/0x120 [snd_sof]
snd_soc_component_probe+0x21/0x60 [snd_soc_core]
...Jump to 'free_available_fmt' instead, as the other process widget error paths after sof_ipc4_get_audio_fmt() already do.
The other IPC4 widget setup functions (pga, mixer, src, asrc) free the audio formats in their common error label and are not affected.
--- sound/soc/sof/ipc4-topology.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/sof/ipc4-topology.c +1 -1
@@ -1205,7 +1205,7 @@ static int sof_ipc4_widget_setup_comp_pr ret =sof_ipc4_widget_setup_msg (swidget, &process->msg);if (ret) - goto err; + goto free_available_fmt;/* parse process init module payload config type from module info */ fw_module = swidget->module_info;
Greg Kroah-Hartman
maintainerPATCH 765/990 tpm: eventlog: check the payload size before reading tag events
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guanglei Zhu <[email protected]>
commit 0a385f668ba77d29ae167c1668fd452418ebc9d6 upstream.
The EVENT_TAG branch of get_event_name() casts the event payload to struct tcpa_pc_event and reads from it:
pc_event = (struct tcpa_pc_event *)event_entry;
switch (do_endian_conversion(pc_event->event_id)) {
...
for (i = 0; i < 20; i++)
d_len += sprintf(&data[2*i], "%02x",
pc_event->event_data[i]);The log iterators only verify that the event header plus the declared event_size stays within the log buffer; they do not require the payload of an EVENT_TAG entry to be large enough for the fields the branch reads. A truncated entry makes the branch read up to 20 bytes of event_data[] past the end of the entry, and, for the last entry in the log, past the end of the buffer itself.
The legacy PC Client spec defines the EV_EVENT_TAG payload as a TCPA_PC_EVENT - event_id, event_size and event-type-specific data - so a conformant entry carries the 8-byte header and the hash-type ids carry a full digest. The log itself, however, is an ACPI table the firmware leaves in memory: the TPM never measures the log, so the kernel cannot tell a conformant log from a corrupted one. The iterators already work on that assumption - they stop once the declared event_size runs past the buffer end - and the readers should apply the same rule to what they take off the payload.
Skip entries whose payload cannot even hold the event id, and skip the 20-byte digest dump when the payload cannot hold the full tcpa_pc_event header plus the digest, so the branch never reads beyond the entry it is formatting.
--- drivers/char/tpm/eventlog/tpm1.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/char/tpm/eventlog/tpm1.c +7 -0
@@ -178,6 +178,10 @@ static int get_event_name(char *dest, st }break ;case EVENT_TAG : +if (do_endian_conversion (event->event_size) < +sizeof (pc_event->event_id)) +break ; + pc_event = (struct tcpa_pc_event *)event_entry;/* ToDo Row data -> Base64 */
@@ -203,6 +207,9 @@ static int get_event_name(char *dest, st name = tcpa_pc_event_id_strings[do_endian_conversion (pc_event->event_id)]; n_len =strlen (name); +if (do_endian_conversion (event->event_size) < +sizeof (struct tcpa_pc_event ) +20 ) +break ;for (i =0 ; i <20 ; i++) d_len +=sprintf (&data[2 *i],"%02x" , pc_event->event_data[i]);
Greg Kroah-Hartman
maintainerPATCH 766/990 tpm: flush timeout work outside buffer_mutex to avoid deadlock
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunjung Ko <[email protected]>
commit c22052a012698ce56d599d75b669d55778521c7c upstream.
tpm_common_read() calls flush_work(&priv->timeout_work) under priv->buffer_mutex, but tpm_timeout_work() also takes buffer_mutex, so a running timeout work deadlocks the flush. Flush after unlocking; the timer is deleted under the lock, so no new work can be queued.
--- drivers/char/tpm/tpm-dev-common.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm-dev-common.c +11 -1
@@ -132,6 +132,7 @@ ssize_t tpm_common_read(struct file *fil {struct file_priv *priv = file->private_data;ssize_t ret_size =0 ; +bool flush = false;int rc;if (!size)
@@ -164,9 +165,18 @@ out:if (!priv->response_length) { *off =0 ;timer_delete_sync (&priv->user_read_timer); -flush_work (&priv->timeout_work); + flush = true; }mutex_unlock (&priv->buffer_mutex); + +/* +* tpm_timeout_work() takes buffer_mutex, so flush it after dropping +* the mutex to avoid a deadlock; the timer is deleted above, so no new +* timeout work can be queued once the mutex is released. +*/ +if (flush) +flush_work (&priv->timeout_work); +return ret_size; }
Greg Kroah-Hartman
maintainerPATCH 767/990 spi: tegra210-quad: Track DMA mapping state
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vishwaroop A <[email protected]>
commit 7b9e6f7bc13c0259b192d0a964e802d4ad53b8b8 upstream.
tegra_qspi_dma_unmap_xfer() assumes a streaming mapping is always outstanding and recomputes its length from the live tqspi->curr_dma_words. Nothing records whether tegra_qspi_dma_map_xfer() mapped anything, so neither assumption holds.
For a multi-chunk transfer, handle_dma_based_xfer() unmaps the chunk that just completed, recalculates the parameters for the next chunk, which overwrites curr_dma_words, and re-arms the hardware. If tegra_qspi_start_dma_based_transfer() then fails at its tegra_qspi_dma_map_xfer() call, nothing is mapped. That early return also sits above the smp_store_release() that clears tqspi->trans_status, so the previous chunk's QSPI_RDY survives, and the re-arm's return value is never checked, so handle_dma_based_xfer() returns IRQ_HANDLED without completing the transfer.
The caller times out, tegra_qspi_handle_timeout() sees the stale QSPI_RDY, concludes the transfer completed and calls handle_dma_based_xfer() again. No DMA completion arrives, so num_errors is incremented and tegra_qspi_dma_unmap_xfer() runs with nothing mapped. t->tx_dma then holds either the DMA_MAPPING_ERROR sentinel or, if the RX mapping was the one that failed, the preceding chunk's address that has already been released. Behind an IOMMU the latter frees an IOVA that may since have been reallocated.
Record whether a mapping is outstanding and the length that was mapped, and return early from tegra_qspi_dma_unmap_xfer() when there is nothing to release. is_dma_mapped is only updated under tqspi->lock, or on the timeout path after synchronize_irq() and cancel_work_sync() have quiesced the ISR and the bottom half.
Also skip releasing the TX mapping on the RX failure path unless a TX mapping was created; t->tx_dma is uninitialised when t->tx_buf is NULL.
--- drivers/spi/spi-tegra210-quad.c | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-)
drivers/spi/spi-tegra210-quad.c +25 -6
@@ -215,6 +215,17 @@ struct tegra_qspi {bool is_packed;bool use_dma; +/* +* Set while a streaming mapping created by +* tegra_qspi_dma_map_xfer() is outstanding, together with the +* length that was handed to dma_map_single(). is_curr_dma_xfer +* only records that the last armed chunk took the DMA path, +* which is not the same thing: a chunk whose mapping failed +* leaves the DMA path flagged with nothing mapped. +*/ +bool is_dma_mapped; +unsigned int dma_map_len; +u32 command1_reg;u32 dma_control_reg;u32 def_command1_reg;
@@ -584,24 +595,32 @@ static int tegra_qspi_dma_map_xfer(strucif (t->rx_buf) { t->rx_dma =dma_map_single (tqspi->rx_dma_dev, (void *)rx_buf, len,DMA_FROM_DEVICE );if (dma_mapping_error (tqspi->rx_dma_dev, t->rx_dma)) { -dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, len,DMA_TO_DEVICE ); +if (t->tx_buf) +dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, + len,DMA_TO_DEVICE );return -ENOMEM ; } } + tqspi->dma_map_len = len; + tqspi->is_dma_mapped = true; +return 0 ; }static void tegra_qspi_dma_unmap_xfer (struct tegra_qspi *tqspi,struct spi_transfer *t) { -unsigned int len; - - len =DIV_ROUND_UP (tqspi->curr_dma_words * tqspi->bytes_per_word,4 ) *4 ; +if (!tqspi->is_dma_mapped) +return ;if (t->tx_buf) -dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, len,DMA_TO_DEVICE ); +dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, + tqspi->dma_map_len,DMA_TO_DEVICE );if (t->rx_buf) -dma_unmap_single (tqspi->rx_dma_dev, t->rx_dma, len,DMA_FROM_DEVICE ); +dma_unmap_single (tqspi->rx_dma_dev, t->rx_dma, + tqspi->dma_map_len,DMA_FROM_DEVICE ); + + tqspi->is_dma_mapped = false; }static int tegra_qspi_start_dma_based_transfer (struct tegra_qspi *tqspi,struct spi_transfer *t)
Greg Kroah-Hartman
maintainerPATCH 768/990 watchdog: npcm: fix clock prepare leak when setting timeout on a running watchdog
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Feng <[email protected]>
commit 57c7cbe21acc77291ec0fbdd4bd72aa259cf4986 upstream.
npcm_wdt_start() unconditionally prepares and enables the watchdog clock, and npcm_wdt_stop() is the only place that disables it. npcm_wdt_set_timeout() calls npcm_wdt_start() again whenever the watchdog is already active, so every WDIOC_SETTIMEOUT ioctl issued while the watchdog is running takes one extra clock prepare/enable reference that is never dropped.
Split the register programming out of npcm_wdt_start() into a __npcm_wdt_start() helper that assumes the clock is already running, and call the helper from npcm_wdt_set_timeout() instead; only the watchdog .start callback (and the restart path, which intentionally keeps the clock) now acquires the clock.
--- drivers/watchdog/npcm_wdt.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/watchdog/npcm_wdt.c +11 -4
@@ -63,13 +63,11 @@ static int npcm_wdt_ping(struct watchdogreturn 0 ; } -static int npcm_wdt_start (struct watchdog_device *wdd) +static void __npcm_wdt_start (struct watchdog_device *wdd) {struct npcm_wdt *wdt =to_npcm_wdt (wdd);u32 val; -clk_prepare_enable (wdt->clk); -if (wdd->timeout <2 ) val =0x800 ;else if (wdd->timeout <3 )
@@ -94,6 +92,15 @@ static int npcm_wdt_start(struct watchdo val |=NPCM_WTRE |NPCM_WTE |NPCM_WTR |NPCM_WTIE ;writel (val, wdt->reg); +} + +static int npcm_wdt_start (struct watchdog_device *wdd) +{ +struct npcm_wdt *wdt =to_npcm_wdt (wdd); + +clk_prepare_enable (wdt->clk); + +__npcm_wdt_start (wdd);return 0 ; }
@@ -134,7 +141,7 @@ static int npcm_wdt_set_timeout(struct w wdd->timeout =2750 ;if (watchdog_active (wdd)) -npcm_wdt_start (wdd); +__npcm_wdt_start (wdd);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 769/990 x86/CPU/AMD: Dont print reset reason in VMs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jason Andryuk <[email protected]>
commit ea51d1a4c31fc8320c34f897dc5296a0bfc5c7ca upstream.
print_s5_reset_status_mmio() expects to read FCH MMIO on baremetal. VMs don't have emulated FCH registers, so there is nothing to check. Add an early exit when running on a hypervisor.
The real motivation is Xen PV domUs can't boot on Zen CPUs. PV domUs PTEs contain system physical addresses - they don't have the concept of guest physical addresses. domUs can only map physical addresses they are assigned, so a domU fails to map the FCH MMIO addresses.
However set_pte() does not return failure, so ioremap() returns a pointer while the PTEs are unpopulated. print_s5_reset_status_mmio() faults when reading through the pointer, breaking the boot.
Limit the reset reason printing to baremetal only where it actually makes sense.
[ bp: Massage commit message. ]
--- arch/x86/kernel/cpu/amd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/amd.c +2 -1
@@ -1370,7 +1370,8 @@ static __init int print_s5_reset_status_u32 value;int i; -if (!cpu_feature_enabled (X86_FEATURE_ZEN )) +if (!cpu_feature_enabled (X86_FEATURE_ZEN ) || +cpu_feature_enabled (X86_FEATURE_HYPERVISOR ))return 0 ; addr =ioremap (FCH_PM_BASE +FCH_PM_S5_RESET_STATUS ,sizeof (value));
Greg Kroah-Hartman
maintainerPATCH 770/990 x86/mm: Ensure write visibility during LDT installation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Hansen <[email protected]>
commit 0dc2a4dac3d04e9e4479aeb0b46172feab1cca0a upstream.
During LDT installation, the intent is to overwrite the old per-mm LDT value, then send an IPI to the mm user CPUs to have each load the new value.
But there is an ordering problem: a new mm user CPU sets itself in mm_cpumask() and then reads mm->context.ldt. The LDT-installing CPU writes mm->context.ldt and then reads mm_cpumask(). But, there is nothing which orders the LDT installation side actions. The CPU can read mm_cpumask() before its write becomes visible.
Ensure that new mm user CPUs see the new mm->context.ldt. Make mm->context.ldt visible before reading mm_cpumask().
Also convert the smp_store_release() over to a WRITE_ONCE(). smp_store_release() has an internal barrier which is weaker than the new smp_mb(). Avoid an extra barrier by converting it to WRITE_ONCE().
Also refresh/correct misleading comments. READ/WRITE_ONCE() do not "synchronize" anything themselves.
--- arch/x86/kernel/ldt.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
arch/x86/kernel/ldt.c +9 -3
@@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm) {struct ldt_struct *ldt; -/* READ_ONCE synchronizes with smp_store_release */ +/* Pairs with WRITE_ONCE() in install_ldt() */ ldt =READ_ONCE (mm->context.ldt);/*
@@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct {mutex_lock (&mm->context.lock); -/* Synchronizes with READ_ONCE in load_mm_ldt. */ -smp_store_release (&mm->context.ldt, ldt); +/* +* Ensure that new mm user CPUs either see the new LDT value +* or get an IPI. Make the store visible before reading +* mm_cpumask(). New mm users make their mm_cpumask() writes +* visible before reading mm->context.ldt. +*/ +WRITE_ONCE (mm->context.ldt, ldt); +smp_mb ();/* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask (mm_cpumask (mm), flush_ldt, mm, true);
Greg Kroah-Hartman
maintainerPATCH 771/990 x86/video: Preserve the default VGA fallback for legacy modes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hengyu Liang <[email protected]>
commit 3b4c98b47ba7c3c57bcf54fb85f54a854622041c upstream.
Commit
596b3678326d ("x86/video: Only fall back to vga_default_device() without screen info")
made video_is_primary_device() rely exclusively on screen_info resources whenever any are available.
However, screen_info_resources() also returns legacy I/O and memory ranges for VGA text modes. These ranges are not PCI BARs, so pci_find_resource() does not find them and the default VGA fallback is skipped. As a result, no device is primary in VGA text mode.
On a SeaBIOS QEMU guest with bochs and VKMS, the boot VGA (bochs) loses its DRM boot_display attribute. VKMS registers fb0 and bochs registers fb1. VKMS is not a PCI device, so it is not primary either. With no primary device, fbcon keeps the console on fb0 and never remaps it to bochs. This can be checked with:
cat /sys/class/drm/card1/boot_display
stty -F /dev/tty1 size
Without the fix, boot_display is missing and tty1 is 48 rows by 128 columns. With it, boot_display contains 1 and tty1 is 50 rows by 160 columns. VKMS only makes the console part visible. Without VKMS, tty1 has the same size with and without the fix, but boot_display is still missing without it.
Use resource-based selection only for linear framebuffers. Fall back to vga_default_device() for legacy display modes, while keeping EFI and VESA framebuffer ownership authoritative.
--- arch/x86/video/video-common.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/video/video-common.c +1 -1
@@ -45,7 +45,7 @@ bool video_is_primary_device(struct devi#ifdef CONFIG_SCREEN_INFO numres =screen_info_resources (si, res,ARRAY_SIZE (res)); -if (numres >0 ) { +if (numres >0 &&__screen_info_has_lfb (screen_info_video_type (si))) {for (i =0 ; i < numres; ++i) {if (!(res[i].flags &IORESOURCE_MEM ))continue ;
Greg Kroah-Hartman
maintainerPATCH 772/990 xen/gntdev: fix deadlock between map ioctl and mmap
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 7620a997e4854c94eacebf0c2d453fbd78ccdb46 upstream.
Commit 45ca1afe2fd1 ("xen/gntdev: fix error handling in ioctl") moved copy_to_user() in gntdev_ioctl_map_grant_ref() under priv->lock. A fault in copy_to_user() takes mmap_lock, while gntdev_mmap() is called with mmap_lock held and takes priv->lock:
ioctl thread mmap thread
mutex_lock(&priv->lock)
mmap_write_lock(mm)
gntdev_mmap()
mutex_lock(&priv->lock) copy_to_user() faults
mmap_read_lock(mm)
Reproduced on Debian 6.12.111 in a Xen guest, with the ioctl argument on a MAP_PRIVATE file page that has not been written yet. sysrq-w:
task:repro state:D stack:0 pid:4479 tgid:4477 ppid:1 flags:0x00000000
rwsem_down_read_slowpath+0x25c/0x480 down_read_killable+0x48/0xc0 lock_mm_and_find_vma+0x96/0x250 do_user_addr_fault+0x12d/0x620 exc_page_fault+0x7e/0x180 asm_exc_page_fault+0x26/0x30 _copy_to_user+0x36/0x50 gntdev_ioctl+0x3b9/0xa00 [xen_gntdev] __x64_sys_ioctl+0x97/0xc0 task:repro state:D stack:0 pid:4480 tgid:4477 ppid:1 flags:0x00000000 __mutex_lock.constprop.0+0x41b/0x720 gntdev_mmap+0x4d/0x330 [xen_gntdev] __mmap_region+0x697/0xb10 mmap_region+0x78/0xa0 do_mmap+0x45d/0x630 vm_mmap_pgoff+0xf8/0x1c0
Drop priv->lock before copy_to_user() again. On failure, re-take it and remove the map by index, as IOCTL_GNTDEV_UNMAP_GRANT_REF does, since another thread may have unmapped it meanwhile.
Message-ID: <[email protected]>
--- drivers/xen/gntdev.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/xen/gntdev.c +6 -2
@@ -676,15 +676,19 @@ static long gntdev_ioctl_map_grant_ref(smutex_lock (&priv->lock);gntdev_add_map (priv, map); op.index = map->index <<PAGE_SHIFT ; +mutex_unlock (&priv->lock);if (copy_to_user (u, &op,sizeof (op)) !=0 ) { -list_del (&map->next); +mutex_lock (&priv->lock); + map =gntdev_find_map_index (priv, op.index >>PAGE_SHIFT , + op.count); +if (map) +list_del (&map->next);mutex_unlock (&priv->lock);gntdev_put_map (priv, map);return -EFAULT ; } -mutex_unlock (&priv->lock);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 773/990 xen/privcmd: fix double free when an irqfd is shut down twice
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qihang <[email protected]>
commit 72a900c666adb97df77b05cf8540c4117f9c83ba upstream.
irqfd_deactivate() takes the irqfd off irqfds_list and queues irqfd_shutdown(). queue_work() is not a once-only gate: it refuses to enqueue a work item only while WORK_STRUCT_PENDING is set, and process_one_work() clears that bit before it calls the work function. So nothing records that the shutdown work has already been queued, and nothing protects the window between the start of irqfd_shutdown() and the kfree() at its end.
Two paths call irqfd_deactivate() for the same irqfd:
- privcmd_irqfd_deassign(), from the PRIVCMD_IRQFD_FLAG_DEASSIGN ioctl;
- irqfd_wakeup(), with EPOLLHUP set, when the last reference to the
eventfd file goes away, which runs wake_up_poll(&ctx->wqh, EPOLLHUP)
from eventfd_release().irqfds_lock serialises the two calls, but it does not make the second one a no-op, and eventfd_ctx_fdget() takes a reference to the eventfd_ctx, not to the struct file, so the last fd can still be closed while the ioctl is running:
CPU0 CPU1
eventfd_ctx_fdget()
spin_lock(irqfds_lock)
list_del_init(&kirqfd->list)
queue_work(&kirqfd->shutdown) close(fd)
eventfd_release()
wake_up_poll(EPOLLHUP)
irqfd_wakeup() spin_lock(irqfds_lock) irqfd_deactivate() again
If the work item has already started by then, its pending bit has been cleared and the second queue_work() succeeds. irqfd_shutdown() then runs twice, so eventfd_ctx_remove_wait_queue(), eventfd_ctx_put() and kfree() each hit the same object a second time; and when the second queue_work() lands after the irqfd has been freed, the workqueue list operations write to freed memory.
virt/kvm/eventfd.c has the same two callers and has had this guard since the original irqfd support (721eecbf4fe99): irqfd_wakeup() calls irqfd_deactivate() only if irqfd_is_active(). The comment there explains why that is enough: the other side deactivates the irqfd before it takes it off the waitqueue, and irqfd_shutdown() needs the waitqueue lock, which this callback holds, so the irqfd cannot be freed under it.
Do the same here. list_del_init() leaves the list head empty and the irqfd stays off the list until kfree(), so it serves as a one-way "active" flag. The test is in irqfd_deactivate() rather than in irqfd_wakeup() because privcmd_irqfd_deassign() walks irqfds_list and can therefore never reach an inactive irqfd; only the wakeup path can, and a single test covers both callers.
Message-ID: <[email protected]>
--- drivers/xen/privcmd.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/xen/privcmd.c +15 -0
@@ -901,10 +901,25 @@ struct privcmd_kernel_irqfd {poll_table pt; }; +static bool irqfd_is_active (struct privcmd_kernel_irqfd *kirqfd) +{ +lockdep_assert_held (&irqfds_lock); + +return !list_empty (&kirqfd->list); +} +static void irqfd_deactivate (struct privcmd_kernel_irqfd *kirqfd) {lockdep_assert_held (&irqfds_lock); +/* +* Both the deassign ioctl and the eventfd wakeup path can reach +* this function. list_del_init() marks the irqfd inactive, so +* only the first caller may queue the shutdown work. +*/ +if (!irqfd_is_active (kirqfd)) +return ; +list_del_init (&kirqfd->list);queue_work (irqfd_cleanup_wq, &kirqfd->shutdown); }
Greg Kroah-Hartman
maintainerPATCH 774/990 xen/pvcalls: unwind pvcalls_new_active_socket() step by step
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 702ba3c80a8736898813a2c7484d695278aa114d upstream.
Every error path in pvcalls_new_active_socket() jumps to one shared label that does list_del(&map->list) and then hands map to pvcalls_back_release_active(). But map comes from kzalloc() and its list_head is only published at the very end of the function, after the last of those jumps:
down(&fedata->socket_lock); list_add_tail(&map->list, &fedata->socket_mappings); up(&fedata->socket_lock);
so on the error path map->list is still {NULL, NULL} and __list_del() writes through a NULL pointer.
A frontend gets there with one value it owns: the ring_order field of the page it granted. Anything above MAX_RING_ORDER takes the second goto, and nothing else in the function has run by then.
The result is an oops in whichever context handled the request - the pvcalls-back threaded IRQ handler for PVCALLS_CONNECT, mappass->wq for PVCALLS_ACCEPT - and because it happens after down(&fedata->socket_lock) that semaphore is never released, so every later operation on the frontend blocks on it and the backend never completes backend_disconnect(). (With CONFIG_DEBUG_LIST the list_del() only reports and returns, and pvcalls_back_release_active() then runs on a map whose irq is still 0 and whose bytes, ioworker.wq and saved_data_ready are all NULL.)
A frontend asking for ring_order 5, on a dom0 built with KASAN (the request was issued by a test-only change to the frontend):
[ 133.728877] pvcalls_new_active_socket frontend requested ring_order 5, which is > MAX (4) [ 133.732868] Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI [ 133.737910] KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f] [ 133.741666] CPU: 0 UID: 0 PID: 133 Comm: irq/39-pvcalls- Not tainted 7.3.0-kCTLblk2-15482-g21a7f44fd076-dirty #1 PREEMPT(full) [ 133.746986] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 [ 133.751512] RIP: 0010:pvcalls_new_active_socket+0x821/0xb90 [ 133.754237] Code: 48 89 fa 48 c1 ea 03 80 3c 02 00 0f 85 f6 01 00 00 48 8d 79 08 4c 8b 6b 08 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 14 02 00 00 4c 89 ea 4c 89 69 08 48 b8 00 00 00 [ 133.763126] RSP: 0018:ffffc900004afb38 EFLAGS: 00010202 [ 133.765861] RAX: dffffc0000000000 RBX: ffff88810886c900 RCX: 0000000000000000 [ 133.769348] RDX: 0000000000000001 RSI: 0000000000000246 RDI: 0000000000000008 [ 133.772787] RBP: 1ffff92000095f6b R08: 0000000000000001 R09: fffff52000095f58 [ 133.776260] R10: 0000000000000003 R11: ffff888100077320 R12: ffff88810858b410 [ 133.779823] R13: 0000000000000000 R14: ffff88810858b460 R15: ffff88810858b400 [ 133.783382] FS: 0000000000000000(0000) GS:ffff8881b034c000(0000) knlGS:0000000000000000 [ 133.787351] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 133.790308] CR2: 00000000006042c0 CR3: 0000000108400001 CR4: 0000000000770ef0 [ 133.793822] PKRU: 55555554 [ 133.795347] Call Trace: [ 133.796778] <TASK> [ 133.798082] ? __pfx_pvcalls_new_active_socket+0x10/0x10 [ 133.800801] ? security_socket_post_create+0x4d/0x60 [ 133.803275] ? release_sock+0x1a/0x1d0 [ 133.805182] pvcalls_back_event+0x1b09/0x23e0 [ 133.807431] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.809814] ? __pfx__raw_spin_lock_irqsave+0x10/0x10 [ 133.812251] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.814554] irq_thread_fn+0x86/0x150 [ 133.816468] irq_thread+0x2da/0x580 [ 133.818363] ? __pfx_irq_thread_fn+0x10/0x10 [ 133.820586] ? __pfx_irq_thread+0x10/0x10 [ 133.822670] ? __kthread_parkme+0x88/0x170 [ 133.824803] ? __pfx_irq_thread+0x10/0x10 [ 133.827153] ? __pfx_irq_thread+0x10/0x10 [ 133.829304] kthread+0x2c8/0x3b0 [ 133.831176] ? recalc_sigpending+0x15c/0x1e0 [ 133.833570] ? __pfx_kthread+0x10/0x10 [ 133.835572] ret_from_fork+0x373/0x5b0 [ 133.837581] ? __pfx_ret_from_fork+0x10/0x10 [ 133.839978] ? __switch_to+0x3c4/0xb40 [ 133.841984] ? __pfx_kthread+0x10/0x10 [ 133.843970] ret_from_fork_asm+0x1a/0x30 [ 133.846031] </TASK> [ 133.847420] Modules linked in: [ 133.849240] ---[ end trace 0000000000000000 ]---
Give each failure its own label, so that only resources that were actually acquired are released and the list the map was never added to is left
alone. The map is not published anywhere at that point, so the error path needs no socket_lock at all. sock_release() stays in the callee on every error path, the way
commit 8fafac202d18 ("xen/pvcalls-back: fix double frees with pvcalls_new_active_socket()") arranged it.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
drivers/xen/pvcalls-back.c +15 -10
@@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_ ret =xenbus_map_ring_valloc (fedata->dev, &ref,1 , &page);if (ret <0 ) - goto out; + goto out_map; map->ring = page; map->ring_order = map->ring->ring_order;/* first read the order, then map the data ring */
@@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_if (map->ring_order >MAX_RING_ORDER ) {pr_warn ("%s frontend requested ring_order %u, which is > MAX (%u)\n" , __func__, map->ring_order,MAX_RING_ORDER ); - goto out; + goto out_unmap_ring; } ret =xenbus_map_ring_valloc (fedata->dev, map->ring->ref, (1 << map->ring_order), &page);if (ret <0 ) - goto out; + goto out_unmap_ring; map->bytes = page; ret =bind_interdomain_evtchn_to_irqhandler_lateeoi ( fedata->dev, evtchn, pvcalls_back_conn_event,0 ,"pvcalls-backend" , map);if (ret <0 ) - goto out; + goto out_unmap_bytes; map->irq = ret; map->data.in = map->bytes;
@@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_ map->ioworker.wq =alloc_ordered_workqueue ("pvcalls_io" ,0 );if (!map->ioworker.wq) - goto out; + goto out_unbind;atomic_set (&map->io,1 );INIT_WORK (&map->ioworker.register_work, pvcalls_back_ioworker);
@@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_write_unlock_bh (&map->sock->sk->sk_callback_lock);return map; -out: -down (&fedata->socket_lock); -list_del (&map->list); -pvcalls_back_release_active (fedata->dev, fedata, map); -up (&fedata->socket_lock); + +out_unbind: +unbind_from_irqhandler (map->irq, map); +out_unmap_bytes: +xenbus_unmap_ring_vfree (fedata->dev, map->bytes); +out_unmap_ring: +xenbus_unmap_ring_vfree (fedata->dev, (void *)map->ring); +out_map: +sock_release (sock); +kfree (map);return NULL ; }
Greg Kroah-Hartman
maintainerPATCH 739/990 Bluetooth: hci_qca: fix use-after-free in ibs debugfs files
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: YuanZhe Liu <[email protected]>
commit eeca795cec6d9c6c193c2c1bd0cb26cde44f9fc3 upstream.
qca_debugfs_init() creates an "ibs" directory under hdev->debugfs and stores pointers to fields of struct qca_data in the debugfs files. qca_close() frees qca_data without removing that directory, while hdev->debugfs is only removed when the HCI device is released. The HCI device can outlive the driver data, for example when an HCI socket still references it, so reading or writing one of the ibs files then dereferences freed memory.
Store the directory dentry in struct qca_data and remove the directory with debugfs_remove_recursive() before qca_data is freed. debugfs_remove() waits for callers that are already inside the file operations, and any later access fails with -EIO instead of reaching the debugfs helpers. This covers the two writable files as well.
--- drivers/bluetooth/hci_qca.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/bluetooth/hci_qca.c +5 -0
@@ -162,6 +162,7 @@ struct qca_data {struct delayed_work ctrl_memdump_timeout;struct qca_memdump_info *qca_memdump;unsigned long flags; +struct dentry *debugfs_ibs_dir;struct completion drop_ev_comp;wait_queue_head_t suspend_wait_q;enum qca_memdump_states memdump_state;
@@ -667,6 +668,7 @@ static void qca_debugfs_init(struct hci_return ; ibs_dir =debugfs_create_dir ("ibs" , hdev->debugfs); + qca->debugfs_ibs_dir = ibs_dir;/* read only */ mode =0444 ;
@@ -742,6 +744,9 @@ static int qca_close(struct hci_uart *hu hu->priv =NULL ; +debugfs_remove_recursive (qca->debugfs_ibs_dir); + qca->debugfs_ibs_dir =NULL ; +kfree (qca);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 775/990 xen/pvcalls: destroy the per-socket workqueue on release
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 6b3feb6bfa9ac384f7a3ec25c40b9b4d3da96d25 upstream.
pvcalls_new_active_socket() gives every active socket its own ordered workqueue:
map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0);and nothing ever destroys it. pvcalls_back_release_active() flushes map->ioworker.register_work and frees map, but the workqueue and its pool_workqueues stay allocated, so a frontend leaks a workqueue per socket it connects and releases - a loop a guest can run as long as it likes.
Destroy it right after flush_work(): the IRQ is disabled and sk_data_ready restored by then, so nothing can queue new work, and the rings are still mapped while it drains - pvcalls_conn_back_read() reads map->ring and map->data, which xenbus_unmap_ring_vfree() takes away a few lines later. pvcalls_back_ioworker() does not take fedata->socket_lock, which the backend_disconnect() caller holds here - only the socket's own sk_receive_queue lock - so draining it from this point is safe; the flush_work() just above already has the same requirement.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 1 + 1 file changed, 1 insertion(+)
drivers/xen/pvcalls-back.c +1 -0
@@ -452,6 +452,7 @@ static int pvcalls_back_release_active(satomic_set (&map->release,1 );flush_work (&map->ioworker.register_work); +destroy_workqueue (map->ioworker.wq);xenbus_unmap_ring_vfree (dev, map->bytes);xenbus_unmap_ring_vfree (dev, (void *)map->ring);
Greg Kroah-Hartman
maintainerPATCH 776/990 hwmon: (aht10) Fix update_interval overflow on 64-bit
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rupesh Majhi <[email protected]>
commit b5c5b67e02406fb48acf57cf2c30a570230fd6aa upstream.
On 64-bit, update_interval writes are clamped to LONG_MAX ms, but ms_to_ktime() overflows above 9223372036854 ms and the interval wraps. LONG_MAX becomes -1 ms, so every read starts a new measurement and update_interval reads back -1.
Clamp to INT_MAX like sht4x, so the limit is the same on all platforms.
--- drivers/hwmon/aht10.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aht10.c +1 -1
@@ -229,7 +229,7 @@ static int aht10_read_values(struct aht1static ssize_t aht10_interval_write (struct aht10_data *data,long val) { - data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,LONG_MAX )); + data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,INT_MAX ));return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 777/990 hwmon: (gpio-fan) Fix runtime PM imbalance in probe and teardown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
commit 221b565a3316b1ba3a9bcd1f61238440207b3e00 upstream.
In gpio_fan_probe(), gpio_fan_stop() is registered conditionally as a devres action before runtime PM is initialized, while gpio_fan_stop() unconditionally calls pm_runtime_disable(). This breaks runtime PM disable_depth and usage_count invariants across several paths:
- On alarm-only devices without control GPIOs, gpio_fan_stop() is never registered, leaving pm_runtime_enable() unbalanced on unbind and triggering "Unbalanced pm_runtime_enable!" on subsequent binds.
- When control GPIOs are present and devm_add_action_or_reset(), hwmon registration, or fan_alarm_init() fails, gpio_fan_stop() runs before pm_runtime_enable(), incrementing disable_depth to 2 (leaving runtime PM permanently disabled on re-probe) and, if speed_index > 0, underflowing usage_count via pm_runtime_put_sync().
- If pm_runtime_resume_and_get() fails when speed_index > 0, it drops its reference while speed_index remains non-zero, causing gpio_fan_stop() to call pm_runtime_put_sync() and underflow usage_count.
- Registering the hwmon device before enabling runtime PM exposes sysfs attributes that can invoke set_fan_speed() before runtime PM state is initialized.
Initialize runtime PM upfront with pm_runtime_set_suspended() and devm_pm_runtime_enable(), remove pm_runtime_disable() from gpio_fan_stop(), and acquire the initial active runtime PM reference before registering gpio_fan_stop() and the hwmon device.
--- drivers/hwmon/gpio-fan.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-)
drivers/hwmon/gpio-fan.c +11 -13
@@ -531,8 +531,6 @@ static void gpio_fan_stop(void *data)mutex_lock (&fan_data->lock);set_fan_speed (data,0 );mutex_unlock (&fan_data->lock); - -pm_runtime_disable (fan_data->dev); }static int gpio_fan_probe (struct platform_device *pdev)
@@ -560,6 +558,11 @@ static int gpio_fan_probe(struct platforreturn dev_err_probe (dev,PTR_ERR (fan_data->supply),"Failed to get fan-supply" ); +pm_runtime_set_suspended (dev); + err =devm_pm_runtime_enable (dev); +if (err) +return err; +/* Configure control GPIOs if available. */ if (fan_data->gpios && fan_data->num_gpios >0 ) {if (!fan_data->speed || fan_data->num_speed <=1 )
@@ -567,6 +570,12 @@ static int gpio_fan_probe(struct platfor err =fan_ctrl_init (fan_data);if (err)return err; +/* If current GPIO state is active, mark RPM as active as well */ +if (fan_data->speed_index >0 ) { + err =pm_runtime_resume_and_get (dev); +if (err) +return err; + } err =devm_add_action_or_reset (dev, gpio_fan_stop, fan_data);if (err)return err;
@@ -587,17 +596,6 @@ static int gpio_fan_probe(struct platforreturn err; } -pm_runtime_set_suspended (&pdev->dev); -pm_runtime_enable (&pdev->dev); -/* If current GPIO state is active, mark RPM as active as well */ -if (fan_data->speed_index >0 ) { -int ret; - - ret =pm_runtime_resume_and_get (&pdev->dev); -if (ret) -return ret; - } -/* Optional cooling device register for Device tree platforms */ fan_data->cdev =devm_thermal_of_cooling_device_register (dev, np,"gpio-fan" , fan_data, &gpio_fan_cool_ops);
Greg Kroah-Hartman
maintainerPATCH 778/990 hwmon: (pmbus/mp2975) Get vout fault limits dynamically
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Radensky <[email protected]>
commit 00944852275efd39706fe7b9ce75c28edde983eb upstream.
The over- and under-voltage fault limits of the tracking mode are relative to the voltage reference, which follows the VID/AVS requests issued to the device and therefore changes at runtime.
The driver reads the voltage reference once during probe and derives the limits from that snapshot, which the PMBus core caches in addition. As a result in2_crit and in2_lcrit reflect the operating point at probe, rather than the thresholds the device enforces. On systems where the device supplies the CPU core voltage, in2_crit was reported anywhere between 1.15V and 1.70V across identical systems, causing false over-voltage reports once the CPU voltage exceeded the value latched at probe.
Read the voltage reference and the over-voltage offset selector whenever a limit is requested, and mark both limits with pmbus_set_update(), so that the core does not cache them. The voltage reference is available on page 3 only. Let the core change the page, so that the page it caches matches the device, except for a single rail configuration, for which the core does not issue PAGE commands, and the page is changed directly.
With the selector read at runtime, a device configured with an unsupported selector no longer fails to probe. The OVP1 threshold, which does not depend on the selector, is reported for it instead, with a warning.
Clamp the under-voltage limit to zero, since the offset can exceed a low voltage reference, while a negative value would be reported as a read error.
--- drivers/hwmon/pmbus/mp2975.c | 207 +++++++++++++++++++++++-------------------- 1 file changed, 115 insertions(+), 92 deletions(-)
drivers/hwmon/pmbus/mp2975.c +115 -92
@@ -110,10 +110,7 @@ struct mp2975_data {int vout_scale;int max_phases[MP2975_PAGE_NUM ];int vid_step[MP2975_PAGE_NUM ]; -int vref[MP2975_PAGE_NUM ]; -int vref_off[MP2975_PAGE_NUM ];int vout_max[MP2975_PAGE_NUM ]; -int vout_ov_fixed[MP2975_PAGE_NUM ];int curr_sense_gain[MP2975_PAGE_NUM ]; };
@@ -466,12 +463,77 @@ static int mp2973_write_word_data(structreturn pmbus_write_word_data (client,0 ,PMBUS_SMBALERT_MASK , ret); } +/* +* Let the PMBus core change the page, so that the page it caches matches the +* device. The core does not issue PAGE commands for a single rail +* configuration, thus change the page directly then. +*/ +static int +mp2975_page_set (struct i2c_client *client,struct mp2975_data *data,int page) +{ +if (data->info.pages >1 ) +return pmbus_set_page (client, page,0xff ); + +return i2c_smbus_write_byte_data (client,PMBUS_PAGE , page); +} + +/* +* Voltage reference is available on page 3 only. The callers read a register +* of the rail through the core first, thus the core caches the rail page. +*/ +static int +mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data,int page) +{ +int ret, vref; + + ret =mp2975_page_set (client, data,3 ); +if (ret <0 ) +return ret; + + vref =i2c_smbus_read_word_data (client, page ?MP2975_MFR_READ_VREF_R2 : +MP2975_MFR_READ_VREF_R1 ); + + ret =mp2975_page_set (client, data, page); +if (ret <0 ) +return ret; + +return (vref <0 ) ? vref : vref * data->vid_step[page]; +} + +static int +mp2975_ovp2_offset_get (int ovp_th_set) +{ +switch ((ovp_th_set &GENMASK (5 ,3 )) >>3 ) { +case 1 : +return 140 ; +case 2 : +return 220 ; +case 4 : +return 400 ; +default : +return -EINVAL ; + } +} + +static int +mp2975_vout_ovp2_get (struct i2c_client *client,struct mp2975_data *data, +int page,int vref_off) +{ +int vref; + + vref =mp2975_vref_get (client, data, page); +if (vref <0 ) +return vref; + +return vref +DIV_ROUND_CLOSEST (vref_off * data->vout_scale,10 ); +} +static int mp2975_read_word_data (struct i2c_client *client,int page,int phase,int reg) {const struct pmbus_driver_info *info =pmbus_get_driver_info (client);struct mp2975_data *data =to_mp2975_data (info); -int ret; +int ret, ovp1, vref_off, uv_off;switch (reg) {case PMBUS_OT_FAULT_LIMIT :
@@ -488,19 +550,35 @@ static int mp2975_read_word_data(structbreak ;case PMBUS_VOUT_OV_FAULT_LIMIT :/* -* Register provides two values for over-voltage protection -* threshold for fixed (ovp2) and tracking (ovp1) modes. The -* minimum of these two values is provided as over-voltage -* fault alarm. +* Device provides dual over-voltage protection. OVP1 is +* referred to the maximum reference voltage, while OVP2 is +* referred to the current voltage reference, which is changed +* at runtime. Protection is tripped by any of them, thus the +* minimum of the two is exposed as over-voltage fault alarm, +* and OVP2 is obtained on each read. */ ret =mp2975_read_word_helper (client, page, phase,MP2975_MFR_OVP_TH_SET , -GENMASK (2 ,0 )); +GENMASK (5 ,0 ));if (ret <0 )return ret; - ret =min_t (int, data->vout_max[page] +50 * (ret +1 ), - data->vout_ov_fixed[page]); + ovp1 = data->vout_max[page] +50 * ((ret &GENMASK (2 ,0 )) +1 ); + +/* OVP1 still applies if the OVP2 threshold is unknown. */ + vref_off =mp2975_ovp2_offset_get (ret); +if (vref_off <0 ) { +dev_warn_once (&client->dev, +"unsupported OVP2 selector, reporting OVP1 threshold\n" ); + ret = ovp1; +break ; + } + + ret =mp2975_vout_ovp2_get (client, data, page, vref_off); +if (ret <0 ) +return ret; + + ret =min_t (int, ovp1, ret);break ;case PMBUS_VOUT_UV_FAULT_LIMIT : ret = mp2975_read_word_helper(client, page, phase,
@@ -509,8 +587,17 @@ static int mp2975_read_word_data(structif (ret <0 )return ret; - ret =DIV_ROUND_CLOSEST (data->vref[page] *10 -50 * - (ret +1 ) * data->vout_scale,10 ); + uv_off =50 * (ret +1 ) * data->vout_scale; + + ret =mp2975_vref_get (client, data, page); +if (ret <0 ) +return ret; + +/* +* Offset can exceed the voltage reference, while a negative +* value would be reported as a read error. +*/ + ret =max_t (int,DIV_ROUND_CLOSEST (ret *10 - uv_off,10 ),0 );break ;case PMBUS_VIRT_READ_POUT_MAX : ret = mp2975_read_word_helper(client, page, phase,
@@ -760,60 +847,6 @@ mp2975_current_sense_gain_get(struct i2c }static int -mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data, -struct pmbus_driver_info *info) -{ -int ret; - - ret =i2c_smbus_write_byte_data (client,PMBUS_PAGE ,3 ); -if (ret <0 ) -return ret; - -/* Get voltage reference value for rail 1. */ - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R1 ); -if (ret <0 ) -return ret; - - data->vref[0 ] = ret * data->vid_step[0 ]; - -/* Get voltage reference value for rail 2, if connected. */ -if (data->info.pages ==MP2975_PAGE_NUM ) { - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R2 ); -if (ret <0 ) -return ret; - - data->vref[1 ] = ret * data->vid_step[1 ]; - } -return 0 ; -} - -static int -mp2975_vref_offset_get (struct i2c_client *client,struct mp2975_data *data, -int page) -{ -int ret; - - ret =i2c_smbus_read_word_data (client,MP2975_MFR_OVP_TH_SET ); -if (ret <0 ) -return ret; - -switch ((ret &GENMASK (5 ,3 )) >>3 ) { -case 1 : - data->vref_off[page] =140 ; -break ; -case 2 : - data->vref_off[page] =220 ; -break ; -case 4 : - data->vref_off[page] =400 ; -break ; -default : -return -EINVAL ; - } -return 0 ; -} - -static int mp2975_vout_max_get (struct i2c_client *client,struct mp2975_data *data,struct pmbus_driver_info *info,int page) {
@@ -917,25 +950,6 @@ mp2975_vout_per_rail_config_get(struct i ret =mp2975_vout_max_get (client, data, info, i);if (ret <0 )return ret; - -/* Skip if reading Vref is unsupported */ -if (data->chip_id != mp2975) -continue ; - -/* Obtain voltage reference offsets. */ - ret =mp2975_vref_offset_get (client, data, i); -if (ret <0 ) -return ret; - -/* -* Set over-voltage fixed value. Thresholds are provided as -* fixed value, and tracking value. The minimum of them are -* exposed as over-voltage critical threshold. -*/ - data->vout_ov_fixed[i] = data->vref[i] + -DIV_ROUND_CLOSEST (data->vref_off[i] * - data->vout_scale, -10 ); }return 0 ;
@@ -1049,11 +1063,6 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -/* Obtain voltage reference values. */ - ret =mp2975_vref_get (client, data, info); -if (ret) -return ret; -/* Obtain vout over-voltage scales. */ ret =mp2975_vout_ov_scale_get (client, data, info);if (ret <0 )
@@ -1070,7 +1079,21 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -return pmbus_do_probe (client, info); + ret =pmbus_do_probe (client, info); +if (ret) +return ret; + +/* +* Vout over- and under-voltage fault limits are relative to the +* voltage reference, which is changed at runtime. Do not allow the +* PMBus core to cache them. +*/ +if (data->chip_id == mp2975) { +pmbus_set_update (client,PMBUS_VOUT_OV_FAULT_LIMIT , true); +pmbus_set_update (client,PMBUS_VOUT_UV_FAULT_LIMIT , true); + } + +return 0 ; }static const struct of_device_id mp2975_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 779/990 hwmon: (sy7636a) fix negative temperatures
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Mazzini <[email protected]>
commit fc8519fab34e162b0c29dacccf73031820878917 upstream.
The thermistor readout is a signed 8-bit value in degrees Celsius.
--- drivers/hwmon/sy7636a-hwmon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/sy7636a-hwmon.c +1 -1
@@ -29,7 +29,7 @@ static int sy7636a_read(struct device *dif (ret)return ret; - *temp = reg_val *1000 ; + *temp = (s8 )reg_val *1000 ;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 780/990 hwmon: (scmi) Check channel config allocation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sudeep Holla <[email protected]>
commit a2996d892d0150d059d39c683d95d6fd7a37630a upstream.
scmi_hwmon_add_chan_info() can fail to allocate a channel's config array. Ignoring that error leaves a channel with a NULL config pointer in the hwmon chip info, which hwmon dereferences while registering the device.
Check the helper's return value and abort probe on failure.
--- drivers/hwmon/scmi-hwmon.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/hwmon/scmi-hwmon.c +7 -5
@@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(static int scmi_hwmon_probe (struct scmi_device *sdev) { -int i, idx;u16 nr_sensors; +int i, idx, ret;enum hwmon_sensor_types type;struct scmi_sensors *scmi_sensors;const struct scmi_sensor_info *sensor;
@@ -297,8 +297,12 @@ static int scmi_hwmon_probe(struct scmi_if (!nr_count[type])continue ; -scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, nr_count[type], - type, hwmon_attributes[type]); + ret =scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, + nr_count[type], type, + hwmon_attributes[type]); +if (ret) +return ret; + *ptr_scmi_ci++ = scmi_hwmon_chan++; scmi_sensors->info[type] =
@@ -333,8 +337,6 @@ static int scmi_hwmon_probe(struct scmi_return PTR_ERR (hwdev);for (i =0 ; i < nr_count_temp; i++) { -int ret; - sensor = *(scmi_sensors->info[hwmon_temp] + i);if (!sensor)continue ;
Greg Kroah-Hartman
maintainerPATCH 781/990 hwmon: (max31760) Fix the local temperature limit registers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 028ed93145d9be88eee670088ef13482b5d36c1a upstream.
temp2_max and temp2_crit use each other's registers, so reading them shows the local limits swapped and writing temp2_max changes the overtemperature (SHDN) threshold.
Use the high limit (0x0C) for temp2_max and the overtemperature limit (0x08) for temp2_crit.
--- drivers/hwmon/max31760.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +2 -2
@@ -27,8 +27,8 @@#define REG_TACH (ch) (0x52 + (ch) * 2)#define REG_TEMP_INPUT (ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX (ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT (ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX (ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT (ch) ((ch) ? 0x08 : 0x0A)#define TEMP11_FROM_REG (reg) ((reg) / 32 * 125)#define TEMP11_TO_REG (val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \
Greg Kroah-Hartman
maintainerPATCH 782/990 hwmon: (max31760) Leave standby mode at probe
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 95bddc5252a4c0a2ed9d62e7e53a3461265d9603 upstream.
The driver never clears the standby bit (CR2_STBY) during probe. While max31760_resume() clears this bit on resume, probe only configured CR2_ALERTS.
If the chip was left in standby (for example, by boot firmware or a previously running OS before a warm reboot), it remains in standby:
temperature sensing, fan speed counting, and PWM output are halted. This occurs on the Samsung Galaxy XR, where the bootloader places the chip in standby during boot.
Clear CR2_STBY alongside setting CR2_ALERTS in probe.
--- drivers/hwmon/max31760.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +3 -2
@@ -533,8 +533,9 @@ static int max31760_probe(struct i2c_clidev_set_drvdata (dev, state); -/* Set alert output to comparator mode */ - ret =regmap_set_bits (state->regmap,REG_CR2 ,CR2_ALERTS ); +/* Leave standby mode, set alert output to comparator mode */ + ret =regmap_update_bits (state->regmap,REG_CR2 ,CR2_STBY |CR2_ALERTS , +CR2_ALERTS );if (ret)return dev_err_probe (dev, ret,"cannot write register\n" );
Greg Kroah-Hartman
maintainerPATCH 740/990 Bluetooth: L2CAP: Keep recvmsg from resuming a closed channel
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 1f2ac56137c51be0601e18a163d817e02a15913f upstream.
Reading buffered ERTM data after ACL link loss can clear local busy and send a supervisory frame after l2cap_conn_del() has destroyed the HCI channel, which oopses on a NULL pointer in hci_send_acl(). The socket still owns its L2CAP channel, so its lifetime does not protect the underlying HCI channel.
Require BT_CONNECTED before clearing local busy in recvmsg. The socket lock already held here serializes this check and send with teardown, which closes the socket before the HCI channel is destroyed. Continue to allow buffered data to be read after disconnection.
AI assistance was used.
--- net/bluetooth/l2cap_sock.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_sock.c +2 -1
@@ -1289,7 +1289,8 @@ static int l2cap_sock_recvmsg(struct soc* available. This avoids resending large numbers of * frames. */ -if (test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) && +if (sk->sk_state ==BT_CONNECTED && +test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) &&atomic_read (&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >>1 )l2cap_chan_busy (pi->chan,0 );
Greg Kroah-Hartman
maintainerPATCH 741/990 cgroup/cpuset: Dont revive invalid partition without active CPU on hotplug
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ridong Chen <[email protected]>
commit acec9637e03ca54bd3c3a0c1a6ad5c6dfa07c0df upstream.
When a CPU hotplug leaves no CPU outside of the partitions for the top cpuset, cpuset_handle_hotplug() clears subpartitions_cpus and gives all the active CPUs back to the top cpuset. cpuset_hotplug_update_tasks() then walks the hierarchy and invalidates the partitions, as subpartitions_cpus is empty.
However, an invalid partition visited in the same walk may be revived if its effective_xcpus is not empty. tasks_nocpu_error() doesn't catch it when its CPUs are all offline but it has no task. Its CPUs are put back into subpartitions_cpus, and the valid partitions visited after it are no longer invalidated, as subpartitions_cpus is not empty any more. The top cpuset is left with CPUs overlapping with these partitions.
It can be reproduced on a system with 8 CPUs:
# cd /sys/fs/cgroup # echo +cpuset > cgroup.subtree_control # mkdir A1 B1 # echo 1 > A1/cpuset.cpus # echo 1 > A1/cpuset.cpus.exclusive # echo 0,2-7 > B1/cpuset.cpus # echo root > B1/cpuset.cpus.partition # echo root > A1/cpuset.cpus.partition # cat A1/cpuset.cpus.partition root invalid (Parent unable to distribute cpu downstream) # echo 0 > /sys/devices/system/cpu/cpu1/online # cat A1/cpuset.cpus.partition B1/cpuset.cpus.partition root root # cat cpuset.cpus.effective 0,2-7
A1 can't take CPU 1, the last CPU of the root cgroup which has tasks. When CPU 1 is offlined, A1 is revived without any active CPU, and B1 stays valid while its CPUs are also in the effective CPUs of the root cgroup, which triggers
WARNING: kernel/cgroup/cpuset.c:919 at rebuild_sched_domains_locked
Only revive an invalid partition in hotplug if its effective_xcpus has an active CPU, the same as what is required to create a partition with tasks. With that, A1 and B1 are both invalidated in the above case.
--- kernel/cgroup/cpuset.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
@@ -4164,10 +4164,10 @@ retry: partcmd = partcmd_invalidate;/* * On the other hand, an invalid partition root may be transitioned -* back to a regular one with a non-empty effective xcpus. +* back to a regular one if its effective xcpus has an active CPU. */ else if (is_partition_valid(parent) && is_partition_invalid(cs) && - !cpumask_empty(cs->effective_xcpus)) + cpumask_intersects(cs->effective_xcpus, cpu_active_mask)) partcmd = partcmd_update;if (partcmd >=0 ) {
Greg Kroah-Hartman
maintainerPATCH 742/990 crypto: caam - reject overlong RSA CRT parameters
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 828c3b265b6df877dced3dde56ea41daa2e6181e upstream.
caam_read_rsa_crt() right-aligns dP, dQ, and qInv in buffers sized from the corresponding prime. rsa_parse_priv_key() only bounds these integers against n, so a malformed key can provide, for example, a two-byte dP with a one-byte p. dstlen - nbytes then underflows and memcpy() writes outside the allocation during set_priv_key(). KASAN reports a slab-out-of-bounds write in caam_read_rsa_crt().
Reject empty or overlong CRT parameters after stripping leading zeros. qInv is consumed by CAAM as a p-sized value, so size it from p rather than q to match the DMA mapping in set_rsa_priv_f3_pdb(). Let the top-level key cleanup handle partial form-3 allocations and return the specific error to the caller.
Also test nbytes before dereferencing it while stripping zeros, so an all-zero integer does not read one byte beyond its input.
--- drivers/crypto/caam/caampkc.c | 79 +++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 47 deletions(-)
drivers/crypto/caam/caampkc.c +32 -47
@@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caastatic void caam_rsa_drop_leading_zeros (const u8 **ptr,size_t *nbytes) { -while (!**ptr && *nbytes) { +while (*nbytes && !**ptr) { (*ptr)++; (*nbytes)--; }
@@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(* @ptr : pointer to {dP, dQ, qInv} CRT member * @nbytes: length in bytes of {dP, dQ, qInv} CRT member * @dstlen: length in bytes of corresponding p or q prime factor +* @dst : pointer to the zero-padded output buffer */ -static u8 *caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen) +static int caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen, +u8 **dst) { -u8 *dst; -caam_rsa_drop_leading_zeros (&ptr, &nbytes); -if (!nbytes) -return NULL ; +if (!nbytes || nbytes > dstlen) +return -EINVAL ; - dst =kzalloc (dstlen,GFP_KERNEL ); -if (!dst) -return NULL ; + *dst =kzalloc (dstlen,GFP_KERNEL ); +if (!*dst) +return -ENOMEM ; -memcpy (dst + (dstlen - nbytes), ptr, nbytes); +memcpy (*dst + (dstlen - nbytes), ptr, nbytes); -return dst; +return 0 ; }/**
@@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(stsize_t p_sz = raw_key->p_sz;size_t q_sz = raw_key->q_sz;unsigned aligned_size; +int ret; rsa_key->p =caam_read_raw_data (raw_key->p, &p_sz);if (!rsa_key->p)
@@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(st rsa_key->q =caam_read_raw_data (raw_key->q, &q_sz);if (!rsa_key->q) - goto free_p; +return -ENOMEM ; rsa_key->q_sz = q_sz; aligned_size =ALIGN (raw_key->p_sz,dma_get_cache_alignment ()); rsa_key->tmp1 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp1) - goto free_q; +return -ENOMEM ; aligned_size =ALIGN (raw_key->q_sz,dma_get_cache_alignment ()); rsa_key->tmp2 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp2) - goto free_tmp1; +return -ENOMEM ; rsa_key->priv_form =FORM2 ; - rsa_key->dp =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz); -if (!rsa_key->dp) - goto free_tmp2; - - rsa_key->dq =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz); -if (!rsa_key->dq) - goto free_dp; - - rsa_key->qinv =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, - q_sz); -if (!rsa_key->qinv) - goto free_dq; + ret =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz, + &rsa_key->dp); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz, + &rsa_key->dq); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, p_sz, + &rsa_key->qinv); +if (ret) +return ret; rsa_key->priv_form =FORM3 ;return 0 ; - -free_dq: -kfree_sensitive (rsa_key->dq); - rsa_key->dq =NULL ; -free_dp: -kfree_sensitive (rsa_key->dp); - rsa_key->dp =NULL ; -free_tmp2: -kfree_sensitive (rsa_key->tmp2); - rsa_key->tmp2 =NULL ; -free_tmp1: -kfree_sensitive (rsa_key->tmp1); - rsa_key->tmp1 =NULL ; -free_q: -kfree_sensitive (rsa_key->q); - rsa_key->q =NULL ; -free_p: -kfree_sensitive (rsa_key->p); - rsa_key->p =NULL ; -return -ENOMEM ; } static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key,
@@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(structif (ret)return ret; + ret = -ENOMEM ; +/* Copy key in DMA zone */ rsa_key->d =kmemdup (raw_key.d, raw_key.d_sz,GFP_KERNEL );if (!rsa_key->d)
@@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct err:caam_rsa_free_key (rsa_key); -return -ENOMEM ; +return ret; }static unsigned int caam_rsa_max_size (struct crypto_akcipher *tfm)
Greg Kroah-Hartman
maintainerPATCH 743/990 crypto: essiv - fix use-after-free in AEAD path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit e9ce64dce975a14700e835003847415e29918474 upstream.
The request that ESSIV submits to its wrapped AEAD transform may finish before crypto_aead_encrypt() or crypto_aead_decrypt() returns. In case this happens, essiv_aead_done() calls aead_request_complete() on the original ESSIV request, which can end up freeing the request before essiv_aead_crypt() resumes, creating a UAF:
BUG: KASAN: slab-use-after-free in essiv_aead_crypt+0x8e6/0x950 Read of size 8 at addr ffff888102af1360 by task init/66
Check the return status before dereferencing rctx after submitting that request. If the operation did not return -EINPROGRESS or -EBUSY, then the request cannot have been freed yet.
--- crypto/essiv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
crypto/essiv.c +1 -1
@@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_ err = enc ?crypto_aead_encrypt (subreq) :crypto_aead_decrypt (subreq); -if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY ) +if (err != -EINPROGRESS && err != -EBUSY )kfree (rctx->assoc);return err; }
Greg Kroah-Hartman
maintainerPATCH 744/990 dcache: let d_invalidate() wait for a d_set_mounted() in flight
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 20a6a9ec19e522ae85f87337886b3fb47efce5f3 upstream.
d_invalidate() and d_set_mounted() are supposed to exclude each other. Either the mount fails with -ENOENT because an ancestor of the mountpoint was unhashed or d_invalidate() finds the mountpoint and detaches the mount. d_invalidate() unhashes the dentry first and then searches the subtree with d_walk() which starts out lockless and only looks at the seqcount of rename_lock.
Since d_set_mounted() switched to read_seqlock_excl() nothing makes that walk wait or retry:
CPU0: mount on A/M CPU1: d_invalidate(A)
d_set_mounted(M)
read_seqlock_excl(&rename_lock)
A is hashed, go on
__d_drop(A)
shrink_dcache_parent(A)
d_walk(A, find_submount)
read_seqbegin(&rename_lock)
M is not a mountpoint
need_seqretry() == false
return
M->d_flags |= DCACHE_MOUNTED
return 0mount gets attached to M
The mount ends up below an unhashed dentry. It can't be reached anymore and pins the subtree until its parent mount or the mount namespace goes away. The window grows with the depth of the mountpoint. With a FUSE directory 3000 levels deep a bind mount racing with FUSE_NOTIFY_INVAL_ENTRY for the parent of the mountpoint survived in 151 of 200 attempts.
Before 5e317d23f6c6 the seqcount bump made the walk wait while d_set_mounted() ran and retry under the lock when one had run in the meantime. That was the right thing to wait for on the wrong counter:
every rename_lock reader paid for it, d_lookup(), d_path(), the ".." step of the RCU walk.
So give d_set_mounted() a seqlock of its own. It is the only writer and d_invalidate() is the only reader. After unhashing the dentry d_invalidate() runs an empty read_seqbegin()/read_seqretry() section on it. That spins while the count is odd, i.e. while a d_set_mounted() is between its ancestor check and its flag, and goes round once more if one started in the meantime. Nobody else retries anything. The ordering comes from the locks both already take:
- If that d_set_mounted() saw the dentry hashed its check ran under the dentry's d_lock before __d_drop() took it. So the count is odd by the time d_invalidate() reads it and d_invalidate() waits.
- Once the count is even again the flag has been set under the mountpoint's d_lock and the walk takes that lock to look at it.
A d_set_mounted() that starts after the unhash fails its ancestor check and never touches the flag. So the only flag the walk can pick up belongs to the one mount that saw the dentry hashed and is still in flight, and there is at most one of those because namespace_sem serializes mounts. Either it gets attached and detach_mounts() takes it off after waiting for namespace_sem or it fails later on and drops the flag again. In that case the walk goes round once more and finds nothing. The same goes for the mountpoint that attach_recursive_mnt() preallocates on the root of the tree it attaches. IOW, d_invalidate() does at most one extra round, which the removed-name trap (cf. [1]) relies on.
Note that on PREEMPT_RT read_seqbegin() takes the lock instead of spinning on a preempted d_set_mounted().
The cost is a seqlock around the ancestor walk for every new mountpoint and two loads of a cacheline that only d_set_mounted() writes for every d_invalidate() of a positive dentry. Walking the ancestors a second time after setting the flag would close the race as well but doubles the cost of d_set_mounted() with the depth of the mountpoint: about 1us at 64 levels and 75us at 4096 levels.
[1]: https://patch.msgid.link/[email protected]
--- fs/dcache.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-)
fs/dcache.c +15 -4
@@ -1437,21 +1437,25 @@ int path_has_submounts(const struct path }EXPORT_SYMBOL (path_has_submounts); +/* odd while d_set_mounted() runs, d_invalidate() waits on it */ +static __cacheline_aligned_in_smp DEFINE_SEQLOCK (d_set_mounted_lock ); +/* * Called by mount code to set a mountpoint and check if the mountpoint is * reachable (e.g. NFS can unhash a directory dentry and then the complete * subtree can become unreachable). * * Only one of d_invalidate() and d_set_mounted() must succeed. For -* this reason take rename_lock and d_lock on dentry and ancestors. -* Likewise for dont_mount() which marks a dentry that is being removed -* under d_lock. +* this reason take rename_lock, d_set_mounted_lock and d_lock on dentry +* and ancestors. Likewise for dont_mount() which marks a dentry that +* is being removed under d_lock. */ int d_set_mounted (struct dentry *dentry) {struct dentry *p;int ret = -ENOENT ;read_seqlock_excl (&rename_lock); +write_seqlock (&d_set_mounted_lock);for (p = dentry->d_parent; !IS_ROOT (p); p = p->d_parent) {/* Need exclusion wrt. d_invalidate() */ spin_lock (&p->d_lock);
@@ -1469,8 +1473,9 @@ int d_set_mounted(struct dentry *dentry) ret =0 ; } } -spin_unlock (&dentry->d_lock); +spin_unlock (&dentry->d_lock); out: +write_sequnlock (&d_set_mounted_lock);read_sequnlock_excl (&rename_lock);return ret; }
@@ -1674,6 +1679,7 @@ static enum d_walk_ret find_submount(voivoid d_invalidate (struct dentry *dentry) {bool had_submounts = false; +unsigned seq;spin_lock (&dentry->d_lock);if (d_unhashed (dentry)) {spin_unlock (&dentry->d_lock);
@@ -1686,6 +1692,11 @@ void d_invalidate(struct dentry *dentry)if (!dentry->d_inode)return ; +/* wait for a d_set_mounted() that saw us hashed to set its flag */ +do { + seq =read_seqbegin (&d_set_mounted_lock); + }while (read_seqretry (&d_set_mounted_lock, seq)); +shrink_dcache_parent (dentry);for (;;) {struct dentry *victim =NULL ;
Greg Kroah-Hartman
maintainerPATCH 735/990 perf/core: Do not resurrect cpuctx->cgrp after last cgroup event exit
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Phat Dinh <[email protected]>
commit 59f1398140869432c7171b9a2a279ca315467c4e upstream.
perf_cgroup_switch() relies on:
/*
* cpuctx->cgrp is set when the first cgroup event enabled,
* and is cleared when the last cgroup event disabled. */
It computes the next task's cgroup, schedules out the CPU context and then assigns cpuctx->cgrp unconditionally:
ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
/*
* must not be done before ctxswout due
* to update_cgrp_time_from_cpuctx() in
* ctx_sched_out()
*/
cpuctx->cgrp = cgrp;However, ctx_sched_out() can disable events itself. If a cgroup event has a pending disable from perf_event_disable_inatomic() (e.g. its PERF_EVENT_IOC_REFRESH limit ran out) that the irq_work has not handled yet, event_sched_out() consumes it inline:
if (event->pending_disable) {
event->pending_disable = 0;
perf_cgroup_event_disable(event, ctx);
state = PERF_EVENT_STATE_OFF;
}If that was the last cgroup event, perf_cgroup_event_disable() clears cpuctx->cgrp:
if (--ctx->nr_cgroups)
return;
cpuctx->cgrp = NULL;and perf_cgroup_switch() then sets it again. cpuctx->cgrp is left non-NULL with ctx.nr_cgroups == 0, so the NULL check in perf_cgroup_switch() no longer catches it and the next switch trips:
WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
cpuctx->cgrp does not hold a reference on the cgroup. Once that cgroup is removed, the next ctx_sched_in() dereferences the stale pointer:
BUG: KASAN: slab-use-after-free in ctx_sched_in+0xb1f/0xfa0 Read of size 8 at addr ffff8881008972d0 by task swapper/3/0 Tainted: [W]=WARN Call Trace: <IRQ> ctx_sched_in+0xb1f/0xfa0 perf_event_sched_in+0x1a/0x70 ctx_resched+0x32b/0xac0 __perf_install_in_context+0x475/0xab0 remote_function+0x105/0x200 __flush_smp_call_function_queue+0x179/0x8d0 __sysvec_call_function_single+0x1b/0x1c0 sysvec_call_function_single+0x66/0x80 </IRQ> <TASK> asm_sysvec_call_function_single+0x1a/0x20
Only assign cpuctx->cgrp when cgroup events remain after the context has been scheduled out, so that it stays NULL as the invariant requires.
--- kernel/events/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/events/core.c +6 -1
@@ -971,8 +971,13 @@ static void perf_cgroup_switch(struct ta* must not be done before ctxswout due * to update_cgrp_time_from_cpuctx() in * ctx_sched_out() +* +* ctx_sched_out() can consume a pending disable and drop the last cgroup +* event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup +* event, so do not resurrect it */ - cpuctx->cgrp = cgrp; +if (cpuctx->ctx.nr_cgroups) + cpuctx->cgrp = cgrp;/* * set cgrp before ctxsw in to allow * perf_cgroup_set_timestamp() in ctx_sched_in()
Greg Kroah-Hartman
maintainerPATCH 784/990 s390/dasd: Fix wrong free and refcount leak in build_check_tcw error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit df56f7a6c20a5eb2794c0a7391bde50ba7c8c54b upstream.
dasd_eckd_build_check_tcw() allocates its request with dasd_fmalloc_request(), but its out_err path frees it with dasd_sfree_request(). The latter uses a different pool and therefor, leading to invalid pointer arithmetic and a crash.
Use the matching dasd_ffree_request() instead.
The same error path also leaves start_priv->count incremented without ever decrementing it again.
This leaks a permanent reference on every build failure. Decrement it before freeing the request.
--- drivers/s390/block/dasd_eckd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_eckd.c +2 -1
@@ -2594,7 +2594,8 @@ dasd_eckd_build_check_tcw(struct dasd_dereturn cqr; out_err: -dasd_sfree_request (cqr, startdev); + start_priv->count--; +dasd_ffree_request (cqr, startdev);return ERR_PTR (rc); }
Greg Kroah-Hartman
maintainerPATCH 793/990 sctp: report the partially delivered MID in PARTIAL_DELIVERY_ABORTED
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 3097fba868019924e92b8786ebd473992565f015 upstream.
When an I-FORWARD-TSN skips the message being partially delivered on a stream, sctp_intl_skip() passes the MID from the I-FORWARD-TSN to the PARTIAL_DELIVERY_ABORTED notification as pdapi_seq. That MID is the highest one skipped on the stream, so when more than one message is skipped, the notification names a later message instead of the one whose partial delivery was aborted.
Report the MID being partially delivered, sin->mid_uo or sin->mid, instead.
Reproduced on an unmodified kernel with the pdapi and pdapi_uo tests of the sctp_ifwdtsn.sh selftest added later in this series, which pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
net/sctp/stream_interleave.c +2 -2
@@ -1245,7 +1245,7 @@ static void sctp_intl_skip(struct sctp_uif (flags &SCTP_FTSN_U_BIT ) {if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 , +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid_uo,0x1 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);
@@ -1257,7 +1257,7 @@ static void sctp_intl_skip(struct sctp_uif (sin->pd_mode) { sin->pd_mode =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid,0x0 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);
Greg Kroah-Hartman
maintainerPATCH 794/990 sctp: reset stored flag for each association
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 173712d868eb20628ad82deb07f6829a68a9e064 upstream.
sctp_send_asconf_del_ip() walks every association on an endpoint. The stored flag records that the current association took the single-homed deferral path and therefore did not allocate an ASCONF chunk. It is currently scoped to the whole function. Once one association sets it, later eligible multihomed associations allocate chunks but skip sctp_send_asconf(), leaking each chunk and its skb.
Reset stored for every association so only an association taking the deferral path skips transmission. In an A/B kmemleak test, the vulnerable kernel reported 210 leaked objects from this call path and the fixed kernel reported none.
--- net/sctp/socket.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/socket.c +1 -1
@@ -808,7 +808,6 @@ static int sctp_send_asconf_del_ip(strucstruct sctp_sockaddr_entry *saddr;int i;int retval =0 ; -int stored =0 ; chunk =NULL ; sp =sctp_sk (sk);
@@ -821,6 +820,7 @@ static int sctp_send_asconf_del_ip(struc __func__, sk, addrs, addrcnt);list_for_each_entry (asoc, &ep->asocs, asocs) { +int stored =0 ;if (!asoc->peer.asconf_capable)continue ;
Greg Kroah-Hartman
maintainerPATCH 795/990 LoongArch: kexec_file: Fix a modified cmdline leak
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinjie Ruan <[email protected]>
commit b7000844b374a1ab75f0cc561f1d4d321cd6eeb0 upstream.
machine_kexec_prepare() copies it to KEXEC_CMDLINE_ADDR and overwrites the pointer. Free the heap buffer after the copy here.
--- arch/loongarch/kernel/machine_kexec.c | 2 ++ 1 file changed, 2 insertions(+)
arch/loongarch/kernel/machine_kexec.c +2 -0
@@ -14,6 +14,7 @@#include <linux/mm.h> #include <linux/of_fdt.h> #include <linux/reboot.h> +#include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/task_stack.h>
@@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage *kimage)*/ memcpy ((void *)KEXEC_CMDLINE_ADDR , (void *)kimage->arch.cmdline_ptr,strlen ((char *)kimage->arch.cmdline_ptr) +1 ); +kfree ((void *)kimage->arch.cmdline_ptr); kimage->arch.cmdline_ptr = (unsigned long )KEXEC_CMDLINE_ADDR ; }else {/* Find the command line */
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 796/990 LoongArch: kexec_file: Fix elf_headers memory leak in retry loop
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinjie Ruan <[email protected]>
commit 065dd1636abef6b9962fd5af82accac69850bbe8 upstream.
A retry allocates new elf headers and overwrites image->elf_headers, leaking the previous buffer. Free it before assigning here.
--- arch/loongarch/kernel/machine_kexec_file.c | 4 ++++ 1 file changed, 4 insertions(+)
arch/loongarch/kernel/machine_kexec_file.c +4 -0
@@ -182,6 +182,10 @@ int load_other_segments(struct kimage *ivfree (headers); goto out_err; } + +if (unlikely (image->elf_headers)) +vfree (image->elf_headers); + image->elf_headers = headers; image->elf_load_addr = kbuf.mem; image->elf_headers_sz = headers_sz;
Greg Kroah-Hartman
maintainerPATCH 797/990 LoongArch: Restore KFENCE pages through DMW on resume
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
commit 40d7a3e63c3d88b43e9115d23d9937dd506bbd02 upstream.
With KFENCE enabled, resume from hibernation triggers KFENCE reports while swsusp_asm_resume() copies the image pages, for example:
BUG: KFENCE: use-after-free write in swsusp_asm_resume+0x20/0x94
Use-after-free write at 0x00000000a57ee925 (in kfence-#254):
swsusp_asm_resume+0x20/0x94 hibernation_restore+0x128/0x1a0 load_image_and_restore+0x6c/0xc8 software_resume+0x240/0x260 do_one_initcall+0x68/0x200 kernel_init_freeable+0x26c/0x304 kernel_init+0x20/0x134 ret_from_kernel_thread+0x24/0x1d0 ret_from_kernel_thread_asm+0xc/0x98
During resume from hibernation, the image pages that occupy physical pages used by the restore kernel are first loaded into free pages and then, as the very last step, swsusp_asm_resume() copies them to their final location pointed to by pbe->orig_address, which the hibernation core sets to page_address() of the page in the restore kernel.
The early KFENCE pool is allocated from memblock and normally occupies the same physical pages in the restore kernel and in the image kernel, so these pages are usually copied by swsusp_asm_resume().
The KFENCE pool is remapped into the KFENCE area above vm_map_base and set_page_address() adjusts page->virtual so that page_address() returns the page-table mapped alias rather than the DMW virtual address of the pool pages.
Hence, pbe->orig_address of KFENCE pages points to that alias and swsusp_asm_resume() writes them through the page tables. But:
* the copy loop overwrites the kernel page tables, so a TLB refill for the KFENCE alias may use a partially restored page table
* the KFENCE pool pages that are protected in the restore kernel fault in the middle of the copy
Convert pbe->orig_address to DMW addresses before starting the copy.
--- arch/loongarch/power/hibernate.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/loongarch/power/hibernate.c +6 -0
@@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void);int swsusp_arch_resume (void ) { +#ifdef CONFIG_KFENCE +struct pbe *pbe; + +for (pbe = restore_pblist; pbe; pbe = pbe->next) + pbe->orig_address =__va (virt_to_phys (pbe->orig_address)); +#endif /* Avoid TLB mismatch during and after kernel resume */ local_flush_tlb_all ();return swsusp_asm_resume ();
Greg Kroah-Hartman
maintainerPATCH 798/990 LoongArch: KVM: Propagate real error code in kvm_pch_pic_create()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tao Cui <[email protected]>
commit 20f3bf3d3dce16f43b82881293586ce7d73982b6 upstream.
The real error code of kvm_setup_default_irq_routing() is replaced by kvm_pch_pic_create() with a fixed -ENOMEM. Return the actual error code, as kvm_eiointc_create() already does; while the kvm_ipi_create() case is fixed separately by "Return the actual error code in kvm_ipi_create()" (Chaithanya Lagisetty).
--- arch/loongarch/kvm/intc/pch_pic.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kvm/intc/pch_pic.c +1 -1
@@ -436,7 +436,7 @@ static int kvm_pch_pic_create(struct kvm ret =kvm_setup_default_irq_routing (kvm);if (ret) -return -ENOMEM ; +return ret; s =kzalloc (sizeof (struct loongarch_pch_pic ),GFP_KERNEL );if (!s)
Greg Kroah-Hartman
maintainerPATCH 799/990 LoongArch: KVM: Reject repeated PCH-PIC CTRL_INIT
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tao Cui <[email protected]>
commit 422e532809572ba1043192bf6a0c653bc68b3140 upstream.
KVM_DEV_LOONGARCH_PCH_PIC_CTRL_INIT has no guard against repeated
invocation: every call overwrites pch_pic_base and registers the same kvm_io_device on the MMIO bus at the new base address, while the kvm_pch_pic_destroy() unregisters only one bus range. After a repeated init, MMIO to the stale ranges computes its register offset against the new base address and silently reads 0 / drops writes, and the leftover bus entries persist until the VM is destroyed.
Reject repeated initialization with -EEXIST, using the initialized state of the kvm_io_device as the indicator. The check, the MMIO base update and the bus registration are serialized by slots_lock, and the real registration error is propagated instead of being replaced with -EFAULT. On a registration failure the base addr and the device state are rolled back so that a retry can start over.
--- arch/loongarch/kvm/intc/pch_pic.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-)
arch/loongarch/kvm/intc/pch_pic.c +12 -3
@@ -273,16 +273,25 @@ static int kvm_pch_pic_init(struct kvm_dstruct kvm_io_device *device;struct loongarch_pch_pic *s = dev->kvm->arch.pch_pic; - s->pch_pic_base = addr; device = &s->device; +mutex_lock (&kvm->slots_lock); +if (s->device.ops) { + ret = -EEXIST ; + goto out; + } + s->pch_pic_base = addr;/* init device by pch pic writing and reading ops */ kvm_iodevice_init (device, &kvm_pch_pic_ops); -mutex_lock (&kvm->slots_lock);/* register pch pic device */ ret =kvm_io_bus_register_dev (kvm,KVM_MMIO_BUS , addr,PCH_PIC_SIZE , device); +if (ret) { + s->pch_pic_base =0 ; + s->device.ops =NULL ; + } +out:mutex_unlock (&kvm->slots_lock); -return (ret <0 ) ? -EFAULT :0 ; +return ret; }/* used by user space to get or set pch pic registers */
Greg Kroah-Hartman
maintainerPATCH 800/990 tracing/perf: Clear stop state in perf_trace_add()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paolo Bertinetti <[email protected]>
commit fb3f6b21b04f1e8b8982e90e9bf62db9f0dcb5e4 upstream.
Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.
perf_trace_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_tp_event_match() drops every later hit. A tracepoint, kprobe or uprobe event re-armed this way delivers only its first overflow. This breaks self-profilers such as async-profiler, and the "Event re-armed with PERF_EVENT_IOC_REFRESH" perf test fails:
1000 events, count 1, 1 overflows (1 POLL_HUP), re-arm errno 0 Tracepoint event : FAILED!
Set the state from PERF_EF_START on every add, as perf_swevent_add() does.
--- kernel/trace/trace_event_perf.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_event_perf.c +1 -2
@@ -354,8 +354,7 @@ int perf_trace_add(struct perf_event *p_struct trace_event_call *tp_event = p_event->tp_event;struct hw_perf_event *hwc = &p_event->hw; -if (!(flags &PERF_EF_START )) - p_event->hw.state =PERF_HES_STOPPED ; + hwc->state = (flags &PERF_EF_START ) ?0 :PERF_HES_STOPPED ;if (is_sampling_event (p_event)) { hwc->last_period = hwc->sample_period;
Greg Kroah-Hartman
maintainerPATCH 801/990 tracing/uprobes: Fix memory leak of tail in __trace_uprobe_create()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit c15120853eebbda98f3fe1f1e59370439c6c4447 upstream.
When generating a default event name in __trace_uprobe_create(), tail is allocated with kstrdup() without __free(kfree). If the subsequent kmalloc() for buf fails, the function returns -ENOMEM immediately and leaks tail.
Declare tail with __free(kfree) so it is automatically freed on all exit paths.
--- kernel/trace/trace_uprobe.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_uprobe.c +1 -2
@@ -666,7 +666,7 @@ static int __trace_uprobe_create(int arg }if (!event) { -char *tail; + char *tail __free(kfree) = NULL;char *ptr; tail =kstrdup (kbasename (filename),GFP_KERNEL );
@@ -682,7 +682,6 @@ static int __trace_uprobe_create(int arg goto fail_mem;snprintf (buf,MAX_EVENT_NAME_LEN ,"%c_%s_0x%lx" ,'p' , tail, offset); event = buf; -kfree (tail); } argc -=2 ;
Greg Kroah-Hartman
maintainerPATCH 802/990 tracing/eprobe: Fix 1-byte signed field fetch in get_event_field()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit a0f836eea463d4c468edb58eedb03911c9c0791d upstream.
Because the kernel is built with -funsigned-char, plain 'char' is unsigned on all architectures. Reading 1-byte signed trace event fields via *(char *)addr in get_event_field() therefore zero-extends instead of sign-extending negative s8 values.
Use explicit fixed-width integer types (s8/u8, s16/u16, s32/u32) when reading event fields.
--- kernel/trace/trace_eprobe.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_eprobe.c +6 -6
@@ -328,21 +328,21 @@ get_event_field(struct fetch_insn *code,switch (field->size) {case 1 :if (field->is_signed) - val = *(char *)addr; + val = *(s8 *)addr;else - val = *(unsigned char *)addr; + val = *(u8 *)addr;break ;case 2 :if (field->is_signed) - val = *(short *)addr; + val = *(s16 *)addr;else - val = *(unsigned short *)addr; + val = *(u16 *)addr;break ;case 4 :if (field->is_signed) - val = *(int *)addr; + val = *(s32 *)addr;else - val = *(unsigned int *)addr; + val = *(u32 *)addr;break ;default :if (field->size ==sizeof (long )) {
Greg Kroah-Hartman
maintainerPATCH 785/990 s390/dasd: Dont trust userspace-supplied result field in format check
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit 7cc2dda4f7aaf596c1796184649007151ff98f8d upstream.
BIODASDCHECKFMT used to copy the entire format_check_t struct from userspace, including the result/unit/rec/num_records/blksize/ key_length fields that are output fields only. dasd_eckd_format_evaluate_tracks() relies on cdata->result being zero to decide whether to apply an index correction (i--/pos--) after a successful check. A caller that pre-sets result to a non-zero value can suppress that correction, leaving pos advanced past the last valid entry; the (partially out-of-bounds) fmt_buffer[pos] fields are then copied back to userspace, leaking heap contents.
Only expect is an Input field; copy just that member in and zero the rest of cdata.
--- drivers/s390/block/dasd_ioctl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_ioctl.c +3 -1
@@ -304,7 +304,9 @@ static int dasd_ioctl_check_format(struc goto out_err; } -if (copy_from_user (&cdata, argp,sizeof (cdata))) { +/* copy only input fields, clear the rest */ +memset (&cdata,0 ,sizeof (cdata)); +if (copy_from_user (&cdata.expect, argp,sizeof (cdata.expect))) { rc = -EFAULT ; goto out_err; }
Greg Kroah-Hartman
maintainerPATCH 803/990 tracing/eprobe: Disallow attaching eprobes to fprobe events
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 92d9fa0ed69e1f724feed908bd0a462a42df4b88 upstream.
Event probes (eprobes) are not allowed to attach to other dynamic probe events (kprobes, uprobes, and eprobes) to avoid recursive probe chains and lifecycle dependencies. However, when fprobe events were introduced, TRACE_EVENT_FL_FPROBE was omitted from the exclusion mask in find_and_get_event(), allowing eprobes to attach to fprobe and tprobe events.
Exclude TRACE_EVENT_FL_FPROBE events in find_and_get_event().
--- kernel/trace/trace_eprobe.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/trace/trace_eprobe.c +2 -1
@@ -756,7 +756,8 @@ find_and_get_event(const char *system, c (TRACE_EVENT_FL_IGNORE_ENABLE |TRACE_EVENT_FL_KPROBE |TRACE_EVENT_FL_UPROBE | - TRACE_EVENT_FL_EPROBE)) +TRACE_EVENT_FL_EPROBE | + TRACE_EVENT_FL_FPROBE)) continue;if (!tp_event->class->system ||strcmp (system, tp_event->class->system))
Greg Kroah-Hartman
maintainerPATCH 804/990 tracing/probes: Check enabled and busy state before unlinking sibling probes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit f1d9b7a3fe99b4228acdbab3c744c29f7ffe86ef upstream.
When a multiprobe event is enabled or referenced (for example, by an eprobe, trigger, or open tracefs file) and a user attempts to delete the event or one of its probes via dynamic_events, checking trace_probe_has_sibling() before the enabled and busy checks allows the first probe to be unlinked and freed while the event is still active, only returning -EBUSY on the last sibling probe. For uprobe events, unlinking and freeing an enabled sibling probe without unregistering its uprobe_consumer also causes a use-after-free.
Ensure all four probe types (kprobe, fprobe, uprobe, and eprobe) verify that the event is neither enabled nor busy before unlinking any sibling probe.
--- kernel/trace/trace_eprobe.c | 12 ++++++++---- kernel/trace/trace_fprobe.c | 8 ++++---- kernel/trace/trace_kprobe.c | 8 ++++---- kernel/trace/trace_uprobe.c | 8 ++++++-- 4 files changed, 22 insertions(+), 14 deletions(-)
kernel/trace/trace_eprobe.c +8 -4
@@ -89,14 +89,18 @@ static int eprobe_dyn_event_show(structstatic int unregister_trace_eprobe (struct trace_eprobe *ep) { -/* If other probes are on the event, just unregister eprobe */ -if (trace_probe_has_sibling (&ep->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&ep->tp))return -EBUSY ; +/* If there's a reference to the dynamic event */ +if (trace_event_dyn_busy (trace_probe_event_call (&ep->tp))) +return -EBUSY ; + +/* If other probes are on the event, just unregister eprobe */ +if (trace_probe_has_sibling (&ep->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (trace_probe_unregister_event_call (&ep->tp))return -EBUSY ;
kernel/trace/trace_fprobe.c +4 -4
@@ -857,10 +857,6 @@ static void __unregister_trace_fprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_fprobe (struct trace_fprobe *tf) { -/* If other probes are on the event, just unregister fprobe */ -if (trace_probe_has_sibling (&tf->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tf->tp))return -EBUSY ;
@@ -869,6 +865,10 @@ static int unregister_trace_fprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tf->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister fprobe */ +if (trace_probe_has_sibling (&tf->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_fprobe_event (tf))return -EBUSY ;
kernel/trace/trace_kprobe.c +4 -4
@@ -538,10 +538,6 @@ static void __unregister_trace_kprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_kprobe (struct trace_kprobe *tk) { -/* If other probes are on the event, just unregister kprobe */ -if (trace_probe_has_sibling (&tk->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tk->tp))return -EBUSY ;
@@ -550,6 +546,10 @@ static int unregister_trace_kprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tk->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister kprobe */ +if (trace_probe_has_sibling (&tk->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event (tk))return -EBUSY ;
kernel/trace/trace_uprobe.c +6 -2
@@ -396,13 +396,17 @@ static int unregister_trace_uprobe(struc {int ret; -if (trace_probe_has_sibling (&tu->tp)) - goto unreg; +/* Enabled event can not be unregistered */ +if (trace_probe_is_enabled (&tu->tp)) +return -EBUSY ;/* If there's a reference to the dynamic event */ if (trace_event_dyn_busy (trace_probe_event_call (&tu->tp)))return -EBUSY ; +if (trace_probe_has_sibling (&tu->tp)) + goto unreg; + ret =unregister_uprobe_event (tu);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 805/990 tracing/probes: Enable newly appended probe when target event is enabled
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 72d3a5cb0cd7335553549aaffecc683e3ecc0c43 upstream.
Unlike kprobe events, fprobe and uprobe events only register their underlying probes when the trace event is enabled. When a new probe is appended to an existing multiprobe fprobe or uprobe event that is already enabled, the appended probe is linked into the event's probe list without being registered.
As a result, the newly appended probe never fires until the event is disabled and re-enabled. Moreover, disabling an fprobe event calls unregister_fprobe() on the unregistered fprobe, and opening or closing a perf event on an enabled uprobe event dereferences a NULL tu->uprobe in uprobe_apply().
Register and enable the newly appended fprobe or uprobe immediately when the target event is already enabled.
--- kernel/trace/trace_fprobe.c | 14 ++++------- kernel/trace/trace_uprobe.c | 56 +++++++++++++++++++++++++++++--------------- 2 files changed, 43 insertions(+), 27 deletions(-)
kernel/trace/trace_fprobe.c +6 -8
@@ -937,7 +937,10 @@ static int append_trace_fprobe_event(strif (ret)return ret; - ret =trace_fprobe_verify_target (tf); +if (trace_probe_is_enabled (&tf->tp)) + ret =__register_trace_fprobe (tf); +else + ret =trace_fprobe_verify_target (tf);if (ret)trace_probe_unlink (&tf->tp);else
@@ -1522,13 +1525,8 @@ static int disable_trace_fprobe(struct ttrace_probe_clear_flag (tp,TP_FLAG_PROFILE );if (!trace_probe_is_enabled (tp)) { -list_for_each_entry (tf,trace_probe_probe_list (tp), tp.list) { -unregister_fprobe (&tf->fp); -if (tf->tuser) { -tracepoint_user_put (tf->tuser); - tf->tuser =NULL ; - } - } +list_for_each_entry (tf,trace_probe_probe_list (tp), tp.list) +__unregister_trace_fprobe (tf); } out:
kernel/trace/trace_uprobe.c +37 -19
75 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 806/990 tracing/probes: Fix missing BTF kind checks in char pointer/array helpers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit c1e2c63e65421068566db3dde44dfd4fe7adb46d upstream.
In struct btf_type, the type ID and byte size share a union, and only BTF_KIND_INT types are followed by a 32-bit integer encoding word. Because btf_type_is_char_ptr() and btf_type_is_char_array() do not verify that the outer type is BTF_KIND_PTR or that the resolved element type is a non-NULL BTF_KIND_INT before inspecting it, non-pointer BTF types can have their byte size misinterpreted as a BTF type ID, and arrays of non-integer types read out-of-bounds or misinterpret trailing BTF metadata as BTF_INT_* encoding bits.
Validate the BTF type kinds and NULL pointers before reading inner type metadata in both helpers.
--- kernel/trace/trace_probe.c | 8 ++++++++ 1 file changed, 8 insertions(+)
kernel/trace/trace_probe.c +8 -0
@@ -356,6 +356,9 @@ static bool btf_type_is_char_ptr(structconst struct btf_type *real_type;u32 intdata; +if (BTF_INFO_KIND (type->info) !=BTF_KIND_PTR ) +return false; + real_type =btf_type_skip_modifiers (btf, type->type,NULL );if (!real_type)return false;
@@ -380,6 +383,11 @@ static bool btf_type_is_char_array(struc array = (const struct btf_array *)(type +1 ); real_type =btf_type_skip_modifiers (btf, array->type,NULL ); +if (!real_type) +return false; + +if (BTF_INFO_KIND (real_type->info) !=BTF_KIND_INT ) +return false; intdata =btf_type_int (real_type);return !(BTF_INT_ENCODING (intdata) &BTF_INT_SIGNED )
Greg Kroah-Hartman
maintainerPATCH 807/990 tracing/probes: Fix user-space dereference string array store type
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 2721573e6c6faaba2e31f352f2c02ec5f3ecf5e9 upstream.
When finalizing a string array argument (e.g. +0u(%reg):string[N]), finalize_fetch_insn() advances the instruction pointer to a new slot for the store operation before checking whether the preceding operation was FETCH_OP_UDEREF. As a result, user-space dereference string arrays with type "string" emit FETCH_OP_ST_STRING (kernel memory read) instead of FETCH_OP_ST_USTRING.
Check for FETCH_OP_UDEREF before advancing the instruction pointer.
--- kernel/trace/trace_probe.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/trace/trace_probe.c +4 -2
@@ -1484,6 +1484,8 @@ static int finalize_fetch_insn(struct fe/* Store operation */ if (parg->type->is_string) { +bool is_uderef; +/* Check bad combination of the type and the last fetch_insn. */ if (!strcmp (parg->type->name,"symstr" )) { if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK &&
@@ -1503,6 +1505,7 @@ static int finalize_fetch_insn(struct fe } } + is_uderef = (code->op ==FETCH_OP_UDEREF ); if (!strcmp(parg->type->name, "symstr") || (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM || code->op == FETCH_OP_DATA) || code->op == FETCH_OP_TP_ARG ||
@@ -1523,8 +1526,7 @@ static int finalize_fetch_insn(struct fe }/* If op == DEREF, replace it with STRING */ -if (!strcmp (parg->type->name,"ustring" ) || - code->op ==FETCH_OP_UDEREF ) +if (!strcmp (parg->type->name,"ustring" ) || is_uderef) code->op =FETCH_OP_ST_USTRING ;else if (!strcmp (parg->type->name,"symstr" )) code->op =FETCH_OP_ST_SYMSTR ;
Greg Kroah-Hartman
maintainerPATCH 808/990 tracing/probes: Reject array count on non-dereference string sources
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 0941144ebeaf3ce46c80711f00e935921eb28b21 upstream.
The runtime array loop (FETCH_OP_LP_ARRAY) for string types requires a preceding memory dereference instruction so it can advance the pointer address on each iteration. Non-dereference string sources such as $comm, immediate strings, and eprobe event fields cannot be indexed as pointer arrays, but finalize_fetch_insn() still accepts an array count on them and emits an invalid FETCH_OP_LP_ARRAY sequence.
Reject string array counts when the preceding operation is not a memory dereference.
--- kernel/trace/trace_probe.c | 6 ++++++ 1 file changed, 6 insertions(+)
kernel/trace/trace_probe.c +6 -0
@@ -1518,6 +1518,12 @@ static int finalize_fetch_insn(struct fe* For the symstr, it doesn't need to dereference, thus * it just get the value. */ +if (parg->count && (code->op !=FETCH_OP_DEREF && + code->op !=FETCH_OP_UDEREF )) { +trace_probe_log_err (ctx->offset + type_offset, +BAD_STRING ); +return -EINVAL ; + } code++;if (code->op !=FETCH_OP_NOP ) {trace_probe_log_err (ctx->offset,TOO_MANY_OPS );
Greg Kroah-Hartman
maintainerPATCH 809/990 wifi: ath12k: assign device id from the WSI index
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benoit Masson <[email protected]>
commit 81986a81f09fae73926c7c44863b335880269c90 upstream.
Devices of a hardware group are added to ag->ab[] in PCI probe completion order (ab->device_id = ag->num_probed++), which is not stable across boots. The wiphy radio array is built from ag->ab[] and the wiphy device is taken from its first entry, so the wiphy sysfs path and the mapping of radio indices to bands change on every boot.
Persisted wireless configurations reference radios by index (e.g. OpenWrt/hostapd "radio0"), so such a configuration attaches to a random band at each boot. This affects any multi-chip group with single-band radios, e.g. TP-Link Archer BE800 (three QCN9274/QCN9224 radios in one group).
Store each ab in ag->ab[] at its wsi_info.index, which is derived from the device tree WSI ring and is therefore deterministic. ag->num_probed remains the group device counter. The unassign path is unchanged, it already indexes ag->ab[] by ab->device_id.
--- drivers/net/wireless/ath/ath12k/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/wireless/ath/ath12k/core.c +2 -1
@@ -1943,7 +1943,8 @@ exit: goto invalid_group; } - ab->device_id = ag->num_probed++; + ag->num_probed++; + ab->device_id = wsi->index; ag->ab[ab->device_id] = ab; ab->ag = ag;
Greg Kroah-Hartman
maintainerPATCH 810/990 wifi: ath9k_htc: do not start ANI before the first channel is set
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mehmet Fide <[email protected]>
commit dda63dd136ba2bc3b297079b190ac81a0aea40ae upstream.
ath9k_htc_add_interface() starts ANI for the first AP interface, before any channel is configured. The per-channel calibration data only gets attached by the first ath9k_htc_set_channel() that is not a fast channel change, and that same call cancels the ANI work a few milliseconds after add_interface, so normally the work never runs.
When the bring-up stalls for more than the 100 ms ANI poll interval in between, it does run, and ar9002_hw_per_calibration() records the IQ calibration result in the calibration data that does not exist yet:
Unable to handle kernel NULL pointer dereference at virtual address 00000008 PC is at ar9002_hw_calibrate+0x1f8/0x570 [ath9k_hw] Workqueue: phy0 ath9k_htc_ani_work [ath9k_htc]
Seen about once per thousand AP starts with an AR9271 on a Cortex-A5 board that starts hostapd while still booting; a 500 ms delay after add_interface reproduces it on every start. The crashed work never completes, so the next cancel_delayed_work_sync() blocks for good.
Drop the start; it has nothing to calibrate against and is cancelled anyway. The TSF adjust bit that shared its condition is now set for every AP interface, which is harmless: the next reset applies it. The next patch starts ANI once the interface beacons.
--- drivers/net/wireless/ath/ath9k/htc_drv_main.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/net/wireless/ath/ath9k/htc_drv_main.c +1 -4
@@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(strucath9k_htc_set_opmode (priv); -if ((priv->ah->opmode ==NL80211_IFTYPE_AP ) && - !test_bit (ATH_OP_ANI_RUN , &common->op_flags)) { +if (priv->ah->opmode ==NL80211_IFTYPE_AP )ath9k_hw_set_tsfadjust (priv->ah, true); -ath9k_htc_start_ani (priv); - }ath_dbg (common,CONFIG ,"Attach a VIF of type: %d at idx: %d\n" , vif->type, avp->index);
Greg Kroah-Hartman
maintainerPATCH 811/990 wifi: cfg80211: release rejected nontransmitted BSS reference
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f3c45d5b741a7d7586e639c2f55d2557029f2e1a upstream.
Repeated MBSSID reports without an SSID can leak BSS entries outside the scan cache, where the BSS entry limit cannot account for them.
__cfg80211_bss_update() returns a referenced BSS. If adding it to the transmitting BSS list fails, unlinking drops the cache reference, but the caller reference is lost when res is cleared.
Release the caller reference before discarding the unlinked BSS.
LLM assistance was used to find the bug and review.
--- net/wireless/scan.c | 1 + 1 file changed, 1 insertion(+)
net/wireless/scan.c +1 -0
@@ -2437,6 +2437,7 @@ cfg80211_inform_single_bss_data(struct wif (cfg80211_add_nontrans_list (data->source_bss, &res->pub)) {if (__cfg80211_unlink_bss (rdev, res)) { rdev->bss_generation++; +bss_ref_put (rdev, res); res =NULL ; } }
Greg Kroah-Hartman
maintainerPATCH 812/990 wifi: cfg80211: preserve mesh A-MSDU lengths when adding mesh headers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 9083da9dd3223068237395432323b407012aec1f upstream.
A malformed mesh A-MSDU subframe with a declared payload length near 65535 bytes can pass validation against a much shorter aggregate.
ieee80211_amsdu_subframe_length() adds the mesh control length to the declared length in a u16, and ieee80211_is_valid_amsdu() stores the result in a u16 local. The sum therefore wraps before either walker compares it with the remaining aggregate length. The decomposer then splits and delivers the malformed aggregate instead of rejecting it.
Keep the computed length in unsigned int in both the helper and the validator so oversized subframes cannot wrap.
LLM assistance was used to find the bug and review.
--- net/wireless/util.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
net/wireless/util.c +3 -3
@@ -745,12 +745,12 @@ __ieee80211_amsdu_copy(struct sk_buff *sreturn frame; } -static u16 +static unsigned int ieee80211_amsdu_subframe_length (void *field,u8 mesh_flags,u8 hdr_type) {__le16 *field_le = field;__be16 *field_be = field; -u16 len; +unsigned int len;if (hdr_type >=2 ) len =le16_to_cpu (*field_le);
@@ -772,7 +772,7 @@ bool ieee80211_is_valid_amsdu(struct sk___be16 len;u8 mesh_flags; } hdr; -u16 len; +unsigned int len;if (sizeof (hdr) > remaining)return false;
Greg Kroah-Hartman
maintainerPATCH 786/990 sched/deadline: Fix spurious -EPERM for migration-disabled tasks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 6616bffa9b52da1338cf8bff9882404e02b9e361 upstream.
sched_setattr() can refuse to make a task SCHED_DEADLINE with -EPERM, even though the task's affinity covers the whole root domain. A retry can succeed, but the error blames an affinity the task does not have.
__sched_setscheduler() tests p->cpus_ptr, which is not always the task's affinity. When a task is scheduled out inside a migrate_disable() section, migrate_disable_switch() points p->cpus_ptr at the current CPU until migrate_enable(). On PREEMPT_RT every spinlock_t holder is in such a section, so ordinary kernel work opens the window. Elsewhere, seccomp filters run in one.
Test p->cpus_mask instead, which keeps the task's affinity and is what sched_getaffinity() reports. This should be safe because an admitted task's cpus_mask covers the root domain, so set_cpus_allowed_dl() moves no bandwidth when migrate_enable() restores p->cpus_ptr.
The following program, run as root, had 553679, 453720 and 424623 of its 1000000 requests refused on three boots of a 4-CPU PREEMPT_RT guest, and 236182, 217174 and 237183 without PREEMPT_RT. With this applied the count is 0, also with lockdep, and a task pinned to one CPU is still refused:
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#define REQUESTS 1000000
#define INSNS 300
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static long set(struct attr a)
{
a.size = sizeof(a);
return syscall(SYS_sched_setattr, target, &a, 0);
}
static void *worker(void *arg)
{
struct sock_filter f[INSNS + 1];
struct sock_fprog prog = { .len = INSNS + 1, .filter = f };
int i; /* Reading the arguments keeps seccomp from caching the result */
for (i = 0; i < INSNS; i++)
f[i] = (struct sock_filter)
BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
offsetof(struct seccomp_data, args));
f[INSNS] = (struct sock_filter)
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog);
target = syscall(SYS_gettid);
while (!stop)
syscall(SYS_getppid);
return arg;}
static void *hog(void *arg)
{
while (!stop)
;
return arg;
}
int main(void)
{
pthread_t t[9];
long refused = 0;
int i; pthread_create(&t[0], NULL, worker, NULL);
while (!target)
usleep(100);
for (i = 1; i < 9; i++)
pthread_create(&t[i], NULL, hog, NULL);
for (i = 0; i < REQUESTS; i++) {
/* SCHED_DEADLINE, 2us every 1s */
if (set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 }) && errno == EPERM)
refused++;
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
stop = 1;
for (i = 0; i < 9; i++)
pthread_join(t[i], NULL);
printf("%ld of %d requests refused\n", refused, REQUESTS);
return 0;}
An LLM helped find this bug and write this patch and its test.
--- kernel/sched/syscalls.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/syscalls.c +1 -1
@@ -638,7 +638,7 @@ change:* the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ -if (!cpumask_subset (span, p->cpus_ptr) || +if (!cpumask_subset (span, &p->cpus_mask) || rq->rd->dl_bw.bw ==0 ) { retval = -EPERM ; goto unlock;
Greg Kroah-Hartman
maintainerPATCH 813/990 wifi: cfg80211: dont truncate the merged MBSSID profile length
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit 3ea152f3f77eeffc37b2f4423688b4df9136f90c upstream.
cfg80211_parse_mbssid_data() keeps the length of a non-transmitted BSSID profile in a u8. cfg80211_merge_profile() returns a size_t, and it concatenates a profile that is split over several Multiple BSSID elements, so the merged length can be well above 255 even though every single sub-element is at most 255 bytes long.
The value is then cut to its low 8 bits. A 300 byte profile is handled as a 44 byte one: the elements after the cut are lost from the generated non-transmitted BSS, and if the Multiple BSSID-Index element lies past the cut the BSS is dropped altogether. Any AP in range can send such a profile.
The multi-link code further down in the same file already uses a signed size type for the profile length. Do the same here, cfg80211_find_ie() and cfg80211_gen_new_ie() take a size_t anyway.
--- net/wireless/scan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/wireless/scan.c +1 -1
@@ -2580,7 +2580,7 @@ cfg80211_parse_mbssid_data(struct wiphyif (elem->data[0 ] <1 || (int )elem->data[0 ] >8 )continue ;for_each_element (sub, elem->data +1 , elem->datalen -1 ) { -u8 profile_len; +size_t profile_len;if (sub->id !=0 || sub->datalen <4 ) {/* not a valid BSS profile */
Greg Kroah-Hartman
maintainerPATCH 814/990 wifi: mac80211: fix use-after-free when MLO link setup is rolled back
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit a155ef2ef79531c139244289c5b8f15c05d16a0e upstream.
Rolling back an MLO link addition can free link containers while RCU readers still hold pointers to them. ieee80211_vif_update_links() publishes new links before checking for duplicate addresses and calling drv_change_vif_links(). If either fails, it restores the old pointers and frees the new containers without waiting for readers.
During a non-MLO to MLO transition, the published link 0 replaces the deflink, so existing link 0 users can acquire the new container. Readers such as ieee80211_csa_finish() and ieee80211_obss_color_collision_notify() can also queue work embedded in the link. If they queue after ieee80211_link_stop() cancels that work, it remains queued when the container is freed.
Wait for RCU readers after restoring the old pointers and before stopping the new links, so their work is queued before it is cancelled.
--- net/mac80211/link.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/link.c +2 -0
@@ -385,6 +385,8 @@ static int ieee80211_vif_update_links(stmemcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old));ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +/* drain RCU readers before cancelling work they may queue */ +synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {ieee80211_link_debugfs_remove (&links[link_id]->data);ieee80211_link_stop (&links[link_id]->data);
Greg Kroah-Hartman
maintainerPATCH 815/990 wifi: mac80211: drain link readers before stopping removed links
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 745f5d04395dfc4c311f443c7c04ccb00c436984 upstream.
Removing an MLO link can leave work queued on its link container after the container is freed.
ieee80211_tear_down_links() stops each link before the RCU grace period. A reader that fetched the link earlier can therefore queue work after ieee80211_link_stop() has canceled it. ieee80211_request_smps() and ieee80211_csa_finish() can both reach this window.
Record each removed link while removing its keys and debugfs state. Wait for RCU readers, then stop the recorded links so cancellation includes work queued by those readers. Free the detached keys after the grace period as before.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/mac80211/link.c +7 -1
@@ -179,6 +179,7 @@ struct link_container {static void ieee80211_tear_down_links (struct ieee80211_sub_if_data *sdata,struct link_container **links,u16 mask) { +struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS ] = {};struct ieee80211_link_data *link;LIST_HEAD (keys);unsigned int link_id;
@@ -193,11 +194,16 @@ static void ieee80211_tear_down_links(stcontinue ;ieee80211_remove_link_keys (link, &keys);ieee80211_link_debugfs_remove (link); -ieee80211_link_stop (link); + stop[link_id] = link; } +/* drain RCU readers before cancelling work they may queue */ synchronize_rcu (); +for (link_id =0 ; link_id <IEEE80211_MLD_MAX_NUM_LINKS ; link_id++) +if (stop[link_id]) +ieee80211_link_stop (stop[link_id]); +ieee80211_free_key_list (sdata->local, &keys); }
Greg Kroah-Hartman
maintainerPATCH 816/990 wifi: mac80211: recheck injected headers after removing FCS
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 339564c7ac50464695dfed847f89d118f4cc1dc5 upstream.
Injecting a short frame with IEEE80211_RADIOTAP_F_FCS on a monitor interface can pass a truncated 802.11 header to transmit handlers.
ieee80211_monitor_start_xmit() validates the linear 802.11 header before parsing radiotap. Radiotap parsing then removes the four-byte FCS without rechecking the remaining header length. Software encryption can subtract the larger header length and pass the resulting negative length as an unsigned size.
Recheck the required linear header length after pulling the radiotap header and before handing the frame to the transmit path. Require at least addr1, which the transmit path reads even for extension frames whose header is shorter.
LLM assistance was used to find the bug and review.
--- net/mac80211/tx.c | 6 ++++++ 1 file changed, 6 insertions(+)
net/mac80211/tx.c +6 -0
@@ -2552,6 +2552,12 @@ netdev_tx_t ieee80211_monitor_start_xmit/* remove the injection radiotap header */ skb_pull (skb, len_rthdr); +/* FCS removal may have shortened the 802.11 header. */ + hdrlen =max_t (int, hdrlen, + offsetofend(struct ieee80211_hdr, addr1)); +if (skb_headlen (skb) < hdrlen) + goto fail_rcu; +ieee80211_xmit (sdata,NULL , skb);rcu_read_unlock ();
Greg Kroah-Hartman
maintainerPATCH 817/990 wifi: mac80211: recheck the IBSS station limit before insertion
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f7670bcdf650b37551a9c5d084521f877d939f11 upstream.
Frames from successive unknown IBSS peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ibss.c +6 -2
@@ -1656,8 +1656,12 @@ void ieee80211_ibss_work(struct ieee8021list_del (&sta->list);spin_unlock_bh (&ifibss->incomplete_lock); -ieee80211_ibss_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_IBSS_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ibss_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 818/990 wifi: mac80211: recheck the OCB station limit before insertion
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 27e29a077b4887d0e0a813337f8b7e06bd020c81 upstream.
Frames from successive unknown OCB peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ocb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ocb.c +6 -2
@@ -136,8 +136,12 @@ void ieee80211_ocb_work(struct ieee80211list_del (&sta->list);spin_unlock_bh (&ifocb->incomplete_lock); -ieee80211_ocb_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_OCB_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ocb_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 819/990 wifi: mac80211: reject invalid EHT guard intervals in airtime estimates
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 582edbdbc5d288bd128b54935738fe38f15c8c29 upstream.
An invalid EHT guard interval can select the wrong airtime group and, at 320 MHz, read beyond airtime_mcs_groups.
Guard interval 3 advances EHT_GROUP_IDX() into the next bandwidth group at narrower widths. With one spatial stream and 320 MHz, it evaluates to 264, one past the 264-entry table. RX rate parsing rejects the value, but the common TX-status validator has no EHT check and last_rate_info can carry it to the airtime helper.
Reject values above NL80211_RATE_INFO_EHT_GI_3_2 in the helper. This also protects exported ieee80211_calc_rx_airtime() callers that do not pass through the TX-status validator.
LLM assistance was used to find the bug and review.
--- net/mac80211/airtime.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/airtime.c +2 -0
@@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(s group =HE_GROUP_IDX (streams, status->he_gi, bw);break ;case RX_ENC_EHT : +if (status->eht.gi >NL80211_RATE_INFO_EHT_GI_3_2 ) +return 0 ; streams = status->nss; idx = status->rate_idx; group =EHT_GROUP_IDX (streams, status->eht.gi, bw);
Greg Kroah-Hartman
maintainerPATCH 820/990 wifi: mac80211: restore dormant links when link updates fail
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit bb22f3b2d8f8a2f883944f24678cf84e18b162e8 upstream.
A failed MLO link update can leave the interface with the requested dormant-links bitmap instead of its previous one. This can disable active links or trigger a bitmap warning during rollback.
The error path restores the old valid-links bitmap but passes the new dormant_links argument to ieee80211_set_vif_links_bitmaps().
Save the old dormant bitmap before changing link state and use it when restoring the old configuration.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/link.c +2 -1
@@ -284,6 +284,7 @@ static int ieee80211_vif_update_links(st {u16 old_links = sdata->vif.valid_links;u16 old_active = sdata->vif.active_links; +u16 old_dormant = sdata->vif.dormant_links;unsigned long add = new_links & ~old_links;unsigned long rem = old_links & ~new_links;unsigned long sta_rem = rem;
@@ -390,7 +391,7 @@ static int ieee80211_vif_update_links(st/* restore config */ memcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old)); -ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +ieee80211_set_vif_links_bitmaps (sdata, old_links, old_dormant);/* drain RCU readers before cancelling work they may queue */ synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {
Greg Kroah-Hartman
maintainerPATCH 821/990 wifi: mac80211: fix use-after-free on TTLM disconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Berg <[email protected]>
commit 4af2b71495a3f12196cbea1c9a502c62ada867be upstream.
If ieee80211_process_adv_ttlm() disconnects, and some other changes were also detected in the beacon, the link update to the driver is still done, leading to use-after-free. Fix this by returning, like other functions, whether or not the update was accepted by the function.
--- net/mac80211/mlme.c | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-)
net/mac80211/mlme.c +14 -11
@@ -7127,15 +7127,15 @@ static void ieee80211_tid_to_link_map_wo sdata->u.mgd.ttlm_info.switch_time =0 ; } -static void ieee80211_process_adv_ttlm (struct ieee80211_sub_if_data *sdata, -struct ieee802_11_elems *elems, -u64 beacon_ts) +static bool ieee80211_process_adv_ttlm (struct ieee80211_sub_if_data *sdata, +struct ieee802_11_elems *elems, +u64 beacon_ts) {u8 i;int ret;if (!ieee80211_vif_is_mld (&sdata->vif)) -return ; +return true;if (!elems->ttlm_num) {if (sdata->u.mgd.ttlm_info.switch_time) {
@@ -7153,14 +7153,14 @@ static void ieee80211_process_adv_ttlm(s 0);if (ret) {sdata_info (sdata,"Failed setting valid/dormant links\n" ); -return ; +return true; }ieee80211_vif_cfg_change_notify (sdata,BSS_CHANGED_MLD_VALID_LINKS ); }memset (&sdata->u.mgd.ttlm_info,0 ,sizeof (sdata->u.mgd.ttlm_info)); -return ; +return true; }for (i =0 ; i < elems->ttlm_num; i++) {
@@ -7172,7 +7172,7 @@ static void ieee80211_process_adv_ttlm(sif (res) {__ieee80211_disconnect (sdata); -return ; +return false; }if (ttlm_info.switch_time) {
@@ -7197,7 +7197,7 @@ static void ieee80211_process_adv_ttlm(s* switch the AP will continue to announce it anyway. */ if (delay >IEEE80211_ADV_TTLM_ST_UNDERFLOW ) -return ; +return true; delay_usec =ieee80211_tu_to_usec (delay);
@@ -7216,9 +7216,11 @@ static void ieee80211_process_adv_ttlm(swiphy_hrtimer_work_queue (sdata->local->hw.wiphy, &sdata->u.mgd.ttlm_work,us_to_ktime (delay_usec)); -return ; +return true; } } + +return true; } static void
@@ -7738,8 +7740,9 @@ static void ieee80211_rx_mgmt_beacon(str elems->cisco_dtpc_elem);ieee80211_ml_reconfiguration (sdata, elems); -ieee80211_process_adv_ttlm (sdata, elems, -le64_to_cpu (mgmt->u.beacon.timestamp)); +if (!ieee80211_process_adv_ttlm (sdata, elems, +le64_to_cpu (mgmt->u.beacon.timestamp))) + goto free; apply:ieee80211_link_info_change_notify (sdata, link, changed);
Greg Kroah-Hartman
maintainerPATCH 822/990 wifi: mac80211: bound pending IBSS station allocations
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 3029ca2112d7bee4d3e3eadd02decdb3eddb9485 upstream.
Delaying the IBSS station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when disconnect frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 13 ++++++++++++- net/mac80211/ieee80211_i.h | 1 + 2 files changed, 13 insertions(+), 1 deletion(-)
net/mac80211/ibss.c +12 -1
@@ -691,6 +691,7 @@ static void ieee80211_ibss_disconnect(stspin_unlock_bh (&ifibss->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
@@ -1207,9 +1208,18 @@ void ieee80211_ibss_rx_no_sta(struct iee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifibss->incomplete_sta_count,1 , +IEEE80211_IBSS_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new IBSS STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifibss->incomplete_sta_count);return ; + }/* make sure mandatory rates are always added */ sband = local->hw.wiphy->bands[band];
@@ -1662,6 +1672,7 @@ void ieee80211_ibss_work(struct ieee8021ieee80211_ibss_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
net/mac80211/ieee80211_i.h +1 -0
@@ -668,6 +668,7 @@ struct ieee80211_if_ibss {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;enum {IEEE80211_IBSS_MLME_SEARCH ,
Greg Kroah-Hartman
maintainerPATCH 787/990 sched/uclamp: Reject clamp values above SCHED_CAPACITY_SCALE
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 8127ec8458df29bd702db602473042ccb9e619b9 upstream.
sched_setattr() accepts sched_util_min and sched_util_max values that do not fit in uclamp_se::value. A single thread can do:
sched_setattr(max = 800) returns 0
sched_setattr(min = 0xfffffffe) returns 0
sched_getattr() min=2046 max=800
which leaves the minimum above both SCHED_CAPACITY_SCALE and the task's own maximum.
The range check in uclamp_validate() relies on the + 1 wrapping -1, the reset value, to 0:
if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
That only works for an unsigned type. util_min and util_max are int and SCHED_CAPACITY_SCALE is a long, so every negative value passes the check, and so does INT_MAX, whose + 1 wraps.
uclamp_se_set() then truncates what got through to the 11 bits of uclamp_se::value, but computes the bucket from the full value. A minimum of 0xfffff800 is stored as 0 in the top bucket, where uclamp_rq_max_value() takes it for the highest active clamp once a higher value leaves the rq. The rq clamp falls below what the remaining tasks requested, and emptying their bucket trips the WARN_ON_ONCE() in uclamp_rq_dec_id(), without any privilege:
WARNING: kernel/sched/core.c:1862 at dequeue_task+0x2a3/0x2b0, CPU#0: repro/126 Call Trace: __schedule+0x933/0x1320 schedule+0x36/0x100 do_nanosleep+0x61/0x190 hrtimer_nanosleep+0xb5/0x1d0
Make util_min and util_max unsigned int, so that -1 is the only value that wraps. The pair check below is unaffected, since it skips -1 explicitly and anything else is at most SCHED_CAPACITY_SCALE by then.
Requests that were only accepted because of this now fail with -EINVAL.
The following program triggers the warning when run by any user outside a child cpu cgroup. With this applied, its 0xfffff800 request fails with -EINVAL and the warning no longer appears:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
uint32_t util_min, util_max;
};static volatile int stop;
static void set_min(uint32_t v)
{
/* KEEP_POLICY | KEEP_PARAMS | UTIL_CLAMP_MIN */
struct attr a = { .size = sizeof(a), .flags = 0x38, .util_min = v };syscall(SYS_sched_setattr, 0, &a, 0);
}
static void burn(long us)
{
struct timespec s, n; clock_gettime(CLOCK_MONOTONIC, &s);
do
clock_gettime(CLOCK_MONOTONIC, &n);
while ((n.tv_sec - s.tv_sec) * 1000000 +
(n.tv_nsec - s.tv_nsec) / 1000 < us);}
static void *bogus(void *arg)
{
set_min(0xfffff800);
while (!stop)
burn(1000);
return arg;
}
static void *worker(void *arg)
{
long v = (long)arg; set_min(v);
while (!stop) {
burn(v == 800 ? 300 : 1500);
usleep(100);
}
return arg;}
int main(void)
{
pthread_t t[3];
cpu_set_t c;
int i; CPU_ZERO(&c);
CPU_SET(0, &c);
sched_setaffinity(0, sizeof(c), &c);
pthread_create(&t[0], NULL, bogus, NULL);
usleep(50000);
pthread_create(&t[1], NULL, worker, (void *)500L);
pthread_create(&t[2], NULL, worker, (void *)800L);
sleep(15);
stop = 1;
for (i = 0; i < 3; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the warning and write this patch and its tests.
--- kernel/sched/syscalls.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/sched/syscalls.c +2 -2
@@ -328,8 +328,8 @@ static inline void __setscheduler_dl_pi(static int uclamp_validate (struct task_struct *p,const struct sched_attr *attr) { -int util_min = p->uclamp_req[UCLAMP_MIN ].value; -int util_max = p->uclamp_req[UCLAMP_MAX ].value; +unsigned int util_min = p->uclamp_req[UCLAMP_MIN ].value; +unsigned int util_max = p->uclamp_req[UCLAMP_MAX ].value;if (attr->sched_flags &SCHED_FLAG_UTIL_CLAMP_MIN ) { util_min = attr->sched_util_min;
Greg Kroah-Hartman
maintainerPATCH 823/990 wifi: mac80211: bound pending OCB station allocations
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit ee1a5e92dba0a98cabe476c780e3af4f0ab88b27 upstream.
Delaying the OCB station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when leave frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ieee80211_i.h | 2 ++ net/mac80211/ocb.c | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-)
net/mac80211/ieee80211_i.h +2 -0
@@ -683,6 +683,7 @@ struct ieee80211_if_ibss {* @wrkq_flags: OCB deferred task action * @incomplete_lock: delayed STA insertion lock * @incomplete_stations: list of STAs waiting for delayed insertion +* @incomplete_sta_count: pending entries and reserved allocations * @joined: indication if the interface is connected to an OCB network */ struct ieee80211_if_ocb {
@@ -691,6 +692,7 @@ struct ieee80211_if_ocb {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;bool joined; };
net/mac80211/ocb.c +12 -1
@@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifocb->incomplete_sta_count,1 , +IEEE80211_OCB_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new OCB STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifocb->incomplete_sta_count);return ; + }/* Add only mandatory rates for now */ sband = local->hw.wiphy->bands[band];
@@ -142,6 +151,7 @@ void ieee80211_ocb_work(struct ieee80211ieee80211_ocb_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
@@ -225,6 +235,7 @@ int ieee80211_ocb_leave(struct ieee80211spin_unlock_bh (&ifocb->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 824/990 gpio: aspeed: Clear only the acked lines G4 interrupt status
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Billy Tsai <[email protected]>
commit 5d362564bd2982def7e80d7f1e756a97440c7adb upstream.
The G4 interrupt status registers are write-1-to-clear: writing 0 to a bit has no effect and writing 1 clears that line's status flag. aspeed_gpio_irq_ack() clears a line's status through aspeed_g4_reg_bit_set(), which reads the bank's status register, sets the line's bit and writes the whole value back. That write clears every interrupt pending in the 32-line bank, not just the acked one.
aspeed_gpio_irq_handler() reads each bank's status register once and dispatches the lines that were set. If another line in the same bank latches an edge after that read and before an ack in the bank, the ack clears its status and the handler is never called for it, so the edge is lost.
Write only the line's own bit when clearing the interrupt status on G4.
--- drivers/gpio/gpio-aspeed.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
drivers/gpio/gpio-aspeed.c +11 -0
@@ -1045,6 +1045,17 @@ static void aspeed_g4_reg_bit_set(structvoid __iomem *addr =aspeed_gpio_g4_bank_reg (gpio, bank, reg);u32 temp; +/* +* The interrupt status register is write-1-to-clear. Write only this +* line's bit so that interrupts pending on the other lines of the bank +* stay latched. +*/ +if (reg == reg_irq_status) { +if (val) +iowrite32 (GPIO_BIT (offset), addr); +return ; + } +if (reg == reg_val) temp = gpio->dcache[GPIO_BANK (offset)];else
Greg Kroah-Hartman
maintainerPATCH 825/990 gpio: aspeed: Preserve the pending G7 interrupt status on control writes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Billy Tsai <[email protected]>
commit 18cc1d1ad94df8a6760fff2617d3d6923550cba0 upstream.
On G7 each line has its own control register, and its interrupt status bit (bit 12) is write-1-to-clear. aspeed_g7_reg_bit_set() updates a field by reading the control register, replacing that field and writing the value back. When the line's interrupt is pending, the status bit reads as 1 and is written back as 1, so updating an unrelated field such as the interrupt enable, trigger type, direction or debounce selection also clears the pending interrupt.
Mask out the status bit when composing the value to write, so it is written as 1 only when the status field itself is being set to ack the interrupt.
--- drivers/gpio/gpio-aspeed.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/gpio/gpio-aspeed.c +7 -1
@@ -1172,7 +1172,13 @@ static void aspeed_g7_reg_bit_set(structu32 write_val;if (mask) { - write_val = (ioread32 (addr) & ~(mask)) |field_prep (mask, val); +/* +* The interrupt status bit is write-1-to-clear. Keep it zero +* unless it is the field being written, so that updating any +* other field leaves a pending interrupt latched. +*/ + write_val =ioread32 (addr) & ~(mask |GPIO_G7_CTRL_IRQ_STS ); + write_val |=field_prep (mask, val);iowrite32 (write_val, addr); } }
Greg Kroah-Hartman
maintainerPATCH 826/990 gpio: brcmstb: fix UAF after IRQ domain setup failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit baa14758afb3e2828de1f76511edc1de50216f39 upstream.
When devm_request_irq() fails in brcmstb_gpio_irq_setup(), the error path removes the IRQ domain but leaves priv->irq_domain non-NULL.
The probe error path subsequently calls brcmstb_gpio_remove(), which checks priv->irq_domain and attempts to access the already-freed domain through irq_find_mapping(). It also attempts to remove the domain again, resulting in a use-after-free and potentially further memory corruption.
Set priv->irq_domain to NULL after removing it so that the common cleanup path skips the already-freed IRQ domain.
This issue was found by our static analysis tool under development.
--- drivers/gpio/gpio-brcmstb.c | 1 + 1 file changed, 1 insertion(+)
drivers/gpio/gpio-brcmstb.c +1 -0
@@ -486,6 +486,7 @@ static int brcmstb_gpio_irq_setup(struct out_free_domain:irq_domain_remove (priv->irq_domain); + priv->irq_domain =NULL ;return err; }
Greg Kroah-Hartman
maintainerPATCH 827/990 gpio: rockchip: Fix debounce arithmetic for GPIO v2
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cunhao Lu <[email protected]>
commit 13467fd6998f5da4f5b4f172f1af3d9c48d5de8f upstream.
The debounce interval calculations use unsigned long operands. On 32-bit systems, the numerator used to calculate the maximum interval overflows before division, while multiplying the requested interval by the clock rate overflows before it is assigned to a u64. A zero debounce clock rate also causes division by zero.
Use 64-bit arithmetic for both calculations and reject a zero clock rate before division.
At 32768 Hz, a 1 us request rounds to zero divider periods. Subtracting one then wraps the divider value to ULONG_MAX. Decrement only a nonzero rounded period count so that such requests use the smallest divider value.
--- drivers/gpio/gpio-rockchip.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpio/gpio-rockchip.c +10 -5
@@ -201,20 +201,25 @@ static int rockchip_gpio_set_debounce(st {struct rockchip_pin_bank *bank =gpiochip_get_data (gc);const struct rockchip_gpio_regs *reg = bank->gpio_regs; -unsigned long flags, div_reg, freq, max_debounce; +unsigned long flags, div_reg, freq;bool div_debounce_support;unsigned int cur_div_reg; -u64 div; +u64 div, max_debounce;if (bank->gpio_type ==GPIO_TYPE_V2 && !IS_ERR (bank->db_clk)) { div_debounce_support = true; freq =clk_get_rate (bank->db_clk); - max_debounce = (GENMASK (23 ,0 ) +1 ) *2 *1000000 / freq; +if (!freq) +return -EINVAL ; + + div = (u64)(GENMASK (23 ,0 ) +1 ) *2 *USEC_PER_SEC ; + max_debounce =div64_u64 (div, freq);if (debounce > max_debounce)return -EINVAL ; - div = debounce * freq; - div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ) -1 ; + div = (u64 )debounce * freq; + div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ); + div_reg = div_reg ? div_reg -1 :0 ; }else { div_debounce_support = false; }
Greg Kroah-Hartman
maintainerPATCH 828/990 gpio: sodaville: fix use-after-free bug when registering the irqchip
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit ab9102375b7c77e0c4d33c7594e514454dc9f2b3 upstream.
In sdv_register_irqsupport(), if irq_domain_create_legacy() fails during device probing, a generic IRQ chip is left registered in the global gc_list while its underlying memory is freed, leading to a use-after-free. Use the managed variant of irq_setup_generic_chip() to ensure that the chip gets unregistered before the memory it uses is freed.
--- drivers/gpio/gpio-sodaville.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/gpio/gpio-sodaville.c +6 -3
@@ -166,9 +166,12 @@ static int sdv_register_irqsupport(struc ct->chip.irq_eoi = irq_gc_eoi; ct->chip.irq_set_type = sdv_gpio_pub_set_type; -irq_setup_generic_chip (sd->gc,IRQ_MSK (SDV_NUM_PUB_GPIOS ), -IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , -IRQ_LEVEL |IRQ_NOPROBE ); + ret =devm_irq_setup_generic_chip (&pdev->dev, sd->gc, +IRQ_MSK (SDV_NUM_PUB_GPIOS ), +IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , +IRQ_LEVEL |IRQ_NOPROBE ); +if (ret) +return ret; sd->id =irq_domain_create_legacy (dev_fwnode (&pdev->dev),SDV_NUM_PUB_GPIOS , sd->irq_base,0 , &irq_domain_sdv_ops, sd);
Greg Kroah-Hartman
maintainerPATCH 829/990 gpio: virtuser: fix interrupt leak and UAF
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit 24cafd9580627f9f066296f4a6ce1b282a3f425d upstream.
When configuring interrupt handlers for GPIOs requested by virtual users, we never verify if an interrupt has been previously requested and just leak it if it was.
We also never free the interrupts at device unbind. This is both a leak and a potential UAF bug.
We use atomic_t for the irq field for now reason, it can't be modifying or read from atomic context. Let's repurpose the existing consumer_lock mutex and serialize access to the irq field. Let's add sanitization of input and schedule a tear-down action.
--- drivers/gpio/gpio-virtuser.c | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -10
@@ -58,9 +58,9 @@ struct gpio_virtuser_line_array_data {struct gpio_virtuser_line_data {struct gpio_virtuser_attr_data ad;char consumer[GPIO_VIRTUSER_NAME_BUF_LEN ]; -struct mutex consumer_lock; +struct mutex lock;unsigned int debounce; -atomic_t irq; +int irq;atomic_t irq_count; };
@@ -612,7 +612,7 @@ static ssize_t gpio_virtuser_consumer_rememset (buf,0x0 ,sizeof (buf)); -scoped_guard (mutex, &data->consumer_lock) +scoped_guard (mutex, &data->lock) ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer);return simple_read_from_buffer (user_buf, size, ppos, buf, ret);
@@ -640,7 +640,7 @@ static ssize_t gpio_virtuser_consumer_wrif (ret)return ret; - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock)strscpy (data->consumer, buf,sizeof (data->consumer));return count;
@@ -680,7 +680,12 @@ static int gpio_virtuser_interrupts_set(if (val >1 )return -EINVAL ; +guard (mutex)(&ld->lock); +if (val) { +if (ld->irq >=0 ) +return -EBUSY ; + irq =gpiod_to_irq (ld->ad.desc);if (irq <0 )return irq;
@@ -694,11 +699,13 @@ static int gpio_virtuser_interrupts_set(if (ret)return ret; -atomic_set (&ld->irq, irq); + ld->irq = irq; }else { - irq =atomic_xchg (&ld->irq,0 ); -if (irq) -free_irq (irq, ld); +if (ld->irq <0 ) +return -EBUSY ; + +free_irq (ld->irq, ld); + ld->irq =-1 ; }return 0 ;
@@ -798,6 +805,14 @@ static int gpio_virtuser_dbgfs_init_line data->ad.dbgfs_dir, data); } +static void gpio_virtuser_free_irq (void *data) +{ +struct gpio_virtuser_line_data *ld = data; + +if (ld->irq >=0 ) +free_irq (ld->irq, ld); +} + static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, struct gpio_desc *desc, const char *id,
@@ -814,14 +829,18 @@ static int gpio_virtuser_dbgfs_init_line data->ad.desc = desc;strscpy (data->consumer, id); -atomic_set (&data->irq,0 ); + data->irq =-1 ;atomic_set (&data->irq_count,0 ); + ret =devm_add_action_or_reset (dev, gpio_virtuser_free_irq, data); +if (ret) +return ret; + name =devm_kasprintf (dev,GFP_KERNEL ,"gpiod:%s:%u" , id, index);if (!name)return -ENOMEM ; - ret =devm_mutex_init (dev, &data->consumer_lock); + ret =devm_mutex_init (dev, &data->lock);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 830/990 gpio: virtuser: remove the debugfs files before freeing the line data
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
commit c2d0710318b8cd57d0ef6088d0ee4bbc1e827fd3 upstream.
gpio_virtuser_probe() registers the devm action that removes the debugfs directory before it allocates the per-line and per-array data that the debugfs files point to. devres releases resources in reverse order, so on unbind the line data is freed, the consumer_lock mutex is destroyed and the GPIO descriptors are put first, and the debugfs files are only removed afterwards.
A read or write of any of the per-line debugfs files (value, direction, consumer, interrupts, ...) that runs in that window dereferences the freed data. debugfs_remove_recursive() waits for in-flight file operations, but by then the data has already been freed.
Running eight threads that read the per-line debugfs files while another task writes 1 and 0 to the configfs "live" attribute triggers this within a second on a KASAN kernel, with gpio-sim as the provider:
BUG: KASAN: slab-use-after-free in gpio_virtuser_value_get+0x19/0x60 Read of size 8 at addr ffff888005109e38 by task vu_race/3479 Call Trace: gpio_virtuser_value_get+0x19/0x60 simple_attr_read+0x109/0x290 debugfs_attr_read+0x5e/0x80 full_proxy_read+0xae/0xe0 vfs_read+0x1bc/0x7a0 Allocated by task 1: devm_kmalloc+0x89/0x1d0 gpio_virtuser_probe+0x56f/0x910 Freed by task 1: kfree+0x196/0x430 release_nodes+0x77/0xa0 devres_release_all+0xf3/0x150 device_unbind_cleanup+0x18/0x130 ... platform_device_unregister+0x3c/0x50 gpio_virtuser_device_deactivate+0x3c/0xc0
The same run also reports use-after-free on the freed consumer_lock from the consumer attribute.
Register the debugfs removal action after the line data has been set up, so that it runs first on unbind, and remove the directory by hand on the probe error paths before that point.
--- drivers/gpio/gpio-virtuser.c | 46 +++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 17 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -17
@@ -951,38 +951,50 @@ static int gpio_virtuser_probe(struct pl "Failed to get the IDs of GPIOs to request\n"); dbgfs_entry =debugfs_create_dir (dev_name (dev), gpio_virtuser_dbg_root); - ret =devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, - dbgfs_entry); -if (ret) -return ret;for (i =0 ; i < num_ids; i++) { descs =devm_gpiod_get_array (dev, ids[i],GPIOD_ASIS ); -if (IS_ERR (descs)) -return dev_err_probe (dev,PTR_ERR (descs), -"Failed to request the '%s' GPIOs\n" , - ids[i]); +if (IS_ERR (descs)) { + ret =dev_err_probe (dev,PTR_ERR (descs), +"Failed to request the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } ret =gpio_virtuser_dbgfs_init_line_array_attrs (dev, descs, ids[i], dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + }for (j =0 ; j < descs->ndescs; j++) { ret =gpio_virtuser_dbgfs_init_line_attrs (dev, descs->desc[j], ids[i], j, dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } } } -return 0 ; +/* +* The debugfs files point to the devres-managed line data allocated +* above. Register the removal last so that it runs first on unbind, +* before any of that data is released. +*/ +return devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, + dbgfs_entry); + +err_remove_debugfs: +debugfs_remove_recursive (dbgfs_entry); +return ret; }static const struct of_device_id gpio_virtuser_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 788/990 sched/core: Fix cpuset_mutex double unlock in __sched_setscheduler()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit f7141257dd67d4936f906a6cfd1d0007721f6898 upstream.
A sched_setattr() with SCHED_FLAG_KEEP_POLICY on a SCHED_DEADLINE task unlocks cpuset_mutex twice if the task's policy changes concurrently:
WARNING: bad unlock balance detected! 7.4.0-rc1 #1 Not tainted
-------------------------------------
repro/126 is trying to release lock (cpuset_mutex) at:
[<ffffffff9a17cacc>] __sched_setscheduler+0x9cc/0xc40 but there are no more locks to release! ... Call Trace: print_unlock_imbalance_bug.part.0+0xfb/0x110 lock_release+0x286/0x2e0 __mutex_unlock_slowpath+0x1a/0x400 __sched_setscheduler+0x9cc/0xc40 __x64_sys_sched_setattr+0xa3/0x1b0 do_syscall_64+0x106/0x5f0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
__sched_setscheduler() samples p->policy before taking any lock, and restarts from the recheck label if p->policy differs under the rq lock. The restart drops cpuset_mutex but leaves cpuset_locked set, so a pass that no longer needs the mutex still unlocks it on its way out:
CPU 1 CPU 2
__sched_setscheduler(KEEP_POLICY)
policy = p->policy /* DEADLINE */
__sched_setscheduler(SCHED_OTHER)
p->policy = SCHED_OTHER
cpuset_locked = true
cpuset_lock()
rq = task_rq_lock(p)
oldpolicy != p->policy
cpuset_unlock()
goto recheck
/* no cpuset_lock() this time */
...
if (cpuset_locked)
cpuset_unlock()Without CONFIG_DEBUG_MUTEXES, or CONFIG_DEBUG_RT_MUTEXES on PREEMPT_RT, nothing warns. The second unlock still clears the owner field regardless of who holds the mutex, so another task can lose cpuset_mutex inside its critical section. Entering SCHED_DEADLINE needs CAP_SYS_NICE, but a racing caller that owns the task does not need it if it samples a policy other than SCHED_DEADLINE.
Clear cpuset_locked when dropping the mutex for the restart. This should be safe because the flag is only tested on the paths leaving the next pass, after that pass has set it again if it took the mutex.
The following program, run as root, reproduces the splat, which no longer appears with this applied. On PREEMPT_RT it crashes the kernel within seconds, which this also fixes:
#define _GNU_SOURCE
#include <pthread.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static void set(struct attr a)
{
a.size = sizeof(a);
syscall(SYS_sched_setattr, target, &a, 0);
}
static void *sleeper(void *arg)
{
target = syscall(SYS_gettid);
while (!stop)
usleep(1000);
return arg;
}
static void *switcher(void *arg)
{
while (!stop) {
/* SCHED_DEADLINE, 2us every 1s */
set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 });
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
return arg;
}
static void *racer(void *arg)
{
/* KEEP_POLICY | KEEP_PARAMS */
while (!stop)
set((struct attr){ .flags = 0x18 });
return arg;
}
int main(void)
{
pthread_t t[5];
int i; pthread_create(&t[0], NULL, sleeper, NULL);
while (!target)
usleep(100);
pthread_create(&t[1], NULL, switcher, NULL);
for (i = 2; i < 5; i++)
pthread_create(&t[i], NULL, racer, NULL);
sleep(30);
stop = 1;
for (i = 0; i < 5; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the PREEMPT_RT crash and write this patch and its test.
--- kernel/sched/syscalls.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +3 -1
@@ -650,8 +650,10 @@ change:if (unlikely (oldpolicy !=-1 && oldpolicy != p->policy)) { policy = oldpolicy =-1 ;task_rq_unlock (rq, p, &rf); -if (cpuset_locked) +if (cpuset_locked) {cpuset_unlock (); + cpuset_locked = false; + } goto recheck; }
Greg Kroah-Hartman
maintainerPATCH 789/990 sctp: abort unordered partial delivery when its message is skipped
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 05852c8b70f2291a50bb3f740a66ce9caf9cb98d upstream.
When an I-FORWARD-TSN skips unordered messages on a stream, sctp_intl_skip() only aborts the stream's unordered partial delivery if the MID being delivered is lower than the skipped MID. If the skipped message is the one being partially delivered, partial delivery stays in
progress: no PARTIAL_DELIVERY_ABORTED is sent, and the next unordered message on the stream is delivered as the rest of the abandoned one.
Abort the partial delivery when the MID being delivered is at or below the skipped MID, as the ordered case already does.
Reproduced on an unmodified kernel with the uo_pd test of the sctp_ifwdtsn.sh selftest added later in this series; its partial delivery checks pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/stream_interleave.c +1 -1
@@ -1255,7 +1255,7 @@ static void sctp_intl_skip(struct sctp_ustruct sctp_stream *stream = &ulpq->asoc->stream;if (flags &SCTP_FTSN_U_BIT ) { -if (sin->pd_mode_uo &&MID_lt (sin->mid_uo, mid)) { +if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ;sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC );
Greg Kroah-Hartman
maintainerPATCH 790/990 sctp: avoid requeueing pending control chunks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 665b4149e91b781a71bce8637c3a4d7d64dba05f upstream.
The T4 and RE-CONFIG timeout handlers take a reference to their cached control chunk and submit it through SCTP_CMD_REPLY. A previous transmission can still be on the control outqueue when output is corked or suppressed, or when sctp_packet_transmit_chunk() could not append the chunk.
sctp_outq_tail() then adds the same list node a second time. Re-adding a non-tail entry can corrupt the list without being caught by the insertion-time list checks. A subsequent flush or association teardown can access an already freed chunk. The ASCONF path is reproducible by an unprivileged SCTP socket owner in a user/network namespace, with KASAN reporting a use-after-free in __sctp_outq_teardown().
Check sctp_chunk_pending() in both timeout handlers before taking the extra reference and issuing SCTP_CMD_REPLY. If the chunk is already linked, leave the existing entry for normal output processing. Keep the remaining timer and error-handling commands unchanged. This also covers RE-CONFIG retransmission after sctp_assoc_rm_peer() moves the request to another transport and starts its timer.
The issue was found by an LLM.
--- net/sctp/sm_statefuns.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
net/sctp/sm_statefuns.c +10 -6
@@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_reconreturn SCTP_DISPOSITION_DELETE_TCB ; } -sctp_chunk_hold (asoc->strreset_chunk); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->strreset_chunk)); +if (!sctp_chunk_pending (asoc->strreset_chunk)) { +sctp_chunk_hold (asoc->strreset_chunk); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->strreset_chunk)); + }sctp_add_cmd_sf (commands,SCTP_CMD_STRIKE ,SCTP_TRANSPORT (transport));return SCTP_DISPOSITION_CONSUME ;
@@ -6194,9 +6196,11 @@ enum sctp_disposition sctp_sf_t4_timer_e* chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ -sctp_chunk_hold (asoc->addip_last_asconf); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->addip_last_asconf)); +if (!sctp_chunk_pending (asoc->addip_last_asconf)) { +sctp_chunk_hold (asoc->addip_last_asconf); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->addip_last_asconf)); + }/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new
Greg Kroah-Hartman
maintainerPATCH 791/990 sctp: fix ASCONF address change on single-homed hosts
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 5175b2fb34c77cf2cd56a290affa45412cb3a228 upstream.
Commit 9b2854f86f0b ("sctp: don't free the ASCONF's own transport in DEL-IP processing") refuses a DEL-IP of the transport the ASCONF was located by, so that a later wildcard DEL-IP cannot use it after free.
This also breaks the single-homed address change (RFC 5061 5.3.2). The host sends [Address Parameter L] [ADD-IP S] [DEL-IP L], the association is located by L, and DEL-IP L is now refused. The sender never gets an all-success ASCONF-ACK, keeps src_out_of_asoc_ok set and stops sending data, so the association stalls.
Fix the wildcard DEL-IP instead: look up the transport of the packet source rather than reusing asconf->transport. Both DEL-IP paths can now free asconf->transport, and chunks bundled after the ASCONF still use it, so point it at a surviving transport: the packet source for the wildcard delete, the primary path for a plain one.
Found by manual code inspection while reviewing a backport of commit 9b2854f86f0b; reproduced on a two-namespace single-homed renumber.
--- net/sctp/sm_make_chunk.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
net/sctp/sm_make_chunk.c +8 -9
@@ -3157,9 +3157,12 @@ static __be16 sctp_process_asconf_param(* packet MUST be deleted. */ if (af->is_any (&addr)) { -sctp_assoc_set_primary (asoc, asconf->transport); -sctp_assoc_del_nonprimary_peers (asoc, - asconf->transport); + peer =sctp_assoc_lookup_paddr (asoc, &asconf->source); +if (!peer) +return SCTP_ERROR_REQ_REFUSED ; +sctp_assoc_set_primary (asoc, peer); +sctp_assoc_del_nonprimary_peers (asoc, peer); + asconf->transport = peer;return SCTP_ERROR_NO_ERROR ; }
@@ -3172,13 +3175,9 @@ static __be16 sctp_process_asconf_param(if (!peer)return SCTP_ERROR_DNS_FAILED ; -/* Don't free asconf->transport; a later wildcard DEL-IP -* parameter reuses it. -*/ -if (peer == asconf->transport) -return SCTP_ERROR_REQ_REFUSED ; -sctp_assoc_rm_peer (asoc, peer); +if (asconf->transport == peer) + asconf->transport = asoc->peer.primary_path;break ;case SCTP_PARAM_SET_PRIMARY :/* ADDIP Section 4.2.4
Greg Kroah-Hartman
maintainerPATCH 792/990 sctp: fix I-FORWARD-TSN handling of fragments on other streams
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 5b9cfc6491a6e32e7315dc222992c7dbd5baa3e9 upstream.
sctp_report_iftsn() incorrectly frees queued I-DATA fragments in two cases. First, it drops any queued fragments with TSN less than or equal to the New Cumulative TSN. This prevents reconstruction of messages still being received on other streams and can fully block an ordered stream. Second, it calls sctp_intl_abort_pd() if the New Cumulative TSN equals the highest TSN seen. This check exists for association resets but can be inadvertently triggered by any I-FORWARD-TSN that arrives before data with a higher TSN, causing data loss and, if a partial delivery is in progress on an ordered stream, an aborted association.
Fix the first by freeing fragments from sctp_intl_skip() based on stream, U bit, and MID instead of TSN. Fix the second by moving the call to sctp_intl_abort_pd() from sctp_report_iftsn() to the corresponding reset handlers.
Observed in real use as unexpected message loss. Reproduced on an unmodified kernel with the sctp_ifwdtsn.sh selftest added later in this series, which passes with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream.c | 2 ++ net/sctp/stream_interleave.c | 32 +++++++++++--------------------- 2 files changed, 13 insertions(+), 21 deletions(-)
net/sctp/stream.c +2 -0
@@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset*/ max_tsn_seen =sctp_tsnmap_get_max_tsn_seen (&asoc->peer.tsn_map); asoc->stream.si->report_ftsn (&asoc->ulpq, max_tsn_seen); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC );/* G1: Compute an appropriate value for the Receiver's Next TSN -- the * TSN that the peer should use to send the next DATA chunk. The
@@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strresetLIST_HEAD (temp); asoc->stream.si->report_ftsn (&asoc->ulpq, mtsn); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC ); sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
net/sctp/stream_interleave.c +11 -21
@@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct scsctp_ulpq_abort_pd (ulpq,GFP_ATOMIC ); } -static void sctp_intl_reasm_flushtsn (struct sctp_ulpq *ulpq,__u32 ftsn) +static void sctp_intl_reasm_flush_mid (struct sk_buff_head *reasm,__u16 sid, +__u32 mid) {struct sk_buff *pos, *tmp; - skb_queue_walk_safe(&ulpq->reasm, pos, tmp) { + skb_queue_walk_safe(reasm, pos, tmp) {struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm); -sctp_ulpevent_free (event); - } - } +if (event->stream < sid) +continue ; +if (event->stream > sid ||MID_lt (mid, event->mid)) +break ; - skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) { -struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; - -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm_uo); -sctp_ulpevent_free (event); - } +__skb_unlink (pos, reasm); +sctp_ulpevent_free (event); } }
@@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sct {/* Move the Cumulattive TSN Ack ahead. */ sctp_tsnmap_skip (&ulpq->asoc->peer.tsn_map, ftsn); -/* purge the fragmentation queue */ -sctp_intl_reasm_flushtsn (ulpq, ftsn); -/* abort only when it's for all data */ -if (ftsn ==sctp_tsnmap_get_max_tsn_seen (&ulpq->asoc->peer.tsn_map)) -sctp_intl_abort_pd (ulpq,GFP_ATOMIC ); }static void sctp_handle_fwdtsn (struct sctp_ulpq *ulpq,struct sctp_chunk *chunk)
@@ -1260,6 +1248,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);return ; }
@@ -1271,6 +1260,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);sctp_mid_skip (stream, in, sid, mid);sctp_intl_reap_ordered (ulpq, sid);
Greg Kroah-Hartman
maintainerPATCH 783/990 hwmon: (max31760) Report 0 RPM before the first fan speed measurement
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 33d58cbf2ab26bda81bc3052158d8b9867d5b9a6 upstream.
The tachometer count registers initialize to 0 until the first measurement cycle completes after power-on. To prevent division by zero, tach_to_rpm() clamped tach == 0 to 1, causing it to compute and report 3,000,000 RPM (60 * 100000 / 1 / 2).
Return 0 RPM when tach == 0 instead.
--- drivers/hwmon/max31760.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/max31760.c +2 -1
@@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {static int tach_to_rpm (u16 tach) { +/* The count is 0 until the first measurement */ if (tach ==0 ) - tach =1 ; +return 0 ;return 60 *100000 / tach /2 ; }
Greg Kroah-Hartman
maintainerPATCH 832/990 ovl: reject different lower idmaps on the same fs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 720f40c05b2785406121da0151543751204f2953 upstream.
Overayfs mounted with index=on or nfs_export=on require file handle support from backing filesystems.
Overlay file handles identify a backing filesystem, but not the lower mount used to decode it. If lower layers share a superblock and use different idmaps, a handle can decode through the wrong layer.
Record the first idmap on a private lower clone for each backing filesystem. Fail if another clone has a different idmap. Comparing the private clones prevents mount_setattr() from changing the checked state. Distinct idmap objects are treated as ambiguous.
--- fs/overlayfs/ovl_entry.h | 2 ++ fs/overlayfs/super.c | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+)
fs/overlayfs/ovl_entry.h +2 -0
@@ -24,6 +24,8 @@ struct ovl_config {struct ovl_sb {struct super_block *sb;dev_t pseudo_dev; +/* Idmap of the first lower layer on this fs */ +const struct mnt_idmap *lower_idmap;/* Unusable (conflicting) uuid */ bool bad_uuid;/* Used as a lower layer (but maybe also as upper) */
fs/overlayfs/super.c +23 -0
@@ -1125,6 +1125,29 @@ static int ovl_get_layers(struct super_b }/* +* Lower file handles identify the lower fs, but not the layer, +* so with different idmaps on the same lower fs, index and +* nfs_export may decode a file handle through a layer with the +* wrong idmap. Following copy up origin without index is only +* used for st_ino, which does not depend on the idmap. +*/ +if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { +const struct mnt_idmap *idmap =mnt_idmap (mnt); +struct ovl_sb *fs = &ofs->fs[fsid]; + +if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + }else if (fs->lower_idmap != idmap) { +pr_err ("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n" , + l->path.dentry); +iput (trap); +kern_unmount (mnt); +return -EINVAL ; + } + } + +/* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */
Greg Kroah-Hartman
maintainerPATCH 841/990 smb: client: fix OOB write when compounding SMB2_IOCTL with encryption
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 73a0060cb22a1d2bd8bff364c18a4259ec0cb528 upstream.
On an encrypted ("seal") mount, SMB2_ioctl_init() keeps the IOCTL input in a separate iov (iov[1]); iov[0] is a 448-byte buffer from cifs_small_buf_get(). When such an IOCTL is not the last request of a compound, smb2_set_next_command() pads it for alignment by copying the whole request into iov[0]. A large enough input overflows that 448-byte buffer and corrupts the slab; the copy also sets rq_nvec to 1, so the input buffer is leaked too.
An unprivileged user can trigger it by creating a symlink with a long target on such a mount: the native symlink is sent as FSCTL_SET_REPARSE_POINT + QUERY_INFO + CLOSE in one compound, so the IOCTL is not the last request.
With slub_debug red zones on the cifs_small_rq cache, the overflow is caught on the next allocation from that cache in the same compound (the 0x61 bytes are the 'a' characters of the symlink target):
BUG cifs_small_rq (Not tainted): Object corrupt
[Left Redzone overwritten] 0xffff8a59c7790500-0xffff8a59c779053f First byte 0x61 instead of 0xbb
Call Trace: check_object+0x1a8/0x350 alloc_debug_processing+0xab/0x110 ___slab_alloc+0x7e/0x2f0 kmem_cache_alloc_noprof+0x28d/0x4b0 mempool_alloc_slab+0x16/0x30 cifs_small_buf_get+0x1a/0x30 [cifs] SMB2_close_init+0x8a/0x100 [cifs] smb2_compound_op+0x2571/0x2b50 [cifs] smb2_create_reparse_inode+0x27e/0x490 [cifs] mknod_nfs+0x1ce/0x2e0 [cifs] create_reparse_symlink+0x119/0x180 [cifs] cifs_symlink+0x19f/0x8e0 [cifs] vfs_symlink+0xa3/0x1b0 __x64_sys_symlink+0x41/0x70
Pad the input to a multiple of 8 bytes when encryption is required. The request is then already aligned and smb2_set_next_command() no longer copies it; InputCount still carries the real length.
--- fs/smb/client/smb2pdu.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/smb/client/smb2pdu.c +8 -4
@@ -3354,11 +3354,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, char *in_data, u32 indatalen, __u32 max_response_size) { - struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; +struct smb2_ioctl_req *req; +u32 in_buf_len = indatalen;unsigned int total_len; -int rc;char *in_data_buf; +int rc; rc =smb2_ioctl_req_init (opcode, tcon, server, (void **) &req, &total_len);
@@ -3366,15 +3367,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,return rc;if (indatalen) { +if (smb3_encryption_required (tcon)) + in_buf_len =ALIGN (indatalen,8 );/* * indatalen is usually small at a couple of bytes max, so * just allocate through generic pool */ - in_data_buf =kmemdup (in_data, indatalen,GFP_NOFS ); + in_data_buf =kzalloc (in_buf_len,GFP_NOFS );if (!in_data_buf) {cifs_small_buf_release (req);return -ENOMEM ; } +memcpy (in_data_buf, in_data, indatalen); } req->CtlCode =cpu_to_le32 (opcode);
@@ -3398,7 +3402,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, rqst->rq_nvec =2 ; iov[0 ].iov_len = total_len -1 ; iov[1 ].iov_base = in_data_buf; - iov[1 ].iov_len = indatalen; + iov[1 ].iov_len = in_buf_len; }else { rqst->rq_nvec =1 ; iov[0 ].iov_len = total_len;
Greg Kroah-Hartman
maintainerPATCH 842/990 smb: client: fix out-of-bounds read in dfs_parse_target_referral()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
commit 86aacc2f3f6ba18e1d87feee24f37c94b3ce863a upstream.
dfs_parse_target_referral() decides whether a prefix path remains after the consumed part of full_path with:
if (strlen(full_path) - ref->path_consumed)
strlen() returns size_t, so if path_consumed is larger than the length of full_path, the subtraction wraps around to a huge non-zero value. The branch is then taken, prepath is set to a pointer past the terminating NUL of full_path, and *prepath reads out of bounds.
path_consumed can exceed strlen(full_path) when the mount charset is not utf8. The referral code derives path_consumed from the canonical path, which is in the DFS cache charset (utf8), but it is applied here to full_path, which is in the mount charset. Each non-ASCII character in the consumed part of the path that is longer in utf8 than in the mount charset makes the count too large by the difference.
This was reproduced with iocharset=iso8859-1 against a Samba DFS root containing a link named "café", mounting with the single Latin-1 byte 0xe9 in the path. On an unmodified tree such a mount fails earlier with -ENOENT because the path is converted to utf8 twice in setup_dfs_ref(); with that fixed ("smb: client: fix double conversion of DFS path in setup_dfs_ref()"), the mount reaches this code. full_path was 29 bytes while path_consumed was 30:
BUG: KASAN: slab-out-of-bounds in dfs_parse_target_referral+0x26a/0x270 Read of size 1 at addr ffff88810db89d5f by task mount/1743 ... The buggy address is located 0 bytes to the right of allocated 31-byte region [ffff88810db89d40, ffff88810db89d5f)
Compare path_consumed against the string length instead of subtracting, so that no prefix path is used when the consumed count covers the whole string. With the bounds check in place the same mount succeeds and no KASAN report is produced.
This only prevents the out-of-bounds access. path_consumed is still in the wrong units, so a non-ASCII link followed by a path component can still produce a wrong prefix path. That needs a separate fix.
--- fs/smb/client/dfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/dfs.c +1 -1
@@ -33,7 +33,7 @@ int dfs_parse_target_referral(const charif (WARN_ON_ONCE (!ref->node_name || ref->path_consumed <0 ))return -EINVAL ; -if (strlen (full_path) - ref->path_consumed) { +if ((size_t )ref->path_consumed <strlen (full_path)) { prepath = full_path + ref->path_consumed;/* skip initial delimiter */ if (*prepath =='/' || *prepath =='\\' )
Greg Kroah-Hartman
maintainerPATCH 843/990 smb: client: flush deferred handles of other names before a hard link open
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 25912ed3b75dcf5ff623dcb549b925dd0d0948f7 upstream.
Opening a hard link of a file whose other name still holds a deferred, leased handle fails with EINVAL over SMB3. The client caches lease keys per inode, but the server ties a lease to the file name it was granted under, so reusing the inode's lease key to open a different name of the same inode is rejected with STATUS_INVALID_PARAMETER (MS-SMB2 3.3.5.9.11).
Commit 262b73ef442e ("smb3 client: fix open hardlink on deferred close file error") already closes the inode's deferred handles before such an open so the new name can take a fresh lease, but cifs_get_hardlink_path() only triggered that flush when a cached handle had the same open flags as the new open, so a differently accessed name - written then read, say - slipped through and still failed.
Match on the name instead: flush when a cached handle for another name of the inode is open, regardless of access mode.
--- fs/smb/client/file.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/file.c +1 -1
@@ -2206,7 +2206,7 @@ cifs_get_hardlink_path(struct cifs_tconspin_lock (&cinode->open_file_lock);list_for_each_entry (open_file, &cinode->openFileList, flist) { -if (file->f_flags == open_file->f_flags) { +if (open_file->dentry !=file_dentry (file)) { rc = -EINVAL ;break ; }
Greg Kroah-Hartman
maintainerPATCH 844/990 smb: client: hold the inode across cifs_oplock_break()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit fce78321f1b59531cf6fc94860550db1db8dec55 upstream.
cifs_oplock_break() drops the handle reference in the middle of the handler and keeps using cinode afterwards, to send the break acknowledgment and again in cifs_done_oplock_break(). The reference cifs_queue_oplock_break() takes is the only pin: the handle holds the dentry and the dentry is what keeps the inode alive.
When that put is the last reference, the dput() in cifsFileInfo_put_final() kills an unhashed dentry, drops the last i_count and evicts the inode, so the rest of the handler runs on an object whose free is only RCU-deferred. An unhashed dentry that a handle still references is an ordinary state: unlinking an open file leaves the dentry that way, and so does the dcache teardown at unmount.
Take a reference on the inode for the lifetime of the handler and drop it once the break has been reported. This also covers the cifs_get_tlink() failure path, where the put is followed directly by the out label.
--- fs/smb/client/file.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/smb/client/file.c +9 -0
@@ -3284,6 +3284,14 @@ void cifs_oplock_break(struct work_struc__u64 persistent_fid, volatile_fid;__u16 net_fid; +/* +* Dropping the handle reference below also drops the dentry +* reference that pins this inode, and cinode is still needed to +* acknowledge the break and to report it as complete. Hold the inode +* until that is done. +*/ +ihold (inode); +wait_on_bit (&cinode->flags,CIFS_INODE_PENDING_WRITERS ,TASK_UNINTERRUPTIBLE );
@@ -3359,6 +3367,7 @@ oplock_break_ack:cifs_put_tlink (tlink); out:cifs_done_oplock_break (cinode); +iput (inode); } static int cifs_swap_activate(struct swap_info_struct *sis,
Greg Kroah-Hartman
maintainerPATCH 845/990 smb: client: issue writes from a worker if the task is dying
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 1a747bacf250959703c68fed1bb643f888dd3ad2 upstream.
A task with a fatal signal pending can't send on the socket:__smb_send_rqst() refuses it upfront with -ERESTARTSYS, as SIGKILL can't be blocked and a send interrupted halfway forces a reconnect. Writeback, however, runs in the context of whoever starts it, so when a dying task flushes dirty pages - close() racing with SIGKILL, or fd teardown during exit_group() - every write subrequest gets refused:
smb3_write_err: ... offset=0x1400000 len=0x400000 rc=-512
cifs_flush_err: ino=... rc=-512
Since the switch to netfslib, a failed upload ends writeback with the folios clean, so the data is silently lost: the server ends up with 20MiB of a 64MiB file while stat(2) reports the full size.
Issue writeback subrequests of dying tasks from a new cifswritebackd workqueue instead, like afs does for all of its writes, so they get sent from a context with no signals. Leave direct and unbuffered writes alone, as their callers get the error. Use a dedicated WQ_UNBOUND workqueue as the writes may block for long on credits, sends or reopens, e.g. on hard mounts with an unresponsive server, and must not hold up other cifs work such as reconnects, nor starve the WQ_MEM_RECLAIM rescuer of cifsiod_wq.
--- fs/smb/client/cifsfs.c | 13 ++++++++++++- fs/smb/client/cifsglob.h | 1 + fs/smb/client/file.c | 26 +++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 2 deletions(-)
fs/smb/client/cifsfs.c +12 -1
@@ -198,6 +198,7 @@ struct workqueue_struct *cifsoplockd_wq;struct workqueue_struct *deferredclose_wq;struct workqueue_struct *serverclose_wq;struct workqueue_struct *cfid_put_wq; +struct workqueue_struct *cifs_writeback_wq;__u32 cifs_lock_secret;/*
@@ -2076,9 +2077,16 @@ init_cifs(void) goto out_destroy_serverclose_wq; } + cifs_writeback_wq =alloc_workqueue ("cifswritebackd" , +WQ_UNBOUND |WQ_MEM_RECLAIM ,0 ); +if (!cifs_writeback_wq) { + rc = -ENOMEM ; + goto out_destroy_cfid_put_wq; + } + rc =cifs_init_inodecache ();if (rc) - goto out_destroy_cfid_put_wq; + goto out_destroy_writeback_wq; rc =cifs_init_netfs ();if (rc)
@@ -2149,6 +2157,8 @@ out_destroy_netfs:cifs_destroy_netfs (); out_destroy_inodecache:cifs_destroy_inodecache (); +out_destroy_writeback_wq: +destroy_workqueue (cifs_writeback_wq); out_destroy_cfid_put_wq:destroy_workqueue (cfid_put_wq); out_destroy_serverclose_wq:
@@ -2194,6 +2204,7 @@ exit_cifs(void)destroy_workqueue (fileinfo_put_wq);destroy_workqueue (serverclose_wq);destroy_workqueue (cfid_put_wq); +destroy_workqueue (cifs_writeback_wq);destroy_workqueue (cifsiod_wq); }
fs/smb/client/cifsglob.h +1 -0
@@ -2108,6 +2108,7 @@ extern struct workqueue_struct *cifsoploextern struct workqueue_struct *deferredclose_wq;extern struct workqueue_struct *serverclose_wq;extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq;extern __u32 cifs_lock_secret;extern mempool_t *cifs_sm_req_poolp;
fs/smb/client/file.c +25 -1
@@ -106,10 +106,16 @@ retry:#endif } +static bool cifs_writeback_dying (struct netfs_io_subrequest *subreq) +{ +return subreq->rreq->origin ==NETFS_WRITEBACK && +fatal_signal_pending (current); +} +/* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write (struct netfs_io_subrequest *subreq) +static void __cifs_issue_write (struct netfs_io_subrequest *subreq) {struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq);
@@ -143,6 +149,24 @@ fail: goto out; } +static void cifs_issue_write_worker (struct work_struct *work) +{ +struct netfs_io_subrequest *subreq; + + subreq = container_of(work, struct netfs_io_subrequest, work); +__cifs_issue_write (subreq); +} + +static void cifs_issue_write (struct netfs_io_subrequest *subreq) +{ +if (unlikely (cifs_writeback_dying (subreq))) { + subreq->work.func = cifs_issue_write_worker; +WARN_ON_ONCE (!queue_work (cifs_writeback_wq, &subreq->work)); +return ; + } +__cifs_issue_write (subreq); +} +static void cifs_netfs_invalidate_cache (struct netfs_io_request *wreq) {cifs_invalidate_cache (wreq->inode,0 );
Greg Kroah-Hartman
maintainerPATCH 846/990 smb: client: retry writes that couldnt be issued due to a reconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 64db0dc1f3e689145e698bc1b20ee70b1724b945 upstream.
__cifs_issue_write() fails a subrequest with -EAGAIN when its handle got invalidated or its credits belong to a session from before a reconnect, both before sending anything. netfs used to retry any -EAGAIN by itself, but now only retries subrequests marked for it, so these writes fail and their folios end writeback clean, losing the data.
Mark them for retry instead. The retry gets the handle reopened and fresh credits in cifs_prepare_write().
--- fs/smb/client/file.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/file.c +4 -2
@@ -140,10 +140,12 @@ out:return ; fail: -if (rc == -EAGAIN ) +if (rc == -EAGAIN ) {trace_netfs_sreq (subreq, netfs_sreq_trace_retry); -else +__set_bit (NETFS_SREQ_NEED_RETRY , &subreq->flags); + }else {trace_netfs_sreq (subreq, netfs_sreq_trace_fail); + }add_credits_and_wake_if (wdata->server, &wdata->credits,0 );cifs_write_subrequest_terminated (wdata, rc); goto out;
Greg Kroah-Hartman
maintainerPATCH 847/990 smb: client: skip NULL channel in __cifs_put_smb_ses()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 8deaf64a59a263161dfc5128f8398fb3dcba4fac upstream.
cifs_chan_skip_or_disable() clears a secondary channel's slot in the session (ses->chans[chan_index].server = NULL) without lowering chan_count when the server stops supporting multichannel. When the session is later released, __cifs_put_smb_ses() walks every slot up to chan_count and calls cifs_put_tcp_session() on it, which dereferences the server pointer immediately, so a slot left NULL by the skip path makes the release crash with a NULL pointer dereference.
Clearing a slot without lowering chan_count is older than cifs_chan_skip_or_disable(): cifs_chan_update_iface() could already do the same since commit b54034a73baf9 ("cifs: during reconnect, update interface if necessary"), and the release loop has been unguarded since then. Commit 12d1e301bdfd1 ("cifs: do not let cifs_chan_update_iface deallocate channels") later removed that trigger, but the crash is reachable through it on older kernels.
cifs_decrease_secondary_channels() already guards the same put with if (server). Add the same guard to the release loop so a skipped channel slot is left alone.
--- fs/smb/client/connect.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/smb/client/connect.c +2 -1
@@ -2178,7 +2178,8 @@ void __cifs_put_smb_ses(struct cifs_seskref_put (&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface =NULL ; } -cifs_put_tcp_session (ses->chans[i].server,0 ); +if (ses->chans[i].server) +cifs_put_tcp_session (ses->chans[i].server,0 ); ses->chans[i].server =NULL ; }
Greg Kroah-Hartman
maintainerPATCH 848/990 smb: client: validate descriptor headers before query result allocation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: liuyong <[email protected]>
commit ffb59029c0d52bf76fdd2678f5d6fd13e26220dd upstream.
query_info() uses the server's returned length instead of the caller's minimum when a dynamic result is requested. A zero-length ACL response can therefore return ZERO_SIZE_PTR to id_mode_to_cifs_acl(), whose ownership-change path reads dacloffset before checking the header size. A KASAN-enabled test shows a read at address 0x20 and a kernel Oops.
Validate the returned range and the caller's minimum before allocating the dynamic result. Keep the reported length zero if validation fails.
Use the security descriptor header size as the minimum in SMB2_query_acl(). DACL-only and SACL-only xattr queries do not require owner and group SIDs, so enforcing MIN_SEC_DESC_LEN would reject short descriptors that these queries could previously return. The rewrite paths validate the required owner/group SIDs and DACL separately before using their contents.
These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.
--- fs/smb/client/cifsacl.h | 14 -------------- fs/smb/client/smb2pdu.c | 11 ++++++++++- 2 files changed, 10 insertions(+), 15 deletions(-)
fs/smb/client/cifsacl.h +0 -14
@@ -93,18 +93,4 @@ struct owner_group_sids { struct owner_sid group; } __packed; -/* -* Minimum security identifier can be one for system defined Users -* and Groups such as NULL SID and World or Built-in accounts such -* as Administrator and Guest and consists of -* Revision + Num (Sub)Auths + Authority + Domain (one Subauthority) -*/ -#define MIN_SID_LEN (1 + 1 + 6 + 4)/* in bytes */ - -/* -* Minimum security descriptor can be one without any SACL and DACL and can -* consist of revision, type, and two sids of minimum size for owner and group -*/ -#define MIN_SEC_DESC_LEN (sizeof(struct smb_ntsd) + (2 * MIN_SID_LEN)) -#endif /* _CIFSACL_H */
fs/smb/client/smb2pdu.c +10 -1
@@ -3940,6 +3940,14 @@ replay_again: ses->Suid, info_class, (__u32)info_type);if (dlen) { + rc =smb2_validate_iov (le16_to_cpu (rsp->OutputBufferOffset), +le32_to_cpu (rsp->OutputBufferLength), + &rsp_iov, min_len); +if (rc) { + *dlen =0 ; + goto qinf_exit; + } + *dlen =le32_to_cpu (rsp->OutputBufferLength);if (!*data) { *data =kmalloc (*dlen,GFP_KERNEL );
@@ -4012,7 +4020,8 @@ SMB2_query_acl(const unsigned int xid, sreturn query_info (xid, tcon, persistent_fid, volatile_fid,0 ,SMB2_O_INFO_SECURITY , extra_info, -SMB2_MAX_BUFFER_SIZE ,MIN_SEC_DESC_LEN , data, plen); +SMB2_MAX_BUFFER_SIZE ,sizeof (struct smb_ntsd ), + data, plen); }int
Greg Kroah-Hartman
maintainerPATCH 849/990 dm log userspace: drop the device reference on error
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 0550d3b14e008b033b02cfce668008ec6addffe4 upstream.
userspace_ctr() takes a reference on the log device with dm_get_device(). When the integrated-flush workqueue allocation fails it jumps to the shared error path, which frees the log context without dropping that reference, so the device stays busy and cannot be removed.
userspace_dtr() drops the reference correctly; do the same here.
--- drivers/md/dm-log-userspace-base.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-log-userspace-base.c +5 -1
@@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty } r =dm_get_device (ti, devices_rdata,dm_table_get_mode (ti->table), &lc->log_dev); -if (r) +if (r) {DMERR ("Failed to register %s with device-mapper" , devices_rdata); + goto out; + } }if (lc->integrated_flush) {
@@ -315,6 +317,8 @@ static int userspace_ctr(struct dm_dirty out:kfree (devices_rdata);if (r) { +if (lc->log_dev) +dm_put_device (lc->ti, lc->log_dev);mempool_exit (&lc->flush_entry_pool);kfree (lc);kfree (ctr_str);
Greg Kroah-Hartman
maintainerPATCH 850/990 dm: avoid double-dropping the zone reset submission reference
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yaohan Li <[email protected]>
commit c4965effbe15f837a8089e79c0fc17ab19363cce upstream.
On an error in __send_zone_reset_all(), the submission reference held by the dm_io can be decremented there and again by the caller's error path. If another clone is still outstanding, the second drop can release the dm_io before that clone completes.
Only drop the submission reference in __send_zone_reset_all() on success. On failure, leave the reference for the caller's existing error handling to release once.
The error path was reproduced under KASAN with an injected GFP_NOIO allocation failure while another zone-reset clone remained in flight. With the change, the same failure was reported normally, without the observed use-after-free, and ordinary zone resets continued to work.
--- drivers/md/dm.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/md/dm.c +7 -2
@@ -1924,8 +1924,13 @@ static blk_status_t __send_zone_reset_albreak ; } -/* Release the reference that alloc_io() took for submission. */ -atomic_sub (1 , &ci->io->io_count); +/* +* Release the reference that alloc_io() took for submission. On error, +* that reference was not consumed: dm_split_and_process_bio() releases +* it on the error path, so do not release it here a second time. +*/ +if (sts ==BLK_STS_OK ) +atomic_dec (&ci->io->io_count);return sts; }
Greg Kroah-Hartman
maintainerPATCH 833/990 ovl: report the requested redirect_dir mode in conflicting options
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 248503755b3cab89742edcc3cfd53adbcf7bfec2 upstream.
Since the redirect_dir mode is stored as an enum, "off" is translated to "follow" or "nofollow" when parsing the option and redirect_dir=follow is translated to "on" for a non-upper mount, so the errors about options that conflict with an explicit redirect_dir= report a mode that the user did not request.
Translate "off" when verifying the mount options instead of when parsing them and report the requested mode in those errors.
--- fs/overlayfs/overlayfs.h | 10 +++++++--- fs/overlayfs/params.c | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 16 deletions(-)
fs/overlayfs/overlayfs.h +7 -3
@@ -74,9 +74,13 @@ enum ovl_entry_flag { };enum { -OVL_REDIRECT_OFF ,/* "off" mode is never used. In effect */ -OVL_REDIRECT_FOLLOW ,/* ...it translates to either "follow" */ -OVL_REDIRECT_NOFOLLOW ,/* ...or "nofollow". */ +/* +* "off" mode is never used after mount options are verified. In effect +* it translates to either "follow" or "nofollow". +*/ +OVL_REDIRECT_OFF , +OVL_REDIRECT_FOLLOW , +OVL_REDIRECT_NOFOLLOW ,OVL_REDIRECT_ON , };
fs/overlayfs/params.c +30 -13
99 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 851/990 dm: fail a REQ_PREFLUSH bio with data when its preflush fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
commit e92cd41e8e5ee5616c6c7cd4378661d942f0a7c0 upstream.
For a bio with REQ_PREFLUSH and data, dm core may send an empty flush first. If the flush fails, __dm_io_complete() still reissues the bio without REQ_PREFLUSH and drops the error. When that write succeeds, the XFS log keeps running and fsync() can return 0.
End the bio with the flush error instead of writing the data, as blk-mq does.
--- drivers/md/dm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/md/dm.c +2 -2
@@ -983,7 +983,7 @@ static void __dm_io_complete(struct dm_iif (requeued)return ; -if (unlikely (requeue_flush_with_data)) { +if (unlikely (requeue_flush_with_data) && !io_error) {/* * Preflush done for flush with data, reissue * without REQ_PREFLUSH.
@@ -991,7 +991,7 @@ static void __dm_io_complete(struct dm_i bio->bi_opf &= ~REQ_PREFLUSH ;queue_io (md, bio); }else { -/* done with normal IO or empty flush */ +/* done with normal IO, empty flush or failed preflush */ if (io_error) bio->bi_status = io_error;bio_endio (bio);
Greg Kroah-Hartman
maintainerPATCH 852/990 dm: fix infinite loop in dm_blk_do_report_zones()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Bundschuh <[email protected]>
commit 648320de920b30ae1730bbf0e8b86c0df0fb490a upstream.
If the device underlying a zoned target is removed, its capacity is set to 0 and blkdev_report_zones() returns 0 without reporting any zones. The mapped device keeps its old capacity, so args->zone_idx and args->next_sector never advance and dm_blk_do_report_zones() loops forever. On non-preemptible kernels this causes soft lockups and RCU stalls.
The following sequence of commands triggers the hang:
modprobe scsi_debug zbc=managed dev_size_mb=1024 zone_size_mb=64 udevadm settle
echo '0 2097152 linear /dev/sda 0' | dmsetup create lin echo 1 > /sys/block/sda/device/delete
blkzone report -o 0 -c 1 /dev/mapper/lin
Fix this by returning -EIO when a target reports no zones. The target always maps args->next_sector, so a zero return means the underlying device no longer covers that sector.
--- drivers/md/dm-zone.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/md/dm-zone.c +2 -0
@@ -33,6 +33,8 @@ static int dm_blk_do_report_zones(struct nr_zones - args->zone_idx);if (ret <0 )return ret; +if (!ret) +return -EIO ; }while (args->zone_idx < nr_zones && args->next_sector <get_capacity (md->disk));
Greg Kroah-Hartman
maintainerPATCH 853/990 dm: Reject table setup after queue or disk teardown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kirtikumar Anandrao Ramchandani <[email protected]>
commit ae310e4ad872a42f4707a596e66417f2aaa52826 upstream.
A failed table load can leave a mapped device in a state where its queue has already been initialized or its disk has been removed, while md->type is still DM_TYPE_NONE. A later table load then calls blk_mq_init_allocated_queue() on the same queue. If del_gendisk() exited the old hardware contexts, blk_mq_exit_hctx() dereferences their cleared flush queue pointer.
Reject setup attempts after queue initialization or disk removal. A failed request queue initialization still leaves md->tag_set NULL and can be retried. Set the request-based disk operations only after that initialization succeeds, so an unsuccessful attempt cannot leave a bio-based retry with request-based operations.
--- drivers/md/dm.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm.c +5 -1
@@ -2596,13 +2596,17 @@ int dm_setup_md_queue(struct mapped_deviWARN_ON_ONCE (type ==DM_TYPE_NONE ); +/* A failed setup may have left the queue initialized or the disk dead. */ +if (md->tag_set ||test_bit (GD_DEAD , &md->disk->state)) +return -ENODEV ; +if (type ==DM_TYPE_REQUEST_BASED ) { - md->disk->fops = &dm_rq_blk_dops; r =dm_mq_init_request_queue (md, t);if (r) {DMERR ("Cannot initialize queue for request-based dm mapped device" );return r; } + md->disk->fops = &dm_rq_blk_dops; } r =dm_calculate_queue_limits (t, &limits);
Greg Kroah-Hartman
maintainerPATCH 854/990 dm cache: reject kcopyd client destory if it setup failed
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Edward Adam Davis <[email protected]>
commit 8b97b168eb4d3affcf23d2980a0c3f35ed9262e2 upstream.
The value of cache->copier is -EINTR when failed to create a rescuer kthread for wq kcopyd, in cache_create(), the code jumps directly to __destroy(cache), it merely performs a simple check to see whether copier is NULL, potentially hitting:
BUG: KASAN: null-ptr-deref in dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 Read of size 4 at addr 0000000000000174 by task syz.2.19/6560 Call Trace: dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 __destroy+0x172/0x2f0 drivers/md/dm-cache-target.c:1973 cache_create drivers/md/dm-cache-target.c:2604 [inline] cache_ctr+0x1674/0x2bf0 drivers/md/dm-cache-target.c:2649 dm_table_add_target+0x58d/0xc70 drivers/md/dm-table.c:749 populate_table drivers/md/dm-ioctl.c:1602 [inline] table_load+0x325/0x8a0 drivers/md/dm-ioctl.c:1645 ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
Set copier to NULL to avoid destroying a invalid kcopy client.
--- drivers/md/dm-cache-target.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-target.c +1 -0
@@ -2550,6 +2550,7 @@ static int cache_create(struct cache_argif (IS_ERR (cache->copier)) { *error ="could not create kcopyd client" ; r =PTR_ERR (cache->copier); + cache->copier =NULL ; goto bad; }
Greg Kroah-Hartman
maintainerPATCH 855/990 dm crypt: fix use of uninitialized percpu_counter in ctr error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Feng <[email protected]>
commit 8ba1ade3e6b595b9091040feaa3341d7e45ba95d upstream.
If percpu_counter_init() fails in crypt_ctr() (e.g. when the underlying percpu allocation fails under memory pressure or fault injection), the error path jumps to "bad", which calls crypt_dtr(). crypt_dtr() then evaluates WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0) and calls percpu_counter_destroy() on a counter that was never initialized, because __percpu_counter_init_many() returns -ENOMEM before calling raw_spin_lock_init() on fbc->lock.
With lockdep enabled this triggers "INFO: trying to register non-static key" in __percpu_counter_sum(), as reported by syzbot. The console additionally shows "crypt: Unknown error (-ENOMEM)" because this failure path sets no ti->error.
Move percpu_counter_init() to right after the allocation of cc, before ti->private is set and before any "goto bad" can happen. On failure, set ti->error and free cc directly, so that crypt_dtr() is only ever called with an initialized counter.
--- drivers/md/dm-crypt.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/md/dm-crypt.c +8 -4
@@ -3287,6 +3287,14 @@ static int crypt_ctr(struct dm_target *t ti->error ="Cannot allocate encryption context" ;return -ENOMEM ; } + + ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); +if (ret <0 ) { + ti->error ="Cannot initialize page counter" ; +kfree_sensitive (cc); +return ret; + } + cc->key_size = key_size; cc->sector_size = (1 <<SECTOR_SHIFT ); cc->sector_shift =0 ;
@@ -3298,10 +3306,6 @@ static int crypt_ctr(struct dm_target *tcrypt_calculate_pages_per_client ();spin_unlock (&dm_crypt_clients_lock); - ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); -if (ret <0 ) - goto bad; -/* Optional parameters need to be read before cipher constructor */ if (argc >5 ) { ret =crypt_ctr_optional (ti, argc -5 , &argv[5 ]);
Greg Kroah-Hartman
maintainerPATCH 856/990 dm mpath: fix buffer overflow in parse_hw_handler()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 8f611fe94a781c6fb658488cc7eab4e4923e6df6 upstream.
parse_hw_handler() builds the hw_handler parameter string in a buffer sized with
len = 4;
plus one byte per argument. Those four bytes were meant for the decimal form of the parameter count, three digits plus the terminating NUL. dm_read_arg_group() accepts up to 1024 arguments and the count written is 'hw_argc - 1', so a count of 1000 or more needs four digits plus the NUL and sprintf() writes one byte past the allocation.
Size the buffer from the actual string length instead.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -1084,8 +1084,9 @@ static int parse_hw_handler(struct dm_arif (hw_argc >1 ) {char *p; -int i, j, len =4 ; +int i, j, len; + len =snprintf (NULL ,0 ,"%d" , hw_argc -1 ) +1 ;for (i =0 ; i <= hw_argc -2 ; i++) len +=strlen (as->argv[i]) +1 ; p = m->hw_handler_params =kzalloc (len,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 857/990 dm mpath: cap queue_if_no_path_timeout_secs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit ae5b40accbc06f93e6a513e0e9a07fd32b197e49 upstream.
enable_nopath_timeout() arms the no-path timer with
jiffies + queue_if_no_path_timeout_secs * HZ. The module parameter is an unbounded unsigned long, so the delay can exceed what mod_timer()
handles: a delay above LONG_MAX is treated as already expired, and values above ULONG_MAX / HZ also wrap in the multiplication. The timer then clears queue_if_no_path right away, and I/O queued after the last path fails gets -EIO instead of waiting for the configured time.
On x86-64 with HZ=1000, 9223372036854776 seconds failed a write after 124 ms while one second less remained queued throughout a 4.2-second observation window. A value of 18446744073709552 seconds wrapped to 384 jiffies and failed the write after 455 ms. On 32-bit kernels with HZ=1000 the delay passes LONG_MAX above 2147483 seconds, a little under 25 days.
Cap the seconds value at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET before multiplying by HZ. This prevents signed-delta overflow and multiplication wrap. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -803,7 +803,8 @@ static void queue_if_no_path_timeout_worstatic void enable_nopath_timeout (struct multipath *m) {unsigned long queue_if_no_path_timeout = -READ_ONCE (queue_if_no_path_timeout_secs) *HZ ; + min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;lockdep_assert_held (&m->lock);
Greg Kroah-Hartman
maintainerPATCH 858/990 dm thin: avoid wrapping no_space_timeout
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit bcb78d49620f666b4a9d62997691e8d031fd4ebc upstream.
set_pool_mode() converts the no_space_timeout module parameter with READ_ONCE(no_space_timeout_secs) * HZ. The usual arithmetic conversions evaluate the product as unsigned int, so it can wrap before being stored in the unsigned long delay. With HZ=1000, 4294968 seconds becomes 704
jiffies: a pool that runs out of data space switches to error_if_no_space and fails queued writes with -ENOSPC after about 0.7 seconds.
Widen the value before the multiplication and cap it at MAX_JIFFY_OFFSET / HZ, so large timeouts no longer wrap into short delays. On 32-bit kernels, values beyond the supported jiffies range saturate at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-thin.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-thin.c +3 -1
@@ -2544,7 +2544,9 @@ static void set_pool_mode(struct pool *pstruct pool_c *pt = pool->ti->private;bool needs_check =dm_pool_metadata_needs_check (pool->pmd);enum pool_mode old_mode =get_pool_mode (pool); -unsigned long no_space_timeout =READ_ONCE (no_space_timeout_secs) *HZ ; +unsigned long no_space_timeout = + min_t(unsigned long, READ_ONCE(no_space_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;/* * Never allow the pool to transition to PM_WRITE mode if user
Greg Kroah-Hartman
maintainerPATCH 859/990 dm-pcache: do not advance dirty_tail after backing flush failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: guolingxing <[email protected]>
commit b1310cb291935c788f34ed6eb1e7e9b42cfac045 upstream.
After all writeback bios for a kset complete, writeback_ctx_end() flushes the backing device and then advances the persistent dirty_tail. However, backing_dev_flush() discards the error returned by blkdev_issue_flush(), so dirty_tail is advanced even when the written data is not known to be durable.
dirty_tail points to the first kset that still requires writeback. Advancing it causes recovery to treat the preceding kset as clean and allows its cache copy to eventually be reclaimed by garbage collection. If the backing device flush failed, a subsequent power failure may therefore result in data loss.
Make backing_dev_flush() return the flush status and handle a flush failure like a writeback I/O failure. Leave dirty_tail unchanged so that the same kset will be retried.
--- drivers/md/dm-pcache/backing_dev.c | 4 ++-- drivers/md/dm-pcache/backing_dev.h | 2 +- drivers/md/dm-pcache/cache_writeback.c | 28 +++++++++++++++++++------- 3 files changed, 24 insertions(+), 10 deletions(-)
drivers/md/dm-pcache/backing_dev.c +2 -2
@@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_dev_req_create(struct pcache_backing_devreturn backing_req; } -void backing_dev_flush (struct pcache_backing_dev *backing_dev) +int backing_dev_flush (struct pcache_backing_dev *backing_dev) { -blkdev_issue_flush (backing_dev->dm_dev->bdev); +return blkdev_issue_flush (backing_dev->dm_dev->bdev); }int pcache_backing_init (void )
drivers/md/dm-pcache/backing_dev.h +1 -1
@@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_dev_req_alloc(struct pcache_backing_dev * struct pcache_backing_dev_req_opts *opts);void backing_dev_req_init (struct pcache_backing_dev_req *backing_req,struct pcache_backing_dev_req_opts *opts); -void backing_dev_flush (struct pcache_backing_dev *backing_dev); +int backing_dev_flush (struct pcache_backing_dev *backing_dev);int pcache_backing_init (void );void pcache_backing_exit (void );
drivers/md/dm-pcache/cache_writeback.c +21 -7
@@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pcache_cache *cache, int ret)return ;if (!cache->writeback_ctx.ret) { -backing_dev_flush (cache->backing_dev); - -mutex_lock (&cache->dirty_tail_lock); -cache_pos_advance (&cache->dirty_tail, cache->writeback_ctx.advance); -cache_encode_dirty_tail (cache); -mutex_unlock (&cache->dirty_tail_lock); + ret =backing_dev_flush (cache->backing_dev); +if (ret) { +pcache_dev_err (CACHE_TO_PCACHE (cache), +"failed to flush backing device: %d" , ret); + cache->writeback_ctx.ret = ret; + }else { +mutex_lock (&cache->dirty_tail_lock); +cache_pos_advance (&cache->dirty_tail, + cache->writeback_ctx.advance); +cache_encode_dirty_tail (cache); +mutex_unlock (&cache->dirty_tail_lock); + } }queue_delayed_work (cache_get_wq (cache), &cache->writeback_work,0 ); }
@@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct pcache_cache *cache, struct pcache_cachvoid cache_writeback_exit (struct pcache_cache *cache) { +int ret; +cancel_delayed_work_sync (&cache->writeback_work); -backing_dev_flush (cache->backing_dev); + + ret =backing_dev_flush (cache->backing_dev); +if (ret) +pcache_dev_err (CACHE_TO_PCACHE (cache), +"failed to flush backing device during exit: %d" , + ret); +cache_tree_exit (&cache->writeback_key_tree); }
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 860/990 dm-sysfs: fix misbehavior if kobject_init_and_add fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 406d576cc457203cf86eac7f17839b2efec81db4 upstream.
If kobject_init_and_add fails, we must call kobject_put (see the comment at kobject_init_and_add).
Before calling kobject_init_and_add, we must zero the kobject (see
https://lwn.net/Articles/52085/). If the first call to dm_sysfs_init failed, it may be called again, and that second call would see an uninitialized kobject.
--- drivers/md/dm-sysfs.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-)
drivers/md/dm-sysfs.c +14 -3
@@ -132,9 +132,20 @@ static const struct kobj_type dm_ktype =*/ int dm_sysfs_init (struct mapped_device *md) { -return kobject_init_and_add (dm_kobject (md), &dm_ktype, - &disk_to_dev (dm_disk (md))->kobj, -"%s" ,"dm" ); +struct kobject *kobj =dm_kobject (md); +int r; + +/* The kobject must be zeroed before calling kobject_init */ +memset (kobj,0 ,sizeof (struct kobject )); + r =kobject_init_and_add (kobj, &dm_ktype, + &disk_to_dev (dm_disk (md))->kobj, +"%s" ,"dm" ); +if (unlikely (r)) { +/* Weird semantics - we must call kobject_put on failure */ +dm_sysfs_exit (md); +return r; + } +return 0 ; }/*
Greg Kroah-Hartman
maintainerPATCH 834/990 ovl: return EIO if the lowerdata is missing
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Scrivano <[email protected]>
commit 0d5e729c515f4ae4eacc179dbcf350d9b499a161 upstream.
The data of a metacopy file that redirects to a data-only layer is looked up when the file is opened, and the error of the lookup is returned as is. If the data file is missing, open() fails with ENOENT even though the file is there and stat() works.
This can be an integrity problem when using composefs: a data file that is changed or has the wrong fs-verity digest is reported with EIO, but a missing one is not reported, the file just looks like it does not exist, e.g. a configuration file that overrides the defaults.
Return EIO as it is already done in ovl_lookup() when no lower data is found for a metacopy file. ENOMEM is not changed.
--- fs/overlayfs/namei.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/overlayfs/namei.c +8 -0
@@ -1047,6 +1047,14 @@ out: out_err:pr_warn_ratelimited ("lazy lowerdata lookup failed (%pd2, err=%i)\n" , dentry, err); +/* +* The data of a metacopy file is missing or is not a regular file in +* the data-only layers: the layers are corrupted. Do not return the +* error of the lookup (e.g. ENOENT) to the caller, it would make the +* file look like it does not exist. +*/ +if (err != -ENOMEM ) + err = -EIO ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 861/990 dm-verity: dont restart or panic on errors during system shutdown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weijiang Zhou <[email protected]>
commit 47930d1236d2988cdc580c10d3af21b6b02d7ece upstream.
Commit 252bd1256396 ("dm verity: skip verity work if I/O error when system is shutting down") stopped I/O errors during shutdown from triggering a restart, since devices may legitimately be gone by then. Errors that reach verity_handle_err(), e.g. through a failed hash block read followed by a failed FEC attempt, are not covered and still call kernel_restart() or panic().
During a reboot that is both wrong (nothing is corrupt) and harmful: it races with the reboot already in progress and replaces its reason with "dm-verity device corrupted", which bootloaders such as Android's treat as a verity failure and switch the device to EIO mode.
Apply the same shutdown check in verity_handle_err(). Corruption is still logged, recorded in hash_failed and reported via uevent, and the I/O still fails.
--- drivers/md/dm-verity-target.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-)
drivers/md/dm-verity-target.c +18 -9
@@ -156,6 +156,15 @@ static void verity_hash_at_level(struct }/* +* Skip verity work in response to I/O error when system is shutting down. +*/ +static inline bool verity_is_system_shutting_down (void ) +{ +return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF + || system_state ==SYSTEM_RESTART ; +} + +/* * Handle verification errors. */ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
@@ -204,6 +213,15 @@ out:if (v->mode ==DM_VERITY_MODE_LOGGING )return 0 ; +/* +* Devices may already be quiesced (e.g. UFS set offline by its +* shutdown hook), so a failure here does not imply corruption. Fail +* the I/O but do not restart or panic, which would also override the +* reboot reason of the shutdown already in progress. +*/ +if (verity_is_system_shutting_down ()) +return 1 ; +if (v->mode ==DM_VERITY_MODE_RESTART )kernel_restart ("dm-verity device corrupted" );
@@ -523,15 +541,6 @@ static int verity_verify_io(struct dm_vereturn 0 ; } -/* -* Skip verity work in response to I/O error when system is shutting down. -*/ -static inline bool verity_is_system_shutting_down (void ) -{ -return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF - || system_state ==SYSTEM_RESTART ; -} -static void restart_io_error (struct work_struct *w) {kernel_restart ("dm-verity device has I/O error" );
Greg Kroah-Hartman
maintainerPATCH 862/990 dm persistent data: test return value of node_copy
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 624d146d97c5fbe7200ef4b2dd5350ecf57d6b79 upstream.
There were 3 places where the return value of node_copy was not tested.
--- drivers/md/persistent-data/dm-btree-remove.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-btree-remove.c +10 -3
@@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_/* * Merge */ -node_copy (left, right, -nr_right); + ret =node_copy (left, right, -nr_right); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + nr_right);delete_at (parent, r->index);
@@ -315,13 +317,16 @@ static int delete_center_node(struct dm_ {uint32_t max_entries =le32_to_cpu (left->header.max_entries);unsigned int shift =min (max_entries - nr_left, nr_center); +int ret;if (nr_left + shift > max_entries) {DMERR ("node shift out of bounds" );return -EINVAL ; } -node_copy (left, center, -shift); + ret =node_copy (left, center, -shift); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + shift);if (shift != nr_center) {
@@ -333,7 +338,9 @@ static int delete_center_node(struct dm_ }node_shift (right, shift); -node_copy (center, right, shift); + ret =node_copy (center, right, shift); +if (unlikely (ret)) +return ret; right->header.nr_entries =cpu_to_le32 (nr_right + shift); } *key_ptr (parent, r->index) = right->keys[0 ];
Greg Kroah-Hartman
maintainerPATCH 863/990 dm persistent data: dont ignore writeback errors
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit fa887f2ebee7aff97eb87b3365939616ade09774 upstream.
An error returned by ie_cache_writeback could be silently overwritten by another successful ie_cache_writeback. This commit fixes disk_ll_commit, so that it doesn't ignore the error and returns it immediatelly.
--- drivers/md/persistent-data/dm-space-map-common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-space-map-common.c +6 -3
@@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(ststatic int disk_ll_commit (struct ll_disk *ll) { -int r =0 ; +int r;unsigned int i;for (i =0 ; i <IE_CACHE_SIZE ; i++) {struct ie_cache *iec = ll->ie_cache + i; -if (iec->valid && iec->dirty) +if (iec->valid && iec->dirty) { r =ie_cache_writeback (ll, iec); +if (unlikely (r)) +return r; + } } -return r; +return 0 ; }int sm_ll_new_disk (struct ll_disk *ll,struct dm_transaction_manager *tm)
Greg Kroah-Hartman
maintainerPATCH 864/990 dm persistent data: dont leak bufio buffer if find_leaf fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit b27523a0781aae0b51ac13f29dc65373d14b8434 upstream.
If find_leaf fails, the function dm_btree_cursor_begin would return an error, but it would keep the dm-bufio buffers held. This would result in a memory leak and a warning when releasing the dm-bufio cache.
This commit fixes it, so that dm_btree_cursor_begin releases the buffers on error.
--- drivers/md/persistent-data/dm-btree.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/persistent-data/dm-btree.c +7 -1
@@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btreif (r)return r; -return find_leaf (c); + r =find_leaf (c); +if (unlikely (r)) { +dm_btree_cursor_end (c); +return r; + } + +return 0 ; }EXPORT_SYMBOL_GPL (dm_btree_cursor_begin);
Greg Kroah-Hartman
maintainerPATCH 865/990 dm snapshot: fix discard_granularity unit in snapshot_io_hints
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: wuyuehong <[email protected]>
commit d7216d7be2bbfdf3312695b6e41a4fc7c5e22902 upstream.
snapshot_io_hints() copies the snapshot store's chunk_size, which is in 512-byte sectors, into queue_limits.discard_granularity, which, like all other members of struct queue_limits, is in bytes.
For snapshots with a chunk size smaller than 512 sectors, e.g. the 16 KiB (32-sector) chunks created by the syzkaller reproducer, the resulting granularity is smaller than a single sector. When dm_calculate_queue_limits() then stacks the target limits into the table limits:
blk_stack_limits(limits, &ti_limits, 0)
queue_limit_discard_alignment() truncates that granularity to zero sectors and sector_div() divides by zero:
Oops: divide error: 0000 [#1] SMP KASAN NOPTI RIP: 0010:queue_limit_discard_alignment block/blk-settings.c:645 [inline] RIP: 0010:blk_stack_limits+0x1105/0x2d00 block/blk-settings.c:916 Call Trace: dm_calculate_queue_limits+0x70c/0x1510 drivers/md/dm-table.c:1823 dm_setup_md_queue+0x199/0x4f0 drivers/md/dm.c:2618 table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
The divide fault itself only became reachable when commit e924da7d6622 ("block: Drop granularity check in queue_limit_discard_alignment()") removed the check for a sub-sector granularity in v6.13. Kernels before that returned a zero discard alignment instead of faulting, but they still advertised a granularity 512 times too small.
Use the same chunk_size << SECTOR_SHIFT conversion that io_overlaps_chunk() already applies to turn chunk_size into bytes.
--- drivers/md/dm-snap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-snap.c +1 -1
@@ -2420,7 +2420,7 @@ static void snapshot_io_hints(struct dm_ snap = snap_src;/* All discards are split on chunk_size boundary */ - limits->discard_granularity = snap->store->chunk_size; + limits->discard_granularity = snap->store->chunk_size <<SECTOR_SHIFT ; limits->max_hw_discard_sectors = snap->store->chunk_size;up_read (&_origins_lock);
Greg Kroah-Hartman
maintainerPATCH 866/990 dm snapshot: split discards on chunk boundaries
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 4fe2c2baad01da64d47f1a0c8fc093df994bcef5 upstream.
dm-snapshot did not set ti->max_discard_granularity when it allows discards, so a discard could reach the target unaligned, or spanning several chunks. Set the flag, so dm splits discards on chunk boundaries.
--- drivers/md/dm-snap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-snap.c +3 -1
@@ -1364,8 +1364,10 @@ static int snapshot_ctr(struct dm_target ti->private = s; ti->num_flush_bios = num_flush_bios; -if (s->discard_zeroes_cow) +if (s->discard_zeroes_cow) { ti->num_discard_bios = (s->discard_passdown_origin ?2 :1 ); + ti->max_discard_granularity = true; + } ti->per_io_data_size =sizeof (struct dm_snap_tracked_chunk );/* Add snapshot to the list of snapshots for this origin */
Greg Kroah-Hartman
maintainerPATCH 867/990 dm snapshot: fix discard writing into the next COW chunk
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 73174b4bb6fcd0e6cf973c9402a0fae2e567ad9f upstream.
zero_exception() zeroes one chunk of the COW device and takes the start sector from bio->bi_iter.bi_sector. remap_exception() has already set that to the COW chunk start plus the offset inside the chunk. That offset is needed for reads and writes, but for a discard it is wrong:
the zeroing window is shifted, so the head of the target chunk keeps its old data and the tail lands in the next COW chunk, which holds a different exception.
io_overlaps_chunk() should have caught this, but it only compares the length. "maps to entire chunks" in snapshot.rst also means the discard has to start on a chunk boundary.
A discard that is not a full chunk has a second problem: after remap_exception() it is sent to the COW device, where it hits a chunk that still backs a live exception. After a discard the contents are undefined, but the exception stays in the table and keeps pointing at that chunk, so a later read returns whatever the discard left instead of the snapshot's data.
Reproducer:
truncate -s 4M o.img c.img o=$(losetup -f --show o.img) c=$(losetup -f --show c.img) dmsetup create snap --table \ "0 8192 snapshot $o $c P 512 1 discard_zeroes_cow" # write two chunks, this creates two exceptions head -c 256K /dev/zero | tr '\000' '\252' > pat dd if=pat of=/dev/mapper/snap bs=256K seek=1 count=1 conv=notrunc dd if=pat of=/dev/mapper/snap bs=256K seek=2 count=1 conv=notrunc # shift the snapshot by 8 sectors, so a discard that is aligned on # top is unaligned inside the snapshot dmsetup create top --table "0 8184 linear /dev/mapper/snap 8" blkdiscard -o 262144 -l 262144 /dev/mapper/top sync echo 3 > /proc/sys/vm/drop_caches # chunk 1 dd if=/dev/mapper/snap bs=512 skip=512 count=8 | od -An -tx1 -N1 # chunk 2 dd if=/dev/mapper/snap bs=512 skip=1024 count=8 | od -An -tx1 -N1
Before: aa 00 <- chunk 2 was zeroed although it was not discarded After: aa aa <- nothing written, a discard is only a hint
Fix it by requiring the discard to start on a chunk boundary in io_overlaps_chunk(), and by finishing a discard that is not a full chunk with bio_endio() instead of passing it down to the COW device.
--- drivers/md/dm-snap.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/md/dm-snap.c +7 -5
@@ -1954,8 +1954,8 @@ static void zero_exception(struct dm_snastatic bool io_overlaps_chunk (struct dm_snapshot *s,struct bio *bio) { -return bio->bi_iter.bi_size == - (s->store->chunk_size <<SECTOR_SHIFT ); +return bio->bi_iter.bi_size == (s->store->chunk_size <<SECTOR_SHIFT ) && + !(bio->bi_iter.bi_sector & s->store->chunk_mask); }static int snapshot_map (struct dm_target *ti,struct bio *bio)
@@ -2015,11 +2015,13 @@ static int snapshot_map(struct dm_target e =dm_lookup_exception (&s->complete, chunk);if (e) {remap_exception (s, e, bio, chunk); -if (unlikely (bio_op (bio) ==REQ_OP_DISCARD ) && -io_overlaps_chunk (s, bio)) { +if (unlikely (bio_op (bio) ==REQ_OP_DISCARD )) {dm_exception_table_unlock (&lock);up_read (&s->lock); -zero_exception (s, e, bio, chunk); +if (io_overlaps_chunk (s, bio)) +zero_exception (s, e, bio, chunk); +else +bio_endio (bio); r =DM_MAPIO_SUBMITTED ;/* discard is not issued */ goto out; }
Greg Kroah-Hartman
maintainerPATCH 868/990 dm zoned: back off when reclaim cannot make progress
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit 9bb1d14877f4929be17f7fdbeb4cfdf5025d464b upstream.
When a reclaim pass cannot make progress, dmz_reclaim_work() still ends with dmz_schedule_reclaim(). If the target is idle, dmz_should_reclaim() keeps returning true, the work is queued again with no delay and the worker spins on the same failing pass. This patch handles two such cases:
- dmz_do_reclaim() fails with -ENOSPC because no free zone is available to copy the data into, for example on a target without cache zones that has no free sequential zone left. The next patch also makes this the expected result when an idle target with cache zones has random zones but no free sequential zone.
- dmz_do_reclaim() finds no zone it can lock for reclaim and returns -EBUSY. Since commit 90a9b8693f1b ("dm zoned: reclaim random zones when idle"), dmz_should_reclaim() returns true on an idle target whenever the total number of random (and cache) zones is non-zero, whether or not any of them holds data. Each pass then also runs dmz_check_dev(), which checks every device for media events (a TEST UNIT READY on SCSI disks).
The -EBUSY loop lasts as long as the target stays idle; it ends when a pass finishes while the target is busy and has enough free zones. On three 27 TB host-managed SATA drives used as md RAID5 members (7.2.10 with the module built out of tree, all random zones free, target idle for 300 seconds, kprobes attached, two other drives on the controller being zero-filled), each member's SCSI device counted about 108,000 requests per second with the stock module and the system used about 915 s of CPU time, against about 46 s with this series. libata completes TEST UNIT READY in software, so these counters do not measure commands sent to the drives; the cost is CPU time.
When a pass fails with -ENOSPC or -EBUSY, retrying at once is unlikely to make progress: re-arm the idle poll instead, so that reclaim is retried after DMZ_IDLE_PERIOD unless a zone allocation or a "reclaim" message queues it earlier. On a busy target, zone allocations can restart reclaim immediately when free space is low enough to require reclaim. Re-arming also keeps the poll running after a complete idle drain. The poll can still stop after a pass that ends while reclaim is not needed; that is unchanged.
Skip the device check for these two results: they normally mean that there is no zone to copy into or no zone to reclaim, not that a device failed, and the I/O paths check the devices themselves. Use queue_delayed_work() so that work an allocation has already queued is not postponed.
A pass that fails with an I/O error, for example on an unreadable block of a device that stays online, is still retried at once while the target is idle; this patch does not change that.
Tested on 7.4-rc1 with this patch and the next one, on three emulated host-managed drives (scsi_debug, 1 GiB, 32 MiB zones) each under dm-zoned as md RAID5 members, all random zones free and the target idle for 300 seconds. With the stock module each member's SCSI device counted about 70.2 million requests and the reclaim workers used 726 s of CPU. With this series: 75 requests per member, 30 passes per worker (one per DMZ_IDLE_PERIOD) and 0.08 s of CPU. Data written during the tests read back with matching checksums, and no kernel warnings were logged.
--- drivers/md/dm-zoned-reclaim.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
drivers/md/dm-zoned-reclaim.c +10 -0
@@ -539,6 +539,16 @@ static void dmz_reclaim_work(struct work dmz_nr_rnd_zones(zmd, zrc->dev_idx)); ret =dmz_do_reclaim (zrc); +if (ret == -ENOSPC || ret == -EBUSY ) { +/* +* No zone to copy into (-ENOSPC) or no zone to reclaim +* (-EBUSY): retrying at once cannot make progress and would +* spin. Poll again after the idle period instead, without +* postponing work that an allocation has already queued. +*/ +queue_delayed_work (zrc->wq, &zrc->work,DMZ_IDLE_PERIOD ); +return ; + }if (ret && ret != -EINTR ) {if (!dmz_check_dev (zmd))return ;
Greg Kroah-Hartman
maintainerPATCH 869/990 dm zoned: do not reclaim a random zone into another random zone
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit dab527d83462a618d99bfc96370ce45ae3428706 upstream.
dmz_reclaim_rnd_data() falls back to a random destination zone when no free sequential zone is available and the target has cache zones. When the target is idle and the cache zone list is empty, dmz_get_rnd_zone_for_reclaim() selects random zones of the zoned device as well, so a random zone is then copied into another random zone. That frees nothing: the next pass picks the next random zone and copies it again, for as long as the target stays idle.
Seen on a two-device target (256 GiB regular cache device plus a 27 TB host-managed drive) used as an md RAID5 member: after a full rebuild every chunk was mapped and no sequential zone was free, and the idle drive kept reading and writing while the free zone counters in "dmsetup status" did not change.
Only switch to a random destination zone when the zone being reclaimed is a cache zone: moving it to the zoned device still frees cache space.
This depends on "dm zoned: back off when reclaim cannot make progress":
without it, dmz_reclaim_work() would retry the resulting -ENOSPC at once, and run dmz_check_dev(), for as long as the target stays idle.
Tested on 7.4-rc1 together with the previous patch, on a two-device target (a 512 MiB RAM-backed regular cache device plus a 1 GiB scsi_debug host-managed drive) filled until no sequential zone was free, then idle for 60 seconds: the stock module made 877 random-to-random copies; with this series it made none, and each pass failed with -ENOSPC once per DMZ_IDLE_PERIOD without a device check.
--- drivers/md/dm-zoned-reclaim.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/dm-zoned-reclaim.c +7 -1
@@ -290,7 +290,13 @@ static int dmz_reclaim_rnd_data(struct d again: szone =dmz_alloc_zone (zmd, zrc->dev_idx, alloc_flags |DMZ_ALLOC_RECLAIM ); -if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_nr_cache_zones (zmd)) { +/* +* If no free sequential zone is available, a cache zone can still be +* moved into a free random zone of the zoned device, which frees cache +* space. Do not do this for a random zone: moving it into another +* random zone frees nothing and, on an idle target, repeats forever. +*/ +if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_is_cache (dzone)) { alloc_flags =DMZ_ALLOC_RND ; goto again; }
Greg Kroah-Hartman
maintainerPATCH 870/990 dm-cache: fix NULL pointer dereference on open failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit d12afc2f9ed6e14019fed9c02a74ad699915dc85 upstream.
When __begin_transaction_flags in metadata_open fails, dm_cache_metadata_close is called. dm_cache_metadata_close attempts to execute list_del(&cmd->list);, but the "cmd" object is not on any list yet, thus it crashes with NULL pointer dereference.
Fix this by initializing cmd->list after cmd is allocated.
--- drivers/md/dm-cache-metadata.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-metadata.c +1 -0
@@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadatreturn ERR_PTR (-ENOMEM ); } +INIT_LIST_HEAD (&cmd->list); cmd->version = metadata_version;refcount_set (&cmd->ref_count,1 );init_rwsem (&cmd->root_lock);
Greg Kroah-Hartman
maintainerPATCH 835/990 ovl: do not allow nfs_export with data-only layers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit fba955b070d13e2fdac097577ce3c6ffbeda4ea9 upstream.
Since data-only layers no longer require metacopy=on, which conflicts with nfs_export=on, an overlay with data-only layers can be mounted with nfs_export=on.
Decoding a file handle of a lower metacopy file whose data is in a data-only layer builds the inode only from the decoded lower dentry, without the lazy lowerdata redirect, so the data of the file would be read from the metacopy file in the lower layer.
Fail the mount with explicit nfs_export=on and data-only layers and otherwise disable nfs_export with data-only layers.
--- fs/overlayfs/params.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
fs/overlayfs/params.c +10 -0
@@ -945,6 +945,16 @@ int ovl_fs_params_verify(const struct ov } } +/* Resolve nfs_export -> !data-only layers dependency */ +if (config->nfs_export && ctx->nr_data) { +if (set.nfs_export) { +pr_err ("NFS export is not supported with data-only layers\n" ); +return -EINVAL ; + } +pr_info ("disabling nfs_export due to data-only layers\n" ); + config->nfs_export = false; + } +/* Resolve nfs_export -> index dependency */ if (config->nfs_export && !config->index) { if (!config->upperdir &&
Greg Kroah-Hartman
maintainerPATCH 871/990 dm-cache: fix ending a cursor that never began
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 421420758be348cb90715bfaa26e1211a12ff1d0 upstream.
If dm_bitset_cursor_begin fails, dm_array_cursor_end(&cmd->hint_cursor) is called. However, cmd->hint_cursor was only initialized if the variable hints_valid is true. Thus, we must also destroy hint_cursor only if hints_valid is true.
--- drivers/md/dm-cache-metadata.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-cache-metadata.c +2 -1
@@ -1433,7 +1433,8 @@ static int __load_mappings(struct dm_cacfrom_cblock (cmd->cache_blocks), &cmd->dirty_cursor);if (r) { -dm_array_cursor_end (&cmd->hint_cursor); +if (hints_valid) +dm_array_cursor_end (&cmd->hint_cursor);dm_array_cursor_end (&cmd->mapping_cursor);return r; }
Greg Kroah-Hartman
maintainerPATCH 872/990 dm-crypt: reject integrity_key_size with non-authenc AEAD ciphers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: xietangxin <[email protected]>
commit bd93c4e59c5132282c01f142806e307c7380e7ea upstream.
When integrity_key_size parameter is paired with a pure AEAD cipher that is not an authenc composite, crypt_ctr_auth_cipher() returns 0 early without allocating cc->authenc_key, but cc->key_mac_size remains non-zero because CRYPT_KEY_MAC_SIZE_SET was set during option parsing. As a result crypt_copy_authenckey() dereferences NULL crashes the kernel.
Reject the contradictory configuration explicitly instead of silently returning 0, so userspace gets a clear -EINVAL.
--- drivers/md/dm-crypt.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-crypt.c +4 -1
@@ -2905,8 +2905,11 @@ static int crypt_ctr_auth_cipher(structchar *start, *end, *mac_alg =NULL ;struct crypto_ahash *mac; -if (!strstarts (cipher_api,"authenc(" )) +if (!strstarts (cipher_api,"authenc(" )) { +if (test_bit (CRYPT_KEY_MAC_SIZE_SET , &cc->cipher_flags)) +return -EINVAL ;return 0 ; + } start =strchr (cipher_api,'(' ); end =strchr (cipher_api,',' );
Greg Kroah-Hartman
maintainerPATCH 873/990 dm-crypt: defer async write submission to write thread
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Schlehofer <[email protected]>
commit 6fed9e26810f0b466dbcebe35a73d1fd48793ff5 upstream.
With no_write_workqueue, kcryptd_crypt_write_io_submit() submits the bio directly, even when called from kcryptd_async_done(). An async cipher may run this callback in softirq or with BH disabled, where submit_bio_noacct() must not be called because it can sleep.
Submit inline only when async is false. Async completions are sent to the write thread, as is already done for submit_from_crypt_cpus. Use the async flag rather than in_interrupt(), since callback context depends on the cipher driver. Sync ciphers still submit inline.
Tested with cryptd in QEMU (x86_64 and arm64) with CONFIG_DEBUG_ATOMIC_SLEEP, and on a P2020 running 6.18.55 without it.
In QEMU:
- 4k writes logging "sleeping function called from invalid context":
100/100 unpatched, 0/155 patched.
- nr_requests=4 on a loop device: 0/6 unpatched runs completed, 4/4 patched runs completed.
On the P2020, a warning in blk_mq_run_hw_queue() appeared in the 6th unpatched run and did not appear in 30 patched runs.
--- drivers/md/dm-crypt.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/md/dm-crypt.c +3 -2
@@ -2039,8 +2039,9 @@ static void kcryptd_crypt_write_io_submi/* crypt_convert should have filled the clone bio */ BUG_ON (io->ctx.iter_out.bi_size); -if ((likely (!async) &&test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags)) || -test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags)) { +if (likely (!async) && + (test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags) || +test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags))) {dm_submit_bio_remap (io->base_bio, clone);return ; }