6.12.114-rc1 review
Subsystems (5)
Greg Kroah-Hartman
maintainerPATCH 611/869 net: bridge: arp/nd proxy: fix reading neigh ha
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikolay Aleksandrov <[email protected]>
[ Upstream commit 57549ab9079122991dfa0f8248ca00e101e8e69b ]
Currently neigh ha address is read directly, but that can result in torn/partial reads if the neigh is being updated. Use neigh_ha_snapshot to take a stable snapshot of the address.
--- net/bridge/br_arp_nd_proxy.c | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-)
net/bridge/br_arp_nd_proxy.c +14 -10
@@ -191,13 +191,15 @@ void br_do_proxy_suppress_arp(struct sk_buff *skb, struct net_bridge *br, n =neigh_lookup (&arp_tbl, &tip, vlandev);if (n) {struct net_bridge_fdb_entry *f; +u8 ha[ETH_ALEN ]__aligned(2) ;if (!(READ_ONCE (n->nud_state) &NUD_VALID )) {neigh_release (n);return ; } - f =br_fdb_find_rcu (br, n->ha, vid); +neigh_ha_snapshot (ha, n, n->dev); + f =br_fdb_find_rcu (br, ha, vid);if (f) {const struct net_bridge_port *dst =READ_ONCE (f->dst);bool replied = false;
@@ -207,10 +209,10 @@ void br_do_proxy_suppress_arp(struct sk_buff *skb, struct net_bridge *br, br_is_neigh_suppress_enabled(dst, vid)) {if (!vid)br_arp_send (br, p, skb->dev, sip, tip, - sha, n->ha, sha,0 ,0 ); + sha, ha, sha,0 ,0 );else br_arp_send (br, p, skb->dev, sip, tip, - sha, n->ha, sha, + sha, ha, sha, skb->vlan_proto,skb_vlan_tag_get (skb)); replied = true;
@@ -248,7 +250,7 @@ struct nd_msg *br_is_nd_neigh_msg(struct sk_buff *skb, struct nd_msg *msg) }static void br_nd_send (struct net_bridge *br,struct net_bridge_port *p, -struct sk_buff *request,struct neighbour *n, +struct sk_buff *request,struct neighbour *n,u8 *ha,__be16 vlan_proto,u16 vlan_tci) {struct net_device *dev = request->dev;
@@ -306,7 +308,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p,ipv6_eth_mc_map (&in6addr_linklocal_allnodes,eth_hdr (reply)->h_dest); else ether_addr_copy(eth_hdr(reply)->h_dest, daddr); -ether_addr_copy (eth_hdr (reply)->h_source, n->ha); +ether_addr_copy (eth_hdr (reply)->h_source, ha);eth_hdr (reply)->h_proto =htons (ETH_P_IPV6 ); reply->protocol =htons (ETH_P_IPV6 );
@@ -336,7 +338,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, na->icmph.icmp6_override =1 ; na->icmph.icmp6_solicited = dad ?0 :1 ; na->target = ns->target; -ether_addr_copy (&na->opt[2 ], n->ha); +ether_addr_copy (&na->opt[2 ], ha); na->opt[0 ] =ND_OPT_TARGET_LL_ADDR ; na->opt[1 ] = na_olen >>3 ;
@@ -365,7 +367,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p,__vlan_hwaccel_put_tag (reply, vlan_proto, vlan_tci);netdev_dbg (dev,"nd send dev %s dst %pI6 dst_hw %pM src %pI6 src_hw %pM\n" , - dev->name, &pip6->daddr, daddr, &pip6->saddr, n->ha); + dev->name, &pip6->daddr, daddr, &pip6->saddr, ha);if (p) {dev_queue_xmit (reply);
@@ -462,24 +464,26 @@ void br_do_suppress_nd(struct sk_buff *skb, struct net_bridge *br, n =neigh_lookup (ipv6_stub->nd_tbl, &msg->target, vlandev);if (n) {struct net_bridge_fdb_entry *f; +u8 ha[ETH_ALEN ]__aligned(2) ;if (!(READ_ONCE (n->nud_state) &NUD_VALID )) {neigh_release (n);return ; } - f =br_fdb_find_rcu (br, n->ha, vid); +neigh_ha_snapshot (ha, n, n->dev); + f =br_fdb_find_rcu (br, ha, vid);if (f) {const struct net_bridge_port *dst =READ_ONCE (f->dst);bool replied = false;if (br_is_neigh_suppress_enabled (dst, vid)) {if (vid !=0 ) -br_nd_send (br, p, skb, n, +br_nd_send (br, p, skb, n, ha, skb->vlan_proto,skb_vlan_tag_get (skb));else -br_nd_send (br, p, skb, n,0 ,0 ); +br_nd_send (br, p, skb, n, ha,0 ,0 ); replied = true; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 612/869 ip6mr: do not clone dst in ip6mr_cache_report()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit 235b42b5860189eb8c27c36435ad932cae65a734 ]
IPv6 input attaches a non-refcounted (NOREF) dst to skbs under RCU. When an ingress multicast packet misses MFC lookup, ip6mr_cache_unresolved() places the skb onto the unresolved queue, escaping the receive-side RCU grace period.
If the underlying route is deleted and freed, and the MFC queue is later resolved with a wrong parent interface, ip6_mr_forward() invokes ip6mr_cache_report(..., MRT6MSG_WRONGMIF), which executes dst_clone(skb_dst(pkt)) on the freed dst entry, triggering a slab use-after-free.
Report packets queued to mroute6_sk (a raw socket) and netlink notifications do not require an attached dst entry.
Fix this by:
1. Removing dst_clone() in ip6mr_cache_report() and ensuring report skbs do not hold a dst.
2. Dropping skb_dst before queuing unresolved skbs in ip6mr_cache_unresolved(), matching the fact that multicast forwarding resolves outgoing routes anew via ip6_route_output().
--- net/ipv6/ip6mr.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/ipv6/ip6mr.c +2 -1
@@ -1128,7 +1128,6 @@ static int ip6mr_cache_report(const struct mr_table *mrt, struct sk_buff *pkt, msg->im6_src =ipv6_hdr (pkt)->saddr; msg->im6_dst =ipv6_hdr (pkt)->daddr; -skb_dst_set (skb,dst_clone (skb_dst (pkt))); skb->ip_summed =CHECKSUM_UNNECESSARY ; }
@@ -1138,6 +1137,7 @@ static int ip6mr_cache_report(const struct mr_table *mrt, struct sk_buff *pkt,return -EINVAL ; } +skb_dst_drop (skb);mrt6msg_netlink_event (mrt, skb);/* Deliver to user space multicast routing algorithms */
@@ -1217,6 +1217,7 @@ static int ip6mr_cache_unresolved(struct mr_table *mrt, mifi_t mifi, skb->dev = dev; skb->skb_iif = dev->ifindex; } +skb_dst_drop (skb);skb_queue_tail (&c->_c.mfc_un.unres.unresolved, skb); err =0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 613/869 ALSA: mtpav: shut down output timer before card teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Runyu Xiao <[email protected]>
[ Upstream commit c73cb5b7c159246dd572277c668851a56e516019 ]
snd_mtpav_output_timer() rearms chip->timer while holding chip->spinlock and accesses the card-private mtpav state.
snd_mtpav_free() currently takes the same lock and calls timer_delete() when the timer is active. This only removes a pending timer; it does not wait for a callback that is already running and does not prevent the callback from rearming the timer.
A callback running on another CPU can therefore continue after snd_mtpav_free() releases the lock and access the card-private state while the card is being torn down. It can also rearm the timer after timer_delete() has returned.
Call timer_shutdown_sync() without holding chip->spinlock. This waits for any running callback to finish and prevents further rearming before the card-private mtpav state is released.
--- sound/drivers/mtpav.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-)
sound/drivers/mtpav.c +1 -5
@@ -657,12 +657,8 @@ static int snd_mtpav_get_RAWMIDI(struct mtpav *mcard)static void snd_mtpav_free (struct snd_card *card) {struct mtpav *crd = card->private_data; -unsigned long flags; -spin_lock_irqsave (&crd->spinlock, flags); -if (crd->istimer >0 ) -snd_mtpav_remove_output_timer (crd); -spin_unlock_irqrestore (&crd->spinlock, flags); +timer_shutdown_sync (&crd->timer); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 614/869 virtio_net: Fix resize of the RX ring
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anton Protopopov <[email protected]>
[ Upstream commit d09c98a6da215bce2173a292e4b95c8de6ea5d51 ]
When a AF_XDP socket is attached, the virtnet_rx_resize should resize the rq->xsk_buffs XSK buffer array. Otherwise, when the size grows, the virtnet_rx_resume() causes a write past the end of the array. This is easily reproducable with
ethtool -G ens3 rx 32
./xdpsock -i eth0 -q 0 -r -z &
ethtool -G eth0 rx 256
--- drivers/net/virtio_net.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
drivers/net/virtio_net.c +14 -0
@@ -3220,17 +3220,31 @@ static void virtnet_rx_resume(struct virtnet_info *vi, struct receive_queue *rq)static int virtnet_rx_resize (struct virtnet_info *vi,struct receive_queue *rq,u32 ring_num) { +unsigned int old_ring_num =virtqueue_get_vring_size (rq->vq); +struct xdp_buff **tmp_xsk_buffs =NULL ;int err, qindex; qindex = rq - vi->rq; +if (rq->xsk_pool && ring_num > old_ring_num) { + tmp_xsk_buffs =kvzalloc_objs (*tmp_xsk_buffs, ring_num); +if (!tmp_xsk_buffs) +return -ENOMEM ; + } +virtnet_rx_pause (vi, rq); err =virtqueue_resize (rq->vq, ring_num, virtnet_rq_unmap_free_buf,NULL ); + +/* virtqueue_resize may have changed the size even if err != 0 */ +if (tmp_xsk_buffs &&virtqueue_get_vring_size (rq->vq) > old_ring_num) +swap (rq->xsk_buffs, tmp_xsk_buffs); +if (err)netdev_err (vi->dev,"resize rx fail: rx queue index: %d err: %d\n" , qindex, err);virtnet_rx_resume (vi, rq); +kvfree (tmp_xsk_buffs);return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 615/869 dpll: fix NULL deref in dpll_device_ops() during teardown race
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Petr Oros <[email protected]>
[ Upstream commit 33f016b23a219fe034213849b51436b8e79df251 ]
When the last owner of a dpll device unregisters while a foreign driver still holds a pin on it via dpll_pin_on_pin_register(), the dpll object stays alive with an empty registration list. A pin notification queued before the unregister (e.g. ice reacting to zl3073x_i2c removal) then walks pin->dpll_refs into dpll_device_ops(), which trips the WARN_ON and dereferences the missing registration. dpll_lock cannot help because the notification work was queued before the unregistering driver took the lock.
Treat the empty registration list as a legitimate transient state. Make dpll_priv() and dpll_device_ops() return NULL in that case and make every pin netlink path that resolves a device from a pin skip such dplls. dpll_cmd_pin_get_one() picks a ref with a live registration and returns -ENODEV when there is none, the pin dumpit skips such a pin instead of aborting the dump, dpll_msg_add_pin_dplls() and the frequency, esync, reference sync and phase adjust set paths skip dead refs, and dpll_pin_parent_device_set() validates the parent with dpll_device_get_by_id(). dpll_pin_register() is the last caller that dereferenced the device ops without a check, so move its frequency monitor validation under dpll_lock and tolerate a missing registration there as well.
The empty registration list is equivalent to a cleared DPLL_REGISTERED mark, both transitions happen under dpll_lock in dpll_device_register() and dpll_device_unregister(). A pin notification for a pin whose dplls are all gone is now dropped with -ENODEV instead of crashing, all callers in the core ignore that return value.
WARNING: drivers/dpll/dpll_core.c:1092 at dpll_device_ops+0x24/0x40, CPU#83: kworker/u576:3/23471 Modules linked in: ... ice ... zl3073x_i2c(-) ... zl3073x ... Workqueue: ice_dpll_wq ice_dpll_pin_notify_work [ice] RIP: 0010:dpll_device_ops+0x24/0x40 Call Trace: <TASK> dpll_cmd_pin_get_one+0x336/0x520 dpll_pin_event_send+0x82/0x140 dpll_pin_on_pin_unregister+0xbb/0x160 ice_dpll_pin_notify_work+0x1bc/0x1f0 [ice] process_one_work+0x19e/0x370 worker_thread+0x1a6/0x310 kthread+0xe4/0x120 ret_from_fork+0x1a1/0x270 ret_from_fork_asm+0x1a/0x30 </TASK> ---[ end trace 0000000000000000 ]--- BUG: kernel NULL pointer dereference, address: 0000000000000010 #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page
--- drivers/dpll/dpll_core.c | 12 +++---- drivers/dpll/dpll_netlink.c | 68 +++++++++++++++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 9 deletions(-)
drivers/dpll/dpll_core.c +6 -6
@@ -1009,12 +1009,8 @@ EXPORT_SYMBOL_GPL(dpll_pin_ref_sync_pair_add);static struct dpll_device_registration *dpll_device_registration_first (struct dpll_device *dpll) { -struct dpll_device_registration *reg; - - reg =list_first_entry_or_null ((struct list_head *)&dpll->registration_list, - struct dpll_device_registration, list); -WARN_ON (!reg); -return reg; +return list_first_entry_or_null ((struct list_head *)&dpll->registration_list, + struct dpll_device_registration, list); }void *dpll_priv (struct dpll_device *dpll)
@@ -1022,6 +1018,8 @@ void *dpll_priv(struct dpll_device *dpll)struct dpll_device_registration *reg; reg =dpll_device_registration_first (dpll); +if (!reg) +return NULL ;return reg->priv; }
@@ -1030,6 +1028,8 @@ const struct dpll_device_ops *dpll_device_ops(struct dpll_device *dpll)struct dpll_device_registration *reg; reg =dpll_device_registration_first (dpll); +if (!reg) +return NULL ;return reg->ops; }
drivers/dpll/dpll_netlink.c +65 -3
188 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 616/869 bpf, xdp: move offload check into dev_xdp_install()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiayuan Chen <[email protected]>
[ Upstream commit ad27ed7d2309419a129078d781504f486b1b469a ]
bpf_xdp_link_update() calls dev_xdp_install() directly and skips dev_xdp_attach(), so the checks in dev_xdp_attach() do not run. A user can make an XDP link with a normal program and then swap in an offloaded or device-bound program with BPF_LINK_UPDATE, which puts it on the software path.
dev_xdp_install() is the one place all three paths go through:
"ip link set xdp" and BPF_LINK_CREATE reach it via dev_xdp_attach(), and BPF_LINK_UPDATE calls it directly. So move the program checks (offloaded, bound to another device, device-bound in generic mode, native vs generic, DEVMAP and CPUMAP) there, and keep only the netlink-flag check (XDP_FLAGS_UPDATE_IF_NOEXIST) in dev_xdp_attach().
--- net/core/dev.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
net/core/dev.c +31 -0
@@ -9627,6 +9627,37 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,return -EBUSY ; } +if (prog) { +enum bpf_xdp_mode other_mode = mode ==XDP_MODE_SKB + ?XDP_MODE_DRV :XDP_MODE_SKB ; +bool offload = mode ==XDP_MODE_HW ; + +if (!offload &&dev_xdp_prog (dev, other_mode)) { +NL_SET_ERR_MSG (extack,"Native and generic XDP can't be active at the same time" ); +return -EEXIST ; + } +if (!offload &&bpf_prog_is_offloaded (prog->aux)) { +NL_SET_ERR_MSG (extack,"Using offloaded program without HW_MODE flag is not supported" ); +return -EINVAL ; + } +if (bpf_prog_is_dev_bound (prog->aux) && !bpf_offload_dev_match (prog, dev)) { +NL_SET_ERR_MSG (extack,"Program bound to different device" ); +return -EINVAL ; + } +if (bpf_prog_is_dev_bound (prog->aux) && mode ==XDP_MODE_SKB ) { +NL_SET_ERR_MSG (extack,"Can't attach device-bound programs in generic mode" ); +return -EINVAL ; + } +if (prog->expected_attach_type ==BPF_XDP_DEVMAP ) { +NL_SET_ERR_MSG (extack,"BPF_XDP_DEVMAP programs can not be attached to a device" ); +return -EINVAL ; + } +if (prog->expected_attach_type ==BPF_XDP_CPUMAP ) { +NL_SET_ERR_MSG (extack,"BPF_XDP_CPUMAP programs can not be attached to a device" ); +return -EINVAL ; + } + } +memset (&xdp,0 ,sizeof (xdp)); xdp.command = mode ==XDP_MODE_HW ?XDP_SETUP_PROG_HW :XDP_SETUP_PROG ; xdp.extack = extack;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 617/869 NFSv4/flexfiles: fix NULL dereference for NFSv4.0 data servers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeuk Kim <[email protected]>
[ Upstream commit 2b03ebbf8d5e8f6af4ecd6c65375232dd1ec32cc ]
flexfiles accepts NFSv4.0 data servers, but two NFSv4 code paths assume the data server client has a session. Unlike NFSv4.1+, an NFSv4.0 client has no session (clp->cl_session is NULL; it uses clp->cl_slot_tbl), so I/O to a v4.0 flexfiles DS oopses:
- nfs4_init_ds_session() dereferences clp->cl_session->session_state while seeding the DS lease. It also only seeds cl_lease_time when NFS4_SESSION_INITING is set; without a session that never happens, so cl_lease_time stays 0 and nfs4_renew_state() busy-loops, requeuing every 5 seconds. Seed the lease whenever there is no session and return before touching session state.
- ff_layout_async_handle_error_v4() dereferences
clp->cl_session->fc_slot_table on every DS I/O error. Fall back to the
v4.0 transport slot table (clp->cl_slot_tbl) when there is no session.--- fs/nfs/flexfilelayout/flexfilelayout.c | 3 ++- fs/nfs/nfs4session.c | 16 +++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-)
fs/nfs/flexfilelayout/flexfilelayout.c +2 -1
@@ -1154,7 +1154,8 @@ static int ff_layout_async_handle_error_v4(struct rpc_task *task,struct pnfs_layout_hdr *lo = lseg->pls_layout;struct inode *inode = lo->plh_inode;struct nfs4_deviceid_node *devid =FF_LAYOUT_DEVID_NODE (lseg, idx); -struct nfs4_slot_table *tbl = &clp->cl_session->fc_slot_table; +struct nfs4_slot_table *tbl =nfs4_has_session (clp) ? + &clp->cl_session->fc_slot_table : clp->cl_slot_tbl;switch (op_status) {case NFS4_OK :
fs/nfs/nfs4session.c +11 -5
@@ -634,16 +634,22 @@ int nfs4_init_ds_session(struct nfs_client *clp, unsigned long lease_time)int ret;spin_lock (&clp->cl_lock); -if (test_and_clear_bit (NFS4_SESSION_INITING , &session->session_state)) { -/* -* Do not set NFS_CS_CHECK_LEASE_TIME instead set the -* DS lease to be equal to the MDS lease. -*/ +/* +* Do not set NFS_CS_CHECK_LEASE_TIME instead set the +* DS lease to be equal to the MDS lease. +* +* A v4.0 DS has no session, so seed the lease every time. +*/ +if (!session || +test_and_clear_bit (NFS4_SESSION_INITING , &session->session_state)) { clp->cl_lease_time = lease_time; clp->cl_last_renewal = jiffies; }spin_unlock (&clp->cl_lock); +if (!session) +return 0 ; + ret =nfs41_check_session_ready (clp);if (ret)return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 618/869 ksmbd: scope session state changes to bound connections
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit c50e628122aed077695669e25b842e778511a43d ]
ksmbd_all_conn_set_status() treats every connection whose transient binding flag is set as belonging to the target SessionId. A logoff or session replacement can consequently move an unrelated connection to NEED_RECONNECT or NEED_SETUP.
Pass the target session itself and select connections using either the connection-local session xarray or the session's permanent channel list. Use the same association test while waiting for requests to drain.
Serialize session-wide status changes under request_lock and do not overwrite EXITING or RELEASING. Protect the shutdown transition with the same lock so a concurrent session update cannot revive a closing connection.
--- fs/smb/server/connection.c | 37 ++++++++++++++++++++++++++----- fs/smb/server/connection.h | 7 ++++-- fs/smb/server/mgmt/user_session.c | 8 +++---- fs/smb/server/smb2pdu.c | 6 ++--- 4 files changed, 42 insertions(+), 16 deletions(-)
fs/smb/server/connection.c +31 -6
@@ -242,15 +242,37 @@ void ksmbd_conn_unlock(struct ksmbd_conn *conn)mutex_unlock (&conn->srv_mutex); } -void ksmbd_all_conn_set_status (u64 sess_id,u32 status) +static bool ksmbd_session_is_bound_to_conn (struct ksmbd_session *sess, +struct ksmbd_conn *conn) +{ +bool found; + +rcu_read_lock (); + found =xa_load (&conn->sessions, sess->id) == sess; +rcu_read_unlock (); +if (found) +return true; + +down_read (&sess->chann_lock); + found =xa_load (&sess->ksmbd_chann_list, (long )conn); +up_read (&sess->chann_lock); +return found; +} + +void ksmbd_all_conn_set_status (struct ksmbd_session *sess,u32 status) {struct ksmbd_conn *conn;int bkt;down_read (&conn_list_lock);hash_for_each (conn_list, bkt, conn, hlist) { -if (conn->binding ||xa_load (&conn->sessions, sess_id)) -WRITE_ONCE (conn->status, status); +if (ksmbd_session_is_bound_to_conn (sess, conn)) { +spin_lock (&conn->request_lock); +if (!ksmbd_conn_exiting (conn) && + !ksmbd_conn_releasing (conn)) +WRITE_ONCE (conn->status, status); +spin_unlock (&conn->request_lock); + } }up_read (&conn_list_lock); }
@@ -276,7 +298,8 @@ void ksmbd_conn_wait_idle(struct ksmbd_conn *conn)wait_event (conn->req_running_q,atomic_read (&conn->req_running) <2 ); } -int ksmbd_conn_wait_idle_sess_id (struct ksmbd_conn *curr_conn,u64 sess_id) +int ksmbd_conn_wait_idle_sess (struct ksmbd_conn *curr_conn, +struct ksmbd_session *sess) {struct ksmbd_conn *conn;int rc, retry_count =0 , max_timeout =120 ;
@@ -288,7 +311,7 @@ int ksmbd_conn_wait_idle_sess_id(struct ksmbd_conn *curr_conn, u64 sess_id)down_read (&conn_list_lock);hash_for_each (conn_list, bkt, conn, hlist) { -if (conn->binding ||xa_load (&conn->sessions, sess_id)) { +if (ksmbd_session_is_bound_to_conn (sess, conn)) { rcount = (conn == curr_conn) ?2 :1 ;if (atomic_read (&conn->req_running) >= rcount) { rc = wait_event_timeout(conn->req_running_q,
@@ -609,8 +632,10 @@ static void stop_sessions(void)* handler exited its receive loop for an unrelated * reason). */ -if (READ_ONCE (conn->status) !=KSMBD_SESS_RELEASING ) +spin_lock (&conn->request_lock); +if (!ksmbd_conn_releasing (conn))ksmbd_conn_set_exiting (conn); +spin_unlock (&conn->request_lock); target = conn;break ; }
fs/smb/server/connection.h +5 -2
@@ -20,6 +20,8 @@#include "smb_common.h" #include "ksmbd_work.h" +struct ksmbd_session ; +#define KSMBD_SOCKET_BACKLOG 16enum {
@@ -161,7 +163,8 @@ extern struct rw_semaphore conn_list_lock;bool ksmbd_conn_alive (struct ksmbd_conn *conn);void ksmbd_conn_wait_idle (struct ksmbd_conn *conn); -int ksmbd_conn_wait_idle_sess_id (struct ksmbd_conn *curr_conn,u64 sess_id); +int ksmbd_conn_wait_idle_sess (struct ksmbd_conn *curr_conn, +struct ksmbd_session *sess);struct ksmbd_conn *ksmbd_conn_alloc (void );void ksmbd_conn_free (struct ksmbd_conn *conn);struct ksmbd_conn *ksmbd_conn_get (struct ksmbd_conn *conn);
@@ -266,5 +269,5 @@ static inline void ksmbd_conn_set_releasing(struct ksmbd_conn *conn) WRITE_ONCE(conn->status, KSMBD_SESS_RELEASING); } -void ksmbd_all_conn_set_status (u64 sess_id,u32 status); +void ksmbd_all_conn_set_status (struct ksmbd_session *sess,u32 status);#endif /* __CONNECTION_H__ */
fs/smb/server/mgmt/user_session.c +4 -4
@@ -413,16 +413,16 @@ void destroy_previous_session(struct ksmbd_conn *conn, memcmp(user->passkey, prev_user->passkey, user->passkey_sz)) goto out; -ksmbd_all_conn_set_status (id,KSMBD_SESS_NEED_RECONNECT ); - err =ksmbd_conn_wait_idle_sess_id (conn, id); +ksmbd_all_conn_set_status (prev_sess,KSMBD_SESS_NEED_RECONNECT ); + err =ksmbd_conn_wait_idle_sess (conn, prev_sess);if (err) { -ksmbd_all_conn_set_status (id,KSMBD_SESS_NEED_SETUP ); +ksmbd_all_conn_set_status (prev_sess,KSMBD_SESS_NEED_SETUP ); goto out; }ksmbd_destroy_file_table (prev_sess); prev_sess->state =SMB2_SESSION_EXPIRED ; -ksmbd_all_conn_set_status (id,KSMBD_SESS_NEED_SETUP ); +ksmbd_all_conn_set_status (prev_sess,KSMBD_SESS_NEED_SETUP );ksmbd_launch_ksmbd_durable_scavenger (); out:up_write (&conn->session_lock);
fs/smb/server/smb2pdu.c +2 -4
@@ -2264,7 +2264,6 @@ int smb2_session_logoff(struct ksmbd_work *work)struct ksmbd_session *sess = work->sess;struct smb2_logoff_req *req;struct smb2_logoff_rsp *rsp; -u64 sess_id;int err;WORK_BUFFERS (work, req, rsp);
@@ -2278,8 +2277,7 @@ int smb2_session_logoff(struct ksmbd_work *work)smb2_set_err_rsp (work);return -ENOENT ; } - sess_id =le64_to_cpu (req->hdr.SessionId); -ksmbd_all_conn_set_status (sess_id,KSMBD_SESS_NEED_RECONNECT ); +ksmbd_all_conn_set_status (sess,KSMBD_SESS_NEED_RECONNECT );ksmbd_conn_unlock (conn);ksmbd_close_session_fds (work);
@@ -2296,7 +2294,7 @@ int smb2_session_logoff(struct ksmbd_work *work) sess->state =SMB2_SESSION_EXPIRED ;up_write (&conn->session_lock); -ksmbd_all_conn_set_status (sess_id,KSMBD_SESS_NEED_SETUP ); +ksmbd_all_conn_set_status (sess,KSMBD_SESS_NEED_SETUP ); rsp->StructureSize =cpu_to_le16 (4 ); err =ksmbd_iov_pin_rsp (work, rsp,sizeof (struct smb2_logoff_rsp ));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 619/869 ksmbd: detach blocked lock requests before freeing
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit 215e8816b1ac25176d911abb8704390413ccee4b ]
A file_lock retained by ksmbd for byte-range lock bookkeeping can still be part of the VFS blocked-request graph. In particular, the VFS can chain a new waiter below an already blocked request through flc_blocked_requests. The ksmbd_file reference count does not cover that graph.
Both __ksmbd_close_fd() and the cross-request unlock path free these retained file_lock objects directly. If a dependent waiter is still attached, locks_release_private() hits BUG_ON(!list_empty(&flc->flc_blocked_requests)). The same lifetime mismatch can leave a freed ksmbd_lock reachable through its request-local llist.
Detach the file_lock from the blocked-request graph before freeing it in the close, cross-request unlock, and rollback paths. locks_delete_block() also wakes requests chained below the object. Remove llist when a completed lock is published so a globally visible ksmbd_lock no longer points into the submitting worker's stack.
--- fs/smb/server/smb2pdu.c | 14 ++++++++++---- fs/smb/server/vfs_cache.c | 8 +++++--- 2 files changed, 15 insertions(+), 7 deletions(-)
fs/smb/server/smb2pdu.c +10 -4
@@ -7524,6 +7524,12 @@ static void smb2_remove_blocked_lock(void **argv)locks_wake_up (flock); } +static void smb2_free_lock (struct file_lock *flock) +{ +ksmbd_vfs_posix_lock_unblock (flock); +locks_free_lock (flock); +} +static inline bool lock_defer_pending (struct file_lock *fl) {/* check pending lock waiters */
@@ -7677,14 +7683,14 @@ int smb2_lock(struct ksmbd_work *work) cmp_lock->end == smb_lock->end && !lock_defer_pending(cmp_lock->fl)) { nolock =0 ; -list_del (&cmp_lock->flist); -list_del (&cmp_lock->clist); +list_del_init (&cmp_lock->flist); +list_del_init (&cmp_lock->clist); cmp_lock->conn =NULL ;spin_unlock (&conn->llist_lock);up_read (&conn_list_lock);ksmbd_conn_put (conn); -locks_free_lock (cmp_lock->fl); +smb2_free_lock (cmp_lock->fl);kfree (cmp_lock); goto out_check_cl; }
@@ -7882,7 +7888,7 @@ int smb2_lock(struct ksmbd_work *work)spin_unlock (&conn->llist_lock);ksmbd_conn_put (conn); -locks_free_lock (smb_lock->fl); +smb2_free_lock (smb_lock->fl);if (rlock)locks_free_lock (rlock);kfree (smb_lock);
fs/smb/server/vfs_cache.c +5 -3
@@ -388,8 +388,9 @@ static void __ksmbd_close_fd(struct ksmbd_file_table *ft, struct ksmbd_file *fp)if (!IS_ERR_OR_NULL (filp))fput (filp); -/* because the reference count of fp is 0, it is guaranteed that -* there are not accesses to fp->lock_list. +/* +* The zero fp reference count serializes access to fp->lock_list, but +* the VFS may still have blocked requests chained below these locks. */ list_for_each_entry_safe (smb_lock, tmp_lock, &fp->lock_list, flist) {struct ksmbd_conn *conn = smb_lock->conn;
@@ -402,7 +403,8 @@ static void __ksmbd_close_fd(struct ksmbd_file_table *ft, struct ksmbd_file *fp)ksmbd_conn_put (conn); } -list_del (&smb_lock->flist); +list_del_init (&smb_lock->flist); +ksmbd_vfs_posix_lock_unblock (smb_lock->fl);locks_free_lock (smb_lock->fl);kfree (smb_lock); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 620/869 ksmbd: safely discard unregistered deferred locks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit 054bcca4cd9f00719b01f7108b51a2168fb94f15 ]
When vfs_lock_file() defers a lock, smb2_lock() puts its ksmbd_lock on rollback_list before allocating and registering the asynchronous work. If either operation fails, rollback assumes that smb_lock->conn is initialized and dereferences NULL. The deferred file_lock also remains linked into the VFS blocked-lock state while it is freed.
Keep the lock off rollback_list until async setup succeeds. On setup failures, explicitly unblock and wake the deferred lock before freeing it and its ksmbd wrapper.
--- fs/smb/server/smb2pdu.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +5 -1
@@ -7772,11 +7772,12 @@ int smb2_lock(struct ksmbd_work *work)ksmbd_debug (SMB ,"would have to wait for getting lock\n" ); -list_add (&smb_lock->llist, &rollback_list); argv =kmalloc (sizeof (void *),KSMBD_DEFAULT_GFP );if (!argv) { err = -ENOMEM ; +smb2_free_lock (flock); +kfree (smb_lock); goto out; } argv[0 ] = flock;
@@ -7787,8 +7788,11 @@ int smb2_lock(struct ksmbd_work *work)if (rc) {kfree (argv); err = -ENOMEM ; +smb2_free_lock (flock); +kfree (smb_lock); goto out; } +list_add (&smb_lock->llist, &rollback_list);spin_lock (&fp->f_lock);list_add (&work->fp_entry, &fp->blocked_works);spin_unlock (&fp->f_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 621/869 erofs: fix interlaced ztailpacking pclusters
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gao Xiang <[email protected]>
[ Upstream commit 862427ebb81d1f6abbf74d799790e1694b37b187 ]
On-disk sizes of interlaced pclusters should be block-aligned, and ztailpacking interlaced pclusters should be invalid at all.
Currently, mkfs.erofs won't generate any interlaced pcluster with ztailpacking enabled, so this doesn't affect any existing valid filesystems.
However, crafted images can contain invalid interlaced ztailpacking pclusters, resulting in an out-of-bounds read from a kmap'd page and copying irrelevant kernel memory into userspace-visible page cache.
--- fs/erofs/decompressor.c | 1 + fs/erofs/zmap.c | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-)
fs/erofs/decompressor.c +1 -0
@@ -312,6 +312,7 @@ static int z_erofs_transform_plain(struct z_erofs_decompress_req *rq,return -EOPNOTSUPP ;if (rq->alg ==Z_EROFS_COMPRESSION_INTERLACED ) { cur = bs - (rq->pageofs_out & (bs -1 )); +DBG_BUGON (rq->pageofs_in & (bs -1 )); pi = (rq->pageofs_in + rq->inputsize - cur) & ~PAGE_MASK ; cur =min (cur, rq->outputsize);if (cur && rq->out[0 ]) {
fs/erofs/zmap.c +5 -3
@@ -477,9 +477,11 @@ static int z_erofs_do_map_blocks(struct inode *inode, err = -EFSCORRUPTED ; goto unmap_out; } - afmt = vi->z_advise &Z_EROFS_ADVISE_INTERLACED_PCLUSTER ? -Z_EROFS_COMPRESSION_INTERLACED : -Z_EROFS_COMPRESSION_SHIFTED ; +if ((vi->z_advise &Z_EROFS_ADVISE_INTERLACED_PCLUSTER ) && + !(map->m_flags &EROFS_MAP_META )) + afmt =Z_EROFS_COMPRESSION_INTERLACED ; +else + afmt =Z_EROFS_COMPRESSION_SHIFTED ; }else { afmt = m.headtype ==Z_EROFS_LCLUSTER_TYPE_HEAD2 ? vi->z_algorithmtype[1 ] : vi->z_algorithmtype[0 ];
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 622/869 ksmbd: defer publishing granted locks to prevent UAF/double-free race
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilan Dudnik <[email protected]>
[ Upstream commit 29f74f0f2e6df3b393b7b66e810136d0c64e3c59 ]
In smb2_lock(), mid-batch granted locks are published to connection-wide (conn->lock_list) and file-wide (fp->lock_list) lists immediately upon vfs_lock_file() success, while also remaining tracked on the stack-local rollback_list.
If a subsequent element in the same SMB2_LOCK request array fails validation or execution, the thread jumps to out: and walks rollback_list to undo previously granted locks. However, because the granted lock was already published to conn->lock_list, a concurrent UNLOCK request on the same connection can find the lock object and kfree() it before the rollback loop executes.
When the granting thread subsequently walks rollback_list, it dereferences and frees the already-freed ksmbd_lock structure, resulting in a Use-After-Free and Double-Free (on both ksmbd_lock and struct file_lock).
Fix this by deferring the publication of granted locks to conn->lock_list and fp->lock_list until after the entire array of lock elements has been processed without error. Mid-batch grants remain tracked exclusively on the request-local rollback_list until the whole batch succeeds, eliminating the race window.
--- fs/smb/server/smb2pdu.c | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-)
fs/smb/server/smb2pdu.c +15 -17
@@ -7825,16 +7825,10 @@ int smb2_lock(struct ksmbd_work *work) rsp->hdr.Status =STATUS_RANGE_NOT_LOCKED ;kfree (smb_lock); - goto out2; +/* rollback_list may still hold earlier grants */ + goto out; }else if (!rc) {list_add (&smb_lock->llist, &rollback_list); - smb_lock->conn =ksmbd_conn_get (work->conn); -spin_lock (&work->conn->llist_lock); -list_add_tail (&smb_lock->clist, - &work->conn->lock_list); -list_add_tail (&smb_lock->flist, - &fp->lock_list); -spin_unlock (&work->conn->llist_lock);ksmbd_debug (SMB ,"successful in taking lock\n" ); }else {locks_free_lock (flock);
@@ -7856,6 +7850,19 @@ int smb2_lock(struct ksmbd_work *work)if (err) goto out; +/* publish only once the whole batch has committed */ +if (!list_empty (&rollback_list)) { +spin_lock (&work->conn->llist_lock); +list_for_each_entry (smb_lock, &rollback_list, llist) { + smb_lock->conn =ksmbd_conn_get (work->conn); +list_add_tail (&smb_lock->clist, + &work->conn->lock_list); +list_add_tail (&smb_lock->flist, + &fp->lock_list); + } +spin_unlock (&work->conn->llist_lock); + } +ksmbd_fd_put (work, fp);return 0 ;
@@ -7883,15 +7890,6 @@ int smb2_lock(struct ksmbd_work *work) }list_del (&smb_lock->llist); - conn = smb_lock->conn; -spin_lock (&conn->llist_lock); -if (!list_empty (&smb_lock->flist)) -list_del (&smb_lock->flist); -list_del (&smb_lock->clist); - smb_lock->conn =NULL ; -spin_unlock (&conn->llist_lock); -ksmbd_conn_put (conn); -smb2_free_lock (smb_lock->fl);if (rlock)locks_free_lock (rlock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 623/869 ksmbd: serialize oplock close with pending break ownership
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
[ Upstream commit b0148dc5625dbfd50596ac63c7487c12e8a8ab03 ]
close may abort an in-flight oplock break while another breaker already holds an opinfo reference. Releasing pending_break wakes that waiter, but without serializing the close transition with bit acquisition it can become a new break owner through the test_and_set_bit() fast path. It can then overwrite OPLOCK_CLOSING with OPLOCK_ACK_WAIT and continue a break for a dying opinfo.
Make OPLOCK_CLOSING terminal once the opinfo is removed from the inode list. Serialize that transition, pending_break acquisition, and OPLOCK_ACK_WAIT setup with an opinfo state lock. A breaker which loses the race releases its ownership and returns -ENOENT. Explicitly wake pending_break waiters during close so they can observe the terminal state.
Also prevent ACK and timeout paths from replacing OPLOCK_CLOSING with OPLOCK_STATE_NONE.
--- fs/smb/server/oplock.c | 81 ++++++++++++++++++++++++++++++++++------- fs/smb/server/oplock.h | 1 + fs/smb/server/smb2pdu.c | 12 ++++-- 3 files changed, 77 insertions(+), 17 deletions(-)
fs/smb/server/oplock.c +67 -14
@@ -56,6 +56,7 @@ static struct oplock_info *alloc_opinfo(struct ksmbd_work *work, opinfo->conn =ksmbd_conn_get (work->conn); opinfo->level =SMB2_OPLOCK_LEVEL_NONE ; opinfo->op_state =OPLOCK_STATE_NONE ; +spin_lock_init (&opinfo->state_lock); opinfo->pending_break =0 ; opinfo->fid = id; opinfo->Tid = Tid;
@@ -424,14 +425,23 @@ void close_id_del_oplock(struct ksmbd_file *fp)opinfo_del (opinfo);rcu_assign_pointer (fp->f_opinfo,NULL ); -if (opinfo->op_state ==OPLOCK_ACK_WAIT ) { - opinfo->op_state =OPLOCK_CLOSING ; -wake_up_interruptible_all (&opinfo->oplock_q); -if (opinfo->is_lease) { -atomic_set (&opinfo->breaking_cnt,0 ); -wake_up_interruptible_all (&opinfo->oplock_brk); - } - } +spin_lock (&opinfo->state_lock); +if (opinfo->op_state ==OPLOCK_ACK_WAIT && opinfo->is_lease) +atomic_set (&opinfo->breaking_cnt,0 ); +/* +* An opinfo that has been removed from the inode list is terminal. Keep +* this transition and releasing pending_break under state_lock. a breaker +* takes the same lock before it acquires pending_break or sets ACK_WAIT. +*/ + opinfo->op_state =OPLOCK_CLOSING ; +clear_bit_unlock (0 , &opinfo->pending_break); +spin_unlock (&opinfo->state_lock); +wake_up_interruptible_all (&opinfo->oplock_q); +if (opinfo->is_lease) +wake_up_interruptible_all (&opinfo->oplock_brk); +/* memory barrier is needed for wake_up_bit() */ +smp_mb__after_atomic (); +wake_up_bit (&opinfo->pending_break,0 );opinfo_count_dec (fp);atomic_dec (&opinfo->refcount);
@@ -610,10 +620,16 @@ static void wait_for_break_ack(struct oplock_info *opinfo)/* is this a timeout ? */ if (!rc) { +spin_lock (&opinfo->state_lock); +if (opinfo->op_state ==OPLOCK_CLOSING ) { +spin_unlock (&opinfo->state_lock); +return ; + }if (opinfo->is_lease) opinfo->o_lease->state =SMB2_LEASE_NONE_LE ; opinfo->level =SMB2_OPLOCK_LEVEL_NONE ; opinfo->op_state =OPLOCK_STATE_NONE ; +spin_unlock (&opinfo->state_lock); } }
@@ -625,17 +641,46 @@ static void wake_up_oplock_break(struct oplock_info *opinfo)wake_up_bit (&opinfo->pending_break,0 ); } +static bool oplock_break_set_ack_wait (struct oplock_info *opinfo) +{ +bool ret = false; + +spin_lock (&opinfo->state_lock); +if (opinfo->op_state !=OPLOCK_CLOSING ) { + opinfo->op_state =OPLOCK_ACK_WAIT ; + ret = true; + } +spin_unlock (&opinfo->state_lock); + +return ret; +} +static int oplock_break_pending (struct oplock_info *opinfo,int req_op_level) { -while (test_and_set_bit (0 , &opinfo->pending_break)) { +for (;;) { +bool closing; + +spin_lock (&opinfo->state_lock); + closing = opinfo->op_state ==OPLOCK_CLOSING ; +if (!closing && !test_and_set_bit (0 , &opinfo->pending_break)) { +spin_unlock (&opinfo->state_lock); +break ; + } +spin_unlock (&opinfo->state_lock); +if (closing) +return -ENOENT ; +wait_on_bit (&opinfo->pending_break,0 ,TASK_UNINTERRUPTIBLE );/* Not immediately break to none. */ opinfo->open_trunc =0 ; -if (opinfo->op_state ==OPLOCK_CLOSING ) +spin_lock (&opinfo->state_lock); + closing = opinfo->op_state ==OPLOCK_CLOSING ; +spin_unlock (&opinfo->state_lock); +if (closing)return -ENOENT ; -else if (opinfo->level <= req_op_level) { +if (opinfo->level <= req_op_level) {if (opinfo->is_lease == false)return 1 ;
@@ -1005,7 +1050,11 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,release_async_work (in_work); } - brk_opinfo->op_state =OPLOCK_ACK_WAIT ; +if (!oplock_break_set_ack_wait (brk_opinfo)) { +atomic_dec_if_positive (&brk_opinfo->breaking_cnt); +wake_up_oplock_break (brk_opinfo); +return -ENOENT ; + } }else atomic_dec (&brk_opinfo->breaking_cnt); }else {
@@ -1014,8 +1063,12 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,return err <0 ? err :0 ;if (brk_opinfo->level ==SMB2_OPLOCK_LEVEL_BATCH || - brk_opinfo->level ==SMB2_OPLOCK_LEVEL_EXCLUSIVE ) - brk_opinfo->op_state =OPLOCK_ACK_WAIT ; + brk_opinfo->level ==SMB2_OPLOCK_LEVEL_EXCLUSIVE ) { +if (!oplock_break_set_ack_wait (brk_opinfo)) { +wake_up_oplock_break (brk_opinfo); +return -ENOENT ; + } + } }if (brk_opinfo->is_lease)
fs/smb/server/oplock.h +1 -0
@@ -59,6 +59,7 @@ struct oplock_info {struct ksmbd_file *o_fp;int level;int op_state; +spinlock_t state_lock;unsigned long pending_break;u64 fid;atomic_t breaking_cnt;
fs/smb/server/smb2pdu.c +9 -3
@@ -8827,7 +8827,10 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)smb2_set_err_rsp (work); out: - opinfo->op_state =OPLOCK_STATE_NONE ; +spin_lock (&opinfo->state_lock); +if (opinfo->op_state !=OPLOCK_CLOSING ) + opinfo->op_state =OPLOCK_STATE_NONE ; +spin_unlock (&opinfo->state_lock);wake_up_interruptible_all (&opinfo->oplock_q);opinfo_put (opinfo);ksmbd_fd_put (work, fp);
@@ -8913,9 +8916,12 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)if (ret) goto err_out; - opinfo->op_state =OPLOCK_STATE_NONE ; +spin_lock (&opinfo->state_lock); +if (opinfo->op_state !=OPLOCK_CLOSING ) + opinfo->op_state =OPLOCK_STATE_NONE ; +spin_unlock (&opinfo->state_lock);wake_up_interruptible_all (&opinfo->oplock_q); -atomic_dec (&opinfo->breaking_cnt); +atomic_dec_if_positive (&opinfo->breaking_cnt);wake_up_interruptible_all (&opinfo->oplock_brk);opinfo_put (opinfo);return ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 624/869 ksmbd: fix slab-out-of-bounds read in ksmbd_alloc_user()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yunseong Kim <[email protected]>
[ Upstream commit 7405d0ba294306721843bc551611775e6edef516 ]
ksmbd_alloc_user() copies resp->hash_sz bytes out of the mountd IPC login response with
user->passkey_sz = resp->hash_sz; user->passkey = kmalloc(resp->hash_sz, KSMBD_DEFAULT_GFP); if (user->passkey) memcpy(user->passkey, resp->hash, resp->hash_sz);
resp->hash_sz is a __u16 supplied by the response, but resp->hash[] is only KSMBD_REQ_MAX_HASH_SZ bytes. A malformed or malicious login response can set hash_sz well beyond that (up to 65535), so the memcpy() reads past the end of the response object. ipc_validate_msg() does not bound hash_sz, so reject any response whose hash_sz exceeds the on-stack hash[] buffer before allocating and copying.
[ 2030.238706] BUG: KASAN: slab-out-of-bounds in ksmbd_alloc_user+0x278/0x680 [ 2030.240549] Read of size 65535 at addr ffff888121bb6680 by task kworker/4:1/18611 [ 2030.242296] [ 2030.242710] CPU: 4 UID: 0 PID: 18611 Comm: kworker/4:1 Not tainted 7.1.0-next-20260623-virtme #96 PREEMPT(lazy) [ 2030.242732] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014 [ 2030.242743] Workqueue: ksmbd-io handle_ksmbd_work [ 2030.242763] Call Trace: [ 2030.242769] <TASK> [ 2030.242776] dump_stack_lvl+0xa2/0xd0 [ 2030.242794] print_address_description+0x77/0x200 [ 2030.242815] ? ksmbd_alloc_user+0x278/0x680 [ 2030.242831] print_report+0x58/0x70 [ 2030.242848] kasan_report+0x117/0x150 [ 2030.242869] ? ksmbd_alloc_user+0x278/0x680 [ 2030.242888] kasan_check_range+0x3c7/0x3f0 [ 2030.242908] ? ksmbd_alloc_user+0x278/0x680 [ 2030.242925] __asan_memcpy+0x29/0x70 [ 2030.242942] ksmbd_alloc_user+0x278/0x680 [ 2030.242960] ksmbd_login_user+0xc3/0x120 [ 2030.242978] ntlm_authenticate+0x5e6/0x1b00 [ 2030.243017] ? __pfx_ntlm_authenticate+0x10/0x10 [ 2030.243035] ? ksmbd_session_lookup+0x188/0x1d0 [ 2030.243054] ? __pfx_ksmbd_session_lookup+0x10/0x10 [ 2030.243090] ? __sanitizer_cov_trace_switch+0x7b/0x140 [ 2030.243108] smb2_sess_setup+0x1e4a/0x27b0 [ 2030.243126] ? copy_from_kernel_nofault+0x199/0x300 [ 2030.243156] ? __pfx_smb2_sess_setup+0x10/0x10 [ 2030.243173] ? get_smb2_cmd_val+0xe3/0x1c0 [ 2030.243208] handle_ksmbd_work+0x954/0x1280 [ 2030.243230] ? __pfx_handle_ksmbd_work+0x10/0x10 [ 2030.243249] ? process_scheduled_works+0xa07/0x1490 [ 2030.243270] ? process_scheduled_works+0xa07/0x1490 [ 2030.243291] process_scheduled_works+0xa70/0x1490 [ 2030.243320] ? __pfx_process_scheduled_works+0x10/0x10 [ 2030.243340] ? do_raw_spin_lock+0x130/0x300 [ 2030.243358] ? lock_is_held_type+0x7b/0x110 [ 2030.243388] worker_thread+0x932/0xe20 [ 2030.243415] kthread+0x38a/0x470 [ 2030.243431] ? __pfx_worker_thread+0x10/0x10 [ 2030.243451] ? __pfx_kthread+0x10/0x10 [ 2030.243467] ret_from_fork+0x484/0x910 [ 2030.243485] ? __pfx_ret_from_fork+0x10/0x10 [ 2030.243501] ? __switch_to+0xc77/0x12c0 [ 2030.243523] ? __pfx_kthread+0x10/0x10 [ 2030.243540] ret_from_fork_asm+0x1a/0x30 [ 2030.243564] </TASK> [ 2030.243570] [ 2030.290164] Allocated by task 19279: [ 2030.290911] kasan_save_track+0x3e/0x80 [ 2030.292179] __kasan_kmalloc+0x72/0x90 [ 2030.293217] __kvmalloc_node_noprof+0x3ff/0x6b0 [ 2030.294467] handle_generic_event+0x59b/0x750 [ 2030.295345] genl_family_rcv_msg_doit+0x238/0x340 [ 2030.296553] genl_rcv_msg+0x606/0x7b0 [ 2030.297129] netlink_rcv_skb+0x22b/0x4a0 [ 2030.298500] genl_rcv+0x2d/0x40 [ 2030.299273] netlink_unicast+0x7ba/0x930 [ 2030.300019] netlink_sendmsg+0x8c3/0xb00 [ 2030.301073] __sock_sendmsg+0xec/0x140 [ 2030.301579] __sys_sendto+0x357/0x470 [ 2030.302255] __x64_sys_sendto+0xe3/0x100 [ 2030.303425] do_syscall_64+0x135/0x460 [ 2030.304763] entry_SYSCALL_64_after_hwframe+0x77/0x7f [ 2030.305594] [ 2030.305819] The buggy address belongs to the object at ffff888121bb6640 [ 2030.305819] which belongs to the cache kmalloc-192 of size 192 [ 2030.309595] The buggy address is located 64 bytes inside of [ 2030.309595] allocated 166-byte region [ffff888121bb6640, ffff888121bb66e6) [ 2030.312484] [ 2030.312719] The buggy address belongs to the physical page: [ 2030.314315] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x121bb6 [ 2030.316481] head: order:1 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0 [ 2030.318248] flags: 0x100000000000040(head|node=0|zone=2) [ 2030.319662] page_type: f5(slab) [ 2030.320242] raw: 0100000000000040 ffff8881000424c0 ffffea00047c1510 ffff888100040468 [ 2030.321911] raw: 0000000000000000 0000000000150015 00000000f5000000 0000000000000000 [ 2030.324413] head: 0100000000000040 ffff8881000424c0 ffffea00047c1510 ffff888100040468 [ 2030.326150] head: 0000000000000000 0000000000150015 00000000f5000000 0000000000000000 [ 2030.327960] head: 0100000000000001 ffffffffffffff81 00000000ffffffff 00000000ffffffff [ 2030.329615] head: ffff888121bb7ab0 0000000000000000 00000000ffffffff 0000000000000000 [ 2030.331861] page dumped because: kasan: bad access detected [ 2030.332946] [ 2030.333502] Memory state around the buggy address: [ 2030.334698] ffff888121bb6580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 2030.336475] ffff888121bb6600: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00 [ 2030.338143] >ffff888121bb6680: 00 00 00 00 00 00 00 00 00 00 00 00 06 fc fc fc [ 2030.339116] ^ [ 2030.341315] ffff888121bb6700: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 2030.342801] ffff888121bb6780: fc fc fc fc fc fc fc fc fa fb fb fb fb fb fb fb [ 2030.344643] ==================================================================
Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.
[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow
--- fs/smb/server/mgmt/user_config.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/smb/server/mgmt/user_config.c +11 -0
@@ -37,6 +37,17 @@ struct ksmbd_user *ksmbd_alloc_user(struct ksmbd_login_response *resp, {struct ksmbd_user *user; +/* +* resp->hash_sz is a __u16 taken from the mountd IPC login response but +* resp->hash[] is only KSMBD_REQ_MAX_HASH_SZ bytes. A malformed or +* malicious response can set hash_sz far beyond that (up to 65535), +* making the memcpy() below read past the response object +* (slab-out-of-bounds in ksmbd_alloc_user()). Reject any oversized +* hash rather than trust the length. +*/ +if (resp->hash_sz >sizeof (resp->hash)) +return NULL ; + user =kmalloc (sizeof (struct ksmbd_user ),KSMBD_DEFAULT_GFP );if (!user)return NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 625/869 bpf: Check pointer type for all atomic RMW paths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yiyang Chen <[email protected]>
[ Upstream commit 4bc49ae344d65cfcef738f281ac575cf73ca2fc5 ]
Atomic RMW verification records an instruction pointer type only when the current destination is PTR_TO_ARENA. A second path can therefore reach the same instruction with an ordinary pointer without comparing it against the saved arena type.
The post-verification fixup uses the saved type to rewrite the instruction to BPF_PROBE_ATOMIC for every path. Record the actual destination type for all atomic RMW paths so the existing mismatch check rejects incompatible uses of one instruction.
--- kernel/bpf/verifier.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
kernel/bpf/verifier.c +3 -5
@@ -7559,11 +7559,9 @@ static int check_atomic_rmw(struct bpf_verifier_env *env,if (err)return err; -if (is_arena_reg (env, insn->dst_reg)) { - err =save_aux_ptr_type (env,PTR_TO_ARENA , false); -if (err) -return err; - } + err =save_aux_ptr_type (env,reg_state (env, insn->dst_reg)->type, false); +if (err) +return err;/* Check whether we can write into the same memory. */ err =check_mem_access (env, env->insn_idx, insn->dst_reg, insn->off,BPF_SIZE (insn->code),BPF_WRITE ,-1 , true, false);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 626/869 apparmor: fix deadlock in complain-mode change_hat
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: John Johansen <[email protected]>
[ Upstream commit 4ec11f14d1d6fdda787d991b142537be7841d395 ]
The use of change_hat when in complain mode can cause a deadlock when the hat doesn't exist and a new learning profile is created for the missing profile. This is because change_hat() has taken the lock to search the hat list and creating the new learning profile needs to take the lock to add it to the list.
Quoted 1 line
From the bug report:
Originally found in 7.0.0 in LTS ubuntu 26.04 with pam_apparmor + su in complain mode set to change hats. Then verified in newest available vanilla kernel I've compiled to see if still present:
7.2-rc7 vanilla -> affected
checked also some other kernels:
6.18.44 vanilla -> affected
6.12.95 with debian patches -> unaffected
On systems without bug (for example 6.12.95 debian) it just prints:
aa_change_hat rc=0
On systems with bug, the executable always hangs, prints nothing and becomes unkillable. (And once stuck this way, it will cause any further hat changes to also cause the changing process to get stuck)
Then in syslog you can find hint about cause:
kernel: INFO: task hat:3409 blocked for more than 483 seconds. kernel: Not tainted 7.2.0-rc7 #1 kernel: "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. kernel: task:hat state:D stack:0 pid:3409 tgid:3409 ppid:2605 task_flags:0x400000 flags:0x00080800 kernel: Call Trace: kernel: <TASK> kernel: __schedule+0x48f/0xfe0 kernel: schedule+0x27/0xa0 kernel: schedule_preempt_disabled+0x15/0x30 kernel: __mutex_lock.constprop.0+0x569/0xa10 kernel: aa_new_learning_profile+0x15f/0x210 kernel: build_change_hat+0x19f/0x3b0 kernel: change_hat.isra.0+0x5dd/0xd60 kernel: aa_change_hat+0x2f3/0x710 kernel: aa_setprocattr_changehat+0x121/0x1f0 kernel: do_setattr+0x28c/0x340 kernel: apparmor_setselfattr+0x20/0x50 kernel: security_setselfattr+0xf6/0x110 kernel: __x64_sys_lsm_set_self_attr+0x53/0x90 kernel: do_syscall_64+0xdd/0x5e0 kernel: ? __mod_memcg_lruvec_state+0xfd/0x260 kernel: ? lruvec_stat_mod_folio+0x8d/0xd0 kernel: ? __folio_mod_stat+0x2d/0x90 kernel: ? map_anon_folio_pte_nopf+0xd1/0x1f0 kernel: ? do_anonymous_page+0x184/0xa10 kernel: ? __handle_mm_fault+0x805/0x870 kernel: ? count_memcg_events+0xef/0x230 kernel: ? handle_mm_fault+0x1f0/0x2f0 kernel: ? do_user_addr_fault+0x2bb/0x7b0 kernel: ? do_syscall_64+0x94/0x5e0 kernel: ? exc_page_fault+0x75/0x160 kernel: entry_SYSCALL_64_after_hwframe+0x76/0x7e kernel: RIP: 0033:0x7f815e134c8d kernel: RSP: 002b:00007fff6df94ea8 EFLAGS: 00000246 ORIG_RAX: 00000000000001cc kernel: RAX: ffffffffffffffda RBX: 0000556d8c81d040 RCX: 00007f815e134c8d kernel: RDX: 0000000000000046 RSI: 0000556d8c81d040 RDI: 0000000000000064 kernel: RBP: 00007fff6df94ef0 R08: 00007f815e212ac8 R09: 000000000000000c kernel: R10: 0000000000000000 R11: 0000000000000246 R12: 0000556d8c81d010 kernel: R13: 0000000000000026 R14: 0000000000000046 R15: 0000000000000064 kernel: </TASK> kernel: INFO: task hat:3409 is blocked on a mutex likely owned by task hat:3409.
To fix the issue, lift the locking out of the core of aa_new_learning_profile(), introduce a wrapper function that takes the lock where needed, and have build_change_hat() call the core function that no longer takes the lock.
In addition fix 4 other issues introduced by commit32e92764d6f8d ("apparmor: grab ns lock and refresh when looking up changehat child profiles")
- aa_get_profile_rcu() was replaced-by: aa_get_profile without the accompanying rcu_dereference_protected()
- an extra aa_get_label(label) was introduced at the start of
change_hat() without an accompanying aa_put_label() causing a
reference count leak.
- a reference count leak was introduced in the label_is_stale(label)
case, where the newest profile would be leaked instead of the
label passed to the function.
- a potential UAF when the lookup walks up the tree with new_ns != ns
the new label reference is put, and then used for the next lookup.
The mutex_lock, will block replacement, and removal in the locked
ns. However there are two cases where putting the reference can
result in the label being freed even with the lock held.
1. the label does not have a list reference (possible for temporary or special profiles) in which case the put can trigger the cleanup.
2. the new label reference is in a different namespace, which does not have a lock held on it. This extends case 1 to also include replacement, and removal that could be occurring in the namespace new is in.
--- security/apparmor/domain.c | 25 +++++++++++++++++-------- security/apparmor/include/policy.h | 3 +++ security/apparmor/policy.c | 22 +++++++++++++++++----- 3 files changed, 37 insertions(+), 13 deletions(-)
security/apparmor/domain.c +17 -8
@@ -1036,8 +1036,8 @@ static struct aa_label *build_change_hat(const struct cred *subj_cred,if (!hat) { error = -ENOENT ;if (COMPLAIN_MODE (profile)) { - hat =aa_new_learning_profile (profile, true, name, -GFP_KERNEL ); + hat =__aa_new_learning_profile (profile, true, name, +GFP_KERNEL );if (!hat) { info ="failed null profile create" ; error = -ENOMEM ;
@@ -1075,6 +1075,7 @@ static struct aa_label *change_hat(const struct cred *subj_cred,bool sibling = false;const char *name, *info =NULL ;int i, error; +bool needput = false;AA_BUG (!label);AA_BUG (!hats);
@@ -1087,7 +1088,6 @@ static struct aa_label *change_hat(const struct cred *subj_cred,* the profiles and label, we can rely on the namespaces being live * and avoid incrementing their refcounts while grabbing the lock. */ - label =aa_get_label (label); ns =labels_ns (label); retry:
@@ -1095,15 +1095,19 @@ static struct aa_label *change_hat(const struct cred *subj_cred,if (label_is_stale (label)) { new =aa_get_newest_label (label); new_ns =labels_ns (new); + +if (needput) +/* aa_put_label() is safe to call when under lock */ +aa_put_label (label); + label = new; + needput = true; +/* check if replaced with label in parent ns, and lock there */ if (new_ns != ns) { -aa_put_label (new);mutex_unlock (&ns->lock); ns = new_ns; - label = new; +/* retry will bottom out at the root of the tree */ goto retry; } -aa_put_label (label); - label = new; }if (PROFILE_IS_HAT (labels_profile (label)))
@@ -1114,7 +1118,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred, name = hats[i];label_for_each_in_ns (it,labels_ns (label), label, profile) {if (sibling &&PROFILE_IS_HAT (profile)) { - root =aa_get_profile (profile->parent); + root =aa_get_profile (rcu_dereference_protected (profile->parent, +mutex_is_locked (&ns->lock))); }else if (!sibling && !PROFILE_IS_HAT (profile)) { root =aa_get_profile (profile); }else {/* conflicting change type */
@@ -1175,6 +1180,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred, } }mutex_unlock (&ns->lock); +if (needput) +aa_put_label (label);return ERR_PTR (error); build:
@@ -1188,6 +1195,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred, goto fail; }/* else if (IS_ERR) build_change_hat has logged error so return new */ mutex_unlock (&ns->lock); +if (needput) +aa_put_label (label);return new; }
security/apparmor/include/policy.h +3 -0
@@ -258,6 +258,9 @@ struct aa_profile *aa_alloc_profile(const char *name, struct aa_proxy *proxy, gfp_t gfp);struct aa_profile *aa_alloc_null (struct aa_profile *parent,const char *name,gfp_t gfp); +struct aa_profile *__aa_new_learning_profile (struct aa_profile *parent, +bool hat,const char *base, +gfp_t gfp);struct aa_profile *aa_new_learning_profile (struct aa_profile *parent,bool hat,const char *base,gfp_t gfp);void aa_free_profile (struct aa_profile *profile);
security/apparmor/policy.c +17 -5
@@ -667,7 +667,7 @@ struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name, }/** -* aa_new_learning_profile - create or find a null-X learning profile +* __aa_new_learning_profile - create or find a null-X learning profile * @parent: profile that caused this profile to be created (NOT NULL) * @hat: true if the null- learning profile is a hat * @base: name to base the null profile off of
@@ -684,14 +684,16 @@ struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name,* * Returns: new refcounted profile else NULL on failure */ -struct aa_profile *aa_new_learning_profile (struct aa_profile *parent,bool hat, -const char *base,gfp_t gfp) +struct aa_profile *__aa_new_learning_profile (struct aa_profile *parent, +bool hat,const char *base, +gfp_t gfp) {struct aa_profile *p, *profile;const char *bname;char *name =NULL ;AA_BUG (!parent); +AA_BUG (!mutex_is_locked (&parent->ns->lock));if (base) { name = kmalloc(strlen(parent->base.hname) + 8 + strlen(base),
@@ -723,7 +725,6 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,if (hat) profile->label.flags |=FLAG_HAT ; -mutex_lock_nested (&profile->ns->lock, profile->ns->level); p =__find_child (&parent->base.profiles, bname);if (p) {aa_free_profile (profile);
@@ -731,7 +732,6 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat, }else {__add_profile (&parent->base.profiles, profile); } -mutex_unlock (&profile->ns->lock);/* refcount released by caller */ out:
@@ -745,6 +745,18 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,return NULL ; } +struct aa_profile *aa_new_learning_profile (struct aa_profile *parent,bool hat, +const char *base,gfp_t gfp) +{ +struct aa_profile *profile; + +mutex_lock_nested (&parent->ns->lock, parent->ns->level); + profile =__aa_new_learning_profile (parent, hat, base, gfp); +mutex_unlock (&parent->ns->lock); + +return profile; +} +/** * replacement_allowed - test to see if replacement is allowed * @profile: profile to test if it can be replaced (MAYBE NULL)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 627/869 blk-cgroup: delay freeing policy data after rcu grace period
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Kuai <[email protected]>
[ Upstream commit 0af3fedb8c8ed3c07b4f76927bd7fc88f6f82efb ]
Currently blkcg_print_blkgs() must hold RCU to iterate blkgs from a blkcg, and prfill() must hold queue_lock to prevent policy data from being freed by policy deactivation. As a consequence, queue_lock has to be nested under RCU from blkcg_print_blkgs().
Delay freeing policy data until after an RCU grace period so prfill() can be protected by RCU alone.
Stable-dep-of: 97cb95d21488 ("blk-iocost: clear delay state when freeing policy data")
--- block/bfq-cgroup.c | 9 ++++++++- block/blk-cgroup.h | 2 ++ block/blk-iocost.c | 14 ++++++++++++-- block/blk-iolatency.c | 10 +++++++++- block/blk-throttle.c | 13 +++++++++++-- 5 files changed, 42 insertions(+), 6 deletions(-)
block/bfq-cgroup.c +8 -1
@@ -548,14 +548,21 @@ static void bfq_pd_init(struct blkg_policy_data *pd) bfqg->rq_pos_tree =RB_ROOT ; } -static void bfq_pd_free (struct blkg_policy_data *pd) +static void bfqg_release (struct rcu_head *rcu) { +struct blkg_policy_data *pd = + container_of(rcu, struct blkg_policy_data, rcu_head);struct bfq_group *bfqg =pd_to_bfqg (pd);bfqg_stats_exit (&bfqg->stats);bfqg_put (bfqg); } +static void bfq_pd_free (struct blkg_policy_data *pd) +{ +call_rcu (&pd->rcu_head, bfqg_release); +} +static void bfq_pd_reset_stats (struct blkg_policy_data *pd) {struct bfq_group *bfqg =pd_to_bfqg (pd);
block/blk-cgroup.h +2 -0
@@ -140,6 +140,8 @@ struct blkg_policy_data {struct blkcg_gq *blkg;int plid;bool online; + +struct rcu_head rcu_head; };/*
block/blk-iocost.c +12 -2
@@ -3019,6 +3019,16 @@ static void ioc_pd_init(struct blkg_policy_data *pd)spin_unlock_irqrestore (&ioc->lock, flags); } +static void iocg_release (struct rcu_head *rcu) +{ +struct blkg_policy_data *pd = + container_of(rcu, struct blkg_policy_data, rcu_head); +struct ioc_gq *iocg =pd_to_iocg (pd); + +free_percpu (iocg->pcpu_stat); +kfree (iocg); +} +static void ioc_pd_free (struct blkg_policy_data *pd) {struct ioc_gq *iocg =pd_to_iocg (pd);
@@ -3043,8 +3053,8 @@ static void ioc_pd_free(struct blkg_policy_data *pd)hrtimer_cancel (&iocg->waitq_timer); } -free_percpu (iocg->pcpu_stat); -kfree (iocg); + +call_rcu (&pd->rcu_head, iocg_release); }static void ioc_pd_stat (struct blkg_policy_data *pd,struct seq_file *s)
block/blk-iolatency.c +9 -1
@@ -1031,13 +1031,21 @@ static void iolatency_pd_offline(struct blkg_policy_data *pd)iolatency_clear_scaling (blkg); } -static void iolatency_pd_free (struct blkg_policy_data *pd) +static void iolat_release (struct rcu_head *rcu) { +struct blkg_policy_data *pd = + container_of(rcu, struct blkg_policy_data, rcu_head);struct iolatency_grp *iolat =pd_to_lat (pd); +free_percpu (iolat->stats);kfree (iolat); } +static void iolatency_pd_free (struct blkg_policy_data *pd) +{ +call_rcu (&pd->rcu_head, iolat_release); +} +static struct cftype iolatency_files[] = { { .name ="latency" ,
block/blk-throttle.c +11 -2
@@ -327,16 +327,25 @@ static void throtl_pd_online(struct blkg_policy_data *pd)tg_update_has_rules (tg); } -static void throtl_pd_free (struct blkg_policy_data *pd) +static void tg_release (struct rcu_head *rcu) { +struct blkg_policy_data *pd = + container_of(rcu, struct blkg_policy_data, rcu_head);struct throtl_grp *tg =pd_to_tg (pd); -del_timer_sync (&tg->service_queue.pending_timer);blkg_rwstat_exit (&tg->stat_bytes);blkg_rwstat_exit (&tg->stat_ios);kfree (tg); } +static void throtl_pd_free (struct blkg_policy_data *pd) +{ +struct throtl_grp *tg =pd_to_tg (pd); + +del_timer_sync (&tg->service_queue.pending_timer); +call_rcu (&pd->rcu_head, tg_release); +} +static struct throtl_grp *throtl_rb_first (struct throtl_service_queue *parent_sq) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 628/869 blk-iocost: clear delay state when freeing policy data
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Usama Arif <[email protected]>
[ Upstream commit 97cb95d2148835ae86ff916b145aef332d40439d ]
iocg_kick_delay() turns sufficiently large debt into an explicit block-cgroup delay with blkcg_set_delay(), setting blkg->use_delay to -1 and incrementing blkcg->congestion_count. Clearing it again depends on iocg_kick_delay() running from the period timer, the waitq timer or the issue path.
ioc_pd_free() removes the iocg from active_iocgs and cancels its waitq timer, and no further bios can arrive, so once it has run nothing is left which can reduce the debt and clear the delay. The blkcg stays marked congested for the rest of its life.
blk_cgroup_congested() then returns true for every task in that cgroup and its descendants: page_cache_sync_ra() cuts readahead to a single page, page_cache_async_ra() skips it altogether, and __folio_throttle_swaprate() takes swap_avail_lock and schedules a throttle on anonymous folio allocation.
Clear it explicitly, after the list removal and the synchronous hrtimer_cancel() so that neither timer processing nor an I/O path can re-arm it. The free callback can also see policy data which was never attached to a blkg, hence the pd->blkg check.
--- block/blk-iocost.c | 7 +++++++ 1 file changed, 7 insertions(+)
block/blk-iocost.c +7 -0
@@ -3032,6 +3032,7 @@ static void iocg_release(struct rcu_head *rcu)static void ioc_pd_free (struct blkg_policy_data *pd) {struct ioc_gq *iocg =pd_to_iocg (pd); +struct blkcg_gq *blkg =pd_to_blkg (pd);struct ioc *ioc = iocg->ioc;unsigned long flags;
@@ -3054,6 +3055,12 @@ static void ioc_pd_free(struct blkg_policy_data *pd)hrtimer_cancel (&iocg->waitq_timer); } +/* off ->active_iocgs and timer gone, so nothing can re-arm the delay */ + iocg->delay =0 ; + iocg->indelay_since =0 ; +if (blkg) +blkcg_clear_delay (blkg); +call_rcu (&pd->rcu_head, iocg_release); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 629/869 blk-iolatency: clear delay state when freeing policy data
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Usama Arif <[email protected]>
[ Upstream commit 8935bf22c0a0db517a7f72f7097300e05dd852f5 ]
io.latency can throttle a group which has no latency target of its own. When a sibling misses its target, check_scale_change() scales down its peers, and a peer that reaches queue depth one gets blkcg_use_delay() called on it on every further scale-down, even with min_lat_nsec == 0.
iolatency_pd_offline() resets the target through iolatency_set_min_lat_nsec(), which clears the delay only on a nonzero to zero transition, so it never clears such a peer. Freeing the policy data then leaves blkg->use_delay set and blkcg->congestion_count elevated with nothing left that can drop it.
blk_cgroup_congested() then returns true for every task in that cgroup and its descendants for as long as the cgroup lives: page_cache_sync_ra() cuts readahead to a single page, page_cache_async_ra() skips it altogether, and __folio_throttle_swaprate() takes swap_avail_lock and schedules a throttle on anonymous folio allocation.
Clear the delay in iolatency_pd_free(). By then bio-held blkg references have drained, or the queue is frozen for policy deactivation, so check_scale_change() cannot re-arm it. The free callback can also see policy data which was never attached to a blkg, hence the pd->blkg check.
--- block/blk-iolatency.c | 9 +++++++++ 1 file changed, 9 insertions(+)
block/blk-iolatency.c +9 -0
@@ -1043,6 +1043,15 @@ static void iolat_release(struct rcu_head *rcu)static void iolatency_pd_free (struct blkg_policy_data *pd) { +struct blkcg_gq *blkg =pd_to_blkg (pd); + +/* +* Groups throttled as collateral have min_lat_nsec == 0, so +* iolatency_pd_offline() leaves their delay set. Drop it here, where +* no in-flight bio can re-arm it via check_scale_change(). +*/ +if (blkg) +blkcg_clear_delay (blkg);call_rcu (&pd->rcu_head, iolat_release); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 630/869 ocfs2: validate DIO orphan slot during inode read
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: ZhengYuan Huang <[email protected]>
[ Upstream commit bb88131c9831075b8dc08cdd375743e5d44c7ca2 ]
[BUG]
A corrupted append-DIO dinode (high byte at offset 0xa1 corrupted from 0 to 1) can carry an i_dio_orphaned_slot outside the mounted filesystem slot range and trigger a use-after-free error:
BUG: KASAN: slab-use-after-free in ocfs2_get_system_file_inode+0x780/0x820 fs/ocfs2/sysfile.c:102 Read of size 8 at addr ffff88800b767c00 by task kworker/u8:3/85 Call Trace: ... ocfs2_get_system_file_inode+0x780/0x820 fs/ocfs2/sysfile.c:102 ocfs2_wipe_inode+0x292/0xf70 fs/ocfs2/inode.c:840 ocfs2_delete_inode fs/ocfs2/inode.c:1155 [inline] ocfs2_evict_inode+0x6c9/0x1170 fs/ocfs2/inode.c:1295 evict+0x38e/0x8f0 fs/inode.c:810 iput_final fs/inode.c:1914 [inline] iput fs/inode.c:1966 [inline] iput+0x55b/0x8b0 fs/inode.c:1926 ocfs2_recover_orphans+0x610/0xe40 fs/ocfs2/journal.c:2374 ocfs2_complete_recovery+0x5af/0xd00 fs/ocfs2/journal.c:1373 ...
[CAUSE]ocfs2_del_inode_from_orphan() uses i_dio_orphaned_slot to index the slot-local system inode cache. The dinode validator does not check this active slot, so an out-of-range value produces an invalid cache entry pointer that is dereferenced as an inode pointer.
[FIX]
Reject an active i_dio_orphaned_slot outside the slot range during dinode validation, before DIO orphan recovery can consume it.
--- fs/ocfs2/inode.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ocfs2/inode.c +8 -0
@@ -1466,6 +1466,14 @@ int ocfs2_validate_inode_block(struct super_block *sb, goto bail; } +if ((le32_to_cpu (di->i_flags) &OCFS2_DIO_ORPHANED_FL ) && +le16_to_cpu (di->i_dio_orphaned_slot) >=OCFS2_SB (sb)->max_slots) { + rc =ocfs2_error (sb,"Invalid dinode %llu: DIO orphaned slot %u\n" , + (unsigned long long )bh->b_blocknr, +le16_to_cpu (di->i_dio_orphaned_slot)); + goto bail; + } +/* * Reject dinodes whose i_mode does not name one of the seven * canonical POSIX file types. ocfs2_populate_inode() copies
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 631/869 ocfs2: validate orphan slot during inode read
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: ZhengYuan Huang <[email protected]>
[ Upstream commit b2d31acbd3b182755b019183fb46949ba5e39b9f ]
Patch series "ocfs2: validate active orphan slots during inode read".
OCFS2 trusts active ordinary and append-DIO orphan slots read from dinodes. A corrupted slot can therefore index osb_orphan_wipes or the slot-local system-inode cache outside their allocations before the corruption is reported.
Patch 1 validates the ordinary orphan slot used by inode wipe processing. Patch 2 validates the append-DIO orphan slot used by DIO completion and orphan recovery. Both checks reject corrupt metadata at the existing inode validation boundary.
This patch (of 2):
[BUG]
A corrupted dinode with OCFS2_ORPHANED_FL can carry an i_orphaned_slot outside the mounted filesystem slot range. ocfs2_wipe_inode() uses it to index osb_orphan_wipes before looking up the orphan directory, causing an out-of-bounds memory access.
BUG: KASAN: slab-use-after-free in ocfs2_get_system_file_inode+0x780/0x820 fs/ocfs2/sysfile.c:102 Read of size 8 at addr ffff88800b767c00 by task kworker/u8:3/85 Call Trace: ... ocfs2_get_system_file_inode+0x780/0x820 fs/ocfs2/sysfile.c:102 ocfs2_wipe_inode+0x292/0xf70 fs/ocfs2/inode.c:840 ocfs2_delete_inode fs/ocfs2/inode.c:1155 [inline] ocfs2_evict_inode+0x6c9/0x1170 fs/ocfs2/inode.c:1295 evict+0x38e/0x8f0 fs/inode.c:810 iput_final fs/inode.c:1914 [inline] iput fs/inode.c:1966 [inline] iput+0x55b/0x8b0 fs/inode.c:1926 ocfs2_recover_orphans+0x610/0xe40 fs/ocfs2/journal.c:2374 ocfs2_complete_recovery+0x5af/0xd00 fs/ocfs2/journal.c:1373 ...
[CAUSE]ocfs2_validate_inode_block() validates i_suballoc_slot but leaves the active ordinary orphan slot unchecked. Downstream consumers assume that the value is smaller than osb->max_slots.
[FIX]
Reject an active i_orphaned_slot outside the slot range during dinode validation, before the inode reaches orphan wipe processing.
--- fs/ocfs2/inode.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/ocfs2/inode.c +8 -0
@@ -1474,6 +1474,14 @@ int ocfs2_validate_inode_block(struct super_block *sb, goto bail; } +if ((le32_to_cpu (di->i_flags) &OCFS2_ORPHANED_FL ) && +le16_to_cpu (di->i_orphaned_slot) >=OCFS2_SB (sb)->max_slots) { + rc =ocfs2_error (sb,"Invalid dinode %llu: orphaned slot %u\n" , + (unsigned long long )bh->b_blocknr, +le16_to_cpu (di->i_orphaned_slot)); + goto bail; + } +/* * Reject dinodes whose i_mode does not name one of the seven * canonical POSIX file types. ocfs2_populate_inode() copies
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 632/869 nvmet: fix max_qid race between configfs and controller allocation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Maurizio Lombardi <[email protected]>
[ Upstream commit f1a8846e06388113dfdbb89dee005083fa9afdf9 ]
The function nvmet_subsys_attr_qid_max_store() can race against nvmet_alloc_ctrl() when a subsystem's max_qid limit is modified.
Suppose max_qid is currently 64. If nvmet_alloc_ctrl() executes:ctrl->sqs = kzalloc_objs(struct nvmet_sq *, subsys->max_qid + 1); and at this exact point, a userspace process changes max_qid to 128, nvmet_subsys_attr_qid_max_store() will set the new max_qid value. It attempts to delete active controllers to force a reconnect, but the new controller won't be deleted because it hasn't been added to the subsys->ctrls list yet.
nvmet_alloc_ctrl() then proceeds and adds the new controller to the subsys->ctrls list. Later, when nvmet_install_queue() is called, it will see max_qid set to 128, but the memory allocated for sqs is only sized for 64 entries. This results in a KASAN out-of-bounds warning and potential memory corruptions.
Fix this by protecting the queue allocations and list insertion in nvmet_alloc_ctrl() with down_read(&nvmet_config_sem). Because nvmet_subsys_attr_qid_max_store() acquires down_write(&nvmet_config_sem) to modify the attribute, this safely prevents the configfs writer from modifying max_qid during controller creation.
Copy the max_qid from the subsystem to the controller's structure during the allocation; ctrl->max_qid never changes as long as the controller remains in LIVE state, so this will prevent similar race conditions.
--- drivers/nvme/target/admin-cmd.c | 8 +++--- drivers/nvme/target/core.c | 41 ++++++++++++++++++------------- drivers/nvme/target/fabrics-cmd.c | 2 +- drivers/nvme/target/nvmet.h | 6 +++++ 4 files changed, 35 insertions(+), 22 deletions(-)
drivers/nvme/target/admin-cmd.c +4 -4
@@ -828,7 +828,7 @@ u16 nvmet_set_feat_async_event(struct nvmet_req *req, u32 mask)void nvmet_execute_set_features (struct nvmet_req *req) { -struct nvmet_subsys *subsys =nvmet_req_subsys (req); +struct nvmet_ctrl *ctrl =nvmet_req_ctrl (req);u32 cdw10 =le32_to_cpu (req->cmd->common.cdw10);u32 cdw11 =le32_to_cpu (req->cmd->common.cdw11);u16 status =0 ;
@@ -847,7 +847,7 @@ void nvmet_execute_set_features(struct nvmet_req *req)break ; }nvmet_set_result (req, - (subsys->max_qid -1 ) | ((subsys->max_qid -1 ) <<16 )); + (ctrl->max_qid -1 ) | ((ctrl->max_qid -1 ) <<16 ));break ;case NVME_FEAT_KATO : status =nvmet_set_feat_kato (req);
@@ -902,7 +902,7 @@ void nvmet_get_feat_async_event(struct nvmet_req *req)void nvmet_execute_get_features (struct nvmet_req *req) { -struct nvmet_subsys *subsys =nvmet_req_subsys (req); +struct nvmet_ctrl *ctrl =nvmet_req_ctrl (req);u32 cdw10 =le32_to_cpu (req->cmd->common.cdw10);u16 status =0 ;
@@ -939,7 +939,7 @@ void nvmet_execute_get_features(struct nvmet_req *req)break ;case NVME_FEAT_NUM_QUEUES :nvmet_set_result (req, - (subsys->max_qid-1 ) | ((subsys->max_qid-1 ) <<16 )); + (ctrl->max_qid-1 ) | ((ctrl->max_qid-1 ) <<16 ));break ;case NVME_FEAT_KATO :nvmet_get_feat_kato (req);
drivers/nvme/target/core.c +24 -17
64 lines not on this page · raw message
drivers/nvme/target/fabrics-cmd.c +1 -1
@@ -350,7 +350,7 @@ static void nvmet_execute_io_connect(struct nvmet_req *req) goto out; } -if (unlikely (qid > ctrl->subsys->max_qid)) { +if (unlikely (qid > ctrl->max_qid)) {pr_warn ("invalid queue id (%d)\n" , qid); status =NVME_SC_CONNECT_INVALID_PARAM |NVME_STATUS_DNR ; req->cqe->result.u32 =IPO_IATTR_CONNECT_SQE (qid);
drivers/nvme/target/nvmet.h +6 -0
@@ -204,6 +204,7 @@ struct nvmet_ctrl {uuid_t hostid;u16 cntlid; +u16 max_qid;u32 kato;struct nvmet_port *port;
@@ -642,6 +643,11 @@ static inline struct nvmet_subsys *nvmet_req_subsys(struct nvmet_req *req)return req->sq->ctrl->subsys; } +static inline struct nvmet_ctrl *nvmet_req_ctrl (struct nvmet_req *req) +{ +return req->sq->ctrl; +} +static inline bool nvmet_is_disc_subsys (struct nvmet_subsys *subsys) {return subsys->type !=NVME_NQN_NVME ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 633/869 clocksource/drivers/samsung_pwm: Switch to raw_spinlock_t type
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marek Szyprowski <[email protected]>
[ Upstream commit 3b212f9d70805d91febae01d618868f4860e267c ]
Samsung PWM timer might be used as a clock source on some legacy systems. When PREEMPT_RT is enabled on ARM, regular spinlock is converted to a sleeping lock (mutex-based), which must not be used in atomic context such as hard interrupt handlers. Switch the samsung_pwm_lock to the raw_spinlock, which remains a true non-sleeping spinlock even under PREEMPT_RT.
--- drivers/clocksource/samsung_pwm_timer.c | 22 +++++++++++----------- drivers/pwm/pwm-samsung.c | 22 +++++++++++----------- include/clocksource/samsung_pwm.h | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-)
drivers/clocksource/samsung_pwm_timer.c +11 -11
@@ -56,7 +56,7 @@#define TCON_AUTORELOAD (chan) \ ((chan < 5) ? _TCON_AUTORELOAD(chan) : _TCON_AUTORELOAD4(chan)) -DEFINE_SPINLOCK (samsung_pwm_lock); +DEFINE_RAW_SPINLOCK (samsung_pwm_lock);EXPORT_SYMBOL (samsung_pwm_lock);struct samsung_pwm_clocksource {
@@ -87,14 +87,14 @@ static void samsung_timer_set_prescale(unsigned int channel, u16 prescale)if (channel >=2 ) shift =TCFG0_PRESCALER1_SHIFT ; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); reg =readl (pwm.base +REG_TCFG0 ); reg &= ~(TCFG0_PRESCALER_MASK << shift); reg |= (prescale -1 ) << shift;writel (reg, pwm.base +REG_TCFG0 ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); }static void samsung_timer_set_divisor (unsigned int channel,u8 divisor)
@@ -106,14 +106,14 @@ static void samsung_timer_set_divisor(unsigned int channel, u8 divisor) bits = (fls (divisor) -1 ) - pwm.variant.div_base; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); reg =readl (pwm.base +REG_TCFG1 ); reg &= ~(TCFG1_MUX_MASK << shift); reg |= bits << shift;writel (reg, pwm.base +REG_TCFG1 ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); }static void samsung_time_stop (unsigned int channel)
@@ -124,13 +124,13 @@ static void samsung_time_stop(unsigned int channel)if (channel >0 ) ++channel; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl_relaxed (pwm.base +REG_TCON ); tcon &= ~TCON_START (channel);writel_relaxed (tcon, pwm.base +REG_TCON ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); }static void samsung_time_setup (unsigned int channel,unsigned long tcnt)
@@ -142,7 +142,7 @@ static void samsung_time_setup(unsigned int channel, unsigned long tcnt)if (tcon_chan >0 ) ++tcon_chan; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl_relaxed (pwm.base +REG_TCON );
@@ -153,7 +153,7 @@ static void samsung_time_setup(unsigned int channel, unsigned long tcnt)writel_relaxed (tcnt, pwm.base +REG_TCMPB (channel));writel_relaxed (tcon, pwm.base +REG_TCON ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); }static void samsung_time_start (unsigned int channel,bool periodic)
@@ -164,7 +164,7 @@ static void samsung_time_start(unsigned int channel, bool periodic)if (channel >0 ) ++channel; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl_relaxed (pwm.base +REG_TCON );
@@ -178,7 +178,7 @@ static void samsung_time_start(unsigned int channel, bool periodic)writel_relaxed (tcon, pwm.base +REG_TCON ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); } static int samsung_set_next_event(unsigned long cycles,
drivers/pwm/pwm-samsung.c +11 -11
@@ -102,7 +102,7 @@ struct samsung_pwm_chip {* IP. Should this change, both drivers will need to be modified to * properly synchronize accesses to particular instances. */ -static DEFINE_SPINLOCK (samsung_pwm_lock); +static DEFINE_RAW_SPINLOCK (samsung_pwm_lock);#endif static inline
@@ -141,14 +141,14 @@ static void pwm_samsung_set_divisor(struct samsung_pwm_chip *our_chip, bits = (fls (divisor) -1 ) - our_chip->variant.div_base; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); reg =readl (our_chip->base +REG_TCFG1 ); reg &= ~(TCFG1_MUX_MASK << shift); reg |= bits << shift;writel (reg, our_chip->base +REG_TCFG1 ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); }static int pwm_samsung_is_tdiv (struct samsung_pwm_chip *our_chip,unsigned int chan)
@@ -249,7 +249,7 @@ static int pwm_samsung_enable(struct pwm_chip *chip, struct pwm_device *pwm)unsigned long flags;u32 tcon; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl (our_chip->base +REG_TCON );
@@ -263,7 +263,7 @@ static int pwm_samsung_enable(struct pwm_chip *chip, struct pwm_device *pwm) our_chip->disabled_mask &= ~BIT (pwm->hwpwm); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags);return 0 ; }
@@ -275,7 +275,7 @@ static void pwm_samsung_disable(struct pwm_chip *chip, struct pwm_device *pwm)unsigned long flags;u32 tcon; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl (our_chip->base +REG_TCON ); tcon &= ~TCON_AUTORELOAD (tcon_chan);
@@ -290,7 +290,7 @@ static void pwm_samsung_disable(struct pwm_chip *chip, struct pwm_device *pwm) our_chip->disabled_mask |=BIT (pwm->hwpwm); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); } static void pwm_samsung_manual_update(struct samsung_pwm_chip *our_chip,
@@ -298,11 +298,11 @@ static void pwm_samsung_manual_update(struct samsung_pwm_chip *our_chip, {unsigned long flags; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags);__pwm_samsung_manual_update (our_chip, pwm); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); } static int __pwm_samsung_config(struct pwm_chip *chip, struct pwm_device *pwm,
@@ -390,7 +390,7 @@ static void pwm_samsung_set_invert(struct samsung_pwm_chip *our_chip,unsigned long flags;u32 tcon; -spin_lock_irqsave (&samsung_pwm_lock, flags); +raw_spin_lock_irqsave (&samsung_pwm_lock, flags); tcon =readl (our_chip->base +REG_TCON );
@@ -404,7 +404,7 @@ static void pwm_samsung_set_invert(struct samsung_pwm_chip *our_chip,writel (tcon, our_chip->base +REG_TCON ); -spin_unlock_irqrestore (&samsung_pwm_lock, flags); +raw_spin_unlock_irqrestore (&samsung_pwm_lock, flags); } static int pwm_samsung_set_polarity(struct pwm_chip *chip,
include/clocksource/samsung_pwm.h +1 -1
@@ -15,7 +15,7 @@* spinlock is not shared between both drivers. */ #ifdef CONFIG_CLKSRC_SAMSUNG_PWM -extern spinlock_t samsung_pwm_lock; +extern raw_spinlock_t samsung_pwm_lock;#endif struct samsung_pwm_variant {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 634/869 bpf, s390: Clear fetch destination on faulting arena atomic
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniel Borkmann <[email protected]>
[ Upstream commit cc3e12330599f097f0e1f792435686ddc276f26d ]
Same missing register clear as on riscv64. A RMW atomic on an arena pointer is converted to BPF_PROBE_ATOMIC and gets an exception table entry, but bpf_jit_probe_atomic_pre() only fills in the arena base and the probe offset, leaving probe->reg at the -1 that bpf_jit_probe_init() set, which bpf_jit_probe_post() writes into the entry and ex_handler_bpf() then reads back as "there is nothing to clear".
That is right for a plain BPF_{ADD,AND,OR,XOR}, which only writes memory, but an RMW carrying BPF_FETCH also reads the old value into a register:src_reg for BPF_{ADD,AND,OR,XOR} | BPF_FETCH and BPF_XCHG, and r0 for BPF_CMPXCHG. So on a fault over an unmapped arena page the program resumes at the landing pad with whatever that register held before the atomic instead of the 0 that every other BPF_PROBE_* access delivers.
Fill probe->reg in from bpf_atomic_load_reg(). Unlike x86-64 and arm64, s390x does not report arena violations from its exception handler, so there is no access direction to correct here, only the missing register clear.
--- arch/s390/net/bpf_jit_comp.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
arch/s390/net/bpf_jit_comp.c +11 -0
@@ -782,6 +782,8 @@ static void bpf_jit_probe_atomic_pre(struct bpf_jit *jit,struct bpf_insn *insn, struct bpf_jit_probe *probe) { + int load_reg; +if (BPF_MODE (insn->code) !=BPF_PROBE_ATOMIC )return ;
@@ -791,6 +793,14 @@ static void bpf_jit_probe_atomic_pre(struct bpf_jit *jit,EMIT4 (0xb9080000 ,REG_W1 , insn->dst_reg); probe->arena_reg =REG_W1 ; probe->prg = jit->prg; +/* +* A read-modify-write carrying BPF_FETCH reads the old value into +* src_reg, or into r0 for a BPF_CMPXCHG. Clear that register on +* fault, the remaining atomics only write memory. +*/ + load_reg =bpf_atomic_load_reg (insn); +if (load_reg >=0 ) + probe->reg = reg2hex[load_reg]; } static int bpf_jit_probe_post(struct bpf_jit *jit, struct bpf_prog *fp,
@@ -1653,6 +1663,7 @@ static noinline int bpf_jit_insn(struct bpf_jit *jit, struct bpf_prog *fp,if (load_probe.prg !=-1 ) { probe.prg = jit->prg; probe.arena_reg = load_probe.arena_reg; + probe.reg = load_probe.reg; } loop_start = jit->prg;/* 0: {csy|csg} %w0,%src,off(%arena) */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 635/869 bpf: Compare iterator types during state pruning
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ning Ding <[email protected]>
[ Upstream commit 83608e303b95d07afba1c15da0b5d9e513c2f15a ]
An iterator stack slot can be MEM_RCU or PTR_UNTRUSTED. These states must not be equal, or the verifier can prune an unsafe path.
Compare the pointer type for STACK_ITER slots.
--- kernel/bpf/verifier.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +2 -1
@@ -18053,7 +18053,8 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,* infinite loop check triggering, see * iter_active_depths_differ() */ - if (old_reg->iter.btf != cur_reg->iter.btf || + if (old_reg->type != cur_reg->type || + old_reg->iter.btf != cur_reg->iter.btf || old_reg->iter.btf_id != cur_reg->iter.btf_id || old_reg->iter.state != cur_reg->iter.state ||/* ignore {old_reg,cur_reg}->iter.depth, see above */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 636/869 apparmor: fix unconfined user namespace restriction forced stack
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: John Johansen <[email protected]>
[ Upstream commit 08c2f7c8d4b1434cfae006f3daf4d1bce330b57b ]
If a task is already confined by a stack the unprivileged transition restriction on unconfined is not correctly, applied. This results in an escape if two transitions through an unconfined profile can be executed.
Fix this by pushing the check into the per profile label build. The check will always be done against unconfined and result in a stack of just the unconfined component when necessary.
--- security/apparmor/domain.c | 80 +++++++++++++++++++++++++------------- 1 file changed, 54 insertions(+), 26 deletions(-)
security/apparmor/domain.c +54 -26
@@ -812,6 +812,52 @@ static int profile_onexec(const struct cred *subj_cred,/* ensure none ns domain transitions are correctly applied with onexec */ +static bool is_profile_priv_restricted_to_stack (const struct cred *subj_cred, +struct aa_profile *profile) +{ +if (profile_unconfined (profile) && profile == profile->ns->unconfined && + aa_unprivileged_unconfined_restricted && +/* cap_capable returns false (0) if true, hence true here means +* doesn't have capability and the stack will be restricted +*/ +cap_capable (current_cred (), &init_user_ns,CAP_MAC_OVERRIDE , +CAP_OPT_NOAUDIT )) +return true; +return false; +} + +static const char *stack_msg ="change_profile unprivileged unconfined converted to stacking" ; + +static struct aa_label *priv_restricted_transition (const struct cred *subj_cred, +struct aa_profile *profile, +const char *op,u32 request, +const char *name, +struct aa_label *transition, +gfp_t gfp) +{ +if (!is_profile_priv_restricted_to_stack (subj_cred, profile)) +return aa_get_newest_label (transition); + +/* transition allowed but only via stack */ +struct aa_label *target =aa_label_merge (&profile->label, + transition, gfp); +if (!target) +return ERR_PTR (-ENOMEM ); + +/* doing this here is less than optimal but good enough until the +* fs mediation rework lands +*/ +struct aa_perms perms = { + .allow = request, + .audit = request, + }; +aa_audit_file (subj_cred, profile, &perms, op, + request, name,NULL , target, + subj_cred->euid, stack_msg,0 ); + +return target; +} + static struct aa_label *handle_onexec(const struct cred *subj_cred, struct aa_label *label, struct aa_label *onexec, bool stack,
@@ -835,7 +881,10 @@ static struct aa_label *handle_onexec(const struct cred *subj_cred,if (error)return ERR_PTR (error); new =fn_label_build_in_ns (label, profile,GFP_KERNEL , -aa_get_newest_label (onexec), +priv_restricted_transition (subj_cred, profile, +OP_CHANGE_ONEXEC ,AA_MAY_ONEXEC , + bprm->filename, onexec, +GFP_KERNEL ),profile_transition (subj_cred, profile, bprm, buffer, cond, unsafe));
@@ -1354,8 +1403,6 @@ static int change_profile_perms_wrapper(const char *op, const char *name,return error; } -static const char *stack_msg ="change_profile unprivileged unconfined converted to stacking" ; -/** * aa_change_profile - perform a one-way profile transition * @fqname: name of profile may include namespace (NOT NULL)
@@ -1415,28 +1462,6 @@ int aa_change_profile(const char *fqname, int flags) op =OP_CHANGE_PROFILE ; } -/* This should move to a per profile test. Requires pushing build -* into callback -*/ -if (!stack &&unconfined (label) && - label == &labels_ns (label)->unconfined->label && - aa_unprivileged_unconfined_restricted && -/* TODO: refactor so this check is a fn */ -cap_capable (current_cred (), &init_user_ns,CAP_MAC_OVERRIDE , -CAP_OPT_NOAUDIT )) { -/* regardless of the request in this case apparmor -* stacks against unconfined so admin set policy can't be -* by-passed -*/ - stack = true; - perms.audit = request; - (void )fn_for_each_in_ns (label, profile, -aa_audit_file (subj_cred, profile, &perms, op, - request, auditname,NULL , target, -GLOBAL_ROOT_UID , stack_msg,0 )); - perms.audit =0 ; - } -if (*fqname =='&' ) { stack = true;/* don't have label_parse() do stacking */
@@ -1507,7 +1532,10 @@ int aa_change_profile(const char *fqname, int flags)/* stacking is always a subset, so only check the nonstack case */ if (!stack) { new =fn_label_build_in_ns (label, profile,GFP_KERNEL , -aa_get_label (target), +priv_restricted_transition (subj_cred, profile, + op, request, + auditname, target, +GFP_KERNEL ),aa_get_label (&profile->label));if (IS_ERR_OR_NULL (new)) goto build_fail;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 637/869 amt: Dont support cross-netns setup.
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kuniyuki Iwashima <[email protected]>
[ Upstream commit e99ecc3046ea5f5c6b5e1f8b4ef854c6c6998e06 ]
When a lower device is unregistered, amt_device_event() tries to unregister its upper AMT device, but it has two problems.
1. amt_lookup_upper_dev() looks up an upper device in the lower device's netns only
2. amt_device_event() unregisters a single upper device only
If AMT device is created on a lower device in another netns, removing the lower device triggers the splat below and gets stuck until all upper devices are removed. [0]
The cross-netns setup seems unintentional considering 1. and the following points:
* amt_link_setup() sets dev->netns_immutable to true
* skb_scrub_packet() is not called in the fast path
* iproute2 binary fails to find cross-netns lower device via link-netns:
# ip -n ns1 link add amt0 link-netns ns2 type amt dev veth1 Cannot find device "veth1"
Instead of supporting it properly and preparing for per-netns netdev unreg, let's forbid cross-netns setup.
Note that the problem 2. needs a separate fix.
[0]:
WARNING: net/core/dev.c:12518 at unregister_netdevice_many_notify+0x1cce/0x2250, CPU#48: ip/2031
Modules linked in:
CPU: 48 UID: 0 PID: 2031 Comm: ip Not tainted 7.2.0-rc5+ #27 PREEMPT(full)
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
RIP: 0010:unregister_netdevice_many_notify (net/core/dev.c:12518)
Code: 89 ef e8 d5 52 ae fe e9 d0 f4 ff ff 48 8d 3d f9 3b 9c 02 48 c7 c6 c0 0b 63 84 ba ab 1f 00 00 67 48 0f b9 3a e9 65 ff ff ff 90 <0f> 0b 90 eb 81 48 8d 3d f6 3b 9c 02 48 c7 c6 c0 0b 63 84 ba e2 1f
RSP: 0018:ffffc90004abf160 EFLAGS: 00010212
RAX: ffff888104d38260 RBX: ffff88800b0911b8 RCX: dffffc0000000000
RDX: 0000000000000000 RSI: 0000000000000008 RDI: ffffffff85b9f880
RBP: ffffc90004abf2d0 R08: ffffffff85b9f887 R09: 1ffffffff0b73f10
R10: dffffc0000000000 R11: fffffbfff0b73f11 R12: ffff88800b091d08
R13: ffff88800b091178 R14: dffffc0000000000 R15: ffff88800b091000
FS: 00007f555b86c600(0000) GS:ffff8881942a0000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000562107d489c0 CR3: 0000000109a40002 CR4: 0000000000372ef0
Call Trace:
<TASK>
rtnl_dellink (net/core/rtnetlink.c:3632 net/core/rtnetlink.c:3674)
rtnetlink_rcv_msg (net/core/rtnetlink.c:7112)
netlink_rcv_skb (net/netlink/af_netlink.c:2556)
netlink_unicast (net/netlink/af_netlink.c:1319)
netlink_sendmsg (net/netlink/af_netlink.c:1900)
____sys_sendmsg (net/socket.c:775)
__sys_sendmsg (net/socket.c:2738)
do_syscall_64 (arch/x86/entry/syscall_64.c:63)
entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121)
...
unregister_netdevice: waiting for veth0 to become free. Usage count = 7
ref_tracker: netdev@ffff88800d7496d8 has 3/3 users at
__netdev_adjacent_dev_insert (./include/linux/netdevice.h:4525 ./include/linux/netdevice.h:4554 net/core/dev.c:8791)
__netdev_upper_dev_link (net/core/dev.c:8879 net/core/dev.c:8963)
netdev_upper_dev_link (net/core/dev.c:9009)
amt_newlink (drivers/net/amt.c:3321)--- drivers/net/amt.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/net/amt.c +3 -0
@@ -3195,6 +3195,9 @@ static int amt_newlink(struct net *net, struct net_device *dev,struct amt_dev *amt =netdev_priv (dev);int err = -EINVAL ; +if (!net_eq (net,dev_net (dev))) +return err; + amt->net = net; amt->mode =nla_get_u32 (data[IFLA_AMT_MODE ]);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 638/869 NFS: Return a delegation the client fails to record
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
[ Upstream commit 220af23d863995091f0edeb1e6aa0945b3db8b37 ]
When an NFS server grants a delegation in an OPEN reply, nfs_inode_set_delegation() records it on the client. However, three of its error flows return without sending DELEGRETURN.
A delegation can be relinquished only by DELEGRETURN (RFC 8881 Section 20.2.4), so dropping one silently leaves the server believing the client still holds it. If the server happens to recall that delegation, the client answers CB_RECALL with NFS4ERR_BADHANDLE because it has no record of the stateid. The server revokes the delegation and moves it onto its cl_revoked list, because the client never sends the FREE_STATEID that would drain it. Every subsequent SEQUENCE reply then carries SEQ4_STATUS_RECALLABLE_STATE_REVOKED, and the client's state manager loops issuing TEST_STATEID across its delegations without ever clearing the condition.
The window is easy to reach now that a server offers a write delegation on any write OPEN: a delegation recalled for one opener races a re-open that the server answers with a fresh write delegation.
Instead of dropping it, hand the delegation back during these error flows.
--- fs/nfs/delegation.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)
fs/nfs/delegation.c +14 -4
@@ -455,11 +455,14 @@ int nfs_inode_set_delegation(struct inode *inode, const struct cred *cred,struct nfs_inode *nfsi =NFS_I (inode);struct nfs_delegation *delegation, *old_delegation;struct nfs_delegation *freeme =NULL ; +bool orphaned = false;int status =0 ; delegation =kmalloc (sizeof (*delegation),GFP_KERNEL_ACCOUNT ); -if (delegation ==NULL ) +if (delegation ==NULL ) { +nfs4_proc_delegreturn (inode, cred, stateid,NULL ,0 );return -ENOMEM ; + }nfs4_stateid_copy (&delegation->stateid, stateid);refcount_set (&delegation->refcount,1 ); delegation->type = type;
@@ -507,12 +510,16 @@ int nfs_inode_set_delegation(struct inode *inode, const struct cred *cred, goto out; }if (test_and_set_bit (NFS_DELEGATION_RETURNING , - &old_delegation->flags)) + &old_delegation->flags)) { + orphaned = true; goto out; + } } freeme =nfs_detach_delegation_locked (nfsi, old_delegation, clp); -if (freeme ==NULL ) +if (freeme ==NULL ) { + orphaned = true; goto out; + } add_new:/* * If we didn't revalidate the change attribute before setting
@@ -544,8 +551,11 @@ int nfs_inode_set_delegation(struct inode *inode, const struct cred *cred,nfs_update_delegated_mtime (inode); out:spin_unlock (&clp->cl_lock); -if (delegation !=NULL ) +if (delegation !=NULL ) { +if (orphaned) +nfs_do_return_delegation (inode, delegation,0 );__nfs_free_delegation (delegation); + }if (freeme !=NULL ) {nfs_do_return_delegation (inode, freeme,0 );nfs_free_delegation (freeme);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 639/869 iommu/vt-d: Flush context cache with correct SID when tearing down aliases
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lu Baolu <[email protected]>
[ Upstream commit c54e4ae971b98e8d650400137d332cee56c03f55 ]
domain_context_clear_one() and device_pasid_table_teardown() are both invoked once per DMA alias of a device. Each function locates the context entry using the bus/devfn pair provided by the pci_for_each_dma_alias() callback, then calls intel_context_flush_no_pasid(), which constructs a device-selective context-cache invalidation from info->bus and info->devfn (that is, always the requester ID of the device itself).
As a result, for every alias other than the device’s own RID, the context entry that was just cleared in memory is never invalidated in the context cache. Hardware may continue using that stale cached entry. In the scalable-mode teardown path, intel_pasid_free_table() can then free the PASID directory still referenced by that stale entry, allowing the IOMMU to walk freed memory.
Fix this by passing the source ID of the entry being torn down to intel_context_flush_no_pasid(), instead of deriving it from @info.
--- drivers/iommu/intel/iommu.c | 4 ++-- drivers/iommu/intel/iommu.h | 2 +- drivers/iommu/intel/pasid.c | 9 ++++++--- 3 files changed, 9 insertions(+), 6 deletions(-)
drivers/iommu/intel/iommu.c +2 -2
@@ -1921,7 +1921,7 @@ static void domain_context_clear_one(struct device_domain_info *info, u8 bus, u8context_clear_present (context);__iommu_flush_cache (iommu, context,sizeof (*context));spin_unlock (&iommu->lock); -intel_context_flush_no_pasid (info, context, did); +intel_context_flush_no_pasid (info, context, did,PCI_DEVID (bus, devfn));context_clear_entry (context);__iommu_flush_cache (iommu, context,sizeof (*context)); }
@@ -4164,7 +4164,7 @@ static int context_flip_pri(struct device_domain_info *info, bool enable)if (!ecap_coherent (iommu->ecap))clflush_cache_range (context,sizeof (*context)); -intel_context_flush_no_pasid (info, context, did); +intel_context_flush_no_pasid (info, context, did,PCI_DEVID (bus, devfn));spin_unlock (&iommu->lock);return 0 ;
drivers/iommu/intel/iommu.h +1 -1
@@ -1297,7 +1297,7 @@ void cache_tag_flush_range_np(struct dmar_domain *domain, unsigned long start, unsigned long end);void intel_context_flush_no_pasid (struct device_domain_info *info, -struct context_entry *context,u16 did); +struct context_entry *context,u16 did,u16 sid);int intel_iommu_enable_prq (struct intel_iommu *iommu);int intel_iommu_finish_prq (struct intel_iommu *iommu);
drivers/iommu/intel/pasid.c +6 -3
@@ -717,7 +717,7 @@ static void device_pasid_table_teardown(struct device *dev, u8 bus, u8 devfn)context_clear_present (context);__iommu_flush_cache (iommu, context,sizeof (*context));spin_unlock (&iommu->lock); -intel_context_flush_no_pasid (info, context, did); +intel_context_flush_no_pasid (info, context, did,PCI_DEVID (bus, devfn));context_clear_entry (context);__iommu_flush_cache (iommu, context,sizeof (*context)); }
@@ -919,9 +919,12 @@ static void __context_flush_dev_iotlb(struct device_domain_info *info)* This helper can only be used when IOMMU is working in the legacy mode or * IOMMU is in scalable mode but all PASID table entries of the device are * non-present. +* +* @sid identifies the context entry that was modified, which may be a DMA +* alias of @info->dev rather than its own requester ID. */ void intel_context_flush_no_pasid (struct device_domain_info *info, -struct context_entry *context,u16 did) +struct context_entry *context,u16 did,u16 sid) {struct intel_iommu *iommu = info->iommu;
@@ -931,7 +934,7 @@ void intel_context_flush_no_pasid(struct device_domain_info *info,* when operating in scalable mode. Therefore the @did value doesn't * matter in scalable mode. */ - iommu->flush.flush_context (iommu, did,PCI_DEVID (info->bus, info->devfn), + iommu->flush.flush_context (iommu, did, sid,DMA_CCMD_MASK_NOBIT ,DMA_CCMD_DEVICE_INVL );/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 640/869 bpf: Fix mmap_lock leak in irq_work path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sanghyun Park <[email protected]>
[ Upstream commit fa9dcacdcdf487f0ffef64bf67622f1caed509f1 ]
stack_map_get_build_id_offset() introduced a per-CPU irq_work to defer mmap_read_unlock() from NMI context, and bpf_find_vma() later reused the same mmap_unlock_work. Both callers only check whether the work is busy before taking mmap_lock, so a nested caller can reuse the slot before the first caller queues it. Two read locks may then be acquired while only one deferred unlock runs, leaking a read lock and blocking exit_mmap().
Reserve the per-CPU slot before mmap_read_trylock(). Use the same wrapper in stackmap and bpf_find_vma() so both callers release the reservation on trylock failure. Keep rejecting the slot while the irq_work remains busy. Release it after the irq_work callback unlocks the mm.
--- kernel/bpf/mmap_unlock_work.h | 51 ++++++++++++++++++++--------------- kernel/bpf/stackmap.c | 33 +++++++++++++---------- kernel/bpf/task_iter.c | 14 +++++++--- 3 files changed, 58 insertions(+), 40 deletions(-)
kernel/bpf/mmap_unlock_work.h +29 -22
@@ -4,12 +4,15 @@#ifndef __MMAP_UNLOCK_WORK_H__#define __MMAP_UNLOCK_WORK_H__ +#include <linux/atomic.h> +#include <linux/err.h> #include <linux/irq_work.h> /* irq_work to run mmap_read_unlock() in irq_work */ struct mmap_unlock_irq_work {struct irq_work irq_work;struct mm_struct *mm; +atomic_t active; }; DECLARE_PER_CPU(struct mmap_unlock_irq_work, mmap_unlock_work);
@@ -18,32 +21,36 @@ DECLARE_PER_CPU(struct mmap_unlock_irq_work, mmap_unlock_work);* We cannot do mmap_read_unlock() when the irq is disabled, because of * risk to deadlock with rq_lock. To look up vma when the irqs are * disabled, we need to run mmap_read_unlock() in irq_work. We use a -* percpu variable to do the irq_work. If the irq_work is already used -* by another lookup, we fall over. +* percpu variable to do the irq_work. The active flag reserves the slot +* before mmap_read_trylock() and until the irq_work callback consumes mm. */ -static inline bool bpf_mmap_unlock_get_irq_work (struct mmap_unlock_irq_work **work_ptr) +static inline struct mmap_unlock_irq_work *bpf_mmap_unlock_guard_get (void ) { -struct mmap_unlock_irq_work *work =NULL ; -bool irq_work_busy = false; +struct mmap_unlock_irq_work *work; -if (irqs_disabled ()) { -if (!IS_ENABLED (CONFIG_PREEMPT_RT )) { - work =this_cpu_ptr (&mmap_unlock_work); -if (irq_work_is_busy (&work->irq_work)) { -/* cannot queue more up_read, fallback */ - irq_work_busy = true; - } - }else { -/* -* PREEMPT_RT does not allow to trylock mmap sem in -* interrupt disabled context. Force the fallback code. -*/ - irq_work_busy = true; - } - } +if (!irqs_disabled ()) +return NULL ; + +/* +* PREEMPT_RT does not allow to trylock mmap sem in interrupt +* disabled context. Force the fallback code. +*/ +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +return ERR_PTR (-EBUSY ); + + work =this_cpu_ptr (&mmap_unlock_work); +if (irq_work_is_busy (&work->irq_work) || +atomic_cmpxchg_acquire (&work->active,0 ,1 )) +return ERR_PTR (-EBUSY ); - *work_ptr = work; -return irq_work_busy; +return work; +} + +static inline void +bpf_mmap_unlock_guard_put (struct mmap_unlock_irq_work *work) +{ +if (work) +atomic_set_release (&work->active,0 ); }static inline void bpf_mmap_unlock_mm (struct mmap_unlock_irq_work *work,struct mm_struct *mm)
kernel/bpf/stackmap.c +19 -14
@@ -166,23 +166,20 @@ static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs, u32 trace_nr, bool user, bool may_fault) { int i; -struct mmap_unlock_irq_work *work =NULL ; -bool irq_work_busy =bpf_mmap_unlock_get_irq_work (&work); +struct mmap_unlock_irq_work *work;struct vm_area_struct *vma, *prev_vma =NULL ;const char *prev_build_id; -/* If the irq_work is in use, fall back to report ips. Same -* fallback is used for kernel stack (!user) on a stackmap with -* build_id. -*/ -if (!user || !current || !current->mm || irq_work_busy || - !mmap_read_trylock (current->mm)) { -/* cannot access current->mm, fall back to ips */ -for (i =0 ; i < trace_nr; i++) { - id_offs[i].status =BPF_STACK_BUILD_ID_IP ; -memset (id_offs[i].build_id,0 ,BUILD_ID_SIZE_MAX ); - } -return ; +if (!user || !current || !current->mm) + goto fallback; + + work =bpf_mmap_unlock_guard_get (); +if (IS_ERR (work)) + goto fallback; + +if (!mmap_read_trylock (current->mm)) { +bpf_mmap_unlock_guard_put (work); + goto fallback; }for (i =0 ; i < trace_nr; i++) {
@@ -207,6 +204,14 @@ static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs, prev_build_id = id_offs[i].build_id; }bpf_mmap_unlock_mm (work, current->mm); +return ; + +fallback: +/* cannot access current->mm, fall back to ips */ +for (i =0 ; i < trace_nr; i++) { + id_offs[i].status =BPF_STACK_BUILD_ID_IP ; +memset (id_offs[i].build_id,0 ,BUILD_ID_SIZE_MAX ); + } } static struct perf_callchain_entry *
kernel/bpf/task_iter.c +10 -4
@@ -757,9 +757,8 @@ static struct bpf_iter_reg task_vma_reg_info = { BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start, bpf_callback_t, callback_fn, void *, callback_ctx, u64, flags) { -struct mmap_unlock_irq_work *work =NULL ; +struct mmap_unlock_irq_work *work;struct vm_area_struct *vma; -bool irq_work_busy = false;bool __maybe_unused mmput_needed = false;struct mm_struct *mm;int ret = -ENOENT ;
@@ -796,9 +795,14 @@ BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start,if (!mm)return -ENOENT ; - irq_work_busy =bpf_mmap_unlock_get_irq_work (&work); + work =bpf_mmap_unlock_guard_get (); +if (IS_ERR (work)) { + ret =PTR_ERR (work); + goto out; + } -if (irq_work_busy || !mmap_read_trylock (mm)) { +if (!mmap_read_trylock (mm)) { +bpf_mmap_unlock_guard_put (work); ret = -EBUSY ; goto out; }
@@ -1195,6 +1199,8 @@ static void do_mmap_read_unlock(struct irq_work *entry) work = container_of(entry, struct mmap_unlock_irq_work, irq_work);mmap_read_unlock_non_owner (work->mm); + work->mm =NULL ; +bpf_mmap_unlock_guard_put (work); }static int __init task_iter_init (void )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 641/869 Bluetooth: ISO: fix race of kfree vs kref_get_unless_zero
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pauli Virtanen <[email protected]>
[ Upstream commit af24e338bf5dafb80f42baa9a0b9e9b57b1c5d9c ]
hci_conn::iso_data is accessed and modified without lock or RCU. This leads to a race
[Task hdev->workqueue] [Task 2]
iso_recv iso_conn_put(conn)
conn = LOAD hcon->iso_data iso_conn_free(conn)
iso_conn_hold_unless_zero(conn) hcon->iso_data = NULL
kfree(conn)
kref_get_unless_zero(&conn->ref) /* UAF */and also to races in iso_conn_add() vs. iso_conn_free().
Fix by adding spinlock hci_conn::proto_lock and using it to guard hci_conn::iso_data.
Stable-dep-of: 2b66c83ff175 ("Bluetooth: L2CAP: use proto_lock for l2cap_data to fix l2cap_disconn_ind")
--- include/net/bluetooth/hci_core.h | 2 ++ net/bluetooth/hci_conn.c | 2 ++ 2 files changed, 4 insertions(+)
include/net/bluetooth/hci_core.h +2 -0
@@ -751,6 +751,8 @@ struct hci_conn {struct dentry *debugfs;struct hci_dev *hdev; + +spinlock_t proto_lock;/* lock guarding protocol data */ void *l2cap_data;void *sco_data;void *iso_data;
net/bluetooth/hci_conn.c +2 -0
@@ -1052,6 +1052,8 @@ static struct hci_conn *__hci_conn_add(struct hci_dev *hdev, int type, bdaddr_tINIT_DELAYED_WORK (&conn->idle_work, hci_conn_idle);INIT_DELAYED_WORK (&conn->le_conn_timeout, le_conn_timeout); +spin_lock_init (&conn->proto_lock); +atomic_set (&conn->refcnt,0 );hci_dev_hold (hdev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 642/869 Bluetooth: L2CAP: use proto_lock for l2cap_data to fix l2cap_disconn_ind
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pauli Virtanen <[email protected]>
[ Upstream commit 2b66c83ff1751d6bd3201b3017206262ab46dc05 ]
hci_conn::l2cap_data is accessed without locks in l2cap_disconn_ind via hci_conn_timeout (disc_work) -> hci_proto_disconn_ind -> l2cap_disconn_ind. This is UAF if the l2cap_conn is deleted concurrently.
disc_work is disabled sync in hci_conn_del(), so we cannot take hci_dev_lock in disc_work.
Fix by using proto_lock to guard l2cap_data, in addition to hdev->lock which is held in other access paths.
--- net/bluetooth/l2cap_core.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
net/bluetooth/l2cap_core.c +17 -6
@@ -1843,7 +1843,10 @@ static void l2cap_conn_del(struct hci_conn *hcon, int err)hci_chan_del (conn->hchan); conn->hchan =NULL ; +spin_lock (&hcon->proto_lock); hcon->l2cap_data =NULL ; +spin_unlock (&hcon->proto_lock); +mutex_unlock (&conn->lock);l2cap_conn_put (conn); }
@@ -7167,8 +7170,6 @@ static struct l2cap_conn *l2cap_conn_add(struct hci_conn *hcon) }kref_init (&conn->ref); - hcon->l2cap_data = conn; - conn->hcon =hci_conn_get (hcon); conn->hchan = hchan;BT_DBG ("hcon %p conn %p hchan %p" , hcon, conn, hchan);
@@ -7197,6 +7198,11 @@ static struct l2cap_conn *l2cap_conn_add(struct hci_conn *hcon) conn->disc_reason =HCI_ERROR_REMOTE_USER_TERM ; +spin_lock (&hcon->proto_lock); + conn->hcon =hci_conn_get (hcon); + hcon->l2cap_data = conn; +spin_unlock (&hcon->proto_lock); +return conn; }
@@ -7585,13 +7591,18 @@ static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status)int l2cap_disconn_ind (struct hci_conn *hcon) { -struct l2cap_conn *conn = hcon->l2cap_data; +struct l2cap_conn *conn; +int ret =HCI_ERROR_REMOTE_USER_TERM ;BT_DBG ("hcon %p" , hcon); -if (!conn) -return HCI_ERROR_REMOTE_USER_TERM ; -return conn->disc_reason; +spin_lock (&hcon->proto_lock); + conn = hcon->l2cap_data; +if (conn) + ret = conn->disc_reason; +spin_unlock (&hcon->proto_lock); + +return ret; }static void l2cap_disconn_cfm (struct hci_conn *hcon,u8 reason)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 643/869 btrfs: qgroup: fix a wrong length calculation in qgroup_free_reserved_data()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qu Wenruo <[email protected]>
[ Upstream commit 9102b179512e11644fb0489ae62010a09afa199c ]
In that function, we round down the start position and round up the ending position.
But during the calculation of @len, we use "round_up(start + len, sectorsize)", which is the rounded up end position, not the rounded up length.
Which results a much larger length, and later we are still using "start + len", which is completely incorrect.
Fix it by declaring a local @aligned_start and @aligned_len and use them instead.
--- fs/btrfs/qgroup.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
fs/btrfs/qgroup.c +11 -7
@@ -4371,12 +4371,13 @@ static int qgroup_free_reserved_data(struct btrfs_inode *inode,struct ulist_node *unode;struct ulist_iterator uiter;struct extent_changeset changeset; +const u32 sectorsize = root->fs_info->sectorsize; +const u64 aligned_start =round_down (start, sectorsize); +const u64 aligned_len =round_up (start + len, sectorsize) - aligned_start;u64 freed =0 ;int ret;extent_changeset_init (&changeset); - len =round_up (start + len, root->fs_info->sectorsize); - start =round_down (start, root->fs_info->sectorsize);ULIST_ITER_INIT (&uiter);while ((unode =ulist_next (&reserved->range_changed, &uiter))) {
@@ -4388,12 +4389,15 @@ static int qgroup_free_reserved_data(struct btrfs_inode *inode,extent_changeset_release (&changeset); -/* Only free range in range [start, start + len) */ -if (range_start >= start + len || - range_start + range_len <= start) +/* +* Only free the range within +* [aligned_start, aligned_start + aligned_len). +*/ +if (range_start >= aligned_start + aligned_len || + range_start + range_len <= aligned_start)continue ; - free_start =max (range_start, start); - free_len =min (start + len, range_start + range_len) - + free_start =max (range_start, aligned_start); + free_len =min (aligned_start + aligned_len, range_start + range_len) - free_start;/* * TODO: To also modify reserved->ranges_reserved to reflect
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 644/869 btrfs: zoned: dont clobber the extent buffer when zeroing it out
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Thumshirn <[email protected]>
[ Upstream commit db4b9eefc8ee0bcaeee4d5e6a7313905f6a2fe7c ]
On a zoned filesystem a freed-but-still-dirty tree block is written out as zeros (EXTENT_BUFFER_ZONED_ZEROOUT) only to keep the zone write pointer advancing. btree_csum_one_bio() implemented this by memzeroing the extent buffer's own folios before submission.
That destroys the in-memory buffer while it may still be referenced. In particular btrfs_free_tree_block() can run on it afterwards and reads the header to add a delayed reference; once the header has been zeroed it frees bytenr 0 and corrupts the extent tree (the btrfs_header_bytenr(buf) != 0 ASSERT in btrfs_free_tree_block(), or an "unable to find ref" abort). It is flaky and reproduces under fsstress, e.g. generic/461 and generic/013.
Write the zeros to disk from the shared zero page instead and leave the extent buffer content untouched, so any later reference - including the delayed reference from btrfs_free_tree_block() - still sees a valid header. end_bbio_meta_write() now clears writeback on the buffer's own folios, as the bio no longer carries them.
--- fs/btrfs/disk-io.c | 13 +++++----- fs/btrfs/extent_io.c | 58 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 53 insertions(+), 18 deletions(-)
fs/btrfs/disk-io.c +7 -6
@@ -272,14 +272,15 @@ blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)return BLK_STS_IOERR ;/* -* If an extent_buffer is marked as EXTENT_BUFFER_ZONED_ZEROOUT, don't -* checksum it but zero-out its content. This is done to preserve -* ordering of I/O without unnecessarily writing out data. +* An extent_buffer marked EXTENT_BUFFER_ZONED_ZEROOUT is written out as +* zeros to preserve ordering of I/O without persisting the now +* unnecessary block. The bio is fed from the shared zero page (see +* write_one_eb()), so there is nothing to checksum here. Crucially, the +* buffer's own content is left intact: it may still be referenced, e.g. +* btrfs_free_tree_block() reads its header to add a delayed reference. */ -if (test_bit (EXTENT_BUFFER_ZONED_ZEROOUT , &eb->bflags)) { -memzero_extent_buffer (eb,0 , eb->len); +if (test_bit (EXTENT_BUFFER_ZONED_ZEROOUT , &eb->bflags))return BLK_STS_OK ; - }if (WARN_ON_ONCE (found_start != eb->start))return BLK_STS_IOERR ;
fs/btrfs/extent_io.c +46 -12
88 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 645/869 btrfs: check if root is readonly when setting posix acl
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sun YangKai <[email protected]>
[ Upstream commit 01c2f41fc441f75b3f9326443372faceb1cb6638 ]
For a filesystem which has btrfs read-only property set to true, all write operations including acl and xattr should be denied. However, acl can still be set even if btrfs ro property is true.
This happens because no function on the set_acl code path checks the root is readonly or not. It was checked in btrfs_setxattr_trans() but got removed in commit 353c2ea735e4 ("btrfs: remove redundant readonly root check in btrfs_setxattr_trans")
That commit didn't check if all the callers properly check the root's read-only flag. A previous fix is commit b51111271b03 ("btrfs: check if root is readonly while setting security xattr").
Always check if the root is read-only before performing the set acl operation.
--- fs/btrfs/acl.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/btrfs/acl.c +4 -0
@@ -14,6 +14,7 @@#include "ctree.h" #include "xattr.h" #include "acl.h" +#include "btrfs_inode.h" struct posix_acl *btrfs_get_acl (struct inode *inode,int type,bool rcu) {
@@ -116,6 +117,9 @@ int btrfs_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,struct inode *inode =d_inode (dentry);umode_t old_mode = inode->i_mode; +if (btrfs_root_readonly (BTRFS_I (inode)->root)) +return -EROFS ; +if (type ==ACL_TYPE_ACCESS && acl) { ret =posix_acl_update_mode (idmap, inode, &inode->i_mode, &acl);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 646/869 btrfs: always wait for ordered extents to avoid OE races
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qu Wenruo <[email protected]>
[ Upstream commit ec78575dde998c21be7e0cb2503b5620f34b6255 ]
[BUG]
Syzbot reported a bug that there can be conflicting OEs for the same range:
BTRFS critical (device loop4): panic in insert_ordered_extent:264: overlapping ordered extents, existing oe file_offset 16384 num_bytes 430080 flags 0x1089, new oe file_offset 16384 num_bytes 430080 flags 0x80 (errno=-17 Object alrea[ 179.162726][ T6897] BTRFS critical (device loop4): panic in insert_ordered_extent:264: overlapping ordered extents, existing oe file_offset 16384 num_bytes 430080 flags 0x1089, new oe file_offset 16384 num_bytes 430080 flags 0x80 (errno=-17 Object already exists)
------------[ cut here ]------------ kernel BUG at fs/btrfs/ordered-data.c:264! Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 05/09/2026 RIP: 0010:btrfs_alloc_ordered_extent+0x943/0xad0 Call Trace: <TASK> cow_file_range+0x744/0x12a0 fallback_to_cow+0x5ea/0xa00 run_delalloc_nocow+0x110c/0x17a0 btrfs_run_delalloc_range+0xbe4/0x1c20 writepage_delalloc+0x104d/0x1ba0 btrfs_writepages+0x1667/0x28b0 do_writepages+0x338/0x560 filemap_fdatawrite_range+0x1f2/0x300 btrfs_fdatawrite_range+0x54/0xf0 btrfs_direct_write+0x6a0/0xc30 btrfs_do_write_iter+0x329/0x790 do_iter_readv_writev+0x624/0x8d0 vfs_writev+0x34c/0x990 __se_sys_pwritev2+0x17a/0x2a0 do_syscall_64+0x174/0x580 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK> ---[ end trace 0000000000000000 ]---
[CAUSE]
Since commit ff66fe666233 ("btrfs: fix incorrect buffered IO fallback for append direct writes"), if the direct IO finished short, we will revert the isize back to the original one, so that append writes can be respected during the buffered fallback.
Normally we rely on lock_and_cleanup_extent_if_need() function during buffered writeback to wait for any existing ordered extents.
But that ordered extent waiting only happens if the start_pos is inside the isize.
Since we have reverted the isize during failed direct IO, we will not wait for any ordered extents.
This means we can have a race where the direct IO OE is still in the tree, finished but not yet removed, then we're inserting the OE for the buffered write, causing the above crash.
[FIX]
Make the OE wait to be unconditional, to handle the reverted isize situation.
And since lock_and_cleanup_extent_if_need() now either lock the extents or return -EAGAIN, also remove the branches that handles no-extent-locked cases, and rename it to remove the "_if_need" suffix.
The following micro benchmark shows the runtime difference for btrfs_buffered_write(), doing xfs_io -f -c "pwrite 0 1m" workload, all values are the average runtime in nano seconds.
function runtime | before | after
-----------------------------------+-------------+---------------
lock_and_cleanup_extent_if_need() | 58.2 | 183.0 btrfs_buffered_write() | 2115.6 | 2973.3
The overall runtime of btrfs_buffered_write() is still pretty tiny (still less than 3 micro seconds), I'd say the extra cost is still acceptable.
An alternative to fix this problem is to wait ordered extents during iomap_end() where the isize revert is done.
But that solution will break nowait requirement, as if a nowait direct IO finished short, we have to wait for the OEs unconditionally or the next append buffered IO can still hit the same problem.
So here we have to move the wait cost to buffered write, but at least the code is slightly more streamline.
--- fs/btrfs/file.c | 101 ++++++++++++++++++++---------------------------- 1 file changed, 41 insertions(+), 60 deletions(-)
fs/btrfs/file.c +41 -60
@@ -969,70 +969,64 @@ static noinline int prepare_pages(struct inode *inode, struct page **pages,/* * This function locks the extent and properly waits for data=ordered extents -* to finish before allowing the pages to be modified if need. +* to finish before allowing the pages to be modified. * * The return value: -* 1 - the extent is locked -* 0 - the extent is not locked, and everything is OK +* 0 - the extent is locked * -EAGAIN - need re-prepare the pages * the other < 0 number - Something wrong happens */ static noinline int -lock_and_cleanup_extent_if_need (struct btrfs_inode *inode,struct page **pages, -size_t num_pages,loff_t pos, -size_t write_bytes, -u64 *lockstart,u64 *lockend,bool nowait, -struct extent_state **cached_state) +lock_and_cleanup_extent (struct btrfs_inode *inode,struct page **pages, +size_t num_pages,loff_t pos, +size_t write_bytes, +u64 *lockstart,u64 *lockend,bool nowait, +struct extent_state **cached_state) {struct btrfs_fs_info *fs_info = inode->root->fs_info; +struct btrfs_ordered_extent *ordered;u64 start_pos;u64 last_pos;int i; -int ret =0 ; start_pos =round_down (pos, fs_info->sectorsize); last_pos =round_up (pos + write_bytes, fs_info->sectorsize) -1 ; -if (start_pos < inode->vfs_inode.i_size) { -struct btrfs_ordered_extent *ordered; - -if (nowait) { -if (!btrfs_try_lock_extent (&inode->io_tree, start_pos, last_pos, - cached_state)) { -for (i =0 ; i < num_pages; i++) { -unlock_page (pages[i]); -put_page (pages[i]); - pages[i] =NULL ; - } - -return -EAGAIN ; - } - }else { -btrfs_lock_extent (&inode->io_tree, start_pos, last_pos, cached_state); - } - - ordered =btrfs_lookup_ordered_range (inode, start_pos, - last_pos - start_pos +1 ); -if (ordered && - ordered->file_offset + ordered->num_bytes > start_pos && - ordered->file_offset <= last_pos) { -btrfs_unlock_extent (&inode->io_tree, start_pos, last_pos, - cached_state); +if (nowait) { +if (!btrfs_try_lock_extent (&inode->io_tree, start_pos, last_pos, + cached_state)) {for (i =0 ; i < num_pages; i++) {unlock_page (pages[i]);put_page (pages[i]); + pages[i] =NULL ; } -btrfs_start_ordered_extent (ordered); -btrfs_put_ordered_extent (ordered); +return -EAGAIN ; } -if (ordered) -btrfs_put_ordered_extent (ordered); + }else { +btrfs_lock_extent (&inode->io_tree, start_pos, last_pos, cached_state); + } - *lockstart = start_pos; - *lockend = last_pos; - ret =1 ; + ordered =btrfs_lookup_ordered_range (inode, start_pos, + last_pos - start_pos +1 ); +if (ordered && + ordered->file_offset + ordered->num_bytes > start_pos && + ordered->file_offset <= last_pos) { +btrfs_unlock_extent (&inode->io_tree, start_pos, last_pos, + cached_state); +for (i =0 ; i < num_pages; i++) { +unlock_page (pages[i]); +put_page (pages[i]); + } +btrfs_start_ordered_extent (ordered); +btrfs_put_ordered_extent (ordered); +return -EAGAIN ; } +if (ordered) +btrfs_put_ordered_extent (ordered); + + *lockstart = start_pos; + *lockend = last_pos;/* * We should be called after prepare_pages() which should have locked
@@ -1041,7 +1035,7 @@ lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,for (i =0 ; i < num_pages; i++)WARN_ON (!PageLocked (pages[i])); -return ret; +return 0 ; }/*
@@ -1242,7 +1236,6 @@ ssize_t btrfs_buffered_write(struct kiocb *iocb, struct iov_iter *i)size_t copied;size_t dirty_sectors;size_t num_sectors; -int extents_locked;/* * Fault pages before locking them in prepare_pages
@@ -1326,17 +1319,15 @@ ssize_t btrfs_buffered_write(struct kiocb *iocb, struct iov_iter *i)break ; } - extents_locked =lock_and_cleanup_extent_if_need ( -BTRFS_I (inode), pages, + ret =lock_and_cleanup_extent (BTRFS_I (inode), pages, num_pages, pos, write_bytes, &lockstart, &lockend, nowait, &cached_state); -if (extents_locked <0 ) { -if (!nowait && extents_locked == -EAGAIN ) +if (ret <0 ) { +if (!nowait) goto again;btrfs_delalloc_release_extents (BTRFS_I (inode), reserve_bytes); - ret = extents_locked;break ; }
@@ -1389,18 +1380,8 @@ ssize_t btrfs_buffered_write(struct kiocb *iocb, struct iov_iter *i) dirty_pages, pos, copied, &cached_state, only_release_metadata); -/* -* If we have not locked the extent range, because the range's -* start offset is >= i_size, we might still have a non-NULL -* cached extent state, acquired while marking the extent range -* as delalloc through btrfs_dirty_pages(). Therefore free any -* possible cached extent state to avoid a memory leak. -*/ -if (extents_locked) -btrfs_unlock_extent (&BTRFS_I (inode)->io_tree, lockstart, - lockend, &cached_state); -else -free_extent_state (cached_state); +btrfs_unlock_extent (&BTRFS_I (inode)->io_tree, lockstart, + lockend, &cached_state);btrfs_delalloc_release_extents (BTRFS_I (inode), reserve_bytes);if (ret) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 647/869 btrfs: defrag: fix deadlock between defrag and delalloc space reservation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Filipe Manana <[email protected]>
[ Upstream commit ba02eab28041f9a4bbe9fc90c7249644fef6de0f ]
While running fsstress with autodefrag and flushoncommit, hit a deadlock due to the fact that defrag reserves delalloc space while it's holding dirty and locked folios, besides the extent range lock. The stack traces are the following:
[958.624] task:kworker/u50:3 state:D stack:0 pid:20365 tgid:20365 ppid:2 task_flags:0x4208060 flags:0x00080000 [958.626] Workqueue: events_unbound btrfs_async_reclaim_metadata_space [btrfs] [958.627] Call Trace: [958.628] <TASK> [958.628] __schedule+0x4be/0x10f0 [958.629] ? preempt_count_add+0x69/0xa0 [958.630] schedule+0x26/0xd0 [958.631] wait_current_trans+0x102/0x160 [btrfs] [958.632] ? __pfx_autoremove_wake_function+0x10/0x10 [958.633] start_transaction+0x374/0x900 [btrfs] [958.634] btrfs_commit_current_transaction+0x1d/0x70 [btrfs] [958.635] flush_space+0xca/0x5e0 [btrfs] [958.636] ? _raw_spin_unlock+0x15/0x30 [958.637] ? btrfs_reduce_alloc_profile+0x8c/0x190 [btrfs] [958.639] ? _raw_spin_unlock+0x15/0x30 [958.640] ? calc_available_free_space.isra.0+0x6f/0x110 [btrfs] [958.641] do_async_reclaim_metadata_space+0x84/0x190 [btrfs] [958.642] btrfs_async_reclaim_metadata_space+0x64/0x80 [btrfs] [958.644] process_one_work+0x19d/0x3a0 [958.644] worker_thread+0x1c4/0x330 [958.645] ? __pfx_worker_thread+0x10/0x10 [958.646] kthread+0xfc/0x130 [958.647] ? __pfx_kthread+0x10/0x10 [958.648] ret_from_fork+0x1f7/0x2c0 [958.648] ? __pfx_kthread+0x10/0x10 [958.649] ret_from_fork_asm+0x1a/0x30 [958.650] </TASK> [958.651] task:kworker/u49:7 state:D stack:0 pid:52990 tgid:52990 ppid:2 task_flags:0x4208060 flags:0x00080000 [958.653] Workqueue: writeback wb_workfn (flush-btrfs-334) [958.655] Call Trace: [958.655] <TASK> [958.656] __schedule+0x4be/0x10f0 [958.657] ? __blk_flush_plug+0xe9/0x140 [958.658] schedule+0x26/0xd0 [958.658] io_schedule+0x42/0x70 [958.659] folio_wait_bit_common+0x12b/0x330 [958.660] ? folio_wait_bit_common+0x100/0x330 [958.662] ? __pfx_wake_page_function+0x10/0x10 [958.663] extent_write_cache_pages+0x599/0x830 [btrfs] [958.664] ? acpi_fwnode_get_reference_args+0x1fa/0x270 [958.665] btrfs_writepages+0x77/0x130 [btrfs] [958.666] ? __pfx_end_bbio_data_write+0x10/0x10 [btrfs] [958.667] do_writepages+0xc6/0x160 [958.668] __writeback_single_inode+0x42/0x310 [958.669] writeback_sb_inodes+0x231/0x570 [958.670] wb_writeback+0x8a/0x340 [958.671] wb_workfn+0xbf/0x450 [958.672] ? finish_task_switch.isra.0+0xc1/0x350 [958.673] process_one_work+0x19d/0x3a0 [958.673] worker_thread+0x1c4/0x330 [958.674] ? __pfx_worker_thread+0x10/0x10 [958.675] kthread+0xfc/0x130 [958.676] ? __pfx_kthread+0x10/0x10 [958.676] ret_from_fork+0x1f7/0x2c0 [958.677] ? __pfx_kthread+0x10/0x10 [958.678] ret_from_fork_asm+0x1a/0x30 [958.679] </TASK> [958.679] task:btrfs-cleaner state:D stack:0 pid:296750 tgid:296750 ppid:2 task_flags:0x208040 flags:0x00080000 [958.681] Call Trace: [958.682] <TASK> [958.682] __schedule+0x4be/0x10f0 [958.683] schedule+0x26/0xd0 [958.684] handle_reserve_ticket+0x1b9/0x2c0 [btrfs] [958.685] ? __pfx_autoremove_wake_function+0x10/0x10 [958.686] reserve_bytes+0x283/0x4c0 [btrfs] [958.687] btrfs_reserve_metadata_bytes+0x18/0xb0 [btrfs] [958.688] btrfs_delalloc_reserve_metadata+0x121/0x320 [btrfs] [958.690] btrfs_delalloc_reserve_space+0x46/0xb0 [btrfs] [958.691] btrfs_defrag_file+0x903/0x1110 [btrfs] [958.692] btrfs_run_defrag_inodes+0x334/0x430 [btrfs] [958.694] cleaner_kthread+0x97/0x1c0 [btrfs] [958.694] ? __pfx_cleaner_kthread+0x10/0x10 [btrfs] [958.696] kthread+0xfc/0x130 [958.696] ? __pfx_kthread+0x10/0x10 [958.697] ret_from_fork+0x1f7/0x2c0 [958.698] ? __pfx_kthread+0x10/0x10 [958.699] ret_from_fork_asm+0x1a/0x30 [958.700] </TASK> [958.716] task:fsstress state:D stack:0 pid:296769 tgid:296769 ppid:296768 task_flags:0x400140 flags:0x00080000 [958.718] Call Trace: [958.719] <TASK> [958.719] __schedule+0x4be/0x10f0 [958.720] ? preempt_count_add+0x69/0xa0 [958.721] schedule+0x26/0xd0 [958.722] wb_wait_for_completion+0x79/0xc0 [958.723] ? __pfx_autoremove_wake_function+0x10/0x10 [958.724] __writeback_inodes_sb_nr+0xc5/0xf0 [958.725] try_to_writeback_inodes_sb+0x55/0x70 [958.726] btrfs_commit_transaction+0x19d/0xeb0 [btrfs] [958.727] ? start_transaction+0x343/0x900 [btrfs] [958.728] btrfs_mksubvol+0x28b/0x4e0 [btrfs] [958.729] btrfs_mksnapshot+0x74/0xa0 [btrfs] [958.730] __btrfs_ioctl_snap_create+0x194/0x210 [btrfs] [958.732] btrfs_ioctl_snap_create_v2+0xef/0x150 [btrfs] [958.733] btrfs_ioctl+0x7ec/0x2a70 [btrfs] [958.734] ? __virt_addr_valid+0xe4/0x180 [958.735] ? __check_object_size+0x1cd/0x1f0 [958.736] ? kmem_cache_free+0x146/0x380 [958.737] ? _raw_spin_unlock+0x15/0x30 [958.738] ? do_sys_openat2+0x83/0xd0 [958.739] __x64_sys_ioctl+0x92/0xe0 [958.740] do_syscall_64+0x60/0x590 [958.741] ? clear_bhb_loop+0x60/0xb0 [958.742] entry_SYSCALL_64_after_hwframe+0x76/0x7e [958.743] RIP: 0033:0x7f4431e108db [958.744] RSP: 002b:00007ffcd147db20 EFLAGS: 00000246 ORIG_RAX: 0000000000000010 [958.746] RAX: ffffffffffffffda RBX: 0000000000000004 RCX: 00007f4431e108db [958.747] RDX: 00007ffcd147eb90 RSI: 0000000050009417 RDI: 0000000000000005 [958.749] RBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000 [958.751] R10: 0000000000000000 R11: 0000000000000246 R12: 00007ffcd147fbf0 [958.752] R13: 00007ffcd147eb90 R14: 0000000000000005 R15: 0000000000000003 [958.754] </TASK>
What happens is the following:
1) The cleaner kthread is running autodefrag, and in defrag_one_range() it acquired all the folios for the range and locked them.
Then it locked the extent range in the inode's iotree.
It got two subranges from defrag_collect_targets(), the first one with folio A and the second one with folio B.
After it defragged the first subrange, folio A remains locked and dirty - it's only unlocked when defrag_one_range() returns.
When it attempts to defrag the second subrange (containing folio B), btrfs_delalloc_reserve_space() creates a space reservation ticket, due to lack of free metadata space and blocks waiting for the async metadata reclaim task to free space and wake it up;
2) The async reclaim metadata task attempts to commit the current transaction, but it blocks because there is another task that started the commit first;
3) A task creating a snapshot is committing the transaction and because the fs was mounted with flushoncommit, it calls try_to_writeback_inodes_sb(), which spawns a task to flush delalloc and waits for it to complete;
4) The task flushing delalloc (kworker/u49:7), finds that folio A for the inode being defragged is dirty, so it tries to lock it...
But it blocks because folio A is locked by the defrag task (the cleaner kthread) which is blocked waiting for the reservation ticket to be served, but the async reclaim metadata task is blocked waiting for the transaction commit, which in turn is blocked waiting for the delalloc flush task, which is trying to lock folio A, resulting in a deadlock.
The same type of problem can happen if the async reclaim task starts to flush delalloc, as that requires both locking the folio and the extent range in the inode's io tree, and in this case we don't need the fs to be mounted with flushoncommit. This type of problem has ocurred several times in the past with reflinks for example, where we had a dirty folio while holding the extent range locked and then starting a transaction blocked waiting for the async reclaim task due to lack of free metadata space.
So fix this by reserving delalloc space before locking folios and locking the extent range in the inode's iotree. We can not simply unlock the folios for each subrange given by defrag_collect_targets() after we defrag it because the same folio may be present too in the next subrange (due to large folios).
--- fs/btrfs/defrag.c | 50 +++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 17 deletions(-)
fs/btrfs/defrag.c +33 -17
@@ -1153,26 +1153,21 @@ static_assert(PAGE_ALIGNED(CLUSTER_SIZE));* * - Extent bits are locked */ -static int defrag_one_locked_target (struct btrfs_inode *inode, -struct defrag_target_range *target, -struct folio **folios,int nr_pages, -struct extent_state **cached_state) +static void defrag_one_locked_target (struct btrfs_inode *inode, +struct defrag_target_range *target, +struct folio **folios,int nr_pages, +struct extent_state **cached_state) {struct btrfs_fs_info *fs_info = inode->root->fs_info; -struct extent_changeset *data_reserved =NULL ;const u64 start = target->start;const u64 len = target->len;unsigned long last_index = (start + len -1 ) >>PAGE_SHIFT ;unsigned long start_index = start >>PAGE_SHIFT ;unsigned long first_index = folios[0 ]->index; -int ret =0 ;int i;ASSERT (last_index - first_index +1 <= nr_pages); - ret =btrfs_delalloc_reserve_space (inode, &data_reserved, start, len); -if (ret <0 ) -return ret;clear_extent_bit (&inode->io_tree, start, start + len -1 ,EXTENT_DELALLOC |EXTENT_DO_ACCOUNTING |EXTENT_DEFRAG , cached_state);
@@ -1184,10 +1179,6 @@ static int defrag_one_locked_target(struct btrfs_inode *inode,folio_clear_checked (folios[i]);btrfs_folio_clamp_set_dirty (fs_info, folios[i], start, len); } -btrfs_delalloc_release_extents (inode, len); -extent_changeset_free (data_reserved); - -return ret; } static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
@@ -1203,6 +1194,8 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,u64 last_index = (start + len -1 ) >>PAGE_SHIFT ;u64 start_index = start >>PAGE_SHIFT ;unsigned int nr_pages = last_index - start_index +1 ; +struct extent_changeset *data_reserved =NULL ; +u64 last_defrag_end = start;int ret =0 ;int i;
@@ -1213,6 +1206,22 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,if (!folios)return -ENOMEM ; +/* +* Reserve delalloc space before locking the range and before locking +* and dirtying any folios - otherwise we could deadlock, for example +* after defrag of one range we dirty folios and keep them locked when +* we move to the next range, so reserving delalloc space right before +* each range could trigger flushing of delalloc and deadlock on the +* extent lock or trigger a transaction commit with flushoncommit, which +* can either deadlock on the lock of a folio made dirty in the previous +* range or the extent lock. +*/ + ret =btrfs_delalloc_reserve_space (inode, &data_reserved, start, len); +if (ret <0 ) { +kfree (folios); +return ret; + } +/* Prepare all pages */ for (i =0 ; i < nr_pages; i++) { folios[i] =defrag_prepare_one_folio (inode, start_index + i);
@@ -1243,10 +1252,11 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len, goto btrfs_unlock_extent;list_for_each_entry (entry, &target_list, list) { - ret =defrag_one_locked_target (inode, entry, folios, nr_pages, - &cached_state); -if (ret <0 ) -break ; +defrag_one_locked_target (inode, entry, folios, nr_pages, &cached_state); +if (entry->start > last_defrag_end) +btrfs_delalloc_release_space (inode, data_reserved, last_defrag_end, + entry->start - last_defrag_end, true); + last_defrag_end = entry->start + entry->len; }list_for_each_entry_safe (entry, tmp, &target_list, list) {
@@ -1263,6 +1273,12 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,folio_put (folios[i]); }kfree (folios); +btrfs_delalloc_release_extents (inode, len); +if (last_defrag_end < start + len) +btrfs_delalloc_release_space (inode, data_reserved, last_defrag_end, + start + len - last_defrag_end, true); +extent_changeset_free (data_reserved); +return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 648/869 scsi: sd: Move the sd_config_discard() function definition
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bart Van Assche <[email protected]>
[ Upstream commit c0daf4836114fcbdf64bf817cab00b75ce712945 ]
Move the sd_config_discard() function definition such that its forward declaration can be removed.
Stable-dep-of: bb31844d88b7 ("scsi: sd: Fix special_vec mempool leak when scsi_alloc_sgtables() fails")
--- drivers/scsi/sd.c | 114 ++++++++++++++++++++++++++---------------------------- 1 file changed, 56 insertions(+), 58 deletions(-)
drivers/scsi/sd.c +56 -58
@@ -102,8 +102,6 @@ MODULE_ALIAS_SCSI_DEVICE(TYPE_ZBC);#define SD_MINORS 16 -static void sd_config_discard (struct scsi_disk *sdkp,struct queue_limits *lim, -unsigned int mode);static void sd_config_write_same (struct scsi_disk *sdkp,struct queue_limits *lim);static int sd_revalidate_disk (struct gendisk *);
@@ -121,6 +119,62 @@ static const char *sd_cache_types[] = {"write back, no read (daft)" }; +static void sd_disable_discard (struct scsi_disk *sdkp) +{ + sdkp->provisioning_mode =SD_LBP_DISABLE ; +blk_queue_disable_discard (sdkp->disk->queue); +} + +static void sd_config_discard (struct scsi_disk *sdkp,struct queue_limits *lim, +unsigned int mode) +{ +unsigned int logical_block_size = sdkp->device->sector_size; +unsigned int max_blocks =0 ; + + lim->discard_alignment = sdkp->unmap_alignment * logical_block_size; + lim->discard_granularity =max (sdkp->physical_block_size, + sdkp->unmap_granularity * logical_block_size); + sdkp->provisioning_mode = mode; + +switch (mode) { + +case SD_LBP_FULL : +case SD_LBP_DISABLE : +break ; + +case SD_LBP_UNMAP : + max_blocks =min_not_zero (sdkp->max_unmap_blocks, + (u32 )SD_MAX_WS16_BLOCKS ); +break ; + +case SD_LBP_WS16 : +if (sdkp->device->unmap_limit_for_ws) + max_blocks = sdkp->max_unmap_blocks; +else + max_blocks = sdkp->max_ws_blocks; + + max_blocks =min_not_zero (max_blocks, (u32 )SD_MAX_WS16_BLOCKS ); +break ; + +case SD_LBP_WS10 : +if (sdkp->device->unmap_limit_for_ws) + max_blocks = sdkp->max_unmap_blocks; +else + max_blocks = sdkp->max_ws_blocks; + + max_blocks =min_not_zero (max_blocks, (u32 )SD_MAX_WS10_BLOCKS ); +break ; + +case SD_LBP_ZERO : + max_blocks =min_not_zero (sdkp->max_ws_blocks, + (u32 )SD_MAX_WS10_BLOCKS ); +break ; + } + + lim->max_hw_discard_sectors = max_blocks * + (logical_block_size >>SECTOR_SHIFT ); +} +static void sd_set_flush_flag (struct scsi_disk *sdkp,struct queue_limits *lim) {
@@ -836,62 +890,6 @@ static unsigned char sd_setup_protect_cmreturn protect; } -static void sd_disable_discard (struct scsi_disk *sdkp) -{ - sdkp->provisioning_mode =SD_LBP_DISABLE ; -blk_queue_disable_discard (sdkp->disk->queue); -} - -static void sd_config_discard (struct scsi_disk *sdkp,struct queue_limits *lim, -unsigned int mode) -{ -unsigned int logical_block_size = sdkp->device->sector_size; -unsigned int max_blocks =0 ; - - lim->discard_alignment = sdkp->unmap_alignment * logical_block_size; - lim->discard_granularity =max (sdkp->physical_block_size, - sdkp->unmap_granularity * logical_block_size); - sdkp->provisioning_mode = mode; - -switch (mode) { - -case SD_LBP_FULL : -case SD_LBP_DISABLE : -break ; - -case SD_LBP_UNMAP : - max_blocks =min_not_zero (sdkp->max_unmap_blocks, - (u32 )SD_MAX_WS16_BLOCKS ); -break ; - -case SD_LBP_WS16 : -if (sdkp->device->unmap_limit_for_ws) - max_blocks = sdkp->max_unmap_blocks; -else - max_blocks = sdkp->max_ws_blocks; - - max_blocks =min_not_zero (max_blocks, (u32 )SD_MAX_WS16_BLOCKS ); -break ; - -case SD_LBP_WS10 : -if (sdkp->device->unmap_limit_for_ws) - max_blocks = sdkp->max_unmap_blocks; -else - max_blocks = sdkp->max_ws_blocks; - - max_blocks =min_not_zero (max_blocks, (u32 )SD_MAX_WS10_BLOCKS ); -break ; - -case SD_LBP_ZERO : - max_blocks =min_not_zero (sdkp->max_ws_blocks, - (u32 )SD_MAX_WS10_BLOCKS ); -break ; - } - - lim->max_hw_discard_sectors = max_blocks * - (logical_block_size >>SECTOR_SHIFT ); -} -static void *sd_set_special_bvec (struct request *rq,unsigned int data_len) {struct page *page;
Greg Kroah-Hartman
maintainerPATCH 649/869 scsi: sd: Fix special_vec mempool leak when scsi_alloc_sgtables() fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yang Xiuwei <[email protected]>
[ Upstream commit bb31844d88b77138b67aa20c3600203baff40140 ]
sd_set_special_bvec() allocates a special payload page for UNMAP and WRITE SAME commands. If scsi_alloc_sgtables() fails afterward in sd_setup_unmap_cmnd() or sd_setup_write_same{10,16}_cmnd(), the SCSI midlayer does not call uninit_command() because RQF_DONTPREP is not set yet, leaking the page.
Call sd_uninit_command() on error, and clear RQF_SPECIAL_PAYLOAD after freeing the page.
--- drivers/scsi/sd.c | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-)
drivers/scsi/sd.c +26 -11
@@ -890,6 +890,17 @@ static unsigned char sd_setup_protect_cmreturn protect; } +static void sd_uninit_command (struct scsi_cmnd *cmd) +{ +struct request *rq =scsi_cmd_to_rq (cmd); + +if (!(rq->rq_flags &RQF_SPECIAL_PAYLOAD )) +return ; + +mempool_free (rq->special_vec.bv_page, sd_page_pool); + rq->rq_flags &= ~RQF_SPECIAL_PAYLOAD ; +} +static void *sd_set_special_bvec (struct request *rq,unsigned int data_len) {struct page *page;
@@ -912,6 +923,7 @@ static blk_status_t sd_setup_unmap_cmnd(u32 nr_blocks =sectors_to_logical (sdp,blk_rq_sectors (rq));unsigned int data_len =24 ;char *buf; +blk_status_t ret; buf =sd_set_special_bvec (rq, data_len);if (!buf)
@@ -930,7 +942,10 @@ static blk_status_t sd_setup_unmap_cmnd( cmd->transfersize = data_len; rq->timeout =SD_TIMEOUT ; -return scsi_alloc_sgtables (cmd); + ret =scsi_alloc_sgtables (cmd); +if (ret !=BLK_STS_OK ) +sd_uninit_command (cmd); +return ret; }static void sd_config_atomic (struct scsi_disk *sdkp,struct queue_limits *lim)
@@ -1000,6 +1015,7 @@ static blk_status_t sd_setup_write_same1u64 lba =sectors_to_logical (sdp,blk_rq_pos (rq));u32 nr_blocks =sectors_to_logical (sdp,blk_rq_sectors (rq));u32 data_len = sdp->sector_size; +blk_status_t ret;if (!sd_set_special_bvec (rq, data_len))return BLK_STS_RESOURCE ;
@@ -1015,7 +1031,10 @@ static blk_status_t sd_setup_write_same1 cmd->transfersize = data_len; rq->timeout = unmap ?SD_TIMEOUT :SD_WRITE_SAME_TIMEOUT ; -return scsi_alloc_sgtables (cmd); + ret =scsi_alloc_sgtables (cmd); +if (ret !=BLK_STS_OK ) +sd_uninit_command (cmd); +return ret; } static blk_status_t sd_setup_write_same10_cmnd(struct scsi_cmnd *cmd,
@@ -1027,6 +1046,7 @@ static blk_status_t sd_setup_write_same1u64 lba =sectors_to_logical (sdp,blk_rq_pos (rq));u32 nr_blocks =sectors_to_logical (sdp,blk_rq_sectors (rq));u32 data_len = sdp->sector_size; +blk_status_t ret;if (!sd_set_special_bvec (rq, data_len))return BLK_STS_RESOURCE ;
@@ -1042,7 +1062,10 @@ static blk_status_t sd_setup_write_same1 cmd->transfersize = data_len; rq->timeout = unmap ?SD_TIMEOUT :SD_WRITE_SAME_TIMEOUT ; -return scsi_alloc_sgtables (cmd); + ret =scsi_alloc_sgtables (cmd); +if (ret !=BLK_STS_OK ) +sd_uninit_command (cmd); +return ret; }static blk_status_t sd_setup_write_zeroes_cmnd (struct scsi_cmnd *cmd)
@@ -1466,14 +1489,6 @@ static blk_status_t sd_init_command(stru } } -static void sd_uninit_command (struct scsi_cmnd *SCpnt) -{ -struct request *rq =scsi_cmd_to_rq (SCpnt); - -if (rq->rq_flags &RQF_SPECIAL_PAYLOAD ) -mempool_free (rq->special_vec.bv_page, sd_page_pool); -} -static bool sd_need_revalidate (struct gendisk *disk,struct scsi_disk *sdkp) {if (sdkp->device->removable || sdkp->write_prot) {
Greg Kroah-Hartman
maintainerPATCH 650/869 coresight: etm4x: missing cscfg_csdev_disable_active_config() in perf enable
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yeoreum Yun <[email protected]>
[ Upstream commit 0a47f0be6557b4a851addd430383a4dc7ee08752 ]
In the perf enable path, there are missing cases where cscfg_csdev_disable_active_config() is not called:
- Branch broadcast is selected but not supported by the hardware
- etm4_enable_hw() fails
This can lead to a leak of config_desc->active_cnt. Fix this by properly calling cscfg_csdev_disable_active_config() in these error paths.
--- .../coresight/coresight-etm4x-core.c | 46 +++++++++++-------- 1 file changed, 28 insertions(+), 18 deletions(-)
drivers/hwtracing/coresight/coresight-etm4x-core.c +28 -18
@@ -698,8 +698,7 @@ static int etm4_parse_event_config(struct coresight_device *csdev,struct etmv4_drvdata *drvdata =dev_get_drvdata (csdev->dev.parent);struct etmv4_config *config = &drvdata->config;struct perf_event_attr *attr = &event->attr; -unsigned long cfg_hash; -int preset, cc_threshold; +int cc_threshold;/* Clear configuration from previous run */ memset (config,0 ,sizeof (struct etmv4_config ));
@@ -774,20 +773,6 @@ static int etm4_parse_event_config(struct coresight_device *csdev,/* bit[12], Return stack enable bit */ config->cfg |=TRCCONFIGR_RS ; -/* -* Set any selected configuration and preset. -* -* This extracts the values of PMU_FORMAT_ATTR(configid) and PMU_FORMAT_ATTR(preset) -* in the perf attributes defined in coresight-etm-perf.c. -* configid uses bits 63:32 of attr->config2, preset uses bits 3:0 of attr->config. -* A zero configid means no configuration active, preset = 0 means no preset selected. -*/ -if (attr->config2 &GENMASK_ULL (63 ,32 )) { - cfg_hash = (u32)(attr->config2 >>32 ); - preset = attr->config &0xF ; - ret =cscfg_csdev_enable_active_config (csdev, cfg_hash, preset); - } -/* branch broadcast - enable if selected and supported */ if (attr->config &BIT (ETM_OPT_BRANCH_BROADCAST )) {if (!drvdata->trcbb) {
@@ -810,8 +795,10 @@ static int etm4_enable_perf(struct coresight_device *csdev,struct perf_event *event, struct coresight_trace_id_map *id_map) { - int ret = 0, trace_id; + int ret = 0, trace_id, preset;struct etmv4_drvdata *drvdata =dev_get_drvdata (csdev->dev.parent); +struct perf_event_attr *attr = &event->attr; +unsigned long cfg_hash =0 ;if (WARN_ON_ONCE (drvdata->cpu !=smp_processor_id ())) { ret = -EINVAL ;
@@ -823,6 +810,22 @@ static int etm4_enable_perf(struct coresight_device *csdev,if (ret) goto out; +/* +* Set any selected configuration and preset. +* +* This extracts the values of PMU_FORMAT_ATTR(configid) and PMU_FORMAT_ATTR(preset) +* in the perf attributes defined in coresight-etm-perf.c. +* configid uses bits 63:32 of attr->config2, preset uses bits 3:0 of attr->config. +* A zero configid means no configuration active, preset = 0 means no preset selected. +*/ +if (attr->config2 &GENMASK_ULL (63 ,32 )) { + cfg_hash = (u32)(attr->config2 >>32 ); + preset = attr->config &0xF ; + ret =cscfg_csdev_enable_active_config (csdev, cfg_hash, preset); +if (ret) + goto out; + } +/* * perf allocates cpu ids as part of _setup_aux() - device needs to use * the allocated ID. This reads the current version without allocation.
@@ -836,13 +839,20 @@ static int etm4_enable_perf(struct coresight_device *csdev,dev_err (&drvdata->csdev->dev,"Failed to set trace ID for %s on CPU%d\n" ,dev_name (&drvdata->csdev->dev), drvdata->cpu); ret = -EINVAL ; - goto out; + goto err_cfg; } drvdata->trcid = (u8 )trace_id;/* And enable it */ ret =etm4_enable_hw (drvdata); +if (ret) + goto err_cfg; + +return 0 ; +err_cfg: +if (cfg_hash) +cscfg_csdev_disable_active_config (csdev); out:return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 651/869 drm/amd/display: disable replay when crc source is enabled
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ray Wu <[email protected]>
[ Upstream commit a036db3953140d5c2816b056aa3e73b8e98d9bc0 ]
[Why]
IGT CRC tests fail on replay panels due to invalid CRC values captured when replay is active.
[How]
- Disable replay when CRC source is enabled; set flag to prevent unexpected re-enable
- Reset flag when CRC source is disabled to allow replay
Stable-dep-of: 261e0fe4e2c9 ("drm/amd/display: Resize MST HDCP per-connector arrays to 32")
--- .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.h | 1 + .../drm/amd/display/amdgpu_dm/amdgpu_dm_crc.c | 25 ++++++++++++++++--- .../amd/display/amdgpu_dm/amdgpu_dm_replay.c | 7 ++++++ 3 files changed, 30 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.h +1 -0
@@ -732,6 +732,7 @@ struct amdgpu_dm_connector {int sr_skip_count;bool disallow_edp_enter_psr; +bool disallow_edp_enter_replay;/* Record progress status of mst*/ uint8_t mst_status;
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_crc.c +22 -3
@@ -31,6 +31,7 @@#include "dc.h" #include "amdgpu_securedisplay.h" #include "amdgpu_dm_psr.h" +#include "amdgpu_dm_replay.h" static const char *const pipe_crc_sources[] = {"none" ,
@@ -216,6 +217,7 @@ int amdgpu_dm_crtc_configure_crc_source(struct drm_crtc *crtc, {struct amdgpu_device *adev =drm_to_adev (crtc->dev);struct dc_stream_state *stream_state = dm_crtc_state->stream; +struct amdgpu_dm_connector *aconnector =NULL ;bool enable =amdgpu_dm_is_valid_crc_source (source);int ret =0 ;
@@ -223,11 +225,22 @@ int amdgpu_dm_crtc_configure_crc_source(struct drm_crtc *crtc,if (!stream_state)return -EINVAL ; +/* Get connector from stream */ + aconnector = (struct amdgpu_dm_connector *)stream_state->dm_stream_context; +mutex_lock (&adev->dm.dc_lock); -/* For PSR1, check that the panel has exited PSR */ -if (stream_state->link->psr_settings.psr_version <DC_PSR_VERSION_SU_1 ) -amdgpu_dm_psr_wait_disable (stream_state); + +if (enable) { +/* For PSR1, check that the panel has exited PSR */ +if (stream_state->link->psr_settings.psr_version <DC_PSR_VERSION_SU_1 ) +amdgpu_dm_psr_wait_disable (stream_state); + +/* Set flag to disallow enter replay when CRC source is enabled */ +if (aconnector) + aconnector->disallow_edp_enter_replay = true; +amdgpu_dm_replay_disable (stream_state); + }/* Enable or disable CRTC CRC generation */ if (dm_is_crc_source_crtc (source) || source ==AMDGPU_DM_PIPE_CRC_SOURCE_NONE ) {
@@ -250,6 +263,12 @@ int amdgpu_dm_crtc_configure_crc_source(struct drm_crtc *crtc, DYN_EXPANSION_AUTO); } +if (!enable) { +/* Clear flag to allow enter replay when CRC source is disabled */ +if (aconnector) + aconnector->disallow_edp_enter_replay = false; + } + unlock:mutex_unlock (&adev->dm.dc_lock);
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_replay.c +7 -0
@@ -153,10 +153,17 @@ bool amdgpu_dm_replay_enable(struct dc_stream_state *stream, bool wait) {bool replay_active = true;struct dc_link *link =NULL ; +struct amdgpu_dm_connector *aconnector =NULL ;if (stream ==NULL )return false; +/* Check if replay is disabled by connector flag */ + aconnector = (struct amdgpu_dm_connector *)stream->dm_stream_context; +if (!aconnector || aconnector->disallow_edp_enter_replay) { +return false; + } + link = stream->link;if (link) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 652/869 drm/amd/display: Resize MST HDCP per-connector arrays to 32
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Harry Wentland <[email protected]>
[ Upstream commit 261e0fe4e2c99f687114b64b10b98db964b475f4 ]
AMDGPU_DM_MAX_DISPLAY_INDEX is 31. It suggest a maximum number of 32 connectors. But the way it's used is like MAX_DISPLAY_COUNT. Hence we're off by one with DRM core, which supports a max of 32 connectors.
Rename AMDGPU_DM_MAX_DISPLAY_INDEX to AMDGPU_DM_MAX_DISPLAY_COUNT to match its actual use, and increase the size to 32 to match the originally intended size.
--- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.h | 2 +- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_hdcp.c | 10 +++++----- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_hdcp.h | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.h +1 -1
@@ -44,7 +44,7 @@* in amdgpu_dm_kms.h file */ -#define AMDGPU_DM_MAX_DISPLAY_INDEX 31 +#define AMDGPU_DM_MAX_DISPLAY_COUNT 32#define AMDGPU_DM_MAX_CRTC 6
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_hdcp.c +5 -5
@@ -256,7 +256,7 @@ void hdcp_reset_display(struct hdcp_workqueue *hdcp_work, unsigned int link_indecancel_delayed_work (&hdcp_w->property_validate_dwork); -for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_INDEX ; conn_index++) { +for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_COUNT ; conn_index++) { hdcp_w->encryption_status[conn_index] =MOD_HDCP_ENCRYPTION_STATUS_HDCP_OFF ;if (hdcp_w->aconnector[conn_index]) {
@@ -303,7 +303,7 @@ static void event_property_update(struct work_struct *work)struct drm_connector *connector;struct drm_connector_state *conn_state; -for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_INDEX ; conn_index++) { +for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_COUNT ; conn_index++) { aconnector = hdcp_work->aconnector[conn_index];if (!aconnector)
@@ -372,7 +372,7 @@ static void event_property_validate(struct work_struct *work)guard (mutex)(&hdcp_work->mutex); -for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_INDEX ; +for (conn_index =0 ; conn_index <AMDGPU_DM_MAX_DISPLAY_COUNT ; conn_index++) { aconnector = hdcp_work->aconnector[conn_index];
@@ -749,10 +749,10 @@ struct hdcp_workqueue *hdcp_create_workqueue(struct amdgpu_device *adev,memset (hdcp_work[i].aconnector,0 ,sizeof (struct amdgpu_dm_connector *) * -AMDGPU_DM_MAX_DISPLAY_INDEX ); +AMDGPU_DM_MAX_DISPLAY_COUNT );memset (hdcp_work[i].encryption_status,0 ,sizeof (enum mod_hdcp_encryption_status ) * -AMDGPU_DM_MAX_DISPLAY_INDEX ); +AMDGPU_DM_MAX_DISPLAY_COUNT ); } cp_psp->funcs.update_stream_config = update_config;
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_hdcp.h +4 -4
@@ -43,7 +43,7 @@ struct hdcp_workqueue {struct delayed_work callback_dwork;struct delayed_work watchdog_timer_dwork;struct delayed_work property_validate_dwork; -struct amdgpu_dm_connector *aconnector[AMDGPU_DM_MAX_DISPLAY_INDEX ]; +struct amdgpu_dm_connector *aconnector[AMDGPU_DM_MAX_DISPLAY_COUNT ];struct mutex mutex;struct mod_hdcp hdcp;
@@ -51,7 +51,7 @@ struct hdcp_workqueue {struct mod_hdcp_display display;struct mod_hdcp_link link; -enum mod_hdcp_encryption_status encryption_status[AMDGPU_DM_MAX_DISPLAY_INDEX ]; +enum mod_hdcp_encryption_status encryption_status[AMDGPU_DM_MAX_DISPLAY_COUNT ];/* when display is unplugged from mst hub, connctor will be * destroyed within dm_dp_mst_connector_destroy. connector * hdcp perperties, like type, undesired, desired, enabled,
@@ -61,9 +61,9 @@ struct hdcp_workqueue {* will be retrieved from hdcp_work within dm_dp_mst_get_modes */ /* un-desired, desired, enabled */ -unsigned int content_protection[AMDGPU_DM_MAX_DISPLAY_INDEX ]; +unsigned int content_protection[AMDGPU_DM_MAX_DISPLAY_COUNT ];/* hdcp1.x, hdcp2.x */ -unsigned int hdcp_content_type[AMDGPU_DM_MAX_DISPLAY_INDEX ]; +unsigned int hdcp_content_type[AMDGPU_DM_MAX_DISPLAY_COUNT ];uint8_t max_link;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 653/869 bpf: Factor callchain_store function from __bpf_get_stack
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Olsa <[email protected]>
[ Upstream commit cbb99938e7935c9f62c891573a4b09690e5e22de ]
The new callchain_store function stores trace entries buffer into user supplied buffer. It covers both just-ip and buildid data.
Stable-dep-of: f5d242825ca4 ("bpf: Clear buf on error in __bpf_get_task_stack")
--- kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-)
kernel/bpf/stackmap.c +25 -14
@@ -488,6 +488,29 @@ const struct bpf_func_proto bpf_get_stackid_proto_pe = { .arg3_type = ARG_ANYTHING, }; +static u32 callchain_store (struct perf_callchain_entry *trace,void *buf, +u32 elem_size,u64 flags) +{ +bool user_build_id = flags &BPF_F_USER_BUILD_ID ; +u32 skip = flags &BPF_F_SKIP_FIELD_MASK ; +u32 trace_nr, copy_len; +u64 *ips; + + trace_nr = trace->nr - skip; + copy_len = trace_nr * elem_size; + + ips = trace->ip + skip; +if (user_build_id) { +struct bpf_stack_build_id *id_offs = buf; + +for (u32 i =0 ; i < trace_nr; i++) + id_offs[i].ip = ips[i]; + }else { +memcpy (buf, ips, copy_len); + } +return trace_nr; +} +static long __bpf_get_stack (struct pt_regs *regs,struct task_struct *task,struct perf_callchain_entry *trace_in,void *buf,u32 size,u64 flags,bool may_fault)
@@ -500,7 +523,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,struct perf_callchain_entry *trace;bool kernel = !user;int err = -EINVAL ; -u64 *ips;if (unlikely (flags & ~(BPF_F_SKIP_FIELD_MASK |BPF_F_USER_STACK |BPF_F_USER_BUILD_ID )))
@@ -547,21 +569,10 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, goto err_fault; } - trace_nr = trace->nr - skip; + trace_nr =callchain_store (trace, buf, elem_size, flags); copy_len = trace_nr * elem_size; - ips = trace->ip + skip; -if (user_build_id) { -struct bpf_stack_build_id *id_offs = buf; -u32 i; - -for (i =0 ; i < trace_nr; i++) - id_offs[i].ip = ips[i]; - }else { -memcpy (buf, ips, copy_len); - } - -/* trace/ips should not be dereferenced after this point */ +/* trace should not be dereferenced after this point */ if (may_fault)rcu_read_unlock ();preempt_enable ();
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 654/869 bpf: Factor callchain_finalize function from __bpf_get_stack
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Olsa <[email protected]>
[ Upstream commit 014fbe5902dccdaef69114abdcdb15e3dbe55e34 ]
The new callchain_finalize function calls the build-id retrieval (if needed) and zeroes the buffer. This makes things easier for preemption fix in following change.
Stable-dep-of: f5d242825ca4 ("bpf: Clear buf on error in __bpf_get_task_stack")
--- kernel/bpf/stackmap.c | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-)
kernel/bpf/stackmap.c +17 -8
@@ -511,16 +511,31 @@ static u32 callchain_store(struct perf_callchain_entry *trace, void *buf,return trace_nr; } +static long callchain_finalize (void *buf,u32 size,u32 trace_nr,u32 elem_size, +u64 flags,bool may_fault) +{ +bool user_build_id = flags &BPF_F_USER_BUILD_ID ; +bool user = flags &BPF_F_USER_STACK ; +u32 copy_len = trace_nr * elem_size; + +if (user_build_id) +stack_map_get_build_id_offset (buf, trace_nr, user, may_fault); + +if (size > copy_len) +memset (buf + copy_len,0 , size - copy_len); +return copy_len; +} +static long __bpf_get_stack (struct pt_regs *regs,struct task_struct *task,struct perf_callchain_entry *trace_in,void *buf,u32 size,u64 flags,bool may_fault) { -u32 trace_nr, copy_len, elem_size, max_depth;bool user_build_id = flags &BPF_F_USER_BUILD_ID ;bool crosstask = task && task != current;u32 skip = flags &BPF_F_SKIP_FIELD_MASK ;bool user = flags &BPF_F_USER_STACK ;struct perf_callchain_entry *trace; +u32 trace_nr, elem_size, max_depth;bool kernel = !user;int err = -EINVAL ;
@@ -570,19 +585,13 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, } trace_nr =callchain_store (trace, buf, elem_size, flags); - copy_len = trace_nr * elem_size;/* trace should not be dereferenced after this point */ if (may_fault)rcu_read_unlock ();preempt_enable (); -if (user_build_id) -stack_map_get_build_id_offset (buf, trace_nr, user, may_fault); - -if (size > copy_len) -memset (buf + copy_len,0 , size - copy_len); -return copy_len; +return callchain_finalize (buf, size, trace_nr, elem_size, flags, may_fault); err_fault: err = -EFAULT ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 655/869 bpf: Remove trace_in argument from __bpf_get_stack
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Olsa <[email protected]>
[ Upstream commit 58cfc2201d964163fe9c4a703136eb64db799f08 ]
Now with the new callchain_* helper functions we can process trace_in case directly in bpf_get_stack_pe function and remove it from __bpf_get_stack which makes things easier for preemption fix in following change.
Stable-dep-of: f5d242825ca4 ("bpf: Clear buf on error in __bpf_get_task_stack")
--- kernel/bpf/stackmap.c | 49 ++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 14 deletions(-)
kernel/bpf/stackmap.c +35 -14
@@ -527,7 +527,6 @@ static long callchain_finalize(void *buf, u32 size, u32 trace_nr, u32 elem_size, }static long __bpf_get_stack (struct pt_regs *regs,struct task_struct *task, -struct perf_callchain_entry *trace_in,void *buf,u32 size,u64 flags,bool may_fault) {bool user_build_id = flags &BPF_F_USER_BUILD_ID ;
@@ -567,10 +566,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,if (may_fault)rcu_read_lock ();/* need RCU for perf's callchain below */ -if (trace_in) { - trace = trace_in; - trace->nr =min_t (u32, trace->nr, max_depth); - }else if (kernel && task) { +if (kernel && task) { trace =get_callchain_entry_for_task (task, max_depth); }else { trace = get_perf_callchain(regs, kernel, user, max_depth,
@@ -603,7 +599,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size, u64, flags) { -return __bpf_get_stack (regs,NULL ,NULL , buf, size, flags, false/* !may_fault */ ); +return __bpf_get_stack (regs,NULL , buf, size, flags, false/* !may_fault */ ); }const struct bpf_func_proto bpf_get_stack_proto = {
@@ -619,7 +615,7 @@ const struct bpf_func_proto bpf_get_stack_proto = { BPF_CALL_4(bpf_get_stack_sleepable, struct pt_regs *, regs, void *, buf, u32, size, u64, flags) { -return __bpf_get_stack (regs,NULL ,NULL , buf, size, flags, true/* may_fault */ ); +return __bpf_get_stack (regs,NULL , buf, size, flags, true/* may_fault */ ); }const struct bpf_func_proto bpf_get_stack_sleepable_proto = {
@@ -644,7 +640,7 @@ static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, regs =task_pt_regs (task);if (regs) - res =__bpf_get_stack (regs, task,NULL , buf, size, flags, may_fault); + res =__bpf_get_stack (regs, task, buf, size, flags, may_fault);put_task_stack (task);return res;
@@ -685,6 +681,32 @@ const struct bpf_func_proto bpf_get_task_stack_sleepable_proto = { .arg4_type = ARG_ANYTHING, }; +static int __bpf_get_stack_pe (struct perf_callchain_entry *trace,void *buf,u32 size, +u64 flags) +{ +bool user_build_id = flags &BPF_F_USER_BUILD_ID ; +u64 skip = flags &BPF_F_SKIP_FIELD_MASK ; +bool user = flags &BPF_F_USER_STACK ; +u32 elem_size, max_depth, nr_trace; +bool kernel = !user; + +if (kernel && user_build_id) +return -EINVAL ; + + elem_size = user_build_id ?sizeof (struct bpf_stack_build_id ) :sizeof (u64); +if (unlikely (size % elem_size)) +return -EINVAL ; + + max_depth =stack_map_calculate_max_depth (size, elem_size, flags); + trace->nr =min_t (u32, trace->nr, max_depth); + +if (trace->nr < skip) +return -EFAULT ; + + nr_trace =callchain_store (trace, buf, elem_size, flags); +return callchain_finalize (buf, size, nr_trace, elem_size, flags, false/* !may_fault */ ); +} + BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, void *, buf, u32, size, u64, flags) {
@@ -696,7 +718,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,__u64 nr_kernel;if (!(event->attr.sample_type &PERF_SAMPLE_CALLCHAIN )) -return __bpf_get_stack (regs,NULL ,NULL , buf, size, flags, false/* !may_fault */ ); +return __bpf_get_stack (regs,NULL , buf, size, flags, false/* !may_fault */ );if (unlikely (flags & ~(BPF_F_SKIP_FIELD_MASK |BPF_F_USER_STACK |BPF_F_USER_BUILD_ID )))
@@ -716,7 +738,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,__u64 nr = trace->nr; trace->nr = nr_kernel; - err =__bpf_get_stack (regs,NULL , trace, buf, size, flags, false/* !may_fault */ ); + err =__bpf_get_stack_pe (trace, buf, size, flags);/* restore nr */ trace->nr = nr;
@@ -726,14 +748,13 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, skip += nr_kernel;if (skip >BPF_F_SKIP_FIELD_MASK ) goto clear; - flags = (flags & ~BPF_F_SKIP_FIELD_MASK ) | skip; - err =__bpf_get_stack (regs,NULL , trace, buf, size, flags, false/* !may_fault */ ); + err =__bpf_get_stack_pe (trace, buf, size, flags); } -return err; clear: -memset (buf,0 , size); +if (err <0 ) +memset (buf,0 , size);return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 656/869 bpf: Clear buf on error in __bpf_get_task_stack
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Olsa <[email protected]>
[ Upstream commit f5d242825ca417bb6afe35fde6e8880f97ca43fb ]
Both bpf_get_task_stack and bpf_get_task_stack_sleepable helpers that use __bpf_get_task_stack have buf defined as ARG_PTR_TO_UNINIT_MEM argument and we should initialize the buf on every return path.
Adding missing buf memset for __bpf_get_task_stack fail paths. This provides deterministic buffer contents, which is useful when the buffer is used directly as a map key.
--- kernel/bpf/stackmap.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
kernel/bpf/stackmap.c +5 -2
@@ -635,14 +635,17 @@ static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size,struct pt_regs *regs;long res = -EINVAL ; -if (!try_get_task_stack (task)) +if (!try_get_task_stack (task)) { +memset (buf,0 , size);return -EFAULT ; + } regs =task_pt_regs (task);if (regs) res =__bpf_get_stack (regs, task, buf, size, flags, may_fault); +else +memset (buf,0 , size);put_task_stack (task); -return res; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 657/869 ocfs2/heartbeat: fix slot mapping rollback leaks on error paths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yufan Chen <[email protected]>
[ Upstream commit 5686459423d03d192134166f0ec45f98bb2d5d57 ]
o2hb_map_slot_data() allocates hr_tmp_block, hr_slots, hr_slot_data, and pages in stages. If a later allocation fails, the current code returns without unwinding the earlier allocations.
o2hb_region_dev_store() also leaves slot mapping resources behind when setup aborts, and it keeps hr_aborted_start/hr_node_deleted set across retries. That leaves stale state behind after a failed start.
Factor the slot cleanup into o2hb_unmap_slot_data(), use it from both o2hb_map_slot_data() and o2hb_region_release(), and call it from the dev_store() rollback after stopping a started heartbeat thread. While freeing pages, clear each hr_slot_data entry as it is released, and reset the start state before each new setup attempt.
This closes the slot mapping leak on allocation/setup failure paths and keeps failed setup attempts retryable.
Stable-dep-of: 011291b70ba4 ("ocfs2: o2hb: quiesce negotiate handlers and timeout work")
--- fs/ocfs2/cluster/heartbeat.c | 83 ++++++++++++++++++++++++------------ 1 file changed, 56 insertions(+), 27 deletions(-)
fs/ocfs2/cluster/heartbeat.c +56 -27
@@ -1531,33 +1531,45 @@ static struct o2hb_region *to_o2hb_region(struct config_item *item) return item ? container_of(item, struct o2hb_region, hr_item) : NULL; } -/* drop_item only drops its ref after killing the thread, nothing should -* be using the region anymore. this has to clean up any state that -* attributes might have built up. */ -static void o2hb_region_release (struct config_item *item) +static void o2hb_unmap_slot_data (struct o2hb_region *reg) {int i;struct page *page; -struct o2hb_region *reg =to_o2hb_region (item); - -mlog (ML_HEARTBEAT ,"hb region release (%pg)\n" ,reg_bdev (reg)); - -kfree (reg->hr_tmp_block);if (reg->hr_slot_data) {for (i =0 ; i < reg->hr_num_pages; i++) { page = reg->hr_slot_data[i]; -if (page) +if (page) {__free_page (page); + reg->hr_slot_data[i] =NULL ; + } }kfree (reg->hr_slot_data); + reg->hr_slot_data =NULL ; } +kfree (reg->hr_slots); + reg->hr_slots =NULL ; + +kfree (reg->hr_tmp_block); + reg->hr_tmp_block =NULL ; +} + +/* drop_item only drops its ref after killing the thread, nothing should +* be using the region anymore. this has to clean up any state that +* attributes might have built up. +*/ +static void o2hb_region_release (struct config_item *item) +{ +struct o2hb_region *reg =to_o2hb_region (item); + +mlog (ML_HEARTBEAT ,"hb region release (%pg)\n" ,reg_bdev (reg)); + +o2hb_unmap_slot_data (reg); +if (reg->hr_bdev_file)fput (reg->hr_bdev_file); -kfree (reg->hr_slots); -debugfs_remove_recursive (reg->hr_debug_dir);kfree (reg->hr_db_livenodes);kfree (reg->hr_db_regnum);
@@ -1708,6 +1720,7 @@ static void o2hb_init_region_params(struct o2hb_region *reg)static int o2hb_map_slot_data (struct o2hb_region *reg) {int i, j; +int ret = -ENOMEM ;unsigned int last_slot;unsigned int spp = reg->hr_slots_per_page;struct page *page;
@@ -1715,15 +1728,15 @@ static int o2hb_map_slot_data(struct o2hb_region *reg)struct o2hb_disk_slot *slot; reg->hr_tmp_block =kmalloc (reg->hr_block_bytes,GFP_KERNEL ); -if (reg->hr_tmp_block ==NULL ) -return -ENOMEM ; +if (!reg->hr_tmp_block) + goto out; reg->hr_slots =kcalloc (reg->hr_blocks,sizeof (struct o2hb_disk_slot ),GFP_KERNEL ); -if (reg->hr_slots ==NULL ) -return -ENOMEM ; +if (!reg->hr_slots) + goto out; -for (i =0 ; i < reg->hr_blocks; i++) { +for (i =0 ; i < reg->hr_blocks; i++) { slot = ®->hr_slots[i]; slot->ds_node_num = i;INIT_LIST_HEAD (&slot->ds_live_item);
@@ -1738,12 +1751,12 @@ static int o2hb_map_slot_data(struct o2hb_region *reg) reg->hr_slot_data =kcalloc (reg->hr_num_pages,sizeof (struct page *),GFP_KERNEL );if (!reg->hr_slot_data) -return -ENOMEM ; + goto out; -for (i =0 ; i < reg->hr_num_pages; i++) { +for (i =0 ; i < reg->hr_num_pages; i++) { page =alloc_page (GFP_KERNEL );if (!page) -return -ENOMEM ; + goto out; reg->hr_slot_data[i] = page;
@@ -1763,6 +1776,10 @@ static int o2hb_map_slot_data(struct o2hb_region *reg) }return 0 ; + +out: +o2hb_unmap_slot_data (reg); +return ret; }/* Read in all the slots available and populate the tracking
@@ -1854,9 +1871,11 @@ static ssize_t o2hb_region_dev_store(struct config_item *item,"blocksize %u incorrect for device, expected %d" , reg->hr_block_bytes, sectsize); ret = -EINVAL ; - goto out3; + goto out; } + reg->hr_aborted_start =0 ; + reg->hr_node_deleted =0 ;o2hb_init_region_params (reg);/* Generation of zero is invalid */
@@ -1868,13 +1887,13 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, ret =o2hb_map_slot_data (reg);if (ret) {mlog_errno (ret); - goto out3; + goto out; } ret =o2hb_populate_slot_data (reg);if (ret) {mlog_errno (ret); - goto out3; + goto out; }INIT_DELAYED_WORK (®->hr_write_timeout_work, o2hb_write_timeout);
@@ -1905,7 +1924,7 @@ static ssize_t o2hb_region_dev_store(struct config_item *item,if (IS_ERR (hb_task)) { ret =PTR_ERR (hb_task);mlog_errno (ret); - goto out3; + goto out; }spin_lock (&o2hb_live_lock);
@@ -1922,12 +1941,12 @@ static ssize_t o2hb_region_dev_store(struct config_item *item,if (reg->hr_aborted_start) { ret = -EIO ; - goto out3; + goto out; }if (reg->hr_node_deleted) { ret = -EINVAL ; - goto out3; + goto out; }/* Ok, we were woken. Make sure it wasn't by drop_item() */
@@ -1946,8 +1965,18 @@ static ssize_t o2hb_region_dev_store(struct config_item *item,printk (KERN_NOTICE "o2hb: Heartbeat started on region %s (%pg)\n" ,config_item_name (®->hr_item),reg_bdev (reg)); -out3: +out:if (ret <0 ) { +spin_lock (&o2hb_live_lock); + hb_task = reg->hr_task; + reg->hr_task =NULL ; +spin_unlock (&o2hb_live_lock); + +if (hb_task) +kthread_stop (hb_task); + +o2hb_unmap_slot_data (reg); +fput (reg->hr_bdev_file); reg->hr_bdev_file =NULL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 658/869 ocfs2: o2hb: quiesce negotiate handlers and timeout work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 011291b70ba4832e136b7b581825b2bc0f525bf6 ]
Heartbeat regions publish struct o2hb_region as the private data for the NEGO_TIMEOUT and NEGO_APPROVE o2net handlers as soon as make_item() creates the configfs region. The approve handler can call o2hb_arm_timeout(), so a peer can touch the region timeout work before dev_store() has finished building the heartbeat runtime, or after teardown has started to shut that runtime back down.
The final configfs put also has to keep reg alive until the last in-flight o2net callback drops its handler reference. o2net_unregister_handler_list() blocks future handler lookups, but it does not wait for sc_rx_work that already passed o2net_handler_get(). That drain needs to cover local listener teardown as well, where the o2net ordered workqueue may already be inside destroy_workqueue().
Fix the lifetime rule in both directions. Initialize the region delayed works before publishing reg through the o2net handler table, keep new or stopping regions non-armable with hr_stopping, and quiesce both delayed works on failed-start and teardown paths even when no heartbeat thread is left to call o2hb_disarm_timeout(). Then unregister handlers before tearing down handler-visible region state and make the drain wait for the active or destroying o2net ordered workqueue before release frees reg.
The buggy scenario involves two paths, with each column showing the order within that path:
region lifecycle: late negotiate callback:
1. make_item() registers the 1. o2net_process_message() gets a
region handlers before heartbeat handler for reg.
dev_store() has built a 2. The callback runs after the lookup
runnable heartbeat context. lock is dropped and dereferences reg.
2. A failed start or rmdir 3. An approve or timeout path tries to
stops the heartbeat thread, queue reg's delayed work, or release quiesces existing work, and races the callback body after handler drops the final configfs ref. unregister.
3. region_release() must drain 4. The callback or delayed work can
handler-visible o2net rx work outlive reg unless lifecycle code
before freeing reg. keeps the region non-armable and
drains the active-or-destroying o2net workqueue.
Validation reproduced this kernel report:
KASAN slab-use-after-free in __run_timers+0x22c/0x5b0
Write of size 8 Call trace: dump_stack_lvl+0x66/0xa0 print_report+0xce/0x630 __run_timers+0x22c/0x5b0 kasan_report+0xe0/0x110 _raw_spin_unlock_irqrestore+0x27/0x60 try_to_wake_up+0x191/0xf70 timer_expire_remote+0xae/0xf0 run_timer_softirq+0x19b/0x1a0 handle_softirqs+0x156/0x660 __irq_exit_rcu+0xc4/0x160 irq_exit_rcu+0xe/0x20 sysvec_apic_timer_interrupt+0x6c/0x80 asm_sysvec_apic_timer_interrupt+0x1a/0x20 Allocated by task stack: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 o2hb_heartbeat_group_make_item+0x3c/0x600
--- fs/ocfs2/cluster/heartbeat.c | 56 ++++++++++++++++--- fs/ocfs2/cluster/tcp.c | 105 ++++++++++++++++++++++++++++++----- fs/ocfs2/cluster/tcp.h | 1 + 3 files changed, 139 insertions(+), 23 deletions(-)
fs/ocfs2/cluster/heartbeat.c +48 -8
@@ -14,6 +14,7 @@#include <linux/file.h> #include <linux/kthread.h> #include <linux/configfs.h> +#include <linux/mutex.h> #include <linux/random.h> #include <linux/crc32.h> #include <linux/time.h>
@@ -265,6 +266,9 @@ struct o2hb_region {/* Message key for negotiate timeout message. */ unsigned int hr_key;struct list_head hr_handler_list; +/* Serializes timeout arming against failed-start and teardown. */ +struct mutex hr_arming_mutex; +bool hr_stopping;/* last hb status, 0 for success, other value for error. */ int hr_last_hb_status;
@@ -329,9 +333,14 @@ static void o2hb_write_timeout(struct work_struct *work)static void o2hb_arm_timeout (struct o2hb_region *reg) { +mutex_lock (®->hr_arming_mutex); + +if (reg->hr_stopping) + goto out_unlock; +/* Arm writeout only after thread reaches steady state */ if (atomic_read (®->hr_steady_iterations) !=0 ) -return ; + goto out_unlock;mlog (ML_HEARTBEAT ,"Queue write timeout for %u ms\n" ,O2HB_MAX_WRITE_TIMEOUT_MS );
@@ -350,6 +359,18 @@ static void o2hb_arm_timeout(struct o2hb_region *reg)schedule_delayed_work (®->hr_nego_timeout_work,msecs_to_jiffies (O2HB_NEGO_TIMEOUT_MS ));bitmap_zero (reg->hr_nego_node_bitmap,O2NM_MAX_NODES ); + +out_unlock: +mutex_unlock (®->hr_arming_mutex); +} + +static void o2hb_queue_nego_timeout (struct o2hb_region *reg, +unsigned long delay) +{ +mutex_lock (®->hr_arming_mutex); +if (!reg->hr_stopping) +schedule_delayed_work (®->hr_nego_timeout_work, delay); +mutex_unlock (®->hr_arming_mutex); }static void o2hb_disarm_timeout (struct o2hb_region *reg)
@@ -358,6 +379,19 @@ static void o2hb_disarm_timeout(struct o2hb_region *reg)cancel_delayed_work_sync (®->hr_nego_timeout_work); } +static void o2hb_set_region_stopping (struct o2hb_region *reg,bool stopping) +{ +mutex_lock (®->hr_arming_mutex); + reg->hr_stopping = stopping; +mutex_unlock (®->hr_arming_mutex); +} + +static void o2hb_quiesce_timeout (struct o2hb_region *reg) +{ +o2hb_set_region_stopping (reg, true); +o2hb_disarm_timeout (reg); +} +static int o2hb_send_nego_msg (int key,int type,u8 target,u8 node_num) {struct o2hb_nego_msg msg;
@@ -407,8 +441,7 @@ static void o2hb_nego_timeout(struct work_struct *work)/* check negotiate bitmap every second to do timeout * approve decision. */ -schedule_delayed_work (®->hr_nego_timeout_work, -msecs_to_jiffies (1000 )); +o2hb_queue_nego_timeout (reg,msecs_to_jiffies (1000 ));return ; }
@@ -1565,6 +1598,8 @@ static void o2hb_region_release(struct config_item *item)mlog (ML_HEARTBEAT ,"hb region release (%pg)\n" ,reg_bdev (reg)); +o2hb_quiesce_timeout (reg); +o2net_unregister_and_flush_handler_list (®->hr_handler_list);o2hb_unmap_slot_data (reg);if (reg->hr_bdev_file)
@@ -1580,7 +1615,6 @@ static void o2hb_region_release(struct config_item *item)list_del (®->hr_all_item);spin_unlock (&o2hb_live_lock); -o2net_unregister_handler_list (®->hr_handler_list);kfree (reg); }
@@ -1896,9 +1930,6 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, goto out; } -INIT_DELAYED_WORK (®->hr_write_timeout_work, o2hb_write_timeout); -INIT_DELAYED_WORK (®->hr_nego_timeout_work, o2hb_nego_timeout); -/* * A node is considered live after it has beat LIVE_THRESHOLD * times. We're not steady until we've given them a chance
@@ -1918,6 +1949,7 @@ static ssize_t o2hb_region_dev_store(struct config_item *item,atomic_set (®->hr_steady_iterations, live_threshold);/* unsteady_iterations is triple the steady_iterations */ atomic_set (®->hr_unsteady_iterations, (live_threshold *3 )); +o2hb_set_region_stopping (reg, false); hb_task =kthread_run (o2hb_thread, reg,"o2hb-%s" , reg->hr_item.ci_name);
@@ -1967,6 +1999,8 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, out:if (ret <0 ) { +o2hb_quiesce_timeout (reg); +spin_lock (&o2hb_live_lock); hb_task = reg->hr_task; reg->hr_task =NULL ;
@@ -2108,6 +2142,10 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g*/ reg->hr_key =crc32_le (reg->hr_region_num +O2NM_MAX_REGIONS , name,strlen (name)); +mutex_init (®->hr_arming_mutex); + reg->hr_stopping = true; +INIT_DELAYED_WORK (®->hr_write_timeout_work, o2hb_write_timeout); +INIT_DELAYED_WORK (®->hr_nego_timeout_work, o2hb_nego_timeout);INIT_LIST_HEAD (®->hr_handler_list); ret = o2net_register_handler(O2HB_NEGO_TIMEOUT_MSG, reg->hr_key, sizeof(struct o2hb_nego_msg),
@@ -2128,7 +2166,7 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *greturn ®->hr_item; unregister_handler: -o2net_unregister_handler_list (®->hr_handler_list); +o2net_unregister_and_flush_handler_list (®->hr_handler_list); remove_item:spin_lock (&o2hb_live_lock);list_del (®->hr_all_item);
@@ -2147,6 +2185,8 @@ static void o2hb_heartbeat_group_drop_item(struct config_group *group,struct o2hb_region *reg =to_o2hb_region (item);int quorum_region =0 ; +o2hb_quiesce_timeout (reg); +/* stop the thread when the user removes the region dir */ spin_lock (&o2hb_live_lock); hb_task = reg->hr_task;
fs/ocfs2/cluster/tcp.c +90 -15
162 lines not on this page · raw message
fs/ocfs2/cluster/tcp.h +1 -0
@@ -89,6 +89,7 @@ int o2net_register_handler(u32 msg_type, u32 key, u32 max_len,o2net_post_msg_handler_func *post_func, struct list_head *unreg_list);void o2net_unregister_handler_list (struct list_head *list); +void o2net_unregister_and_flush_handler_list (struct list_head *list);void o2net_fill_node_map (unsigned long *map,unsigned bytes);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 659/869 ARM: 9481/2: breakpoint: CFI breakpoints only on demand
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linus Walleij <[email protected]>
[ Upstream commit 8ed9bff906cf8036531d1559f10e82733a52b41f ]
This removes the stub hw_breakpoint_cfi_handler() from ARM, making it not steal breakpoint type 0x03 (ARM_ENTRY_CFI_BREAKPOINT) unless CFI is actively used in the kernel.
When not instrumenting with CFI, or when a breakpoint is issued in userspace, we fall through to return 1 from hw_breakpoint_pending() "unhandled fault" so userspace can make use of this breakpoint.
Tested with LKDTM and this command line:
echo CFI_FORWARD_PROTO > /sys/kernel/debug/provoke-crash/DIRECT still works as expected.
--- arch/arm/kernel/hw_breakpoint.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
arch/arm/kernel/hw_breakpoint.c +6 -5
@@ -929,10 +929,6 @@ static void hw_breakpoint_cfi_handler(struct pt_regs *regs) break; } } -#else -static void hw_breakpoint_cfi_handler (struct pt_regs *regs) -{ -}#endif /*
@@ -964,9 +960,14 @@ static int hw_breakpoint_pending(unsigned long addr, unsigned int fsr,case ARM_ENTRY_SYNC_WATCHPOINT :watchpoint_handler (addr, fsr, regs);break ; +#ifdef CONFIG_CFI case ARM_ENTRY_CFI_BREAKPOINT : -hw_breakpoint_cfi_handler (regs); +if (user_mode (regs)) + ret =1 ;/* Don't handle userspace BKPT */ +else +hw_breakpoint_cfi_handler (regs);break ; +#endif default : ret =1 ;/* Unhandled fault. */ }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 660/869 thermal: hwmon: Remove hwmon class device along with its parent
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
[ Upstream commit 2b57e24d34b2dfc43c81942bb359d6315bf302fb ]
The current code creates one hwmon device per thermal zone type and that device is registered under the first thermal zone of the given type.
That turns out to be problematic when the thermal zone holding the hwmon device is removed.
For example, say that there are two ACPI thermal zones on a system
/sys/devices/virtual/thermal/thermal_zone0/
/sys/devices/virtual/thermal/thermal_zone1/
The current code registers a hwmon class device for thermal_zone0 only:
/sys/devices/virtual/thermal/thermal_zone0/hwmon0/
because the type is "acpitz" for both of them, but it adds a sysfs attribute that belongs to thermal_zone1 under it:
/sys/devices/virtual/thermal/thermal_zone0/hwmon0/temp2_input
There is also
/sys/devices/virtual/thermal/thermal_zone0/hwmon0/temp1_input
which belongs to thermal_zone0.
When thermal_zone0 is removed, say because the ACPI thermal driver is unbound from the underlying platform device, thermal_remove_hwmon_sysfs() skips the removal of hwmon0 because of the temp2_input attribute belonging to thermal_zone1 which effectively prevents thermal_zone0 removal from making progress.
Address this by making thermal_remove_hwmon_sysfs() remove the entire hwmon class device interface for the given thermal zone type when the thermal zone device holding it is removed.
To prevent races with thermal_add_hwmon_sysfs() that may interfere with this, carry out the entire addition and removal of hwmon sysfs interfaces for thermal zones under thermal_hwmon_list_lock.
Also adjust the layout of the labels in thermal_add_hwmon_sysfs() to the current kernel coding style to align with the new "unlock" label.
--- drivers/thermal/thermal_hwmon.c | 87 +++++++++++++-------------------- 1 file changed, 34 insertions(+), 53 deletions(-)
drivers/thermal/thermal_hwmon.c +34 -53
@@ -98,34 +98,12 @@ thermal_hwmon_lookup_by_type(const struct thermal_zone_device *tz)struct thermal_hwmon_device *hwmon;char type[THERMAL_NAME_LENGTH ]; -mutex_lock (&thermal_hwmon_list_lock);list_for_each_entry (hwmon, &thermal_hwmon_list, node) {strcpy (type, tz->type);strreplace (type,'-' ,'_' ); -if (!strcmp (hwmon->type, type)) { -mutex_unlock (&thermal_hwmon_list_lock); +if (!strcmp (hwmon->type, type))return hwmon; - } } -mutex_unlock (&thermal_hwmon_list_lock); - -return NULL ; -} - -/* Find the temperature input matching a given thermal zone */ -static struct thermal_hwmon_temp * -thermal_hwmon_lookup_temp (const struct thermal_hwmon_device *hwmon, -const struct thermal_zone_device *tz) -{ -struct thermal_hwmon_temp *temp; - -mutex_lock (&thermal_hwmon_list_lock); -list_for_each_entry (temp, &hwmon->tz_list, hwmon_node) -if (temp->tz == tz) { -mutex_unlock (&thermal_hwmon_list_lock); -return temp; - } -mutex_unlock (&thermal_hwmon_list_lock);return NULL ; }
@@ -141,7 +119,9 @@ int thermal_add_hwmon_sysfs(struct thermal_zone_device *tz)struct thermal_hwmon_device *hwmon;struct thermal_hwmon_temp *temp;int new_hwmon_device =1 ; -int result; +int result =0 ; + +mutex_lock (&thermal_hwmon_list_lock); hwmon =thermal_hwmon_lookup_by_type (tz);if (hwmon) {
@@ -150,8 +130,10 @@ int thermal_add_hwmon_sysfs(struct thermal_zone_device *tz) } hwmon =kzalloc (sizeof (*hwmon),GFP_KERNEL ); -if (!hwmon) -return -ENOMEM ; +if (!hwmon) { + result = -ENOMEM ; + goto unlock; + }INIT_LIST_HEAD (&hwmon->tz_list);strscpy (hwmon->type, tz->type,THERMAL_NAME_LENGTH );
@@ -199,24 +181,24 @@ int thermal_add_hwmon_sysfs(struct thermal_zone_device *tz) temp->temp_crit_present = true; } -mutex_lock (&thermal_hwmon_list_lock);if (new_hwmon_device)list_add_tail (&hwmon->node, &thermal_hwmon_list);list_add_tail (&temp->hwmon_node, &hwmon->tz_list); -mutex_unlock (&thermal_hwmon_list_lock); -return 0 ; + goto unlock; - unregister_input: +unregister_input:device_remove_file (hwmon->device, &temp->temp_input.attr); - free_temp_mem: +free_temp_mem:kfree (temp); - unregister_name: +unregister_name:if (new_hwmon_device)hwmon_device_unregister (hwmon->device); - free_mem: +free_mem:if (new_hwmon_device)kfree (hwmon); +unlock: +mutex_unlock (&thermal_hwmon_list_lock);return result; }
@@ -224,8 +206,11 @@ EXPORT_SYMBOL_GPL(thermal_add_hwmon_sysfs);void thermal_remove_hwmon_sysfs (struct thermal_zone_device *tz) { +struct thermal_hwmon_temp *temp, *entry;struct thermal_hwmon_device *hwmon; -struct thermal_hwmon_temp *temp; +bool unregister; + +guard (mutex)(&thermal_hwmon_list_lock); hwmon =thermal_hwmon_lookup_by_type (tz);if (unlikely (!hwmon)) {
@@ -234,29 +219,25 @@ void thermal_remove_hwmon_sysfs(struct thermal_zone_device *tz)return ; } - temp =thermal_hwmon_lookup_temp (hwmon, tz); -if (unlikely (!temp)) { -/* Should never happen... */ -dev_dbg (&tz->device,"temperature input lookup failed!\n" ); -return ; - } + unregister = hwmon->device->parent == &tz->device; -device_remove_file (hwmon->device, &temp->temp_input.attr); -if (temp->temp_crit_present) -device_remove_file (hwmon->device, &temp->temp_crit.attr); +list_for_each_entry_safe_reverse (temp, entry, &hwmon->tz_list, hwmon_node) { +if (!unregister && temp->tz != tz) +continue ; -mutex_lock (&thermal_hwmon_list_lock); -list_del (&temp->hwmon_node); -kfree (temp); -if (!list_empty (&hwmon->tz_list)) { -mutex_unlock (&thermal_hwmon_list_lock); -return ; +device_remove_file (hwmon->device, &temp->temp_input.attr); +if (temp->temp_crit_present) +device_remove_file (hwmon->device, &temp->temp_crit.attr); + +list_del (&temp->hwmon_node); +kfree (temp); } -list_del (&hwmon->node); -mutex_unlock (&thermal_hwmon_list_lock); -hwmon_device_unregister (hwmon->device); -kfree (hwmon); +if (unregister) { +list_del (&hwmon->node); +hwmon_device_unregister (hwmon->device); +kfree (hwmon); + } }EXPORT_SYMBOL_GPL (thermal_remove_hwmon_sysfs);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 661/869 ocfs2: validate inline xattrs during inode block validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 8914a3330b72378136c2c02d6328a826f6abdad7 ]
Patch series "ocfs2: validate xattr entry bounds", v7.
This series validates OCFS2 xattr entry name/value bounds when xattr metadata is read and validated, before getxattr() or listxattr() can walk out-of-range entry arrays or offsets from corrupted metadata.
This patch (of 2):
ocfs2_validate_inode_block() verifies a dinode before OCFS2 users walk metadata from it, but inline xattr metadata is still checked only in operation-specific consumers. The existing ibody lookup helper validates inline header placement and entry count, but inode block validation does not reject entry name/value bounds.
Add a flat xattr entry validator and call it from inode block validation for inline xattrs. Keep the operation paths on their existing header/count lookup checks; the full entry bounds check now runs when the inode block is validated at read time.
Reject corrupted inline xattr metadata before ocfs2_xattr_ibody_get() or listxattr() can walk past the inline storage.
Validation reproduced this kernel report:
BUG: KASAN: use-after-free in ocfs2_xattr_find_entry+0x5a/0x170 Read of size 2 at addr ffff8881242a2000 by task python3/529 Call Trace: dump_stack_lvl+0x66/0xa0 print_report+0xce/0x630 kasan_report+0xe0/0x110 ocfs2_xattr_find_entry+0x5a/0x170 ocfs2_xattr_get_nolock+0x20a/0x820 ocfs2_xattr_get+0x10c/0x1e0 __vfs_getxattr+0xe2/0x130 vfs_getxattr+0x185/0x1b0
--- fs/ocfs2/inode.c | 4 ++ fs/ocfs2/xattr.c | 118 +++++++++++++++++++++++++++++++++++++++++++++++ fs/ocfs2/xattr.h | 2 + 3 files changed, 124 insertions(+)
fs/ocfs2/inode.c +4 -0
@@ -1562,6 +1562,10 @@ int ocfs2_validate_inode_block(struct super_block *sb, goto bail; } + rc =ocfs2_validate_inode_xattr (sb, bh->b_blocknr, di); +if (rc) + goto bail; +if (le16_to_cpu (di->i_dyn_features) &OCFS2_INLINE_DATA_FL ) {struct ocfs2_inline_data *data = &di->id2.i_data;
fs/ocfs2/xattr.c +118 -0
124 lines not on this page · raw message
fs/ocfs2/xattr.h +2 -0
@@ -43,6 +43,8 @@ int ocfs2_xattr_set_handle(handle_t *, struct inode *, struct buffer_head *, struct ocfs2_alloc_context *);int ocfs2_has_inline_xattr_value_outside (struct inode *inode,struct ocfs2_dinode *di); +int ocfs2_validate_inode_xattr (struct super_block *sb,u64 blkno, +struct ocfs2_dinode *di);int ocfs2_xattr_remove (struct inode *,struct buffer_head *); int ocfs2_init_security_get(struct inode *, struct inode *, const struct qstr *,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 662/869 ublk: check import_ubuf() return value
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Caleb Sander Mateos <[email protected]>
[ Upstream commit 3831568792af75b6523fa93bb91560e29189cf55 ]
import_ubuf() can fail if the address range (provided by the userspace ublk server) is outside the allowed user address space. Return that 0 bytes were copied if import_ubuf() fails rather than passing an uninitialized struct iov_iter to ublk_copy_user_pages().
--- drivers/block/ublk_drv.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/block/ublk_drv.c +8 -2
@@ -915,7 +915,10 @@ static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,struct iov_iter iter;const int dir =ITER_DEST ; -import_ubuf (dir,u64_to_user_ptr (io->addr), rq_bytes, &iter); +if (import_ubuf (dir,u64_to_user_ptr (io->addr), rq_bytes, + &iter) <0 ) +return 0 ; +return ublk_copy_user_pages (req,0 , &iter, dir); }return rq_bytes;
@@ -936,7 +939,10 @@ static int ublk_unmap_io(const struct ublk_queue *ubq,WARN_ON_ONCE (io->res > rq_bytes); -import_ubuf (dir,u64_to_user_ptr (io->addr), io->res, &iter); +if (import_ubuf (dir,u64_to_user_ptr (io->addr), io->res, + &iter) <0 ) +return 0 ; +return ublk_copy_user_pages (req,0 , &iter, dir); }return rq_bytes;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 663/869 blk-cgroup: fix race between policy activation and blkg destruction
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zheng Qixing <[email protected]>
[ Upstream commit 5313d4d41739b0cb63000747c97bb1217ac45f3e ]
When switching an IO scheduler on a block device, blkcg_activate_policy() allocates blkg_policy_data (pd) for all blkgs attached to the queue. However, blkcg_activate_policy() may race with concurrent blkcg deletion, leading to use-after-free and memory leak issues.
The use-after-free occurs in the following race:
T1 (blkcg_activate_policy):
- Successfully allocates pd for blkg1 (loop0->queue, blkcgA)
- Fails to allocate pd for blkg2 (loop0->queue, blkcgB)
- Enters the enomem rollback path to release blkg1 resources
T2 (blkcg deletion):
- blkcgA is deleted concurrently
- blkg1 is freed via blkg_free_workfn()
- blkg1->pd is freed
T1 (continued):
- Rollback path accesses blkg1->pd->online after pd is freed
- Triggers use-after-free
In addition, blkg_free_workfn() frees pd before removing the blkg from q->blkg_list. This allows blkcg_activate_policy() to allocate a new pd for a blkg that is being destroyed, leaving the newly allocated pd unreachable when the blkg is finally freed.
Fix these races by extending blkcg_mutex coverage to serialize blkcg_activate_policy() rollback and blkg destruction, ensuring pd lifecycle is synchronized with blkg list visibility.
--- block/blk-cgroup.c | 3 +++ 1 file changed, 3 insertions(+)
block/blk-cgroup.c +3 -0
@@ -1561,6 +1561,8 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)if (queue_is_mq (q))blk_mq_freeze_queue (q); + +mutex_lock (&q->blkcg_mutex); retry:spin_lock_irq (&q->queue_lock);
@@ -1625,6 +1627,7 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)spin_unlock_irq (&q->queue_lock); out: +mutex_unlock (&q->blkcg_mutex);if (queue_is_mq (q))blk_mq_unfreeze_queue (q);if (pinned_blkg)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 664/869 HID: steam: Reject short reads
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit 33ff7b49c38b39b1f3d27db508ac0720fb25c08a ]
Steam Controller FEATURE reports encode the size of the message in the message itself. Previously we were trusting that the size reported matched the size we actually read, leading to a potential issue with short reads. Instead, we should actually verify the length of the read.
--- drivers/hid/hid-steam.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
drivers/hid/hid-steam.c +30 -3
@@ -324,6 +324,13 @@ static int steam_recv_report(struct steam_device *steam,u8 *buf;int ret; +/* +* All reports start with a two byte header. +* We must read at least two bytes to get a sensible output. +*/ +if (size <2 ) +return -EINVAL ; + r = steam->hdev->report_enum[HID_FEATURE_REPORT ].report_id_hash[0 ];if (!r) {hid_err (steam->hdev,"No HID_FEATURE_REPORT submitted - nothing to read\n" );
@@ -346,10 +353,30 @@ static int steam_recv_report(struct steam_device *steam, ret =hid_hw_raw_request (steam->hdev,0x00 , buf,hid_report_len (r) +1 ,HID_FEATURE_REPORT ,HID_REQ_GET_REPORT ); -if (ret >0 ) -memcpy (data, buf +1 ,min (size, ret -1 )); +if (ret >0 ) { +/* Remove the report ID from the return buffer */ + ret--; + size =min (size, ret); +memcpy (data, buf +1 , size); + }kfree (buf); -return ret; + +if (ret <0 ) { +hid_err (steam->hdev,"%s: error %d\n" , __func__, ret); +return ret; + } + +if (ret <2 ) { +hid_err (steam->hdev,"%s: reply too short\n" , __func__); +return -EPROTO ; + } +if (ret < data[1 ] +2 ) { +hid_err (steam->hdev,"%s: expected %u bytes, read %i\n" , + __func__, data[1 ] +2 , ret); +return -EPROTO ; + } +hid_dbg (steam->hdev,"Received report %*ph\n" , size, data); +return size; } static int steam_send_report(struct steam_device *steam,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 665/869 HID: logitech-hidpp: Fix FF device cleanup on init failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Haoxiang Li <[email protected]>
[ Upstream commit dd5be4d9ce2dfc4d4a4527ef7d31d21a78e3cdac ]
hidpp_ff_init() creates the input force-feedback device with input_ff_create(), then allocates the HID++ FF private data, effect ID array, and workqueue.
If any of those allocations fail after input_ff_create() succeeds, the function returns an error without destroying the FF device. Add an unwind path that frees the private allocations made by hidpp_ff_init() and calls input_ff_destroy() for failures after input_ff_create() succeeds.
--- drivers/hid/hid-logitech-hidpp.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-)
drivers/hid/hid-logitech-hidpp.c +16 -7
@@ -2878,18 +2878,19 @@ static int hidpp_ff_init(struct hidpp_device *hidpp,* ownership to FF core */ data =kmemdup (data,sizeof (*data),GFP_KERNEL ); -if (!data) -return -ENOMEM ; +if (!data) { + error = -ENOMEM ; + goto err_destroy_ff; + } data->effect_ids =kcalloc (num_slots,sizeof (int ),GFP_KERNEL );if (!data->effect_ids) { -kfree (data); -return -ENOMEM ; + error = -ENOMEM ; + goto err_free_data; } data->wq =create_singlethread_workqueue ("hidpp-ff-sendqueue" );if (!data->wq) { -kfree (data->effect_ids); -kfree (data); -return -ENOMEM ; + error = -ENOMEM ; + goto err_free_effect_ids; } data->hidpp = hidpp;
@@ -2919,6 +2920,14 @@ static int hidpp_ff_init(struct hidpp_device *hidpp, version);return 0 ; + +err_free_effect_ids: +kfree (data->effect_ids); +err_free_data: +kfree (data); +err_destroy_ff: +input_ff_destroy (dev); +return error; }/* ************************************************************************** */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 666/869 tty: skip cdev_del() when no cdev is registered
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit c3b5623fd97648f2747444aa8932ae604662df93 ]
TTY device registration can fail before a cdev is allocated. Serial core keeps the port so setserial can still use it, and later removal passes the NULL cdev slot to cdev_del(), causing a NULL-pointer dereference.
Only delete the cdev when the slot is not NULL.
--- drivers/tty/tty_io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/tty/tty_io.c +1 -1
@@ -3341,7 +3341,7 @@ EXPORT_SYMBOL_GPL(tty_register_device_attr);void tty_unregister_device (struct tty_driver *driver,unsigned index) {device_destroy (&tty_class,MKDEV (driver->major, driver->minor_start) + index); -if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC )) { +if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC ) && driver->cdevs[index]) {cdev_del (driver->cdevs[index]); driver->cdevs[index] =NULL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 667/869 serial: core: clear freed pointers on uart_register_driver() failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit 61a2fb25551be0375bc16ef2a70c987dfca26183 ]
uart_register_driver() leaves drv->state pointing to freed memory when tty_alloc_driver() fails. If tty_register_driver() fails, drv->tty_driver also retains a pointer after its reference is dropped.
Drivers that use drv->state as an "already registered" flag can then skip registration on the next probe and pass the freed state to uart_add_one_port().
This issue was found with failslab on QEMU's raspi1ap board by failing registration and binding the PL011 port again.
Clear both pointers on their failure paths, as uart_unregister_driver() already does.
--- drivers/tty/serial/serial_core.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/tty/serial/serial_core.c +2 -0
@@ -2861,8 +2861,10 @@ int uart_register_driver(struct uart_driver *drv)for (i =0 ; i < drv->nr; i++)tty_port_destroy (&drv->state[i].port);tty_driver_kref_put (normal); + drv->tty_driver =NULL ; out_kfree:kfree (drv->state); + drv->state =NULL ; out:return retval; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 668/869 serial: core: do fallible allocations before the console can be registered
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit 1a0e4fbce5d9c1bc179a35a2fd9ed142664299e3 ]
serial_core_add_one_port() allocates uport->tty_groups after uart_configure_port(), which may register the console. If the allocation fails, the driver unwinds the port while its console remains registered. The earlier uport->name allocation has a related failure path that leaves state->uart_port linked to a port being freed.
Failslab reproduced a NULL dereference in PL011 console output and a KASAN use-after-free in i.MX console output after failed binds.
Allocate the name and tty_groups before linking the port and configuring it. Reserve space for the optional driver attribute group because config_port() may populate uport->attr_group during configuration.
--- drivers/tty/serial/serial_core.c | 37 ++++++++++++++++---------------- 1 file changed, 19 insertions(+), 18 deletions(-)
drivers/tty/serial/serial_core.c +19 -18
@@ -3144,7 +3144,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *ustruct tty_port *port;int ret =0 ;struct device *tty_dev; -int num_groups;if (uport->line >= drv->nr)return -EINVAL ;
@@ -3158,6 +3157,25 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u goto out; } + uport->name =kasprintf (GFP_KERNEL ,"%s%u" , drv->dev_name, + drv->tty_driver->name_base + uport->line); +if (!uport->name) { + ret = -ENOMEM ; + goto out; + } + +/* +* uart_configure_port() may set uport->attr_group and register the +* console. Allocate room for both groups and a NULL terminator first. +*/ + uport->tty_groups =kcalloc (3 ,sizeof (*uport->tty_groups),GFP_KERNEL ); +if (!uport->tty_groups) { +kfree (uport->name); + ret = -ENOMEM ; + goto out; + } + uport->tty_groups[0 ] = &tty_dev_attr_group; +/* Link the port to the driver state table and vice versa */ atomic_set (&state->refcount,1 );init_waitqueue_head (&state->remove_wait);
@@ -3174,12 +3192,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u state->pm_state =UART_PM_STATE_UNDEFINED ;uart_port_set_cons (uport, drv->cons); uport->minor = drv->tty_driver->minor_start + uport->line; - uport->name =kasprintf (GFP_KERNEL ,"%s%u" , drv->dev_name, - drv->tty_driver->name_base + uport->line); -if (!uport->name) { - ret = -ENOMEM ; - goto out; - }if (uport->cons && uport->dev)of_console_check (uport->dev->of_node, uport->cons->name, uport->line);
@@ -3189,17 +3201,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u port->console =uart_console (uport); - num_groups =2 ; -if (uport->attr_group) - num_groups++; - - uport->tty_groups =kcalloc (num_groups,sizeof (*uport->tty_groups), -GFP_KERNEL ); -if (!uport->tty_groups) { - ret = -ENOMEM ; - goto out; - } - uport->tty_groups[0 ] = &tty_dev_attr_group;if (uport->attr_group) uport->tty_groups[1 ] = uport->attr_group;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 669/869 wifi: cfg80211: stop PMSR before P2P and NAN teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
[ Upstream commit 6c5fc504d0d6934132637aa3db4b9b58148eaa78 ]
PMSR request teardown must abort active measurements while the wireless_dev is still present in the driver. cfg80211_leave_locked() and cfg80211_stop_pd() already do this before invoking the driver's stop callback, but cfg80211_stop_p2p_device() and cfg80211_stop_nan() do not.
Those helpers are also called directly by nl80211, rfkill shutdown, and wireless_dev unregister paths. If one of these paths stops a P2P device or NAN interface with a pending request, it removes the mac80211 subinterface from the driver first. Subsequent request cleanup cannot reach the lower driver's abort callback, but cfg80211 frees the request regardless. Driver state can then retain a stale request and use it when it later reports a result.
Call cfg80211_pmsr_wdev_down() before stopping the P2P device or NAN interface. This keeps lower-driver request state and cfg80211 request ownership in sync for all of the helpers' callers.
--- net/wireless/core.c | 3 +++ 1 file changed, 3 insertions(+)
net/wireless/core.c +3 -0
@@ -237,6 +237,7 @@ void cfg80211_stop_p2p_device(struct cfg80211_registered_device *rdev,if (!wdev_running (wdev))return ; +cfg80211_pmsr_wdev_down (wdev);rdev_stop_p2p_device (rdev, wdev); wdev->is_running = false;
@@ -262,6 +263,8 @@ void cfg80211_stop_nan(struct cfg80211_registered_device *rdev,if (!wdev_running (wdev))return ; +cfg80211_pmsr_wdev_down (wdev); +rdev_stop_nan (rdev, wdev); wdev->is_running = false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 670/869 wifi: brcmfmac: fix P2P action frame handling without device vif
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jason Huang <[email protected]>
[ Upstream commit 1b1edb9ebed49099bdc924cef49a9aea8b552199 ]
Some P2P action frame paths assume the P2P device vif is always available. That is not true when userspace sends non-P2P public action frames through the primary interface, or when action-frame abort runs after the P2P device vif has not been created.
Fall back to the primary vif when aborting an action frame without a P2P device vif, and guard P2P device saved IE access before using it for peer channel search.
--- drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c +4 -0
@@ -1281,6 +1281,9 @@ static s32 brcmf_p2p_abort_action_frame(struct brcmf_cfg80211_info *cfg)brcmf_dbg (TRACE ,"Enter\n" ); vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE ].vif; +if (!vif) + vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY ].vif; + err =brcmf_fil_bsscfg_data_set (vif->ifp,"actframe_abort" , &int_val,sizeof (s32));if (err)
@@ -1817,6 +1820,7 @@ bool brcmf_p2p_send_action_frame(struct brcmf_if *ifp,/* validate channel and p2p ies */ if (config_af_params.search_channel &&IS_P2P_SOCIAL_CHANNEL (le32_to_cpu (af_params->channel)) && + p2p->bss_idx[P2PAPI_BSSCFG_DEVICE ].vif && p2p->bss_idx[P2PAPI_BSSCFG_DEVICE ].vif->saved_ie.probe_req_ie_len) { afx_hdl = &p2p->afx_hdl; afx_hdl->peer_listen_chan =le32_to_cpu (af_params->channel);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 671/869 wifi: nl80211: check link is beaconing for color change
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Berg <[email protected]>
[ Upstream commit 55308cee9c2196f39cd1ce8ee6c1fed9e12a00d4 ]
When trying to do a color change, validate that the link is beaconing first, to avoid calling the driver with an invalid link.
Stable-dep-of: 927ee844c47a ("wifi: nl80211: clean up color-change beacon data on errors")
--- net/wireless/nl80211.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
net/wireless/nl80211.c +4 -1
@@ -16171,6 +16171,10 @@ static int nl80211_color_change(struct sk_buff *skb, struct genl_info *info) params.count =nla_get_u8 (info->attrs[NL80211_ATTR_COLOR_CHANGE_COUNT ]); params.color =nla_get_u8 (info->attrs[NL80211_ATTR_COLOR_CHANGE_COLOR ]); + params.link_id =nl80211_link_id (info->attrs); +if (!wdev->links[params.link_id].ap.beacon_interval) +return -EINVAL ; + err =nl80211_parse_beacon (rdev, info->attrs, ¶ms.beacon_next, info->extack);if (err)
@@ -16236,7 +16240,6 @@ static int nl80211_color_change(struct sk_buff *skb, struct genl_info *info) params.counter_offset_presp = offset; } - params.link_id =nl80211_link_id (info->attrs); err =rdev_color_change (rdev, dev, ¶ms); out:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 672/869 wifi: nl80211: clean up color-change beacon data on errors
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
[ Upstream commit 927ee844c47ac2aef22c8f7a35f098ff576b398b ]
nl80211_color_change() calls nl80211_parse_beacon() for the beacon_next template, which can allocate params.beacon_next.mbssid_ies and .rnr_ies. A parsing failure returned directly instead of using the out: cleanup, leaking any allocations completed before the error.
Allocate the nested attribute table before parsing beacon_next. Its allocation failure can then return before beacon data exists, while a later parsing failure uses out: to release the parsed data.
--- net/wireless/nl80211.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
net/wireless/nl80211.c +5 -5
@@ -16175,15 +16175,15 @@ static int nl80211_color_change(struct sk_buff *skb, struct genl_info *info)if (!wdev->links[params.link_id].ap.beacon_interval)return -EINVAL ; - err =nl80211_parse_beacon (rdev, info->attrs, ¶ms.beacon_next, - info->extack); -if (err) -return err; - tb =kcalloc (NL80211_ATTR_MAX +1 ,sizeof (*tb),GFP_KERNEL );if (!tb)return -ENOMEM ; + err =nl80211_parse_beacon (rdev, info->attrs, ¶ms.beacon_next, + info->extack); +if (err) + goto out; + err =nla_parse_nested (tb,NL80211_ATTR_MAX , info->attrs[NL80211_ATTR_COLOR_CHANGE_ELEMS ], nl80211_policy, info->extack);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 673/869 arm64: ptrace: Keep orig_x0 in-sync with x0 on syscall entry
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Will Deacon <[email protected]>
[ Upstream commit 88b839ce497ccb1ff92f7ae742c78dd2937ba572 ]
Commit e057b9477232 ("arm64: syscall: Ensure saved x0 is kept in-sync with tracer updates") attempted to resolve a long-standing issue with syscall entry tracing, where a tracer is able to manipulate the first syscall argument without being subjected to seccomp or audit checking.
Unfortunately, that fix was incomplete [1], as it failed to update 'orig_x0' between a tracer updating x0 during a seccomp ptrace exit (SECCOMP_RET_TRACE) and the seccomp filter being re-evaluated.
Rather than add hooks to the core seccomp code, instead move the synchronisation code into the ptrace GPR and syscall setting code so that 'orig_x0' is kept up to date with x0 whenever we're stopped on the syscall entry path.
--- arch/arm64/kernel/ptrace.c | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+)
arch/arm64/kernel/ptrace.c +50 -0
@@ -559,6 +559,42 @@ static int gpr_get(struct task_struct *target,return membuf_write (&to, uregs,sizeof (*uregs)); } +static void update_syscall_orig_x0_after_ptrace (struct task_struct *target) +{ +struct pt_regs *regs =task_pt_regs (target); +struct kernel_siginfo *info = target->last_siginfo; + +/* +* Skip the update for NO_SYSCALL (set either by the user or the +* tracer), as regs[0] holds the return value (see the comment in +* el0_svc_common()) and can be unwound using syscall_rollback(). +*/ +if (regs->syscallno ==NO_SYSCALL ) +return ; + +/* We should only be called when target is in a ptrace stop */ +if (WARN_ON_ONCE (!info)) +return ; + +/* +* For compat tasks, orig_r0 is provided directly through GPR index +* 17. +*/ +if (is_compat_thread (task_thread_info (target))) +return ; + +/* +* Don't update orig_x0 for a syscall-exit-stop, as x0 now contains the +* return value of the system call. +*/ +if ((info->si_code & ~0x80 ) ==SIGTRAP && + target->ptrace_message ==PTRACE_EVENTMSG_SYSCALL_EXIT ) { +return ; + } + + regs->orig_x0 = regs->regs[0 ]; +} +static int gpr_set (struct task_struct *target,const struct user_regset *regset,unsigned int pos,unsigned int count,const void *kbuf,const void __user *ubuf)
@@ -574,6 +610,14 @@ static int gpr_set(struct task_struct *target, const struct user_regset *regset,return -EINVAL ;task_pt_regs (target)->user_regs = newregs; + +/* +* Keep orig_x0 authoritative so that seccomp (via +* syscall_get_arguments()), audit and the restart path all see the same +* first argument the syscall is dispatched with, even if it has been +* updated by a tracer. +*/ +update_syscall_orig_x0_after_ptrace (target);return 0 ; }
@@ -752,6 +796,12 @@ static int system_call_set(struct task_struct *target,return ret;task_pt_regs (target)->syscallno = syscallno; + +/* +* Re-sync orig_x0 in case the syscall number has been changed +* from NO_SYSCALL. +*/ +update_syscall_orig_x0_after_ptrace (target);return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 674/869 wifi: mt76: mt7996: do not attach hif2 WED when the main WED attach failed
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Fietkau <[email protected]>
[ Upstream commit 7c1924332e986019c6bcddf55c843361cccac73f ]
If the WED attach for the primary PCIe function fails, the probe path still attached wed_hif2 for the secondary function, leaving the device in an inconsistent half-WED configuration that crashes later. The hif2 call also re-enabled hwrro_mode, which the failed primary attach had just turned off.
Skip the hif2 WED setup when the primary WED device is not active.
--- drivers/net/wireless/mediatek/mt76/mt7996/mmio.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/net/wireless/mediatek/mt76/mt7996/mmio.c +3 -0
@@ -312,6 +312,9 @@ int mt7996_mmio_wed_init(struct mt7996_dev *dev, void *pdev_ptr,if (!wed_enable)return 0 ; +if (hif2 && !mtk_wed_device_active (&dev->mt76.mmio.wed)) +return 0 ; + dev->has_rro = true; hif1_ofs =MT_WFDMA0_PCIE1 (0 ) -MT_WFDMA0 (0 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 675/869 bpf: Reject >8 byte return values on return-reading trampoline paths
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yonghong Song <[email protected]>
[ Upstream commit c48796aa6c392cde93946e5d5a9a1f1b1cf72feb ]
btf_distill_func_proto() builds the function model used for the fentry/fexit/fmod_ret/fsession trampolines and struct_ops. It has accepted a 16-byte __int128 return value since the trampoline was
introduced: __get_type_size() returns the integer's type size, and the return-type check only rejected ret < 0.
But the BPF trampoline preserves only 8 bytes of the return value (RAX on x86, i.e. R0). For an attach type that reads the target's return value the second half (RDX / R3) is neither saved nor restored, so a program attached to a function returning a 16-byte value corrupts the value seen by the real caller and itself observes only half of it. struct_ops trampolines have the same limitation.
This affects the attach types that read the target's return value: fexit, fmod_ret and fsession (plus the _multi variants of fexit and fsession), and struct_ops. fentry/fentry_multi run before the target returns and are unaffected.
Reject a >8 byte return value for these attach types in bpf_check_attach_target() and bpf_check_attach_btf_id_multi(), and for struct_ops in bpf_struct_ops_desc_init().
--- kernel/bpf/bpf_struct_ops.c | 12 ++++++++++++ kernel/bpf/verifier.c | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+)
kernel/bpf/bpf_struct_ops.c +12 -0
@@ -422,6 +422,18 @@ int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc, goto errout; } +/* +* A >8 byte return value is passed back in a register pair, +* which the struct_ops trampoline does not preserve (only +* 8 bytes of the return value are saved and restored). +*/ +if (st_ops->func_models[i].ret_size >8 ) { +pr_warn ("func ptr %s in struct %s has a >8 byte return value, which is not supported\n" , + mname, st_ops->name); + err = -EOPNOTSUPP ; + goto errout; + } + stub_func_addr = *(void **)(st_ops->cfi_stubs + moff); err = prepare_arg_info(btf, st_ops->name, mname, func_proto, stub_func_addr,
kernel/bpf/verifier.c +19 -0
@@ -22419,6 +22419,17 @@ static int check_non_sleepable_error_inject(u32 btf_id)return btf_id_set_contains (&btf_non_sleepable_error_inject, btf_id); } +static bool attach_uses_trampoline_retval (enum bpf_attach_type type) +{ +switch (type) { +case BPF_MODIFY_RETURN : +case BPF_TRACE_FEXIT : +return true; +default : +return false; + } +} + int bpf_check_attach_target(struct bpf_verifier_log *log, const struct bpf_prog *prog, const struct bpf_prog *tgt_prog,
@@ -22653,6 +22664,14 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,if (ret <0 )return ret; +if (tgt_info->fmodel.ret_size >8 && +attach_uses_trampoline_retval (prog->expected_attach_type)) { +bpf_log (log, +"Attach to function %s with a >8 byte return value is not supported for this attach type\n" , + tname); +return -EOPNOTSUPP ; + } +if (tgt_prog) {if (subprog ==0 ) addr = (long ) tgt_prog->bpf_func;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 676/869 drm/msm: dont tear down KMS twice when KMS init fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dmitry Baryshkov <[email protected]>
[ Upstream commit 93c125e4ea98fb25f927ba5a334d85845127d667 ]
When priv->kms_init() (mdp4_kms_init() / mdp5_kms_init()) fails partway through, both display drivers already tear their KMS state down via mdp4_destroy() / mdp5_kms_destroy() before returning the error. The common error path in msm_drm_init() then runs msm_drm_uninit() -> msm_drm_kms_uninit(), which tries to destroy the very same KMS a second time, which causes a use-after-free crash.
Bring MDP4/MDP5 in line with the DPU driver whose dpu_kms_init() doesn't perform error cleanup on the failure. Let the common path own the cleanup, instead of freeing the KMS from their error paths.
The crash trace for the reference:
__lock_acquire from lock_acquire (kernel/locking/lockdep.c:5906 kernel/locking/lockdep.c:5863) lock_acquire from touch_wq_lockdep_map (kernel/workqueue.c:4094 (discriminator 1)) touch_wq_lockdep_map from __flush_workqueue (kernel/workqueue.c:4136)
__flush_workqueue from msm_drm_kms_uninit (drivers/gpu/drm/msm/msm_kms.c:243 (discriminator 33)) msm_drm_kms_uninit from msm_drm_uninit (drivers/gpu/drm/msm/msm_drv.c:93)
msm_drm_uninit from msm_drm_init (drivers/gpu/drm/msm/msm_drv.c:184)
msm_drm_init from try_to_bring_up_aggregate_device (drivers/base/component.c:249 drivers/base/component.c:227) try_to_bring_up_aggregate_device from __component_add (drivers/base/component.c:269 drivers/base/component.c:748) __component_add from dsi_host_attach (drivers/gpu/drm/msm/dsi/dsi_host.c:1739)
dsi_host_attach from mipi_dsi_attach (drivers/gpu/drm/drm_mipi_dsi.c:383)
mipi_dsi_attach from sharp_nt_panel_probe (drivers/gpu/drm/panel/panel-sharp-ls043t1le01.c:247)
Patchwork: https://patchwork.freedesktop.org/patch/742068/
--- drivers/gpu/drm/msm/disp/mdp4/mdp4_kms.c | 24 +++++++++--------------- drivers/gpu/drm/msm/disp/mdp5/mdp5_kms.c | 11 +++-------- 2 files changed, 12 insertions(+), 23 deletions(-)
drivers/gpu/drm/msm/disp/mdp4/mdp4_kms.c +9 -15
@@ -391,7 +391,7 @@ static int mdp4_kms_init(struct drm_device *dev) ret =mdp_kms_init (&mdp4_kms->base, &kms_funcs);if (ret) {DRM_DEV_ERROR (dev->dev,"failed to init kms\n" ); - goto fail; +return ret; } kms = priv->kms;
@@ -402,7 +402,7 @@ static int mdp4_kms_init(struct drm_device *dev) ret =regulator_enable (mdp4_kms->vdd);if (ret) {DRM_DEV_ERROR (dev->dev,"failed to enable regulator vdd: %d\n" , ret); - goto fail; +return ret; } }
@@ -414,7 +414,7 @@ static int mdp4_kms_init(struct drm_device *dev)DRM_DEV_ERROR (dev->dev,"unexpected MDP version: v%d.%d\n" , major, minor); ret = -ENXIO ; - goto fail; +return ret; } mdp4_kms->rev = minor;
@@ -423,7 +423,7 @@ static int mdp4_kms_init(struct drm_device *dev)if (!mdp4_kms->lut_clk) {DRM_DEV_ERROR (dev->dev,"failed to get lut_clk\n" ); ret = -ENODEV ; - goto fail; +return ret; }clk_set_rate (mdp4_kms->lut_clk, max_clk); }
@@ -445,7 +445,7 @@ static int mdp4_kms_init(struct drm_device *dev) mmu =msm_iommu_new (&pdev->dev,0 );if (IS_ERR (mmu)) { ret =PTR_ERR (mmu); - goto fail; +return ret; }else if (!mmu) {DRM_DEV_INFO (dev->dev,"no iommu, fallback to phys " "contig buffers for scanout\n" );
@@ -458,7 +458,7 @@ static int mdp4_kms_init(struct drm_device *dev)if (!IS_ERR (mmu)) mmu->funcs->destroy (mmu); ret =PTR_ERR (aspace); - goto fail; +return ret; } kms->aspace = aspace;
@@ -467,7 +467,7 @@ static int mdp4_kms_init(struct drm_device *dev) ret =modeset_init (mdp4_kms);if (ret) {DRM_DEV_ERROR (dev->dev,"modeset_init failed: %d\n" , ret); - goto fail; +return ret; } mdp4_kms->blank_cursor_bo =msm_gem_new (dev,SZ_16K ,MSM_BO_WC |MSM_BO_SCANOUT );
@@ -475,14 +475,14 @@ static int mdp4_kms_init(struct drm_device *dev) ret =PTR_ERR (mdp4_kms->blank_cursor_bo);DRM_DEV_ERROR (dev->dev,"could not allocate blank-cursor bo: %d\n" , ret); mdp4_kms->blank_cursor_bo =NULL ; - goto fail; +return ret; } ret =msm_gem_get_and_pin_iova (mdp4_kms->blank_cursor_bo, kms->aspace, &mdp4_kms->blank_cursor_iova);if (ret) {DRM_DEV_ERROR (dev->dev,"could not pin blank-cursor bo: %d\n" , ret); - goto fail; +return ret; } dev->mode_config.min_width =0 ;
@@ -491,12 +491,6 @@ static int mdp4_kms_init(struct drm_device *dev) dev->mode_config.max_height =2048 ;return 0 ; - -fail: -if (kms) -mdp4_destroy (kms); - -return ret; }static const struct dev_pm_ops mdp4_pm_ops = {
drivers/gpu/drm/msm/disp/mdp5/mdp5_kms.c +3 -8
@@ -514,7 +514,7 @@ static int mdp5_kms_init(struct drm_device *dev) ret =mdp_kms_init (&mdp5_kms->base, &kms_funcs);if (ret) {DRM_DEV_ERROR (&pdev->dev,"failed to init kms\n" ); - goto fail; +return ret; } config =mdp5_cfg_get_config (mdp5_kms->cfg);
@@ -537,7 +537,7 @@ static int mdp5_kms_init(struct drm_device *dev) aspace =msm_kms_init_aspace (mdp5_kms->dev);if (IS_ERR (aspace)) { ret =PTR_ERR (aspace); - goto fail; +return ret; } kms->aspace = aspace;
@@ -547,7 +547,7 @@ static int mdp5_kms_init(struct drm_device *dev) ret =modeset_init (mdp5_kms);if (ret) {DRM_DEV_ERROR (&pdev->dev,"modeset_init failed: %d\n" , ret); - goto fail; +return ret; } dev->mode_config.min_width =0 ;
@@ -559,11 +559,6 @@ static int mdp5_kms_init(struct drm_device *dev) dev->vblank_disable_immediate = true;return 0 ; -fail: -if (kms) -mdp5_kms_destroy (kms); - -return ret; }static void mdp5_destroy (struct mdp5_kms *mdp5_kms)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 677/869 wifi: mt76: cancel reset and rc work on device unregister
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Fietkau <[email protected]>
[ Upstream commit e995d3dccc9d980af13a60ad37409ed1561f9eeb ]
Both drivers cancelled dump_work on unregister but left reset_work and rc_work to be flushed only by destroy_workqueue() in mt76_free_device(), which runs after the hw is unregistered and the hardware stopped. A reset_work that fires in that window calls ieee80211_restart_hw() and re-arms mac_work on an unregistered hw, and rc_work touches station state being torn down. Cancel both up front, alongside dump_work.
--- drivers/net/wireless/mediatek/mt76/mt7915/init.c | 2 ++ drivers/net/wireless/mediatek/mt76/mt7996/init.c | 2 ++ 2 files changed, 4 insertions(+)
drivers/net/wireless/mediatek/mt76/mt7915/init.c +2 -0
@@ -1288,6 +1288,8 @@ int mt7915_register_device(struct mt7915_dev *dev)void mt7915_unregister_device (struct mt7915_dev *dev) {cancel_work_sync (&dev->dump_work); +cancel_work_sync (&dev->reset_work); +cancel_work_sync (&dev->rc_work);mt7915_unregister_ext_phy (dev);mt7915_coredump_unregister (dev);mt7915_unregister_thermal (&dev->phy);
drivers/net/wireless/mediatek/mt76/mt7996/init.c +2 -0
@@ -1405,6 +1405,8 @@ void mt7996_unregister_device(struct mt7996_dev *dev) {cancel_work_sync (&dev->dump_work);cancel_work_sync (&dev->wed_rro.work); +cancel_work_sync (&dev->reset_work); +cancel_work_sync (&dev->rc_work);mt7996_unregister_phy (mt7996_phy3 (dev),MT_BAND2 );mt7996_unregister_phy (mt7996_phy2 (dev),MT_BAND1 );mt7996_unregister_thermal (&dev->phy);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 678/869 wifi: mt76: mt7996: hold dev->mt76.mutex while disabling tx worker in SER
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Fietkau <[email protected]>
[ Upstream commit 6190db312b8230813f529f014b26247c6d9800d0 ]
mt7996_mac_reset_work() parked the tx worker and disabled the RX/TX NAPIs before taking dev->mt76.mutex. mt76_worker_disable()/_enable() are plain kthread park/unpark, not refcounted, and __mt76_set_channel() toggles the same worker and the MT76_RESET bit under the mutex. An L1 SER racing a channel switch could therefore have the worker unparked and MT76_RESET cleared while the reset path resets the DMA rings, corrupting descriptors or tokens. Take the mutex before disabling the worker, as mt7915 does.
--- drivers/net/wireless/mediatek/mt76/mt7996/mac.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7996/mac.c +3 -2
@@ -1916,6 +1916,9 @@ void mt7996_mac_reset_work(struct work_struct *work)set_bit (MT76_RESET , &phy3->mt76->state);cancel_delayed_work_sync (&phy3->mt76->mac_work); } + +mutex_lock (&dev->mt76.mutex); +mt76_worker_disable (&dev->mt76.tx_worker);mt76_for_each_q_rx (&dev->mt76, i) { if (mtk_wed_device_active(&dev->mt76.mmio.wed) &&
@@ -1926,8 +1929,6 @@ void mt7996_mac_reset_work(struct work_struct *work) }napi_disable (&dev->mt76.tx_napi); -mutex_lock (&dev->mt76.mutex); -mt76_wr (dev,MT_MCU_INT_EVENT ,MT_MCU_INT_EVENT_DMA_STOPPED );if (mt7996_wait_reset_state (dev,MT_MCU_CMD_RESET_DONE )) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 679/869 wifi: ath12k: fix overreads in ath12k_wmi_process_csa_switch_count_event()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Johnson <[email protected]>
[ Upstream commit 878654eb78c6aa0ff585baf1376567c775ca28ec ]
There is no policy entry for WMI_TAG_PDEV_CSA_SWITCH_COUNT_STATUS_EVENT, so the parse infrastructure does not enforce a minimum length for the event struct. Additionally, the num_vdevs field is taken directly from firmware and used as a loop bound over the vdev_ids array without checking that it fits within the TLV payload. Either condition can cause an out-of-bounds read.
Add a TLV policy entry for WMI_TAG_PDEV_CSA_SWITCH_COUNT_STATUS_EVENT so the parse infrastructure enforces a minimum length for the fixed-size event struct. Add a helper ath12k_wmi_tlv_data_len() to recover the payload length of a parsed TLV from the header preceding its data pointer. Use it in ath12k_wmi_process_csa_switch_count_event() to bound num_vdevs before the loop.
Compile tested only.
--- drivers/net/wireless/ath/ath12k/wmi.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
drivers/net/wireless/ath/ath12k/wmi.c +18 -1
@@ -171,6 +171,8 @@ static const struct ath12k_wmi_tlv_policy ath12k_wmi_tlv_policies[] = { .min_len = sizeof(struct ath12k_wmi_p2p_noa_info) }, [WMI_TAG_P2P_NOA_EVENT] = { .min_len = sizeof(struct wmi_p2p_noa_event) }, + [WMI_TAG_PDEV_CSA_SWITCH_COUNT_STATUS_EVENT] = { + .min_len = sizeof(struct ath12k_wmi_pdev_csa_event) }, };static __le32 ath12k_wmi_tlv_hdr (u32 cmd,u32 len)
@@ -384,6 +386,13 @@ ath12k_wmi_tlv_parse_alloc(struct ath12k_base *ab,return tb; } +static u32 ath12k_wmi_tlv_data_len (const void *data) +{ +const struct wmi_tlv *tlv = (const struct wmi_tlv *)data -1 ; + +return le32_get_bits (tlv->header,WMI_TLV_LEN ); +} +static int ath12k_wmi_cmd_send_nowait (struct ath12k_wmi_pdev *wmi,struct sk_buff *skb,u32 cmd_id) {
@@ -6735,6 +6744,8 @@ ath12k_wmi_process_csa_switch_count_event(struct ath12k_base *ab,const struct ath12k_wmi_pdev_csa_event *ev, const u32 *vdev_ids) { + u32 vdev_ids_len = ath12k_wmi_tlv_data_len(vdev_ids); +u32 num_vdevs =le32_to_cpu (ev->num_vdevs);int i;struct ath12k_vif *arvif;
@@ -6742,8 +6753,14 @@ ath12k_wmi_process_csa_switch_count_event(struct ath12k_base *ab,if (ev->current_switch_count)return ; +if (num_vdevs > vdev_ids_len /sizeof (*vdev_ids)) { +ath12k_warn (ab,"csa switch count num_vdevs %u exceeds tlv array length %u\n" , + num_vdevs, vdev_ids_len); +return ; + } +rcu_read_lock (); -for (i =0 ; i <le32_to_cpu (ev->num_vdevs); i++) { +for (i =0 ; i < num_vdevs; i++) { arvif =ath12k_mac_get_arvif_by_vdev_id (ab, vdev_ids[i]);if (!arvif) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 680/869 drm/i915: rename range_overflows_end() to range_end_overflows()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jani Nikula <[email protected]>
[ Upstream commit 1e4c85167cf672312a178b2af0b058add77e448b ]
Rename range_overflows_end() to range_end_overflows(), along with the _t variant.
It's all rather subjective, but I think range_end_overflows() reads better.
Stable-dep-of: 985f5e12f3cd ("drm/panthor: Add vm_bind region with kbo range overlap check")
--- drivers/gpu/drm/i915/display/intel_fbc.c | 4 ++-- drivers/gpu/drm/i915/gt/intel_rc6.c | 2 +- drivers/gpu/drm/i915/i915_utils.h | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-)
drivers/gpu/drm/i915/display/intel_fbc.c +2 -2
@@ -378,11 +378,11 @@ static void i8xx_fbc_program_cfb(struct intel_fbc *fbc)struct drm_i915_private *i915 =to_i915 (display->drm);drm_WARN_ON (display->drm, -range_overflows_end_t (u64,i915_gem_stolen_area_address (i915), +range_end_overflows_t (u64,i915_gem_stolen_area_address (i915),i915_gem_stolen_node_offset (&fbc->compressed_fb),U32_MAX ));drm_WARN_ON (display->drm, -range_overflows_end_t (u64,i915_gem_stolen_area_address (i915), +range_end_overflows_t (u64,i915_gem_stolen_area_address (i915),i915_gem_stolen_node_offset (&fbc->compressed_llb),U32_MAX )); intel_de_write(i915, FBC_CFB_BASE,
drivers/gpu/drm/i915/gt/intel_rc6.c +1 -1
@@ -341,7 +341,7 @@ static int vlv_rc6_init(struct intel_rc6 *rc6)return PTR_ERR (pctx); } -GEM_BUG_ON (range_overflows_end_t (u64, +GEM_BUG_ON (range_end_overflows_t (u64, i915->dsm.stolen.start, pctx->stolen->start,U32_MAX ));
drivers/gpu/drm/i915/i915_utils.h +3 -3
@@ -81,7 +81,7 @@ bool i915_error_injected(void);#define range_overflows_t (type, start, size, max) \ range_overflows((type)(start), (type)(size), (type)(max)) -#define range_overflows_end (start, size, max) ({ \ +#define range_end_overflows (start, size, max) ({ \ typeof(start) start__ = (start); \ typeof(size) size__ = (size); \ typeof(max) max__ = (max); \
@@ -90,8 +90,8 @@ bool i915_error_injected(void); start__ > max__ || size__ > max__ - start__; \ }) -#define range_overflows_end_t (type, start, size, max) \ - range_overflows_end((type)(start), (type)(size), (type)(max)) +#define range_end_overflows_t (type, start, size, max) \ + range_end_overflows((type)(start), (type)(size), (type)(max))#define ptr_mask_bits (ptr, n) ({ \ unsigned long __v = (unsigned long)(ptr); \
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 681/869 drm/i915: document range_overflows() and range_end_overflows() macros
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jani Nikula <[email protected]>
[ Upstream commit 59bf37add1d2223d699d1855354277b7330765e4 ]
Document the macros in preparation for making them more generally available.
Stable-dep-of: 985f5e12f3cd ("drm/panthor: Add vm_bind region with kbo range overlap check")
--- drivers/gpu/drm/i915/i915_utils.h | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+)
drivers/gpu/drm/i915/i915_utils.h +46 -0
@@ -69,6 +69,18 @@ bool i915_error_injected(void); drm_err(&(i915)->drm, fmt, ##__VA_ARGS__); \ }) +/** +* range_overflows() - Check if a range is out of bounds +* @start: Start of the range. +* @size: Size of the range. +* @max: Exclusive upper boundary. +* +* A strict check to determine if the range [@start, @start + @size) is +* invalid with respect to the allowable range [0, @max). Any range +* starting at or beyond @max is considered an overflow, even if @size is 0. +* +* Returns: true if the range is out of bounds. +*/ #define range_overflows (start, size, max) ({ \ typeof(start) start__ = (start); \ typeof(size) size__ = (size); \
@@ -78,9 +90,32 @@ bool i915_error_injected(void); start__ >= max__ || size__ > max__ - start__; \ }) +/** +* range_overflows_t() - Check if a range is out of bounds +* @type: Data type to use. +* @start: Start of the range. +* @size: Size of the range. +* @max: Exclusive upper boundary. +* +* Same as range_overflows() but forcing the parameters to @type. +* +* Returns: true if the range is out of bounds. +*/ #define range_overflows_t (type, start, size, max) \ range_overflows((type)(start), (type)(size), (type)(max)) +/** +* range_end_overflows() - Check if a range's endpoint is out of bounds +* @start: Start of the range. +* @size: Size of the range. +* @max: Exclusive upper boundary. +* +* Checks only if the endpoint of a range (@start + @size) exceeds @max. +* Unlike range_overflows(), a zero-sized range at the boundary (@start == @max) +* is not considered an overflow. Useful for iterator-style checks. +* +* Returns: true if the endpoint exceeds the boundary. +*/ #define range_end_overflows (start, size, max) ({ \ typeof(start) start__ = (start); \ typeof(size) size__ = (size); \
@@ -90,6 +125,17 @@ bool i915_error_injected(void); start__ > max__ || size__ > max__ - start__; \ }) +/** +* range_end_overflows_t() - Check if a range's endpoint is out of bounds +* @type: Data type to use. +* @start: Start of the range. +* @size: Size of the range. +* @max: Exclusive upper boundary. +* +* Same as range_end_overflows() but forcing the parameters to @type. +* +* Returns: true if the endpoint exceeds the boundary. +*/ #define range_end_overflows_t (type, start, size, max) \ range_end_overflows((type)(start), (type)(size), (type)(max))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 682/869 overflow: add range_overflows() and range_end_overflows()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jani Nikula <[email protected]>
[ Upstream commit 5f3cec21f6d57336a2cbfa9ee428ac66c77a7211 ]
Move the range_overflows() and range_end_overflows() along with the _t variants over from drm/i915 and drm/buddy to overflow.h.
Stable-dep-of: 985f5e12f3cd ("drm/panthor: Add vm_bind region with kbo range overlap check")
--- drivers/gpu/drm/i915/i915_utils.h | 70 ------------------------------- include/linux/gpu_buddy.h | 9 ---- include/linux/overflow.h | 70 +++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 79 deletions(-)
drivers/gpu/drm/i915/i915_utils.h +0 -70
@@ -69,76 +69,6 @@ bool i915_error_injected(void); drm_err(&(i915)->drm, fmt, ##__VA_ARGS__); \ }) -/** -* range_overflows() - Check if a range is out of bounds -* @start: Start of the range. -* @size: Size of the range. -* @max: Exclusive upper boundary. -* -* A strict check to determine if the range [@start, @start + @size) is -* invalid with respect to the allowable range [0, @max). Any range -* starting at or beyond @max is considered an overflow, even if @size is 0. -* -* Returns: true if the range is out of bounds. -*/ -#define range_overflows (start, size, max) ({ \ - typeof(start) start__ = (start); \ - typeof(size) size__ = (size); \ - typeof(max) max__ = (max); \ - (void)(&start__ == &size__); \ - (void)(&start__ == &max__); \ - start__ >= max__ || size__ > max__ - start__; \ -}) - -/** -* range_overflows_t() - Check if a range is out of bounds -* @type: Data type to use. -* @start: Start of the range. -* @size: Size of the range. -* @max: Exclusive upper boundary. -* -* Same as range_overflows() but forcing the parameters to @type. -* -* Returns: true if the range is out of bounds. -*/ -#define range_overflows_t (type, start, size, max) \ - range_overflows((type)(start), (type)(size), (type)(max)) - -/** -* range_end_overflows() - Check if a range's endpoint is out of bounds -* @start: Start of the range. -* @size: Size of the range. -* @max: Exclusive upper boundary. -* -* Checks only if the endpoint of a range (@start + @size) exceeds @max. -* Unlike range_overflows(), a zero-sized range at the boundary (@start == @max) -* is not considered an overflow. Useful for iterator-style checks. -* -* Returns: true if the endpoint exceeds the boundary. -*/ -#define range_end_overflows (start, size, max) ({ \ - typeof(start) start__ = (start); \ - typeof(size) size__ = (size); \ - typeof(max) max__ = (max); \ - (void)(&start__ == &size__); \ - (void)(&start__ == &max__); \ - start__ > max__ || size__ > max__ - start__; \ -}) - -/** -* range_end_overflows_t() - Check if a range's endpoint is out of bounds -* @type: Data type to use. -* @start: Start of the range. -* @size: Size of the range. -* @max: Exclusive upper boundary. -* -* Same as range_end_overflows() but forcing the parameters to @type. -* -* Returns: true if the endpoint exceeds the boundary. -*/ -#define range_end_overflows_t (type, start, size, max) \ - range_end_overflows((type)(start), (type)(size), (type)(max)) -#define ptr_mask_bits (ptr, n) ({ \ unsigned long __v = (unsigned long)(ptr); \ (typeof(ptr))(__v & -BIT(n)); \
include/linux/gpu_buddy.h +0 -9
@@ -14,15 +14,6 @@#include <drm/drm_print.h> -#define range_overflows (start, size, max) ({ \ - typeof(start) start__ = (start); \ - typeof(size) size__ = (size); \ - typeof(max) max__ = (max); \ - (void)(&start__ == &size__); \ - (void)(&start__ == &max__); \ - start__ >= max__ || size__ > max__ - start__; \ -}) -#define GPU_BUDDY_RANGE_ALLOCATION BIT(0)#define GPU_BUDDY_TOPDOWN_ALLOCATION BIT(1)#define GPU_BUDDY_CONTIGUOUS_ALLOCATION BIT(2)
include/linux/overflow.h +70 -0
76 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 683/869 drm/panthor: Add vm_bind region with kbo range overlap check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adrián Larumbe <[email protected]>
[ Upstream commit 985f5e12f3cdf43030e13c2bbd154913133b5c3f ]
When a VM is created, caller has to specify the range of the address space carve-out set aside for mapping kernel BO's. That means vm_bind mappings of UM-exposed BO's should not intersect with that region, but at the moment we're not checking this.
At first, I thought of giving these values to drm_gpuvm_init() through its reserve_{offset, range} arguments, but it turns out that is meant for VM address spans that are not managed through the usual drm_gpuvm split/merge circuit, so storing the end of the user VA range at VM creation time and doing a quick check in the vm_bind ioctl path was the simplest workaround.
The new check also makes sure vm_bind range doesn't overflow the size of a 64-bit unsigned integer. That was already being done further down the call stack inside drm_gpuvm_sm_map -> drm_gpuvm_range_valid, but it's best to fail early in the driver before GPUVM functions are invoked so that we won't waste time allocating vm_bind context resources.
--- drivers/gpu/drm/panthor/panthor_mmu.c | 9 +++++++++ 1 file changed, 9 insertions(+)
drivers/gpu/drm/panthor/panthor_mmu.c +9 -0
@@ -311,6 +311,9 @@ struct panthor_vm {u64 end; } kernel_auto_va; +/** @user_va_range: Upper boundary of VAs VM users can map objects against. */ +u64 user_va_range; +/** @as: Address space related fields. */ struct {/**
@@ -2323,6 +2326,8 @@ panthor_vm_create(struct panthor_device *ptdev, bool for_mcu, va_range = full_va_range; } + vm->user_va_range = kernel_va_start; +mutex_init (&vm->mm_lock);drm_mm_init (&vm->mm, kernel_va_start, kernel_va_size); vm->kernel_auto_va.start = auto_kernel_va_start;
@@ -2412,6 +2417,10 @@ panthor_vm_bind_prepare_op_ctx(struct drm_file *file,if (!IS_ALIGNED (op->va | op->size | op->bo_offset, vm_pgsz))return -EINVAL ; +/* We don't allow mappings that overlap with kbo's reserved range */ +if (range_overflows (op->va, op->size, vm->user_va_range)) +return -EINVAL ; +switch (op->flags &DRM_PANTHOR_VM_BIND_OP_TYPE_MASK ) {case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP : gem =drm_gem_object_lookup (file, op->bo_handle);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 684/869 RDMA/cxgb4: Fix dereg_skb leak and double free in write_tpt_entry()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Leon Romanovsky <[email protected]>
[ Upstream commit 373f3716a2de7adc739269ebb4d87e5bf4dc180c ]
When the device is in the fatal error state, write_tpt_entry() returns -EIO before handing the caller's preallocated skb to the transmit path; its allocation-failure returns do the same. c4iw_dereg_mr() ignores the error and frees mhp, leaking mhp->dereg_skb. c4iw_get_dma_mr() instead frees the skb a second time after dereg_mem() already consumed it, a double free.
Make write_tpt_entry() the sole owner of a non-NULL skb, freeing it on every return preceding handoff to c4iw_ofld_send(): fatal error, tpt and stag allocation failure. c4iw_ofld_send() consumes the skb on success and error alike, so drop the redundant kfree_skb() in c4iw_get_dma_mr() after dereg_mem().
--- drivers/infiniband/hw/cxgb4/mem.c | 46 ++++++++++++------------------- 1 file changed, 17 insertions(+), 29 deletions(-)
drivers/infiniband/hw/cxgb4/mem.c +17 -29
@@ -199,7 +199,8 @@ static int _c4iw_write_mem_dma(struct c4iw_rdev *rdev, u32 addr, u32 len, daddr =dma_map_single (&rdev->lldi.pdev->dev, data, len,DMA_TO_DEVICE );if (dma_mapping_error (&rdev->lldi.pdev->dev, daddr)) -return -1 ; +return _c4iw_write_mem_inline (rdev, addr, len, data, skb, + wr_waitp); save = daddr;while (remain > inline_threshold) {
@@ -235,30 +236,12 @@ static int write_adapter_mem(struct c4iw_rdev *rdev, u32 addr, u32 len, void *data, struct sk_buff *skb, struct c4iw_wr_wait *wr_waitp) { - int ret; - -if (!rdev->lldi.ulptx_memwrite_dsgl || !use_dsgl) { - ret =_c4iw_write_mem_inline (rdev, addr, len, data, skb, - wr_waitp); - goto out; - } - -if (len <= inline_threshold) { - ret =_c4iw_write_mem_inline (rdev, addr, len, data, skb, + if (!rdev->lldi.ulptx_memwrite_dsgl || !use_dsgl || + len <= inline_threshold) + return _c4iw_write_mem_inline(rdev, addr, len, data, skb, wr_waitp); - goto out; - } - - ret =_c4iw_write_mem_dma (rdev, addr, len, data, skb, wr_waitp); -if (ret) { -pr_warn_ratelimited ("%s: dma map failure (non fatal)\n" , -pci_name (rdev->lldi.pdev)); - ret =_c4iw_write_mem_inline (rdev, addr, len, data, skb, - wr_waitp); - } -out: -return ret; + return _c4iw_write_mem_dma(rdev, addr, len, data, skb, wr_waitp); }/*
@@ -280,12 +263,16 @@ static int write_tpt_entry(struct c4iw_rdev *rdev, u32 reset_tpt_entry,bool stag_idx_allocated = false;static atomic_t key; -if (c4iw_fatal_error (rdev)) +if (c4iw_fatal_error (rdev)) { +kfree_skb (skb);return -EIO ; + } tpt =kmalloc (sizeof (*tpt),GFP_KERNEL ); -if (!tpt) +if (!tpt) { +kfree_skb (skb);return -ENOMEM ; + } stag_state = stag_state >0 ; stag_idx = (*stag) >>8 ;
@@ -297,6 +284,7 @@ static int write_tpt_entry(struct c4iw_rdev *rdev, u32 reset_tpt_entry, rdev->stats.stag.fail++;mutex_unlock (&rdev->stats.lock);kfree (tpt); +kfree_skb (skb);return -ENOMEM ; }mutex_lock (&rdev->stats.lock);
@@ -471,8 +459,10 @@ struct ib_mr *c4iw_get_dma_mr(struct ib_pd *pd, int acc)FW_RI_STAG_NSMR , mhp->attr.perms, mhp->attr.mw_bind_enable,0 ,0 , ~0ULL ,0 ,0 ,0 , NULL, mhp->wr_waitp); -if (ret) - goto err_free_skb; +if (ret) { +kfree_skb (mhp->dereg_skb); + goto err_free_wr_wait; + } ret =finish_mem_reg (mhp, stag);if (ret)
@@ -481,8 +471,6 @@ struct ib_mr *c4iw_get_dma_mr(struct ib_pd *pd, int acc) err_dereg_mem:dereg_mem (&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size, mhp->attr.pbl_addr, mhp->dereg_skb, mhp->wr_waitp); -err_free_skb: -kfree_skb (mhp->dereg_skb); err_free_wr_wait:c4iw_put_wr_wait (mhp->wr_waitp); err_free_mhp:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 685/869 PCI: Make pci_match_one_device() match on ID instead of device
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gary Guo <[email protected]>
[ Upstream commit c967b365d7b51c2297d9be5df39ac3e20638faf4 ]
PCI dynamic ID needs to match IDs against a new ID to see if it already exists. Existing APIs can only match IDs against devices, so the dynamic ID insertion code creates a temporary device only for matching purposes. Rename pci_match_one_device() to pci_match_one_id() so it can be used for this purpose instead; add a pci_id_from_device() helper to make it easy to convert users.
Similarly, convert pci_match_id() to do_pci_match_id(). But keep the existing API because there are many users.
Stable-dep-of: 3ffc4c9690c3 ("PCI: Fix UAF when probe runs concurrent to dyn ID removal")
--- drivers/pci/pci-driver.c | 38 +++++++++++++++++++++++++---------- drivers/pci/pci.h | 43 +++++++++++++++++++++++++++++----------- drivers/pci/search.c | 8 +++++--- 3 files changed, 64 insertions(+), 25 deletions(-)
drivers/pci/pci-driver.c +28 -10
@@ -90,6 +90,27 @@ static void pci_free_dynids(struct pci_driver *drv)spin_unlock (&drv->dynids.lock); } +/** +* do_pci_match_id - See if a PCI ID matches a given pci_id table +* @ids: array of PCI device ID structures to search in +* @dev_id: the actual PCI device ID structure to match against. +* +* Return: the matching pci_device_id structure or %NULL if there is no match. +*/ +static const struct pci_device_id * +do_pci_match_id (const struct pci_device_id *ids, +const struct pci_device_id *dev_id) +{ +if (ids) { +while (ids->vendor || ids->subvendor || ids->class_mask) { +if (pci_match_one_id (ids, dev_id)) +return ids; + ids++; + } + } +return NULL ; +} +/** * pci_match_id - See if a PCI device matches a given pci_id table * @ids: array of PCI device ID structures to search in
@@ -105,14 +126,9 @@ static void pci_free_dynids(struct pci_driver *drv)const struct pci_device_id *pci_match_id (const struct pci_device_id *ids,struct pci_dev *dev) { -if (ids) { -while (ids->vendor || ids->subvendor || ids->class_mask) { -if (pci_match_one_device (ids, dev)) -return ids; - ids++; - } - } -return NULL ; +struct pci_device_id dev_id =pci_id_from_device (dev); + +return do_pci_match_id (ids, &dev_id); }EXPORT_SYMBOL (pci_match_id);
@@ -138,6 +154,7 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv, {struct pci_dynid *dynid;const struct pci_device_id *found_id =NULL , *ids; +struct pci_device_id dev_id;int ret;/* When driver_override is set, only bind to the matching driver */
@@ -145,10 +162,11 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv,if (ret ==0 )return NULL ; + dev_id =pci_id_from_device (dev);/* Look at the dynamic ids first, before the static ones */ spin_lock (&drv->dynids.lock);list_for_each_entry (dynid, &drv->dynids.list, node) { -if (pci_match_one_device (&dynid->id, dev)) { +if (pci_match_one_id (&dynid->id, &dev_id)) { found_id = &dynid->id;break ; }
@@ -158,7 +176,7 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv,if (found_id)return found_id; -for (ids = drv->id_table; (found_id =pci_match_id (ids, dev)); +for (ids = drv->id_table; (found_id =do_pci_match_id (ids, &dev_id)); ids = found_id +1 ) {/* * The match table is split based on driver_override.
drivers/pci/pci.h +31 -12
52 lines not on this page · raw message
drivers/pci/search.c +5 -3
@@ -243,8 +243,10 @@ static int match_pci_dev_by_id(struct device *dev, const void *data) {struct pci_dev *pdev =to_pci_dev (dev);const struct pci_device_id *id = data; +struct pci_device_id dev_id; -if (pci_match_one_device (id, pdev)) + dev_id =pci_id_from_device (pdev); +if (pci_match_one_id (id, &dev_id))return 1 ;return 0 ; }
@@ -368,9 +370,9 @@ EXPORT_SYMBOL(pci_get_class);* @class: search for a PCI device with this base class code * @from: Previous PCI device found in search, or %NULL for new search. * -* Iterates through the list of known PCI devices. If a PCI device is found +* Iterate through the list of known PCI devices. If a PCI device is found * with a matching base class code, the reference count to the device is -* incremented. See pci_match_one_device() to figure out how does this works. +* incremented. See pci_match_one_id() to figure out how this works. * A new search is initiated by passing %NULL as the @from argument. * Otherwise if @from is not %NULL, searches continue from next device on the * global list. The reference count for @from is always decremented if it is
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 686/869 PCI: Fix dyn_id add TOCTOU
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gary Guo <[email protected]>
[ Upstream commit 04fde70f782b6ce984f9f80c2023786caea28287 ]
Currently there is a TOCTOU issue in new_id_store() as the dyn ID insertion in pci_add_dynid() and the pci_match_device() are in separate critical sections.
Fix this by moving the existing ID check to inside pci_add_dynid() and only check against the static ID table outside the critical section.
Stable-dep-of: 3ffc4c9690c3 ("PCI: Fix UAF when probe runs concurrent to dyn ID removal")
--- drivers/pci/pci-driver.c | 142 ++++++++++++++++++++------------------- 1 file changed, 73 insertions(+), 69 deletions(-)
drivers/pci/pci-driver.c +73 -69
@@ -29,6 +29,47 @@ struct pci_dynid {struct pci_device_id id; }; +/** +* do_pci_add_dynid - Add a new PCI device ID to this driver and re-probe +* @drv: target PCI driver +* @id: ID to be added +* @check_dup: whether to check if matching ID is already present +* +* Add a new dynamic PCI device ID to this driver and causes the driver to +* probe for all devices again. @drv must have been registered prior to calling +* this function. +* +* Context: Does GFP_KERNEL allocation. +* +* Return: 0 on success, -errno on failure. +*/ +static int do_pci_add_dynid (struct pci_driver *drv, +const struct pci_device_id *id, +bool check_dup) +{ +struct pci_dynid *dynid, *existing_dynid; + + dynid =kzalloc (sizeof (*dynid),GFP_KERNEL ); +if (!dynid) +return -ENOMEM ; + + dynid->id = *id; + + scoped_guard(spinlock, &drv->dynids.lock) { +if (check_dup) { +list_for_each_entry (existing_dynid, &drv->dynids.list, node) { +if (pci_match_one_id (&existing_dynid->id, id)) { +kfree (dynid); +return -EEXIST ; + } + } + } +list_add_tail (&dynid->node, &drv->dynids.list); + } + +return driver_attach (&drv->driver); +} +/** * pci_add_dynid - add a new PCI device ID to this driver and re-probe devices * @drv: target pci driver
@@ -56,25 +97,17 @@ int pci_add_dynid(struct pci_driver *drv, unsigned int class, unsigned int class_mask, unsigned long driver_data) { - struct pci_dynid *dynid; - - dynid =kzalloc (sizeof (*dynid),GFP_KERNEL ); -if (!dynid) -return -ENOMEM ; - - dynid->id.vendor = vendor; - dynid->id.device = device; - dynid->id.subvendor = subvendor; - dynid->id.subdevice = subdevice; - dynid->id.class = class; - dynid->id.class_mask = class_mask; - dynid->id.driver_data = driver_data; - -spin_lock (&drv->dynids.lock); -list_add_tail (&dynid->node, &drv->dynids.list); -spin_unlock (&drv->dynids.lock); - -return driver_attach (&drv->driver); + struct pci_device_id id = { + .vendor = vendor, + .device = device, + .subvendor = subvendor, + .subdevice = subdevice, + .class = class, + .class_mask = class_mask, + .driver_data = driver_data, + }; + +return do_pci_add_dynid (drv, &id, false); }EXPORT_SYMBOL_GPL (pci_add_dynid);
@@ -94,16 +127,20 @@ static void pci_free_dynids(struct pci_driver *drv)* do_pci_match_id - See if a PCI ID matches a given pci_id table * @ids: array of PCI device ID structures to search in * @dev_id: the actual PCI device ID structure to match against. +* @include_override_only: also match against device ID entries marked as +* override only. * * Return: the matching pci_device_id structure or %NULL if there is no match. */ static const struct pci_device_id *do_pci_match_id (const struct pci_device_id *ids, -const struct pci_device_id *dev_id) +const struct pci_device_id *dev_id, +bool include_override_only) {if (ids) {while (ids->vendor || ids->subvendor || ids->class_mask) { -if (pci_match_one_id (ids, dev_id)) +if ((!ids->override_only || include_override_only) && +pci_match_one_id (ids, dev_id))return ids; ids++; }
@@ -128,7 +165,7 @@ const struct pci_device_id *pci_match_id(const struct pci_device_id *ids, {struct pci_device_id dev_id =pci_id_from_device (dev); -return do_pci_match_id (ids, &dev_id); +return do_pci_match_id (ids, &dev_id, true); }EXPORT_SYMBOL (pci_match_id);
@@ -153,7 +190,7 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv, struct pci_dev *dev) {struct pci_dynid *dynid; -const struct pci_device_id *found_id =NULL , *ids; +const struct pci_device_id *found_id =NULL ;struct pci_device_id dev_id;int ret;
@@ -176,20 +213,9 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv,if (found_id)return found_id; -for (ids = drv->id_table; (found_id =do_pci_match_id (ids, &dev_id)); - ids = found_id +1 ) { -/* -* The match table is split based on driver_override. -* In case override_only was set, enforce driver_override -* matching. -*/ -if (found_id->override_only) { -if (ret >0 ) -return found_id; - }else { -return found_id; - } - } + found_id =do_pci_match_id (drv->id_table, &dev_id, ret >0 ); +if (found_id) +return found_id;/* driver_override will always match, send a dummy id */ if (ret >0 )
@@ -197,11 +223,6 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv,return NULL ; } -static void _pci_free_device (struct device *dev) -{ -kfree (to_pci_dev (dev)); -} -/** * new_id_store - sysfs frontend to pci_add_dynid() * @driver: target device driver
@@ -215,38 +236,22 @@ static ssize_t new_id_store(struct device_driver *driver, const char *buf, {struct pci_driver *pdrv =to_pci_driver (driver);const struct pci_device_id *ids = pdrv->id_table; -u32 vendor, device, subvendor =PCI_ANY_ID , - subdevice =PCI_ANY_ID , class =0 , class_mask =0 ; -unsigned long driver_data =0 ; +struct pci_device_id id = { + .subvendor =PCI_ANY_ID , + .subdevice =PCI_ANY_ID + };int fields;int retval =0 ; fields =sscanf (buf,"%x %x %x %x %x %x %lx" , - &vendor, &device, &subvendor, &subdevice, - &class, &class_mask, &driver_data); + &id.vendor, &id.device, &id.subvendor, &id.subdevice, + &id.class, &id.class_mask, &id.driver_data);if (fields <2 )return -EINVAL ;if (fields !=7 ) { -struct pci_dev *pdev =kzalloc (sizeof (*pdev),GFP_KERNEL ); -if (!pdev) -return -ENOMEM ; - - pdev->vendor = vendor; - pdev->device = device; - pdev->subsystem_vendor = subvendor; - pdev->subsystem_device = subdevice; - pdev->class = class; - pdev->dev.release = _pci_free_device; - -device_initialize (&pdev->dev); -if (pci_match_device (pdrv, pdev)) - retval = -EEXIST ; - -put_device (&pdev->dev); - -if (retval) -return retval; +if (do_pci_match_id (pdrv->id_table, &id, false)) +return -EEXIST ; }/* Only accept driver_data values that match an existing id_table
@@ -254,7 +259,7 @@ static ssize_t new_id_store(struct device_driver *driver, const char *buf,if (ids) { retval = -EINVAL ;while (ids->vendor || ids->subvendor || ids->class_mask) { -if (driver_data == ids->driver_data) { +if (id.driver_data == ids->driver_data) { retval =0 ;break ; }
@@ -264,8 +269,7 @@ static ssize_t new_id_store(struct device_driver *driver, const char *buf,return retval; } - retval =pci_add_dynid (pdrv, vendor, device, subvendor, subdevice, - class, class_mask, driver_data); + retval =do_pci_add_dynid (pdrv, &id, fields !=7 );if (retval)return retval;return count;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 687/869 PCI: Fix UAF when probe runs concurrent to dyn ID removal
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gary Guo <[email protected]>
[ Upstream commit 3ffc4c9690c33ee28cdb3d0182b12f9c623e3acc ]
Dynamic IDs are only guaranteed to be valid when dynids.lock is held, as remove_id_store() can free the node. Thus, make a copy in pci_match_device(). Also, clarify that the id parameter is only valid during probe.
--- drivers/pci/pci-driver.c | 28 +++++++++++++++------------- include/linux/pci.h | 1 + 2 files changed, 16 insertions(+), 13 deletions(-)
drivers/pci/pci-driver.c +15 -13
@@ -180,6 +180,7 @@ static const struct pci_device_id pci_device_id_any = {* pci_match_device - See if a device matches a driver's list of IDs * @drv: the PCI driver to match against * @dev: the PCI device structure to match against +* @id_copy: place to store copy of pci_device_id for dynamic ID * * Used by a driver to check whether a PCI device is in its list of * supported devices or in the dynids list, which may have been augmented
@@ -187,9 +188,9 @@ static const struct pci_device_id pci_device_id_any = {* structure or %NULL if there is no match. */ static const struct pci_device_id *pci_match_device (struct pci_driver *drv, -struct pci_dev *dev) +struct pci_dev *dev, +struct pci_device_id *id_copy) { -struct pci_dynid *dynid;const struct pci_device_id *found_id =NULL ;struct pci_device_id dev_id;int ret;
@@ -201,17 +202,16 @@ static const struct pci_device_id *pci_match_device(struct pci_driver *drv, dev_id =pci_id_from_device (dev);/* Look at the dynamic ids first, before the static ones */ -spin_lock (&drv->dynids.lock); -list_for_each_entry (dynid, &drv->dynids.list, node) { -if (pci_match_one_id (&dynid->id, &dev_id)) { - found_id = &dynid->id; -break ; + scoped_guard(spinlock, &drv->dynids.lock) { +struct pci_dynid *dynid; + +list_for_each_entry (dynid, &drv->dynids.list, node) { +if (pci_match_one_id (&dynid->id, &dev_id)) { + *id_copy = dynid->id; +return id_copy; + } } } -spin_unlock (&drv->dynids.lock); - -if (found_id) -return found_id; found_id =do_pci_match_id (drv->id_table, &dev_id, ret >0 );if (found_id)
@@ -438,12 +438,13 @@ static int pci_call_probe(struct pci_driver *drv, struct pci_dev *dev,static int __pci_device_probe (struct pci_driver *drv,struct pci_dev *pci_dev) {const struct pci_device_id *id; +struct pci_device_id id_copy;int error =0 ;if (drv->probe) { error = -ENODEV ; - id =pci_match_device (drv, pci_dev); + id =pci_match_device (drv, pci_dev, &id_copy);if (id) error =pci_call_probe (drv, pci_dev, id); }
@@ -1537,12 +1538,13 @@ static int pci_bus_match(struct device *dev, const struct device_driver *drv)struct pci_dev *pci_dev =to_pci_dev (dev);struct pci_driver *pci_drv;const struct pci_device_id *found_id; +struct pci_device_id id_copy;if (!pci_dev->match_driver)return 0 ; pci_drv = (struct pci_driver *)to_pci_driver (drv); - found_id =pci_match_device (pci_drv, pci_dev); + found_id =pci_match_device (pci_drv, pci_dev, &id_copy);if (found_id)return 1 ;
include/linux/pci.h +1 -0
@@ -929,6 +929,7 @@ struct module;* function returns zero when the driver chooses to * take "ownership" of the device or an error code * (negative number) otherwise. +* The pci_device_id parameter is only valid during probe. * The probe function always gets called from process * context, so it can sleep. * @remove: The remove() function gets called whenever a device
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 688/869 clk: mediatek: pllfh: Fix IO remapping leak in register_pllfhs error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Louis-Alexis Eyraud <[email protected]>
[ Upstream commit 540d91480bcb1b28a62d7023aa70947ea44c55b9 ]
When mtk_clk_register_pllfhs function fails to register a PLL, it unregisters all PLLs and cleans up itself in its error path before returning, so the function callers don't need to do it.
But contrary to mtk_clk_unregister_pllfhs function, that does almost the same sequence, it does not free the IO memory mapped on fhctl node, leading to a leak.
Fix this leak by factorizing the cleanup sequence in a new private function and use it both mtk_clk_register_pllfhs and mtk_clk_unregister_pllfhs functions.
Also, change the loop index start value to avoid the -1 operation on index at each loop.
--- drivers/clk/mediatek/clk-pllfh.c | 98 ++++++++++++++++---------------- 1 file changed, 49 insertions(+), 49 deletions(-)
drivers/clk/mediatek/clk-pllfh.c +49 -49
@@ -194,12 +194,56 @@ static void mtk_clk_unregister_pllfh(struct clk_hw *hw)kfree (fh); } +static void mtk_clk_cleanup_pllfhs (void __iomem *iomem_base, +const struct mtk_pll_data *plls,int num_plls, +void __iomem *iomem_fhctl_base, +struct mtk_pllfh_data *pllfhs,int num_fhs, +struct clk_hw_onecell_data *clk_data) +{ +void __iomem *base = iomem_base; +void __iomem *fhctl_base = iomem_fhctl_base; +int i; + +for (i = num_plls -1 ; i >=0 ; i--) { +const struct mtk_pll_data *pll = &plls[i]; +struct mtk_pllfh_data *pllfh; +bool use_fhctl; + +if (IS_ERR_OR_NULL (clk_data->hws[pll->id])) +continue ; + + pllfh =get_pllfh_by_id (pllfhs, num_fhs, pll->id); + use_fhctl =fhctl_is_supported_and_enabled (pllfh); + +if (!base) + base =mtk_clk_pll_get_base (clk_data->hws[pll->id], + pll); + +if (use_fhctl) { +if (!fhctl_base) + fhctl_base = pllfh->state.base; +mtk_clk_unregister_pllfh (clk_data->hws[pll->id]); + }else { +mtk_clk_unregister_pll (clk_data->hws[pll->id]); + } + + clk_data->hws[pll->id] =ERR_PTR (-ENOENT ); + } + +if (fhctl_base) +iounmap (fhctl_base); + +if (base) +iounmap (base); +} + +int mtk_clk_register_pllfhs (struct device_node *node,const struct mtk_pll_data *plls,int num_plls,struct mtk_pllfh_data *pllfhs,int num_fhs,struct clk_hw_onecell_data *clk_data) { -void __iomem *base; +void __iomem *base, *fhctl_base =NULL ;int i;struct clk_hw *hw;
@@ -235,24 +279,8 @@ int mtk_clk_register_pllfhs(struct device_node *node,return 0 ; err: -while (--i >=0 ) { -const struct mtk_pll_data *pll = &plls[i]; -struct mtk_pllfh_data *pllfh; -bool use_fhctl; - - pllfh =get_pllfh_by_id (pllfhs, num_fhs, pll->id); - use_fhctl =fhctl_is_supported_and_enabled (pllfh); - -if (use_fhctl) -mtk_clk_unregister_pllfh (clk_data->hws[pll->id]); -else -mtk_clk_unregister_pll (clk_data->hws[pll->id]); - - clk_data->hws[pll->id] =ERR_PTR (-ENOENT ); - } - -iounmap (base); - +mtk_clk_cleanup_pllfhs (base, plls, i, fhctl_base, pllfhs, num_fhs, + clk_data);return PTR_ERR (hw); }EXPORT_SYMBOL_GPL (mtk_clk_register_pllfhs);
@@ -261,38 +289,10 @@ void mtk_clk_unregister_pllfhs(const struct mtk_pll_data *plls, int num_plls, struct mtk_pllfh_data *pllfhs, int num_fhs, struct clk_hw_onecell_data *clk_data) { - void __iomem *base = NULL, *fhctl_base = NULL; -int i; - if (!clk_data) return; -for (i = num_plls; i >0 ; i--) { -const struct mtk_pll_data *pll = &plls[i -1 ]; -struct mtk_pllfh_data *pllfh; -bool use_fhctl; - -if (IS_ERR_OR_NULL (clk_data->hws[pll->id])) -continue ; - - pllfh =get_pllfh_by_id (pllfhs, num_fhs, pll->id); - use_fhctl =fhctl_is_supported_and_enabled (pllfh); - -if (use_fhctl) { - fhctl_base = pllfh->state.base; -mtk_clk_unregister_pllfh (clk_data->hws[pll->id]); - }else { - base =mtk_clk_pll_get_base (clk_data->hws[pll->id], - pll); -mtk_clk_unregister_pll (clk_data->hws[pll->id]); - } - - clk_data->hws[pll->id] =ERR_PTR (-ENOENT ); - } - -if (fhctl_base) -iounmap (fhctl_base); - -iounmap (base); +mtk_clk_cleanup_pllfhs (NULL ,plls ,num_plls ,NULL ,pllfhs , +num_fhs ,clk_data ); }EXPORT_SYMBOL_GPL (mtk_clk_unregister_pllfhs);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 689/869 iommu/tegra241-cmdqv: Fix VINTF0 leak on the init-failure path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nicolin Chen <[email protected]>
[ Upstream commit f40f3144477314b489e4bc209c06cb51679fe82b ]
tegra241_cmdqv_init_structures() allocates VINTF0 with kzalloc_obj(), inits it, and preallocates its logical VCMDQs. Two of its error paths leak.
When tegra241_cmdqv_init_vintf() fails it returns before VINTF0 reaches the cmdqv->vintfs[] array, so the devres unwind on probe failure cannot reach it; free it directly there.
A later VCMDQ preallocation failure instead leaves VINTF0 published, and so this time the unwind does reach tegra241_cmdqv_remove_vintf(), which then frees it from vintf->hyp_own. But tegra241_vintf_hw_init() sets that flag only afterward, from a HW read-back, so the still-uninited VINTF0 reads as guest-owned and leaks, with mutex_destroy() and ida_destroy() run on fields it never set up.
Decide ownership from vintf->idx instead, the index assigned when its id is
allocated: idx 0 is the kernel-owned VINTF0, while idx >= 1 marks a guest VINTF. So the in-kernel free decision in tegra241_cmdqv_remove_vintf() and tegra241_vintf_free_lvcmdq() now keys on idx too, and hyp_own stays a pure HW-readback state.
--- drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +6 -0
@@ -778,6 +778,12 @@ static int tegra241_cmdqv_init_structures(struct arm_smmu_device *smmu) ret =tegra241_cmdqv_init_vintf (cmdqv,0 , vintf);if (ret) {dev_err (cmdqv->dev,"failed to init vintf0: %d\n" , ret); +/* +* tegra241_cmdqv_init_vintf() failed to publish the vintf0 to +* cmdqv->vintfs[], so the probe unwind path that goes through +* cmdqv->vintfs[] would miss it. Free it here. +*/ +kfree (vintf);return ret; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 690/869 iommu/tegra241-cmdqv: Dont fall back to a freed smmu after devm_krealloc()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nicolin Chen <[email protected]>
[ Upstream commit d4d05f55e9da646ec03adfa77260eb46f4163749 ]
__tegra241_cmdqv_probe() uses devm_krealloc() to grow @smmu into the larger tegra241_cmdqv, which frees the original @smmu once it relocates. A failure after that returned NULL, and the caller then dereferenced the freed @smmu on its fallback path.
Return an int and take @smmu by reference instead, then update *smmu to the reallocated pointer after devm_krealloc() succeeds, so the caller and its fallback path both use the live @smmu rather than the freed original.
--- .../iommu/arm/arm-smmu-v3/tegra241-cmdqv.c | 54 +++++++++++-------- 1 file changed, 32 insertions(+), 22 deletions(-)
drivers/iommu/arm/arm-smmu-v3/tegra241-cmdqv.c +32 -22
@@ -805,16 +805,22 @@ static int tegra241_cmdqv_init_structures(struct arm_smmu_device *smmu)static struct dentry *cmdqv_debugfs_dir;#endif -static struct arm_smmu_device * -__tegra241_cmdqv_probe (struct arm_smmu_device *smmu,struct resource *res, -int irq) +/* +* Probe the CMDQV and reallocate @smmu into the larger cmdqv->smmu. +* +* devm_krealloc() may relocate and free the original @smmu, so update *smmu to +* the new pointer once it succeeds. The error paths after it do the same, so a +* caller falling back keeps a live @smmu instead of the freed original. +*/ +static int __tegra241_cmdqv_probe (struct arm_smmu_device **smmu, +struct resource *res,int irq) {static const struct arm_smmu_impl_ops init_ops = { .init_structures = tegra241_cmdqv_init_structures, .device_remove = tegra241_cmdqv_remove, }; -struct tegra241_cmdqv *cmdqv =NULL ; -struct arm_smmu_device *new_smmu; +struct device *dev = (*smmu)->dev; +struct tegra241_cmdqv *cmdqv;void __iomem *base;u32 regval;int ret;
@@ -823,25 +829,28 @@ __tegra241_cmdqv_probe(struct arm_smmu_device *smmu, struct resource *res, base =ioremap (res->start,resource_size (res));if (!base) { -dev_err (smmu->dev,"failed to ioremap\n" ); -return NULL ; +dev_err (dev,"failed to ioremap\n" ); +return -ENOMEM ; } regval =readl (base +TEGRA241_CMDQV_CONFIG );if (disable_cmdqv) { -dev_info (smmu->dev,"Detected disable_cmdqv=true\n" ); +dev_info (dev,"Detected disable_cmdqv=true\n" );writel (regval & ~CMDQV_EN , base +TEGRA241_CMDQV_CONFIG ); + ret = -ENODEV ; goto iounmap; } - cmdqv =devm_krealloc (smmu->dev, smmu,sizeof (*cmdqv),GFP_KERNEL ); -if (!cmdqv) + cmdqv =devm_krealloc (dev, *smmu,sizeof (*cmdqv),GFP_KERNEL ); +if (!cmdqv) { + ret = -ENOMEM ; goto iounmap; - new_smmu = &cmdqv->smmu; + } + *smmu = &cmdqv->smmu; cmdqv->irq = irq; cmdqv->base = base; - cmdqv->dev = smmu->impl_dev; + cmdqv->dev = (*smmu)->impl_dev; regval =readl_relaxed (REG_CMDQV (cmdqv,PARAM )); cmdqv->num_vintfs =1 <<FIELD_GET (CMDQV_NUM_VINTF_LOG2 , regval);
@@ -850,8 +859,10 @@ __tegra241_cmdqv_probe(struct arm_smmu_device *smmu, struct resource *res, cmdqv->vintfs =kcalloc (cmdqv->num_vintfs,sizeof (*cmdqv->vintfs),GFP_KERNEL ); -if (!cmdqv->vintfs) +if (!cmdqv->vintfs) { + ret = -ENOMEM ; goto iounmap; + }ida_init (&cmdqv->vintf_ids);
@@ -880,38 +891,37 @@ __tegra241_cmdqv_probe(struct arm_smmu_device *smmu, struct resource *res,#endif /* Provide init-level ops only, until tegra241_cmdqv_init_structures */ - new_smmu->impl_ops = &init_ops; + cmdqv->smmu.impl_ops = &init_ops; -return new_smmu; +return 0 ; free_vintfs:ida_destroy (&cmdqv->vintf_ids);kfree (cmdqv->vintfs); iounmap:iounmap (base); -return NULL ; +return ret; }struct arm_smmu_device *tegra241_cmdqv_probe (struct arm_smmu_device *smmu) { -struct arm_smmu_device *new_smmu;struct resource *res =NULL ; -int irq; +int irq, ret;if (!smmu->dev->of_node) res =tegra241_cmdqv_find_acpi_resource (smmu->impl_dev, &irq);if (!res) goto out_fallback; - new_smmu =__tegra241_cmdqv_probe (smmu, res, irq); + ret =__tegra241_cmdqv_probe (&smmu, res, irq);kfree (res); -if (new_smmu) -return new_smmu; +if (!ret) +return smmu; out_fallback:dev_info (smmu->impl_dev,"Falling back to standard SMMU CMDQ\n" ); smmu->options &= ~ARM_SMMU_OPT_TEGRA241_CMDQV ;put_device (smmu->impl_dev); -return ERR_PTR (-ENODEV ); +return smmu; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 691/869 scsi: ufs: core: Convert string descriptor format macros to enum
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bean Huo <[email protected]>
[ Upstream commit 0d9a7085ec24983b5b8a4971c0eb6c756c75f1bf ]
Convert SD_ASCII_STD and SD_RAW from boolean macros to enum values for improved code readability. This makes ufshcd_read_string_desc() calls self-documenting by using explicit enum values instead of true/false.
Move the ufshcd_read_string_desc() declaration from include/ufs/ufshcd.h to drivers/ufs/core/ufshcd-priv.h since this function is not exported.
Stable-dep-of: d96e83d028d7 ("scsi: ufs: core: Validate string descriptors")
--- drivers/ufs/core/ufshcd-priv.h | 14 ++++++++++---- drivers/ufs/core/ufshcd.c | 8 +++----- include/ufs/ufshcd.h | 4 ---- 3 files changed, 13 insertions(+), 13 deletions(-)
drivers/ufs/core/ufshcd-priv.h +10 -4
@@ -78,11 +78,17 @@ int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);void ufshcd_release_scsi_cmd (struct ufs_hba *hba,struct ufshcd_lrb *lrbp); -#define SD_ASCII_STD true -#define SD_RAW false -int ufshcd_read_string_desc (struct ufs_hba *hba,u8 desc_index, -u8 **buf,bool ascii); +/** +* enum ufs_descr_fmt - UFS string descriptor format +* @SD_RAW: Raw UTF-16 format +* @SD_ASCII_STD: Convert to null-terminated ASCII string +*/ +enum ufs_descr_fmt { +SD_RAW =0 , +SD_ASCII_STD =1 , +}; +int ufshcd_read_string_desc (struct ufs_hba *hba,u8 desc_index,u8 **buf,enum ufs_descr_fmt fmt);int ufshcd_send_uic_cmd (struct ufs_hba *hba,struct uic_command *uic_cmd);int ufshcd_send_bsg_uic_cmd (struct ufs_hba *hba,struct uic_command *uic_cmd);
drivers/ufs/core/ufshcd.c +3 -5
@@ -3738,16 +3738,14 @@ static inline char ufshcd_remove_non_printable(u8 ch)* @desc_index: descriptor index * @buf: pointer to buffer where descriptor would be read, * the caller should free the memory. -* @ascii: if true convert from unicode to ascii characters -* null terminated string. +* @fmt: if %SD_ASCII_STD, convert from UTF-16 to ASCII * * Return: * * string size on success. * * -ENOMEM: on allocation failure * * -EINVAL: on a wrong parameter */ -int ufshcd_read_string_desc (struct ufs_hba *hba,u8 desc_index, -u8 **buf,bool ascii) +int ufshcd_read_string_desc (struct ufs_hba *hba,u8 desc_index,u8 **buf,enum ufs_descr_fmt fmt) {struct uc_string_id *uc_str;u8 *str;
@@ -3776,7 +3774,7 @@ int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, goto out; } -if (ascii) { +if (fmt ==SD_ASCII_STD ) {ssize_t ascii_len;int i;/* remove header and divide by 2 to move from UTF16 to UTF8 */
include/ufs/ufshcd.h +0 -4
@@ -1440,10 +1440,6 @@ static inline int ufshcd_disable_host_tx_lcc(struct ufs_hba *hba)void ufshcd_auto_hibern8_update (struct ufs_hba *hba,u32 ahit);void ufshcd_fixup_dev_quirks (struct ufs_hba *hba,const struct ufs_dev_quirk *fixups); -#define SD_ASCII_STD true -#define SD_RAW false -int ufshcd_read_string_desc (struct ufs_hba *hba,u8 desc_index, -u8 **buf,bool ascii);void ufshcd_hold (struct ufs_hba *hba);void ufshcd_release (struct ufs_hba *hba);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 692/869 scsi: ufs: core: Validate string descriptors
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Qiang <[email protected]>
[ Upstream commit d96e83d028d7d8762e424e49c671d49ac2ecf14f ]
The string descriptor length includes a two-byte header while the UTF-16 payload starts after it. utf16s_to_utf8s() expects a count of UTF-16 code units, not bytes. Passing the payload byte count can make it read beyond the descriptor buffer.
Validate that the payload has an even byte count, pass a code-unit count to the converter, and allocate sufficient UTF-8 output space.
The raw string buffer starts after the descriptor header but its size is bLength. Copying bLength bytes from that pointer can read beyond the response buffer.
Allocate a zeroed bLength-sized buffer and copy only the UTF-16 payload. This preserves the raw buffer size consumed by the RPMB device-ID ABI while avoiding the overread.
--- drivers/ufs/core/ufshcd.c | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-)
drivers/ufs/core/ufshcd.c +19 -5
@@ -3749,7 +3749,7 @@ int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, enum u {struct uc_string_id *uc_str;u8 *str; -int ret; +int ret, uc_len;if (!buf)return -EINVAL ;
@@ -3774,11 +3774,19 @@ int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, enum u goto out; } + uc_len = uc_str->len -QUERY_DESC_HDR_SIZE ; +if (uc_len %sizeof (*uc_str->uc)) { +dev_err (hba->dev,"String Desc has an odd UTF-16 payload length\n" ); + str =NULL ; + ret = -EINVAL ; + goto out; + } +if (fmt ==SD_ASCII_STD ) {ssize_t ascii_len;int i; -/* remove header and divide by 2 to move from UTF16 to UTF8 */ - ascii_len = (uc_str->len -QUERY_DESC_HDR_SIZE ) /2 +1 ; +/* Allow up to three UTF-8 bytes per UTF-16 code unit plus a NUL. */ + ascii_len = uc_len /sizeof (*uc_str->uc) *3 +1 ; str =kzalloc (ascii_len,GFP_KERNEL );if (!str) { ret = -ENOMEM ;
@@ -3790,7 +3798,7 @@ int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, enum u* we need to convert to utf-8 so it can be displayed */ ret =utf16s_to_utf8s (uc_str->uc, - uc_str->len -QUERY_DESC_HDR_SIZE , + uc_len /sizeof (*uc_str->uc),UTF16_BIG_ENDIAN , str, ascii_len -1 );/* replace non-printable or non-ASCII characters with spaces */
@@ -3800,11 +3808,17 @@ int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, enum u str[ret++] ='\0' ; }else { - str =kmemdup (uc_str->uc, uc_str->len,GFP_KERNEL ); +/* +* Keep the bLength-sized raw output for the RPMB device ID ABI. +* The two bytes beyond the UTF-16 payload are explicitly zeroed +* instead of being read past the descriptor buffer. +*/ + str =kzalloc (uc_str->len,GFP_KERNEL );if (!str) { ret = -ENOMEM ; goto out; } +memcpy (str, uc_str->uc, uc_len); ret = uc_str->len; } out:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 693/869 pinctrl: mediatek: use devm_gpiochip_add_data() for GPIO chip
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Justin Yeh <[email protected]>
[ Upstream commit 9c650317ba553d297f3fc5f0ae40ec53d86f9dab ]
The gpio_chip is allocated with device-managed memory but registered with the non-managed gpiochip_add_data(). This was harmless while the drivers were built-in, but once they can be built as modules and unbound/rmmod'd, devm frees the gpio_chip's memory while it is still registered, causing a use-after-free.
Register it with devm_gpiochip_add_data() so it shares the same device-managed lifecycle, which also lets the manual gpiochip_remove() error paths go away.
--- drivers/pinctrl/mediatek/pinctrl-moore.c | 6 ++---- drivers/pinctrl/mediatek/pinctrl-mtk-common.c | 14 ++++---------- drivers/pinctrl/mediatek/pinctrl-paris.c | 2 +- 3 files changed, 7 insertions(+), 15 deletions(-)
drivers/pinctrl/mediatek/pinctrl-moore.c +2 -4
@@ -573,7 +573,7 @@ static int mtk_build_gpiochip(struct mtk_pinctrl *hw) chip->base =-1 ; chip->ngpio = hw->soc->npins; - ret =gpiochip_add_data (chip, hw); + ret =devm_gpiochip_add_data (hw->dev, chip, hw);if (ret <0 )return ret;
@@ -587,10 +587,8 @@ static int mtk_build_gpiochip(struct mtk_pinctrl *hw)if (!of_property_present (hw->dev->of_node,"gpio-ranges" )) { ret =gpiochip_add_pin_range (chip,dev_name (hw->dev),0 ,0 , chip->ngpio); -if (ret <0 ) { -gpiochip_remove (chip); +if (ret <0 )return ret; - } }return 0 ;
drivers/pinctrl/mediatek/pinctrl-mtk-common.c +4 -10
@@ -1118,30 +1118,24 @@ int mtk_pctrl_init(struct platform_device *pdev, pctl->chip->parent = &pdev->dev; pctl->chip->base =-1 ; - ret =gpiochip_add_data (pctl->chip, pctl); + ret =devm_gpiochip_add_data (&pdev->dev, pctl->chip, pctl);if (ret)return -EINVAL ;/* Register the GPIO to pin mappings. */ ret =gpiochip_add_pin_range (pctl->chip,dev_name (&pdev->dev),0 ,0 , pctl->devdata->npins); -if (ret) { - ret = -EINVAL ; - goto chip_error; - } +if (ret) +return -EINVAL ;/* Only initialize EINT if we have EINT pins */ if (data->eint_hw.ap_num >0 ) { ret =mtk_eint_init (pctl, pdev);if (ret) - goto chip_error; +return ret; }return 0 ; - -chip_error: -gpiochip_remove (pctl->chip); -return ret; }int mtk_pctrl_common_probe (struct platform_device *pdev)
drivers/pinctrl/mediatek/pinctrl-paris.c +1 -1
@@ -970,7 +970,7 @@ static int mtk_build_gpiochip(struct mtk_pinctrl *hw) chip->base =-1 ; chip->ngpio = hw->soc->npins; - ret =gpiochip_add_data (chip, hw); + ret =devm_gpiochip_add_data (hw->dev, chip, hw);if (ret <0 )return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 694/869 bpf: Fix WARNING in bpf_tracing_link_release
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Leon Hwang <[email protected]>
[ Upstream commit 61aaa8782bec59ecffd22e030f54ef9351bcabf9 ]
The trampoline could be corrupted by the blindly 'tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX' in verifier.
1. A fexit attached to a tail_call_reachable prog. 'tr->flags' became 'BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_TAIL_CALL_CTX'. And, the trampoline would poke the target prog's nop insn using jmp insn instead of call insn.
2. Another fexit loaded with the same tail_call_reachable prog target. 'tr->flags' became 'BPF_TRAMP_F_TAIL_CALL_CTX'.
3. Close the first fexit link. Due to no BPF_TRAMP_F_CALL_ORIG in 'tr->flags', the trampoline will fail to restore the prog's nop insn using call insn.
[ 3.410719] WARNING: kernel/bpf/syscall.c:3551 at bpf_tracing_link_release+0x53/0x60, CPU#1: test_progs/98 ... [ 3.428793] bpf_link_free+0x58/0x130 [ 3.429293] bpf_link_release+0x23/0x30
Fix the warning by updating 'tr->flags' with '|=' and lock.
--- include/linux/bpf.h | 3 +++ kernel/bpf/trampoline.c | 7 +++++++ kernel/bpf/verifier.c | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-)
include/linux/bpf.h +3 -0
@@ -1323,6 +1323,8 @@ struct bpf_trampoline *bpf_trampoline_get(u64 key,void bpf_trampoline_put (struct bpf_trampoline *tr);int arch_prepare_bpf_dispatcher (void *image,void *buf,s64 *funcs,int num_funcs); +void bpf_trampoline_set_flags (struct bpf_trampoline *tr,u32 flags); +/* * When the architecture supports STATIC_CALL replace the bpf_dispatcher_fn * indirection with a direct call to the bpf program. If the architecture does
@@ -1431,6 +1433,7 @@ static inline bool bpf_prog_has_trampoline(const struct bpf_prog *prog) {return false; } +static inline void bpf_trampoline_set_flags (struct bpf_trampoline *tr,u32 flags) {}#endif struct bpf_func_info_aux {
kernel/bpf/trampoline.c +7 -0
@@ -397,6 +397,13 @@ static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key, int size)return ERR_PTR (err); } +void bpf_trampoline_set_flags (struct bpf_trampoline *tr,u32 flags) +{ +mutex_lock (&tr->mutex); + tr->flags |= flags; +mutex_unlock (&tr->mutex); +} +static int bpf_trampoline_update (struct bpf_trampoline *tr,bool lock_direct_mutex) {struct bpf_tramp_image *im;
kernel/bpf/verifier.c +1 -1
@@ -22908,7 +22908,7 @@ static int check_attach_btf_id(struct bpf_verifier_env *env)return -ENOMEM ;if (tgt_prog && tgt_prog->aux->tail_call_reachable) - tr->flags =BPF_TRAMP_F_TAIL_CALL_CTX ; +bpf_trampoline_set_flags (tr,BPF_TRAMP_F_TAIL_CALL_CTX ); prog->aux->dst_trampoline = tr;return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 695/869 ext4: fix ABBA deadlock in ext4_xattr_inode_cache_find()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aditya Prakash Srivastava <[email protected]>
[ Upstream commit 03438084a7b8621fb5c762dd3d04cff5f2630fb2 ]
Syzbot/stress-ng reported an ABBA deadlock in ext4 when exercising concurrent xattr workloads (using the ea_inode mount/format option).
The deadlock occurs between the running transaction and the eviction thread:
- Task 1 (stress-ng): Holds a reference to a shared mbcache_entry (ce) and calls ext4_xattr_inode_cache_find() -> ext4_iget() to retrieve the corresponding EA inode. Since the EA inode is currently being evicted, ext4_iget() blocks in __wait_on_freeing_inode() waiting for eviction to complete.
- Task 2 (eviction thread): Currently evicting the same EA inode in ext4_evict_ea_inode(). It calls mb_cache_entry_wait_unused(oe) which blocks waiting for Task 1 to release the reference to the mbcache_entry.
To break this deadlock, implement a new ext4_iget() configuration flag named EXT4_IGET_NOWAIT. When set, perform a non-blocking lookup of the inode via VFS's find_inode_nowait() API.
If the inode is currently being evicted (marked with I_FREEING or I_WILL_FREE) or created (I_CREATING), or if it is not present in the VFS inode cache (cache miss), simply skip it (returning -ENOENT) rather than waiting for eviction/creation to complete, breaking the ABBA cycle.
Since we return -ENOENT immediately on a cache miss, we never attempt to allocate a new inode or call iget_locked(), completely eliminating any TOCTOU race window.
If the returned inode is I_NEW, wait for its initialization to clear via wait_on_new_inode(). If initialization fails and the inode is unhashed during wait_on_new_inode() waking up (e.g., due to an I/O read error in another thread), safely drop the reference and return -ENOENT. This unhashed check is executed unconditionally on all cache-hit pathways to properly handle concurrent initialization failures.
Finally, standard validation checks (including is_bad_inode, EXT4_EA_INODE_FL, file_acl, and xattr flags) are executed as normal inside check_igot_inode() to fully guarantee VFS-layer safety.
In ext4_xattr_inode_cache_find(), invoke ext4_iget() with the new EXT4_IGET_NOWAIT flag to perform the non-blocking cache search.
--- fs/ext4/ext4.h | 3 ++- fs/ext4/inode.c | 35 ++++++++++++++++++++++++++++++++--- fs/ext4/xattr.c | 2 +- 3 files changed, 35 insertions(+), 5 deletions(-)
fs/ext4/ext4.h +2 -1
@@ -2984,7 +2984,8 @@ typedef enum {EXT4_IGET_SPECIAL =0x0001 ,/* OK to iget a system inode */ EXT4_IGET_HANDLE =0x0002 ,/* Inode # is from a handle */ EXT4_IGET_BAD =0x0004 ,/* Allow to iget a bad inode */ - EXT4_IGET_EA_INODE = 0x0008 /* Inode should contain an EA value */ +EXT4_IGET_EA_INODE =0x0008 ,/* Inode should contain an EA value */ + EXT4_IGET_NOWAIT = 0x0010 /* Non-blocking lookup (skip if freeing) */ } ext4_iget_flags; extern struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
fs/ext4/inode.c +32 -3
@@ -4783,6 +4783,20 @@ error:return -EFSCORRUPTED ; } +static int ext4_iget_match (struct inode *inode,unsigned long ino,void *data) +{ +if (inode->i_ino != ino) +return 0 ; +spin_lock (&inode->i_lock); +if (inode->i_state & (I_FREEING |I_WILL_FREE |I_CREATING )) { +spin_unlock (&inode->i_lock); +return -1 ; + } +__iget (inode); +spin_unlock (&inode->i_lock); +return 1 ; +} +struct inode *__ext4_iget (struct super_block *sb,unsigned long ino,ext4_iget_flags flags,const char *function,unsigned int line)
@@ -4816,9 +4830,24 @@ struct inode *__ext4_iget(struct super_breturn ERR_PTR (-EFSCORRUPTED ); } - inode =iget_locked (sb, ino); -if (!inode) -return ERR_PTR (-ENOMEM ); +if (flags &EXT4_IGET_NOWAIT ) { + inode =find_inode_nowait (sb, ino, ext4_iget_match,NULL ); +if (!inode) +return ERR_PTR (-ENOENT ); + +if (inode->i_state &I_NEW ) +wait_on_inode (inode); + +if (unlikely (inode_unhashed (inode))) { +iput (inode); +return ERR_PTR (-ENOENT ); + } + }else { + inode =iget_locked (sb, ino); +if (!inode) +return ERR_PTR (-ENOMEM ); + } +if (!(inode->i_state &I_NEW )) { ret =check_igot_inode (inode, flags, function, line);if (ret) {
fs/ext4/xattr.c +1 -1
@@ -1550,7 +1550,7 @@ ext4_xattr_inode_cache_find(struct inodewhile (ce) { ea_inode =ext4_iget (inode->i_sb, ce->e_value, -EXT4_IGET_EA_INODE ); +EXT4_IGET_EA_INODE |EXT4_IGET_NOWAIT );if (IS_ERR (ea_inode)) goto next_entry;ext4_xattr_inode_set_class (ea_inode);
Greg Kroah-Hartman
maintainerPATCH 696/869 kcfi: Rename CONFIG_CFI_CLANG to CONFIG_CFI
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kees Cook <[email protected]>
[ Upstream commit 23ef9d439769d5f35353650e771c63d13824235b ]
The kernel's CFI implementation uses the KCFI ABI specifically, and is not strictly tied to a particular compiler. In preparation for GCC supporting KCFI, rename CONFIG_CFI_CLANG to CONFIG_CFI (along with associated options).
Use new "transitional" Kconfig option for old CONFIG_CFI_CLANG that will enable CONFIG_CFI during olddefconfig.
[ Adapted to this tree: the kconfig here has no "transitional" keyword, so
the CFI_CLANG compat symbol is omitted; re-applied the rename on top of the local contents of the conflicting files, converted the remaining CONFIG_CFI_CLANG users (riscv cfi.c, longest_symbol kunit comment), and dropped the tools/ cfi_types.h hunk as that file is absent here. ]
Stable-dep-of: 52fb1756ea1d ("riscv, bpf: Fix kernel stack corruption in tailcall with CFI")
--- Makefile | 2 +- arch/Kconfig | 26 ++++++++++++------------- arch/arm/Kconfig | 2 +- arch/arm/kernel/hw_breakpoint.c | 2 +- arch/arm/mm/Makefile | 2 +- arch/arm/mm/cache-fa.S | 2 +- arch/arm/mm/cache-v4.S | 2 +- arch/arm/mm/cache-v4wb.S | 4 ++-- arch/arm/mm/cache-v4wt.S | 2 +- arch/arm/mm/cache-v6.S | 2 +- arch/arm/mm/cache-v7.S | 2 +- arch/arm/mm/cache-v7m.S | 2 +- arch/arm/mm/proc-arm1020.S | 2 +- arch/arm/mm/proc-arm1020e.S | 2 +- arch/arm/mm/proc-arm1022.S | 2 +- arch/arm/mm/proc-arm1026.S | 2 +- arch/arm/mm/proc-arm920.S | 2 +- arch/arm/mm/proc-arm922.S | 2 +- arch/arm/mm/proc-arm925.S | 2 +- arch/arm/mm/proc-arm926.S | 2 +- arch/arm/mm/proc-arm940.S | 2 +- arch/arm/mm/proc-arm946.S | 2 +- arch/arm/mm/proc-feroceon.S | 2 +- arch/arm/mm/proc-mohawk.S | 2 +- arch/arm/mm/proc-xsc3.S | 2 +- arch/arm/mm/tlb-v4.S | 2 +- arch/arm64/Kconfig | 4 ++-- arch/arm64/kernel/debug-monitors.c | 2 +- arch/arm64/kernel/traps.c | 4 ++-- arch/arm64/kvm/handle_exit.c | 2 +- arch/riscv/Kconfig | 4 ++-- arch/riscv/include/asm/cfi.h | 4 ++-- arch/riscv/kernel/Makefile | 2 +- arch/riscv/kernel/cfi.c | 2 +- arch/riscv/net/bpf_jit_comp64.c | 4 ++-- arch/riscv/purgatory/Makefile | 2 +- arch/x86/Kconfig | 12 ++++++------ arch/x86/include/asm/cfi.h | 4 ++-- arch/x86/kernel/Makefile | 2 +- arch/x86/kernel/alternative.c | 4 ++-- arch/x86/kernel/kprobes/core.c | 2 +- arch/x86/purgatory/Makefile | 2 +- drivers/misc/lkdtm/cfi.c | 2 +- include/asm-generic/vmlinux.lds.h | 2 +- include/linux/cfi.h | 4 ++-- include/linux/cfi_types.h | 6 +++--- init/Kconfig | 4 ++-- kernel/Makefile | 2 +- kernel/configs/hardening.config | 4 ++-- kernel/module/Kconfig | 2 +- lib/longest_symbol_kunit.c | 2 +- tools/perf/util/include/linux/linkage.h | 2 +- 52 files changed, 82 insertions(+), 82 deletions(-)
Makefile +1 -1
@@ -963,7 +963,7 @@ KBUILD_AFLAGS += -fno-lto export CC_FLAGS_LTO endif -ifdef CONFIG_CFI_CLANG +ifdef CONFIG_CFI CC_FLAGS_CFI := -fsanitize=kcfi ifdef CONFIG_CFI_ICALL_NORMALIZE_INTEGERS CC_FLAGS_CFI += -fsanitize-cfi-icall-experimental-normalize-integers
arch/Kconfig +13 -13
@@ -812,22 +812,22 @@ config LTO_CLANG_THIN If unsure, say Y. endchoice -config ARCH_SUPPORTS_CFI_CLANG +config ARCH_SUPPORTS_CFI bool help - An architecture should select this option if it can support Clang's - Control-Flow Integrity (CFI) checking. + An architecture should select this option if it can support Kernel + Control-Flow Integrity (CFI) checking (-fsanitize=kcfi). config ARCH_USES_CFI_TRAPS bool -config CFI_CLANG - bool "Use Clang's Control Flow Integrity (CFI)" - depends on ARCH_SUPPORTS_CFI_CLANG +config CFI + bool "Use Kernel Control Flow Integrity (kCFI)" + depends on ARCH_SUPPORTS_CFI depends on $(cc-option,-fsanitize=kcfi) help - This option enables Clang's forward-edge Control Flow Integrity - (CFI) checking, where the compiler injects a runtime check to each + This option enables forward-edge Control Flow Integrity (CFI) + checking, where the compiler injects a runtime check to each indirect function call to ensure the target is a valid function with the correct static type. This restricts possible call targets and makes it more difficult for an attacker to exploit bugs that allow
@@ -838,8 +838,8 @@ config CFI_CLANG config CFI_ICALL_NORMALIZE_INTEGERS bool "Normalize CFI tags for integers" - depends on CFI_CLANG - depends on HAVE_CFI_ICALL_NORMALIZE_INTEGERS_CLANG + depends on CFI + depends on HAVE_CFI_ICALL_NORMALIZE_INTEGERS help This option normalizes the CFI tags for integer types so that all integer types of the same size and signedness receive the same CFI
@@ -852,7 +852,7 @@ config CFI_ICALL_NORMALIZE_INTEGERS This option is necessary for using CFI with Rust. If unsure, say N. -config HAVE_CFI_ICALL_NORMALIZE_INTEGERS_CLANG +config HAVE_CFI_ICALL_NORMALIZE_INTEGERS def_bool y depends on $(cc-option,-fsanitize=kcfi -fsanitize-cfi-icall-experimental-normalize-integers) # With GCOV/KASAN we need this fix: https://github.com/llvm/llvm-project/pull/104826
@@ -860,7 +860,7 @@ config HAVE_CFI_ICALL_NORMALIZE_INTEGERS_CLANG config HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC def_bool y - depends on HAVE_CFI_ICALL_NORMALIZE_INTEGERS_CLANG + depends on HAVE_CFI_ICALL_NORMALIZE_INTEGERS depends on RUSTC_VERSION >= 107900 depends on ARM64 || X86_64 # With GCOV/KASAN we need this fix: https://github.com/rust-lang/rust/pull/129373
@@ -869,7 +869,7 @@ config HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC config CFI_PERMISSIVE bool "Use CFI in permissive mode" - depends on CFI_CLANG + depends on CFI help When selected, Control Flow Integrity (CFI) violations result in a warning instead of a kernel panic. This option should only be used
arch/arm/Kconfig +1 -1
@@ -37,7 +37,7 @@ config ARM select ARCH_OPTIONAL_KERNEL_RWX_DEFAULT if CPU_V7 select ARCH_NEED_CMPXCHG_1_EMU if CPU_V6 select ARCH_SUPPORTS_ATOMIC_RMW - select ARCH_SUPPORTS_CFI_CLANG + select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_HUGETLBFS if ARM_LPAE select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_USE_BUILTIN_BSWAP
arch/arm/kernel/hw_breakpoint.c +1 -1
@@ -904,7 +904,7 @@ static void breakpoint_handler(unsigned long unknown, struct pt_regs *regs)watchpoint_single_step_handler (addr); } -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI static void hw_breakpoint_cfi_handler (struct pt_regs *regs) {/*
arch/arm/mm/Makefile +1 -1
@@ -89,7 +89,7 @@ obj-$(CONFIG_CPU_V6) += proc-v6.o obj-$(CONFIG_CPU_V6K) += proc-v6.o obj-$(CONFIG_CPU_V7) += proc-v7.o proc-v7-bugs.o obj-$(CONFIG_CPU_V7M) += proc-v7m.o -obj-$(CONFIG_CFI_CLANG) += proc.o +obj-$(CONFIG_CFI) += proc.o obj-$(CONFIG_OUTER_CACHE) += l2c-common.o obj-$(CONFIG_CACHE_B15_RAC) += cache-b15-rac.o
arch/arm/mm/cache-fa.S +1 -1
@@ -112,7 +112,7 @@ SYM_FUNC_END(fa_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(fa_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b fa_coherent_user_range #endif SYM_FUNC_END(fa_coherent_kern_range)
arch/arm/mm/cache-v4.S +1 -1
@@ -104,7 +104,7 @@ SYM_FUNC_END(v4_coherent_user_range) * - size - region size */ SYM_TYPED_FUNC_START(v4_flush_kern_dcache_area) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v4_dma_flush_range #endif SYM_FUNC_END(v4_flush_kern_dcache_area)
arch/arm/mm/cache-v4wb.S +2 -2
@@ -136,7 +136,7 @@ SYM_FUNC_END(v4wb_flush_user_cache_range) */ SYM_TYPED_FUNC_START(v4wb_flush_kern_dcache_area) add r1, r0, r1 -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v4wb_coherent_user_range #endif SYM_FUNC_END(v4wb_flush_kern_dcache_area)
@@ -152,7 +152,7 @@ SYM_FUNC_END(v4wb_flush_kern_dcache_area) * - end - virtual end address */ SYM_TYPED_FUNC_START(v4wb_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v4wb_coherent_user_range #endif SYM_FUNC_END(v4wb_coherent_kern_range)
arch/arm/mm/cache-v4wt.S +1 -1
@@ -108,7 +108,7 @@ SYM_FUNC_END(v4wt_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(v4wt_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v4wt_coherent_user_range #endif SYM_FUNC_END(v4wt_coherent_kern_range)
arch/arm/mm/cache-v6.S +1 -1
@@ -117,7 +117,7 @@ SYM_FUNC_END(v6_flush_user_cache_range) * - the Icache does not read data from the write buffer */ SYM_TYPED_FUNC_START(v6_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v6_coherent_user_range #endif SYM_FUNC_END(v6_coherent_kern_range)
arch/arm/mm/cache-v7.S +1 -1
@@ -261,7 +261,7 @@ SYM_FUNC_END(v7_flush_user_cache_range) * - the Icache does not read data from the write buffer */ SYM_TYPED_FUNC_START(v7_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v7_coherent_user_range #endif SYM_FUNC_END(v7_coherent_kern_range)
arch/arm/mm/cache-v7m.S +1 -1
@@ -286,7 +286,7 @@ SYM_FUNC_END(v7m_flush_user_cache_range) * - the Icache does not read data from the write buffer */ SYM_TYPED_FUNC_START(v7m_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b v7m_coherent_user_range #endif SYM_FUNC_END(v7m_coherent_kern_range)
arch/arm/mm/proc-arm1020.S +1 -1
@@ -203,7 +203,7 @@ SYM_FUNC_END(arm1020_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm1020_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm1020_coherent_user_range #endif SYM_FUNC_END(arm1020_coherent_kern_range)
arch/arm/mm/proc-arm1020e.S +1 -1
@@ -200,7 +200,7 @@ SYM_FUNC_END(arm1020e_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm1020e_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm1020e_coherent_user_range #endif SYM_FUNC_END(arm1020e_coherent_kern_range)
arch/arm/mm/proc-arm1022.S +1 -1
@@ -199,7 +199,7 @@ SYM_FUNC_END(arm1022_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm1022_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm1022_coherent_user_range #endif SYM_FUNC_END(arm1022_coherent_kern_range)
arch/arm/mm/proc-arm1026.S +1 -1
@@ -194,7 +194,7 @@ SYM_FUNC_END(arm1026_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm1026_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm1026_coherent_user_range #endif SYM_FUNC_END(arm1026_coherent_kern_range)
arch/arm/mm/proc-arm920.S +1 -1
@@ -180,7 +180,7 @@ SYM_FUNC_END(arm920_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm920_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm920_coherent_user_range #endif SYM_FUNC_END(arm920_coherent_kern_range)
arch/arm/mm/proc-arm922.S +1 -1
@@ -182,7 +182,7 @@ SYM_FUNC_END(arm922_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm922_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm922_coherent_user_range #endif SYM_FUNC_END(arm922_coherent_kern_range)
arch/arm/mm/proc-arm925.S +1 -1
@@ -229,7 +229,7 @@ SYM_FUNC_END(arm925_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm925_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm925_coherent_user_range #endif SYM_FUNC_END(arm925_coherent_kern_range)
arch/arm/mm/proc-arm926.S +1 -1
@@ -192,7 +192,7 @@ SYM_FUNC_END(arm926_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm926_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm926_coherent_user_range #endif SYM_FUNC_END(arm926_coherent_kern_range)
arch/arm/mm/proc-arm940.S +1 -1
@@ -153,7 +153,7 @@ SYM_FUNC_END(arm940_coherent_kern_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm940_coherent_user_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm940_flush_kern_dcache_area #endif SYM_FUNC_END(arm940_coherent_user_range)
arch/arm/mm/proc-arm946.S +1 -1
@@ -173,7 +173,7 @@ SYM_FUNC_END(arm946_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(arm946_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b arm946_coherent_user_range #endif SYM_FUNC_END(arm946_coherent_kern_range)
arch/arm/mm/proc-feroceon.S +1 -1
@@ -208,7 +208,7 @@ SYM_FUNC_END(feroceon_flush_user_cache_range) */ .align 5 SYM_TYPED_FUNC_START(feroceon_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b feroceon_coherent_user_range #endif SYM_FUNC_END(feroceon_coherent_kern_range)
arch/arm/mm/proc-mohawk.S +1 -1
@@ -163,7 +163,7 @@ SYM_FUNC_END(mohawk_flush_user_cache_range) * - end - virtual end address */ SYM_TYPED_FUNC_START(mohawk_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b mohawk_coherent_user_range #endif SYM_FUNC_END(mohawk_coherent_kern_range)
arch/arm/mm/proc-xsc3.S +1 -1
@@ -223,7 +223,7 @@ SYM_FUNC_END(xsc3_flush_user_cache_range) * it also trashes the mini I-cache used by JTAG debuggers. */ SYM_TYPED_FUNC_START(xsc3_coherent_kern_range) -#ifdef CONFIG_CFI_CLANG /* Fallthrough if !CFI */ +#ifdef CONFIG_CFI /* Fallthrough if !CFI */ b xsc3_coherent_user_range #endif SYM_FUNC_END(xsc3_coherent_kern_range)
arch/arm/mm/tlb-v4.S +1 -1
@@ -52,7 +52,7 @@ SYM_FUNC_END(v4_flush_user_tlb_range) * - start - virtual address (may not be aligned) * - end - virtual address (may not be aligned) */ -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI SYM_TYPED_FUNC_START(v4_flush_kern_tlb_range) b .v4_flush_kern_tlb_range SYM_FUNC_END(v4_flush_kern_tlb_range)
arch/arm64/Kconfig +2 -2
@@ -97,7 +97,7 @@ config ARM64 select ARCH_SUPPORTS_SHADOW_CALL_STACK if CC_HAVE_SHADOW_CALL_STACK select ARCH_SUPPORTS_LTO_CLANG if CPU_LITTLE_ENDIAN select ARCH_SUPPORTS_LTO_CLANG_THIN - select ARCH_SUPPORTS_CFI_CLANG + select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_INT128 if CC_HAS_INT128 select ARCH_SUPPORTS_NUMA_BALANCING
@@ -207,7 +207,7 @@ config ARM64 select HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS \ if DYNAMIC_FTRACE_WITH_ARGS && DYNAMIC_FTRACE_WITH_CALL_OPS select HAVE_DYNAMIC_FTRACE_WITH_CALL_OPS \ - if (DYNAMIC_FTRACE_WITH_ARGS && !CFI_CLANG && \ + if (DYNAMIC_FTRACE_WITH_ARGS && !CFI && \ (CC_IS_CLANG || !CC_OPTIMIZE_FOR_SIZE)) select FTRACE_MCOUNT_USE_PATCHABLE_FUNCTION_ENTRY \ if DYNAMIC_FTRACE_WITH_ARGS
arch/arm64/kernel/debug-monitors.c +1 -1
@@ -212,7 +212,7 @@ static int call_el1_break_hook(struct pt_regs *regs, unsigned long esr)if (esr_brk_comment (esr) ==BUG_BRK_IMM )return bug_brk_handler (regs, esr); -if (IS_ENABLED (CONFIG_CFI_CLANG ) &&esr_is_cfi_brk (esr)) +if (IS_ENABLED (CONFIG_CFI ) &&esr_is_cfi_brk (esr))return cfi_brk_handler (regs, esr);if (esr_brk_comment (esr) ==FAULT_BRK_IMM )
arch/arm64/kernel/traps.c +2 -2
@@ -1008,7 +1008,7 @@ int bug_brk_handler(struct pt_regs *regs, unsigned long esr)return DBG_HOOK_HANDLED ; } -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI int cfi_brk_handler (struct pt_regs *regs,unsigned long esr) {unsigned long target;
@@ -1032,7 +1032,7 @@ int cfi_brk_handler(struct pt_regs *regs, unsigned long esr)arm64_skip_faulting_instruction (regs,AARCH64_INSN_SIZE ); return DBG_HOOK_HANDLED; } -#endif /* CONFIG_CFI_CLANG */ +#endif /* CONFIG_CFI */ int reserved_fault_brk_handler (struct pt_regs *regs,unsigned long esr) {
arch/arm64/kvm/handle_exit.c +1 -1
@@ -465,7 +465,7 @@ void __noreturn __cold nvhe_hyp_panic_handler(u64 esr, u64 spsr,kvm_err ("nVHE hyp BUG at: %s:%u!\n" , file, line); else print_nvhe_hyp_panic("BUG", panic_addr); - }else if (IS_ENABLED (CONFIG_CFI_CLANG ) &&esr_is_cfi_brk (esr)) { + }else if (IS_ENABLED (CONFIG_CFI ) &&esr_is_cfi_brk (esr)) {kvm_nvhe_report_cfi_failure (panic_addr); }else {print_nvhe_hyp_panic ("panic" , panic_addr);
arch/riscv/Kconfig +2 -2
@@ -58,7 +58,7 @@ config RISCV select ARCH_OPTIONAL_KERNEL_RWX_DEFAULT select ARCH_STACKWALK select ARCH_SUPPORTS_ATOMIC_RMW - select ARCH_SUPPORTS_CFI_CLANG + select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_DEBUG_PAGEALLOC if MMU select ARCH_SUPPORTS_HUGETLBFS if MMU # LLD >= 14: https://github.com/llvm/llvm-project/issues/50505
@@ -72,7 +72,7 @@ config RISCV select ARCH_USE_MEMTEST select ARCH_USE_QUEUED_RWLOCKS select ARCH_USE_SYM_ANNOTATIONS - select ARCH_USES_CFI_TRAPS if CFI_CLANG + select ARCH_USES_CFI_TRAPS if CFI select ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH if MMU select ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT if MMU select ARCH_WANT_FRAME_POINTERS
arch/riscv/include/asm/cfi.h +2 -2
@@ -11,7 +11,7 @@struct pt_regs ; -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI enum bug_trap_type handle_cfi_failure (struct pt_regs *regs);#define __bpfcallstatic inline int cfi_get_offset (void )
@@ -35,6 +35,6 @@ static inline u32 cfi_get_func_hash(void *func) {return 0 ; } -#endif /* CONFIG_CFI_CLANG */ +#endif /* CONFIG_CFI */ #endif /* _ASM_RISCV_CFI_H */
arch/riscv/kernel/Makefile +1 -1
@@ -113,7 +113,7 @@ obj-$(CONFIG_VMCORE_INFO) += vmcore_info.o obj-$(CONFIG_JUMP_LABEL) += jump_label.o -obj-$(CONFIG_CFI_CLANG) += cfi.o +obj-$(CONFIG_CFI) += cfi.o obj-$(CONFIG_EFI) += efi.o obj-$(CONFIG_COMPAT) += compat_syscall_table.o
arch/riscv/kernel/cfi.c +1 -1
@@ -76,7 +76,7 @@ enum bug_trap_type handle_cfi_failure(struct pt_regs *regs)return report_cfi_failure (regs, regs->epc, &target, type); } -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI struct bpf_insn ;/* Must match bpf_func_t / DEFINE_BPF_PROG_RUN() */
arch/riscv/net/bpf_jit_comp64.c +2 -2
@@ -18,7 +18,7 @@#define RV_MAX_REG_ARGS 8#define RV_FENTRY_NINSNS 2#define RV_FENTRY_NBYTES (RV_FENTRY_NINSNS * 4) -#define RV_KCFI_NINSNS (IS_ENABLED(CONFIG_CFI_CLANG) ? 1 : 0) +#define RV_KCFI_NINSNS (IS_ENABLED(CONFIG_CFI) ? 1 : 0)/* imm that allows emit_imm to emit max count insns */ #define RV_MAX_COUNT_IMM 0x7FFF7FF7FF7FF7FF
@@ -469,7 +469,7 @@ static int emit_call(u64 addr, bool fixed_addr, struct rv_jit_context *ctx)static inline void emit_kcfi (u32 hash,struct rv_jit_context *ctx) { -if (IS_ENABLED (CONFIG_CFI_CLANG )) +if (IS_ENABLED (CONFIG_CFI ))emit (hash, ctx); }
arch/riscv/purgatory/Makefile +1 -1
@@ -71,7 +71,7 @@ ifdef CONFIG_STACKPROTECTOR_STRONG PURGATORY_CFLAGS_REMOVE += -fstack-protector-strong endif -ifdef CONFIG_CFI_CLANG +ifdef CONFIG_CFI PURGATORY_CFLAGS_REMOVE += $(CC_FLAGS_CFI) endif
arch/x86/Kconfig +6 -6
@@ -122,8 +122,8 @@ config X86 select ARCH_SUPPORTS_PAGE_TABLE_CHECK if X86_64 select ARCH_SUPPORTS_NUMA_BALANCING if X86_64 select ARCH_SUPPORTS_KMAP_LOCAL_FORCE_MAP if NR_CPUS <= 4096 - select ARCH_SUPPORTS_CFI_CLANG if X86_64 - select ARCH_USES_CFI_TRAPS if X86_64 && CFI_CLANG + select ARCH_SUPPORTS_CFI if X86_64 + select ARCH_USES_CFI_TRAPS if X86_64 && CFI select ARCH_SUPPORTS_LTO_CLANG select ARCH_SUPPORTS_LTO_CLANG_THIN select ARCH_SUPPORTS_RT
@@ -2467,11 +2467,11 @@ config FUNCTION_PADDING_CFI default 3 if FUNCTION_ALIGNMENT_8B default 0 -# Basically: FUNCTION_ALIGNMENT - 5*CFI_CLANG +# Basically: FUNCTION_ALIGNMENT - 5*CFI # except Kconfig can't do arithmetic :/ config FUNCTION_PADDING_BYTES int - default FUNCTION_PADDING_CFI if CFI_CLANG + default FUNCTION_PADDING_CFI if CFI default FUNCTION_ALIGNMENT config CALL_PADDING
@@ -2481,7 +2481,7 @@ config CALL_PADDING config FINEIBT def_bool y - depends on X86_KERNEL_IBT && CFI_CLANG && MITIGATION_RETPOLINE + depends on X86_KERNEL_IBT && CFI && MITIGATION_RETPOLINE select CALL_PADDING config HAVE_CALL_THUNKS
@@ -2494,7 +2494,7 @@ config CALL_THUNKS config PREFIX_SYMBOLS def_bool y - depends on CALL_PADDING && !CFI_CLANG + depends on CALL_PADDING && !CFI menuconfig CPU_MITIGATIONS bool "Mitigations for CPU vulnerabilities"
arch/x86/include/asm/cfi.h +2 -2
@@ -103,7 +103,7 @@ extern enum cfi_mode cfi_mode;struct pt_regs ; -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI enum bug_trap_type handle_cfi_failure (struct pt_regs *regs);#define __bpfcallextern u32 cfi_bpf_hash;
@@ -148,7 +148,7 @@ static inline u32 cfi_get_func_hash(void *func) {return 0 ; } -#endif /* CONFIG_CFI_CLANG */ +#endif /* CONFIG_CFI */ #if HAS_KERNEL_IBT ==1 #define CFI_NOSEAL (x) asm(IBT_NOSEAL(__stringify(x)))
arch/x86/kernel/Makefile +1 -1
@@ -162,7 +162,7 @@ obj-$(CONFIG_UNWINDER_ORC) += unwind_orc.o obj-$(CONFIG_UNWINDER_FRAME_POINTER) += unwind_frame.o obj-$(CONFIG_UNWINDER_GUESS) += unwind_guess.o -obj-$(CONFIG_CFI_CLANG) += cfi.o +obj-$(CONFIG_CFI) += cfi.o obj-$(CONFIG_CALL_THUNKS) += callthunks.o
arch/x86/kernel/alternative.c +2 -2
@@ -1094,7 +1094,7 @@ void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }#ifdef CONFIG_CFI_AUTO_DEFAULT #define __CFI_DEFAULT CFI_AUTO -#elif defined(CONFIG_CFI_CLANG ) +#elif defined(CONFIG_CFI )#define __CFI_DEFAULT CFI_KCFI#else #define __CFI_DEFAULT CFI_OFF
@@ -1102,7 +1102,7 @@ void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }enum cfi_mode cfi_mode__ro_after_init = __CFI_DEFAULT; -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI struct bpf_insn ;/* Must match bpf_func_t / DEFINE_BPF_PROG_RUN() */
arch/x86/kernel/kprobes/core.c +1 -1
@@ -339,7 +339,7 @@ static bool can_probe(unsigned long paddr)if (is_exception_insn (&insn))return false; -if (IS_ENABLED (CONFIG_CFI_CLANG )) { +if (IS_ENABLED (CONFIG_CFI )) {/* * The compiler generates the following instruction sequence * for indirect call checks and cfi.c decodes this;
arch/x86/purgatory/Makefile +1 -1
@@ -57,7 +57,7 @@ ifdef CONFIG_MITIGATION_RETPOLINE PURGATORY_CFLAGS_REMOVE += $(RETPOLINE_CFLAGS) endif -ifdef CONFIG_CFI_CLANG +ifdef CONFIG_CFI PURGATORY_CFLAGS_REMOVE += $(CC_FLAGS_CFI) endif
drivers/misc/lkdtm/cfi.c +1 -1
@@ -43,7 +43,7 @@ static void lkdtm_CFI_FORWARD_PROTO(void)lkdtm_indirect_call ((void *)lkdtm_increment_int);pr_err ("FAIL: survived mismatched prototype function call!\n" ); -pr_expected_config (CONFIG_CFI_CLANG ); +pr_expected_config (CONFIG_CFI ); }/*
include/asm-generic/vmlinux.lds.h +1 -1
@@ -150,7 +150,7 @@#define PATCHABLE_DISCARDS *(__patchable_function_entries)#endif -#ifndef CONFIG_ARCH_SUPPORTS_CFI_CLANG +#ifndef CONFIG_ARCH_SUPPORTS_CFI /* * Simply points to ftrace_stub, but with the proper protocol. * Defined by the linker script in linux/vmlinux.lds.h
include/linux/cfi.h +2 -2
@@ -18,7 +18,7 @@ static inline int cfi_get_offset(void) }#endif -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI enum bug_trap_type report_cfi_failure (struct pt_regs *regs,unsigned long addr,unsigned long *target,u32 type);
@@ -27,7 +27,7 @@ static inline enum bug_trap_type report_cfi_failure_noaddr(struct pt_regs *regs, {return report_cfi_failure (regs, addr,NULL ,0 ); } -#endif /* CONFIG_CFI_CLANG */ +#endif /* CONFIG_CFI */ #ifdef CONFIG_ARCH_USES_CFI_TRAPS bool is_cfi_trap (unsigned long addr);
include/linux/cfi_types.h +3 -3
@@ -8,7 +8,7 @@#ifdef __ASSEMBLY__#include <linux/linkage.h> -#ifdef CONFIG_CFI_CLANG +#ifdef CONFIG_CFI /* * Use the __kcfi_typeid_<function> type identifier symbol to * annotate indirectly called assembly functions. The compiler emits
@@ -29,12 +29,12 @@ #define SYM_TYPED_START(name, linkage, align...) \ SYM_TYPED_ENTRY(name, linkage, align) -#else /* CONFIG_CFI_CLANG */ +#else /* CONFIG_CFI */ #define SYM_TYPED_START(name, linkage, align...) \ SYM_START(name, linkage, align) -#endif /* CONFIG_CFI_CLANG */ +#endif /* CONFIG_CFI */ #ifndef SYM_TYPED_FUNC_START #define SYM_TYPED_FUNC_START (name) \
init/Kconfig +2 -2
@@ -1979,8 +1979,8 @@ config RUST depends on !GCC_PLUGIN_RANDSTRUCT depends on !RANDSTRUCT depends on !DEBUG_INFO_BTF || (PAHOLE_HAS_LANG_EXCLUDE && !LTO) - depends on !CFI_CLANG || HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC - select CFI_ICALL_NORMALIZE_INTEGERS if CFI_CLANG + depends on !CFI || HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC + select CFI_ICALL_NORMALIZE_INTEGERS if CFI depends on !CALL_PADDING || RUSTC_VERSION >= 108100 depends on !KASAN || CC_IS_CLANG depends on !KASAN_SW_TAGS
kernel/Makefile +1 -1
@@ -115,7 +115,7 @@ obj-$(CONFIG_KCSAN) += kcsan/ obj-$(CONFIG_SHADOW_CALL_STACK) += scs.o obj-$(CONFIG_HAVE_STATIC_CALL) += static_call.o obj-$(CONFIG_HAVE_STATIC_CALL_INLINE) += static_call_inline.o -obj-$(CONFIG_CFI_CLANG) += cfi.o +obj-$(CONFIG_CFI) += cfi.o obj-$(CONFIG_PERF_EVENTS) += events/
kernel/configs/hardening.config +2 -2
@@ -87,8 +87,8 @@ CONFIG_SECCOMP_FILTER=y # Provides some protections against SYN flooding. CONFIG_SYN_COOKIES=y -# Enable Kernel Control Flow Integrity (currently Clang only). -CONFIG_CFI_CLANG=y +# Enable Kernel Control Flow Integrity. +CONFIG_CFI=y # CONFIG_CFI_PERMISSIVE is not set # Attack surface reduction: do not autoload TTY line disciplines.
kernel/module/Kconfig +1 -1
@@ -400,6 +400,6 @@ config UNUSED_KSYMS_WHITELIST config MODULES_TREE_LOOKUP def_bool y - depends on PERF_EVENTS || TRACING || CFI_CLANG + depends on PERF_EVENTS || TRACING || CFI endif # MODULES
lib/longest_symbol_kunit.c +1 -1
@@ -3,7 +3,7 @@* Test the longest symbol length. Execute with: * ./tools/testing/kunit/kunit.py run longest-symbol * --arch=x86_64 --kconfig_add CONFIG_KPROBES=y --kconfig_add CONFIG_MODULES=y -* --kconfig_add CONFIG_RETPOLINE=n --kconfig_add CONFIG_CFI_CLANG=n +* --kconfig_add CONFIG_RETPOLINE=n --kconfig_add CONFIG_CFI=n * --kconfig_add CONFIG_MITIGATION_RETPOLINE=n */
tools/perf/util/include/linux/linkage.h +1 -1
@@ -120,7 +120,7 @@#endif // In the kernel sources (include/linux/cfi_types.h), this has a different -// definition when CONFIG_CFI_CLANG is used, for tools/ just use the !clang +// definition when CONFIG_CFI is used, for tools/ just use the !cfi // definition: #ifndef SYM_TYPED_START #define SYM_TYPED_START(name, linkage, align...) \
Signature · 1 line
2.53.0
Re: [PATCH 6.12 696/869] kcfi: Rename CONFIG_CFI_CLANG to CONFIG_CFI
Quoted 21 lines · Greg Kroah-Hartman
6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kees Cook <[email protected]>
[ Upstream commit
23ef9d439769d5f35353650e771c63d13824235b]The kernel's CFI implementation uses the KCFI ABI specifically, and is not strictly tied to a particular compiler. In preparation for GCC supporting KCFI, rename
CONFIG_CFI_CLANGtoCONFIG_CFI(along with associated options).Use new "transitional"
Kconfigoption for oldCONFIG_CFI_CLANGthat will enableCONFIG_CFIduring olddefconfig.Reviewed-by Linus Walleij <[email protected]>Reviewed-by Nathan Chancellor <[email protected]>Signed-off-by Kees Cook <[email protected]>
Quoted 7 lines
[ Adapted to this tree: the kconfig here has no "transitional" keyword, so
theCFI_CLANGcompat symbol is omitted; re-applied the rename on top of the local contents of the conflicting files, converted the remainingCONFIG_CFI_CLANGusers (riscvcfi.c,longest_symbolkunit comment), and dropped thetools/cfi_types.hhunk as that file is absent here. ]Stable-dep-of:
52fb1756ea1d("riscv, bpf: Fix kernel stack corruption in tailcall with CFI")
I object to this being backported in its current form, especially as a "dependency" of the listed change... The transitional keyword is very much needed for this change to avoid silently disabling the feature across olddefconfig. Either backport it as well or just do the simple thing and properly adjust 52fb1756ea1d for trees that do not contain 23ef9d43976:
$ git format-patch --stdout -1 52fb1756ea1d | sed 's;(CONFIG_CFI);(CONFIG_CFI_CLANG);g' | git am
Signature · 2 lines
Cheers, Nathan
Sasha Levin
maintainerRe: [PATCH 6.12 696/869] kcfi: Rename CONFIG_CFI_CLANG to CONFIG_CFI
Quoted 6 lines · Nathan Chancellor
I object to this being backported in its current form, especially as a "dependency" of the listed change... The transitional keyword is very much needed for this change to avoid silently disabling the feature across olddefconfig. Either backport it as well or just do the simple thing and properly adjust
52fb1756ea1dfor trees that do not contain23ef9d43976:
Agreed, thanks for catching this. I confirmed that with the queued 6.12 adaptation, running olddefconfig on a .config with CONFIG_CFI_CLANG=y leaves CONFIG_CFI unset.
I dropped 23ef9d439769 from the 6.12 queue, along with the two patches that depend on the rename.
Signature · 2 lines
Thanks, Sasha
Greg Kroah-Hartman
maintainerPATCH 697/869 riscv, bpf: Fix kernel stack corruption in tailcall with CFI
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pu Lehui <[email protected]>
[ Upstream commit 52fb1756ea1d2759dfef2d86245be00b05dac3a2 ]
When CONFIG_CFI_CLANG is enabled, prog->bpf_func already skips the kcfi instruction during setup. Including it again in the tailcall jump offset causes it to jump over an extra 4 bytes, skipping the stack pointer adjustment, which will result in kernel stack corruption.
--- arch/riscv/net/bpf_jit_comp64.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
arch/riscv/net/bpf_jit_comp64.c +4 -3
@@ -18,7 +18,6 @@#define RV_MAX_REG_ARGS 8#define RV_FENTRY_NINSNS 2#define RV_FENTRY_NBYTES (RV_FENTRY_NINSNS * 4) -#define RV_KCFI_NINSNS (IS_ENABLED(CONFIG_CFI) ? 1 : 0)/* imm that allows emit_imm to emit max count insns */ #define RV_MAX_COUNT_IMM 0x7FFF7FF7FF7FF7FF
@@ -272,8 +271,8 @@ static void __build_epilogue(bool is_tail_call, struct rv_jit_context *ctx)if (!is_tail_call)emit_addiw (RV_REG_A0 ,RV_REG_A5 ,0 , ctx);emit_jalr (RV_REG_ZERO , is_tail_call ?RV_REG_T3 :RV_REG_RA , -/* kcfi, fentry and TCC init insns will be skipped on tailcall */ - is_tail_call ? (RV_KCFI_NINSNS +RV_FENTRY_NINSNS +1 ) *4 :0 , +/* fentry and TCC init insns will be skipped on tailcall */ + is_tail_call ? (RV_FENTRY_NINSNS +1 ) *4 :0 , ctx); }
@@ -2083,6 +2082,8 @@ void bpf_jit_build_prologue(struct rv_jit_context *ctx, bool is_subprog)/* emit kcfi type preamble immediately before the first insn */ emit_kcfi (is_subprog ? cfi_bpf_subprog_hash : cfi_bpf_hash, ctx); +/* bpf prog starts here as kcfi skipped during prog->bpf_func setup */ +/* nops reserved for auipc+jalr pair */ for (i =0 ; i <RV_FENTRY_NINSNS ; i++)emit (rv_nop (), ctx);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 698/869 bpf: Zero queue and stack outputs on lock failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kumar Kartikeya Dwivedi <[email protected]>
[ Upstream commit 7ac6e1ae41a09f1dd4baeeff1d028ae49ee01232 ]
Queue and stack pop/peek helpers accept an uninitialized output buffer because the verifier expects the helper to initialize it. The empty-map error path clears the buffer, but a failed lock acquisition returns -EBUSY without writing it.
Clear the output before returning -EBUSY so BPF programs cannot observe uninitialized stack contents after a failed helper call.
--- kernel/bpf/queue_stack_maps.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/queue_stack_maps.c +6 -2
@@ -99,8 +99,10 @@ static long __queue_map_get(struct bpf_map *map, void *value, bool delete)void *ptr;if (in_nmi ()) { -if (!raw_spin_trylock_irqsave (&qs->lock, flags)) +if (!raw_spin_trylock_irqsave (&qs->lock, flags)) { +memset (value,0 , qs->map.value_size);return -EBUSY ; + } }else {raw_spin_lock_irqsave (&qs->lock, flags); }
@@ -134,8 +136,10 @@ static long __stack_map_get(struct bpf_map *map, void *value, bool delete)u32 index;if (in_nmi ()) { -if (!raw_spin_trylock_irqsave (&qs->lock, flags)) +if (!raw_spin_trylock_irqsave (&qs->lock, flags)) { +memset (value,0 , qs->map.value_size);return -EBUSY ; + } }else {raw_spin_lock_irqsave (&qs->lock, flags); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 699/869 drm/sched: Use struct for drm_sched_init() params
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Philipp Stanner <[email protected]>
[ Upstream commit 796a9f55a8d1d85387b973df9a06cbf4bc2d6327 ]
drm_sched_init() has a great many parameters and upcoming new functionality for the scheduler might add even more. Generally, the great number of parameters reduces readability and has already caused one missnaming, addressed in:
commit 6f1cacf4eba7 ("drm/nouveau: Improve variable name in nouveau_sched_init()").
Introduce a new struct for the scheduler init parameters and port all users.
Stable-dep-of: e2332abed2a4 ("drm/msm: Only fini scheduler after successful init")
--- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 18 ++++-- drivers/gpu/drm/etnaviv/etnaviv_sched.c | 22 ++++---- drivers/gpu/drm/imagination/pvr_queue.c | 18 ++++-- drivers/gpu/drm/lima/lima_sched.c | 16 ++++-- drivers/gpu/drm/msm/msm_ringbuffer.c | 17 +++--- drivers/gpu/drm/nouveau/nouveau_sched.c | 16 ++++-- drivers/gpu/drm/panfrost/panfrost_job.c | 20 ++++--- drivers/gpu/drm/panthor/panthor_mmu.c | 16 ++++-- drivers/gpu/drm/panthor/panthor_sched.c | 28 ++++++---- drivers/gpu/drm/scheduler/sched_main.c | 50 ++++++----------- drivers/gpu/drm/v3d/v3d_sched.c | 65 +++++++++------------- drivers/gpu/drm/xe/xe_execlist.c | 15 +++-- drivers/gpu/drm/xe/xe_gpu_scheduler.c | 17 +++++- include/drm/gpu_scheduler.h | 36 ++++++++++-- 14 files changed, 202 insertions(+), 152 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +12 -6
@@ -2849,6 +2849,12 @@ static int amdgpu_device_fw_loading(struct amdgpu_device *adev)static int amdgpu_device_init_schedulers (struct amdgpu_device *adev) { +struct drm_sched_init_args args = { + .ops = &amdgpu_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .timeout_wq = adev->reset_domain->wq, + .dev = adev->dev, + };long timeout;int r, i;
@@ -2874,12 +2880,12 @@ static int amdgpu_device_init_schedulers(struct amdgpu_device *adev)break ; } - r =drm_sched_init (&ring->sched, &amdgpu_sched_ops,NULL , -DRM_SCHED_PRIORITY_COUNT , - ring->num_hw_submission,0 , - timeout, adev->reset_domain->wq, - ring->sched_score, ring->name, - adev->dev); + args.timeout = timeout; + args.credit_limit = ring->num_hw_submission; + args.score = ring->sched_score; + args.name = ring->name; + + r =drm_sched_init (&ring->sched, &args);if (r) {DRM_ERROR ("Failed to create scheduler on ring %s.\n" , ring->name);
drivers/gpu/drm/etnaviv/etnaviv_sched.c +11 -11
@@ -134,17 +134,17 @@ int etnaviv_sched_push_job(struct etnaviv_gem_submit *submit)int etnaviv_sched_init (struct etnaviv_gpu *gpu) { -int ret; - - ret =drm_sched_init (&gpu->sched, &etnaviv_sched_ops,NULL , -DRM_SCHED_PRIORITY_COUNT , - etnaviv_hw_jobs_limit, etnaviv_job_hang_limit, -msecs_to_jiffies (500 ),NULL ,NULL , -dev_name (gpu->dev), gpu->dev); -if (ret) -return ret; - -return 0 ; +const struct drm_sched_init_args args = { + .ops = &etnaviv_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .credit_limit = etnaviv_hw_jobs_limit, + .hang_limit = etnaviv_job_hang_limit, + .timeout =msecs_to_jiffies (500 ), + .name =dev_name (gpu->dev), + .dev = gpu->dev, + }; + +return drm_sched_init (&gpu->sched, &args); }void etnaviv_sched_fini (struct etnaviv_gpu *gpu)
drivers/gpu/drm/imagination/pvr_queue.c +12 -6
@@ -1240,6 +1240,17 @@ struct pvr_queue *pvr_queue_create(struct pvr_context *ctx, }, };struct pvr_device *pvr_dev = ctx->pvr_dev; +const struct drm_sched_init_args sched_args = { + .ops = &pvr_queue_sched_ops, + .submit_wq = pvr_dev->sched_wq, + .num_rqs =1 , + .credit_limit =64 *1024 , + .hang_limit =1 , + .timeout =msecs_to_jiffies (500 ), + .timeout_wq = pvr_dev->sched_wq, + .name ="pvr-queue" , + .dev = pvr_dev->base.dev, + };struct drm_gpu_scheduler *sched;struct pvr_queue *queue;int ctx_state_size, err;
@@ -1312,12 +1323,7 @@ struct pvr_queue *pvr_queue_create(struct pvr_context *ctx, queue->timeline_ufo.value = cpu_map; - err =drm_sched_init (&queue->scheduler, - &pvr_queue_sched_ops, - pvr_dev->sched_wq,1 ,64 *1024 ,1 , -msecs_to_jiffies (500 ), - pvr_dev->sched_wq,NULL ,"pvr-queue" , - pvr_dev->base.dev); + err =drm_sched_init (&queue->scheduler, &sched_args);if (err) goto err_release_ufo;
drivers/gpu/drm/lima/lima_sched.c +10 -6
@@ -517,18 +517,22 @@ int lima_sched_pipe_init(struct lima_sched_pipe *pipe, const char *name) {unsigned int timeout = lima_sched_timeout_ms >0 ? lima_sched_timeout_ms :10000 ; +const struct drm_sched_init_args args = { + .ops = &lima_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .credit_limit =1 , + .hang_limit = lima_job_hang_limit, + .timeout =msecs_to_jiffies (timeout), + .name = name, + .dev = pipe->ldev->dev, + }; pipe->fence_context =dma_fence_context_alloc (1 );spin_lock_init (&pipe->fence_lock);INIT_WORK (&pipe->recover_work, lima_sched_recover_work); -return drm_sched_init (&pipe->base, &lima_sched_ops,NULL , -DRM_SCHED_PRIORITY_COUNT , -1 , - lima_job_hang_limit, -msecs_to_jiffies (timeout),NULL , -NULL , name, pipe->ldev->dev); +return drm_sched_init (&pipe->base, &args); }void lima_sched_pipe_fini (struct lima_sched_pipe *pipe)
drivers/gpu/drm/msm/msm_ringbuffer.c +9 -8
@@ -59,8 +59,14 @@ static const struct drm_sched_backend_ops msm_sched_ops = {struct msm_ringbuffer *msm_ringbuffer_new (struct msm_gpu *gpu,int id,void *memptrs,uint64_t memptrs_iova) { +struct drm_sched_init_args args = { + .ops = &msm_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .credit_limit = num_hw_submissions, + .timeout =MAX_SCHEDULE_TIMEOUT , + .dev = gpu->dev->dev, + };struct msm_ringbuffer *ring; -long sched_timeout;char name[32 ];int ret;
@@ -87,6 +93,7 @@ struct msm_ringbuffer *msm_ringbuffer_new(struct msm_gpu *gpu, int id, }msm_gem_object_set_name (ring->bo,"ring%d" , id); + args.name =to_msm_bo (ring->bo)->name, ring->end = ring->start + (MSM_GPU_RINGBUFFER_SZ >>2 ); ring->next = ring->start;
@@ -95,13 +102,7 @@ struct msm_ringbuffer *msm_ringbuffer_new(struct msm_gpu *gpu, int id, ring->memptrs = memptrs; ring->memptrs_iova = memptrs_iova; -/* currently managing hangcheck ourselves: */ - sched_timeout =MAX_SCHEDULE_TIMEOUT ; - - ret =drm_sched_init (&ring->sched, &msm_sched_ops,NULL , -DRM_SCHED_PRIORITY_COUNT , - num_hw_submissions,0 , sched_timeout, -NULL ,NULL ,to_msm_bo (ring->bo)->name, gpu->dev->dev); + ret =drm_sched_init (&ring->sched, &args);if (ret) { goto fail; }
drivers/gpu/drm/nouveau/nouveau_sched.c +11 -5
@@ -405,7 +405,14 @@ nouveau_sched_init(struct nouveau_sched *sched, struct nouveau_drm *drm, {struct drm_gpu_scheduler *drm_sched = &sched->base;struct drm_sched_entity *entity = &sched->entity; -const long timeout =msecs_to_jiffies (NOUVEAU_SCHED_JOB_TIMEOUT_MS ); +struct drm_sched_init_args args = { + .ops = &nouveau_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .credit_limit = credit_limit, + .timeout =msecs_to_jiffies (NOUVEAU_SCHED_JOB_TIMEOUT_MS ), + .name ="nouveau_sched" , + .dev = drm->dev->dev + };int ret;if (!wq) {
@@ -417,10 +424,9 @@ nouveau_sched_init(struct nouveau_sched *sched, struct nouveau_drm *drm, sched->wq = wq; } - ret =drm_sched_init (drm_sched, &nouveau_sched_ops, wq, -NOUVEAU_SCHED_PRIORITY_COUNT , - credit_limit,0 , timeout, -NULL ,NULL ,"nouveau_sched" , drm->dev->dev); + args.submit_wq = wq, + + ret =drm_sched_init (drm_sched, &args);if (ret) goto fail_wq;
drivers/gpu/drm/panfrost/panfrost_job.c +11 -9
@@ -830,8 +830,16 @@ static irqreturn_t panfrost_job_irq_handler(int irq, void *data)int panfrost_job_init (struct panfrost_device *pfdev) { +struct drm_sched_init_args args = { + .ops = &panfrost_sched_ops, + .num_rqs =DRM_SCHED_PRIORITY_COUNT , + .credit_limit =2 , + .timeout =msecs_to_jiffies (JOB_TIMEOUT_MS ), + .timeout_wq = pfdev->reset.wq, + .name ="pan_js" , + .dev = pfdev->dev, + };struct panfrost_job_slot *js; -unsigned int nentries =2 ;int ret, j;/* All GPUs have two entries per queue, but without jobchain
@@ -839,7 +847,7 @@ int panfrost_job_init(struct panfrost_device *pfdev)* so let's just advertise one entry in that case. */ if (!panfrost_has_hw_feature (pfdev,HW_FEATURE_JOBCHAIN_DISAMBIGUATION )) - nentries =1 ; + args.credit_limit =1 ; pfdev->js = js =devm_kzalloc (pfdev->dev,sizeof (*js),GFP_KERNEL );if (!js)
@@ -869,13 +877,7 @@ int panfrost_job_init(struct panfrost_device *pfdev)for (j =0 ; j <NUM_JOB_SLOTS ; j++) { js->queue[j].fence_context =dma_fence_context_alloc (1 ); - ret =drm_sched_init (&js->queue[j].sched, - &panfrost_sched_ops,NULL , -DRM_SCHED_PRIORITY_COUNT , - nentries,0 , -msecs_to_jiffies (JOB_TIMEOUT_MS ), - pfdev->reset.wq, -NULL ,"pan_js" , pfdev->dev); + ret =drm_sched_init (&js->queue[j].sched, &args);if (ret) {dev_err (pfdev->dev,"Failed to create scheduler: %d." , ret); goto err_sched;
drivers/gpu/drm/panthor/panthor_mmu.c +11 -5
@@ -2296,6 +2296,16 @@ panthor_vm_create(struct panthor_device *ptdev, bool for_mcu,u64 full_va_range =1ull << va_bits;struct drm_gem_object *dummy_gem;struct drm_gpu_scheduler *sched; +const struct drm_sched_init_args sched_args = { + .ops = &panthor_vm_bind_ops, + .submit_wq = ptdev->mmu->vm.wq, + .num_rqs =1 , + .credit_limit =1 , +/* Bind operations are synchronous for now, no timeout needed. */ + .timeout =MAX_SCHEDULE_TIMEOUT , + .name ="panthor-vm-bind" , + .dev = ptdev->base.dev, + };struct io_pgtable_cfg pgtbl_cfg;u64 mair, min_va, va_range;struct panthor_vm *vm;
@@ -2355,11 +2365,7 @@ panthor_vm_create(struct panthor_device *ptdev, bool for_mcu, goto err_mm_takedown; } -/* Bind operations are synchronous for now, no timeout needed. */ - ret =drm_sched_init (&vm->sched, &panthor_vm_bind_ops, ptdev->mmu->vm.wq, -1 ,1 ,0 , -MAX_SCHEDULE_TIMEOUT ,NULL ,NULL , -"panthor-vm-bind" , ptdev->base.dev); + ret =drm_sched_init (&vm->sched, &sched_args);if (ret) goto err_free_io_pgtable;
drivers/gpu/drm/panthor/panthor_sched.c +17 -11
@@ -3290,6 +3290,22 @@ static struct panthor_queue * group_create_queue(struct panthor_group *group, const struct drm_panthor_queue_create *args) { + const struct drm_sched_init_args sched_args = { + .ops = &panthor_queue_sched_ops, + .submit_wq = group->ptdev->scheduler->wq, + .num_rqs =1 , +/* +* The credit limit argument tells us the total number of +* instructions across all CS slots in the ringbuffer, with +* some jobs requiring twice as many as others, depending on +* their profiling status. +*/ + .credit_limit = args->ringbuf_size /sizeof (u64), + .timeout =msecs_to_jiffies (JOB_TIMEOUT_MS ), + .timeout_wq = group->ptdev->reset.wq, + .name ="panthor-queue" , + .dev = group->ptdev->base.dev, + };struct drm_gpu_scheduler *drm_sched;struct panthor_queue *queue;int ret;
@@ -3360,17 +3376,7 @@ group_create_queue(struct panthor_group *group,if (ret) goto err_free_queue; -/* -* Credit limit argument tells us the total number of instructions -* across all CS slots in the ringbuffer, with some jobs requiring -* twice as many as others, depending on their profiling status. -*/ - ret =drm_sched_init (&queue->scheduler, &panthor_queue_sched_ops, - group->ptdev->scheduler->wq,1 , - args->ringbuf_size /sizeof (u64), -0 ,msecs_to_jiffies (JOB_TIMEOUT_MS ), - group->ptdev->reset.wq, -NULL ,"panthor-queue" , group->ptdev->base.dev); + ret =drm_sched_init (&queue->scheduler, &sched_args);if (ret) goto err_free_queue;
drivers/gpu/drm/scheduler/sched_main.c +17 -33
84 lines not on this page · raw message
drivers/gpu/drm/v3d/v3d_sched.c +26 -39
93 lines not on this page · raw message
drivers/gpu/drm/xe/xe_execlist.c +10 -5
@@ -331,6 +331,15 @@ static const struct drm_sched_backend_ops drm_sched_ops = {static int execlist_exec_queue_init (struct xe_exec_queue *q) {struct drm_gpu_scheduler *sched; +const struct drm_sched_init_args args = { + .ops = &drm_sched_ops, + .num_rqs =1 , + .credit_limit = q->lrc[0 ]->ring.size /MAX_JOB_SIZE_BYTES , + .hang_limit =XE_SCHED_HANG_LIMIT , + .timeout =XE_SCHED_JOB_TIMEOUT , + .name = q->hwe->name, + .dev =gt_to_xe (q->gt)->drm.dev, + };struct xe_execlist_exec_queue *exl;struct xe_device *xe =gt_to_xe (q->gt);int err;
@@ -345,11 +354,7 @@ static int execlist_exec_queue_init(struct xe_exec_queue *q) exl->q = q; - err =drm_sched_init (&exl->sched, &drm_sched_ops,NULL ,1 , - q->lrc[0 ]->ring.size /MAX_JOB_SIZE_BYTES , -XE_SCHED_HANG_LIMIT ,XE_SCHED_JOB_TIMEOUT , -NULL ,NULL , q->hwe->name, -gt_to_xe (q->gt)->drm.dev); + err =drm_sched_init (&exl->sched, &args);if (err) goto err_free;
drivers/gpu/drm/xe/xe_gpu_scheduler.c +14 -3
@@ -63,13 +63,24 @@ int xe_sched_init(struct xe_gpu_scheduler *sched, atomic_t *score, const char *name, struct device *dev) { + const struct drm_sched_init_args args = { + .ops = ops, + .submit_wq = submit_wq, + .num_rqs =1 , + .credit_limit = hw_submission, + .hang_limit = hang_limit, + .timeout = timeout, + .timeout_wq = timeout_wq, + .score = score, + .name = name, + .dev = dev, + }; + sched->ops = xe_ops;INIT_LIST_HEAD (&sched->msgs);INIT_WORK (&sched->work_process_msg, xe_sched_process_msg_work); -return drm_sched_init (&sched->base, ops, submit_wq,1 , hw_submission, - hang_limit, timeout, timeout_wq, score, name, - dev); +return drm_sched_init (&sched->base, &args); }void xe_sched_fini (struct xe_gpu_scheduler *sched)
include/drm/gpu_scheduler.h +31 -5
@@ -550,12 +550,38 @@ struct drm_gpu_scheduler {struct device *dev; }; +/** +* struct drm_sched_init_args - parameters for initializing a DRM GPU scheduler +* +* @ops: backend operations provided by the driver +* @submit_wq: workqueue to use for submission. If NULL, an ordered wq is +* allocated and used. +* @num_rqs: Number of run-queues. This may be at most DRM_SCHED_PRIORITY_COUNT, +* as there's usually one run-queue per priority, but may be less. +* @credit_limit: the number of credits this scheduler can hold from all jobs +* @hang_limit: number of times to allow a job to hang before dropping it. +* This mechanism is DEPRECATED. Set it to 0. +* @timeout: timeout value in jiffies for submitted jobs. +* @timeout_wq: workqueue to use for timeout work. If NULL, the system_wq is used. +* @score: score atomic shared with other schedulers. May be NULL. +* @name: name (typically the driver's name). Used for debugging +* @dev: associated device. Used for debugging +*/ +struct drm_sched_init_args { +const struct drm_sched_backend_ops *ops; +struct workqueue_struct *submit_wq; +struct workqueue_struct *timeout_wq; +u32 num_rqs; +u32 credit_limit; +unsigned int hang_limit; +long timeout; +atomic_t *score; +const char *name; +struct device *dev; +}; +int drm_sched_init (struct drm_gpu_scheduler *sched, -const struct drm_sched_backend_ops *ops, -struct workqueue_struct *submit_wq, -u32 num_rqs,u32 credit_limit,unsigned int hang_limit, -long timeout,struct workqueue_struct *timeout_wq, -atomic_t *score,const char *name,struct device *dev); +const struct drm_sched_init_args *args);void drm_sched_fini (struct drm_gpu_scheduler *sched); int drm_sched_job_init(struct drm_sched_job *job,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 700/869 drm/msm: Only fini scheduler after successful init
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ruoyu Wang <[email protected]>
[ Upstream commit e2332abed2a4d3caa59052095dc16e4ce44791ea ]
msm_ringbuffer_new() destroys a partially initialized ring through msm_ringbuffer_destroy() when an allocation or scheduler setup step fails.
If drm_sched_init() fails before it finishes initializing the scheduler, the failure path still calls drm_sched_fini(). That teardown path assumes the scheduler work items, lists, and workqueue state were initialized.
Track successful scheduler initialization and call drm_sched_fini() only after drm_sched_init() returned 0.
This issue was found by a static analysis checker and confirmed by manual source review.
Patchwork: https://patchwork.freedesktop.org/patch/738905/
Message-ID: <[email protected]>
--- drivers/gpu/drm/msm/msm_ringbuffer.c | 7 ++++--- drivers/gpu/drm/msm/msm_ringbuffer.h | 1 + 2 files changed, 5 insertions(+), 3 deletions(-)
drivers/gpu/drm/msm/msm_ringbuffer.c +4 -3
@@ -103,9 +103,9 @@ struct msm_ringbuffer *msm_ringbuffer_new(struct msm_gpu *gpu, int id, ring->memptrs_iova = memptrs_iova; ret =drm_sched_init (&ring->sched, &args); -if (ret) { +if (ret) goto fail; - } + ring->sched_initialized = true;INIT_LIST_HEAD (&ring->submits);spin_lock_init (&ring->submit_lock);
@@ -127,7 +127,8 @@ void msm_ringbuffer_destroy(struct msm_ringbuffer *ring)if (IS_ERR_OR_NULL (ring))return ; -drm_sched_fini (&ring->sched); +if (ring->sched_initialized) +drm_sched_fini (&ring->sched);msm_fence_context_free (ring->fctx);
drivers/gpu/drm/msm/msm_ringbuffer.h +1 -0
@@ -52,6 +52,7 @@ struct msm_ringbuffer {* The job scheduler for this ring. */ struct drm_gpu_scheduler sched; +bool sched_initialized;/* * List of in-flight submits on this ring. Protected by submit_lock.
Signature · 1 line
2.53.0