5.15.224-rc1 review
Subsystems (4)
Greg Kroah-Hartman
maintainerPATCH 403/571 net: openvswitch: validate transport header presence in set_ipv6_addr
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fernando Fernandez Mancera <[email protected]>
[ Upstream commit 3c6a4b11330fe424557538a98fca9f0a4c5bf313 ]
When executing IPv6 address rewrite actions on IPv6 fragments, set_ipv6_addr() calls update_ipv6_checksum(). If parse_ipv6hdr() processes a non-first IPv6 fragment, it sets key->ip.proto to NEXTHDR_FRAGMENT and returns early without calling skb_set_transport_header().
update_ipv6_checksum() unconditionally evaluates skb_transport_offset() on entry before checking l4_proto. Because skb->transport_header is uninitialized, this triggers a warning under CONFIG_DEBUG_NET=y although it is completely harmless.
Fix this by returning early in update_ipv6_checksum() if l4_proto is NEXTHDR_FRAGMENT. This avoids reading the uninitialized transport offset for fragments while preserving the debug warning for any other protocol where the transport header is unexpectedly missing.
See the syzbot trace:
!skb_transport_header_was_set(skb)
WARNING: ./include/linux/skbuff.h:3075 at skb_transport_header include/linux/skbuff.h:3075 [inline], CPU#1: syz-executor463/5635 WARNING: ./include/linux/skbuff.h:3075 at skb_transport_offset include/linux/skbuff.h:3250 [inline], CPU#1: syz-executor463/5635 WARNING: ./include/linux/skbuff.h:3075 at update_ipv6_checksum net/openvswitch/actions.c:361 [inline], CPU#1: syz-executor463/5635 WARNING: ./include/linux/skbuff.h:3075 at set_ipv6_addr+0x462/0x660 net/openvswitch/actions.c:399, CPU#1: syz-executor463/5635 [...] RIP: 0010:skb_transport_header include/linux/skbuff.h:3075 [inline] RIP: 0010:skb_transport_offset include/linux/skbuff.h:3250 [inline] RIP: 0010:update_ipv6_checksum net/openvswitch/actions.c:361 [inline] RIP: 0010:set_ipv6_addr+0x462/0x660 net/openvswitch/actions.c:399 [...] Call Trace: <TASK> set_ipv6 net/openvswitch/actions.c:531 [inline] do_execute_actions+0x557e/0x8600 net/openvswitch/actions.c:1366 ovs_execute_actions+0xde/0x520 net/openvswitch/actions.c:1592 ovs_packet_cmd_execute+0xb4f/0xf10 net/openvswitch/datapath.c:705 genl_family_rcv_msg_doit+0x233/0x340 net/netlink/genetlink.c:1114 genl_rcv_msg+0x614/0x7a0 net/netlink/genetlink.c:1209 netlink_rcv_skb+0x226/0x4a0 net/netlink/af_netlink.c:2572 genl_rcv+0x28/0x40 net/netlink/genetlink.c:1218 netlink_unicast+0x7bd/0x940 net/netlink/af_netlink.c:1361 netlink_sendmsg+0x813/0xb40 net/netlink/af_netlink.c:1916 sock_sendmsg_nosec+0x14e/0x190 net/socket.c:800
--- net/openvswitch/actions.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
net/openvswitch/actions.c +6 -1
@@ -380,7 +380,12 @@ static void set_ip_addr(struct sk_buff *skb, struct iphdr *nh,static void update_ipv6_checksum (struct sk_buff *skb,u8 l4_proto,__be32 addr[4 ],const __be32 new_addr[4 ]) { -int transport_len = skb->len -skb_transport_offset (skb); +int transport_len; + +if (l4_proto ==NEXTHDR_FRAGMENT ) +return ; + + transport_len = skb->len -skb_transport_offset (skb);if (l4_proto ==NEXTHDR_TCP ) {if (likely (transport_len >=sizeof (struct tcphdr )))
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 404/571 mtd: fix use-after-free in mtd release
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexander Usyskin <[email protected]>
commit e9714c22c1a8238a85d069b1517941fc723312f7 upstream.
I case of partition device_unregister() in mtd_device_release() calls mtd_release() which frees mtd_info structure for partition. All code after device_unregister in mtd_device_release thus uses already freed memory.
Move part of code to mtd_release() and restict mtd->dev cleanup to non-partion object.
For partition object such cleanup have no sense as partition mtd_info is removed.
--- drivers/mtd/mtdcore.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-)
drivers/mtd/mtdcore.c +11 -5
@@ -92,6 +92,9 @@ static void mtd_release(struct device *dstruct mtd_info *mtd =dev_get_drvdata (dev);dev_t index =MTD_DEVT (mtd->index); +idr_remove (&mtd_idr, mtd->index); +of_node_put (mtd_get_of_node (mtd)); +if (mtd_is_partition (mtd))release_mtd_partition (mtd);
@@ -102,6 +105,7 @@ static void mtd_release(struct device *dstatic void mtd_device_release (struct kref *kref) { struct mtd_info *mtd = container_of(kref, struct mtd_info, refcnt); +bool is_partition =mtd_is_partition (mtd);debugfs_remove_recursive (mtd->dbg.dfs_dir);
@@ -110,11 +114,13 @@ static void mtd_device_release(struct krdevice_unregister (&mtd->dev); -/* Clear dev so mtd can be safely re-registered later if desired */ -memset (&mtd->dev,0 ,sizeof (mtd->dev)); - -idr_remove (&mtd_idr, mtd->index); -of_node_put (mtd_get_of_node (mtd)); +/* +* Clear dev so mtd can be safely re-registered later if desired. +* Should not be done for partition, +* as it was already destroyed in device_unregister(). +*/ +if (!is_partition) +memset (&mtd->dev,0 ,sizeof (mtd->dev));module_put (THIS_MODULE ); }
Greg Kroah-Hartman
maintainerPATCH 405/571 mtd: Clean refcounting with MTD_PARTITIONED_MASTER
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Miquel Raynal <[email protected]>
commit 264725e35fbc3b67e053a405e022393a6017e6da upstream.
The logic is way too convoluted, let's clean the kref_get/put section to clarify what this block does when using CONFIG_MTD_PARTITIONED_MASTER:
- Iterate through all the parent mtd devices
- Grab a reference over them all but the master
- Only grab the master whith CONFIG_MTD_PARTITIONED_MASTER Same logic must apply in the put path, otherwise it would be broken.
--- drivers/mtd/mtdcore.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
drivers/mtd/mtdcore.c +10 -7
@@ -1175,14 +1175,15 @@ int __get_mtd_device(struct mtd_info *mtreturn -ENODEV ; } -kref_get (&mtd->refcnt); - -while (mtd->parent) { -if (IS_ENABLED (CONFIG_MTD_PARTITIONED_MASTER ) || mtd->parent != master) -kref_get (&mtd->parent->refcnt); +while (mtd) { +if (mtd != master) +kref_get (&mtd->refcnt); mtd = mtd->parent; } +if (IS_ENABLED (CONFIG_MTD_PARTITIONED_MASTER )) +kref_get (&master->refcnt); +return 0 ; }EXPORT_SYMBOL_GPL (__get_mtd_device);
@@ -1238,10 +1239,12 @@ void __put_mtd_device(struct mtd_info *m {struct mtd_info *master =mtd_get_master (mtd); -while (mtd != master) { +while (mtd) { +/* kref_put() can relese mtd, so keep a reference mtd->parent */ struct mtd_info *parent = mtd->parent; -kref_put (&mtd->refcnt, mtd_device_release); +if (mtd != master) +kref_put (&mtd->refcnt, mtd_device_release); mtd = parent; }
Greg Kroah-Hartman
maintainerPATCH 406/571 mtd: maps: vmu-flash: Fix the (mtd core) switch to ref counters
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Miquel Raynal <[email protected]>
commit a7d84a2e7663bbe12394cc771107e04668ea313a upstream.
While switching to ref counters for track mtd devices use, the vmu-flash driver was forgotten. The reason for reading the ref counter seems debatable, but let's just fix the build for now.
--- drivers/mtd/maps/vmu-flash.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/mtd/maps/vmu-flash.c +1 -1
@@ -720,7 +720,7 @@ static int vmu_can_unload(struct maple_d card =maple_get_drvdata (mdev);for (x =0 ; x < card->partitions; x++) { mtd = &((card->mtd)[x]); -if (mtd->usecount >0 ) +if (kref_read (&mtd->refcnt))return 0 ; }return 1 ;
Greg Kroah-Hartman
maintainerPATCH 407/571 mtd: fix double free and WARN_ON in add_mtd_device() error paths
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xue Lei <[email protected]>
commit 9d4af746af8ce27eefc2338b2feaa1e01f28b6c3 upstream.
When device_register() or mtd_nvmem_add() fails inside add_mtd_device() for a partition, the error handling triggers mtd_release() via put_device() or device_unregister(). mtd_release() calls release_mtd_partition() which frees the mtd_info structure. However, callers such as mtd_add_partition() and add_mtd_partitions() also call free_partition() in their error paths, resulting in a double free.
Additionally, release_mtd_partition() hits WARN_ON(!list_empty( &mtd->part.node)) because the partition node is still linked in the parent's partitions list when the release callback fires from the add_mtd_device() error path.
Fix this by overriding dev->type and dev->release before put_device() in the error paths, so that device_release() invokes a no-op function instead of mtd_release(). For the mtd_nvmem_add() failure case, device_unregister() is replaced with device_del() to separate the device removal from the final kobject reference drop, allowing the override to take effect before put_device() is called.
The callers' error paths (list_del + free_partition) remain the sole owners of mtd_info lifetime on add_mtd_device() failure, which is the expected contract.
The normal partition teardown path is not affected: del_mtd_device() goes through kref_put() -> mtd_device_release() -> device_unregister() with dev->type still set to &mtd_devtype, so mtd_release() -> release_mtd_partition() continues to work correctly for the regular removal case.
--- drivers/mtd/mtdcore.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-)
drivers/mtd/mtdcore.c +19 -4
@@ -102,6 +102,15 @@ static void mtd_release(struct device *ddevice_destroy (&mtd_class, index +1 ); } +/* +* No-op device release used in add_mtd_device() error paths. +* Prevents mtd_release() from being called via device_release(), +* which would free the mtd_info that the caller still manages. +*/ +static void mtd_dev_release_nop (struct device *dev) +{ +} +static void mtd_device_release (struct kref *kref) { struct mtd_info *mtd = container_of(kref, struct mtd_info, refcnt);
@@ -700,10 +709,8 @@ int add_mtd_device(struct mtd_info *mtd)dev_set_drvdata (&mtd->dev, mtd);of_node_get (mtd_get_of_node (mtd)); error =device_register (&mtd->dev); -if (error) { -put_device (&mtd->dev); +if (error) goto fail_added; - }/* Add the nvmem provider */ error =mtd_nvmem_add (mtd);
@@ -730,8 +737,16 @@ int add_mtd_device(struct mtd_info *mtd)return 0 ; fail_nvmem_add: -device_unregister (&mtd->dev); +device_del (&mtd->dev); fail_added: +/* +* Clear type and set nop release to prevent mtd_release() -> +* release_mtd_partition() -> free_partition() from freeing mtd. +* The caller handles cleanup on failure. +*/ + mtd->dev.type =NULL ; + mtd->dev.release = mtd_dev_release_nop; +put_device (&mtd->dev);of_node_put (mtd_get_of_node (mtd));idr_remove (&mtd_idr, i); fail_locked:
Greg Kroah-Hartman
maintainerPATCH 408/571 dlm: validate length in dlm_search_rsb_tree
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ezrak1e <[email protected]>
[ Upstream commit 080e5563f878c64e697b89e7439d730d0daad882 ]
The len parameter in dlm_dump_rsb_name() is not validated and comes from network messages. When it exceeds DLM_RESNAME_MAXLEN, it can cause out-of-bounds write in dlm_search_rsb_tree().
Add length validation to prevent potential buffer overflow.
[Contextual conflict due to dlm_search_rsb_tree() using the RB-tree implementation instead of rhashtable.]
--- fs/dlm/lock.c | 2 ++ 1 file changed, 2 insertions(+)
fs/dlm/lock.c +2 -0
@@ -449,6 +449,8 @@ int dlm_search_rsb_tree(struct rb_root *tree, char *name, int len,struct dlm_rsb *r;int rc; +if (len >DLM_RESNAME_MAXLEN ) +return -EINVAL ;while (node) { r = rb_entry(node, struct dlm_rsb, res_hashnode); rc =rsb_cmp (r, name, len);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 409/571 openvswitch: defer tunnel netdev_put to RCU release
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yang Yang <[email protected]>
[ Upstream commit 6931d21f87bc6d657f145798fad0bf077b82486c ]
ovs_netdev_tunnel_destroy() may run after NETDEV_UNREGISTER already detached the device. Dropping the netdev reference in destroy can race with concurrent readers that still observe vport->dev.
Do not release vport->dev in ovs_netdev_tunnel_destroy(). Instead, let vport_netdev_free() drop the reference from the RCU callback, matching the non-tunnel destroy path and avoiding additional synchronization under RTNL.
--- net/openvswitch/vport-netdev.c | 2 -- 1 file changed, 2 deletions(-)
net/openvswitch/vport-netdev.c +0 -2
@@ -190,8 +190,6 @@ void ovs_netdev_tunnel_destroy(struct vport *vport)*/ if (vport->dev->reg_state ==NETREG_REGISTERED )rtnl_delete_link (vport->dev); -dev_put (vport->dev); - vport->dev =NULL ;rtnl_unlock ();call_rcu (&vport->rcu, vport_netdev_free);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 410/571 openvswitch: vport: fix self-deadlock on release of tunnel ports
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilya Maximets <[email protected]>
[ Upstream commit aa69918bd418e700309fdd08509dba324fb24296 ]
vports are used concurrently and protected by RCU, so netdev_put() must happen after the RCU grace period. So, either in an RCU call or after the synchronize_net(). The rtnl_delete_link() must happen under RTNL and so can't be executed in RCU context. Calling synchronize_net() while holding RTNL is not a good idea for performance and system stability under load in general, so calling netdev_put() in RCU call is the right solution here.
However,
when the device is deleted, rtnl_unlock() will call netdev_run_todo() and block until all the references are gone. In the current code this means that we never reach the call_rcu() and the vport is never freed and the reference is never released, causing a self-deadlock on device removal.
Fix that by moving the rcu_call() before the rtnl_unlock(), so the scheduled RCU callback will be executed when synchronize_net() is called from the rtnl_unlock()->netdev_run_todo() while the RTNL itself is already released.
[Harshit: Resolved minor conflicts because 5.15.y has one-argument rtnl_delete_link() call.]
--- net/openvswitch/vport-netdev.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
net/openvswitch/vport-netdev.c +5 -1
@@ -190,9 +190,13 @@ void ovs_netdev_tunnel_destroy(struct vport *vport)*/ if (vport->dev->reg_state ==NETREG_REGISTERED )rtnl_delete_link (vport->dev); -rtnl_unlock (); +/* We can't put the device reference yet, since it can still be in +* use, but rtnl_unlock()->netdev_run_todo() will block until all +* the references are released, so the RCU call must be before it. +*/ call_rcu (&vport->rcu, vport_netdev_free); +rtnl_unlock (); }EXPORT_SYMBOL_GPL (ovs_netdev_tunnel_destroy);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 411/571 netfilter: nf_tables: release flowtable after rcu grace period on error
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Neira Ayuso <[email protected]>
[ Upstream commit d73f4b53aaaea4c95f245e491aa5eeb8a21874ce ]
Call synchronize_rcu() after unregistering the hooks from error path, since a hook that already refers to this flowtable can be already registered, exposing this flowtable to packet path and nfnetlink_hook control plane.
This error path is rare, it should only happen by reaching the maximum number hooks or by failing to set up to hardware offload, just call synchronize_rcu().
There is a check for already used device hooks by different flowtable that could result in EEXIST at this late stage. The hook parser can be updated to perform this check earlier to this error path really becomes rarely exercised.
Uncovered by KASAN reported as use-after-free from nfnetlink_hook path when dumping hooks.
(cherry picked from commit d73f4b53aaaea4c95f245e491aa5eeb8a21874ce) The cherry-pick did not apply cleanly and required manual conflict resolution because the nftables code differs between the 5.15.y and Linux 6.12.y branches.
--- net/netfilter/nf_tables_api.c | 1 + 1 file changed, 1 insertion(+)
net/netfilter/nf_tables_api.c +1 -0
@@ -8121,6 +8121,7 @@ static int nf_tables_newflowtable(struct sk_buff *skb, &flowtable->hook_list, flowtable);if (err <0 ) { +synchronize_rcu ();nft_flowtable_hooks_destroy (&flowtable->hook_list); goto err4; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 412/571 cifs: fix underflow in parse_server_interfaces()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dan Carpenter <[email protected]>
[ Upstream commit cffe487026be13eaf37ea28b783d9638ab147204 ]
In this loop, we step through the buffer and after each item we check if the size_left is greater than the minimum size we need. However, the problem is that "bytes_left" is type ssize_t while sizeof() is type size_t. That means that because of type promotion, the comparison is done as an unsigned and if we have negative bytes left the loop continues instead of ending.
--- fs/cifs/smb2ops.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/cifs/smb2ops.c +2 -2
@@ -521,7 +521,7 @@ parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf, bytes_left = buf_len; p = buf; -while (bytes_left >=sizeof (*p)) { +while (bytes_left >= (ssize_t )sizeof (*p)) { nb_iface++; next =le32_to_cpu (p->Next);if (!next) {
@@ -556,7 +556,7 @@ parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf, info = *iface_list; bytes_left = buf_len; p = buf; -while (bytes_left >=sizeof (*p)) { +while (bytes_left >= (ssize_t )sizeof (*p)) { info->speed =le64_to_cpu (p->LinkSpeed); info->rdma_capable =le32_to_cpu (p->Capability &RDMA_CAPABLE ) ?1 :0 ; info->rss_capable =le32_to_cpu (p->Capability &RSS_CAPABLE ) ?1 :0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 413/571 smb3: fix for slab out of bounds on mount to ksmbd
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steve French <[email protected]>
[ Upstream commit 7d34ec36abb84fdfb6632a0f2cbda90379ae21fc ]
With KASAN enabled, it is possible to get a slab out of bounds during mount to ksmbd due to missing check in parse_server_interfaces() (see below):
BUG: KASAN: slab-out-of-bounds in parse_server_interfaces+0x14ee/0x1880 [cifs] Read of size 4 at addr ffff8881433dba98 by task mount/9827 CPU: 5 UID: 0 PID: 9827 Comm: mount Tainted: G OE 6.16.0-rc2-kasan #2 PREEMPT(voluntary) Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE Hardware name: Dell Inc. Precision Tower 3620/0MWYPT, BIOS 2.13.1 06/14/2019 Call Trace: <TASK> dump_stack_lvl+0x9f/0xf0 print_report+0xd1/0x670 __virt_addr_valid+0x22c/0x430 ? parse_server_interfaces+0x14ee/0x1880 [cifs] ? kasan_complete_mode_report_info+0x2a/0x1f0 ? parse_server_interfaces+0x14ee/0x1880 [cifs] kasan_report+0xd6/0x110 parse_server_interfaces+0x14ee/0x1880 [cifs] __asan_report_load_n_noabort+0x13/0x20 parse_server_interfaces+0x14ee/0x1880 [cifs] ? __pfx_parse_server_interfaces+0x10/0x10 [cifs] ? trace_hardirqs_on+0x51/0x60 SMB3_request_interfaces+0x1ad/0x3f0 [cifs] ? __pfx_SMB3_request_interfaces+0x10/0x10 [cifs] ? SMB2_tcon+0x23c/0x15d0 [cifs] smb3_qfs_tcon+0x173/0x2b0 [cifs] ? __pfx_smb3_qfs_tcon+0x10/0x10 [cifs] ? cifs_get_tcon+0x105d/0x2120 [cifs] ? do_raw_spin_unlock+0x5d/0x200 ? cifs_get_tcon+0x105d/0x2120 [cifs] ? __pfx_smb3_qfs_tcon+0x10/0x10 [cifs] cifs_mount_get_tcon+0x369/0xb90 [cifs] ? dfs_cache_find+0xe7/0x150 [cifs] dfs_mount_share+0x985/0x2970 [cifs] ? check_path.constprop.0+0x28/0x50 ? save_trace+0x54/0x370 ? __pfx_dfs_mount_share+0x10/0x10 [cifs] ? __lock_acquire+0xb82/0x2ba0 ? __kasan_check_write+0x18/0x20 cifs_mount+0xbc/0x9e0 [cifs] ? __pfx_cifs_mount+0x10/0x10 [cifs] ? do_raw_spin_unlock+0x5d/0x200 ? cifs_setup_cifs_sb+0x29d/0x810 [cifs] cifs_smb3_do_mount+0x263/0x1990 [cifs]
--- fs/cifs/smb2ops.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
fs/cifs/smb2ops.c +10 -1
@@ -528,6 +528,13 @@ parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf, bytes_left -=sizeof (*p);break ; } +/* Validate that Next doesn't point beyond the buffer */ +if (next > bytes_left) { +cifs_dbg (VFS ,"%s: invalid Next pointer %zu > %zd\n" , + __func__, next, bytes_left); + rc = -EINVAL ; + goto out; + } p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next); bytes_left -= next; }
@@ -539,7 +546,9 @@ parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf, }/* Azure rounds the buffer size up 8, to a 16 byte boundary */ -if ((bytes_left >8 ) || p->Next) +if ((bytes_left >8 ) || + (bytes_left >= offsetof(struct network_interface_info_ioctl_rsp , Next) + +sizeof (p->Next) && p->Next))cifs_dbg (VFS ,"%s: incomplete interface info\n" , __func__);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 414/571 smb: client: reject short Next offsets in parse_server_interfaces()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Frank Sorenson <[email protected]>
[ Upstream commit 1b3221bb121079ad79a1f3c3aa360ba649832e7a ]
In parse_server_interfaces(), the server-supplied Next offset is validated against bytes_left, but not against the size of the interface structure itself.
A small, non-zero Next value can pass the bounds check but advance the pointer by less than sizeof(*p). This causes the next iteration of the loop to read misaligned, overlapping structure fields.
Fix this by ensuring the Next offset is at least sizeof(*p).
--- fs/cifs/smb2ops.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
fs/cifs/smb2ops.c +3 -3
@@ -529,9 +529,9 @@ parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf,break ; }/* Validate that Next doesn't point beyond the buffer */ -if (next > bytes_left) { -cifs_dbg (VFS ,"%s: invalid Next pointer %zu > %zd\n" , - __func__, next, bytes_left); +if (next <sizeof (*p) || next > bytes_left) { +cifs_dbg (VFS ,"%s: invalid Next pointer %zu out of range [%zu, %zd]\n" , + __func__, next,sizeof (*p), bytes_left); rc = -EINVAL ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 415/571 ipv6: use RCU in ip6_xmit()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit 9085e56501d93af9f2d7bd16f7fcfacdde47b99c ]
Use RCU in ip6_xmit() in order to use dst_dev_rcu() to prevent possible UAF.
--- net/ipv6/ip6_output.c | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-)
net/ipv6/ip6_output.c +21 -14
@@ -257,33 +257,34 @@ bool ip6_autoflowlabel(struct net *net, const struct ipv6_pinfo *np)int ip6_xmit (const struct sock *sk,struct sk_buff *skb,struct flowi6 *fl6,__u32 mark,struct ipv6_txoptions *opt,int tclass,u32 priority) { -struct net *net =sock_net (sk);const struct ipv6_pinfo *np =inet6_sk (sk);struct in6_addr *first_hop = &fl6->daddr;struct dst_entry *dst =skb_dst (skb); -struct net_device *dev = dst->dev;struct inet6_dev *idev =ip6_dst_idev (dst); +struct net *net =sock_net (sk);unsigned int head_room; +struct net_device *dev;struct ipv6hdr *hdr;u8 proto = fl6->flowi6_proto;int seg_len = skb->len; -int hlimit =-1 ; +int ret, hlimit =-1 ;u32 mtu; +rcu_read_lock (); + + dev =dst_dev_rcu (dst); head_room =sizeof (struct ipv6hdr ) +LL_RESERVED_SPACE (dev);if (opt) head_room += opt->opt_nflen + opt->opt_flen;if (unlikely (head_room >skb_headroom (skb))) { -/* Make sure idev stays alive */ -rcu_read_lock (); +/* idev stays alive while we hold rcu_read_lock(). */ skb =skb_expand_head (skb, head_room);if (!skb) {IP6_INC_STATS (net, idev,IPSTATS_MIB_OUTDISCARDS ); -rcu_read_unlock (); -return -ENOBUFS ; + ret = -ENOBUFS ; + goto unlock; } -rcu_read_unlock (); }if (opt) {
@@ -331,17 +332,21 @@ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,* skb to its handler for processing */ skb =l3mdev_ip6_out ((struct sock *)sk, skb); -if (unlikely (!skb)) -return 0 ; +if (unlikely (!skb)) { + ret =0 ; + goto unlock; + }/* hooks should never assume socket lock is held. * we promote our socket to non const */ -return NF_HOOK (NFPROTO_IPV6 ,NF_INET_LOCAL_OUT , - net, (struct sock *)sk, skb,NULL , dev, - dst_output); + ret =NF_HOOK (NFPROTO_IPV6 ,NF_INET_LOCAL_OUT , + net, (struct sock *)sk, skb,NULL , dev, + dst_output); + goto unlock; } + ret = -EMSGSIZE ; skb->dev = dev;/* ipv6_local_error() does not require socket lock, * we promote our socket to non const
@@ -350,7 +355,9 @@ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,IP6_INC_STATS (net, idev,IPSTATS_MIB_FRAGFAILS );kfree_skb (skb); -return -EMSGSIZE ; +unlock: +rcu_read_unlock (); +return ret; }EXPORT_SYMBOL (ip6_xmit);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 416/571 can: fix unique skb identifier regression under RPS
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Oliver Hartkopp <[email protected]>
commit 7093c3b8314a4ef7405c4066a2521398c455efe7 upstream.
Commit d4fb6514ff8e ("can: use skb hash instead of private variable in headroom") moved the per-skb unique identifier used for raw_rcv() duplicate detection into skb->hash.
With RPS enabled, get_rps_cpu() calls skb_get_hash() before the frame reaches the CAN subsystem. Since CAN skbs have no L3/L4 headers, the flow dissector assigns every CAN frame the same non-zero software hash. can_set_skb_uid() only generated a new identifier when skb->hash was 0, so it kept this constant hash. When the SLAB allocator later reused the same skb address, raw_rcv() mistook the next legitimate frame for a duplicate and dropped it.
Fix this by storing the CAN UID in the CAN skb extension (struct can_skb_ext::can_skb_uid) instead of skb->hash, decoupling it from any hash the network stack may compute. can_set_skb_uid() keeps its "assign only if unset" behaviour, which preserves UIDs set before transmission (e.g. by isotp to identify echo frames) across the local loopback path.
Frames whose extension is shared with another clone (e.g. via tc mirred or netem duplicate) are given a private extension copy before the UID is assigned, so that independently received skb clones from real CAN interfaces (skbcnt = 0) don't end up with the same UID.
The limitation that tc mirred/netem skb duplicates might be dropped in raw_rcv for looped back isotp echo frame skbs is accepted. There is no valid use-case for tc mirred or netem together with isotp which is not capable to operate on different CAN interfaces simultaneously. For routing and modifying CAN frames together with isotp use can-gw.
can-gw and vxcan additionally clear the UID of forwarded/duplicated frames so each newly routed frame gets its own unique identifier.
[ backport to 5.15: no CAN skb extensions available, so the UID is kept
in struct can_skb_priv::skbcnt in the headroom (effectively reverting d4fb6514ff8e) and isotp is adapted accordingly. As skb clones share the headroom, the private extension copy for tc mirred/netem duplicates is not applicable. The UID resets in can-gw and vxcan are omitted, as writing to the shared headroom of cloned skbs would also alter the UID of the original skb. This keeps the pre-d4fb6514ff8e behaviour for routed and vxcan forwarded frames. ]
--- drivers/net/can/dev/skb.c | 2 ++ drivers/net/can/slcan.c | 1 + include/linux/can/skb.h | 3 +++ net/can/af_can.c | 6 ++---- net/can/bcm.c | 2 ++ net/can/isotp.c | 11 +++++++---- net/can/j1939/socket.c | 1 + net/can/j1939/transport.c | 2 ++ net/can/raw.c | 7 ++++--- 9 files changed, 24 insertions(+), 11 deletions(-)
drivers/net/can/dev/skb.c +2 -0
@@ -203,6 +203,7 @@ struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; *cf =skb_put_zero (skb,sizeof (struct can_frame ));
@@ -233,6 +234,7 @@ struct sk_buff *alloc_canfd_skb(struct net_device *dev,can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; *cfd =skb_put_zero (skb,sizeof (struct canfd_frame ));
drivers/net/can/slcan.c +1 -0
@@ -213,6 +213,7 @@ static void slc_bump(struct slcan *sl)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = sl->dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;skb_put_data (skb, &cf,sizeof (struct can_frame ));
include/linux/can/skb.h +3 -0
@@ -43,11 +43,13 @@ struct sk_buff *alloc_can_err_skb(struct net_device *dev,/** * struct can_skb_priv - private additional data inside CAN sk_buffs * @ifindex: ifindex of the first interface the CAN frame appeared on +* @skbcnt: atomic counter to have an unique id together with skb pointer * @frame_len: length of CAN frame in data link layer * @cf: align to the following CAN frame at skb->data */ struct can_skb_priv {int ifindex; +u32 skbcnt;unsigned int frame_len;struct can_frame cf[]; };
@@ -105,6 +107,7 @@ static inline bool can_skb_headroom_valid(struct net_device *dev,if (skb->ip_summed ==CHECKSUM_NONE ) {/* init headroom */ can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; skb->ip_summed =CHECKSUM_UNNECESSARY ;
net/can/af_can.c +2 -4
@@ -644,10 +644,8 @@ static int can_rcv_filter(struct can_dev_rcv_lists *dev_rcv_lists, struct sk_bufvoid can_set_skb_uid (struct sk_buff *skb) {/* create non-zero unique skb identifier together with *skb */ -while (!(skb->hash)) - skb->hash =atomic_inc_return (&skbcounter); - - skb->sw_hash =1 ; +while (!(can_skb_prv (skb)->skbcnt)) +can_skb_prv (skb)->skbcnt =atomic_inc_return (&skbcounter); }EXPORT_SYMBOL (can_set_skb_uid);
net/can/bcm.c +2 -0
@@ -338,6 +338,7 @@ static void bcm_can_tx(struct bcm_op *op, struct canfd_frame *cf)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;skb_put_data (skb, cf, op->cfsiz);
@@ -1576,6 +1577,7 @@ static int bcm_tx_send(struct msghdr *msg, int ifindex, struct sock *sk, }can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; skb->dev = dev;can_skb_set_owner (skb, sk); err =can_send (skb,1 );/* send with loopback */
net/can/isotp.c +7 -4
@@ -287,6 +287,7 @@ static int isotp_send_fc(struct sock *sk, int ae, u8 flowstatus)can_skb_reserve (nskb);can_skb_prv (nskb)->ifindex = dev->ifindex; +can_skb_prv (nskb)->skbcnt =0 ; nskb->dev = dev;can_skb_set_owner (nskb, sk);
@@ -848,6 +849,7 @@ static void isotp_send_cframe(struct isotp_sock *so)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;/* set uid in tx skb to identify CF echo frames */ can_set_skb_uid (skb);
@@ -876,7 +878,7 @@ static void isotp_send_cframe(struct isotp_sock *so)pr_notice_once ("can-isotp: cfecho is %08X != 0\n" , old_cfecho);/* set consecutive frame echo tag */ -WRITE_ONCE (so->cfecho, skb->hash); +WRITE_ONCE (so->cfecho,can_skb_prv (skb)->skbcnt);/* send frame with local echo enabled */ can_send_ret =can_send (skb,1 );
@@ -939,7 +941,7 @@ static void isotp_rcv_echo(struct sk_buff *skb, void *data)spin_lock (&so->rx_lock);/* so->cfecho may since belong to a new transfer; recheck under lock */ -if (READ_ONCE (so->cfecho) != skb->hash) +if (READ_ONCE (so->cfecho) !=can_skb_prv (skb)->skbcnt) goto out_unlock;/* cancel local echo timeout */
@@ -1161,6 +1163,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;/* set uid in tx skb to identify CF echo frames */ can_set_skb_uid (skb);
@@ -1202,7 +1205,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) cf->data[ae] |= size;/* set CF echo tag for isotp_rcv_echo() (SF-mode) */ -WRITE_ONCE (so->cfecho, skb->hash); +WRITE_ONCE (so->cfecho,can_skb_prv (skb)->skbcnt); }else {/* send first frame */
@@ -1219,7 +1222,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) so->txfc.bs =0 ;/* set CF echo tag for isotp_rcv_echo() (CF-mode) */ -WRITE_ONCE (so->cfecho, skb->hash); +WRITE_ONCE (so->cfecho,can_skb_prv (skb)->skbcnt); }else {/* standard flow control check */ new_state =ISOTP_WAIT_FIRST_FC ;
net/can/j1939/socket.c +1 -0
@@ -895,6 +895,7 @@ static struct sk_buff *j1939_sk_alloc_skb(struct net_device *ndev,can_skb_reserve (skb);can_skb_prv (skb)->ifindex = ndev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;skb_reserve (skb, offsetof(struct can_frame , data)); ret =memcpy_from_msg (skb_put (skb, size), msg, size);
net/can/j1939/transport.c +2 -0
@@ -612,6 +612,7 @@ sk_buff *j1939_tp_tx_dat_new(struct j1939_priv *priv, skb->dev = priv->ndev;can_skb_reserve (skb);can_skb_prv (skb)->ifindex = priv->ndev->ifindex; +can_skb_prv (skb)->skbcnt =0 ;/* reserve CAN header */ skb_reserve (skb, offsetof(struct can_frame , data));
@@ -1550,6 +1551,7 @@ j1939_session *j1939_session_fresh_new(struct j1939_priv *priv, skb->dev = priv->ndev;can_skb_reserve (skb);can_skb_prv (skb)->ifindex = priv->ndev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; skcb =j1939_skb_to_cb (skb);memcpy (skcb, rel_skcb,sizeof (*skcb));
net/can/raw.c +4 -3
@@ -74,8 +74,8 @@ MODULE_ALIAS("can-proto-1");*/ struct uniqframe { +u32 skbcnt;const struct sk_buff *skb; -u32 hash;unsigned int join_rx_count; };
@@ -136,7 +136,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data)/* eliminate multiple filter matches for the same skb */ if (this_cpu_ptr (ro->uniq)->skb == oskb && -this_cpu_ptr (ro->uniq)->hash == oskb->hash) { +this_cpu_ptr (ro->uniq)->skbcnt ==can_skb_prv (oskb)->skbcnt) {if (ro->join_filters) {this_cpu_inc (ro->uniq->join_rx_count);/* drop frame until all enabled filters matched */
@@ -147,7 +147,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data) } }else {this_cpu_ptr (ro->uniq)->skb = oskb; -this_cpu_ptr (ro->uniq)->hash = oskb->hash; +this_cpu_ptr (ro->uniq)->skbcnt =can_skb_prv (oskb)->skbcnt;this_cpu_ptr (ro->uniq)->join_rx_count =1 ;/* drop first frame to check all enabled filters? */ if (ro->join_filters && ro->count >1 )
@@ -829,6 +829,7 @@ static int raw_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)can_skb_reserve (skb);can_skb_prv (skb)->ifindex = dev->ifindex; +can_skb_prv (skb)->skbcnt =0 ; err =memcpy_from_msg (skb_put (skb, size), msg, size);if (err <0 )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 417/571 drm/amd/display: Dont replace a sink mode that shares the native totals
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adrian Betschart <[email protected]>
commit 54c998c55fc9cbc391b350d67b86e0c2a0748f1a upstream.
decide_crtc_timing_for_drm_display_mode() copies the native mode's CRTC timing into the requested mode when clock, htotal and vtotal match. That is meant for the modes amdgpu inserts itself:amdgpu_dm_create_common_mode() duplicates the native mode and changes only hdisplay and vdisplay, so those are sent with the native timing and scaled.
A sink can also offer a real mode with the same clock and totals as its native mode. CTA-861 VIC 102 (4096x2160@60) and VIC 97 (3840x2160@60) both use 594 MHz and 4400x2250. With 3840x2160@60 as the preferred mode, a 4096x2160@60 request goes out with the 3840x2160 timing and the framebuffer scaled into it (dst 3840x2025 at y=67), while the AVI InfoFrame still carries VIC 102. A JVC projector then reports 3840x2160 and shows a corrupted right edge. 4096x2160@24, whose totals differ, is sent and displayed correctly.
Inserted modes keep the native sync positions; a real mode with its own active width does not. Compare those too, so only inserted modes are patched.
[ Adrian: this tree keeps the function in amdgpu_dm.c, with the equal-totals
case as its own else-if; added the sync checks there. Dropped the KUnit test, its file does not exist here. ]
--- drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +6 -1
@@ -6029,11 +6029,16 @@ decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,const struct drm_display_mode *native_mode, bool scale_enabled) { + /* Inserted modes copy the native sync; a sink mode with equal totals may not */ if (scale_enabled) {copy_crtc_timing_for_drm_display_mode (native_mode ,drm_mode ); } else if (native_mode->clock == drm_mode->clock && native_mode->htotal == drm_mode->htotal && - native_mode->vtotal == drm_mode->vtotal) { + native_mode->vtotal == drm_mode->vtotal && + native_mode->hsync_start == drm_mode->hsync_start && + native_mode->hsync_end == drm_mode->hsync_end && + native_mode->vsync_start == drm_mode->vsync_start && + native_mode->vsync_end == drm_mode->vsync_end) {copy_crtc_timing_for_drm_display_mode (native_mode, drm_mode); }else {/* no scaling nor amdgpu inserted, no need to patch */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 418/571 HID: hid-steam: Fix cleanup in probe()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dan Carpenter <[email protected]>
[ Upstream commit a9f1da09c69f13ef471db8b22107a28042d230ca ]
There are a number of issues in this code. First of all if steam_create_client_hid() fails then it leads to an error pointer dereference when we call hid_destroy_device(steam->client_hdev).
Also there are a number of leaks. hid_hw_stop() is not called if hid_hw_open() fails for example. And it doesn't call steam_unregister() or hid_hw_close().
[Lee: Move client_hdev creation after steam_register() and omit
mode_switch and rumble_work cancellation as 691ead124a0c and e133dc99fc07 are not present]
--- drivers/hid/hid-steam.c | 43 ++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 20 deletions(-)
drivers/hid/hid-steam.c +23 -20
@@ -751,31 +751,20 @@ static int steam_probe(struct hid_device *hdev,INIT_WORK (&steam->work_connect, steam_work_connect_cb);INIT_LIST_HEAD (&steam->list); - steam->client_hdev =steam_create_client_hid (hdev); -if (IS_ERR (steam->client_hdev)) { - ret =PTR_ERR (steam->client_hdev); - goto client_hdev_fail; - } - steam->client_hdev->driver_data = steam; -/* * With the real steam controller interface, do not connect hidraw. * Instead, create the client_hid and connect that. */ ret =hid_hw_start (hdev,HID_CONNECT_DEFAULT & ~HID_CONNECT_HIDRAW );if (ret) - goto hid_hw_start_fail; - - ret =hid_add_device (steam->client_hdev); -if (ret) - goto client_hdev_add_fail; + goto err_cancel_work; ret =hid_hw_open (hdev);if (ret) {hid_err (hdev,"%s:hid_hw_open\n" , __func__); - goto hid_hw_open_fail; + goto err_hw_stop; }if (steam->quirks &STEAM_QUIRK_WIRELESS ) {
@@ -791,19 +780,33 @@ static int steam_probe(struct hid_device *hdev,hid_err (hdev,"%s:steam_register failed with error %d\n" , __func__, ret); - goto input_register_fail; + goto err_hw_close; } } + steam->client_hdev =steam_create_client_hid (hdev); +if (IS_ERR (steam->client_hdev)) { + ret =PTR_ERR (steam->client_hdev); + goto err_stream_unregister; + } + steam->client_hdev->driver_data = steam; + + ret =hid_add_device (steam->client_hdev); +if (ret) + goto err_destroy; +return 0 ; -input_register_fail: -hid_hw_open_fail: -client_hdev_add_fail: -hid_hw_stop (hdev); -hid_hw_start_fail: +err_destroy:hid_destroy_device (steam->client_hdev); -client_hdev_fail: +err_stream_unregister: +if (steam->connected) +steam_unregister (steam); +err_hw_close: +hid_hw_close (hdev); +err_hw_stop: +hid_hw_stop (hdev); +err_cancel_work:cancel_work_sync (&steam->work_connect); steam_alloc_fail: hid_err(hdev, "%s: failed with error %d\n",
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 419/571 HID: hid-steam: Make client_opened a counter
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit 555b818adb97eca70210a49ba3f1d27882dde092 ]
The client_opened variable was used to track if the hidraw was opened by any clients to silence keyboard/mouse events while opened. However, there was no counting of how many clients were opened, so opening two at the same time and then closing one would fool the driver into thinking it had no remaining opened clients.
[Lee: Adapt steam_client_ll_open() and steam_client_ll_close() as
691ead124a0c and e1147961b214 are not present]
--- drivers/hid/hid-steam.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
drivers/hid/hid-steam.c +7 -7
@@ -114,7 +114,7 @@ struct steam_device {spinlock_t lock;struct hid_device *hdev, *client_hdev;struct mutex mutex; -bool client_opened; +unsigned long client_opened;struct input_dev __rcu *input;unsigned long quirks;struct work_struct work_connect;
@@ -509,7 +509,7 @@ static void steam_battery_unregister(struct steam_device *steam)static int steam_register (struct steam_device *steam) {int ret; -bool client_opened; +unsigned long client_opened;/* * This function can be called several times in a row with the
@@ -634,7 +634,7 @@ static int steam_client_ll_open(struct hid_device *hdev)struct steam_device *steam = hdev->driver_data;mutex_lock (&steam->mutex); - steam->client_opened = true; + steam->client_opened++;mutex_unlock (&steam->mutex);steam_input_unregister (steam);
@@ -654,12 +654,12 @@ static void steam_client_ll_close(struct hid_device *hdev)spin_unlock_irqrestore (&steam->lock, flags);mutex_lock (&steam->mutex); - steam->client_opened = false; -if (connected) + steam->client_opened--; +if (connected && !steam->client_opened)steam_set_lizard_mode (steam, lizard_mode);mutex_unlock (&steam->mutex); -if (connected) +if (connected && !steam->client_opened)steam_input_register (steam); }
@@ -824,7 +824,7 @@ static void steam_remove(struct hid_device *hdev) }hid_destroy_device (steam->client_hdev); - steam->client_opened = false; + steam->client_opened =0 ;cancel_work_sync (&steam->work_connect);if (steam->quirks &STEAM_QUIRK_WIRELESS ) {hid_info (hdev,"Steam wireless receiver disconnected" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 420/571 HID: steam: Fully unregister controller when hidraw is opened
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit cd33a91d37eb4d7c6ce56aa7f4688066309808eb ]
To avoid conflicts between anything touching the hidraw and the driver we had previously detached the evdev nodes when the hidraw is opened. However, this isn't sufficient to avoid FEATURE reports from conflicting, so we change to fully unregistering the controller internally, leaving only the hidraw active until it's closed.
This also unifies the unregister and connect callbacks, as now the logic between these two callbacks is identical.
[Lee: Convert steam_client_ll_open() and steam_client_ll_close() to
schedule work_connect directly and omit sensors, rumble_work, mode_switch and unregister_work changes as e133dc99fc07, e1147961b214 and 1d4549fd1115 are not present]
--- drivers/hid/hid-steam.c | 78 ++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 36 deletions(-)
drivers/hid/hid-steam.c +42 -36
@@ -380,6 +380,7 @@ static int steam_battery_register(struct steam_device *steam) &steam->battery_desc, &battery_cfg);if (IS_ERR (battery)) { ret =PTR_ERR (battery); +devm_kfree (&steam->hdev->dev, steam->battery_desc.name);hid_err (steam->hdev,"%s:power_supply_register failed with error %d\n" , __func__, ret);
@@ -504,12 +505,15 @@ static void steam_battery_unregister(struct steam_device *steam)RCU_INIT_POINTER (steam->battery,NULL );synchronize_rcu ();power_supply_unregister (battery); +devm_kfree (&steam->hdev->dev, steam->battery_desc.name); }static int steam_register (struct steam_device *steam) {int ret;unsigned long client_opened; +unsigned long flags; +bool do_add;/* * This function can be called several times in a row with the
@@ -535,38 +539,47 @@ static int steam_register(struct steam_device *steam)if (steam->quirks &STEAM_QUIRK_WIRELESS )steam_battery_register (steam); -mutex_lock (&steam_devices_lock); -if (list_empty (&steam->list)) -list_add (&steam->list, &steam_devices); -mutex_unlock (&steam_devices_lock); + do_add = true; } -mutex_lock (&steam->mutex); +spin_lock_irqsave (&steam->lock, flags); client_opened = steam->client_opened; -if (!client_opened) -steam_set_lizard_mode (steam, lizard_mode); -mutex_unlock (&steam->mutex); +spin_unlock_irqrestore (&steam->lock, flags); -if (!client_opened) +if (!client_opened) { +mutex_lock (&steam->mutex); +steam_set_lizard_mode (steam, lizard_mode); +mutex_unlock (&steam->mutex); ret =steam_input_register (steam); -else - ret =0 ; +if (ret !=0 ) + goto steam_register_input_fail; + } + +if (do_add) { +mutex_lock (&steam_devices_lock); +if (list_empty (&steam->list)) +list_add (&steam->list, &steam_devices); +mutex_unlock (&steam_devices_lock); + } +return 0 ; +steam_register_input_fail:return ret; }static void steam_unregister (struct steam_device *steam) { +if (!steam->serial_no[0 ]) +return ; + +hid_info (steam->hdev,"Steam Controller '%s' disconnected" , + steam->serial_no);steam_battery_unregister (steam);steam_input_unregister (steam); -if (steam->serial_no[0 ]) { -hid_info (steam->hdev,"Steam Controller '%s' disconnected" , - steam->serial_no); -mutex_lock (&steam_devices_lock); -list_del_init (&steam->list); -mutex_unlock (&steam_devices_lock); - steam->serial_no[0 ] =0 ; - } +mutex_lock (&steam_devices_lock); +list_del_init (&steam->list); +mutex_unlock (&steam_devices_lock); + steam->serial_no[0 ] =0 ; }static void steam_work_connect_cb (struct work_struct *work)
@@ -575,19 +588,20 @@ static void steam_work_connect_cb(struct work_struct *work) work_connect);unsigned long flags;bool connected; +bool opened;int ret;spin_lock_irqsave (&steam->lock, flags); + opened = steam->client_opened; connected = steam->connected;spin_unlock_irqrestore (&steam->lock, flags); -if (connected) { +if (connected && !opened) { ret =steam_register (steam); -if (ret) { +if (ret)hid_err (steam->hdev,"%s:steam_register failed with error %d\n" , __func__, ret); - } }else {steam_unregister (steam); }
@@ -632,12 +646,13 @@ static void steam_client_ll_stop(struct hid_device *hdev)static int steam_client_ll_open (struct hid_device *hdev) {struct steam_device *steam = hdev->driver_data; +unsigned long flags; -mutex_lock (&steam->mutex); +spin_lock_irqsave (&steam->lock, flags); steam->client_opened++; -mutex_unlock (&steam->mutex); +spin_unlock_irqrestore (&steam->lock, flags); -steam_input_unregister (steam); +schedule_work (&steam->work_connect);return 0 ; }
@@ -645,22 +660,13 @@ static int steam_client_ll_open(struct hid_device *hdev)static void steam_client_ll_close (struct hid_device *hdev) {struct steam_device *steam = hdev->driver_data; -unsigned long flags; -bool connected;spin_lock_irqsave (&steam->lock, flags); - connected = steam->connected; -spin_unlock_irqrestore (&steam->lock, flags); - -mutex_lock (&steam->mutex); steam->client_opened--; -if (connected && !steam->client_opened) -steam_set_lizard_mode (steam, lizard_mode); -mutex_unlock (&steam->mutex); +spin_unlock_irqrestore (&steam->lock, flags); -if (connected && !steam->client_opened) -steam_input_register (steam); +schedule_work (&steam->work_connect); } static int steam_client_ll_raw_request(struct hid_device *hdev,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 421/571 HID: steam: Rearrange teardown sequence
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit ddce9641ce924ed91ec8304577e463823a29ffaf ]
This fixes a narrow window during the teardown sequence where callbacks could still be scheduled during cleanup that would then have a dangling pointer to the now-freed steam struct.
This also puts work canceling for rumble and mode switch in steam_unregister, as that shouldn't persist while the client hdev is open.
[Lee: Omit rumble_work, coalesce_rumble_work and mode_switch
cancellation as e133dc99fc07 and 1d4549fd1115 are not present]
--- drivers/hid/hid-steam.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/hid/hid-steam.c +3 -2
@@ -829,15 +829,16 @@ static void steam_remove(struct hid_device *hdev)return ; } +hid_hw_close (hdev);hid_destroy_device (steam->client_hdev); + steam->client_hdev =NULL ; steam->client_opened =0 ;cancel_work_sync (&steam->work_connect);if (steam->quirks &STEAM_QUIRK_WIRELESS ) {hid_info (hdev,"Steam wireless receiver disconnected" ); } -hid_hw_close (hdev); -hid_hw_stop (hdev);steam_unregister (steam); +hid_hw_stop (hdev); }static void steam_do_connect_event (struct steam_device *steam,bool connected)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 422/571 HID: steam: Refactor registration
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit 6f9b740c31ba7e061b2ebb330d9a3d63f1358f29 ]
This refactors and simplifies the registration/unregistration flow. Since we now only perform registration when the client isn't opened anymore, the logic for handling that can be removed, and the rest of the function streamlined.
We also remove the previous assumption that we have a serial number to show we're registered, replacing it with a single purpose boolean.
In a previous refactor the code for unregistering a battery if later registration steps failed was accidentally left out. As a result, a lingering power_supply object could get left over after the steam object was torn down. This is also fixed here.
[Lee: Omit sensors, steam_get_attributes(), rumble_work,
coalesce_rumble_work and mode_switch changes as e133dc99fc07, a0fbd9437d7d and 1d4549fd1115 are not present]
--- drivers/hid/hid-steam.c | 70 ++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 39 deletions(-)
drivers/hid/hid-steam.c +31 -39
@@ -119,6 +119,7 @@ struct steam_device {unsigned long quirks;struct work_struct work_connect;bool connected; +bool registered;char serial_no[STEAM_SERIAL_LEN +1 ];struct power_supply_desc battery_desc;struct power_supply __rcu *battery;
@@ -511,9 +512,6 @@ static void steam_battery_unregister(struct steam_device *steam)static int steam_register (struct steam_device *steam) {int ret; -unsigned long client_opened; -unsigned long flags; -bool do_add;/* * This function can be called several times in a row with the
@@ -521,59 +519,53 @@ static int steam_register(struct steam_device *steam)* another client send a get_connection_status command, for example. * The battery and serial number are set just once per device. */ -if (!steam->serial_no[0 ]) { -/* -* Unlikely, but getting the serial could fail, and it is not so -* important, so make up a serial number and go on. -*/ -mutex_lock (&steam->mutex); -if (steam_get_serial (steam) <0 ) -strlcpy (steam->serial_no,"XXXXXXXXXX" , -sizeof (steam->serial_no)); -mutex_unlock (&steam->mutex); - -hid_info (steam->hdev,"Steam Controller '%s' connected" , - steam->serial_no); +if (steam->registered) +return 0 ; -/* ignore battery errors, we can live without it */ -if (steam->quirks &STEAM_QUIRK_WIRELESS ) -steam_battery_register (steam); +/* +* Unlikely, but getting the serial could fail, and it is not so +* important, so make up a serial number and go on. +*/ +mutex_lock (&steam->mutex); +if (steam_get_serial (steam) <0 || !steam->serial_no[0 ]) +strlcpy (steam->serial_no,"XXXXXXXXXX" , +sizeof (steam->serial_no)); +mutex_unlock (&steam->mutex); - do_add = true; - } +hid_info (steam->hdev,"Steam Controller '%s' connected" , + steam->serial_no); -spin_lock_irqsave (&steam->lock, flags); - client_opened = steam->client_opened; -spin_unlock_irqrestore (&steam->lock, flags); +/* ignore battery errors, we can live without it */ +if (steam->quirks &STEAM_QUIRK_WIRELESS ) +steam_battery_register (steam); -if (!client_opened) { -mutex_lock (&steam->mutex); -steam_set_lizard_mode (steam, lizard_mode); -mutex_unlock (&steam->mutex); - ret =steam_input_register (steam); -if (ret !=0 ) - goto steam_register_input_fail; - } +mutex_lock (&steam->mutex); +steam_set_lizard_mode (steam, lizard_mode); +mutex_unlock (&steam->mutex); + ret =steam_input_register (steam); +if (ret !=0 ) + goto steam_register_input_fail; -if (do_add) { -mutex_lock (&steam_devices_lock); -if (list_empty (&steam->list)) -list_add (&steam->list, &steam_devices); -mutex_unlock (&steam_devices_lock); - } + steam->registered = true; +mutex_lock (&steam_devices_lock); +if (list_empty (&steam->list)) +list_add (&steam->list, &steam_devices); +mutex_unlock (&steam_devices_lock);return 0 ; steam_register_input_fail: +steam_battery_unregister (steam);return ret; }static void steam_unregister (struct steam_device *steam) { -if (!steam->serial_no[0 ]) +if (!steam->registered)return ;hid_info (steam->hdev,"Steam Controller '%s' disconnected" , steam->serial_no); + steam->registered = false;steam_battery_unregister (steam);steam_input_unregister (steam);mutex_lock (&steam_devices_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 423/571 HID: steam: Clean up locking
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vicki Pfau <[email protected]>
[ Upstream commit de1d341b9b3ec9655f31fb8b44f784cca5e670ad ]
This cleans up several issues with locking behavior, including RCU accesses not being guarded behind a lock.
[Lee: Use explicit lock/unlock calls instead of guard(), adapt to
steam->mutex, and omit Steam Deck sensors, mode_switch, rumble_work, coalesce_rumble_work and Ibex changes as 691ead124a0c, e133dc99fc07, a0fbd9437d7d, 1d4549fd1115, fcfa7db89f7a and 0a80b4e8ec6a are not present]
--- drivers/hid/hid-steam.c | 61 +++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 20 deletions(-)
drivers/hid/hid-steam.c +41 -20
@@ -114,6 +114,7 @@ struct steam_device {spinlock_t lock;struct hid_device *hdev, *client_hdev;struct mutex mutex; +struct mutex registration_mutex;unsigned long client_opened;struct input_dev __rcu *input;unsigned long quirks;
@@ -294,9 +295,14 @@ static void steam_set_lizard_mode(struct steam_device *steam, bool enable)static int steam_input_open (struct input_dev *dev) {struct steam_device *steam =input_get_drvdata (dev); +unsigned long flags; +bool client_opened; +spin_lock_irqsave (&steam->lock, flags); + client_opened = steam->client_opened; +spin_unlock_irqrestore (&steam->lock, flags);mutex_lock (&steam->mutex); -if (!steam->client_opened && lizard_mode) +if (!client_opened && lizard_mode)steam_set_lizard_mode (steam, false);mutex_unlock (&steam->mutex);return 0 ;
@@ -305,9 +311,14 @@ static int steam_input_open(struct input_dev *dev)static void steam_input_close (struct input_dev *dev) {struct steam_device *steam =input_get_drvdata (dev); +unsigned long flags; +bool client_opened; +spin_lock_irqsave (&steam->lock, flags); + client_opened = steam->client_opened; +spin_unlock_irqrestore (&steam->lock, flags);mutex_lock (&steam->mutex); -if (!steam->client_opened && lizard_mode) +if (!client_opened && lizard_mode)steam_set_lizard_mode (steam, true);mutex_unlock (&steam->mutex); }
@@ -513,40 +524,43 @@ static int steam_register(struct steam_device *steam) {int ret; +mutex_lock (&steam->registration_mutex);/* * This function can be called several times in a row with the * wireless adaptor, without steam_unregister() between them, because * another client send a get_connection_status command, for example. * The battery and serial number are set just once per device. */ -if (steam->registered) +if (steam->registered) { +mutex_unlock (&steam->registration_mutex);return 0 ; + } +mutex_lock (&steam->mutex);/* * Unlikely, but getting the serial could fail, and it is not so * important, so make up a serial number and go on. */ -mutex_lock (&steam->mutex);if (steam_get_serial (steam) <0 || !steam->serial_no[0 ])strlcpy (steam->serial_no,"XXXXXXXXXX" ,sizeof (steam->serial_no)); -mutex_unlock (&steam->mutex);hid_info (steam->hdev,"Steam Controller '%s' connected" , steam->serial_no); +steam_set_lizard_mode (steam, lizard_mode); +mutex_unlock (&steam->mutex); +/* ignore battery errors, we can live without it */ if (steam->quirks &STEAM_QUIRK_WIRELESS )steam_battery_register (steam); -mutex_lock (&steam->mutex); -steam_set_lizard_mode (steam, lizard_mode); -mutex_unlock (&steam->mutex); ret =steam_input_register (steam);if (ret !=0 ) goto steam_register_input_fail; steam->registered = true; +mutex_unlock (&steam->registration_mutex);mutex_lock (&steam_devices_lock);if (list_empty (&steam->list))list_add (&steam->list, &steam_devices);
@@ -555,6 +569,7 @@ static int steam_register(struct steam_device *steam) steam_register_input_fail:steam_battery_unregister (steam); +mutex_unlock (&steam->registration_mutex);return ret; }
@@ -565,9 +580,11 @@ static void steam_unregister(struct steam_device *steam)hid_info (steam->hdev,"Steam Controller '%s' disconnected" , steam->serial_no); +mutex_lock (&steam->registration_mutex); steam->registered = false;steam_battery_unregister (steam);steam_input_unregister (steam); +mutex_unlock (&steam->registration_mutex);mutex_lock (&steam_devices_lock);list_del_init (&steam->list);mutex_unlock (&steam_devices_lock);
@@ -745,6 +762,7 @@ static int steam_probe(struct hid_device *hdev,hid_set_drvdata (hdev, steam);spin_lock_init (&steam->lock);mutex_init (&steam->mutex); +mutex_init (&steam->registration_mutex); steam->quirks = id->driver_data;INIT_WORK (&steam->work_connect, steam_work_connect_cb);INIT_LIST_HEAD (&steam->list);
@@ -835,13 +853,10 @@ static void steam_remove(struct hid_device *hdev)static void steam_do_connect_event (struct steam_device *steam,bool connected) { -unsigned long flags;bool changed; -spin_lock_irqsave (&steam->lock, flags); changed = steam->connected != connected; steam->connected = connected; -spin_unlock_irqrestore (&steam->lock, flags);if (changed &&schedule_work (&steam->work_connect) ==0 ) dbg_hid("%s: connected=%d event already queued\n",
@@ -1008,8 +1023,6 @@ static void steam_do_input_event(struct steam_device *steam,static void steam_do_battery_event (struct steam_device *steam,struct power_supply *battery,u8 *data) { -unsigned long flags; -s16 volts =steam_le16 (data +12 );u8 batt = data[14 ];
@@ -1017,10 +1030,8 @@ static void steam_do_battery_event(struct steam_device *steam,rcu_read_lock (); battery =rcu_dereference (steam->battery);if (likely (battery)) { -spin_lock_irqsave (&steam->lock, flags); steam->voltage = volts; steam->battery_charge = batt; -spin_unlock_irqrestore (&steam->lock, flags);power_supply_changed (battery); }rcu_read_unlock ();
@@ -1033,10 +1044,12 @@ static int steam_raw_event(struct hid_device *hdev,struct steam_device *steam =hid_get_drvdata (hdev);struct input_dev *input;struct power_supply *battery; +unsigned long flags;if (!steam)return 0 ; +spin_lock_irqsave (&steam->lock, flags);if (steam->client_opened)hid_input_report (steam->client_hdev,HID_FEATURE_REPORT , data, size,0 );
@@ -1057,12 +1070,12 @@ static int steam_raw_event(struct hid_device *hdev,*/ if (size !=64 || data[0 ] !=1 || data[1 ] !=0 ) -return 0 ; + goto out;switch (data[2 ]) {case STEAM_EV_INPUT_DATA :if (steam->client_opened) -return 0 ; + goto out;rcu_read_lock (); input =rcu_dereference (steam->input);if (likely (input))
@@ -1100,6 +1113,8 @@ static int steam_raw_event(struct hid_device *hdev, }break ; } +out: +spin_unlock_irqrestore (&steam->lock, flags);return 0 ; }
@@ -1108,6 +1123,8 @@ static int steam_param_set_lizard_mode(const char *val, {struct steam_device *steam;int ret; +bool client_opened; +unsigned long flags; ret =param_set_bool (val, kp);if (ret)
@@ -1115,10 +1132,14 @@ static int steam_param_set_lizard_mode(const char *val,mutex_lock (&steam_devices_lock);list_for_each_entry (steam, &steam_devices, list) { -mutex_lock (&steam->mutex); -if (!steam->client_opened) +spin_lock_irqsave (&steam->lock, flags); + client_opened = steam->client_opened; +spin_unlock_irqrestore (&steam->lock, flags); +if (!client_opened) { +mutex_lock (&steam->mutex);steam_set_lizard_mode (steam, lizard_mode); -mutex_unlock (&steam->mutex); +mutex_unlock (&steam->mutex); + } }mutex_unlock (&steam_devices_lock);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 424/571 tracing: Set the trace clock before registering the histogram trigger
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
[ Upstream commit 6ede78d0563a2a3ae3e46f9c07cedb5d79645429 ]
hist_register_trigger() puts the trigger on the global named_triggers list in cmd_ops->init(), and only then sets the trace clock:
if (data->cmd_ops->init) {
ret = data->cmd_ops->init(data);
if (ret < 0)
goto out;
}
if (hist_data->enable_timestamps) {
ret = tracing_set_clock(file->tr, hist_data->attrs->clock);
if (ret) {
hist_err(tr, HIST_ERR_SET_CLOCK_FAIL, errpos(clock));
goto out;
}The clock string is not checked anywhere before that call, so a named trigger using common_timestamp with an unknown clock fails after it has already become findable. event_hist_trigger_parse() then frees it without taking it off the list, and the next lookup by name reads the freed object:
~# cd /sys/kernel/tracing/events/sched/sched_switch
~# echo 'hist:name=foo:keys=common_pid:ts=common_timestamp:clock=bogus' > trigger
bash: echo: write error: Invalid argument
~# echo 'hist:name=foo:keys=common_pid' > trigger
BUG: KASAN: slab-use-after-free in find_named_trigger+0xac/0xc0 Read of size 8 at addr ffff88800915d760 by task init/1 find_named_trigger+0xac/0xc0 hist_register_trigger+0xc1/0x900 event_hist_trigger_parse+0x3146/0x6af0 event_trigger_write+0xce/0x160 Freed by task 63: kfree+0x154/0x420 trigger_kthread_fn+0xfd/0x160
Set the clock before the trigger is registered, so that nothing which can fail runs after it is published, the way commit 6f86bdeab633 ("tracing: Fix bad hist from corrupting named_triggers list") moved the registration below the rest of the setup.
tracing_set_filter_buffering() is reference counted, so the init failure path has to drop the reference that the clock block now takes first.
[Lee: Call data->ops->init(data->ops, data) as b052d70f7c9c ("tracing:
Merge struct event_trigger_ops into struct event_command") and 476705419518 ("tracing: Remove redundant trigger_ops params") are not present]
--- kernel/trace/trace_events_hist.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-)
kernel/trace/trace_events_hist.c +9 -6
@@ -5641,12 +5641,6 @@ static int hist_register_trigger(char *glob, struct event_trigger_ops *ops, data->ops = &event_hist_trigger_named_ops; } -if (data->ops->init) { - ret = data->ops->init (data->ops, data); -if (ret <0 ) - goto out; - } -if (hist_data->enable_timestamps) {char *clock = hist_data->attrs->clock;
@@ -5659,6 +5653,15 @@ static int hist_register_trigger(char *glob, struct event_trigger_ops *ops,tracing_set_filter_buffering (file->tr, true); } +if (data->ops->init) { + ret = data->ops->init (data->ops, data); +if (ret <0 ) { +if (hist_data->enable_timestamps) +tracing_set_filter_buffering (file->tr, false); + goto out; + } + } +if (named_data)destroy_hist_data (hist_data);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 425/571 ip6_gre: remove obsolete ERSPAN PMTU update
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit 8bc60db48e8cba35488bbd6e1f94aa990afa275a ]
A tc tunnel_key action can attach a METADATA_IP_TUNNEL dst to an skb, and mirred can redirect it to a native ip6erspan device. The legacy PMTU update in ip6erspan_tunnel_xmit() treats that metadata dst as a route. Since it has no output device, dst_dev(dst)->mtu dereferences NULL.
On v7.2 with KASAN, an initial UID/GID 65534 process with CapEff 0 used self-created user and network namespaces to trigger:
KASAN: null-ptr-deref RIP: ip6erspan_tunnel_xmit+0x10fc/0x2cc0 Kernel panic - not syncing: Fatal exception in interrupt
The update is obsolete. Commit fe1a4ca0a2b7 ("ip6_gre: process toobig in a better way") changed IPv6 GRE Too Big handling to update the underlay route and removed the equivalent block from __gre6_xmit(). ip6_tnl_xmit() then propagates the underlay PMTU to the overlay route.
Remove the stale ERSPAN copy and its now-unused dst variable. This eliminates the metadata-dst dereference and keeps ERSPAN aligned with IPv6 GRE PMTU handling.
--- net/ipv6/ip6_gre.c | 5 ----- 1 file changed, 5 deletions(-)
net/ipv6/ip6_gre.c +0 -5
@@ -917,7 +917,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb, {struct ip_tunnel_info *tun_info =NULL ;struct ip6_tnl *t =netdev_priv (dev); -struct dst_entry *dst =skb_dst (skb);struct net_device_stats *stats;bool truncate = false;int encap_limit =-1 ;
@@ -1050,10 +1049,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb,/* Push GRE header. */ gre_build_header (skb,8 ,TUNNEL_SEQ , proto,0 ,htonl (atomic_fetch_inc (&t->o_seqno))); -/* TooBig packet may have updated dst->dev's mtu */ -if (!t->parms.collect_md && dst &&dst_mtu (dst) > dst->dev->mtu) - dst->ops->update_pmtu (dst,NULL , skb, dst->dev->mtu, false); - err =ip6_tnl_xmit (skb, dev, dsfield, &fl6, encap_limit, &mtu,NEXTHDR_GRE );if (err !=0 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 426/571 selinux: fix data race on AVC latest_notif
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Göttsche <[email protected]>
[ Upstream commit 1ca924044bf0de879a1648be93a56939652267d3 ]
avc_policy_seqno() reads latest_notif without holding notif_lock, while avc_latest_notif_update() can update it under that lock. KCSAN reports these concurrent accesses during policy boolean updates and permission checks.
Use READ_ONCE() for the lockless read and WRITE_ONCE() for the update. The spinlock continues to serialize the comparison and update against other writers. Reads made while holding notif_lock cannot race with a writer and can remain plain accesses.
This marks both sides of the intentional concurrent access and constrains compiler transformations, without suppressing checking with data_race().
--- security/selinux/avc.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
security/selinux/avc.c +3 -2
@@ -588,7 +588,7 @@ static int avc_latest_notif_update(struct selinux_avc *avc, } }else {if (seqno > avc->avc_cache.latest_notif) - avc->avc_cache.latest_notif = seqno; +WRITE_ONCE (avc->avc_cache.latest_notif, seqno); }spin_unlock_irqrestore (¬if_lock, flag);
@@ -1191,7 +1191,8 @@ int avc_has_perm(struct selinux_state *state, u32 ssid, u32 tsid, u16 tclass,u32 avc_policy_seqno (struct selinux_state *state) { -return state->avc->avc_cache.latest_notif; +/* Writers hold notif_lock; readers only sample the sequence number. */ +return READ_ONCE (state->avc->avc_cache.latest_notif); }void avc_disable (void )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 427/571 EDAC/amd64: Mask UMC chip select to the four implemented selects
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vishal Badole <[email protected]>
[ Upstream commit 7484bc43ba6b8e189b482db5b75e7842890a82b1 ]
For DRAM ECC errors, the chip select value can be found in the MCA_SYND[ErrorInformation] field.
ErrorInformation[2:0] was first documented in Zen1. The 3 bit field implied that up to 8 chip selects may be used.
However, all Zen-based systems have only ever had up to 4 chip selects. So only bits [1:0] would contain a valid chip select value.
Future systems are redefining the field to ErrorInformation[1:0]. This matches the existing 'up to 4 chip selects' implementations. And it frees up the extra bit for other decoding.
Change the current chip select mask from 0x7 to 0x3 to prepare for the decode change.
--- drivers/edac/amd64_edac.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/edac/amd64_edac.c +1 -1
@@ -2940,7 +2940,7 @@ static void decode_umc_error(int node_id, struct mce *m) err.err_code =ERR_CHANNEL ; } - err.csrow = m->synd &0x7 ; + err.csrow = m->synd &0x3 ;if (umc_normaddr_to_sysaddr (m->addr, pvt->mc_node_id, err.channel, &sys_addr)) { err.err_code =ERR_NORM_ADDR ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 428/571 mm/mremap: fix locked_vm leak by splitting VMA for MREMAP_DONTUNMAP
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 597e4b9ab48a3f841080f627722064853d3f650e ]
The MREMAP_DONTUNMAP feature is highly unusual in that it permits mremap() operations that keep the original VMA in place.
Historically this has led to a lot of bugs where non-obvious interactions occur between existing mremap() operations and the original VMA.
Fix another of these - partial copies.
The long-standing mremap() partial VMA logic has the baked-in assumption that the originating VMA is unmapped and thus moved.
However MREMAP_DONTUNMAP defeats this by performing a partial copy instead since it keeps the source VMA around.
An mremap(..., MREMAP_DONTUNMAP) operation disallows resizing of the VMA, but the operation can be performed partially:
|-----------------|
| |
| v
<------> <------>
.new_sz. new_sz
|--.------.--| |------|
| .source. | | dest |
|--.------.--| |------|
<------------>
old_szThe page tables in the specified range are moved, but the original VMA is kept intact.
This interacts poorly with mlock()'d VMAs, as the VMA_LOCKED_BIT flag is cleared for the entire source VMA and set for the entire destination VMA.
This results in an mm->locked_vm leak as the change is therefore not accounted correctly.
The clear solution here is to make the portion of the source VMA which is mremap()'d distinct from the rest of it, a.k.a. split it.
Therefore resolve this issue by splitting it ahead of the rest of the mremap() operation if the VMA is mlock()'d.
This is valid, as the source VMA will lose its VMA_LOCKED_BIT flag, so if a partial remap it will become distinct from the rest of the VMA.
In order to make this change re-expose split_vma() in vma.h for CONFIG_MMU (nommu doesn't compile mremap.c and uses a static helper instead).
Finally, update the sys_map_count check to account for this case.
Note that the early check does not use needs_pre_split() - this is because the VMA has not been looked up by this point, so be conservative and assume that the VMA is mlock()'d in this case for the purposes of the sys_map_count check.
--- mm/mremap.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-)
mm/mremap.c +17 -2
@@ -578,6 +578,8 @@ static unsigned long move_vma(struct vm_area_struct *vma,int split =0 ;int err =0 ;bool need_rmap_locks; +const bool split_before = vma->vm_start != old_addr; +const bool split_after = vma->vm_end != old_addr + old_len;/* * We'd prefer to avoid failure later on in do_munmap:
@@ -587,9 +589,9 @@ static unsigned long move_vma(struct vm_area_struct *vma,return -ENOMEM ;if (vma->vm_ops && vma->vm_ops->may_split) { -if (vma->vm_start != old_addr) +if (split_before) err = vma->vm_ops->may_split (vma, old_addr); -if (!err && vma->vm_end != old_addr + old_len) +if (!err && split_after) err = vma->vm_ops->may_split (vma, old_addr + old_len);if (err)return err;
@@ -607,6 +609,19 @@ static unsigned long move_vma(struct vm_area_struct *vma,if (err)return err; +/* +* To account mlock()'d pages correctly in the MREMAP_DONTUNMAP +* case perform any split ahead of time for an mlock()'d VMA. +*/ +if ((flags &MREMAP_DONTUNMAP ) && (vma->vm_flags &VM_LOCKED )) { +if (split_before) + err =split_vma (mm, vma, old_addr,1 ); +if (!err && split_after) + err =split_vma (mm, vma, old_addr + old_len,0 ); +if (err) +return err; + } +if (unlikely (flags &MREMAP_DONTUNMAP && vm_flags &VM_ACCOUNT )) {if (security_vm_enough_memory_mm (mm, new_len >>PAGE_SHIFT ))return -ENOMEM ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 429/571 mm/mremap: fix locked_vm leak from MREMAP_DONTUNMAP self-merge
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 838bb60dc21553e32df90f2f3bac5b905376e7aa ]
The MREMAP_DONTUNMAP feature is highly unusual in that it permits mremap() operations that keep the original VMA in place.
Historically this has led to a lot of bugs where non-obvious interactions occur between existing mremap() operations and the original VMA.
Fix another of these - self-merge.
Self-merge occurs when a VMA is moved in front of or behind itself and the attributes of the VMA permit such a merge.
Practically this can only happen for unfaulted anonymous VMAs due to the page offset equality requirement for merge:
|------------|
| |
| v
|...........||-----------||...........|
| || unfaulted || |
|...........||-----------||...........|
^ |
| |
|------------|This becomes problematic if the VMA is configured by the user to mlock-on-fault, i.e. the VMA_LOCKED_BIT, VMA_LOCKONFAULT_BIT VMA flags are set.
MREMAP_DONTUNMAP clears mlock flags for the source VMA and maintains them for the destination VMA.
Self-merge makes this impossible (there is only one VMA) and incorrectly clears the destination VMA's mlock flags.
This causes a leak in mm->locked_vm as clearing this flag does not decrement the counter and the VMA no longer has VMA_LOCKED_BIT set so it is not decremented on unmap.
Resolve this by simply disallowing a self-merge in this case - the source and destination VMAs are kept distinct and then are able to have distinct mlock() flags.
Update to make the now-redundant self-merge check a VM_WARN_ON_ONCE() instead to guard against future regressions.
--- include/linux/mm.h | 2 +- mm/mmap.c | 23 +++++++++++++++++++---- mm/mremap.c | 7 +++++-- 3 files changed, 25 insertions(+), 7 deletions(-)
include/linux/mm.h +1 -1
@@ -2581,7 +2581,7 @@ extern void __vma_link_rb(struct mm_struct *, struct vm_area_struct *,extern void unlink_file_vma (struct vm_area_struct *);extern struct vm_area_struct *copy_vma (struct vm_area_struct **,unsigned long addr,unsigned long len,pgoff_t pgoff, -bool *need_rmap_locks); +bool *need_rmap_locks,bool keep_source);extern void exit_mmap (struct mm_struct *); static inline int check_data_rlimit(unsigned long rlim,
mm/mmap.c +19 -4
@@ -3281,7 +3281,7 @@ int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)*/ struct vm_area_struct *copy_vma (struct vm_area_struct **vmap,unsigned long addr,unsigned long len,pgoff_t pgoff, -bool *need_rmap_locks) +bool *need_rmap_locks,bool keep_source) {struct vm_area_struct *vma = *vmap;unsigned long vma_start = vma->vm_start;
@@ -3289,6 +3289,7 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,struct vm_area_struct *new_vma, *prev;struct rb_node **rb_link, *rb_parent;bool faulted_in_anon_vma = true; +bool can_self_merge = false;/* * If anonymous vma has not yet been faulted, update new pgoff
@@ -3297,13 +3298,27 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,if (unlikely (vma_is_anonymous (vma) && !vma->anon_vma)) { pgoff = addr >>PAGE_SHIFT ; faulted_in_anon_vma = false; + can_self_merge = true; }if (find_vma_links (mm, addr, addr + len, &prev, &rb_link, &rb_parent))return NULL ;/* should never get here */ - new_vma =vma_merge (mm, prev, addr, addr + len, vma->vm_flags, - vma->anon_vma, vma->vm_file, pgoff,vma_policy (vma), - vma->vm_userfaultfd_ctx); + +/* +* If the original VMA is kept (MREMAP_DONTUNMAP), the source and +* destination VMA must be treated distinctly. +* +* A merge violates this, so in this case disallow a self-merge. A +* self-merge can only occur if the new range is immediately adjacent to +* the source VMA, so simply do not attempt to merge in that case. +*/ +if (can_self_merge && keep_source && + (addr == vma->vm_end || vma->vm_start == addr + len)) + new_vma =NULL ; +else + new_vma =vma_merge (mm, prev, addr, addr + len, vma->vm_flags, + vma->anon_vma, vma->vm_file, pgoff, +vma_policy (vma), vma->vm_userfaultfd_ctx);if (new_vma) {/* * Source vma may have been merged into new_vma
mm/mremap.c +5 -2
@@ -629,7 +629,7 @@ static unsigned long move_vma(struct vm_area_struct *vma, new_pgoff = vma->vm_pgoff + ((old_addr - vma->vm_start) >>PAGE_SHIFT ); new_vma =copy_vma (&vma, new_addr, new_len, new_pgoff, - &need_rmap_locks); + &need_rmap_locks, flags &MREMAP_DONTUNMAP );if (!new_vma) {if (unlikely (flags &MREMAP_DONTUNMAP && vm_flags &VM_ACCOUNT ))vm_unacct_memory (new_len >>PAGE_SHIFT );
@@ -686,6 +686,9 @@ static unsigned long move_vma(struct vm_area_struct *vma,untrack_pfn_moved (vma);if (unlikely (!err && (flags &MREMAP_DONTUNMAP ))) { +/* Self-merge is disallowed. */ +VM_WARN_ON_ONCE (new_vma == vma); +/* We always clear VM_LOCKED[ONFAULT] on the old vma */ vma->vm_flags &=VM_LOCKED_CLEAR_MASK ;
@@ -693,7 +696,7 @@ static unsigned long move_vma(struct vm_area_struct *vma,* anon_vma links of the old vma is no longer needed after its page * table has been moved. */ -if (new_vma != vma && vma->vm_start == old_addr && +if (vma->vm_start == old_addr && vma->vm_end == (old_addr + old_len)) {const pgoff_t pgoff_unfaulted = vma->vm_start >>PAGE_SHIFT ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 430/571 netfilter: nf_tables: fix bidirectional offload regression
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Fietkau <[email protected]>
[ Upstream commit 84443741faab9045d53f022a9ac6a6633067a481 ]
Commit 8f84780b84d6 ("netfilter: flowtable: allow unidirectional rules") made unidirectional flow offload possible, while completely ignoring (and breaking) bidirectional flow offload for nftables.
Add the missing flag that was left out as an exercise for the reader :)
--- net/netfilter/nft_flow_offload.c | 1 + 1 file changed, 1 insertion(+)
net/netfilter/nft_flow_offload.c +1 -0
@@ -351,6 +351,7 @@ static void nft_flow_offload_eval(const struct nft_expr *expr,if (tcph)flow_offload_ct_tcp (ct); +__set_bit (NF_FLOW_HW_BIDIRECTIONAL , &flow->flags); ret =flow_offload_add (flowtable, flow);if (ret <0 ) goto err_flow_add;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 431/571 net: team: Remove unused team_mode_op, port_enabled
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Harvey <[email protected]>
[ Upstream commit 014f249121d73909528df320818fba7693d0ec92 ]
This team_mode_op wasn't used by any of the team modes, so remove it.
Stable-dep-of: b7454f1940c5 ("net: team: stop reusing skb after queue override")
--- drivers/net/team/team.c | 2 -- include/linux/if_team.h | 1 - 2 files changed, 3 deletions(-)
drivers/net/team/team.c +0 -2
@@ -940,8 +940,6 @@ static void team_port_enable(struct team *team, team_port_index_hash(team, port->index));team_adjust_ops (team);team_queue_override_port_add (team, port); -if (team->ops.port_enabled) - team->ops.port_enabled (team, port);team_notify_peers (team);team_mcast_rejoin (team);team_lower_state_changed (port);
include/linux/if_team.h +0 -1
@@ -121,7 +121,6 @@ struct team_mode_ops {int (*port_enter)(struct team *team,struct team_port *port);void (*port_leave)(struct team *team,struct team_port *port);void (*port_change_dev_addr)(struct team *team,struct team_port *port); -void (*port_enabled)(struct team *team,struct team_port *port);void (*port_disabled)(struct team *team,struct team_port *port); };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 432/571 net: team: Rename port_disabled team mode op to port_tx_disabled
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Harvey <[email protected]>
[ Upstream commit cfa477df2cc62ba53cb936669886361152b594a7 ]
This team mode op is only used by the load balance mode, and it only uses it in the tx path.
Stable-dep-of: b7454f1940c5 ("net: team: stop reusing skb after queue override")
--- drivers/net/team/team.c | 4 ++-- drivers/net/team/team_mode_loadbalance.c | 4 ++-- include/linux/if_team.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-)
drivers/net/team/team.c +2 -2
@@ -964,8 +964,8 @@ static void team_port_disable(struct team *team, {if (!team_port_enabled (port))return ; -if (team->ops.port_disabled) - team->ops.port_disabled (team, port); +if (team->ops.port_tx_disabled) + team->ops.port_tx_disabled (team, port);hlist_del_rcu (&port->hlist);__reconstruct_port_hlist (team, port->index); port->index =-1 ;
drivers/net/team/team_mode_loadbalance.c +2 -2
@@ -672,7 +672,7 @@ static void lb_port_leave(struct team *team, struct team_port *port)free_percpu (lb_port_priv->pcpu_stats); } -static void lb_port_disabled (struct team *team,struct team_port *port) +static void lb_port_tx_disabled (struct team *team,struct team_port *port) {lb_tx_hash_to_port_mapping_null_port (team, port); }
@@ -682,7 +682,7 @@ static const struct team_mode_ops lb_mode_ops = { .exit = lb_exit, .port_enter = lb_port_enter, .port_leave = lb_port_leave, - .port_disabled = lb_port_disabled, + .port_tx_disabled = lb_port_tx_disabled, .receive = lb_receive, .transmit = lb_transmit, };
include/linux/if_team.h +1 -1
@@ -121,7 +121,7 @@ struct team_mode_ops {int (*port_enter)(struct team *team,struct team_port *port);void (*port_leave)(struct team *team,struct team_port *port);void (*port_change_dev_addr)(struct team *team,struct team_port *port); -void (*port_disabled)(struct team *team,struct team_port *port); +void (*port_tx_disabled)(struct team *team,struct team_port *port); };extern int team_modeop_port_enter (struct team *team,struct team_port *port);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 433/571 net: team: fix NULL pointer dereference in team_xmit during mode change
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
[ Upstream commit 25fe708bbc59289d3d1ea4b126fbc1b460a072a5 ]
__team_change_mode() clears team->ops with memset() before restoring safe dummy handlers via team_adjust_ops(). A concurrent team_xmit() running under RCU on another CPU can read team->ops.transmit during this window and call a NULL function pointer, crashing the kernel.
The race requires a mode change (CAP_NET_ADMIN) concurrent with transmit on the team device.
BUG: kernel NULL pointer dereference, address: 0000000000000000 Oops: 0010 [#1] SMP KASAN NOPTI RIP: 0010:0x0 Call Trace: team_xmit (drivers/net/team/team_core.c:1853) dev_hard_start_xmit (net/core/dev.c:3904) __dev_queue_xmit (net/core/dev.c:4871) packet_sendmsg (net/packet/af_packet.c:3109) __sys_sendto (net/socket.c:2265)
The original code assumed that no ports means no traffic, so mode changes could freely memset()/memcpy() the ops. AF_PACKET with forced carrier breaks that assumption.
Prevent the race instead of making it safe: replace memset()/memcpy() with per-field updates that never touch transmit or receive. Those two handlers are managed solely by team_adjust_ops(), which already installs dummies when tx_en_port_count == 0 (always true during mode change since no ports are present). WRITE_ONCE/READ_ONCE prevent store/load tearing on the handler pointers.
synchronize_net() before exit_op() drains in-flight readers that may still reference old mode state from before port removal switched the handlers to dummies.
Stable-dep-of: b7454f1940c5 ("net: team: stop reusing skb after queue override")
--- drivers/net/team/team.c | 45 +++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 13 deletions(-)
drivers/net/team/team.c +32 -13
@@ -535,21 +535,23 @@ static void team_adjust_ops(struct team *team)if (!team->en_port_count || !team_is_mode_set (team) || !team->mode->ops->transmit) - team->ops.transmit = team_dummy_transmit; +WRITE_ONCE (team->ops.transmit, team_dummy_transmit);else - team->ops.transmit = team->mode->ops->transmit; +WRITE_ONCE (team->ops.transmit, team->mode->ops->transmit);if (!team->en_port_count || !team_is_mode_set (team) || !team->mode->ops->receive) - team->ops.receive = team_dummy_receive; +WRITE_ONCE (team->ops.receive, team_dummy_receive);else - team->ops.receive = team->mode->ops->receive; +WRITE_ONCE (team->ops.receive, team->mode->ops->receive); }/* -* We can benefit from the fact that it's ensured no port is present -* at the time of mode change. Therefore no packets are in fly so there's no -* need to set mode operations in any special way. +* team_change_mode() ensures no ports are present during mode change, +* but lockless readers can still reach team_xmit(). Avoid touching +* transmit/receive -- they are already set to dummies by +* team_adjust_ops() since no ports are enabled. synchronize_net() +* drains in-flight readers before destroying old mode state. */ static int __team_change_mode (struct team *team,const struct team_mode *new_mode)
@@ -558,9 +560,21 @@ static int __team_change_mode(struct team *team,if (team_is_mode_set (team)) {void (*exit_op)(struct team *team) = team->ops.exit; -/* Clear ops area so no callback is called any longer */ -memset (&team->ops,0 ,sizeof (struct team_mode_ops )); -team_adjust_ops (team); +/* Clear cold-path ops used only under RTNL. transmit and +* receive are already dummies (no ports) so leave them +* alone -- overwriting them is the source of the race. +*/ + team->ops.init =NULL ; + team->ops.exit =NULL ; + team->ops.port_enter =NULL ; + team->ops.port_leave =NULL ; + team->ops.port_change_dev_addr =NULL ; + team->ops.port_tx_disabled =NULL ; + +/* Wait for in-flight readers before tearing down mode +* state they may reference. +*/ +synchronize_net ();if (exit_op)exit_op (team);
@@ -583,7 +597,12 @@ static int __team_change_mode(struct team *team, } team->mode = new_mode; -memcpy (&team->ops, new_mode->ops,sizeof (struct team_mode_ops )); + team->ops.init = new_mode->ops->init; + team->ops.exit = new_mode->ops->exit; + team->ops.port_enter = new_mode->ops->port_enter; + team->ops.port_leave = new_mode->ops->port_leave; + team->ops.port_change_dev_addr = new_mode->ops->port_change_dev_addr; + team->ops.port_tx_disabled = new_mode->ops->port_tx_disabled;team_adjust_ops (team);return 0 ;
@@ -739,7 +758,7 @@ static rx_handler_result_t team_handle_frame(struct sk_buff **pskb)/* allow exact match delivery for disabled ports */ res =RX_HANDLER_EXACT ; }else { - res = team->ops.receive (team, port, skb); + res =READ_ONCE (team->ops.receive)(team, port, skb); }if (res ==RX_HANDLER_ANOTHER ) {struct team_pcpu_stats *pcpu_stats;
@@ -1737,7 +1756,7 @@ static netdev_tx_t team_xmit(struct sk_buff *skb, struct net_device *dev) tx_success =team_queue_override_transmit (team, skb);if (!tx_success) - tx_success = team->ops.transmit (team, skb); + tx_success =READ_ONCE (team->ops.transmit)(team, skb);if (tx_success) {struct team_pcpu_stats *pcpu_stats;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 434/571 net: team: stop reusing skb after queue override
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
[ Upstream commit b7454f1940c5e6d92e753853c476a769e452f30a ]
A nonzero dev_queue_xmit() result does not return ownership of the skb. When an override port's qdisc drops it, the queue override helper used to try another port or the mode transmit op with the freed skb.
Return the handoff decision separately from transmit success. Select only the first override port under RCU and stop after handing it the skb, regardless of the lower transmit result. Keep the existing success and drop accounting.
BUG: KASAN: slab-use-after-free in sk_skb_reason_drop Write of size 4 by task poc/5040 sk_skb_reason_drop (net/core/skbuff.c:1240) dev_kfree_skb_any_reason (net/core/dev.c:3470) ab_transmit (drivers/net/team/team_mode_activebackup.c:49) team_xmit (drivers/net/team/team_core.c:1849) __dev_direct_xmit (net/core/dev.c:4934) Freed by task 5040: __tcf_kfree_skb_list (net/sched/sch_generic.c:43) __dev_queue_xmit (net/core/dev.c:4831) team_xmit (drivers/net/team/team_core.c:1846) Kernel panic - not syncing: KASAN: panic_on_warn set ...
--- drivers/net/team/team.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/net/team/team.c +8 -8
@@ -817,7 +817,8 @@ static struct list_head *__team_get_qom_list(struct team *team, u16 queue_id)/* * note: already called with rcu_read_lock */ -static bool team_queue_override_transmit (struct team *team,struct sk_buff *skb) +static bool team_queue_override_transmit (struct team *team,struct sk_buff *skb, +bool *tx_success) {struct list_head *qom_list;struct team_port *port;
@@ -825,11 +826,11 @@ static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb)if (!team->queue_override_enabled || !skb->queue_mapping)return false; qom_list =__team_get_qom_list (team, skb->queue_mapping); -list_for_each_entry_rcu (port, qom_list, qom_list) { -if (!team_dev_queue_xmit (team, port, skb)) -return true; - } -return false; + port = list_first_or_null_rcu(qom_list, struct team_port, qom_list); +if (!port) +return false; + *tx_success = !team_dev_queue_xmit (team, port, skb); +return true; } static void __team_queue_override_port_del(struct team *team,
@@ -1754,8 +1755,7 @@ static netdev_tx_t team_xmit(struct sk_buff *skb, struct net_device *dev)bool tx_success;unsigned int len = skb->len; - tx_success =team_queue_override_transmit (team, skb); -if (!tx_success) +if (!team_queue_override_transmit (team, skb, &tx_success)) tx_success =READ_ONCE (team->ops.transmit)(team, skb);if (tx_success) {struct team_pcpu_stats *pcpu_stats;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 435/571 Bluetooth: RFCOMM: connect the session socket without rfcomm_mutex
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikhail Gavrilov <[email protected]>
[ Upstream commit ac022970e9fb0a5f7e7d1f6c8e104c1ed924dd1c ]
An RFCOMM connect() issued while a BR/EDR link is being authenticated makes lockdep report a circular dependency, and the reported cycle is a real AB/BA between rfcomm_mutex and hdev->lock.
rfcomm_security_cfm() is called from the HCI event path, which already holds hdev->lock:
hci_rx_work()
hci_event_packet()
hci_cc_read_enc_key_size() [hdev->lock]
hci_encrypt_cfm() [hci_cb_list_lock]
rfcomm_security_cfm() [rfcomm_mutex]while an RFCOMM connect() from userspace takes the same two locks the other way round:
rfcomm_sock_connect()
rfcomm_dlc_open() [rfcomm_mutex]
__rfcomm_dlc_open()
rfcomm_session_create()
kernel_connect()
l2cap_sock_connect()
l2cap_chan_connect() [hdev->lock] WARNING: possible circular locking dependency detected kworker/u131:1/1128 is trying to acquire lock:
rfcomm_mutex, at: rfcomm_security_cfm+0x31/0x3e0 [rfcomm] but task is already holding lock:
hci_cb_list_lock, at: hci_cc_read_enc_key_size+0x1d2/0xcc0
Chain exists of:
rfcomm_mutex --> &hdev->lock --> hci_cb_list_lockhci_auth_complete_evt() and hci_encrypt_change_evt() reach the callback the same way.
Both orders have to be seen in the same boot, which is why a BR/EDR connection alone is not enough to show it: a session set up by the remote side is created by rfcomm_accept_connection() in krfcommd, which calls kernel_accept() and never takes hdev->lock under rfcomm_mutex. Connecting a device that authenticates and encrypts the link and then calling connect() on an RFCOMM socket towards any address - the connect does not have to succeed, the order is recorded before the page timeout
- reports it every time.
Only the session socket has to be connected with the lock held, and it does not: nothing else can see the socket before it is put on the session list. So connect it first and take rfcomm_mutex afterwards, which removes the rfcomm_mutex -> hdev->lock order for good, rather than keeping the HCI event path out of rfcomm_mutex.
rfcomm_session_create() becomes rfcomm_session_connect(), which returns the connected socket without touching the session list, and rfcomm_dlc_open() adds the session once it holds the lock again. If another opener added a session for the same pair while this socket was connecting, that session is used and this socket is dropped. __rfcomm_dlc_open() now takes the session it should use, and its state check runs after the lock is re-acquired, so a DLC that was opened or closed in the meantime is still handled.
Over an existing ACL link the connection can complete before the session reaches the list, and the wakeup from the socket callback is then lost, so krfcommd is woken once the session is visible.
Connecting without the lock opens a window in which the socket can be closed. The DLC is not on a session yet, so rfcomm_dlc_close() finds nothing to do and returns without touching it, and rfcomm_dlc_open() would then attach a DLC whose owner is gone. rfcomm_dlc_close() now marks such a DLC with RFCOMM_CLOSED, and rfcomm_dlc_open() checks the mark once it holds rfcomm_mutex again and drops the socket instead of attaching the DLC. The mark is cleared when an open starts, so a DLC that is reused is not affected. This covers both callers of rfcomm_dlc_open(), the socket and the tty layer.
--- include/net/bluetooth/rfcomm.h | 1 + net/bluetooth/rfcomm/core.c | 134 +++++++++++++++++++++++---------- 2 files changed, 96 insertions(+), 39 deletions(-)
include/net/bluetooth/rfcomm.h +1 -0
@@ -210,6 +210,7 @@ struct rfcomm_dlc {#define RFCOMM_AUTH_REJECT 7#define RFCOMM_DEFER_SETUP 8#define RFCOMM_ENC_DROP 9 +#define RFCOMM_CLOSED 10/* Scheduling flags and events */ #define RFCOMM_SCHED_WAKEUP 31
net/bluetooth/rfcomm/core.c +95 -39
191 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 436/571 drm/vmwgfx: validate pitch coming from userspace
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zack Rusin <[email protected]>
[ Upstream commit 21bc51cb89ced74d6645a138cc2f21184bc75094 ]
Validate the pitch, alongside the box dimensions before trying to copy data from the underlying surface. Fixes possible out of bounds reads with cursor snooping.
--- drivers/gpu/drm/vmwgfx/vmwgfx_kms.c | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-)
drivers/gpu/drm/vmwgfx/vmwgfx_kms.c +18 -4
@@ -155,6 +155,7 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,unsigned long kmap_num;SVGA3dCopyBox *box;unsigned box_count; +u64 src_extent;void *virtual;bool dummy;struct vmw_dma_cmd {
@@ -163,6 +164,8 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, } *cmd;int i, ret; +BUILD_BUG_ON (sizeof (*srf->snooper.image) !=4 ); + cmd = container_of(header, struct vmw_dma_cmd, header);/* No snooper installed */
@@ -200,8 +203,19 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,return ; } +if (box->w ==0 || box->h ==0 ) +return ; + + src_extent = (u64)(box->h -1 ) * cmd->dma.guest.pitch + + (u64 )box->w *4 ; +if (src_extent > bo->base.size) { +DRM_ERROR ("Cursor snoop source of %llu bytes exceeds the %zu byte buffer\n" , + src_extent, bo->base.size); +return ; + } + kmap_offset = cmd->dma.guest.ptr.offset >>PAGE_SHIFT ; - kmap_num = (64 *64 *4 ) >>PAGE_SHIFT ; + kmap_num =PFN_UP (src_extent); ret =ttm_bo_reserve (bo, true, false,NULL );if (unlikely (ret !=0 )) {
@@ -215,13 +229,13 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf, virtual =ttm_kmap_obj_virtual (&map, &dummy); -if (box->w ==64 && cmd->dma.guest.pitch ==64 *4 ) { +if (box->w ==64 && box->h ==64 && cmd->dma.guest.pitch ==64 *4 ) {memcpy (srf->snooper.image, virtual,64 *64 *4 ); }else { -/* Image is unsigned pointer. */ +/* The destination stride is in pixels. */ for (i =0 ; i < box->h; i++)memcpy (srf->snooper.image + i *64 , - virtual + i * cmd->dma.guest.pitch, + virtual + (size_t )i * cmd->dma.guest.pitch, box->w *4 ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 437/571 namespace: dont inherit MNT_UMOUNT in clone_mnt()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit e2c6d326216642011da318b9edfd5d57ebd5a56f ]
MNT_UMOUNT gets raised on a mount that umount_tree() or umount_one() has taken out of its namespace. It's never cleared. __detach_mounts() unhooks a mount that carries it instead of unmounting it.
disconnect_mount() lets an unmounted child stay attached only if its parent carries it. propagate_umount() takes it as the sign that a mount is going to be unmounted when it decides what else can be unmounted, where a chain of locked mounts ends and where a for reparenting an overmount.
clone_mnt() copies the flags of the source and only masks MNT_INTERNAL_FLAGS which doesn't include MNT_UMOUNT. A mount that was lazily unmounted but is kept alive by a file descriptor can still be copied when its root is an nsfs or pidfs file because may_copy_tree() accepts those before checking whether the source is mounted at all:
mount --bind /proc/self/ns/net /tmp/x exec 3< /tmp/x umount -l /tmp/x mount --bind /proc/self/fd/3 /tmp/y
The mount on /tmp/y is attached to the caller's namespace with MNT_UMOUNT already set and every copy of it inherits the flag again.
That causes a number of bugs:
- Unlink its mountpoint from a mount namespace where it isn't one. __detach_mounts() takes it for a mount that was unmounted earlier, unhooks it from its parent and drops the reference the namespace holds on it. It stays in the namespace with one reference too few and as its own parent, so it can't be unmounted through the file descriptor anymore and the namespace never finds it again. When the namespace goes away it's leaked and points to a freed struct mnt_namespace that may_change_propagation() and anon_ns_root() read on the next propagation change or mount_setattr() through the file descriptor.
- Make it shared and unmount a peer. trace_transfers() follows the flag from the peer into it and strips it from its peer group.
- Let a propagated umount reach it. gather_candidates() marks it with T_UMOUNT_CANDIDATE but never puts it on the candidate list, so the mark is never cleared and every later propagated umount skips it. If it's the parent of a locked mount handle_locked() takes it as the cutoff and commits the locked child that should have stayed and disconnect_mount() leaves that child attached to it, unmounted under a mounted parent, which is what disconnect_mount() exists to prevent. When the namespace goes away umount_tree() visits the child a second time. And once __detach_mounts() has made it its own parent reparent() never finds the end of the chain of unmounted parents.
A clone is a new mount that has never been unmounted. Add MNT_UMOUNT to MNT_INTERNAL_FLAGS so clone_mnt() never copies it. And warn when umount_tree() reaches a mount that already has it set.
--- fs/namespace.c | 4 +++- include/linux/mount.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-)
fs/namespace.c +3 -1
@@ -1079,7 +1079,7 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root, } mnt->mnt.mnt_flags = old->mnt.mnt_flags; - mnt->mnt.mnt_flags &= ~(MNT_WRITE_HOLD |MNT_MARKED |MNT_INTERNAL ); + mnt->mnt.mnt_flags &= ~(MNT_WRITE_HOLD |MNT_MARKED |MNT_INTERNAL |MNT_UMOUNT );atomic_inc (&sb->s_active); mnt->mnt.mnt_userns =mnt_user_ns (&old->mnt);
@@ -1518,6 +1518,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)/* Gather the mounts to umount */ for (p = mnt; p; p =next_mnt (p, mnt)) { +/* A mount is unmounted once. */ +WARN_ON_ONCE (p->mnt.mnt_flags &MNT_UMOUNT ); p->mnt.mnt_flags |=MNT_UMOUNT ;list_move (&p->mnt_list, &tmp_list); }
include/linux/mount.h +1 -1
@@ -52,7 +52,7 @@ struct fs_context;#define MNT_INTERNAL_FLAGS (MNT_SHARED | MNT_WRITE_HOLD | MNT_INTERNAL | \ MNT_DOOMED | MNT_SYNC_UMOUNT | MNT_MARKED | \ - MNT_CURSOR) + MNT_CURSOR | MNT_UMOUNT)#define MNT_INTERNAL 0x4000
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 438/571 namespace: check the mounts before reading their parents in pivot_root()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 6b7c001eb5857fa09041f47673666060a2e5fc1c ]
path_pivot_root() reads the parents of new_root and of the caller's root and checks whether they are shared before it checks that either mount is in the caller's mount namespace. Only namespace_sem is held. That's fine for a mount that is in the caller's mount namespace.
But new_root can be a file descriptor to a mount that has been unmounted and that only the file descriptor keeps alive. If that mount stayed attached to its parent when it was unmounted nothing pins the parent for it. The final mntput() of the parent unhooks the children under mount_lock alone and frees the parent afterwards:
pivot_root() close(fd), last ref on the parent
------------ ---------------------------------
ex_parent = new_mnt->mnt_parent
mntput_no_expire_slowpath()
__umount_mnt(new_mnt)
cleanup_mnt()
call_rcu() IS_MNT_SHARED(ex_parent)
BUG: KASAN: slab-use-after-free in path_pivot_root+0xf1a/0x1840 Read of size 4 at addr ffff8881047382f8 by task pivot_widen/157 path_pivot_root+0xf1a/0x1840 __x64_sys_pivot_root+0x165/0x190
The same goes for the caller's root via chroot(). Both outcomes of the check end in EINVAL so nothing but the read itself goes wrong. It's the same thing commit bb4609405752 ("statmount: read the parent of an unmounted mount under mount_lock") fixed for statmount().
Check that both mounts are in the caller's namespace before their parents are read. Every path returns EINVAL either way.
--- fs/namespace.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/namespace.c +3 -2
@@ -3929,14 +3929,15 @@ SYSCALL_DEFINE2(pivot_root, const char __user *, new_root, new_mnt =real_mount (new.mnt); root_mnt =real_mount (root.mnt); old_mnt =real_mount (old.mnt); +/* only a mounted mount has a parent that namespace_sem pins */ +if (!check_mnt (root_mnt) || !check_mnt (new_mnt)) + goto out4; ex_parent = new_mnt->mnt_parent; root_parent = root_mnt->mnt_parent;if (IS_MNT_SHARED (old_mnt) ||IS_MNT_SHARED (ex_parent) ||IS_MNT_SHARED (root_parent)) goto out4; -if (!check_mnt (root_mnt) || !check_mnt (new_mnt)) - goto out4;if (new_mnt->mnt.mnt_flags &MNT_LOCKED ) goto out4; error = -ENOENT ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 439/571 dm: fix reading free memory in do_resume
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
[ Upstream commit c9417c1c5269e2bd0570fbe53e4ec03a8d31f008 ]
When do_resume calls dm_table_get_mode(new_map), the call is done without holding any locks (it only holds a reference to the md). It may be possible that another concurrent ioctl on the same device will swap table after dm_swap_table and before dm_table_get_mode. In this case, dm_table_get_mode(new_map) reads freed memory.
This race condition was triggered by syzbot.
This commit fixes the race by reading mode of the new table before dm_swap_table. Note that new_map is also passed to dm_ima_need_measure, but this function doesn't attempt to dereference it, so this call should be safe.
Note that this is not a security bug because only root can trigger it and the commonly used tools such as lvm or cryptsetup do not call the ioctls concurrently, so that they can't trigger it acceidentally.
--- drivers/md/dm-ioctl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-ioctl.c +3 -1
@@ -1151,6 +1151,7 @@ static int do_resume(struct dm_ioctl *param)/* Do we need to load a new map ? */ if (new_map) {sector_t old_size, new_size; +fmode_t new_map_mode;/* Suspend if it isn't already suspended */ if (param->flags &DM_SKIP_LOCKFS_FLAG )
@@ -1178,6 +1179,7 @@ static int do_resume(struct dm_ioctl *param) } } + new_map_mode =dm_table_get_mode (new_map); old_size =dm_get_size (md); old_map =dm_swap_table (md, new_map);if (IS_ERR (old_map)) {
@@ -1190,7 +1192,7 @@ static int do_resume(struct dm_ioctl *param)if (old_size && new_size && old_size != new_size) need_resize_uevent = true; -if (dm_table_get_mode (new_map) &FMODE_WRITE ) +if (new_map_mode &FMODE_WRITE )set_disk_ro (dm_disk (md),0 );else set_disk_ro (dm_disk (md),1 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 440/571 pmdomain: rockchip: fix clock leak on domain probe failure
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Lin <[email protected]>
[ Upstream commit d8b3847770661b7109146e6479eeadcdab9cecf0 ]
When of_clk_get() failed in the middle of the loop, the references of the clocks acquired so far were leaked instead of being released by the error path.
--- drivers/soc/rockchip/pm_domains.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/soc/rockchip/pm_domains.c +1 -1
@@ -443,7 +443,7 @@ static int rockchip_pm_add_one_domain(struct rockchip_pmu *pmu,dev_err (pmu->dev,"%pOFn: failed to get clk at index %d: %d\n" , node, i, error); -return error; + goto err_put_clocks; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 441/571 pmdomain: rockchip: dont ignore clock lookup errors on attach
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Lin <[email protected]>
[ Upstream commit 4c66c423593e26273ea0d644906ed007630c6f6d ]
rockchip_pd_attach_dev() treated every of_clk_get() error as the end of the clock list, so a clock that exists but is not available yet (e.g. -EPROBE_DEFER) was silently skipped and the device ended up without pm_clk management. Only -ENOENT means there are no more clocks.
--- drivers/soc/rockchip/pm_domains.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/soc/rockchip/pm_domains.c +13 -1
@@ -364,7 +364,19 @@ static int rockchip_pd_attach_dev(struct generic_pm_domain *genpd, } i =0 ; -while ((clk =of_clk_get (dev->of_node, i++)) && !IS_ERR (clk)) { +while (1 ) { + clk =of_clk_get (dev->of_node, i++); +if (IS_ERR (clk)) { + error =PTR_ERR (clk); +if (error == -ENOENT ) +break ; + +dev_err (dev,"failed to get clock %d: %d\n" , i -1 , + error); +pm_clk_destroy (dev); +return error; + } +dev_dbg (dev,"adding clock '%pC' to list of PM clocks\n" , clk); error =pm_clk_add_clk (dev, clk);if (error) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 442/571 pmdomain: rockchip: propagate subdomain add errors
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shawn Lin <[email protected]>
[ Upstream commit 4c0d69d677cf5b0065ebbb3ceb8ba66fddbec630 ]
rockchip_pm_add_subdomain() ignored the return value of its recursive call, so a failure deeper in the hierarchy was silently dropped and probe still succeeded with an incomplete domain tree.
--- drivers/soc/rockchip/pm_domains.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/soc/rockchip/pm_domains.c +3 -1
@@ -629,7 +629,9 @@ static int rockchip_pm_add_subdomain(struct rockchip_pmu *pmu, parent_domain->name, child_domain->name); } -rockchip_pm_add_subdomain (pmu, np); + error =rockchip_pm_add_subdomain (pmu, np); +if (error) + goto err_out; }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 443/571 optee: register TEE devices only once fully initialized
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shao-Fu Chen <[email protected]>
[ Upstream commit c108feca0a096f8db25d1b69130035025e9e936d ]
optee_probe() called tee_device_register() on both the client and the supplicant device before the rest of struct optee had been initialized.
tee_device_register() calls cdev_device_add(), which does two things at
once: it creates /dev/tee0 and /dev/teepriv0, and it links the device into the tee class so that class_find_device() can find it. From that moment on the device is reachable both from user space via tee_open() and from kernel space via tee_client_open_context(). The only gate in teedev_open() is tee_device_get(), which merely checks that teedev->desc is non-NULL, which was already set by tee_device_alloc(). Therefore, there is effectively no gate at all.
A context opened in that window can run against a struct optee where
- optee->call_queue.mutex is not initialized by optee_cq_init()
- optee->supp mutex and completions is not initialized by optee_supp_init()
- optee->rpmb_dev_mutex is not initialized yet,
- the message argument cache is not initialized by optee_shm_arg_cache_init()
- optee->ctx is still NULL
Any open session or invoke during this window takes uninitialized mutexes and dereferences a NULL pointer.
Fix it by moving both tee_device_register() calls down to the point where all of struct optee is set up.
--- drivers/tee/optee/core.c | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-)
drivers/tee/optee/core.c +14 -12
@@ -707,14 +707,6 @@ static int optee_probe(struct platform_device *pdev) } optee->supp_teedev = teedev; - rc =tee_device_register (optee->teedev); -if (rc) - goto err; - - rc =tee_device_register (optee->supp_teedev); -if (rc) - goto err; -mutex_init (&optee->call_queue.mutex);INIT_LIST_HEAD (&optee->call_queue.waiters);optee_wait_queue_init (&optee->wait_queue);
@@ -744,14 +736,24 @@ static int optee_probe(struct platform_device *pdev)platform_set_drvdata (pdev, optee); + rc =tee_device_register (optee->teedev); +if (rc) + goto err_remove; + + rc =tee_device_register (optee->supp_teedev); +if (rc) + goto err_remove; + rc =optee_enumerate_devices (PTA_CMD_GET_DEVICES ); -if (rc) { -optee_remove (pdev); -return rc; - } +if (rc) + goto err_remove;pr_info ("initialized driver\n" );return 0 ; + +err_remove: +optee_remove (pdev); +return rc; err:if (optee) {/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 444/571 scsi: ch: Do not keep references to data transfer element devices
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ahmed Abdelhaleem Ahmed <[email protected]>
[ Upstream commit 27c0f718d3b3c99e6d315308e95d987d0382a8a8 ]
ch_readconfig() looks up the scsi_device of every data transfer element whose SCSI id the changer reports in READ ELEMENT STATUS, and stores it in ch->dt[]. scsi_device_lookup() takes a reference, and nothing ever drops
it: ch_destroy() frees the array with kfree(). ch->dt[] is read nowhere else - it only supplies the vendor, model and revision printed in the same loop.
Once such a drive is removed, its scsi_device can never be released. It stays on the host's device list at its address, so a new device there is refused by anything that walks the list - target_core_pscsi reports "scsi_device_get() failed for H:C:T:L" - and the low-level driver's module can no longer be unloaded. Only a reboot recovers.
It shows with any changer that reports its drives' ids; with the mhvtl virtual library (IBM 3573-TL personality), each create and remove of a library with four drives leaves four references behind, counted by the module's use count in lsmod. With ch not bound the count is unchanged, and with this patch applied it is unchanged too.
Drop the reference as soon as the name has been printed, and remove the now unused dt[] array. That also removes the array leaked when ch_probe() fails after ch_readconfig().
The same leak was reported with an RFC patch in 2022, which was not merged.
--- drivers/scsi/ch.c | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-)
drivers/scsi/ch.c +9 -21
@@ -110,7 +110,6 @@ typedef struct {int minor;char name[8 ];struct scsi_device *device; -struct scsi_device **dt;/* ptrs to data transfer elements */ u_int firsts[CH_TYPES ];u_int counts[CH_TYPES ];u_int unit_attention;
@@ -357,16 +356,10 @@ ch_readconfig(scsi_changer *ch) vendor_labels[i]); } -/* look up the devices of the data transfer elements */ - ch->dt =kcalloc (ch->counts[CHET_DT ],sizeof (*ch->dt), -GFP_KERNEL ); - -if (!ch->dt) { -kfree (buffer); -return -ENOMEM ; - } - +/* report the devices of the data transfer elements */ for (elem =0 ; elem < ch->counts[CHET_DT ]; elem++) { +struct scsi_device *sdev; + id =-1 ; lun =0 ;if (elem <CH_DT_MAX &&-1 != dt_id[elem]) {
@@ -382,10 +375,8 @@ ch_readconfig(scsi_changer *ch)VPRINTK (KERN_INFO ,"dt 0x%x: " ,elem+ch->firsts[CHET_DT ]);if (data[6 ] &0x80 ) {VPRINTK (KERN_CONT ,"not this SCSI bus\n" ); - ch->dt[elem] =NULL ; }else if (0 == (data[6 ] &0x30 )) {VPRINTK (KERN_CONT ,"ID/LUN unknown\n" ); - ch->dt[elem] =NULL ; }else { id = ch->device->id; lun =0 ;
@@ -395,18 +386,16 @@ ch_readconfig(scsi_changer *ch) }if (-1 != id) {VPRINTK (KERN_CONT ,"ID %i, LUN %i, " ,id,lun); - ch->dt[elem] = -scsi_device_lookup (ch->device->host, - ch->device->channel, - id,lun); -if (!ch->dt[elem]) { + sdev =scsi_device_lookup (ch->device->host, + ch->device->channel, + id, lun); +if (!sdev) {/* should not happen */ VPRINTK (KERN_CONT ,"Huh? device not found!\n" ); }else {VPRINTK (KERN_CONT ,"name: %8.8s %16.16s %4.4s\n" , - ch->dt[elem]->vendor, - ch->dt[elem]->model, - ch->dt[elem]->rev); + sdev->vendor, sdev->model, sdev->rev); +scsi_device_put (sdev); } } }
@@ -570,7 +559,6 @@ static void ch_destroy(struct kref *ref)scsi_changer *ch =container_of (ref, scsi_changer, ref); ch->device =NULL ; -kfree (ch->dt);kfree (ch); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 445/571 drm/amdgpu: copy debugfs register data outside the GRBM/SRBM locks
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikhail Gavrilov <[email protected]>
[ Upstream commit 16c64495859f13f75602f439588883f2a4a4d6a6 ]
Reading or writing a register through the amdgpu_regs2 debugfs file with GRBM bank selection, which umr does for every banked access (a single "umr -b x x x -r <reg>" is enough, as is the wave dump with "-O halt_waves"), makes lockdep report a circular locking dependency, after which lockdep stays off until reboot:
WARNING: possible circular locking dependency detected
umr/63306 is trying to acquire lock:
ffff8882cf4b8350 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault+0x9b/0x140
but task is already holding lock:
ffff8881aec010d0 (&amdgpu_grbm_lock_key){+.+.}-{4:4}, at: amdgpu_debugfs_regs2_op.isra.0+0x20d/0xd00 [amdgpu]
...
Chain exists of:
&mm->mmap_lock --> &amdgpu_srbm_lock_key --> &amdgpu_grbm_lock_key
...
__might_fault+0xc5/0x140
amdgpu_debugfs_regs2_op.isra.0+0x441/0xd00 [amdgpu]
full_proxy_write+0x10e/0x1d0
vfs_write+0x1d0/0xf50
ksys_write+0x116/0x250amdgpu_debugfs_regs2_op() and amdgpu_debugfs_process_reg_op() call get_user()/put_user() for every dword while holding grbm_idx_mutex or srbm_mutex, and pm.mutex if requested, so a fault there takes mmap_lock inside those locks. The lock hierarchy in amdgpu_lockdep.c puts srbm_mutex and grbm_idx_mutex below notifier_lock, which amdgpu_cs_submit() takes with the BO reservations held, and dma_resv_lockdep() orders the reservations inside mmap_lock. So mmap_lock is outside grbm_idx_mutex and srbm_mutex, and these two debugfs paths nest it the other way round. The copies under the locks are as old as the bank selection in both files; commit 1d0f5838b126 ("drm/amdgpu: Add lockdep annotations for lock ordering validation") only made them visible to lockdep.
Copy the user buffer in before any of the locks is taken and the result out after all of them are dropped, as amdgpu_debugfs_wave_read(), amdgpu_debugfs_gpr_read() and amdgpu_debugfs_gprwave_read() already do. The buffer is sized by the count passed to read() or write(), so an access larger than PAGE_SIZE is now rejected with -EINVAL; umr reads and writes one register at a time. A fault on the user buffer of a write now fails with -EFAULT before any register is written, instead of after a partial write.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c | 39 ++++++++++++--------- 1 file changed, 23 insertions(+), 16 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c +23 -16
@@ -73,6 +73,7 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f,int r;bool pm_pg_lock, use_bank, use_ring;unsigned instance_bank, sh_bank, se_bank, me, pipe, queue, vmid; + u32 *data __free(kfree) = NULL; pm_pg_lock = use_bank = use_ring = false; instance_bank = sh_bank = se_bank = me = pipe = queue = vmid =0 ;
@@ -110,6 +111,20 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f, *pos &= (1UL <<22 ) -1 ; +if (size >PAGE_SIZE ) +return -EINVAL ; + +/* +* Access the user buffer only while none of the locks below are held: +* a fault takes mmap_lock, and grbm_idx_mutex and srbm_mutex nest +* inside it. +*/ + data =kmalloc (size,GFP_KERNEL ); +if (!data) +return -ENOMEM ; +if (!read &©_from_user (data, buf, size)) +return -EFAULT ; + r =pm_runtime_get_sync (adev_to_drm (adev)->dev);if (r <0 ) {pm_runtime_put_autosuspend (adev_to_drm (adev)->dev);
@@ -142,28 +157,16 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f,mutex_lock (&adev->pm.mutex);while (size) { -uint32_t value; - -if (read) { - value =RREG32 (*pos >>2 ); - r =put_user (value, (uint32_t *)buf); - }else { - r =get_user (value, (uint32_t *)buf); -if (!r) -amdgpu_mm_wreg_mmio_rlc (adev, *pos >>2 , value); - } -if (r) { - result = r; - goto end; - } +if (read) + data[result >>2 ] =RREG32 (*pos >>2 ); +else +amdgpu_mm_wreg_mmio_rlc (adev, *pos >>2 , data[result >>2 ]); result +=4 ; - buf +=4 ; *pos +=4 ; size -=4 ; } -end:if (use_bank) {amdgpu_gfx_select_se_sh (adev,0xffffffff ,0xffffffff ,0xffffffff );mutex_unlock (&adev->grbm_idx_mutex);
@@ -179,6 +182,10 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f,pm_runtime_put_autosuspend (adev_to_drm (adev)->dev);amdgpu_virt_disable_access_debugfs (adev); + +if (read &©_to_user (buf, data, result)) +return -EFAULT ; +return result; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 446/571 drm/fb-helper: defer setup when fbdev_probe() fails, not just on -EAGAIN
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Ngoc Thang <[email protected]>
[ Upstream commit 755c94d178b7e972bb766199d34e4ba4f63a89eb ]
__drm_fb_helper_initial_config_and_unlock() calls drm_client_modeset_probe() first, which already fills in each mode_set->mode/num_connectors for every connected output, and only afterwards calls drm_fb_helper_single_fb_probe() to create fb_helper->fb and wire it into those mode_sets via drm_setup_crtcs_fb().
If drm_fb_helper_single_fb_probe() fails with anything other than -EAGAIN (e.g. dev->driver->fbdev_probe() itself fails), the function bails out before drm_setup_crtcs_fb() runs and before setting fb_helper->deferred_setup. The client is left with mode_sets that have a mode and connectors but mode_set->fb == NULL, and nothing marks this fb_helper as needing a retry.
__drm_fb_helper_restore_fbdev_mode_unlocked() only skips committing when fb_helper->deferred_setup is set, so a later .restore() call (drm_lastclose() on process exit, in this report) commits the stale mode_set through drm_client_modeset_commit() -> drm_client_modeset_commit_atomic() -> __drm_atomic_helper_set_config(), which hits WARN_ON(!set->fb).
Mark fb_helper->deferred_setup on any drm_fb_helper_single_fb_probe() failure, not just -EAGAIN, so restore keeps skipping the commit until a later hotplug event successfully re-probes and re-populates mode_set->fb. The real error code is still returned to the caller unchanged.
--- drivers/gpu/drm/drm_fb_helper.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/gpu/drm/drm_fb_helper.c +4 -4
@@ -1841,11 +1841,11 @@ __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper,drm_client_modeset_probe (&fb_helper->client, width, height); ret =drm_fb_helper_single_fb_probe (fb_helper, bpp_sel);if (ret <0 ) { -if (ret == -EAGAIN ) { - fb_helper->preferred_bpp = bpp_sel; - fb_helper->deferred_setup = true; + fb_helper->preferred_bpp = bpp_sel; +/* modesets are probed but fb_helper->fb isn't; defer restore too */ + fb_helper->deferred_setup = true; +if (ret == -EAGAIN ) ret =0 ; - }mutex_unlock (&fb_helper->lock);return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 447/571 drm/i915/gt: Unmask interrupts only when ACTIVE is true
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Krzysztof Karas <[email protected]>
[ Upstream commit 5346b1cec6afa4f9b4b49a9f84e3cfef95a3f7bb ]
There is a small race window between intel_rps_boost() reading a stale ACTIVE state and queuing rps->work, where ACTIVE may be changed via asynchronous calls triggered by wakeref drop. This means that rps_work() could be triggered after the GT has been parked, so unmasking RPS PM interrupts would happen without holding PM wakelock. This sequence of events may be observed during live_rc6_ctx_wa() selftest:
1) live_rc6_ctx_wa()
-> intel_engine_pm_put()
-> wakeref_put()
ASYNC1) wakeref_put() callback
-> __engine_park()
-> intel_gt_pm_put_async()
-> intel_gt_pm_put_async_untracked()
-> intel_wakeref_put_async()ASYNC2) wakeref_put_async() callback
-> __gt_park()
-> intel_rps_park()
-> intel_rps_clear_active() [clear ACTIVE]
WITH INTERRUPTS:
-> rps_disable_interrupts()
-> cancel_work_sync(rps->work)
-> rps_reset_interrupts() [rps->pm_iir = 0]
WITHOUT INTERRUPTS (TIMER mode):
-> rps_stop_timer()
-> cancel_work_sync(rps->work)2) live_rc6_ctx_wa()
-> intel_gt_wait_for_idle()
-> intel_gt_retire_requests_timeout()
-> dma_fence_wait_timeout()
-> ops->wait() [i915_fence_wait()]
-> i915_request_wait_timeout()
-> intel_rps_boost()
-> intel_rps_is_active() [check ACTIVE]
[OPEN RACE WINDOW]
-> queue_work(rps->work)
-> retire_requests()
-> i915_request_retire()
-> intel_rps_dec_waiters() [from 1 to 0]If ASYNC1 and ASYNC2 would execute during [OPEN RACE WINDOW], then:
3) rps_work() executes from the workqueue and may satisfy "(!pm_iir && !client_boost)" test (in TIMER mode rps->pm_iir is zeroed by an earlier rps_work() call or never gets a new value after previous intel_rps_unpark() event), so it jumps to "out" label, bypassing intel_rps_is_active() guard and executes gen6_gt_pm_unmask_irq();
4) GT is parked and runtime PM wakelock is dropped, so only a raw reference in __gt_park() -> intel_display_power_put_async() remains for 100ms, then the MMIO write in gen6_gt_pm_unmask_irq() detects missing wakelock via assert_rpm_wakelock_held() and emits "RPM wakelock ref not held during HW access" tainting kernel.
Commit 3e7abf814193 ("drm/i915: Extract GT render power state management") dropped the "if (rps->interrupts_enabled)" guard that gen6_pm_rps_work() had around this unmask in i915_irq.c. INTEL_RPS_ACTIVE brackets the same window, since it is set in intel_rps_unpark() before rps_enable_interrupts() and rps_start_timer() and cleared in intel_rps_park() before rps_stop_timer() and rps_disable_interrupts().
Skip unmasking when RPS is no longer active (reaching unmask operation is independent of INTERRUPT mode). This does not prevent RPS operation from resuming on the next unpark. In interrupt mode, intel_rps_unpark() calls rps_enable_interrupts(), which enables and unmasks the PM interrupts. In timer mode, it calls rps_start_timer(), restarting periodic engine-busyness evaluation. The timer generates software RPS events and queues rps_work() directly, independently of PM interrupt delivery. Neither mode requires the late worker to unmask interrupts while the GT is parked
--- drivers/gpu/drm/i915/gt/intel_rps.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/drm/i915/gt/intel_rps.c +2 -1
@@ -1752,7 +1752,8 @@ static void rps_work(struct work_struct *work) out:spin_lock_irq (>->irq_lock); -gen6_gt_pm_unmask_irq (gt, rps->pm_events); +if (intel_rps_is_active (rps)) +gen6_gt_pm_unmask_irq (gt, rps->pm_events);spin_unlock_irq (>->irq_lock); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 448/571 namespace: unhash a dentry before detaching the mounts on it
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 528b383dc35d1e5caf64ddf5d35f983ae543b0d0 ]
unlink(), rmdir() and rename() remove the entry from the filesystem, call detach_mounts() on the entry with the inode locked and then call d_delete() once the inode is unlocked.
The thing is that between detach_mounts() and d_delete() the dentry is still hashed and positive. But after detach_mounts() nothing covers the dentry anymore. A lookup that finds this dentry in the dcache can uncover what the mounts hid.
That's a problem when unlinking files or directories that are mountpoints in other mount namespaces. Everybody who had the underlying entry covered can race the detach_mount() call until d_delete() has run.
The race window isn't all that small. It encompasses namespace_unlock() with a full synchronize_rcu_expedited() grace period and the inode_unlock() of the entry.
In my experiments three walkers that kept trying read an overmounted file in 11938 of the 16140 unlinks that removed its mountpoint from a bind mount of the filesystem within a minute.
Fun fact, d_invalidate() has the same ordering problem but gets it right. It unhashes the dentry first and detaches the mounts afterwards. Let's do the same in __detach_mounts():
- A lookup that hasn't found the dentry yet misses it in the dcache and waits for the directory lock that the caller holds until the name is gone for good.
- A lockless lookup that found it already fails the mount_lock check while the dentry still counts as a mountpoint and the d_seq check once it doesn't, and retries.
This fixes the lockless path. We still need to fix the reference count lookup in a follow-up patch.
So d_drop() the dentry. The dentry stays positive and held but can't be found anymore. Then proceed with the detach and unlink.
Reproducer:
The reads were counted with the program below, three walkers for 60 s in a VM with 4 CPUs. The race window is stretched with the debug patch pasted here. fs.detach_race_walk_us sleeps in lookup_fast() once it found a mountpoint dentry and before its mounts are crossed. fs.detach_race_unlink_us sleeps in vfs_unlink() between detach_mounts() and d_delete().
// SPDX-License-Identifier: GPL-2.0 /* * unlink_covered: unlink a file that is a mountpoint in a detached copy of * its mount, against lookups that open it through that copy. * * A is a tmpfs with the file f1 (content SECRET_F) and the plain file * MARK_A. A' is an open_tree(OPEN_TREE_CLONE) copy of A with MARK_A bound * on A'/f1, held through an O_PATH fd on its root once the tree fd is * closed. Walkers open f1 through that fd while the driver unlinks A/f1, * where nothing is mounted on it. A walker may read MARK_A or get ENOENT. * A read of SECRET_F is a hit: the name was found after its mount was * gone. The lockless walks use openat2(RESOLVE_CACHED). * * usage: unlink_covered [-t seconds] [-w walkers] */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <stdatomic.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/syscall.h> #include <linux/openat2.h> #ifndef __NR_open_tree #define __NR_open_tree 428 #endif #ifndef __NR_move_mount #define __NR_move_mount 429 #endif #ifndef __NR_openat2 #define __NR_openat2 437 #endif #ifndef OPEN_TREE_CLONE #define OPEN_TREE_CLONE 1 #endif #ifndef OPEN_TREE_CLOEXEC #define OPEN_TREE_CLOEXEC O_CLOEXEC #endif #ifndef MOVE_MOUNT_F_EMPTY_PATH #define MOVE_MOUNT_F_EMPTY_PATH 0x00000004 #endif #define WORK "/tmp/uc" #define ADIR WORK "/A"
static int duration = 60, nwalkers = 3;
static atomic_int stop, writer_waiting;
static pthread_rwlock_t cur_lock = PTHREAD_RWLOCK_INITIALIZER;
static int cur_fd = -1; /* the root of A', -1 while there is none */
static atomic_long n_unlink, n_walk, n_mark, n_enoent, n_other, n_secret,
n_secret_cached;
static void die(const char *what)
{
fprintf(stderr, "FATAL %s: %s\n", what, strerror(errno));
exit(2);
} static void put_file(int dfd, const char *name, const char *content) {
int fd = openat(dfd, name, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
0644);
if (fd < 0 || write(fd, content, strlen(content)) < 0)
die(name);
close(fd);
}
/* "plain/../" @n times, then f1: a longer walk that checks nothing on its way */
static char *longpath(int n)
{
char *p = malloc(n * 9 + 3), *q = p;
for (int i = 0; i < n; i++, q += 9)
memcpy(q, "plain/../", 9);
strcpy(q, "f1");
return p;
}
static void try_read(int dfd, const char *path, int cached)
{
struct open_how how = { .flags = O_RDONLY | O_CLOEXEC,
.resolve = RESOLVE_CACHED };
char buf[32] = "";
long n;
int fd;
if (cached)
fd = syscall(__NR_openat2, dfd, path, &how, sizeof(how));
else
fd = openat(dfd, path, O_RDONLY | O_CLOEXEC);
atomic_fetch_add(&n_walk, 1);
if (fd < 0) {
if (errno == ENOENT)
atomic_fetch_add(&n_enoent, 1);
else if (!cached || errno != EAGAIN)
atomic_fetch_add(&n_other, 1);
return;
}
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n >= 6 && !strncmp(buf, "SECRET", 6)) {
if (cached)
atomic_fetch_add(&n_secret_cached, 1);
if (!atomic_fetch_add(&n_secret, 1))
printf("HIT: read \"%s\" through %s (%s walk)\n", buf,
path, cached ? "lockless" : "any");
} else {
atomic_fetch_add(&n_mark, 1);
}
}
static void *walker(void *arg)
{
unsigned int r = (long)arg * 2654435761u;
while (!atomic_load(&stop)) {
char *p_long, *p_short;
int dfd;
while (atomic_load(&writer_waiting) && !atomic_load(&stop))
usleep(20);
pthread_rwlock_rdlock(&cur_lock);
dfd = cur_fd;
if (dfd < 0) {
pthread_rwlock_unlock(&cur_lock);
usleep(100);
continue;
}
r = r * 1103515245u + 12345u;
p_long = longpath(1 + (r >> 8) % 400);
p_short = longpath(0);
try_read(dfd, p_long, 0);
try_read(dfd, p_short, 0);
try_read(dfd, p_long, 1);
pthread_rwlock_unlock(&cur_lock);
free(p_long);
free(p_short);
}
return NULL;
} /* hand the walkers a new A' (or none), close the old one */ static void publish(int fd)
{
int old;
atomic_fetch_add(&writer_waiting, 1);
pthread_rwlock_wrlock(&cur_lock);
old = cur_fd;
cur_fd = fd;
pthread_rwlock_unlock(&cur_lock);
atomic_fetch_sub(&writer_waiting, 1);
if (old >= 0)
close(old);
}
static void *driver(void *arg __attribute__((unused)))
{
int a;
if (mkdir(ADIR, 0755) && errno != EEXIST)
die("mkdir A");
if (mount("A", ADIR, "tmpfs", 0, "size=4M"))
die("mount A");
a = open(ADIR, O_PATH | O_DIRECTORY | O_CLOEXEC);
if (a < 0 || mkdirat(a, "plain", 0755))
die("A/plain");
put_file(a, "MARK_A", "MARK_A");
while (!atomic_load(&stop)) {
int t, m, fd_a;
put_file(a, "f1", "SECRET_F");
t = syscall(__NR_open_tree, a, "",
OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC | AT_EMPTY_PATH);
if (t < 0)
die("open_tree A");
m = syscall(__NR_open_tree, a, "MARK_A",
OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
if (m < 0)
die("open_tree MARK_A");
if (syscall(__NR_move_mount, m, "", t, "f1",
MOVE_MOUNT_F_EMPTY_PATH))
die("move_mount");
close(m);
fd_a = openat(t, ".", O_PATH | O_DIRECTORY | O_CLOEXEC);
if (fd_a < 0)
die("open A'");
publish(fd_a);
usleep(200 + rand() % 1000);
close(t); /* A' is unmounted, fd_a holds it */
usleep(200 + rand() % 1000);
if (unlinkat(a, "f1", 0)) /* through A, a plain file there */
die("unlink f1");
atomic_fetch_add(&n_unlink, 1);
usleep(rand() % 300);
publish(-1);
}
close(a);
umount2(ADIR, MNT_DETACH);
return NULL;
}
int main(int argc, char **argv)
{
pthread_t d, *w;
int c, i;
setvbuf(stdout, NULL, _IOLBF, 0);
while ((c = getopt(argc, argv, "t:w:")) != -1) {
switch (c) {
case 't':
duration = atoi(optarg);
break;
case 'w':
nwalkers = atoi(optarg);
break;
default:
fprintf(stderr, "usage: unlink_covered [-t seconds] [-w walkers]\n");
return 2;
}
}
if (unshare(CLONE_NEWNS) ||
mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL))
die("unshare");
if (mkdir(WORK, 0755) && errno != EEXIST)
die("mkdir");
w = calloc(nwalkers, sizeof(*w));
for (i = 0; i < nwalkers; i++)
if (pthread_create(&w[i], NULL, walker, (void *)(long)i))
die("pthread_create");
if (pthread_create(&d, NULL, driver, NULL))
die("pthread_create");
sleep(duration);
atomic_store(&stop, 1);
pthread_join(d, NULL);
for (i = 0; i < nwalkers; i++)
pthread_join(w[i], NULL);
printf("unlink_covered: %d s, %d walkers: unlinks %ld walks %ld mark %ld enoent %ld other %ld SECRET %ld (lockless %ld)\n",
duration, nwalkers, atomic_load(&n_unlink), atomic_load(&n_walk),
atomic_load(&n_mark), atomic_load(&n_enoent),
atomic_load(&n_other), atomic_load(&n_secret),
atomic_load(&n_secret_cached));
return atomic_load(&n_secret) ? 1 : 0;
}# diff --git a/fs/namei.c b/fs/namei.c
# --- a/fs/namei.c
# +++ b/fs/namei.c
# @@ -35,6 +35,7 @@
# #include <linux/fcntl.h>
# #include <linux/device_cgroup.h>
# #include <linux/fs_struct.h>
# +#include <linux/delay.h>
# #include <linux/posix_acl.h>
# #include <linux/hash.h>
# #include <linux/bitops.h>
# @@ -1205,9 +1206,26 @@ static int sysctl_protected_symlinks __read_mostly;
# static int sysctl_protected_hardlinks __read_mostly;
# static int sysctl_protected_fifos __read_mostly;
# static int sysctl_protected_regular __read_mostly;
# +/* debug: widen the two windows of the detach_mounts() race */
# +static int sysctl_detach_race_walk_us __read_mostly;
# +static int sysctl_detach_race_unlink_us __read_mostly;
#
# #ifdef CONFIG_SYSCTL
# static const struct ctl_table namei_sysctls[] = {
# + {
# + .procname = "detach_race_walk_us",
# + .data = &sysctl_detach_race_walk_us,
# + .maxlen = sizeof(int),
# + .mode = 0644,
# + .proc_handler = proc_dointvec,
# + },
# + {
# + .procname = "detach_race_unlink_us",
# + .data = &sysctl_detach_race_unlink_us,
# + .maxlen = sizeof(int),
# + .mode = 0644,
# + .proc_handler = proc_dointvec,
# + },
# {
# .procname = "protected_symlinks",
# .data = &sysctl_protected_symlinks,
# @@ -1878,6 +1896,10 @@ static struct dentry *lookup_fast(struct nameidata *nd)
# dentry = __d_lookup(parent, &nd->last);
# if (unlikely(!dentry))
# return NULL;
# + /* debug: between finding a mountpoint and crossing its mounts */
# + if (unlikely(sysctl_detach_race_walk_us) && d_mountpoint(dentry))
# + usleep_range(sysctl_detach_race_walk_us,
# + sysctl_detach_race_walk_us + 10);
# status = d_revalidate(nd->inode, &nd->last, dentry, nd->flags);
# }
# if (unlikely(status <= 0)) {
# @@ -5693,6 +5715,10 @@ int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir,
# if (!error) {
# dont_mount(dentry);
# detach_mounts(dentry);
# + /* debug: the mounts are gone, d_delete() is still to come */
# + if (unlikely(sysctl_detach_race_unlink_us))
# + usleep_range(sysctl_detach_race_unlink_us,
# + sysctl_detach_race_unlink_us + 10);
# }
# }
# }--- fs/namespace.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/namespace.c +5 -0
@@ -1694,6 +1694,9 @@ static int do_umount(struct mount *mnt, int flags)* detach_mounts allows lazily unmounting those mounts instead of * leaking them. * +* The dentry is unhashed before the mounts go so that no lookup finds +* what they covered. The caller removes it for good afterwards. +* * The caller may hold dentry->d_inode->i_mutex. */ void __detach_mounts (struct dentry *dentry)
@@ -1707,6 +1710,8 @@ void __detach_mounts(struct dentry *dentry)if (!mp) goto out_unlock; +/* the name goes first, what covered it goes second */ +d_drop (dentry); event++;while (!hlist_empty (&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 449/571 namespace: dont copy an unmounted mount tree
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 8bacbf6be959973b28b691713a872c12eae69eec ]
may_copy_tree() accepts a mount whose root is an nsfs or pidfs file before it checks whether that mount is mounted. This exception exists for nsfs and pidfs mounts. They are part of no mount namespace so neither check_mnt() nor is_mounted() would let them through and bind-mounting a nsfsfd or a pidfd wouldn't work.
Problem is that exception also admits a bind mount of such a file when it was lazily unmounted and is only kept alive by a file descriptor:
mount --bind /proc/self/ns/net /tmp/x exec 3< /tmp/x umount -l /tmp/x mount --rbind /proc/self/fd/3 /tmp/y
With MS_REC or AT_RECURSIVE copy_tree() doesn't stop at the unmounted mount. It copies every mount that stayed attached to it as well. So if you have a bunch of overmounts over the nsfsfd or the pidfd the whole unmounted stack is copied. That's a bug.
So refuse to walk an unmounted tree. Copying its root alone stays possible. So a bind mount of a namespace that is gone can still be recreated from a file descriptor on the old one. The file descriptor pins that mount and its root and __has_locked_children() only reads the direct children which don't leave the parent's list without namespace_sem. The internal mounts carry MNT_NS_INTERNAL instead of NULL and are still walked. Copying an unmounted tree recursively fails with EINVAL.
--- fs/namespace.c | 3 +++ 1 file changed, 3 insertions(+)
fs/namespace.c +3 -0
@@ -2391,6 +2391,9 @@ static struct mount *__do_loopback(struct path *old_path, int recurse)if (!check_mnt (old) && old_path->dentry->d_op != &ns_dentry_operations)return mnt; +if (recurse && !old->mnt_ns) +return ERR_PTR (-EINVAL ); +if (!recurse &&has_locked_children (old, old_path->dentry))return mnt;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 450/571 namespace: check the target before walking it in do_mount_setattr()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 08f4288a37ef4b3d19b4a9599ec3048219cac828 ]
When mount_setattr() changes the propagation type to MS_SHARED do_mount_setattr() takes namespace_sem and calls invent_group_ids() which walks the whole target tree with next_mnt() and allocates a peer group id for every mount that doesn't have one.
Whether the caller may touch the target at all is only checked afterwards under mount_lock. If it may not, cleanup_group_ids() walks the tree a second time on the way out to free the ids again.
A detached tree that a file descriptor keeps alive, a mount in another mount namespace or a mount below the root of an anonymous mount namespace does a bunch of allocation work that is completely useless because it will fail and revert right after.
Do the right thing and check the target right after taking namespace_sem instead. A mount leaves its namespace only under namespace_sem so the mount stays stable. The check under mount_lock stays for the case where no propagation change is requested and namespace_sem isn't taken. Callers get the same EINVAL as before.
--- fs/namespace.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/namespace.c +8 -0
@@ -4074,6 +4074,7 @@ static struct mount *mount_setattr_prepare(struct mount_kattr *kattr, {struct mount *m = mnt, *last =NULL ; +/* Checked under namespace_sem already if the propagation changes. */ if (!is_mounted (&m->mnt)) { *err = -EINVAL ; goto out;
@@ -4183,6 +4184,13 @@ static int do_mount_setattr(struct path *path, struct mount_kattr *kattr)* propagation. */ namespace_lock (); +/* invent_group_ids() walks the tree, only walk a mounted one */ +if (!is_mounted (&mnt->mnt) || + !(mnt_has_parent (mnt) ?check_mnt (mnt) : +is_anon_ns (mnt->mnt_ns))) { +namespace_unlock (); +return -EINVAL ; + }if (kattr->propagation ==MS_SHARED ) { err =invent_group_ids (mnt, kattr->recurse);if (err) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 451/571 fcntl: refuse F_SET_RW_HINT on an immutable inode
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit b0d1022b9bdb1e98aa7fb3244fdd50a58c61766c ]
An immutable inode is never written to so write hints are pointless. Refuse the hint on an immutable inode the way setattr(), fallocate() and etxattr() refuse their changes.
--- fs/fcntl.c | 3 +++ 1 file changed, 3 insertions(+)
fs/fcntl.c +3 -0
@@ -307,6 +307,9 @@ static long fcntl_rw_hint(struct file *file, unsigned int cmd,return -EFAULT ;return 0 ;case F_SET_RW_HINT : +/* nothing is ever written to it */ +if (IS_IMMUTABLE (inode)) +return -EPERM ;if (copy_from_user (&h, argp,sizeof (h)))return -EFAULT ; hint = (enum rw_hint ) h;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 452/571 namespace: handle mount locking for automounts correctly
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 33aadc7c72055fca93cb5a3691d836ebf8b31c9b ]
If mounts are propagated across user namespaces, attach_recursive_mnt() locks every copy of the source mount to protect overmounts from vanishing and revealing the underlying files or directories.
The user namespace is taken from the caller's mount namespaces since this is where the mounts end up. Except, that's not always true. Automounts may legitimately get popped in by tasks located in a different mount and user namespace during path lookup.
Then check doesn't make sense at that point. The copy in the namespace of the parent - which may be the host's - is now locked and the host cannot change the flags of its own mounts anymore.
Here's the reproducer:
- host has debugfs mounted nosuid,nodev,noexec and shared
- tracefs automount below it is not yet active
- hand a child process a directory descriptor on that mount
- child process enters auser and mount namespace
- child process' namespace now holds a locked copy of the host's debugfs mount that receives propagation from it
- child process stats "tracing/." through the descriptor
- lookup runs on the host's mount so the automount lands below the host's mount
- propagation puts a copy below the child's copy
- both try to clear the flags on the mount they got, with a bind remount:
host, on its own automount: MS_REMOUNT|MS_BIND = EPERM
child, on the copy in its namespace: MS_REMOUNT|MS_BIND = 0So the lock landed on the host's mount instead of the child's copy. Congrats. So we need to compare with the owner of the namespace the mount actually gets mounted on. For all regular cases that is the caller's mount namespace and so nothing changes.
Detached trees in anonymous mount namespaces by be handed over via SCM_RIGHTS or inherited in other ways on purpose so the attaching task's mount namespace is authoritative, not the creator of the detached tree.
--- fs/namespace.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-)
fs/namespace.c +17 -1
@@ -2175,14 +2175,30 @@ static int attach_recursive_mnt(struct mount *source_mnt,struct mountpoint *dest_mp, bool moving) { -struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;HLIST_HEAD (tree_list );struct mnt_namespace *ns = dest_mnt->mnt_ns; +struct user_namespace *user_ns = ns->user_ns;struct mountpoint *smp;struct mount *child, *p;struct hlist_node *n;int err; +/* +* A caller in an unprivileged mount namespaces may trigger an +* automount and propagate locked mounts into privileged mount +* namespaces. Take ownership from the target mount namespace. +* It's equivalent for everything but the automount case. +* +* Detached trees in anonymous mount namespaces by be handed +* over via SCM_RIGHTS or inherited in other ways on purpose +* the attaching task's mount namespace is authoritative, not +* the creator of the detached tree. +*/ +if (is_anon_ns (ns)) + user_ns = current->nsproxy->mnt_ns->user_ns; +else + user_ns = ns->user_ns; +/* Preallocate a mountpoint in case the new mounts need * to be tucked under other mounts. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 453/571 netfilter: nf_tables: fix crash when nf_trace is enabled
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Westphal <[email protected]>
[ Upstream commit 399a14ec7993d605740de7b2cd5c0ce8407d12ed ]
do not access info->pkt when info->trace is not 1. nft_traceinfo is not initialized, except when tracing is enabled.
The 'nft_trace_enabled' static key cannot be used for this, we must always check info->trace first.
Pass nft_pktinfo directly to avoid this.
--- net/netfilter/nf_tables_core.c | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-)
net/netfilter/nf_tables_core.c +10 -11
@@ -34,25 +34,23 @@ static noinline void __nft_trace_packet(struct nft_traceinfo *info,nft_trace_notify (info); } -static inline void nft_trace_packet (struct nft_traceinfo *info, +static inline void nft_trace_packet (const struct nft_pktinfo *pkt, +struct nft_traceinfo *info,const struct nft_chain *chain,const struct nft_rule *rule,enum nft_trace_types type) {if (static_branch_unlikely (&nft_trace_enabled)) { -const struct nft_pktinfo *pkt = info->pkt; - info->nf_trace = pkt->skb->nf_trace; info->rule = rule;__nft_trace_packet (info, chain, type); } } -static inline void nft_trace_copy_nftrace (struct nft_traceinfo *info) +static inline void nft_trace_copy_nftrace (const struct nft_pktinfo *pkt, +struct nft_traceinfo *info) {if (static_branch_unlikely (&nft_trace_enabled)) { -const struct nft_pktinfo *pkt = info->pkt; -if (info->trace) info->nf_trace = pkt->skb->nf_trace; }
@@ -96,7 +94,6 @@ static noinline void __nft_trace_verdict(struct nft_traceinfo *info,const struct nft_chain *chain, const struct nft_regs *regs) { - const struct nft_pktinfo *pkt = info->pkt; enum nft_trace_types type;switch (regs->verdict.code) {
@@ -110,7 +107,9 @@ static noinline void __nft_trace_verdict(struct nft_traceinfo *info,break ;default : type =NFT_TRACETYPE_RULE ; - info->nf_trace = pkt->skb->nf_trace; + +if (info->trace) + info->nf_trace = info->pkt->skb->nf_trace;break ; }
@@ -261,10 +260,10 @@ nft_do_chain(struct nft_pktinfo *pkt, void *priv)switch (regs.verdict.code) {case NFT_BREAK : regs.verdict.code =NFT_CONTINUE ; -nft_trace_copy_nftrace (&info); +nft_trace_copy_nftrace (pkt, &info);continue ;case NFT_CONTINUE : -nft_trace_packet (&info, chain, rule, +nft_trace_packet (pkt, &info, chain, rule,NFT_TRACETYPE_RULE );continue ; }
@@ -306,7 +305,7 @@ nft_do_chain(struct nft_pktinfo *pkt, void *priv) goto next_rule; } -nft_trace_packet (&info, basechain,NULL ,NFT_TRACETYPE_POLICY ); +nft_trace_packet (pkt, &info, basechain,NULL ,NFT_TRACETYPE_POLICY );if (static_branch_unlikely (&nft_counters_enabled))nft_update_chain_stats (basechain, pkt);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 454/571 tty: finish kernel-doc of tty_struct members
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Slaby <[email protected]>
[ Upstream commit 18e6c0751cf9ae0631a2623e31af2bf504f72c30 ]
There are already pieces of kernel-doc documentation for struct tty_struct in tty.h. Finish the documentation for the members which were undocumented yet.
It also includes tuning the already existing pieces like flow and ctrl, especially adding highlights to them.
Stable-dep-of: 5dad87615c98 ("tty: add break_wait kernel-doc")
--- include/linux/tty.h | 79 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 64 insertions(+), 15 deletions(-)
include/linux/tty.h +64 -15
@@ -122,33 +122,84 @@ struct tty_operations;/** * struct tty_struct - state associated with a tty while open * -* @flow.lock: lock for flow members -* @flow.stopped: tty stopped/started by tty_stop/tty_start -* @flow.tco_stopped: tty stopped/started by TCOOFF/TCOON ioctls (it has -* precedense over @flow.stopped) +* @magic: magic value set early in @alloc_tty_struct to %TTY_MAGIC, for +* debugging purposes +* @kref: reference counting by tty_kref_get() and tty_kref_put(), reaching zero +* frees the structure +* @dev: class device or %NULL (e.g. ptys, serdev) +* @driver: &struct tty_driver operating this tty +* @ops: &struct tty_operations of @driver for this tty (open, close, etc.) +* @index: index of this tty (e.g. to construct @name like tty12) +* @ldisc_sem: protects line discipline changes (@ldisc) -- lock tty not pty +* @ldisc: the current line discipline for this tty (n_tty by default) +* @atomic_write_lock: protects against concurrent writers, i.e. locks +* @write_cnt, @write_buf and similar +* @legacy_mutex: leftover from history (BKL -> BTM -> @legacy_mutex), +* protecting several operations on this tty +* @throttle_mutex: protects against concurrent tty_throttle_safe() and +* tty_unthrottle_safe() (but not tty_unthrottle()) +* @termios_rwsem: protects @termios and @termios_locked +* @winsize_mutex: protects @winsize +* @termios: termios for the current tty, copied from/to @driver.termios +* @termios_locked: locked termios (by %TIOCGLCKTRMIOS and %TIOCSLCKTRMIOS +* ioctls) +* @name: name of the tty constructed by tty_line_name() (e.g. ttyS3) +* @flags: bitwise OR of %TTY_THROTTLED, %TTY_IO_ERROR, ... +* @count: count of open processes, reaching zero cancels all the work for +* this tty and drops a @kref too (but does not free this tty) +* @winsize: size of the terminal "window" (cf. @winsize_mutex) +* @flow: flow settings grouped together, see also @flow.unused +* @flow.lock: lock for @flow members +* @flow.stopped: tty stopped/started by stop_tty()/start_tty() +* @flow.tco_stopped: tty stopped/started by %TCOOFF/%TCOON ioctls (it has +* precedence over @flow.stopped) * @flow.unused: alignment for Alpha, so that no members other than @flow.* are * modified by the same 64b word store. The @flow's __aligned is * there for the very same reason. -* @ctrl.lock: lock for ctrl members +* @ctrl: control settings grouped together, see also @ctrl.unused +* @ctrl.lock: lock for @ctrl members * @ctrl.pgrp: process group of this tty (setpgrp(2)) * @ctrl.session: session of this tty (setsid(2)). Writes are protected by both -* @ctrl.lock and legacy mutex, readers must use at least one of +* @ctrl.lock and @legacy_mutex, readers must use at least one of * them. -* @ctrl.pktstatus: packet mode status (bitwise OR of TIOCPKT_* constants) +* @ctrl.pktstatus: packet mode status (bitwise OR of %TIOCPKT_ constants) * @ctrl.packet: packet mode enabled +* @ctrl.unused: alignment for Alpha, see @flow.unused for explanation +* @hw_stopped: not controlled by the tty layer, under @driver's control for CTS +* handling +* @receive_room: bytes permitted to feed to @ldisc without any being lost +* @flow_change: controls behavior of throttling, see tty_throttle_safe() and +* tty_unthrottle_safe() +* @link: link to another pty (master -> slave and vice versa) +* @fasync: state for %O_ASYNC (for %SIGIO); managed by fasync_helper() +* @write_wait: concurrent writers are waiting in this queue until they are +* allowed to write +* @read_wait: readers wait for data in this queue +* @hangup_work: normally a work to perform a hangup (do_tty_hangup()); while +* freeing the tty, (re)used to release_one_tty() +* @disc_data: pointer to @ldisc's private data (e.g. to &struct n_tty_data) +* @driver_data: pointer to @driver's private data (e.g. &struct uart_state) +* @files_lock: protects @tty_files list +* @tty_files: list of (re)openers of this tty (i.e. linked &struct +* tty_file_private) +* @closing: when set during close, n_tty processes only START & STOP chars +* @write_buf: temporary buffer used during tty_write() to copy user data to +* @write_cnt: count of bytes written in tty_write() to @write_buf +* @SAK_work: if the tty has a pending do_SAK, it is queued here +* @port: persistent storage for this device (i.e. &struct tty_port) * * All of the state associated with a tty while the tty is open. Persistent -* storage for tty devices is referenced here as @port in struct tty_port. +* storage for tty devices is referenced here as @port and is documented in +* &struct tty_port. */ struct tty_struct {int magic;struct kref kref; -struct device *dev;/* class device or NULL (e.g. ptys, serdev) */ +struct device *dev;struct tty_driver *driver;const struct tty_operations *ops;int index; -/* Protects ldisc changes: Lock tty not pty */ struct ld_semaphore ldisc_sem;struct tty_ldisc *ldisc;
@@ -157,12 +208,11 @@ struct tty_struct {struct mutex throttle_mutex;struct rw_semaphore termios_rwsem;struct mutex winsize_mutex; -/* Termios values are protected by the termios rwsem */ struct ktermios termios, termios_locked;char name[64 ];unsigned long flags;int count; -struct winsize winsize;/* winsize_mutex */ +struct winsize winsize;struct {spinlock_t lock;
@@ -181,7 +231,7 @@ struct tty_struct { }__aligned(sizeof(unsigned long)) ctrl;int hw_stopped; -unsigned int receive_room;/* Bytes free for queue */ +unsigned int receive_room;int flow_change;struct tty_struct *link;
@@ -192,7 +242,7 @@ struct tty_struct {struct work_struct hangup_work;void *disc_data;void *driver_data; -spinlock_t files_lock;/* protects tty_files list */ +spinlock_t files_lock;struct list_head tty_files;#define N_TTY_BUF_SIZE 4096
@@ -200,7 +250,6 @@ struct tty_struct {int closing;unsigned char *write_buf;int write_cnt; -/* If the tty has a pending do_SAK, queue it here - akpm */ struct work_struct SAK_work;struct tty_port *port; } __randomize_layout;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 455/571 tty: add break_wait kernel-doc
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
[ Upstream commit 5dad87615c9861cfa366ca984b52f581e861df20 ]
Add the missing kernel-doc description for the new break_wait field in struct tty_struct.
--- include/linux/tty.h | 1 + 1 file changed, 1 insertion(+)
include/linux/tty.h +1 -0
@@ -175,6 +175,7 @@ struct tty_operations;* @write_wait: concurrent writers are waiting in this queue until they are * allowed to write * @read_wait: readers wait for data in this queue +* @break_wait: wait queue for timed breaks * @hangup_work: normally a work to perform a hangup (do_tty_hangup()); while * freeing the tty, (re)used to release_one_tty() * @disc_data: pointer to @ldisc's private data (e.g. to &struct n_tty_data)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 456/571 xfrm: prevent policy_hthresh.work from racing with netns teardown
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tahera Fahimi <[email protected]>
An XFRM_MSG_NEWSPDINFO request can queue the per-net work item policy_hthresh.work onto the system workqueue. xfrm_hash_rebuild() retrieves the enclosing struct net from the work item, so the callback can dereference freed memory if it runs after net namespace teardown.
Mainline commit 29fe3a61bcdc ("xfrm: prevent policy_hthresh.work from racing with netns teardown") fixes this issue using disable_work_sync(). That API is not available in Linux 5.15, so the mainline change cannot be directly backported.
Provide the same guarantee with an XFRM-local work_disabled flag. Protect the flag and schedule_work() with the existing policy_hthresh seqlock so teardown can atomically stop new queueing attempts. Then use cancel_work_sync() to synchronize work that was queued before the flag was set. This ensures policy_hthresh.work cannot outlive its struct net.
--- include/net/netns/xfrm.h | 1 + net/xfrm/xfrm_policy.c | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-)
include/net/netns/xfrm.h +1 -0
@@ -23,6 +23,7 @@ struct xfrm_policy_hash {struct xfrm_policy_hthresh {struct work_struct work;seqlock_t lock; +bool work_disabled;u8 lbits4;u8 rbits4;u8 lbits6;
net/xfrm/xfrm_policy.c +18 -1
@@ -1378,7 +1378,10 @@ static void xfrm_hash_rebuild(struct work_struct *work)void xfrm_policy_hash_rebuild (struct net *net) { -schedule_work (&net->xfrm.policy_hthresh.work); +write_seqlock (&net->xfrm.policy_hthresh.lock); +if (!net->xfrm.policy_hthresh.work_disabled) +schedule_work (&net->xfrm.policy_hthresh.work); +write_sequnlock (&net->xfrm.policy_hthresh.lock); }EXPORT_SYMBOL (xfrm_policy_hash_rebuild);
@@ -4088,6 +4091,7 @@ static int __net_init xfrm_policy_init(struct net *net) net->xfrm.policy_hthresh.rbits6 =128 ;seqlock_init (&net->xfrm.policy_hthresh.lock); + net->xfrm.policy_hthresh.work_disabled = false;INIT_LIST_HEAD (&net->xfrm.policy_all);INIT_LIST_HEAD (&net->xfrm.inexact_bins);
@@ -4113,6 +4117,19 @@ static void xfrm_policy_fini(struct net *net)unsigned int sz;int dir; +/* Prevent new policy hash rebuilds before draining the work item. +* +* The upstream fix uses disable_work_sync(), which is unavailable +* in v5.15. Protecting work_disabled and schedule_work() with the +* same seqlock closes the check-to-queue race, while the subsequent +* cancel_work_sync() drains work that was queued or running before +* teardown disabled it. +*/ +write_seqlock (&net->xfrm.policy_hthresh.lock); + net->xfrm.policy_hthresh.work_disabled = true; +write_sequnlock (&net->xfrm.policy_hthresh.lock); +cancel_work_sync (&net->xfrm.policy_hthresh.work); +flush_work (&net->xfrm.policy_hash_work);#ifdef CONFIG_XFRM_SUB_POLICY xfrm_policy_flush (net,XFRM_POLICY_TYPE_SUB , false);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 457/571 xfs: log items should have a xlog pointer, not a mount
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit d86142dd7c4e10e50bdb3679b405d748214b2c28 ]
Log items belong to the log, not the xfs_mount. Convert the mount pointer in the log item to a xlog pointer in preparation for upcoming log centric changes to the log items.
Stable-dep-of: 7b5f775be14a ("xfs: fix unmount hang with unflushable inodes stuck in the AIL")
--- fs/xfs/xfs_bmap_item.c | 2 +- fs/xfs/xfs_buf_item.c | 5 +++-- fs/xfs/xfs_extfree_item.c | 2 +- fs/xfs/xfs_log.c | 2 +- fs/xfs/xfs_log_cil.c | 2 +- fs/xfs/xfs_refcount_item.c | 2 +- fs/xfs/xfs_rmap_item.c | 2 +- fs/xfs/xfs_trace.h | 4 ++-- fs/xfs/xfs_trans.c | 2 +- fs/xfs/xfs_trans.h | 3 ++- 10 files changed, 14 insertions(+), 12 deletions(-)
fs/xfs/xfs_bmap_item.c +1 -1
@@ -465,7 +465,7 @@ xfs_bui_item_recover(struct xfs_bui_log_item *buip =BUI_ITEM (lip);struct xfs_trans *tp;struct xfs_inode *ip =NULL ; -struct xfs_mount *mp = lip->li_mountp; +struct xfs_mount *mp = lip->li_log->l_mp;struct xfs_map_extent *bmap;struct xfs_bud_log_item *budp;xfs_filblks_t count;
fs/xfs/xfs_buf_item.c +3 -2
@@ -21,6 +21,7 @@#include "xfs_dquot.h" #include "xfs_trace.h" #include "xfs_log.h" +#include "xfs_log_priv.h" kmem_zone_t *xfs_buf_item_zone;
@@ -428,7 +429,7 @@ xfs_buf_item_format(* occurs during recovery. */ if (bip->bli_flags &XFS_BLI_INODE_BUF ) { -if (xfs_has_v3inodes (lip->li_mountp) || +if (xfs_has_v3inodes (lip->li_log->l_mp) || !((bip->bli_flags &XFS_BLI_INODE_ALLOC_BUF ) &&xfs_log_item_in_current_chkpt (lip))) bip->__bli_format.blf_flags |=XFS_BLF_INODE_BUF ;
@@ -616,7 +617,7 @@ xfs_buf_item_put(* that case, the bli is freed on buffer writeback completion. */ aborted =test_bit (XFS_LI_ABORTED , &lip->li_flags) || -xfs_is_shutdown (lip->li_mountp); +xlog_is_shutdown (lip->li_log); dirty = bip->bli_flags &XFS_BLI_DIRTY ;if (dirty && !aborted)return false;
fs/xfs/xfs_extfree_item.c +1 -1
@@ -597,7 +597,7 @@ xfs_efi_item_recover( struct list_head *capture_list) {struct xfs_efi_log_item *efip =EFI_ITEM (lip); -struct xfs_mount *mp = lip->li_mountp; +struct xfs_mount *mp = lip->li_log->l_mp;struct xfs_efd_log_item *efdp;struct xfs_trans *tp;struct xfs_extent *extp;
fs/xfs/xfs_log.c +1 -1
@@ -1072,7 +1072,7 @@ xfs_log_item_init(int type, const struct xfs_item_ops *ops) { - item->li_mountp = mp; + item->li_log = mp->m_log; item->li_ailp = mp->m_ail; item->li_type = type; item->li_ops = ops;
fs/xfs/xfs_log_cil.c +1 -1
@@ -1428,7 +1428,7 @@ boolxfs_log_item_in_current_chkpt ( struct xfs_log_item *lip) { -struct xfs_cil *cil = lip->li_mountp->m_log->l_cilp; +struct xfs_cil *cil = lip->li_log->l_cilp;if (list_empty (&lip->li_cil))return false;
fs/xfs/xfs_refcount_item.c +1 -1
@@ -459,7 +459,7 @@ xfs_cui_item_recover(struct xfs_cud_log_item *cudp;struct xfs_trans *tp;struct xfs_btree_cur *rcur =NULL ; -struct xfs_mount *mp = lip->li_mountp; +struct xfs_mount *mp = lip->li_log->l_mp;xfs_fsblock_t new_fsb;xfs_extlen_t new_len;unsigned int refc_type;
fs/xfs/xfs_rmap_item.c +1 -1
@@ -512,7 +512,7 @@ xfs_rui_item_recover(struct xfs_rud_log_item *rudp;struct xfs_trans *tp;struct xfs_btree_cur *rcur =NULL ; -struct xfs_mount *mp = lip->li_mountp; +struct xfs_mount *mp = lip->li_log->l_mp;enum xfs_rmap_intent_type type;xfs_exntst_t state;int i;
fs/xfs/xfs_trace.h +2 -2
@@ -1309,7 +1309,7 @@ DECLARE_EVENT_CLASS(xfs_log_item_class,__field (xfs_lsn_t, lsn) ),TP_fast_assign ( - __entry->dev = lip->li_mountp->m_super->s_dev; + __entry->dev = lip->li_log->l_mp->m_super->s_dev; __entry->lip = lip; __entry->type = lip->li_type; __entry->flags = lip->li_flags;
@@ -1362,7 +1362,7 @@ DECLARE_EVENT_CLASS(xfs_ail_class,__field (xfs_lsn_t, new_lsn) ),TP_fast_assign ( - __entry->dev = lip->li_mountp->m_super->s_dev; + __entry->dev = lip->li_log->l_mp->m_super->s_dev; __entry->lip = lip; __entry->type = lip->li_type; __entry->flags = lip->li_flags;
fs/xfs/xfs_trans.c +1 -1
@@ -648,7 +648,7 @@ xfs_trans_add_item(struct xfs_trans *tp, struct xfs_log_item *lip) { - ASSERT(lip->li_mountp == tp->t_mountp); + ASSERT(lip->li_log == tp->t_mountp->m_log);ASSERT (lip->li_ailp == tp->t_mountp->m_ail);ASSERT (list_empty (&lip->li_trans));ASSERT (!test_bit (XFS_LI_DIRTY , &lip->li_flags));
fs/xfs/xfs_trans.h +2 -1
@@ -8,6 +8,7 @@/* kernel only transaction subsystem defines */ +struct xlog ;struct xfs_buf ;struct xfs_buftarg ;struct xfs_efd_log_item ;
@@ -31,7 +32,7 @@ struct xfs_log_item {struct list_head li_ail;/* AIL pointers */ struct list_head li_trans;/* transaction list */ xfs_lsn_t li_lsn;/* last on-disk lsn */ -struct xfs_mount *li_mountp;/* ptr to fs mount */ +struct xlog *li_log;struct xfs_ail *li_ailp;/* ptr to AIL */ uint li_type;/* item type */ unsigned long li_flags;/* misc flags */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 458/571 xfs: aborting inodes on shutdown may need buffer lock
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit d2d7c0473586d2f22e85d615275f34cf19f94447 ]
Most buffer io list operations are run with the bp->b_lock held, but xfs_iflush_abort() can be called without the buffer lock being held resulting in inodes being removed from the buffer list while other list operations are occurring. This causes problems with corrupted bp->b_io_list inode lists during filesystem shutdown, leading to traversals that never end, double removals from the AIL, etc.
Fix this by passing the buffer to xfs_iflush_abort() if we have it locked. If the inode is attached to the buffer, we're going to have to remove it from the buffer list and we'd have to get the buffer off the inode log item to do that anyway.
If we don't have a buffer passed in (e.g. from xfs_reclaim_inode()) then we can determine if the inode has a log item and if it is attached to a buffer before we do anything else. If it does have an attached buffer, we can lock it safely (because the inode has a reference to it) and then perform the inode abort.
Stable-dep-of: 09234a632be4 ("xfs: xfs_ifree_cluster vs xfs_iflush_shutdown_abort deadlock")
--- fs/xfs/xfs_icache.c | 2 +- fs/xfs/xfs_inode.c | 2 +- fs/xfs/xfs_inode_item.c | 162 +++++++++++++++++++++++++++++++++------- fs/xfs/xfs_inode_item.h | 1 + 4 files changed, 136 insertions(+), 31 deletions(-)
fs/xfs/xfs_icache.c +1 -1
@@ -898,7 +898,7 @@ xfs_reclaim_inode(if (xfs_is_shutdown (ip->i_mount)) {xfs_iunpin_wait (ip); -xfs_iflush_abort (ip); +xfs_iflush_shutdown_abort (ip); goto reclaim; }if (xfs_ipincount (ip))
fs/xfs/xfs_inode.c +1 -1
@@ -3648,7 +3648,7 @@ xfs_iflush_cluster(/* * We must use the safe variant here as on shutdown xfs_iflush_abort() -* can remove itself from the list. +* will remove itself from the list. */ list_for_each_entry_safe (lip, n, &bp->b_li_list, li_bio_list) { iip = (struct xfs_inode_log_item *)lip;
fs/xfs/xfs_inode_item.c +133 -29
189 lines not on this page · raw message
fs/xfs/xfs_inode_item.h +1 -0
@@ -44,6 +44,7 @@ static inline int xfs_inode_clean(struct xfs_inode *ip)extern void xfs_inode_item_init (struct xfs_inode *,struct xfs_mount *);extern void xfs_inode_item_destroy (struct xfs_inode *);extern void xfs_iflush_abort (struct xfs_inode *); +extern void xfs_iflush_shutdown_abort (struct xfs_inode *);extern int xfs_inode_item_format_convert (xfs_log_iovec_t *,struct xfs_inode_log_format *);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 459/571 xfs: fix super block buf log item UAF during force shutdown
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guo Xuenan <[email protected]>
[ Upstream commit 575689fc0ffa6c4bb4e72fd18e31a6525a6124e0 ]
xfs log io error will trigger xlog shut down, and end_io worker call xlog_state_shutdown_callbacks to unpin and release the buf log item. The race condition is that when there are some thread doing transaction commit and happened not to be intercepted by xlog_is_shutdown, then, these log item will be insert into CIL, when unpin and release these buf log item, UAF will occur. BTW, add delay before xlog_cil_commit can increase recurrence probability.
The following call graph actually encountered this bad situation.
fsstress io end worker kworker/0:1H-216
xlog_ioend_work
->xlog_force_shutdown
->xlog_state_shutdown_callbacks
->xlog_cil_process_committed
->xlog_cil_committed
->xfs_trans_committed_bulk
->xfs_trans_apply_sb_deltas ->li_ops->iop_unpin(lip, 1);
->xfs_trans_getsb
->_xfs_trans_bjoin
->xfs_buf_item_init
->if (bip) { return 0;} //relog
->xlog_cil_commit
->xlog_cil_insert_items //insert into CIL
->xfs_buf_ioend_fail(bp);
->xfs_buf_ioend
->xfs_buf_item_done
->xfs_buf_item_relse
->xfs_buf_item_freewhen cil push worker gather percpu cil and insert super block buf log item into ctx->log_items then uaf occurs.
==================================================================
BUG: KASAN: use-after-free in xlog_cil_push_work+0x1c8f/0x22f0 Write of size 8 at addr ffff88801800f3f0 by task kworker/u4:4/105 CPU: 0 PID: 105 Comm: kworker/u4:4 Tainted: G W 6.1.0-rc1-00001-g274115149b42 #136 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014 Workqueue: xfs-cil/sda xlog_cil_push_work Call Trace: <TASK> dump_stack_lvl+0x4d/0x66 print_report+0x171/0x4a6 kasan_report+0xb3/0x130 xlog_cil_push_work+0x1c8f/0x22f0 process_one_work+0x6f9/0xf70 worker_thread+0x578/0xf30 kthread+0x28c/0x330 ret_from_fork+0x1f/0x30 </TASK> Allocated by task 2145: kasan_save_stack+0x1e/0x40 kasan_set_track+0x21/0x30 __kasan_slab_alloc+0x54/0x60 kmem_cache_alloc+0x14a/0x510 xfs_buf_item_init+0x160/0x6d0 _xfs_trans_bjoin+0x7f/0x2e0 xfs_trans_getsb+0xb6/0x3f0 xfs_trans_apply_sb_deltas+0x1f/0x8c0 __xfs_trans_commit+0xa25/0xe10 xfs_symlink+0xe23/0x1660 xfs_vn_symlink+0x157/0x280 vfs_symlink+0x491/0x790 do_symlinkat+0x128/0x220 __x64_sys_symlink+0x7a/0x90 do_syscall_64+0x35/0x80 entry_SYSCALL_64_after_hwframe+0x63/0xcd Freed by task 216: kasan_save_stack+0x1e/0x40 kasan_set_track+0x21/0x30 kasan_save_free_info+0x2a/0x40 __kasan_slab_free+0x105/0x1a0 kmem_cache_free+0xb6/0x460 xfs_buf_ioend+0x1e9/0x11f0 xfs_buf_item_unpin+0x3d6/0x840 xfs_trans_committed_bulk+0x4c2/0x7c0 xlog_cil_committed+0xab6/0xfb0 xlog_cil_process_committed+0x117/0x1e0 xlog_state_shutdown_callbacks+0x208/0x440 xlog_force_shutdown+0x1b3/0x3a0 xlog_ioend_work+0xef/0x1d0 process_one_work+0x6f9/0xf70 worker_thread+0x578/0xf30 kthread+0x28c/0x330 ret_from_fork+0x1f/0x30 The buggy address belongs to the object at ffff88801800f388 which belongs to the cache xfs_buf_item of size 272
The buggy address is located 104 bytes inside of
272-byte region [ffff88801800f388, ffff88801800f498)
The buggy address belongs to the physical page:
page:ffffea0000600380 refcount:1 mapcount:0 mapping:0000000000000000 index:0xffff88801800f208 pfn:0x1800e
head:ffffea0000600380 order:1 compound_mapcount:0 compound_pincount:0
flags: 0x1fffff80010200(slab|head|node=0|zone=1|lastcpupid=0x1fffff)
raw: 001fffff80010200 ffffea0000699788 ffff88801319db50 ffff88800fb50640
raw: ffff88801800f208 000000000015000a 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff88801800f280: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff88801800f300: fb fb fb fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff88801800f380: fc fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff88801800f400: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff88801800f480: fb fb fb fc fc fc fc fc fc fc fc fc fc fc fc fc
==================================================================Disabling lock debugging due to kernel taint
Stable-dep-of: d2fe5c4c8d25 ("xfs: rearrange code in xfs_buf_item.c")
--- fs/xfs/xfs_buf_item.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/xfs_buf_item.c +2 -0
@@ -1019,6 +1019,8 @@ xfs_buf_item_relse(trace_xfs_buf_item_relse (bp, _RET_IP_);ASSERT (!test_bit (XFS_LI_IN_AIL , &bip->bli_item.li_flags)); +if (atomic_read (&bip->bli_refcount)) +return ; bp->b_log_item =NULL ;xfs_buf_rele (bp);xfs_buf_item_free (bip);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 460/571 xfs: buffer pins need to hold a buffer reference
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit 89a4bf0dc3857569a77061d3d5ea2ac85f7e13c6 ]
When a buffer is unpinned by xfs_buf_item_unpin(), we need to access the buffer after we've dropped the buffer log item reference count. This opens a window where we can have two racing unpins for the buffer item (e.g. shutdown checkpoint context callback processing racing with journal IO iclog completion processing) and both attempt to access the buffer after dropping the BLI reference count. If we are unlucky, the "BLI freed" context wins the race and frees the buffer before the "BLI still active" case checks the buffer pin count.
This results in a use after free that can only be triggered in active filesystem shutdown situations.
To fix this, we need to ensure that buffer existence extends beyond the BLI reference count checks and until the unpin processing is complete. This implies that a buffer pin operation must also take a buffer reference to ensure that the buffer cannot be freed until the buffer unpin processing is complete.
Stable-dep-of: 816c330b605c ("xfs: factor out stale buffer item completion")
--- fs/xfs/xfs_buf_item.c | 88 ++++++++++++++++++++++++++++++++----------- 1 file changed, 65 insertions(+), 23 deletions(-)
fs/xfs/xfs_buf_item.c +65 -23
@@ -452,10 +452,18 @@ xfs_buf_item_format(* This is called to pin the buffer associated with the buf log item in memory * so it cannot be written out. * -* We also always take a reference to the buffer log item here so that the bli -* is held while the item is pinned in memory. This means that we can -* unconditionally drop the reference count a transaction holds when the -* transaction is completed. +* We take a reference to the buffer log item here so that the BLI life cycle +* extends at least until the buffer is unpinned via xfs_buf_item_unpin() and +* inserted into the AIL. +* +* We also need to take a reference to the buffer itself as the BLI unpin +* processing requires accessing the buffer after the BLI has dropped the final +* BLI reference. See xfs_buf_item_unpin() for an explanation. +* If unpins race to drop the final BLI reference and only the +* BLI owns a reference to the buffer, then the loser of the race can have the +* buffer fgreed from under it (e.g. on shutdown). Taking a buffer reference per +* pin count ensures the life cycle of the buffer extends for as +* long as we hold the buffer pin reference in xfs_buf_item_unpin(). */ STATIC void xfs_buf_item_pin(
@@ -470,13 +478,30 @@ xfs_buf_item_pin(trace_xfs_buf_item_pin (bip); +xfs_buf_hold (bip->bli_buf);atomic_inc (&bip->bli_refcount);atomic_inc (&bip->bli_buf->b_pin_count); }/* -* This is called to unpin the buffer associated with the buf log item which -* was previously pinned with a call to xfs_buf_item_pin(). +* This is called to unpin the buffer associated with the buf log item which was +* previously pinned with a call to xfs_buf_item_pin(). We enter this function +* with a buffer pin count, a buffer reference and a BLI reference. +* +* We must drop the BLI reference before we unpin the buffer because the AIL +* doesn't acquire a BLI reference whenever it accesses it. Therefore if the +* refcount drops to zero, the bli could still be AIL resident and the buffer +* submitted for I/O at any point before we return. This can result in IO +* completion freeing the buffer while we are still trying to access it here. +* This race condition can also occur in shutdown situations where we abort and +* unpin buffers from contexts other that journal IO completion. +* +* Hence we have to hold a buffer reference per pin count to ensure that the +* buffer cannot be freed until we have finished processing the unpin operation. +* The reference is taken in xfs_buf_item_pin(), and we must hold it until we +* are done processing the buffer state. In the case of an abort (remove = +* true) then we re-use the current pin reference as the IO reference we hand +* off to IO failure handling. */ STATIC void xfs_buf_item_unpin(
@@ -493,24 +518,18 @@ xfs_buf_item_unpin(trace_xfs_buf_item_unpin (bip); -/* -* Drop the bli ref associated with the pin and grab the hold required -* for the I/O simulation failure in the abort case. We have to do this -* before the pin count drops because the AIL doesn't acquire a bli -* reference. Therefore if the refcount drops to zero, the bli could -* still be AIL resident and the buffer submitted for I/O (and freed on -* completion) at any point before we return. This can be removed once -* the AIL properly holds a reference on the bli. -*/ freed =atomic_dec_and_test (&bip->bli_refcount); -if (freed && !stale && remove) -xfs_buf_hold (bp);if (atomic_dec_and_test (&bp->b_pin_count))wake_up_all (&bp->b_waiters); -/* nothing to do but drop the pin count if the bli is active */ -if (!freed) +/* +* Nothing to do but drop the buffer pin reference if the BLI is +* still active. +*/ +if (!freed) { +xfs_buf_rele (bp);return ; + }if (stale) {ASSERT (bip->bli_flags &XFS_BLI_STALE );
@@ -522,6 +541,15 @@ xfs_buf_item_unpin(trace_xfs_buf_item_unpin_stale (bip); +/* +* The buffer has been locked and referenced since it was marked +* stale so we own both lock and reference exclusively here. We +* do not need the pin reference any more, so drop it now so +* that we only have one reference to drop once item completion +* processing is complete. +*/ +xfs_buf_rele (bp); +/* * If we get called here because of an IO error, we may or may * not have the item on the AIL. xfs_trans_ail_delete() will
@@ -538,16 +566,30 @@ xfs_buf_item_unpin(ASSERT (bp->b_log_item ==NULL ); }xfs_buf_relse (bp); - }else if (remove) { +return ; + } + +if (remove) {/* -* The buffer must be locked and held by the caller to simulate -* an async I/O failure. We acquired the hold for this case -* before the buffer was unpinned. +* We need to simulate an async IO failures here to ensure that +* the correct error completion is run on this buffer. This +* requires a reference to the buffer and for the buffer to be +* locked. We can safely pass ownership of the pin reference to +* the IO to ensure that nothing can free the buffer while we +* wait for the lock and then run the IO failure completion. */ xfs_buf_lock (bp); bp->b_flags |=XBF_ASYNC ;xfs_buf_ioend_fail (bp); +return ; } + +/* +* BLI has no more active references - it will be moved to the AIL to +* manage the remaining BLI/buffer life cycle. There is nothing left for +* us to do here so drop the pin reference to the buffer. +*/ +xfs_buf_rele (bp); }STATIC uint
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 461/571 xfs: xfs_ifree_cluster vs xfs_iflush_shutdown_abort deadlock
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit 09234a632be42573d9743ac5ff6773622d233ad0 ]
Lock order of xfs_ifree_cluster() is cluster buffer -> try ILOCK -> IFLUSHING, except for the last inode in the cluster that is triggering the free. In that case, the lock order is ILOCK -> cluster buffer -> IFLUSHING.
xfs_iflush_cluster() uses cluster buffer -> try ILOCK -> IFLUSHING, so this can safely run concurrently with xfs_ifree_cluster().
xfs_inode_item_precommit() uses ILOCK -> cluster buffer, but this cannot race with xfs_ifree_cluster() so being in a different order will not trigger a deadlock.
xfs_reclaim_inode() during a filesystem shutdown uses ILOCK -> IFLUSHING -> cluster buffer via xfs_iflush_shutdown_abort(), and this deadlocks against xfs_ifree_cluster() like so:
sysrq: Show Blocked State
task:kworker/10:37 state:D stack:12560 pid:276182 tgid:276182 ppid:2 flags:0x00004000
Workqueue: xfs-inodegc/dm-3 xfs_inodegc_worker Call Trace: <TASK> __schedule+0x650/0xb10 schedule+0x6d/0xf0 schedule_timeout+0x8b/0x180 schedule_timeout_uninterruptible+0x1e/0x30 xfs_ifree+0x326/0x730 xfs_inactive_ifree+0xcb/0x230 xfs_inactive+0x2c8/0x380 xfs_inodegc_worker+0xaa/0x180 process_scheduled_works+0x1d4/0x400 worker_thread+0x234/0x2e0 kthread+0x147/0x170 ret_from_fork+0x3e/0x50 ret_from_fork_asm+0x1a/0x30 </TASK> task:fsync-tester state:D stack:12160 pid:2255943 tgid:2255943 ppid:3988702 flags:0x00004006 Call Trace: <TASK> __schedule+0x650/0xb10 schedule+0x6d/0xf0 schedule_timeout+0x31/0x180 __down_common+0xbe/0x1f0 __down+0x1d/0x30 down+0x48/0x50 xfs_buf_lock+0x3d/0xe0 xfs_iflush_shutdown_abort+0x51/0x1e0 xfs_icwalk_ag+0x386/0x690 xfs_reclaim_inodes_nr+0x114/0x160 xfs_fs_free_cached_objects+0x19/0x20 super_cache_scan+0x17b/0x1a0 do_shrink_slab+0x180/0x350 shrink_slab+0xf8/0x430 drop_slab+0x97/0xf0 drop_caches_sysctl_handler+0x59/0xc0 proc_sys_call_handler+0x189/0x280 proc_sys_write+0x13/0x20 vfs_write+0x33d/0x3f0 ksys_write+0x7c/0xf0 __x64_sys_write+0x1b/0x30 x64_sys_call+0x271d/0x2ee0 do_syscall_64+0x68/0x130 entry_SYSCALL_64_after_hwframe+0x76/0x7e
We can't change the lock order of xfs_ifree_cluster() - XFS_ISTALE and XFS_IFLUSHING are serialised through to journal IO completion by the cluster buffer lock being held.
There's quite a few asserts in the code that check that XFS_ISTALE does not occur out of sync with buffer locking (e.g. in xfs_iflush_cluster). There's also a dependency on the inode log item being removed from the buffer before XFS_IFLUSHING is cleared, also with asserts that trigger on this.
Further, we don't have a requirement for the inode to be locked when completing or aborting inode flushing because all the inode state updates are serialised by holding the cluster buffer lock across the IO to completion.
We can't check for XFS_IRECLAIM in xfs_ifree_mark_inode_stale() and skip the inode, because there is no guarantee that the inode will be reclaimed. Hence it *must* be marked XFS_ISTALE regardless of whether reclaim is preparing to free that inode. Similarly, we can't check for IFLUSHING before locking the inode because that would result in dirty inodes not being marked with ISTALE in the event of racing with XFS_IRECLAIM.
Hence we have to address this issue from the xfs_reclaim_inode() side. It is clear that we cannot hold the inode locked here when calling xfs_iflush_shutdown_abort() because it is the inode->buffer lock order that causes the deadlock against xfs_ifree_cluster().
Hence we need to drop the ILOCK before aborting the inode in the shutdown case. Once we've aborted the inode, we can grab the ILOCK again and then immediately reclaim it as it is now guaranteed to be clean.
Note that dropping the ILOCK in xfs_reclaim_inode() means that it can now be locked by xfs_ifree_mark_inode_stale() and seen whilst in this state. This is safe because we have left the XFS_IFLUSHING flag on the inode and so xfs_ifree_mark_inode_stale() will simply set XFS_ISTALE and move to the next inode. An ASSERT check in this path needs to be tweaked to take into account this new shutdown interaction.
--- fs/xfs/xfs_icache.c | 8 ++++++++ fs/xfs/xfs_inode.c | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-)
fs/xfs/xfs_icache.c +8 -0
@@ -898,7 +898,15 @@ xfs_reclaim_inode(if (xfs_is_shutdown (ip->i_mount)) {xfs_iunpin_wait (ip); +/* +* Avoid a ABBA deadlock on the inode cluster buffer vs +* concurrent xfs_ifree_cluster() trying to mark the inode +* stale. We don't need the inode locked to run the flush abort +* code, but the flush abort needs to lock the cluster buffer. +*/ +xfs_iunlock (ip,XFS_ILOCK_EXCL );xfs_iflush_shutdown_abort (ip); +xfs_ilock (ip,XFS_ILOCK_EXCL ); goto reclaim; }if (xfs_ipincount (ip))
fs/xfs/xfs_inode.c +1 -1
@@ -2492,7 +2492,7 @@ xfs_ifree_mark_inode_stale( iip = ip->i_itemp;if (__xfs_iflags_test (ip,XFS_IFLUSHING )) {ASSERT (!list_empty (&iip->ili_item.li_bio_list)); -ASSERT (iip->ili_last_fields); +ASSERT (iip->ili_last_fields ||xlog_is_shutdown (mp->m_log)); goto out_iunlock; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 462/571 xfs: catch stale AGF/AGF metadata
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit db6a2274162de615ff74b927d38942fe3134d298 ]
There is a race condition that can trigger in dmflakey fstests that can result in asserts in xfs_ialloc_read_agi() and xfs_alloc_read_agf() firing. The asserts look like this:
XFS: Assertion failed: pag->pagf_freeblks == be32_to_cpu(agf->agf_freeblks), file: fs/xfs/libxfs/xfs_alloc.c, line: 3440
.....
Call Trace: <TASK> xfs_alloc_read_agf+0x2ad/0x3a0 xfs_alloc_fix_freelist+0x280/0x720 xfs_alloc_vextent_prepare_ag+0x42/0x120 xfs_alloc_vextent_iterate_ags+0x67/0x260 xfs_alloc_vextent_start_ag+0xe4/0x1c0 xfs_bmapi_allocate+0x6fe/0xc90 xfs_bmapi_convert_delalloc+0x338/0x560 xfs_map_blocks+0x354/0x580 iomap_writepages+0x52b/0xa70 xfs_vm_writepages+0xd7/0x100 do_writepages+0xe1/0x2c0 __writeback_single_inode+0x44/0x340 writeback_sb_inodes+0x2d0/0x570 __writeback_inodes_wb+0x9c/0xf0 wb_writeback+0x139/0x2d0 wb_workfn+0x23e/0x4c0 process_scheduled_works+0x1d4/0x400 worker_thread+0x234/0x2e0 kthread+0x147/0x170 ret_from_fork+0x3e/0x50 ret_from_fork_asm+0x1a/0x30
I've seen the AGI variant from scrub running on the filesysetm after unmount failed due to systemd interference:
XFS: Assertion failed: pag->pagi_freecount == be32_to_cpu(agi->agi_freecount) || xfs_is_shutdown(pag->pag_mount), file: fs/xfs/libxfs/xfs_ialloc.c, line: 2804
.....
Call Trace: <TASK> xfs_ialloc_read_agi+0xee/0x150 xchk_perag_drain_and_lock+0x7d/0x240 xchk_ag_init+0x34/0x90 xchk_inode_xref+0x7b/0x220 xchk_inode+0x14d/0x180 xfs_scrub_metadata+0x2e2/0x510 xfs_ioc_scrub_metadata+0x62/0xb0 xfs_file_ioctl+0x446/0xbf0 __se_sys_ioctl+0x6f/0xc0 __x64_sys_ioctl+0x1d/0x30 x64_sys_call+0x1879/0x2ee0 do_syscall_64+0x68/0x130 ? exc_page_fault+0x62/0xc0 entry_SYSCALL_64_after_hwframe+0x76/0x7e
Essentially, it is the same problem. When _flakey_drop_and_remount() loads the drop-writes table, it makes all writes silently fail. Writes are reported to the fs as completed successfully, but they are not issued to the backing store. The filesystem sees the successful write completion and marks the metadata buffer clean and removes it from the AIL.
If this happens at the same time as memory pressure is occuring, the now-clean AGF and/or AGI buffers can be reclaimed from memory.
Shortly afterwards, but before _flakey_drop_and_remount() runs unmount, background writeback is kicked and it tries to allocate blocks for the dirty pages in memory. This then tries to access the AGF buffer we just turfed out of memory. It's not found, so it gets read in from disk.
This is all fine, except for the fact that the last writeback of the AGF did not actually reach disk. The AGF on disk is stale compared to the in-memory state held by the perag, and so they don't match and the assert fires.
Then other operations on that inode hang because the task was killed whilst holding inode locks. e.g:
Workqueue: xfs-conv/dm-12 xfs_end_io Call Trace: <TASK> __schedule+0x650/0xb10 schedule+0x6d/0xf0 schedule_preempt_disabled+0x15/0x30 rwsem_down_write_slowpath+0x31a/0x5f0 down_write+0x43/0x60 xfs_ilock+0x1a8/0x210 xfs_trans_alloc_inode+0x9c/0x240 xfs_iomap_write_unwritten+0xe3/0x300 xfs_end_ioend+0x90/0x130 xfs_end_io+0xce/0x100 process_scheduled_works+0x1d4/0x400 worker_thread+0x234/0x2e0 kthread+0x147/0x170 ret_from_fork+0x3e/0x50 ret_from_fork_asm+0x1a/0x30 </TASK>
and it's all down hill from there.
Memory pressure is one way to trigger this, another is to run "echo 3 > /proc/sys/vm/drop_caches" randomly while tests are running.
Regardless of how it is triggered, this effectively takes down the system once umount hangs because it's holding a sb->s_umount lock exclusive and now every sync(1) call gets stuck on it.
Fix this by replacing the asserts with a corruption detection check and a shutdown.
6.12:
Fixed conflict due to the following missing commit:
e9c4d8bfb26c ("xfs: factor out a generic xfs_group structure")
6.6:
Fixed conflict due to the following missing commit:
e45ea3645178 ("xfs: split the agf_roots and agf_levels arrays")5.15:
Fixed conflict due to the following missing commits:
6f643c57d57c ("xfs: implement ->notify_failure() for XFS")
[Continuous range: a95fee40e3d4^..08d3e84feeb8]
08d3e84feeb8 ("xfs: pass perag to xfs_alloc_read_agf()")
76b47e528e3a ("xfs: kill xfs_alloc_pagf_init()")
99b13c7f0bd3 ("xfs: pass perag to xfs_ialloc_read_agi()")
a95fee40e3d4 ("xfs: kill xfs_ialloc_pagi_init()")--- fs/xfs/libxfs/xfs_alloc.c | 45 +++++++++++++++++++++++++++++--------- fs/xfs/libxfs/xfs_ialloc.c | 32 +++++++++++++++++++++++---- 2 files changed, 63 insertions(+), 14 deletions(-)
fs/xfs/libxfs/xfs_alloc.c +35 -10
@@ -26,6 +26,7 @@#include "xfs_ag.h" #include "xfs_ag_resv.h" #include "xfs_bmap.h" +#include "xfs_health.h" extern kmem_zone_t *xfs_bmap_free_item_zone;
@@ -3078,18 +3079,42 @@ xfs_alloc_read_agf(if (allocbt_blks >0 )atomic64_add (allocbt_blks, &mp->m_allocbt_blks); } +#ifdef DEBUG - else if (!xfs_is_shutdown(mp)) { -ASSERT (pag->pagf_freeblks ==be32_to_cpu (agf->agf_freeblks)); -ASSERT (pag->pagf_btreeblks ==be32_to_cpu (agf->agf_btreeblks)); -ASSERT (pag->pagf_flcount ==be32_to_cpu (agf->agf_flcount)); -ASSERT (pag->pagf_longest ==be32_to_cpu (agf->agf_longest)); -ASSERT (pag->pagf_levels[XFS_BTNUM_BNOi] == -be32_to_cpu (agf->agf_levels[XFS_BTNUM_BNOi])); -ASSERT (pag->pagf_levels[XFS_BTNUM_CNTi] == -be32_to_cpu (agf->agf_levels[XFS_BTNUM_CNTi])); +/* +* It's possible for the AGF to be out of sync if the block device is +* silently dropping writes. This can happen in fstests with dmflakey +* enabled, which allows the buffer to be cleaned and reclaimed by +* memory pressure and then re-read from disk here. We will get a +* stale version of the AGF from disk, and nothing good can happen from +* here. Hence if we detect this situation, immediately shut down the +* filesystem. +* +* This can also happen if we are already in the middle of a forced +* shutdown, so don't bother checking if we are already shut down. +*/ +if (!xfs_is_shutdown (mp)) { +bool ok = true; + + ok &= pag->pagf_freeblks ==be32_to_cpu (agf->agf_freeblks); + ok &= pag->pagf_freeblks ==be32_to_cpu (agf->agf_freeblks); + ok &= pag->pagf_btreeblks ==be32_to_cpu (agf->agf_btreeblks); + ok &= pag->pagf_flcount ==be32_to_cpu (agf->agf_flcount); + ok &= pag->pagf_longest ==be32_to_cpu (agf->agf_longest); + ok &= pag->pagf_levels[XFS_BTNUM_BNOi] == +be32_to_cpu (agf->agf_levels[XFS_BTNUM_BNOi]); + ok &= pag->pagf_levels[XFS_BTNUM_CNTi] == +be32_to_cpu (agf->agf_levels[XFS_BTNUM_CNTi]); + +if (XFS_IS_CORRUPT (mp, !ok)) { +xfs_ag_mark_sick (pag,XFS_SICK_AG_AGF ); +xfs_trans_brelse (tp, *bpp); + *bpp =NULL ; +xfs_force_shutdown (mp,SHUTDOWN_CORRUPT_INCORE ); +return -EFSCORRUPTED ; + } } -#endif +#endif /* DEBUG */ return 0 ; }
fs/xfs/libxfs/xfs_ialloc.c +28 -4
@@ -27,6 +27,7 @@#include "xfs_log.h" #include "xfs_rmap.h" #include "xfs_ag.h" +#include "xfs_health.h" /* * Lookup a record by ino in the btree given by cur.
@@ -2619,12 +2620,35 @@ xfs_ialloc_read_agi( pag->pagi_init =1 ; } +#ifdef DEBUG /* -* It's possible for these to be out of sync if -* we are in the middle of a forced shutdown. +* It's possible for the AGF to be out of sync if the block device is +* silently dropping writes. This can happen in fstests with dmflakey +* enabled, which allows the buffer to be cleaned and reclaimed by +* memory pressure and then re-read from disk here. We will get a +* stale version of the AGF from disk, and nothing good can happen from +* here. Hence if we detect this situation, immediately shut down the +* filesystem. +* +* This can also happen if we are already in the middle of a forced +* shutdown, so don't bother checking if we are already shut down. */ -ASSERT (pag->pagi_freecount ==be32_to_cpu (agi->agi_freecount) || -xfs_is_shutdown (mp)); +if (!xfs_is_shutdown (mp)) { +bool ok = true; + + ok &= pag->pagi_freecount ==be32_to_cpu (agi->agi_freecount); + ok &= pag->pagi_count ==be32_to_cpu (agi->agi_count); + +if (XFS_IS_CORRUPT (mp, !ok)) { +xfs_ag_mark_sick (pag,XFS_SICK_AG_AGI ); +xfs_trans_brelse (tp, *bpp); + *bpp =NULL ; +xfs_force_shutdown (mp,SHUTDOWN_CORRUPT_INCORE ); +return -EFSCORRUPTED ; + } + } +#endif /* DEBUG */ +return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 463/571 xfs: rearrange code in xfs_buf_item.c
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit d2fe5c4c8d25999862d615f616aea7befdd62799 ]
The code to initialise, release and free items is all the way down the bottom of the file. Upcoming fixes need to these functions earlier in the file, so move them to the top.
There is one code change in this move - the parameter to xfs_buf_item_relse() is changed from the xfs_buf to the xfs_buf_log_item - the thing that the function is releasing.
6.6:
Fixed conflict due to the following missing commits:
[Continuous range: 10634530f7ba^..d4c75a1b40cd]
d4c75a1b40cd ("xfs: convert remaining kmem_free() to kfree()")
49292576136f ("xfs: convert kmem_free() for kvmalloc users to kvfree()")
afdc115559c5 ("xfs: move kmem_to_page()")
f078d4ea8276 ("xfs: convert kmem_alloc() to kmalloc()")
10634530f7ba ("xfs: convert kmem_zalloc() to kzalloc()")Removed ASSERT in favour of existing atomic_read-and-return in xfs_buf_item_relse() due to the following missing commit:
3762113b597f ("xfs: don't lose solo superblock counter update transactions")
5.15:
Fixed conflict due to the following missing commit:
182696fb021f ("xfs: rename _zone variables to _cache")--- fs/xfs/xfs_buf_item.c | 118 +++++++++++++++++++++--------------------- fs/xfs/xfs_buf_item.h | 1 - 2 files changed, 60 insertions(+), 59 deletions(-)
fs/xfs/xfs_buf_item.c +60 -58
@@ -31,6 +31,63 @@ static inline struct xfs_buf_log_item *BUF_ITEM(struct xfs_log_item *lip) return container_of(lip, struct xfs_buf_log_item, bli_item); } +static void +xfs_buf_item_get_format ( +struct xfs_buf_log_item *bip, +int count) +{ +ASSERT (bip->bli_formats ==NULL ); + bip->bli_format_count = count; + +if (count ==1 ) { + bip->bli_formats = &bip->__bli_format; +return ; + } + + bip->bli_formats =kmem_zalloc (count *sizeof (struct xfs_buf_log_format ), +0 ); +} + +static void +xfs_buf_item_free_format ( +struct xfs_buf_log_item *bip) +{ +if (bip->bli_formats != &bip->__bli_format) { +kmem_free (bip->bli_formats); + bip->bli_formats =NULL ; + } +} + +static void +xfs_buf_item_free ( +struct xfs_buf_log_item *bip) +{ +xfs_buf_item_free_format (bip); +kmem_free (bip->bli_item.li_lv_shadow); +kmem_cache_free (xfs_buf_item_zone, bip); +} + +/* +* xfs_buf_item_relse() is called when the buf log item is no longer needed. +*/ +static void +xfs_buf_item_relse ( +struct xfs_buf_log_item *bip) +{ +struct xfs_buf *bp = bip->bli_buf; + +trace_xfs_buf_item_relse (bp, _RET_IP_); + +ASSERT (!test_bit (XFS_LI_IN_AIL , &bip->bli_item.li_flags)); + +if (atomic_read (&bip->bli_refcount)) +return ; + + bp->b_log_item =NULL ; +xfs_buf_rele (bp); +xfs_buf_item_free (bip); +} +/* Is this log iovec plausibly large enough to contain the buffer log format? */ bool xfs_buf_log_check_iovec(
@@ -562,7 +619,7 @@ xfs_buf_item_unpin(ASSERT (list_empty (&bp->b_li_list)); }else {xfs_trans_ail_delete (lip,SHUTDOWN_LOG_IO_ERROR ); -xfs_buf_item_relse (bp); +xfs_buf_item_relse (bip);ASSERT (bp->b_log_item ==NULL ); }xfs_buf_relse (bp);
@@ -672,7 +729,7 @@ xfs_buf_item_put(*/ if (aborted)xfs_trans_ail_delete (lip,0 ); -xfs_buf_item_relse (bip->bli_buf); +xfs_buf_item_relse (bip);return true; }
@@ -792,33 +849,6 @@ static const struct xfs_item_ops xfs_buf_item_ops = { .iop_push = xfs_buf_item_push, }; -STATIC void -xfs_buf_item_get_format ( -struct xfs_buf_log_item *bip, -int count) -{ -ASSERT (bip->bli_formats ==NULL ); - bip->bli_format_count = count; - -if (count ==1 ) { - bip->bli_formats = &bip->__bli_format; -return ; - } - - bip->bli_formats =kmem_zalloc (count *sizeof (struct xfs_buf_log_format ), -0 ); -} - -STATIC void -xfs_buf_item_free_format ( -struct xfs_buf_log_item *bip) -{ -if (bip->bli_formats != &bip->__bli_format) { -kmem_free (bip->bli_formats); - bip->bli_formats =NULL ; - } -} -/* * Allocate a new buf log item to go with the given buffer. * Set the buffer's b_log_item field to point to the new
@@ -1040,34 +1070,6 @@ xfs_buf_item_dirty_format(return false; } -STATIC void -xfs_buf_item_free ( -struct xfs_buf_log_item *bip) -{ -xfs_buf_item_free_format (bip); -kmem_free (bip->bli_item.li_lv_shadow); -kmem_cache_free (xfs_buf_item_zone, bip); -} - -/* -* xfs_buf_item_relse() is called when the buf log item is no longer needed. -*/ -void -xfs_buf_item_relse ( -struct xfs_buf *bp) -{ -struct xfs_buf_log_item *bip = bp->b_log_item; - -trace_xfs_buf_item_relse (bp, _RET_IP_); -ASSERT (!test_bit (XFS_LI_IN_AIL , &bip->bli_item.li_flags)); - -if (atomic_read (&bip->bli_refcount)) -return ; - bp->b_log_item =NULL ; -xfs_buf_rele (bp); -xfs_buf_item_free (bip); -} -void xfs_buf_item_done (struct xfs_buf *bp)
@@ -1087,5 +1089,5 @@ xfs_buf_item_done(xfs_trans_ail_delete (&bp->b_log_item->bli_item, (bp->b_flags & _XBF_LOGRECOVERY) ?0 :SHUTDOWN_CORRUPT_INCORE ); -xfs_buf_item_relse (bp); +xfs_buf_item_relse (bp->b_log_item); }
fs/xfs/xfs_buf_item.h +0 -1
@@ -51,7 +51,6 @@ struct xfs_buf_log_item {int xfs_buf_item_init (struct xfs_buf *,struct xfs_mount *);void xfs_buf_item_done (struct xfs_buf *bp); -void xfs_buf_item_relse (struct xfs_buf *);bool xfs_buf_item_put (struct xfs_buf_log_item *);void xfs_buf_item_log (struct xfs_buf_log_item *,uint ,uint );bool xfs_buf_item_dirty_format (struct xfs_buf_log_item *);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 464/571 xfs: factor out stale buffer item completion
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit 816c330b605c3f4813c0dc0ab5af5cce17ff06b3 ]
The stale buffer item completion handling is currently only done from BLI unpinning. We need to perform this function from where-ever the last reference to the BLI is dropped, so first we need to factor this code out into a helper.
--- fs/xfs/xfs_buf_item.c | 60 ++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 23 deletions(-)
fs/xfs/xfs_buf_item.c +37 -23
@@ -540,6 +540,42 @@ xfs_buf_item_pin(atomic_inc (&bip->bli_buf->b_pin_count); } +/* +* For a stale BLI, process all the necessary completions that must be +* performed when the final BLI reference goes away. The buffer will be +* referenced and locked here - we return to the caller with the buffer still +* referenced and locked for them to finalise processing of the buffer. +*/ +static void +xfs_buf_item_finish_stale ( +struct xfs_buf_log_item *bip) +{ +struct xfs_buf *bp = bip->bli_buf; +struct xfs_log_item *lip = &bip->bli_item; + +ASSERT (bip->bli_flags &XFS_BLI_STALE ); +ASSERT (xfs_buf_islocked (bp)); +ASSERT (bp->b_flags &XBF_STALE ); +ASSERT (bip->__bli_format.blf_flags &XFS_BLF_CANCEL ); +ASSERT (list_empty (&lip->li_trans)); +ASSERT (!bp->b_transp); + +if (bip->bli_flags &XFS_BLI_STALE_INODE ) { +xfs_buf_item_done (bp); +xfs_buf_inode_iodone (bp); +ASSERT (list_empty (&bp->b_li_list)); +return ; + } + +/* +* We may or may not be on the AIL here, xfs_trans_ail_delete() will do +* the right thing regardless of the situation in which we are called. +*/ +xfs_trans_ail_delete (lip,SHUTDOWN_LOG_IO_ERROR ); +xfs_buf_item_relse (bip); +ASSERT (bp->b_log_item ==NULL ); +} +/* * This is called to unpin the buffer associated with the buf log item which was * previously pinned with a call to xfs_buf_item_pin(). We enter this function
@@ -589,13 +625,6 @@ xfs_buf_item_unpin( }if (stale) { -ASSERT (bip->bli_flags &XFS_BLI_STALE ); -ASSERT (xfs_buf_islocked (bp)); -ASSERT (bp->b_flags &XBF_STALE ); -ASSERT (bip->__bli_format.blf_flags &XFS_BLF_CANCEL ); -ASSERT (list_empty (&lip->li_trans)); -ASSERT (!bp->b_transp); -trace_xfs_buf_item_unpin_stale (bip);/*
@@ -606,22 +635,7 @@ xfs_buf_item_unpin(* processing is complete. */ xfs_buf_rele (bp); - -/* -* If we get called here because of an IO error, we may or may -* not have the item on the AIL. xfs_trans_ail_delete() will -* take care of that situation. xfs_trans_ail_delete() drops -* the AIL lock. -*/ -if (bip->bli_flags &XFS_BLI_STALE_INODE ) { -xfs_buf_item_done (bp); -xfs_buf_inode_iodone (bp); -ASSERT (list_empty (&bp->b_li_list)); - }else { -xfs_trans_ail_delete (lip,SHUTDOWN_LOG_IO_ERROR ); -xfs_buf_item_relse (bip); -ASSERT (bp->b_log_item ==NULL ); - } +xfs_buf_item_finish_stale (bip);xfs_buf_relse (bp);return ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 465/571 xfs: fix unmount hang with unflushable inodes stuck in the AIL
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Chinner <[email protected]>
[ Upstream commit 7b5f775be14ac1532c049022feadcfe44769566d ]
Unmount of a shutdown filesystem can hang with stale inode cluster buffers in the AIL like so:
[95964.140623] Call Trace: [95964.144641] __schedule+0x699/0xb70 [95964.154003] schedule+0x64/0xd0 [95964.156851] xfs_ail_push_all_sync+0x9b/0xf0 [95964.164816] xfs_unmount_flush_inodes+0x41/0x70 [95964.168698] xfs_unmountfs+0x7f/0x170 [95964.171846] xfs_fs_put_super+0x3b/0x90 [95964.175216] generic_shutdown_super+0x77/0x160 [95964.178060] kill_block_super+0x1b/0x40 [95964.180553] xfs_kill_sb+0x12/0x30 [95964.182796] deactivate_locked_super+0x38/0x100 [95964.185735] deactivate_super+0x41/0x50 [95964.188245] cleanup_mnt+0x9f/0x160 [95964.190519] __cleanup_mnt+0x12/0x20 [95964.192899] task_work_run+0x89/0xb0 [95964.195221] resume_user_mode_work+0x4f/0x60 [95964.197931] syscall_exit_to_user_mode+0x76/0xb0 [95964.201003] do_syscall_64+0x74/0x130
$ pstree -N mnt |grep umount |-check-parallel---nsexec---run_test.sh---753---umount
It always seems to be generic/753 that triggers this, and repeating a quick group test run triggers it every 10-15 iterations. Hence it generally triggers once up every 30-40 minutes of test time. just running generic/753 by itself or concurrently with a limited group of tests doesn't reproduce this issue at all.
Tracing on a hung system shows the AIL repeating every 50ms a log force followed by an attempt to push pinned, aborted inodes from the AIL (trimmed for brevity):
xfs_log_force: lsn 0x1c caller xfsaild+0x18e xfs_log_force: lsn 0x0 caller xlog_cil_flush+0xbd xfs_log_force: lsn 0x1c caller xfs_log_force+0x77 xfs_ail_pinned: lip 0xffff88826014afa0 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED xfs_ail_pinned: lip 0xffff88814000a708 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED xfs_ail_pinned: lip 0xffff88810b850c80 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED xfs_ail_pinned: lip 0xffff88810b850af0 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED xfs_ail_pinned: lip 0xffff888165cf0a28 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED xfs_ail_pinned: lip 0xffff88810b850bb8 lsn 1/37472 type XFS_LI_INODE flags IN_AIL|ABORTED
....
The inode log items are marked as aborted, which means that either:
a) a transaction commit has occurred, seen an error or shutdown, and called xfs_trans_free_items() to abort the items. This should happen before any pinning of log items occurs.
or
b) a dirty transaction has been cancelled. This should also happen before any pinning of log items occurs.
or
c) AIL insertion at journal IO completion is marked as aborted. In this case, the log item is pinned by the CIL until journal IO completes and hence needs to be unpinned. This is then done after the ->iop_committed() callback is run, so the pin count should be balanced correctly.
Yet none of these seemed to be occurring. Further tracing indicated this:
d) Shutdown during CIL pushing resulting in log item completion being called from checkpoint abort processing. Items are unpinned and released without serialisation against each other, journal IO completion or transaction commit completion.
In this case, we may still have a transaction commit in flight that holds a reference to a xfs_buf_log_item (BLI) after CIL insertion. e.g. a synchronous transaction will flush the CIL before the transaction is torn down. The concurrent CIL push then aborts insertion it and drops the commit/AIL reference to the BLI. This can leave the transaction commit context with the last reference to the BLI which is dropped here:
xfs_trans_free_items()
->iop_release
xfs_buf_item_release
xfs_buf_item_put
if (XFS_LI_ABORTED)
xfs_trans_ail_delete
xfs_buf_item_relse()
Unlike the journal completion ->iop_unpin path, this path does not run stale buffer completion process when it drops the last reference, hence leaving the stale inodes attached to the buffer sitting the AIL. There are no other references to those inodes, so there is no other mechanism to remove them from the AIL. Hence unmount hangs.
The buffer lock context for stale buffers is passed to the last BLI reference. This is normally the last BLI unpin on journal IO completion. The unpin then processes the stale buffer completion and releases the buffer lock. However, if the final unpin from journal IO completion (or CIL push abort) does not hold the last reference to the BLI, there -must- still be a transaction context that references the BLI, and so that context must perform the stale buffer completion processing before the buffer is unlocked and the BLI torn down.
The fix for this is to rework the xfs_buf_item_relse() path to run stale buffer completion processing if it drops the last reference to the BLI. We still hold the buffer locked, so the buffer owner and lock context is the same as if we passed the BLI and buffer to the ->iop_unpin() context to finish stale process on journal commit.
However, we have to be careful here. In a shutdown state, we can be freeing dirty BLIs from xfs_buf_item_put() via xfs_trans_brelse() and xfs_trans_bdetach(). The existing code handles this case by considering shutdown state as "aborted", but in doing so largely masks the failure to clean up stale BLI state from the xfs_buf_item_relse() path. i.e regardless of the shutdown state and whether the item is in the AIL, we must finish the stale buffer cleanup if we are are dropping the last BLI reference from the ->iop_relse path in transaction commit context.
--- fs/xfs/xfs_buf_item.c | 121 +++++++++++++++++++++++++++++------------- fs/xfs/xfs_buf_item.h | 2 +- 2 files changed, 86 insertions(+), 37 deletions(-)
fs/xfs/xfs_buf_item.c +85 -36
@@ -708,43 +708,42 @@ xfs_buf_item_push(* Drop the buffer log item refcount and take appropriate action. This helper * determines whether the bli must be freed or not, since a decrement to zero * does not necessarily mean the bli is unused. -* -* Return true if the bli is freed, false otherwise. */ -bool +void xfs_buf_item_put (struct xfs_buf_log_item *bip) { -struct xfs_log_item *lip = &bip->bli_item; -bool aborted; -bool dirty; + +ASSERT (xfs_buf_islocked (bip->bli_buf));/* drop the bli ref and return if it wasn't the last one */ if (!atomic_dec_and_test (&bip->bli_refcount)) -return false; +return ; -/* -* We dropped the last ref and must free the item if clean or aborted. -* If the bli is dirty and non-aborted, the buffer was clean in the -* transaction but still awaiting writeback from previous changes. In -* that case, the bli is freed on buffer writeback completion. -*/ - aborted =test_bit (XFS_LI_ABORTED , &lip->li_flags) || -xlog_is_shutdown (lip->li_log); - dirty = bip->bli_flags &XFS_BLI_DIRTY ; -if (dirty && !aborted) -return false; +/* If the BLI is in the AIL, then it is still dirty and in use */ +if (test_bit (XFS_LI_IN_AIL , &bip->bli_item.li_flags)) { +ASSERT (bip->bli_flags &XFS_BLI_DIRTY ); +return ; + }/* -* The bli is aborted or clean. An aborted item may be in the AIL -* regardless of dirty state. For example, consider an aborted -* transaction that invalidated a dirty bli and cleared the dirty -* state. +* In shutdown conditions, we can be asked to free a dirty BLI that +* isn't in the AIL. This can occur due to a checkpoint aborting a BLI +* instead of inserting it into the AIL at checkpoint IO completion. If +* there's another bli reference (e.g. a btree cursor holds a clean +* reference) and it is released via xfs_trans_brelse(), we can get here +* with that aborted, dirty BLI. In this case, it is safe to free the +* dirty BLI immediately, as it is not in the AIL and there are no +* other references to it. +* +* We should never get here with a stale BLI via that path as +* xfs_trans_brelse() specifically holds onto stale buffers rather than +* releasing them. */ -if (aborted) -xfs_trans_ail_delete (lip,0 ); +ASSERT (!(bip->bli_flags &XFS_BLI_DIRTY ) || +test_bit (XFS_LI_ABORTED , &bip->bli_item.li_flags)); +ASSERT (!(bip->bli_flags &XFS_BLI_STALE ));xfs_buf_item_relse (bip); -return true; }/*
@@ -765,6 +764,15 @@ xfs_buf_item_put(* if necessary but do not unlock the buffer. This is for support of * xfs_trans_bhold(). Make sure the XFS_BLI_HOLD field is cleared if we don't * free the item. +* +* If the XFS_BLI_STALE flag is set, the last reference to the BLI *must* +* perform a completion abort of any objects attached to the buffer for IO +* tracking purposes. This generally only happens in shutdown situations, +* normally xfs_buf_item_unpin() will drop the last BLI reference and perform +* completion processing. However, because transaction completion can race with +* checkpoint completion during a shutdown, this release context may end up +* being the last active reference to the BLI and so needs to perform this +* cleanup. */ STATIC void xfs_buf_item_release(
@@ -772,18 +780,19 @@ xfs_buf_item_release( {struct xfs_buf_log_item *bip =BUF_ITEM (lip);struct xfs_buf *bp = bip->bli_buf; -bool released;bool hold = bip->bli_flags &XFS_BLI_HOLD ;bool stale = bip->bli_flags &XFS_BLI_STALE ; -#if defined(DEBUG ) || defined(XFS_WARN ) -bool ordered = bip->bli_flags &XFS_BLI_ORDERED ; -bool dirty = bip->bli_flags &XFS_BLI_DIRTY ;bool aborted =test_bit (XFS_LI_ABORTED , &lip->li_flags); +bool dirty = bip->bli_flags &XFS_BLI_DIRTY ; +#if defined(DEBUG ) || defined(XFS_WARN ) +bool ordered = bip->bli_flags &XFS_BLI_ORDERED ;#endif trace_xfs_buf_item_release (bip); +ASSERT (xfs_buf_islocked (bp)); +/* * The bli dirty state should match whether the blf has logged segments * except for ordered buffers, where only the bli should be dirty.
@@ -799,16 +808,56 @@ xfs_buf_item_release( bp->b_transp =NULL ; bip->bli_flags &= ~(XFS_BLI_LOGGED |XFS_BLI_HOLD |XFS_BLI_ORDERED ); +/* If there are other references, then we have nothing to do. */ +if (!atomic_dec_and_test (&bip->bli_refcount)) + goto out_release; + +/* +* Stale buffer completion frees the BLI, unlocks and releases the +* buffer. Neither the BLI or buffer are safe to reference after this +* call, so there's nothing more we need to do here. +* +* If we get here with a stale buffer and references to the BLI remain, +* we must not unlock the buffer as the last BLI reference owns lock +* context, not us. +*/ +if (stale) { +xfs_buf_item_finish_stale (bip); +xfs_buf_relse (bp); +ASSERT (!hold); +return ; + } + +/* +* Dirty or clean, aborted items are done and need to be removed from +* the AIL and released. This frees the BLI, but leaves the buffer +* locked and referenced. +*/ +if (aborted ||xlog_is_shutdown (lip->li_log)) { +ASSERT (list_empty (&bip->bli_buf->b_li_list)); +xfs_buf_item_done (bp); + goto out_release; + } + +/* +* Clean, unreferenced BLIs can be immediately freed, leaving the buffer +* locked and referenced. +* +* Dirty, unreferenced BLIs *must* be in the AIL awaiting writeback. +*/ +if (!dirty) +xfs_buf_item_relse (bip); +else +ASSERT (test_bit (XFS_LI_IN_AIL , &lip->li_flags)); + +/* Not safe to reference the BLI from here */ +out_release:/* -* Unref the item and unlock the buffer unless held or stale. Stale -* buffers remain locked until final unpin unless the bli is freed by -* the unref call. The latter implies shutdown because buffer -* invalidation dirties the bli and transaction. +* If we get here with a stale buffer, we must not unlock the +* buffer as the last BLI reference owns lock context, not us. */ - released =xfs_buf_item_put (bip); -if (hold || (stale && !released)) +if (stale || hold)return ; -ASSERT (!stale || aborted);xfs_buf_relse (bp); }
fs/xfs/xfs_buf_item.h +1 -1
@@ -51,7 +51,7 @@ struct xfs_buf_log_item {int xfs_buf_item_init (struct xfs_buf *,struct xfs_mount *);void xfs_buf_item_done (struct xfs_buf *bp); -bool xfs_buf_item_put (struct xfs_buf_log_item *); +void xfs_buf_item_put (struct xfs_buf_log_item *bip);void xfs_buf_item_log (struct xfs_buf_log_item *,uint ,uint );bool xfs_buf_item_dirty_format (struct xfs_buf_log_item *);void xfs_buf_inode_iodone (struct xfs_buf *);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 466/571 ksmbd: fix heap out-of-bounds write in krb5_authenticate()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilan Dudnik <[email protected]>
commit 23a0be6a84a38ac169eeab49017934e8e27c65f0 upstream.
In krb5_authenticate(), out_len is calculated to determine available headroom in response_buf for the incoming Kerberos AP-REP token. However, when SMB2_SESSION_SETUP is processed as a non-first element of a compounded SMB2 request, the calculation omits work->next_smb2_rsp_hdr_off.
This causes out_len to overstate remaining buffer headroom by the cumulative size of prior responses in the compound chain. Consequently, the length check in ksmbd_krb5_authenticate()
(*out_len <= resp->spnego_blob_len) passes erroneously, allowing memcpy() to write the AP-REP blob past the end of response_buf into adjacent kernel heap memory.
Fix this by subtracting work->next_smb2_rsp_hdr_off when computing out_len, ensuring it accurately reflects physical remaining buffer space.
--- fs/ksmbd/smb2pdu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ksmbd/smb2pdu.c +1 -1
@@ -1612,7 +1612,7 @@ static int krb5_authenticate(struct ksmb in_len =le16_to_cpu (req->SecurityBufferLength); out_blob = (char *)&rsp->hdr.ProtocolId +le16_to_cpu (rsp->SecurityBufferOffset); - out_len = work->response_sz - + out_len = work->response_sz - work->next_smb2_rsp_hdr_off - (le16_to_cpu (rsp->SecurityBufferOffset) +4 );/* Check previous session */
Greg Kroah-Hartman
maintainerPATCH 467/571 KVM: x86: Use active memslots for the per-vCPU MMIO cache
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinu Kim <[email protected]>
commit b3e6212dea2e4328a841ceb37f377583176dc735 upstream.
KVM tags the per-vCPU MMIO cache with a memslot generation so that a memslot update invalidates cached MMIO information. Both the fill and validation paths use kvm_memslots(), which unconditionally selects address space 0, even when the vCPU is running in SMM and using address space 1.
Commit 56f17dd3fbc4 ("kvm: x86: fix stale mmio cache bug") added the memslot generation to the cache key so that a memslot update could not leave a stale entry valid. When commit 699023e23965 ("KVM: x86: add SMM to the MMU role, support SMRAM address space") added the SMM address space, these helpers were not converted to use the active memslots.
Consequently, an update to the SMM memslots can leave an entry from the old SMM address space apparently valid after the vCPU returns to the normal address space. A guest can then cause an access to valid RAM at the same GFN to be returned to userspace as KVM_EXIT_MMIO.
Completing that exit through the VMM's RAM address space writes the backing page without going through KVM's write-tracking path. If the page backs a nested EPT table, KVM can continue using shadow translations derived from the old contents. The WARN_ON_ONCE() in kvm_mmu_write_protect_fault() catches this invalid cache and memslot combination.
Use the vCPU's active memslots when caching and validating the entry. Memslot generations are unique across address spaces, so the generation also distinguishes the normal and SMM views. This matches the MMIO SPTE cache, which already uses kvm_vcpu_memslots().
On an unpatched current-mainline kernel, a regression test that fills the cache in SMM and updates only the SMM memslots fails the intended RAM write and triggers the kvm_mmu_write_protect_fault() warning. With this change, the same test completes the RAM write without a warning. The x86/smm_test, set_memory_region_test, and memslot_modification_stress_test selftests also pass.
--- arch/x86/kvm/x86.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.h +2 -2
@@ -219,7 +219,7 @@ static inline bool is_noncanonical_addrestatic inline void vcpu_cache_mmio_info (struct kvm_vcpu *vcpu,gva_t gva,gfn_t gfn,unsigned access) { -u64 gen =kvm_memslots (vcpu->kvm)->generation; +u64 gen =kvm_vcpu_memslots (vcpu)->generation;if (unlikely (gen &KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS ))return ;
@@ -236,7 +236,7 @@ static inline void vcpu_cache_mmio_info(static inline bool vcpu_match_mmio_gen (struct kvm_vcpu *vcpu) { -return vcpu->arch.mmio_gen ==kvm_memslots (vcpu->kvm)->generation; +return vcpu->arch.mmio_gen ==kvm_vcpu_memslots (vcpu)->generation; }/*
Greg Kroah-Hartman
maintainerPATCH 468/571 bpf: fix potential 32-bit overflow when accessing ARRAY map element
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrii Nakryiko <[email protected]>
[ Upstream commit 87ac0d600943994444e24382a87aa19acc4cd3d4 ]
If BPF array map is bigger than 4GB, element pointer calculation can overflow because both index and elem_size are u32. Fix this everywhere by forcing 64-bit multiplication. Extract this formula into separate small helper and use it consistently in various places.
Speculative-preventing formula utilizing index_mask trick is left as is, but explicit u64 casts are added in both places.
--- kernel/bpf/arraymap.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-)
kernel/bpf/arraymap.c +11 -7
@@ -158,6 +158,11 @@ static struct bpf_map *array_map_alloc(union bpf_attr *attr)return &array->map; } +static void *array_map_elem_ptr (struct bpf_array * array,u32 index) +{ +return array->value + (u64 )array->elem_size * index; +} +/* Called from syscall or from eBPF program */ static void *array_map_lookup_elem (struct bpf_map *map,void *key) {
@@ -167,7 +172,7 @@ static void *array_map_lookup_elem(struct bpf_map *map, void *key)if (unlikely (index >= array->map.max_entries))return NULL ; -return array->value + array->elem_size * (index & array->index_mask); +return array->value + (u64 )array->elem_size * (index & array->index_mask); } static int array_map_direct_value_addr(const struct bpf_map *map, u64 *imm,
@@ -325,7 +330,7 @@ static int array_map_update_elem(struct bpf_map *map, void *key, void *value, value, map->value_size); }else { val = array->value + - array->elem_size * (index & array->index_mask); + (u64 )array->elem_size * (index & array->index_mask);if (map_flags &BPF_F_LOCK )copy_map_value_locked (map, val, value, false);else
@@ -393,8 +398,7 @@ static void array_map_free_timers(struct bpf_map *map)return ;for (i =0 ; i < array->map.max_entries; i++) -bpf_timer_cancel_and_free (array->value + array->elem_size * i + - map->timer_off); +bpf_timer_cancel_and_free (array_map_elem_ptr (array, i) + map->timer_off); }/* Called when map->refcnt goes to zero, either from workqueue or from syscall */
@@ -534,7 +538,7 @@ static void *bpf_array_map_seq_start(struct seq_file *seq, loff_t *pos) index = info->index & array->index_mask;if (info->percpu_value_buf)return array->pptrs[index]; -return array->value + array->elem_size * index; +return array_map_elem_ptr (array, index); }static void *bpf_array_map_seq_next (struct seq_file *seq,void *v,loff_t *pos)
@@ -553,7 +557,7 @@ static void *bpf_array_map_seq_next(struct seq_file *seq, void *v, loff_t *pos) index = info->index & array->index_mask;if (info->percpu_value_buf)return array->pptrs[index]; -return array->value + array->elem_size * index; +return array_map_elem_ptr (array, index); }static int __bpf_array_map_seq_show (struct seq_file *seq,void *v)
@@ -674,7 +678,7 @@ static int bpf_for_each_array_elem(struct bpf_map *map, void *callback_fn,if (is_percpu) val =this_cpu_ptr (array->pptrs[i]);else - val = array->value + array->elem_size * i; + val =array_map_elem_ptr (array, i); num_elems++; key = i; ret = BPF_CAST_CALL(callback_fn)((u64)(long)map,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 469/571 power: supply: ds2780: Fix ds2780_get_capacity() returning raw value
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xueqin Luo <[email protected]>
[ Upstream commit a58cbc8b36ec0cd00d2ba3de7d003de818a27523 ]
ds2780_get_capacity() returns the raw register value instead of 0 on success. The capacity is already stored in *capacity, so the function should return 0 to indicate success.
--- drivers/power/supply/ds2780_battery.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/power/supply/ds2780_battery.c +1 -1
@@ -304,7 +304,7 @@ static int ds2780_get_capacity(struct ds2780_device_info *dev_info,return ret; *capacity = raw; -return raw; +return 0 ; }static int ds2780_get_status (struct ds2780_device_info *dev_info,int *status)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 470/571 Drivers: hv: Dont reset VMBus connection state on error/exit paths
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael Kelley <[email protected]>
[ Upstream commit ec31dc39e835ccde0930daccece8c492d28282fc ]
In two places, current code forces vmbus_connection.conn_state to DISCONNECTED prior to calling vmbus_disconnect(). But vmbus_disconnect() calls vmbus_initiate_unload(), which unloads the VMBus connection only if the conn_state is CONNECTED. Consequently, the connection remains and the Hyper-V host might continue to send messages or post VMBus interrupts.
The problem was introduced in commit 74347a99e73ae ("x86/Hyper-V:
Unload vmbus channel in hv panic callback"), in that vmbus_initiate_unload() started checking the current connection state before doing the unload. This commit removed some occurrences where conn_state was forced to DISCONNECTED, but these two remained, apparently due to an oversight at the time.
Fix this by not forcing conn_state to DISCONNECTED during VMBus exit, or if a failure occurs when establishing the connection in the first place. Whatever value conn_state has at the time is then read by vmbus_initiate_unload() to determine if there is a connection to be unloaded.
--- drivers/hv/connection.c | 1 - drivers/hv/vmbus_drv.c | 1 - 2 files changed, 2 deletions(-)
drivers/hv/connection.c +0 -1
@@ -274,7 +274,6 @@ int vmbus_connect(void) cleanup:pr_err ("Unable to connect to host\n" ); - vmbus_connection.conn_state =DISCONNECTED ;vmbus_disconnect ();kfree (msginfo);
drivers/hv/vmbus_drv.c +0 -1
@@ -2807,7 +2807,6 @@ static void __exit vmbus_exit(void)hv_remove_kexec_handler ();hv_remove_crash_handler (); - vmbus_connection.conn_state =DISCONNECTED ;hv_stimer_global_cleanup ();vmbus_disconnect ();if (vmbus_irq ==-1 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 471/571 vsock: treat TCP_CLOSING as once-established
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michal Luczaj <[email protected]>
[ Upstream commit 4f6ac74fa594a918d41255c941256e1d51592d3b ]
Handle the TCP_ESTABLISHED -> TCP_CLOSING transition on OP_RST, which can race with the connect loop. Immediately break and return 0 on ESTABLISHED/CLOSING. The return value of connect() should reflect what happened up to the point the connection was established or failed. Events that occur afterwards must not affect it. E.g. even if OP_RW has already set sk_err, connect() should still return 0, not ENOBUFS because of it. Adapt the inaccurate comment above signal_pending().
Resetting a socket that is still present in connected_table can lead to memory corruption. The reporter noted lost transports for in-flight skbs, and I have reproduced crashes caused by re-insertion into connected_table.
list_add double add: new=, prev=, next=.
kernel BUG at lib/list_debug.c:35!
Oops: invalid opcode: 0000 [#1] SMP KASAN NOPTI Workqueue: vsock-loopback vsock_loopback_work RIP: 0010:__list_add_valid_or_report+0x11f/0x130 Call Trace: vsock_insert_connected.cold+0xe/0x13 virtio_transport_recv_pkt+0x10e9/0x1460 vsock_loopback_work+0x305/0x480 process_one_work+0xe4c/0x1560 worker_thread+0x4f1/0xd60 kthread+0x36e/0x470 ret_from_fork+0x47b/0x6b0 ret_from_fork_asm+0x1a/0x30
This fix is supplementary to commit 002541ef650b ("vsock: Ignore signal/timeout on connect() if already established"). Details under Link.
--- net/vmw_vsock/af_vsock.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
net/vmw_vsock/af_vsock.c +8 -9
@@ -1493,23 +1493,22 @@ static int vsock_connect(struct socket *sock, struct sockaddr *addr, timeout =schedule_timeout (timeout);lock_sock (sk); -/* Connection established. Whatever happens to socket once we -* release it, that's not connect()'s concern. No need to go +/* Connection was established. Whatever happens to socket once +* we release it, that's not connect()'s concern. No need to go * into signal and timeout handling. Call it a day. * * Note that allowing to "reset" an already established socket * here is racy and insecure. */ -if (sk->sk_state ==TCP_ESTABLISHED ) -break ; +if (sk->sk_state ==TCP_ESTABLISHED || + sk->sk_state ==TCP_CLOSING ) { + err =0 ; + goto out_wait; + }/* If connection was _not_ established and a signal/timeout came * to be, we want the socket's state reset. User space may want -* to retry. -* -* sk_state != TCP_ESTABLISHED implies that socket is not on -* vsock_connected_table. We keep the binding and the transport -* assigned. +* to retry, so we keep the binding and the transport assigned. */ if (signal_pending (current) || timeout ==0 ) { err = timeout ==0 ? -ETIMEDOUT :sock_intr_errno (timeout);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 472/571 net/rds: dont let the rdma_cm destroy an id RDS still owns on route failure
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Allison Henderson <[email protected]>
[ Upstream commit 98d446b7c013254a8a7b49720557676a3a851fde ]
rds_rdma_cm_event_handler_cmn() hands the return value of rdma_resolve_route() straight back to the rdma_cm on RDMA_CM_EVENT_ADDR_RESOLVED. A synchronous failure there - -ENOMEM from the route work allocation, an SA query that cannot be set up, a RoCE route with no usable device - makes addr_handler() destroy the id the event was delivered on. That id is ic->i_cm_id, and nothing clears the pointer: the connection sits in RDS_CONN_CONNECTING with a freed id until its shutdown calls rdma_disconnect() and rdma_destroy_id() on it.
The ROUTE_RESOLVED case already avoids this: rds_ib_cm_initiate_connect() forces a zero return while ic->i_cm_id == cm_id, as the comment there explains. Do the same here - drop the connection and return 0 - so the id stays RDS's to destroy from the shutdown, and the reconnect gets a fresh one.
--- net/rds/rdma_transport.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
net/rds/rdma_transport.c +11 -1
@@ -89,9 +89,19 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,if (conn) {rdma_set_service_type (cm_id, conn->c_tos);rdma_set_min_rnr_timer (cm_id,IB_RNR_TIMER_000_32 ); -/* XXX do we need to clean up if this fails? */ ret =rdma_resolve_route (cm_id,RDS_RDMA_RESOLVE_TIMEOUT_MS ); +if (ret) { +/* A non-zero return has the rdma_cm destroy +* the id, but it is still ic->i_cm_id, which +* the connection's shutdown would then +* disconnect and destroy again. Drop the +* connection and keep the id for that +* shutdown. +*/ +rds_conn_drop (conn); + ret =0 ; + } }break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 473/571 ASoC: stm32: spdifrx: fix synchronization state check
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
[ Upstream commit 0936bbd35a247665c64886135835faa3c3f4f29f ]
The interrupt handler uses a logical AND to check whether SPDIFRX was in the SYNC state before clearing errors. Since both SYNC (1) and ENABLE (3) are nonzero, this also treats ENABLE as SYNC (and any other non-zero value that might be added).
The logical && basically just converts this to check for != 0.
So errors occurring while SPDIFRX is enabled cause the driver to retry synch instead of disconnecting the PCM stream.
Fix is to change the logical && to equality (==) and only retry when exactly in sync state.
--- sound/soc/stm/stm32_spdifrx.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/stm/stm32_spdifrx.c +1 -1
@@ -727,7 +727,7 @@ static irqreturn_t stm32_spdifrx_isr(int irq, void *devid)if (err) {regmap_read (spdifrx->regmap,STM32_SPDIFRX_CR , &cr); - sync_state =FIELD_GET (SPDIFRX_CR_SPDIFEN_MASK , cr) && + sync_state =FIELD_GET (SPDIFRX_CR_SPDIFEN_MASK , cr) ==SPDIFRX_SPDIFEN_SYNC ;/* SPDIFRX is in STATE_STOP. Disable SPDIFRX to clear errors */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 474/571 ASoC: cs42l56: Put the Limiter Cushion control on the limiter register
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit 203436d2aeb7093290459e344e1912a418a6ebfd ]
The Limiter Cushion control writes bits 4:2 of the ALC Thresholds register. Those bits are ALCMIN, which the ALC MIN control owns. The datasheet puts CUSH at bits 4:2 of the Limit Thresholds Control register, next to LMAX, which the Limiter MAX control already uses.
So setting the limiter cushion changes the ALC minimum threshold, and the cushion itself cannot be set.
Use CS42L56_LIM_THRESHOLD_CTL.
--- sound/soc/codecs/cs42l56.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/codecs/cs42l56.c +1 -1
@@ -449,7 +449,7 @@ static const struct snd_kcontrol_new cs42l56_snd_controls[] = { 0, 0x3f, 0, 0),SOC_SINGLE_TLV ("Limiter MAX" ,CS42L56_LIM_THRESHOLD_CTL ,5 ,0x07 ,1 , alc_tlv), -SOC_SINGLE_TLV ("Limiter Cushion" ,CS42L56_ALC_THRESHOLD , +SOC_SINGLE_TLV ("Limiter Cushion" ,CS42L56_LIM_THRESHOLD_CTL ,2 ,0x07 ,1 , alc_tlv), SOC_SINGLE("NG Switch", CS42L56_NOISE_GATE_CTL, 6, 1, 1),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 475/571 ASoC: cs42l52: Fix the NG Type Switch bit
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit 8b08b98796d2da103f2432550c14a7c687e72080 ]
The NG Type Switch enum selects between "Apply Specific" and "Apply All", which is the NGALL bit. The datasheet puts NGALL at bit 7 of the Noise Gate Control register. The enum uses bit 6, which is NG, the noise gate enable owned by the NG Enable Switch. cs42l52.h names it CS42L52_NG_ENABLE_SHIFT. cs42l56 has the same Noise Gate register and puts its NG All Switch at bit 7.
So changing the noise gate type turns the noise gate on or off, and NGALL cannot be set.
Use bit 7.
--- sound/soc/codecs/cs42l52.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/codecs/cs42l52.c +1 -1
@@ -273,7 +273,7 @@ static const char * const cs42l52_ng_type_text[] = { }; static SOC_ENUM_SINGLE_DECL(ng_type_enum, - CS42L52_NOISE_GATE_CTL, 6, + CS42L52_NOISE_GATE_CTL, 7, cs42l52_ng_type_text);static const char *const left_swap_text[] = {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 476/571 ASoC: pcm3168a: Fix the DAC zero flag polarity bit
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit b26edc925c1cfa0184cd270ed81d4833db045ce0 ]
The DAC Zero Flag Polarity enum uses PCM3168A_DAC_ATSPDA_SHIFT, which is bit 6 of register 70. That bit is ATSPDA, the attenuation speed, which the DAC Volume Rate Multiplier enum already owns. The datasheet puts ZREV, the zero flag polarity, at bit 0. The header defines PCM3168A_DAC_ZREV_SHIFT for it, but nothing uses it.
So changing the zero flag polarity changes the attenuation speed, and ZREV cannot be set.
Use PCM3168A_DAC_ZREV_SHIFT.
--- sound/soc/codecs/pcm3168a.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/codecs/pcm3168a.c +1 -1
@@ -106,7 +106,7 @@ static SOC_ENUM_SINGLE_DECL(pcm3168a_dac_zf_func, PCM3168A_DAC_ATT_DEMP_ZF,static const char *const pcm3168a_pol[] = {"Active High" ,"Active Low" }; static SOC_ENUM_SINGLE_DECL(pcm3168a_dac_zf_pol, PCM3168A_DAC_ATT_DEMP_ZF, - PCM3168A_DAC_ATSPDA_SHIFT, pcm3168a_pol); + PCM3168A_DAC_ZREV_SHIFT, pcm3168a_pol);static const char *const pcm3168a_con[] = {"Differential" ,"Single-Ended" };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 477/571 ASoC: max98371: Fix the Speaker DHT Min Volume bits
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit f7934340c56a84fc1b246ebf6b2e806d775f3b54 ]
Register 0x31 holds two 4-bit fields. The datasheet puts SPK_GAIN_MIN at bits 7:4 and DHT_VROT_PNT at bits 3:0. The Speaker DHT Min Volume and Speaker DHT Rotation Volume controls both use bits 3:0.
So setting the minimum speaker gain changes the DHT rotation point, and SPK_GAIN_MIN cannot be set.
Move Speaker DHT Min Volume to bits 7:4.
--- sound/soc/codecs/max98371.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/codecs/max98371.c +1 -1
@@ -166,7 +166,7 @@ static const struct snd_kcontrol_new max98371_snd_controls[] = { 0, (1<<MAX98371_DHT_MAX_WIDTH)-1, 0, max98371_dht_max_gain),SOC_SINGLE_TLV ("Speaker DHT Min Volume" ,MAX98371_DHT_GAIN , -0 , (1 <<MAX98371_DHT_GAIN_WIDTH )-1 ,0 , +4 , (1 <<MAX98371_DHT_GAIN_WIDTH )-1 ,0 , max98371_dht_min_gain), SOC_SINGLE_TLV("Speaker DHT Rotation Volume", MAX98371_DHT_GAIN, 0, (1<<MAX98371_DHT_ROT_WIDTH)-1, 0,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 478/571 ASoC: wm8978: Fix the 128x oversampling switch bits
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit d0567ca9a2faa33efbe5ae84ef7b86423a93bffd ]
The DAC and ADC 128x Oversampling Switches use bit 5 of R10 and R14. Table 66 of the WM8978 datasheet puts DACOSR128 and ADCOSR128 at bit 3 of those registers.
In R14, bit 5 is inside HPFCUT[6:4], which the High Pass Cut Off control owns. So turning on ADC oversampling changes the high pass cut-off, and the oversampling bit cannot be set. In R10, bit 5 is reserved, so the DAC switch has no effect.
Use bit 3 for both.
--- sound/soc/codecs/wm8978.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wm8978.c +2 -2
@@ -255,9 +255,9 @@ static const struct snd_kcontrol_new wm8978_snd_controls[] = {/* DAC / ADC oversampling */ SOC_SINGLE ("DAC 128x Oversampling Switch" ,WM8978_DAC_CONTROL , -5 ,1 ,0 ), +3 ,1 ,0 ),SOC_SINGLE ("ADC 128x Oversampling Switch" ,WM8978_ADC_CONTROL , - 5, 1, 0), + 3, 1, 0), };/* Mixer #1: Output (OUT1, OUT2) Mixer: mix AUX, Input mixer output and DAC */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 479/571 ASoC: nau8822: Fix the 128x oversampling switch bits
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit 4db45fc1da3d62d0fa6e8f1e457ae92e8741ed07 ]
The DAC and ADC 128x Oversampling Switches use bit 5 of R10 and R14. The NAU8822 datasheet register map puts DACOS and ADCOS at bit 3 of those registers.
In R14, bit 5 is inside HPF[6:4], which the High Pass Cut Off control owns. So turning on ADC oversampling changes the high pass cut-off, and the oversampling bit cannot be set. In R10, bit 5 is reserved, so the DAC switch has no effect.
Use bit 3 for both.
--- sound/soc/codecs/nau8822.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/nau8822.c +2 -2
@@ -379,9 +379,9 @@ static const struct snd_kcontrol_new nau8822_snd_controls[] = { NAU8822_REG_RIGHT_ADC_BOOST_CONTROL, 0, 7, 0, boost_tlv), SOC_SINGLE("DAC 128x Oversampling Switch", - NAU8822_REG_DAC_CONTROL, 5, 1, 0), + NAU8822_REG_DAC_CONTROL, 3, 1, 0), SOC_SINGLE("ADC 128x Oversampling Switch", - NAU8822_REG_ADC_CONTROL, 5, 1, 0), + NAU8822_REG_ADC_CONTROL, 3, 1, 0), };/* LMAIN and RMAIN Mixer */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 480/571 netlink: remove netlink_broadcast_filtered
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Westphal <[email protected]>
[ Upstream commit 549017aa1bb7ec19a1e24e7f65480a1c2e76b90e ]
No users in tree since commit a3498436b3a0 ("netns: restrict uevents"), so remove this functionality.
Stable-dep-of: 8bf659bd54e1 ("netlink: reset skb headers before unicast and multicast filtering")
--- include/linux/netlink.h | 4 ---- net/netlink/af_netlink.c | 23 ++--------------------- 2 files changed, 2 insertions(+), 25 deletions(-)
include/linux/netlink.h +0 -4
@@ -156,10 +156,6 @@ bool netlink_strict_get_check(struct sk_buff *skb);int netlink_unicast (struct sock *ssk,struct sk_buff *skb,__u32 portid,int nonblock);int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,__u32 portid,__u32 group,gfp_t allocation); -int netlink_broadcast_filtered (struct sock *ssk,struct sk_buff *skb, -__u32 portid,__u32 group,gfp_t allocation, -int (*filter)(struct sock *dsk,struct sk_buff *skb,void *data), -void *filter_data);int netlink_set_err (struct sock *ssk,__u32 portid,__u32 group,int code);int netlink_register_notifier (struct notifier_block *nb);int netlink_unregister_notifier (struct notifier_block *nb);
net/netlink/af_netlink.c +2 -21
@@ -1413,8 +1413,6 @@ struct netlink_broadcast_data {int delivered;gfp_t allocation;struct sk_buff *skb, *skb2; -int (*tx_filter)(struct sock *dsk,struct sk_buff *skb,void *data); -void *tx_data; }; static void do_one_broadcast(struct sock *sk,
@@ -1468,11 +1466,6 @@ static void do_one_broadcast(struct sock *sk, p->delivery_failure =1 ; goto out; } -if (p->tx_filter && p->tx_filter (sk, p->skb2, p->tx_data)) { -kfree_skb (p->skb2); - p->skb2 =NULL ; - goto out; - }if (sk_filter (sk, p->skb2)) {kfree_skb (p->skb2); p->skb2 =NULL ;
@@ -1500,10 +1493,8 @@ static void do_one_broadcast(struct sock *sk,sock_put (sk); } -int netlink_broadcast_filtered (struct sock *ssk,struct sk_buff *skb,u32 portid, -u32 group,gfp_t allocation, -int (*filter)(struct sock *dsk,struct sk_buff *skb,void *data), -void *filter_data) +int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,u32 portid, +u32 group,gfp_t allocation) {struct net *net =sock_net (ssk);struct netlink_broadcast_data info;
@@ -1522,8 +1513,6 @@ int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid info.allocation = allocation; info.skb = skb; info.skb2 =NULL ; - info.tx_filter = filter; - info.tx_data = filter_data;/* While we sleep in clone, do not allow to change socket list */
@@ -1549,14 +1538,6 @@ int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid }return -ESRCH ; } -EXPORT_SYMBOL (netlink_broadcast_filtered); - -int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,u32 portid, -u32 group,gfp_t allocation) -{ -return netlink_broadcast_filtered (ssk, skb, portid, group, allocation, -NULL ,NULL ); -}EXPORT_SYMBOL (netlink_broadcast);struct netlink_set_err_data {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 481/571 netlink: Reverse the patch which removed filtering
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anjali Kulkarni <[email protected]>
[ Upstream commit a3377386b56420d78a4c0a931a40f9a25c3ca2bd ]
To use filtering at the connector & cn_proc layers, we need to enable filtering in the netlink layer. This reverses the patch which removed netlink filtering - commit ID for that patch:549017aa1bb7 (netlink: remove netlink_broadcast_filtered).
Stable-dep-of: 8bf659bd54e1 ("netlink: reset skb headers before unicast and multicast filtering")
--- include/linux/netlink.h | 5 +++++ net/netlink/af_netlink.c | 27 +++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-)
include/linux/netlink.h +5 -0
@@ -156,6 +156,11 @@ bool netlink_strict_get_check(struct sk_buff *skb);int netlink_unicast (struct sock *ssk,struct sk_buff *skb,__u32 portid,int nonblock);int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,__u32 portid,__u32 group,gfp_t allocation); +int netlink_broadcast_filtered (struct sock *ssk,struct sk_buff *skb, +__u32 portid,__u32 group,gfp_t allocation, +int (*filter)(struct sock *dsk, +struct sk_buff *skb,void *data), +void *filter_data);int netlink_set_err (struct sock *ssk,__u32 portid,__u32 group,int code);int netlink_register_notifier (struct notifier_block *nb);int netlink_unregister_notifier (struct notifier_block *nb);
net/netlink/af_netlink.c +25 -2
@@ -1413,6 +1413,8 @@ struct netlink_broadcast_data {int delivered;gfp_t allocation;struct sk_buff *skb, *skb2; +int (*tx_filter)(struct sock *dsk,struct sk_buff *skb,void *data); +void *tx_data; }; static void do_one_broadcast(struct sock *sk,
@@ -1466,6 +1468,13 @@ static void do_one_broadcast(struct sock *sk, p->delivery_failure =1 ; goto out; } + +if (p->tx_filter && p->tx_filter (sk, p->skb2, p->tx_data)) { +kfree_skb (p->skb2); + p->skb2 =NULL ; + goto out; + } +if (sk_filter (sk, p->skb2)) {kfree_skb (p->skb2); p->skb2 =NULL ;
@@ -1493,8 +1502,12 @@ static void do_one_broadcast(struct sock *sk,sock_put (sk); } -int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,u32 portid, -u32 group,gfp_t allocation) +int netlink_broadcast_filtered (struct sock *ssk,struct sk_buff *skb, +u32 portid, +u32 group,gfp_t allocation, +int (*filter)(struct sock *dsk, +struct sk_buff *skb,void *data), +void *filter_data) {struct net *net =sock_net (ssk);struct netlink_broadcast_data info;
@@ -1513,6 +1526,8 @@ int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid, info.allocation = allocation; info.skb = skb; info.skb2 =NULL ; + info.tx_filter = filter; + info.tx_data = filter_data;/* While we sleep in clone, do not allow to change socket list */
@@ -1538,6 +1553,14 @@ int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid, }return -ESRCH ; } +EXPORT_SYMBOL (netlink_broadcast_filtered); + +int netlink_broadcast (struct sock *ssk,struct sk_buff *skb,u32 portid, +u32 group,gfp_t allocation) +{ +return netlink_broadcast_filtered (ssk, skb, portid, group, allocation, +NULL ,NULL ); +}EXPORT_SYMBOL (netlink_broadcast);struct netlink_set_err_data {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 482/571 netlink: reset skb headers before unicast and multicast filtering
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
[ Upstream commit 8bf659bd54e1f00e34cf5244b1d289c506fa47c0 ]
Socket filters can use SKF_NET_OFF and SKF_LL_OFF to read relative to an skb's network and MAC headers. Netlink producers may reserve headroom without resetting those headers, allowing a receiving socket's filter to read data before the initialized message.
For example, IWPM HELLO replies are allocated with dev_alloc_skb(), which reserves NET_SKB_PAD bytes. An unprivileged NETLINK_RDMA user can attach a classic socket filter and disclose this headroom through the length of the delivered reply. The resets in netlink_dump() do not help because IWPM sends a separately allocated skb through netlink_unicast().
Reset both headers before running the receiver's filter in unicast and broadcast delivery, as is already done for dump skbs. This also covers other netlink producers that reserve headroom without changing their allocation or message-building code.
--- net/netlink/af_netlink.c | 4 ++++ 1 file changed, 4 insertions(+)
net/netlink/af_netlink.c +4 -0
@@ -1339,6 +1339,8 @@ int netlink_unicast(struct sock *ssk, struct sk_buff *skb,if (netlink_is_kernel (sk))return netlink_unicast_kernel (sk, skb, ssk); +skb_reset_network_header (skb); +skb_reset_mac_header (skb);if (sk_filter (sk, skb)) { err = skb->len;kfree_skb (skb);
@@ -1475,6 +1477,8 @@ static void do_one_broadcast(struct sock *sk, goto out; } +skb_reset_network_header (p->skb2); +skb_reset_mac_header (p->skb2);if (sk_filter (sk, p->skb2)) {kfree_skb (p->skb2); p->skb2 =NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 483/571 nios2: fix __wsum type degradation in csum_fold()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Keith Busch <[email protected]>
[ Upstream commit b963f2345fa20417401c51a69dedb6a58eea33a9 ]
csum_fold() shifts a bitwise __wsum type, which sparse reports as "restricted __wsum degrades to integer". Sparse only checks the body of a static inline once something instantiates it, so this went unnoticed until a recent block layer change added the first csum_fold() caller to a file built on this architecture.
Force cast to a __u32 for the shift, as the other architectures do.
--- arch/nios2/include/asm/checksum.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/nios2/include/asm/checksum.h +1 -1
@@ -27,7 +27,7 @@ static inline __sum16 csum_fold(__wsum sum) "add %0, %0, r8\n" "nor %0, %0, %0\n" : "=r" (sum) - : "r" (sum << 16), "0" (sum) + : "r" ((__force u32)sum << 16), "0" (sum) : "r8");return (__force __sum16 ) sum; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 484/571 scsi: st: Save the visited block for the partition the drive is in
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Laurence Oberman <[email protected]>
[ Upstream commit c9e9f024dd4f61f0f6636c9f2ed0830f87060e11 ]
set_location() saves the current tape location before switching partitions, so that switch_partition() can return to it later. It reads the location with READ POSITION but stores it in the st_partstat of STp->partition, ignoring the partition the drive reports.
The two differ after a device reset. When the reset is recovered with MTREW, MTSEEK or MTEOM, st_ioctl() sets STp->partition = 0 and calls switch_partition() to return to STp->new_partition. A drive that was in partition 1 is still there, so set_location() files the partition 1 position under partition 0. The next switch to partition 0 locates to that block: if partition 0 holds less data, MTSETPART fails with EIO (BLANK CHECK), otherwise the tape is silently positioned at the wrong block.
IBM ULTRIUM-TD5 (LTO-5), LU reset in partition 1 at block 1025:
st 12:0:0:0: [st0] Visited block 1025 for partition 0 saved.
...
st 12:0:0:0: [st0] Setting block to 1025 and partition to 0. st 12:0:0:0: [st0] Error: 402, cmd: 2b 2 0 0 0 4 st 12:0:0:0: [st0] Sense Key : Blank Check [current] st 12:0:0:0: [st0] Add. Sense: End-of-data detected
Store the location in the st_partstat of the partition reported by READ POSITION. With the fix:
st 12:0:0:0: [st0] Visited block 1025 for partition 1 saved.
This is a pre-existing issue. It was not caught when testing the recent st reset series because the partition test was only run on scsi_debug:
on the LTO drive it was skipped, since can-partitions is off in the test harness's stinit.conf, as is normal for LTO. scsi_debug hides the problem because its emulated tape returns to the beginning of partition 0 on an LU reset. It was found while validating a backport of that series to RHEL 9.8, when the partition tests were run on real hardware with can-partitions enabled. The same failure then reproduced on unmodified RHEL 9.8 and on upstream, and the fix makes the test pass on v7.3-rc3 and RHEL 9.8 with an LTO-5.
The harness (https://gitlab.com/loberman/tapetest, test X03) now refuses to silently skip the partition tests on hardware.
--- drivers/scsi/st.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/scsi/st.c +10 -4
@@ -3184,14 +3184,20 @@ static int set_location(struct scsi_tape *STp, unsigned int block, int partition partition >= ST_NBR_PARTITIONS)return (-EINVAL );if (partition != STp->partition) { -if (get_location (STp, &blk, &p,1 )) +/* +* Save the location for the partition the drive reports, +* not for STp->partition: after a reset STp->partition may +* not match the partition the drive is in. +*/ +if (get_location (STp, &blk, &p,1 ) || + p <0 || p >=ST_NBR_PARTITIONS ) STps->last_block_valid =0 ;else { - STps->last_block_valid =1 ; - STps->last_block_visited = blk; + STp->ps[p].last_block_valid =1 ; + STp->ps[p].last_block_visited = blk;DEBC_printk (STp,"Visited block %d for " "partition %d saved.\n" , - blk, STp->partition); + blk, p); } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 485/571 scsi: target: iscsi: Fix race in discovery auth updates
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linfeng Sun <[email protected]>
[ Upstream commit e15b81f602edbdee39c335546f25486a1747f3f0 ]
Separate configfs opens can concurrently update the discovery AuthMethod parameter. Both callers may free the same value in iscsi_update_param_value(), causing a double-free.
Protect the lookup and replacement with the discovery TPG access lock, as used by the other TPG configfs parameter updates.
--- drivers/target/iscsi/iscsi_target_configfs.c | 26 ++++++++++++++------ 1 file changed, 19 insertions(+), 7 deletions(-)
drivers/target/iscsi/iscsi_target_configfs.c +19 -7
@@ -1284,17 +1284,24 @@ static ssize_t iscsi_disc_enforce_discovery_auth_store(struct config_item *item,return -EINVAL ; } +if (iscsit_get_tpg (discovery_tpg) <0 ) +return -EINVAL ; + param =iscsi_find_param_from_key (AUTHMETHOD , discovery_tpg->param_list); -if (!param) -return -EINVAL ; +if (!param) { + err = -EINVAL ; + goto out; + }if (op) {/* * Reset the AuthMethod key to CHAP. */ -if (iscsi_update_param_value (param,CHAP ) <0 ) -return -EINVAL ; +if (iscsi_update_param_value (param,CHAP ) <0 ) { + err = -EINVAL ; + goto out; + } discovery_tpg->tpg_attrib.authentication =1 ; iscsit_global->discovery_acl.node_auth.enforce_discovery_auth =1 ;
@@ -1305,8 +1312,10 @@ static ssize_t iscsi_disc_enforce_discovery_auth_store(struct config_item *item,/* * Reset the AuthMethod key to CHAP,None */ -if (iscsi_update_param_value (param,"CHAP,None" ) <0 ) -return -EINVAL ; +if (iscsi_update_param_value (param,"CHAP,None" ) <0 ) { + err = -EINVAL ; + goto out; + } discovery_tpg->tpg_attrib.authentication =0 ; iscsit_global->discovery_acl.node_auth.enforce_discovery_auth =0 ;
@@ -1315,7 +1324,10 @@ static ssize_t iscsi_disc_enforce_discovery_auth_store(struct config_item *item, " Discovery TPG\n"); } -return count; + err = count; +out: +iscsit_put_tpg (discovery_tpg); +return err; }CONFIGFS_ATTR (iscsi_disc_, enforce_discovery_auth);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 486/571 ocfs2/dlm: Protect the recovery list during debugfs reads
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 4c435828932bf46f29860e4a0375bcae101b778a ]
Recovery participant records must remain alive while debug_state_print() walks reco.node_data and formats their fields. The formatter holds dlm->spinlock, but the recovery participant list is protected by dlm_reco_state_lock. In particular, dlm_destroy_recovery_area() detaches the list under dlm_reco_state_lock and frees the detached records after releasing it. A concurrent debugfs open can therefore read freed memory.
Protect the participant traversal and field reads in debug_state_print() with dlm_reco_state_lock, matching the existing list writers. This also serializes the traversal against list_add_tail() during recovery-area initialization. Make the existing lock available to the debug code through dlmcommon.h; the lock remains internal to the OCFS2 DLM module.
Release dlm->spinlock after formatting the other domain state and before acquiring dlm_reco_state_lock, so the debug reader does not nest the two locks. Leave recovery list insertion, detachment and freeing unchanged.
KASAN report as below:
BUG: KASAN: slab-use-after-free in debug_state_open+0x1169/0x12d0
Read of size 4 at addr ffff88810662ef80 by task dlm-state-stres/896
CPU: 1 UID: 0 PID: 896 Comm: dlm-state-stres Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? debug_state_open+0x1169/0x12d0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? debug_state_open+0x1169/0x12d0
kasan_report+0xe0/0x110
? debug_state_open+0x1169/0x12d0
debug_state_open+0x1169/0x12d0
? __pfx_debug_state_open+0x10/0x10
full_proxy_open_regular+0x193/0x310
do_dentry_open+0x595/0x12d0
? __pfx_full_proxy_open_regular+0x10/0x10
vfs_open_consume+0xd1/0x400
? srso_alias_return_thunk+0x5/0xfbef5
path_openat+0x18d0/0x2020
? __pfx_path_openat+0x10/0x10
do_file_open+0x21e/0x470
? __pfx_do_file_open+0x10/0x10
? _raw_spin_unlock+0x23/0x40
? srso_alias_return_thunk+0x5/0xfbef5
? alloc_fd+0x3a6/0x6b0
do_sys_openat2+0xf4/0x1b0
? __pfx_do_sys_openat2+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __fput+0x5b5/0xa60
__x64_sys_openat+0x136/0x1e0
? __pfx___x64_sys_openat+0x10/0x10
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
[Register dump omitted.]
</TASK>
Allocated by task 880:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
dlm_remaster_locks+0x147/0x1d90
dlm_do_recovery+0xde1/0x1580
dlm_recovery_thread+0x109/0x300
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 880:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
dlm_destroy_recovery_area+0x285/0x460
dlm_remaster_locks+0x17c4/0x1d90
dlm_do_recovery+0xde1/0x1580
dlm_recovery_thread+0x109/0x300
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810662ef80
which belongs to the cache kmalloc-32 of size 32
The buggy address is located 0 bytes inside of
freed 32-byte region [ffff88810662ef80, ffff88810662efa0)[Page and memory-state dumps omitted.]
--- fs/ocfs2/dlm/dlmcommon.h | 2 ++ fs/ocfs2/dlm/dlmdebug.c | 5 ++++- fs/ocfs2/dlm/dlmrecovery.c | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-)
fs/ocfs2/dlm/dlmcommon.h +2 -0
@@ -435,6 +435,8 @@ enum { DLM_DEREF_LOCKRES_DONE = 522, }; +extern spinlock_t dlm_reco_state_lock; +struct dlm_reco_node_data {int state;
fs/ocfs2/dlm/dlmdebug.c +4 -1
@@ -792,8 +792,11 @@ static int debug_state_print(struct dlm_ctxt *dlm, char *buf, int len) buf + out, len - out); out +=scnprintf (buf + out, len - out,"\n" ); +spin_unlock (&dlm->spinlock); +/* Recovery Node State: */ out +=scnprintf (buf + out, len - out,"Recovery Node State:\n" ); +spin_lock (&dlm_reco_state_lock);list_for_each_entry (node, &dlm->reco.node_data, list) {switch (node->state) {case DLM_RECO_NODE_DATA_INIT :
@@ -825,7 +828,7 @@ static int debug_state_print(struct dlm_ctxt *dlm, char *buf, int len) node->node_num, state); } -spin_unlock (&dlm->spinlock); +spin_unlock (&dlm_reco_state_lock);return out; }
fs/ocfs2/dlm/dlmrecovery.c +1 -1
@@ -80,7 +80,7 @@ static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,static u64 dlm_get_next_mig_cookie (void ); -static DEFINE_SPINLOCK (dlm_reco_state_lock); +DEFINE_SPINLOCK (dlm_reco_state_lock);static DEFINE_SPINLOCK (dlm_mig_cookie_lock);static u64 dlm_mig_cookie =1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 487/571 samples: pidfd: fix userprogs typo
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
[ Upstream commit f1365f97fb7498d805981102eee22d362ae643f2 ]
The Makefile adds pidfd-metadata to "usertprogs-always-y", which kbuild does not know, so the sample has not been built since the conversion to userprogs, even with CONFIG_SAMPLE_PIDFD=y.
Fix the variable name. pidfd-metadata.c builds without warnings with gcc and clang for x86_64 and arm64.
--- samples/pidfd/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
samples/pidfd/Makefile +1 -1
@@ -1,4 +1,4 @@ # SPDX-License-Identifier: GPL-2.0 -usertprogs-always-y += pidfd-metadata +userprogs-always-y += pidfd-metadata userccflags += -I usr/include
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 488/571 clone: add CLONE_AUTOREAP
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit 12ae2c81b21cfaa193db2faf035d495807edc3a7 ]
Add a new clone3() flag CLONE_AUTOREAP that makes a child process auto-reap on exit without ever becoming a zombie. This is a per-process property in contrast to the existing auto-reap mechanism via SA_NOCLDWAIT or SIG_IGN for SIGCHLD which applies to all children of a given parent.
Currently the only way to automatically reap children is to set SA_NOCLDWAIT or SIG_IGN on SIGCHLD. This is a parent-scoped property affecting all children which makes it unsuitable for libraries or applications that need selective auto-reaping of specific children while still being able to wait() on others.
CLONE_AUTOREAP stores an autoreap flag in the child's signal_struct. When the child exits do_notify_parent() checks this flag and causes exit_notify() to transition the task directly to EXIT_DEAD. Since the flag lives on the child it survives reparenting: if the original parent exits and the child is reparented to a subreaper or init the child still auto-reaps when it eventually exits.
CLONE_AUTOREAP can be combined with CLONE_PIDFD to allow the parent to monitor the child's exit via poll() and retrieve exit status via PIDFD_GET_INFO. Without CLONE_PIDFD it provides a fire-and-forget pattern where the parent simply doesn't care about the child's exit status. No exit signal is delivered so exit_signal must be zero.
CLONE_AUTOREAP is rejected in combination with CLONE_PARENT. If a CLONE_AUTOREAP child were to clone(CLONE_PARENT) the new grandchild would inherit exit_signal == 0 from the autoreap parent's group leader but without signal->autoreap. This grandchild would become a zombie that never sends a signal and is never autoreaped - confusing and arguably broken behavior.
The flag is not inherited by the autoreap process's own children. Each child that should be autoreaped must be explicitly created with CLONE_AUTOREAP.
Stable-dep-of: 28d2905d77bc ("exit: fix lost-update race on the child_subreaper bitfields")
--- include/linux/sched/signal.h | 1 + include/uapi/linux/sched.h | 5 +++-- kernel/fork.c | 17 ++++++++++++++++- kernel/ptrace.c | 3 ++- kernel/signal.c | 4 ++++ 5 files changed, 26 insertions(+), 4 deletions(-)
include/linux/sched/signal.h +1 -0
@@ -121,6 +121,7 @@ struct signal_struct {*/ unsigned int is_child_subreaper:1; unsigned int has_child_subreaper:1; + unsigned int autoreap:1;#ifdef CONFIG_POSIX_TIMERS
include/uapi/linux/sched.h +3 -2
@@ -34,8 +34,9 @@#define CLONE_IO 0x80000000/* Clone io context */ /* Flags for the clone3() syscall. */ -#define CLONE_CLEAR_SIGHAND 0x100000000ULL/* Clear any signal handler and reset to SIG_DFL. */ -#define CLONE_INTO_CGROUP 0x200000000ULL/* Clone into a specific cgroup given the right permissions. */ +#define CLONE_CLEAR_SIGHAND (1ULL << 32)/* Clear any signal handler and reset to SIG_DFL. */ +#define CLONE_INTO_CGROUP (1ULL << 33)/* Clone into a specific cgroup given the right permissions. */ +#define CLONE_AUTOREAP (1ULL << 34)/* Auto-reap child on exit. */ /* * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
kernel/fork.c +16 -1
@@ -2105,6 +2105,18 @@ static __latent_entropy struct task_struct *copy_process(return ERR_PTR (-EINVAL ); } +if (clone_flags &CLONE_AUTOREAP ) { +if (clone_flags &CLONE_THREAD ) +return ERR_PTR (-EINVAL ); +if (clone_flags &CLONE_PARENT ) +return ERR_PTR (-EINVAL ); +if (args->exit_signal) +return ERR_PTR (-EINVAL ); + } + +if ((clone_flags &CLONE_PARENT ) && current->signal->autoreap) +return ERR_PTR (-EINVAL ); +/* * Force any signals received before this point to be delivered * before the fork happens. Collect up signals sent to multiple
@@ -2479,6 +2491,8 @@ static __latent_entropy struct task_struct *copy_process(*/ p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper || p->real_parent->signal->is_child_subreaper; +if (clone_flags &CLONE_AUTOREAP ) + p->signal->autoreap =1 ;list_add_tail (&p->sibling, &p->real_parent->children);list_add_tail_rcu (&p->tasks, &init_task.tasks);attach_pid (p,PIDTYPE_TGID );
@@ -2903,7 +2917,8 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs) {/* Verify that no unknown flags are passed along. */ if (kargs->flags & - ~(CLONE_LEGACY_FLAGS |CLONE_CLEAR_SIGHAND |CLONE_INTO_CGROUP )) + ~(CLONE_LEGACY_FLAGS |CLONE_CLEAR_SIGHAND |CLONE_INTO_CGROUP | +CLONE_AUTOREAP ))return false;/*
kernel/ptrace.c +2 -1
@@ -584,7 +584,8 @@ static bool __ptrace_detach(struct task_struct *tracer, struct task_struct *p)if (!dead &&thread_group_empty (p)) {if (!same_thread_group (p->real_parent, tracer)) dead =do_notify_parent (p, p->exit_signal); -else if (ignoring_children (tracer->sighand)) { +else if (ignoring_children (tracer->sighand) || + p->signal->autoreap) {__wake_up_parent (p, tracer); dead = true; }
kernel/signal.c +4 -0
@@ -2121,6 +2121,10 @@ bool do_notify_parent(struct task_struct *tsk, int sig)if (psig->action[SIGCHLD -1 ].sa.sa_handler ==SIG_IGN ) sig =0 ; } +if (!tsk->ptrace && tsk->signal->autoreap) { + autoreap = true; + sig =0 ; + }/* * Send with __send_signal as si_pid and si_uid are in the * parent's namespaces.
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 489/571 exit: fix lost-update race on the child_subreaper bitfields
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
[ Upstream commit 28d2905d77bc2e7c20260a6bc6b4179bdf95cb06 ]
is_child_subreaper, has_child_subreaper, autoreap and, with CONFIG_POSIX_TIMERS=y, timer_create_restore_ids are 1-bit fields that share one memory location in struct signal_struct. A store to any of them is a read-modify-write of the whole word, and three of the stores run without a common lock:
- PR_SET_CHILD_SUBREAPER writes me->signal->is_child_subreaper with no lock held.
- propagate_has_child_subreaper(), run by walk_process_tree() from the same prctl in an ancestor, writes p->signal->has_child_subreaper of every descendant p under read_lock(&tasklist_lock), which does not exclude the other writers.
- PR_TIMER_CREATE_RESTORE_IDS writes
current->signal->timer_create_restore_ids with no lock held.
When a process calls prctl(PR_SET_CHILD_SUBREAPER, 1) while an ancestor's PR_SET_CHILD_SUBREAPER walk visits it, or while another thread of the same process calls prctl(PR_TIMER_CREATE_RESTORE_IDS), the read-modify-write sequences interleave and one of the bits is silently lost:
- If has_child_subreaper is lost, the process's orphaned descendants are reparented straight to init when it exits: find_new_reaper() tests father->signal->has_child_subreaper first and never looks for the ancestor subreaper. The service manager that registered as the subreaper never gets SIGCHLD for them and cannot wait() on them.
- If is_child_subreaper is lost, the prctl returned 0 but the process is not a subreaper: orphans of its descendants skip it and are reparented to the next subreaper up or to init. PR_GET_CHILD_SUBREAPER reads back 0.
- If timer_create_restore_ids is lost, the prctl returned 0 but timer_create() does not restore the requested timer ids (or keeps restoring them after _OFF), and _GET reads back the old value.
Documentation/memory-barriers.txt requires all fields of one bitfield to be protected by one lock for exactly this reason. No lock is taken or documented for these flags, and the prctls need no privilege, so any process can hit the race against its own ancestors or descendants, or between two of its own threads.
Make is_child_subreaper and has_child_subreaper separate bool members. Each store then has its own memory location and no read-modify-write of a neighbour. The readers and their locking are unchanged.
autoreap stays a bit-field and so shares a memory location only with timer_create_restore_ids. That pair is race-free: autoreap is stored exactly once, in copy_process() before the new signal_struct is reachable by any other task, and timer_create_restore_ids is only stored to the signal_struct of an already running process.
--- include/linux/sched/signal.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
include/linux/sched/signal.h +2 -2
@@ -119,8 +119,8 @@ struct signal_struct {* process will inherit a flag if they should look for a * child_subreaper process at exit. */ - unsigned int is_child_subreaper:1; - unsigned int has_child_subreaper:1; +bool is_child_subreaper; +bool has_child_subreaper; unsigned int autoreap:1;#ifdef CONFIG_POSIX_TIMERS
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 490/571 pipe: preserve existing fasync readers on writer setup failure
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
[ Upstream commit 40bb03d3ea6f6a915218508819ecc4d7a7fa260d ]
F_SETFL and FIOASYNC decide whether to invoke ->fasync() before pipe_fasync() takes pipe->mutex. Two enables of one O_RDWR FIFO can therefore both enter the callback.
fasync_helper() allocates before checking for an existing entry. If the first enable installs both entries, a second enable can update the reader entry and then fail the allocation for the writer entry. The error path removes the pre-existing reader entry, clearing FASYNC while the writer entry remains registered. __fput() then skips ->fasync(), so a later pipe notification can dereference the freed file or its f_owner. An unprivileged memory-pressure reproducer triggers a KASAN slab-use-after-free in send_sigio() through this path.
Keep the reader helper's result and undo the registration only if this call added it. The pipe mutex serializes changes to both lists, so a failed new registration still removes its reader, while a failed duplicate preserves the existing registrations and FASYNC. Successful duplicate enables continue to update fa_fd as before.
--- fs/pipe.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/pipe.c +4 -2
@@ -749,9 +749,11 @@ pipe_fasync(int fd, struct file *filp, int on)if (filp->f_mode &FMODE_READ ) retval =fasync_helper (fd, filp, on, &pipe->fasync_readers);if ((filp->f_mode &FMODE_WRITE ) && retval >=0 ) { +int read_ret = retval; + retval =fasync_helper (fd, filp, on, &pipe->fasync_writers); -if (retval <0 && (filp->f_mode &FMODE_READ )) -/* this can happen only if on == T */ +/* Undo only a reader entry added by this call. */ +if (retval <0 && read_ret >0 )fasync_helper (-1 , filp,0 , &pipe->fasync_readers); }__pipe_unlock (pipe);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 491/571 netlink: avoid hashing the network namespace pointer
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
[ Upstream commit f88bb3606e4bd11ee035b682cddc2999e604609a ]
The netlink rhashtable key includes a raw struct net pointer and a user-controlled port ID. Both /proc/net/netlink and socket diagnostics expose the table's bucket order. By binding and rebinding chosen NETLINK_USERSOCK port IDs, an unprivileged reader can distinguish equal buckets and recover the low bits of the Jenkins hash. Its 32-bit seed and the limited set of kernel-image slides can then be searched offline to recover the address of init_net.
Use the namespace's unique, non-address net_cookie in the comparison key instead. It is assigned before the per-net initializers run and remains unchanged for the namespace's lifetime. The lookup key and object hash are still built by netlink_compare_arg_init(), keeping lookup, insertion, removal and rehashing consistent while preserving namespace separation. Neither public table walker needs to change.
Reading the socket's namespace cookie in netlink_compare() is safe under RCU, including during namespace teardown. netlink_release() removes the socket from the hash table and defers its final put with call_rcu(). cleanup_net() runs the per-net exit methods and waits for outstanding RCU callbacks with rcu_barrier() before freeing namespace storage.
Unlike ns.ns_id, net_cookie is also available and initialized during setup_net() in older stable kernels, making the change straightforward to backport to v5.15 and later.
--- net/netlink/af_netlink.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
net/netlink/af_netlink.c +3 -3
@@ -463,7 +463,7 @@ netlink_unlock_table(void)struct netlink_compare_arg { -possible_net_t pnet; +u64 net_cookie;u32 portid; };
@@ -478,14 +478,14 @@ static inline int netlink_compare(struct rhashtable_compare_arg *arg,const struct netlink_sock *nlk = ptr;return nlk->portid != x->portid || - !net_eq (sock_net (&nlk->sk),read_pnet (&x->pnet)); +sock_net (&nlk->sk)->net_cookie != x->net_cookie; }static void netlink_compare_arg_init (struct netlink_compare_arg *arg,struct net *net,u32 portid) {memset (arg,0 ,sizeof (*arg)); -write_pnet (&arg->pnet, net); + arg->net_cookie = net->net_cookie; arg->portid = portid; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 492/571 autofs: ignore notification errors from a replaced pipe
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sung Byeongchan <[email protected]>
commit 65676cd4203c0e41a94caf54080a7f0a95434bda upstream.
autofs_notify_daemon() takes a reference to the current notification pipe under wq_mutex, then drops the mutex before writing the request. The write can block while the daemon enters catatonic mode and installs a replacement pipe.
If the old pipe's reader is then closed, the delayed write returns -EPIPE and the generic error path enters catatonic mode again. That transition acts on the current superblock state, closes the replacement pipe, and releases the new daemon generation's wait queues.
Only enter catatonic mode when the pipe which failed is still the current pipe. Factor the already-locked transition so the identity check and state change are atomic with respect to another replacement.
This was reproduced on v7.3-rc5-337-gff47652a4b66c in a local QEMU guest. An unprivileged UID 65534 lookup filled the old packet pipe before a normal CATATONIC/SETPIPEFD restart. On the unmodified kernel, the new pipe received HUP and both a pending victim lookup and a later lookup failed with ENOENT in two out of two fresh-mount runs.
With this change, the new pipe remained active, received an intact 304-byte request, and both victim lookups completed in two out of two runs. Normal lookup and restart-without-a-blocked-writer controls passed. No KASAN, oops, refcount, or lock diagnostic was observed. A source reproducer and complete local logs are available privately on request.
The demonstrated impact is limited to denial of a shared autofs service during a legitimate daemon restart. No memory corruption, information leak, privilege escalation, or code execution primitive was observed.
--- fs/autofs/waitq.c | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-)
fs/autofs/waitq.c +19 -6
@@ -12,15 +12,13 @@*/ static autofs_wqt_t autofs_next_wait_queue =1 ; -void autofs_catatonic_mode (struct autofs_sb_info *sbi) +static void autofs_catatonic_mode_locked (struct autofs_sb_info *sbi) {struct autofs_wait_queue *wq, *nwq; -mutex_lock (&sbi->wq_mutex); -if (sbi->flags &AUTOFS_SBI_CATATONIC ) { -mutex_unlock (&sbi->wq_mutex); +lockdep_assert_held (&sbi->wq_mutex); +if (sbi->flags &AUTOFS_SBI_CATATONIC )return ; - }pr_debug ("entering catatonic mode\n" );
@@ -40,6 +38,21 @@ void autofs_catatonic_mode(struct autofsfput (sbi->pipe);/* Close the pipe */ sbi->pipe =NULL ; sbi->pipefd =-1 ; +} + +void autofs_catatonic_mode (struct autofs_sb_info *sbi) +{ +mutex_lock (&sbi->wq_mutex); +autofs_catatonic_mode_locked (sbi); +mutex_unlock (&sbi->wq_mutex); +} + +static void autofs_catatonic_mode_for_pipe (struct autofs_sb_info *sbi, +struct file *pipe) +{ +mutex_lock (&sbi->wq_mutex); +if (sbi->pipe == pipe) +autofs_catatonic_mode_locked (sbi);mutex_unlock (&sbi->wq_mutex); }
@@ -170,7 +183,7 @@ static void autofs_notify_daemon(structautofs_wait_release (sbi, wq->wait_queue_token, ret);break ;default : -autofs_catatonic_mode (sbi); +autofs_catatonic_mode_for_pipe (sbi, pipe);break ; }fput (pipe);
Greg Kroah-Hartman
maintainerPATCH 493/571 KVM: nVMX: Reset MMU back to the root MMU if loading L2 state fails for !VM-Entry
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amirmohammad Eftekhar <[email protected]>
commit c8f4cfe1cf93bce924e27f2abead7a4c4a487505 upstream.
Reset the vCPU's MMU pointer back to the root MMU if loading L2 state fails in the "not from VM-Entry" case, i.e. when emulating RSM or handling KVM_SET_NESTED_STATE. Failure to unwind the MMU pointer results in KVM trying to run L1 with a nested MMU, and is especially problematic if the vCPU manages to free its nested state before the VM crashes. Constructing the root for a nested EPT MMU goes through vmcs12, which is dynamically allocated/freed when nVMX is enabled/disabled. And so if the nested state is freed with the MMU still pointing at the nested MMU, KVM will hit a NULL pointer deref when attempting to get L1=>L2 EPTP.
BUG: kernel NULL pointer dereference, address: 0000000000000078 #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page PGD 114a2d067 P4D 111743067 PUD 11141f067 PMD 0 Oops: Oops: 0000 [#1] SMP CPU: 20 UID: 1000 PID: 1272 Comm: nested_tdp_faul Not tainted 7.3.0-rc4-8c89f11d1a99b-sink-vm #1914 PREEMPTLAZY Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015 RIP: 0010:nested_ept_get_eptp+0xb/0x10 [kvm_intel] Call Trace: <TASK> kvm_mmu_load+0xcd/0x870 [kvm] kvm_arch_vcpu_ioctl_run+0x18f5/0x1f80 [kvm] kvm_vcpu_ioctl+0x2c7/0x970 [kvm] __x64_sys_ioctl+0x90/0xd0 do_syscall_64+0x9c/0x4d0 entry_SYSCALL_64_after_hwframe+0x4b/0x53 RIP: 0033:0x47491b </TASK> Modules linked in: kvm_intel kvm irqbypass CR2: 0000000000000078 ---[ end trace 0000000000000000 ]--- RIP: 0010:nested_ept_get_eptp+0xb/0x10 [kvm_intel]
--- arch/x86/kvm/vmx/nested.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/nested.c +3 -1
@@ -3538,8 +3538,10 @@ vmentry_fail_vmexit_guest_mode: vmentry_fail_vmexit:vmx_switch_vmcs (vcpu, &vmx->vmcs01); -if (!from_vmentry) +if (!from_vmentry) { +nested_ept_uninit_mmu_context (vcpu);return NVMX_VMENTRY_VMEXIT ; + }load_vmcs12_host_state (vcpu, vmcs12); vmcs12->vm_exit_reason = exit_reason.full;
Greg Kroah-Hartman
maintainerPATCH 494/571 fsnotify: prevent mark additions during connector teardown
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 36ebddca56b9d8993d6dc984fdecc748ee1f5e06 upstream.
fsnotify_destroy_marks() keeps a reference to its current mark while it drops conn->lock to destroy the mark. This stabilizes the forward-walk cursor, but does not prevent a new mark from being inserted before it. For example, an inotify watch re-added after IN_IGNORED sorts before the old, detached mark for the same group. The walk can miss the replacement and then detach the entire connector from the object.
The replacement is still on its group's marks_list and, for inotify, in the watch IDR. The group mutex no longer protects the connector's object from disappearing. An unprivileged fdinfo read racing the final detach can consequently call igrab(NULL):
BUG: KASAN: null-ptr-deref in igrab+0x24/0x100 Write of size 4 at addr 0000000000000148 Call Trace: igrab+0x24/0x100 inotify_show_fdinfo+0x1dc/0x5e0 seq_show+0x397/0x690
Set a DESTROYING flag under conn->lock before starting the walk, and reject new marks on that connector with -ENOENT. The existing add-mark error paths undo the temporary group-list entry and the backend's watch allocation. Do not wait for teardown while holding the group mutex, which the destroyer needs. Once the old connector is detached, an add can install a fresh connector as before.
This closes the insertion race for all object types using the common connector teardown, without changing the mark reference or SRCU lifetime rules.
--- fs/notify/mark.c | 11 +++++++++++ include/linux/fsnotify_backend.h | 1 + 2 files changed, 12 insertions(+)
fs/notify/mark.c +11 -0
@@ -686,6 +686,11 @@ restart: goto out_err; } +if (conn->flags &FSNOTIFY_CONN_FLAG_DESTROYING ) { + err = -ENOENT ; + goto out_err; + } +/* is mark the first mark? */ if (hlist_empty (&conn->list)) {hlist_add_head_rcu (&mark->obj_list, &conn->list);
@@ -869,6 +874,12 @@ void fsnotify_destroy_marks(fsnotify_conif (!conn)return ;/* +* New marks could be inserted before our cursor and survive the final +* detachment of the connector from the object. Prevent additions to +* this connector before dropping its lock. +*/ + conn->flags |=FSNOTIFY_CONN_FLAG_DESTROYING ; +/* * We have to be careful since we can race with e.g. * fsnotify_clear_marks_by_group() and once we drop the conn->lock, the * list can get modified. However we are holding mark reference and
include/linux/fsnotify_backend.h +1 -0
@@ -474,6 +474,7 @@ struct fsnotify_mark_connector {unsigned short type;/* Type of object [lock] */ #define FSNOTIFY_CONN_FLAG_HAS_FSID 0x01#define FSNOTIFY_CONN_FLAG_HAS_IREF 0x02 +#define FSNOTIFY_CONN_FLAG_DESTROYING 0x04unsigned short flags;/* flags [lock] */ __kernel_fsid_t fsid;/* fsid of filesystem containing object */ union {
Greg Kroah-Hartman
maintainerPATCH 495/571 net/sched: fix use-after-free in __tcf_action_put()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 7b16eb911091aae237a8673da94e4dfb9cd21d54 upstream.
__tcf_action_put() decrements the reference count before decrementing the binding count. Another thread can free the action between these operations, causing the binding-count update to access freed memory. KASAN reports it as:
BUG: KASAN: slab-use-after-free in __tcf_action_put+0x327/0x340 Write of size 4 at addr ff11000000d46420 by task tc-put-pause/64
Hold the action IDR mutex across both counter updates and IDR removal, keeping cleanup outside the lock.
--- net/sched/act_api.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
net/sched/act_api.c +5 -6
@@ -137,9 +137,10 @@ static int __tcf_action_put(struct tc_ac {struct tcf_idrinfo *idrinfo = p->idrinfo; -if (refcount_dec_and_mutex_lock (&p->tcfa_refcnt, &idrinfo->lock)) { -if (bind) -atomic_dec (&p->tcfa_bindcnt); +mutex_lock (&idrinfo->lock); +if (bind) +atomic_dec (&p->tcfa_bindcnt); +if (refcount_dec_and_test (&p->tcfa_refcnt)) {idr_remove (&idrinfo->action_idr, p->tcfa_index);mutex_unlock (&idrinfo->lock);
@@ -147,9 +148,7 @@ static int __tcf_action_put(struct tc_acreturn 1 ; } -if (bind) -atomic_dec (&p->tcfa_bindcnt); - +mutex_unlock (&idrinfo->lock);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 496/571 net: rds: fix uninitialized trans dereference in CM event handler
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aohan Mei <[email protected]>
commit 492ba6ac1b1ffb8a06ff52db0825c1af2cdb28c8 upstream.
rds_rdma_cm_event_handler_cmn() assigns trans only when the RDMA device is an InfiniBand CA (RDMA_NODE_IB_CA). On any other device type, e.g. an iWARP RNIC such as siw, trans stays uninitialized, but the event switch dereferences it: unconditionally in the RDMA_CM_EVENT_CONNECT_REQUEST case via trans->cm_handle_connect(), and (with a connection context) in the ROUTE_RESOLVED and ESTABLISHED cases.
An RDS listener on an iWARP device therefore crashes the kernel as soon as a connect request arrives: with CONFIG_INIT_STACK_ALL_ZERO the wild load becomes a NULL dereference at offset 0xa0 (&trans->cm_handle_connect) in the iw_cm_wq workqueue.
GCC masks the bug in default builds by folding the uninitialized load into &rds_ib_transport; Clang-built kernels take the real uninitialized path and oops.
The active side can land on a non-IB device too: the id that rds_ib_conn_path_connect() creates is not restricted to a node type, so rdma_resolve_addr() binds it to whichever device serves the local address, and an iWARP RNIC on the same netdev qualifies. The crash there is different: resolving a route on an iWARP id never fills in cm_id->route.path_rec, and the ROUTE_RESOLVED case writes path_rec[0].sl before it calls into the transport.
The iWARP transport was dropped long ago and IB is the only transport left, so make that explicit: initialize trans to &rds_ib_transport at declaration, drop the conditional assignment, reject a connect request that arrives on a non-IB device, and drop a connection whose address resolved to one instead of resolving a route on it. The rejection is limited to RDMA_CM_EVENT_CONNECT_REQUEST on purpose: a non-zero return from the handler makes rdma_cm destroy the id the event was delivered on, which is right for the request's freshly created id but would free a connection id that RDS still owns for any other event. On the active side the id stays ic->i_cm_id and the connection's shutdown destroys it, so that case returns 0.
[achender: reject only on RDMA_CM_EVENT_CONNECT_REQUEST instead of
bailing out for every event on a non-IB device, so that rdma_cm does not destroy connection ids RDS still tracks; drop a connection whose address resolved to a non-IB device before a route is resolved on it; changelog adjusted]
--- net/rds/rdma_transport.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-)
net/rds/rdma_transport.c +22 -4
@@ -52,7 +52,7 @@ static int rds_rdma_cm_event_handler_cmn {/* this can be null in the listening path */ struct rds_connection *conn = cm_id->context; -struct rds_transport *trans; +struct rds_transport *trans = &rds_ib_transport;int ret =0 ;int *err;u8 len;
@@ -60,9 +60,6 @@ static int rds_rdma_cm_event_handler_cmnrdsdebug ("conn %p id %p handling event %u (%s)\n" , conn, cm_id, event->event,rdma_event_msg (event->event)); -if (cm_id->device->node_type ==RDMA_NODE_IB_CA ) - trans = &rds_ib_transport; -/* Prevent shutdown from tearing down the connection * while we're executing. */ if (conn) {
@@ -82,11 +79,32 @@ static int rds_rdma_cm_event_handler_cmnswitch (event->event) {case RDMA_CM_EVENT_CONNECT_REQUEST : +/* Only the IB transport is supported, but RDS listens on +* every RDMA device: reject a request that arrived on any +* other kind. A non-zero return has rdma_cm destroy the +* request's id, which is what we want here and only here. +*/ +if (cm_id->device->node_type !=RDMA_NODE_IB_CA ) { + ret =1 ; +break ; + } ret = trans->cm_handle_connect (cm_id, event, isv6);break ;case RDMA_CM_EVENT_ADDR_RESOLVED :if (conn) { +/* The address resolved to a device RDS has no +* transport for. Do not go on to resolve a route: +* an iWARP route leaves cm_id->route.path_rec +* unset, which the ROUTE_RESOLVED case below +* dereferences. Drop the connection instead; the +* id is still ic->i_cm_id, so return 0 and let the +* shutdown destroy it. +*/ +if (cm_id->device->node_type !=RDMA_NODE_IB_CA ) { +rds_conn_drop (conn); +break ; + }rdma_set_service_type (cm_id, conn->c_tos);rdma_set_min_rnr_timer (cm_id,IB_RNR_TIMER_000_32 ); ret = rdma_resolve_route(cm_id,
Greg Kroah-Hartman
maintainerPATCH 497/571 sctp: revalidate output stream after association connect wait
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
commit b7ad72414c673ce1fa1f463e807cd4f34f8be9bf upstream.
When message interleaving is enabled, the first send waits for association establishment before building its data chunks. The wait drops the socket lock, and handshake processing can reduce the output stream count to the peer-advertised inbound stream count. sctp_stream_init() then frees the extension of every removed stream.
The sender resumes with the stream that it checked before the wait. If the peer removed that stream, sctp_outq_tail() later dereferences its NULL extension. Fatal-oops policies then panic the host.
KASAN: null-ptr-deref in range [0x38-0x3f] RIP: sctp_outq_tail+0x49e/0xaa0 Call Trace: sctp_primitive_SEND sctp_sendmsg_to_asoc sctp_sendmsg
A range check alone is insufficient. Stream reconfiguration can grow the output count again while the lock is released without recreating extensions freed by the earlier shrink. The stream can then be in range while its extension remains NULL. The send-buffer wait has the same issue.
Factor the range and extension checks into a helper and repeat both after each send-path wait that drops the socket lock. Once the lock is reacquired, the validation remains stable through data creation and queueing.
If validation fails after the connect wait, the auto-created association is already established. Return ESRCH so the existing caller path keeps it under state-machine ownership instead of freeing it directly, which would leave protocol, counter and socket state inconsistent.
--- net/sctp/socket.c | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-)
net/sctp/socket.c +21 -12
@@ -1783,6 +1783,18 @@ static int sctp_sendmsg_check_sflags(strreturn 1 ; } +static int sctp_sendmsg_check_stream (struct sctp_association *asoc, +struct sctp_sndrcvinfo *sinfo) +{ +if (unlikely (sinfo->sinfo_stream >= asoc->stream.outcnt)) +return -EINVAL ; + +if (unlikely (!SCTP_SO (&asoc->stream, sinfo->sinfo_stream)->ext)) +return sctp_stream_init_ext (&asoc->stream, sinfo->sinfo_stream); + +return 0 ; +} + static int sctp_sendmsg_to_asoc(struct sctp_association *asoc, struct msghdr *msg, size_t msg_len, struct sctp_transport *transport,
@@ -1797,16 +1809,9 @@ static int sctp_sendmsg_to_asoc(struct slong timeo;int err; -if (sinfo->sinfo_stream >= asoc->stream.outcnt) { - err = -EINVAL ; + err =sctp_sendmsg_check_stream (asoc, sinfo); +if (err) goto err; - } - -if (unlikely (!SCTP_SO (&asoc->stream, sinfo->sinfo_stream)->ext)) { - err =sctp_stream_init_ext (&asoc->stream, sinfo->sinfo_stream); -if (err) - goto err; - }if (sp->disable_fragments && msg_len > asoc->frag_point) { err = -EMSGSIZE ;
@@ -1830,10 +1835,9 @@ static int sctp_sendmsg_to_asoc(struct s err =sctp_wait_for_sndbuf (asoc, transport, &timeo, msg_len);if (err) goto err; -if (unlikely (sinfo->sinfo_stream >= asoc->stream.outcnt)) { - err = -EINVAL ; + err =sctp_sendmsg_check_stream (asoc, sinfo); +if (err) goto err; - } }if (sctp_state (asoc,CLOSED )) {
@@ -1848,6 +1852,11 @@ static int sctp_sendmsg_to_asoc(struct s err = -ESRCH ; goto err; } + err =sctp_sendmsg_check_stream (asoc, sinfo); +if (err) { + err = -ESRCH ; + goto err; + } }else { wait_connect = true; }
Greg Kroah-Hartman
maintainerPATCH 498/571 tools: gpio: fix building from the top level with O=
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sasha Levin <[email protected]>
commit 52336337f1a01ad803c7f3ddb23f40222e9ad58d upstream.
"make O=<dir> tools/gpio" fails:
Makefile:27: /tools/build/Makefile.include: No such file or directory
tools/Makefile clears srctree, and the gpio Makefile only works it out again when building_out_of_srctree is not set, which the top-level Makefile sets for O= builds.
Also work out srctree when it is empty, as tools/bpf/Makefile does since commit a89b2cbf71d64 ("tools, bpf: Fix build for 'make -s tools/bpf O=<dir>'").
--- tools/gpio/Makefile | 6 ++++++ 1 file changed, 6 insertions(+)
tools/gpio/Makefile +6 -0
@@ -7,7 +7,13 @@ bindir ?= /usr/bin # isn't set and when invoked from selftests build, where srctree # is set to ".". building_out_of_srctree is undefined for in srctree # builds +ifeq ($(srctree),) +update_srctree := 1 +endif ifndef building_out_of_srctree +update_srctree := 1 +endif +ifeq ($(update_srctree),1) srctree := $(patsubst %/,%,$(dir $(CURDIR))) srctree := $(patsubst %/,%,$(dir $(srctree))) endif
Greg Kroah-Hartman
maintainerPATCH 499/571 i2c: qcom-cci: Fix HALT_ACK reset request being dropped
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Loic Poulain <[email protected]>
commit 195f3d74b5de98969dc4fad956393bb00787efd1 upstream.
A HALT_ACK interrupt indicates that the corresponding I2C master has entered the halted state and must be reset before further operation.
The M0 and M1 HALT_ACK status bits may be asserted simultaneously in a single interrupt. However, the interrupt handler currently overwrites the reset mask when processing each HALT_ACK condition, causing the first reset request to be lost if both events are reported together.
Accumulate reset requests instead of overwriting them so that both masters are properly reset when M0 and M1 HALT_ACK events occur in the same interrupt.
--- drivers/i2c/busses/i2c-qcom-cci.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/i2c/busses/i2c-qcom-cci.c +2 -2
@@ -168,12 +168,12 @@ static irqreturn_t cci_isr(int irq, void }if (unlikely (val &CCI_IRQ_STATUS_0_I2C_M0_Q0Q1_HALT_ACK )) { - reset =CCI_RESET_CMD_M0_MASK ; + reset |=CCI_RESET_CMD_M0_MASK ; ret =IRQ_HANDLED ; }if (unlikely (val &CCI_IRQ_STATUS_0_I2C_M1_Q0Q1_HALT_ACK )) { - reset =CCI_RESET_CMD_M1_MASK ; + reset |=CCI_RESET_CMD_M1_MASK ; ret =IRQ_HANDLED ; }
Greg Kroah-Hartman
maintainerPATCH 500/571 scsi: libiscsi: Reject a negative task index from parse_pdu_itt
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 8ee2a09a1dbb257c9e828ad2497f8e4832dfb142 upstream.
A transport that implements parse_pdu_itt hands libiscsi an index taken from the PDU, and both lookups bound it from above only:
if (i >= session->cmds_max)
i and cmds_max are both int, so a negative index passes and session->cmds[i] is read from before the array.
be2iscsi produces one. beiscsi_parse_pdu() assigns the raw tag,
*index = (int)itt;
and beiscsi_complete_pdu() forwards an unsolicited NOP-In from the hardware async ring without replacing its ITT, so the value is the target's. It also reports the session's own age rather than the one in the tag, which leaves the age comparison in iscsi_verify_itt() with nothing to reject.
Bound the index from below in both lookups.
--- drivers/scsi/libiscsi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/scsi/libiscsi.c +2 -2
@@ -1132,7 +1132,7 @@ struct iscsi_task *iscsi_itt_to_task(str session->tt->parse_pdu_itt (conn, itt, &i,NULL ); else i =get_itt (itt); -if (i >= session->cmds_max) +if (i <0 || i >= session->cmds_max)return NULL ;return session->cmds[i];
@@ -1325,7 +1325,7 @@ int iscsi_verify_itt(struct iscsi_conn *return ISCSI_ERR_BAD_ITT ; } -if (i >= session->cmds_max) { +if (i <0 || i >= session->cmds_max) {iscsi_conn_printk (KERN_ERR , conn,"received invalid itt index %u (max cmds " "%u.\n" , i, session->cmds_max);
Greg Kroah-Hartman
maintainerPATCH 501/571 scsi: libiscsi: Validate the ITT reflected in a Reject PDU
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit c5958c770b2a0ee492414e26b07da9164a0d1f5d upstream.
A Reject PDU carries a copy of the header it rejects, and iscsi_handle_reject() takes the ITT out of that copy to find the task to clean up:
memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
...
task = iscsi_itt_to_task(conn, rejected_pdu.itt);That value is whatever the target put there. iscsi_itt_to_task() bounds the index against cmds_max and checks nothing else, so any task in the pool can be named, and iscsi_nop_out_rsp() then completes it.
An index that has never been used gives a NULL task->conn: the pool is zeroed at session setup and conn is assigned only when a task is allocated. If the task was used and returned, iscsi_complete_task() hits its WARN_ON_ONCE(task->state == ISCSI_TASK_FREE) and the refcount underflows. An in-flight SCSI command is completed as successful - a 1 MiB read returned 1048576 with none of its buffer written and no warning.
Validate the reflected ITT the way iscsi_itt_to_ctask() validates a command ITT, and require the task to be in flight and not a SCSI command.
[ 6.248477] Oops: general protection fault, probably for non-canonical address 0xdffffc000000000c: 0000 [#1] SMP KASAN NOPTI [ 6.249357] KASAN: null-ptr-deref in range [0x0000000000000060-0x0000000000000067] [ 6.249951] CPU: 1 UID: 0 PID: 0 Comm: swapper/1 Not tainted 7.2.0-rc5-ISCSI1-gf5098b6bae76 #1 PREEMPT(lazy) [ 6.250718] Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 [ 6.251616] RIP: 0010:iscsi_nop_out_rsp.constprop.0+0x46/0x160 [ 6.252043] Code: c1 ea 03 48 83 ec 08 80 3c 02 00 0f 85 f5 00 00 00 48 b8 00 00 00 00 00 fc ff df 48 8b 6b 58 48 8d 7d 60 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 c0 00 00 00 48 8b 45 60 48 39 c3 74 50 48 b8 00 [ 6.252813] RSP: 0018:ffff88806c907b80 EFLAGS: 00010206 [ 6.253042] RAX: dffffc0000000000 RBX: ffff88800607e000 RCX: ffffffff8d571a25 [ 6.253345] RDX: 000000000000000c RSI: ffff88806c907c38 RDI: 0000000000000060 [ 6.253642] RBP: 0000000000000000 R08: 0000000000000000 R09: fffffbfff235a504 [ 6.253947] R10: 0000000000000003 R11: 7463656e6e6f6320 R12: 0000000000000000 [ 6.254251] R13: 0000000000000000 R14: ffff88806c907c38 R15: 0000000000000000 [ 6.254549] FS: 0000000000000000(0000) GS:ffff8880d95bc000(0000) knlGS:0000000000000000 [ 6.254887] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 6.255140] CR2: 00007fc393e8ffc0 CR3: 0000000005252006 CR4: 0000000000770ef0 [ 6.255439] PKRU: 55555554 [ 6.255564] Call Trace: [ 6.255674] <IRQ> [ 6.255768] __iscsi_complete_pdu+0x18bf/0x22a0 [ 6.256733] iscsi_complete_pdu+0x54/0xa0 [ 6.256905] iscsi_tcp_data_recv_done+0xf4/0x250 [ 6.257103] iscsi_tcp_recv_skb+0x31e/0xec0 [ 6.257680] iscsi_sw_tcp_recv+0x12f/0x390 [ 6.258061] __tcp_read_sock+0x1ab/0x810 [ 6.258853] iscsi_sw_tcp_data_ready+0x18b/0x510 [ 6.259808] tcp_data_queue+0x1f13/0x4cd0 [ 6.260567] tcp_rcv_established+0x8a5/0x3a00 [ 6.261931] tcp_v4_do_rcv+0x449/0x960 [ 6.262269] tcp_v4_rcv+0x2245/0x3bc0
--- drivers/scsi/libiscsi.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/scsi/libiscsi.c +5 -3
@@ -1083,13 +1083,15 @@ static int iscsi_handle_reject(struct isspin_unlock (&conn->session->frwd_lock);spin_lock (&conn->session->back_lock); }else { -struct iscsi_task *task; +struct iscsi_task *task =NULL ;/* * Our nop as ping got dropped. We know the target * and transport are ok so just clean up */ - task =iscsi_itt_to_task (conn, rejected_pdu.itt); -if (!task) { +if (!iscsi_verify_itt (conn, rejected_pdu.itt)) + task =iscsi_itt_to_task (conn, rejected_pdu.itt); +if (!task || task->state ==ISCSI_TASK_FREE || + task->sc) {iscsi_conn_printk (KERN_ERR , conn,"Invalid pdu reject. Could " "not lookup rejected task.\n" );
Greg Kroah-Hartman
maintainerPATCH 502/571 scsi: libiscsi: Validate the task named by a management response
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 11bffcd9cb346732eab2914ef44fe777a3f0b585 upstream.
__iscsi_complete_pdu() fetches the task for five response types from one place and checks only that the index resolved:
case ISCSI_OP_LOGOUT_RSP:
case ISCSI_OP_LOGIN_RSP:
case ISCSI_OP_TEXT_RSP:
case ISCSI_OP_SCSI_TMFUNC_RSP:
case ISCSI_OP_NOOP_IN:
task = iscsi_itt_to_task(conn, hdr->itt);
if (!task)
return ISCSI_ERR_BAD_ITT;iscsi_itt_to_task() bounds the index against cmds_max and looks at nothing else, so a target can name any slot in the pool, including one that has never been used. task->conn is then NULL, and both iscsi_nop_out_rsp() and iscsi_complete_task() dereference it. One unsolicited NOP-In is enough; a Text Response carrying the same ITT crashes in iscsi_complete_task() instead.
Require the task to be in flight and not a SCSI command, the way iscsi_itt_to_ctask() does for the command opcodes.
[ 6.298634] Oops: general protection fault, probably for non-canonical address 0xdffffc000000000c: 0000 [#1] SMP KASAN NOPTI [ 6.298642] KASAN: null-ptr-deref in range [0x0000000000000060-0x0000000000000067] [ 6.298652] CPU: 1 UID: 0 PID: 111 Comm: iscsistart Not tainted 7.2.0-rc5-ISCSI1-gf5098b6bae76 #1 PREEMPT(lazy) [ 6.298654] Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 [ 6.298656] RIP: 0010:iscsi_nop_out_rsp.constprop.0+0x46/0x160 [ 6.298691] Code: c1 ea 03 48 83 ec 08 80 3c 02 00 0f 85 f5 00 00 00 48 b8 00 00 00 00 00 fc ff df 48 8b 6b 58 48 8d 7d 60 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 c0 00 00 00 48 8b 45 60 48 39 c3 74 50 48 b8 00 [ 6.298698] RSP: 0018:ffff88806c907be8 EFLAGS: 00010206 [ 6.298701] RAX: dffffc0000000000 RBX: ffff888006116800 RCX: 0000000000000020 [ 6.298702] RDX: 000000000000000c RSI: ffff88800525d578 RDI: 0000000000000060 [ 6.298703] RBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000 [ 6.298706] R10: 0000000000000020 R11: 0000000000000000 R12: 0000000000000000 [ 6.298706] R13: 000000000000002e R14: ffff8880056eb440 R15: ffff888006116800 [ 6.298707] FS: 00007fc02d1c2740(0000) GS:ffff8880b29bc000(0000) knlGS:0000000000000000 [ 6.298710] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 6.298711] CR2: 000055fe3b56ddf8 CR3: 00000000053b9004 CR4: 0000000000770ef0 [ 6.298712] PKRU: 55555554 [ 6.298713] Call Trace: [ 6.298714] <IRQ> [ 6.298714] __iscsi_complete_pdu+0x13a8/0x22a0 [ 6.298758] iscsi_complete_pdu+0x54/0xa0 [ 6.298759] iscsi_tcp_hdr_recv_done+0x870/0x2c80 [ 6.298778] iscsi_tcp_recv_skb+0x31e/0xec0 [ 6.298800] iscsi_sw_tcp_recv+0x12f/0x390 [ 6.298804] __tcp_read_sock+0x1ab/0x810 [ 6.298812] iscsi_sw_tcp_data_ready+0x18b/0x510 [ 6.298814] tcp_rcv_established+0x1f56/0x3a00 [ 6.298842] tcp_v4_do_rcv+0x449/0x960 [ 6.298847] tcp_v4_rcv+0x2245/0x3bc0
--- drivers/scsi/libiscsi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/libiscsi.c +1 -1
@@ -1227,7 +1227,7 @@ int __iscsi_complete_pdu(struct iscsi_cocase ISCSI_OP_SCSI_TMFUNC_RSP :case ISCSI_OP_NOOP_IN : task =iscsi_itt_to_task (conn, hdr->itt); -if (!task) +if (!task || task->state ==ISCSI_TASK_FREE || task->sc)return ISCSI_ERR_BAD_ITT ;break ;default :
Greg Kroah-Hartman
maintainerPATCH 503/571 drm/amdgpu/sdma3: Work around POLL_REGMEM / FENCE hang
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Timur Kristóf <[email protected]>
commit 752480ad62964edf0254e151110d3e53a7cb37de upstream.
SDMA can randomly hang on Polaris 10. Hard to reproduce, but has been occurring sporadically in the Mesa CI on the RADV Polaris 10 job even when Mesa isn't using the SDMA engine.
When Mesa actually uses the SDMA on Polaris, the hang becomes more frequent and the reproduction rate goes up significantly in the CI system.
We don't know why the hangs occur, but it seems that inserting a single NOP packet before each POLL_REGMEM and FENCE packet works around it. At the moment it's unclear which GPUs are affected, so let's apply this to SDMA 3.x for now.
Note that this issue is not documented or acknowledged by AMD.
--- drivers/gpu/drm/amd/amdgpu/sdma_v3_0.c | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-)
drivers/gpu/drm/amd/amdgpu/sdma_v3_0.c +21 -4
@@ -460,6 +460,9 @@ static void sdma_v3_0_ring_emit_hdp_fluselse ref_and_mask =REG_SET_FIELD (ref_and_mask,GPU_HDP_FLUSH_DONE ,SDMA1 ,1 ); +/* Hang workaround */ +amdgpu_ring_write (ring,SDMA_PKT_NOP_HEADER_OP (SDMA_OP_NOP )); +amdgpu_ring_write (ring,SDMA_PKT_HEADER_OP (SDMA_OP_POLL_REGMEM ) |SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH (1 ) |SDMA_PKT_POLL_REGMEM_HEADER_FUNC (3 ));/* == */
@@ -487,6 +490,10 @@ static void sdma_v3_0_ring_emit_fence(st unsigned flags) {bool write64bit = flags &AMDGPU_FENCE_FLAG_64BIT ; + +/* Hang workaround */ +amdgpu_ring_write (ring,SDMA_PKT_NOP_HEADER_OP (SDMA_OP_NOP )); +/* write the fence */ amdgpu_ring_write (ring,SDMA_PKT_HEADER_OP (SDMA_OP_FENCE ));amdgpu_ring_write (ring,lower_32_bits (addr));
@@ -495,7 +502,11 @@ static void sdma_v3_0_ring_emit_fence(st/* optionally write high bits as well */ if (write64bit) { +/* Hang workaround */ +amdgpu_ring_write (ring,SDMA_PKT_NOP_HEADER_OP (SDMA_OP_NOP )); + addr +=4 ; +amdgpu_ring_write (ring,SDMA_PKT_HEADER_OP (SDMA_OP_FENCE ));amdgpu_ring_write (ring,lower_32_bits (addr));amdgpu_ring_write (ring,upper_32_bits (addr));
@@ -1049,6 +1060,9 @@ static void sdma_v3_0_ring_emit_pipelineuint32_t seq = ring->fence_drv.sync_seq;uint64_t addr = ring->fence_drv.gpu_addr; +/* Hang workaround */ +amdgpu_ring_write (ring,SDMA_PKT_NOP_HEADER_OP (SDMA_OP_NOP )); +/* wait for idle */ amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_POLL_REGMEM) | SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH(0) |
@@ -1077,6 +1091,9 @@ static void sdma_v3_0_ring_emit_vm_flush {amdgpu_gmc_emit_flush_gpu_tlb (ring, vmid, pd_addr); +/* Hang workaround */ +amdgpu_ring_write (ring,SDMA_PKT_NOP_HEADER_OP (SDMA_OP_NOP )); +/* wait for flush */ amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_POLL_REGMEM) | SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH(0) |
@@ -1584,11 +1601,11 @@ static const struct amdgpu_ring_funcs sd .get_wptr = sdma_v3_0_ring_get_wptr, .set_wptr = sdma_v3_0_ring_set_wptr, .emit_frame_size = -6 +/* sdma_v3_0_ring_emit_hdp_flush */ +6 +1 +/* sdma_v3_0_ring_emit_hdp_flush */ 3 +/* hdp invalidate */ -6 +/* sdma_v3_0_ring_emit_pipeline_sync */ -VI_FLUSH_GPU_TLB_NUM_WREG *3 +6 +/* sdma_v3_0_ring_emit_vm_flush */ - 10 + 10 + 10, /* sdma_v3_0_ring_emit_fence x3 for user fence, vm fence */ +6 +1 +/* sdma_v3_0_ring_emit_pipeline_sync */ +VI_FLUSH_GPU_TLB_NUM_WREG *3 +6 +1 +/* sdma_v3_0_ring_emit_vm_flush */ + (10 + 1) * 3, /* sdma_v3_0_ring_emit_fence x3 for user fence, vm fence */ .emit_ib_size = 7 + 6, /* sdma_v3_0_ring_emit_ib */ .emit_ib = sdma_v3_0_ring_emit_ib, .emit_fence = sdma_v3_0_ring_emit_fence,
Greg Kroah-Hartman
maintainerPATCH 504/571 drm/amdgpu: dont drop the runtime PM reference twice in amdgpu_gpr
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
commit de9f6bcdb44f0e410031002e2f103826ea6b6259 upstream.
amdgpu_debugfs_gpr_read() drops its runtime PM reference right after reading the wave registers. When copying them to userspace fails, it jumps to the err label, which drops the reference a second time. A read into a bad buffer on Navi31 either steals a reference somebody else holds (power/runtime_usage goes from 1 to 0) or underflows the count:
amdgpu 0000:03:00.0: Runtime PM usage count underflow!
The registers are already in the kernel buffer at that point, so finish the hardware access first and copy the buffer with a single copy_to_user() instead of the put_user() loop with its own error path.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c +3 -18
@@ -858,7 +858,6 @@ static ssize_t amdgpu_debugfs_gpr_read(s {struct amdgpu_device *adev = f->f_inode->i_private;int r; -ssize_t result =0 ;uint32_t offset, se, sh, cu, wave, simd, thread, bank, *data;if (size >4096 || size &3 || *pos &3 )
@@ -903,25 +902,11 @@ static ssize_t amdgpu_debugfs_gpr_read(spm_runtime_mark_last_busy (adev_to_drm (adev)->dev);pm_runtime_put_autosuspend (adev_to_drm (adev)->dev); +amdgpu_virt_disable_access_debugfs (adev); -while (size) { -uint32_t value; - - value = data[result >>2 ]; - r =put_user (value, (uint32_t *)buf); -if (r) { -amdgpu_virt_disable_access_debugfs (adev); - goto err; - } - - result +=4 ; - buf +=4 ; - size -=4 ; - } - + r =copy_to_user (buf, data, size) ? -EFAULT : size;kfree (data); -amdgpu_virt_disable_access_debugfs (adev); -return result; +return r; err:pm_runtime_put_autosuspend (adev_to_drm (adev)->dev);
Greg Kroah-Hartman
maintainerPATCH 505/571 tracing: Fix the shift out of bounds in the log2 histogram modifier
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
commit 647c2f97fcb94bc642cefe6db004999974563f06 upstream.
The .log2 key modifier files a value under its base-2 order:
# echo 'hist:keys=bytes_req.log2' > events/kmem/kmalloc/trigger
hist_field_log2() computes that as ilog2(roundup_pow_of_two(val)). The out-of-line form of roundup_pow_of_two() is
return 1UL << fls_long(n - 1);
which shifts by 64 on a 64-bit kernel both when n is 0, where n - 1 wraps to ULONG_MAX, and when n is above 2^63. Both are ordinary keys, because the field fetch hands every value over as a u64: a syscall argument of 0 reaches the first, and one above 2^63 reaches the second.
Keying sys_enter_lseek on offset.log2 and passing 0, 1, 2, 3, 1000, 2^63+1 and U64_MAX gives
{ offset: ~ 2^1 } hitcount: 1
{ offset: ~ 2^10 } hitcount: 1
{ offset: ~ 2^2 } hitcount: 1
{ offset: ~ 2^0 } hitcount: 4Keys above 2^63 land in the lowest bucket. With CONFIG_UBSAN_SHIFT=y the shift is also reported:
UBSAN: shift-out-of-bounds in include/linux/log2.h:57:13 shift exponent 64 is too large for 64-bit type 'long unsigned int' __ubsan_handle_shift_out_of_bounds.cold+0xdd/0x1cb hist_fn_call.cold+0x8b/0xd9 event_hist_trigger+0x1cc/0x790 ftrace_syscall_enter+0x197/0x360 do_syscall_64+0x402/0x4b0
Use order_base_2(), which is ilog2(n - 1) + 1 for n > 1 and 0 below that. It returns what the old expression returned on every input the old one was defined for. Where it was not, 0 stays in bucket 0, which is where x86_64 had been putting it, and the keys above 2^63 move into bucket 64.
--- kernel/trace/trace_events_hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
@@ -217,7 +217,7 @@ static u64 hist_field_log2(struct hist_fu64 val = operand->fn (operand, elt, buffer, rbe, event); -return (u64 )ilog2 (roundup_pow_of_two (val)); +return order_base_2 (val); } static u64 hist_field_bucket(struct hist_field *hist_field,
Greg Kroah-Hartman
maintainerPATCH 506/571 tracing: Fix hist trigger timestamps for buffered events
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tengda Wu <[email protected]>
commit 9414ca3b99e5a7f1f3bf51c2a01b383e1b355dd0 upstream.
Syzkaller triggered a WARN_ON_ONCE(!nest) warning:
WARNING: kernel/trace/ring_buffer.c:821 at ring_buffer_event_time_stamp
Call trace:
ring_buffer_event_time_stamp
hist_field_timestamp
hist_fn_call
event_hist_trigger
event_triggers_call
__event_trigger_test_discard
trace_event_buffer_commit
do_trace_event_raw_event_sched_switch
trace_event_raw_event_sched_switchThe warning is probabilistically reproducible and is related to syzkaller executing the following commands:
echo 'prev_pid == 999999' > events/sched/sched_switch/filter echo 'hist:keys=common_timestamp' > events/sched/sched_switch/trigger
The specific triggering process is as follows:
CPU 0 CPU 1
(context switching) (echo 'hist:keys=common_timestamp' > \
events/sched/sched_switch/trigger)
do_trace_event_raw_event_##call
trace_event_buffer_lock_reserve
if (!tr->no_filter_buffering_ref &&
trace_file->flags & EVENT_FILE_FL_FILTERED)
return entry; // return directly
event_hist_trigger_parse
hist_register_trigger
tracing_set_filter_buffering(file->tr, true);
tr->no_filter_buffering_ref++;
__trace_buffer_lock_reserve
rb_start_commit
local_inc(&cpu_buffer->committing); // skipped and not executed trace_event_buffer_commit
__event_trigger_test_discard
event_triggers_call
event_hist_trigger
hist_fn_call
hist_field_timestamp
ring_buffer_event_time_stamp
nest = local_read(&cpu_buffer->committing); WARN_ON_ONCE(!nest) // trigger warning
The root cause is that when an event file has a filter attached and the hist trigger has not yet been attached, trace_event_buffer_lock_reserve() writes the event into the per-CPU trace_buffered_event temp buffer instead of reserving it in the ring buffer, so cpu_buffer->committing is not incremented. When the event is later processed at commit time by a hist trigger, hist_field_timestamp() -> ring_buffer_event_time_stamp() sees a zero committing count, triggering WARN_ON_ONCE(!nest).
tracing_event_time_stamp() was added by commit d8279bfc5e959 ("tracing:
Add tracing_event_time_stamp() API") for exactly this case: if the event is the per-CPU trace_buffered_event, it returns the current ring buffer timestamp. But it never gained a caller. Use it in hist_field_timestamp(), so that a hist trigger that races onto a buffered event records the current time, which is only marginally later than when the event was recorded, instead of warning and recording a bogus timestamp.
--- kernel/trace/trace_events_hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
@@ -665,7 +665,7 @@ static u64 hist_field_timestamp(struct hstruct hist_trigger_data *hist_data = hist_field->hist_data;struct trace_array *tr = hist_data->event_file->tr; -u64 ts =ring_buffer_event_time_stamp (buffer, rbe); +u64 ts =tracing_event_time_stamp (buffer, rbe);if (hist_data->attrs->ts_in_usecs &&trace_clock_in_ns (tr)) ts =ns2usecs (ts);
Greg Kroah-Hartman
maintainerPATCH 507/571 wifi: p54: validate firmware record lengths
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heyang Tan <[email protected]>
commit db7b86bd97b380ece8fa39cfdd7502a9fd35e56f upstream.
The p54 firmware parser accesses component ID and component version records without checking that their lengths cover the fields being read. A malformed record can therefore make the parser read past the record.
Validate the component ID and component version record lengths before accessing their data. The descriptor record is also checked against the shortest descriptor length found in the supported firmware images.
Reject descriptor values that underflow the RX offset or produce an empty RX range before updating the driver state.
--- drivers/net/wireless/intersil/p54/fwio.c | 42 +++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-)
drivers/net/wireless/intersil/p54/fwio.c +37 -5
@@ -52,6 +52,13 @@ int p54_parse_firmware(struct ieee80211_u32 code =le32_to_cpu (bootrec->code);switch (code) {case BR_CODE_COMPONENT_ID : +if (len <sizeof (struct bootrec_comp_id ) / +sizeof (*bootrec->data)) { +wiphy_err (priv->hw->wiphy, +"firmware component ID is too short\n" ); +return -EINVAL ; + } + priv->fw_interface =be32_to_cpup ((__be32 *) bootrec->data);switch (priv->fw_interface) {
@@ -72,16 +79,41 @@ int p54_parse_firmware(struct ieee80211_ }break ;case BR_CODE_COMPONENT_VERSION : +if (len <DIV_ROUND_UP (sizeof (struct bootrec_comp_ver ), +sizeof (*bootrec->data))) { +wiphy_err (priv->hw->wiphy, +"firmware component version is too short\n" ); +return -EINVAL ; + } +/* 24 bytes should be enough for all firmwares */ -if (strnlen ((unsigned char *) bootrec->data,24 ) <24 ) - fw_version = (unsigned char *) bootrec->data; +if (strnlen ((unsigned char *)bootrec->data, +sizeof (struct bootrec_comp_ver )) < +sizeof (struct bootrec_comp_ver )) + fw_version = (unsigned char *)bootrec->data;break ;case BR_CODE_DESCR : {struct bootrec_desc *desc = (struct bootrec_desc *)bootrec->data; - priv->rx_start =le32_to_cpu (desc->rx_start); -/* FIXME add sanity checking */ - priv->rx_end =le32_to_cpu (desc->rx_end) -0x3500 ; +u32 rx_start, rx_end; + +/* 0xa is the shortest descriptor in supported firmware. */ +if (len <0xa ) { +wiphy_err (priv->hw->wiphy, +"firmware descriptor is too short\n" ); +return -EINVAL ; + } + + rx_start =le32_to_cpu (desc->rx_start); + rx_end =le32_to_cpu (desc->rx_end); +if (rx_end <0x3500 || rx_end -0x3500 <= rx_start) { +wiphy_err (priv->hw->wiphy, +"firmware descriptor has invalid RX range\n" ); +return -EINVAL ; + } + + priv->rx_start = rx_start; + priv->rx_end = rx_end -0x3500 ; priv->headroom = desc->headroom; priv->tailroom = desc->tailroom; priv->privacy_caps = desc->privacy_caps;
Greg Kroah-Hartman
maintainerPATCH 508/571 tcp: fix use-after-free in do_tcp_getsockopt(TCP_CC_INFO)
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>
commit 385e474086c2e7e29e2dded690be40dc273e20ee upstream.
do_tcp_getsockopt() reads icsk->icsk_ca_ops and dereferences the get_info function pointer without rcu_read_lock(). With BPF struct_ops congestion control, ca_ops can point to dynamically allocated memory that is freed concurrently, resulting in a use-after-free when the kernel dereferences or calls through the stale pointer.
BUG: KASAN: slab-use-after-free in do_tcp_getsockopt+0x2037/0x23e0 Read of size 8 at addr ffff888013701258 by task exploit/149 do_tcp_getsockopt+0x2037/0x23e0 (net/ipv4/tcp.c:4564) tcp_getsockopt+0x91/0xf0 __sys_getsockopt+0xf7/0x170
Fix this by wrapping the ca_ops load and get_info call within rcu_read_lock()/rcu_read_unlock(), and using READ_ONCE() to load the icsk_ca_ops pointer.
--- net/ipv4/tcp.c | 4 +++- net/ipv4/tcp_dctcp.c | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-)
net/ipv4/tcp.c +3 -1
@@ -4053,9 +4053,11 @@ static int do_tcp_getsockopt(struct sockif (get_user (len, optlen))return -EFAULT ; - ca_ops = icsk->icsk_ca_ops; +rcu_read_lock (); + ca_ops =READ_ONCE (icsk->icsk_ca_ops);if (ca_ops && ca_ops->get_info) sz = ca_ops->get_info (sk, ~0U , &attr, &info); +rcu_read_unlock (); len = min_t(unsigned int, len, sz);if (put_user (len, optlen))
net/ipv4/tcp_dctcp.c +1 -1
@@ -201,7 +201,7 @@ static size_t dctcp_get_info(struct sockif (ext & (1 << (INET_DIAG_DCTCPINFO -1 )) || ext & (1 << (INET_DIAG_VEGASINFO -1 ))) {memset (&info->dctcp,0 ,sizeof (info->dctcp)); -if (inet_csk (sk)->icsk_ca_ops != &dctcp_reno) { +if (READ_ONCE (inet_csk (sk)->icsk_ca_ops) != &dctcp_reno) { info->dctcp.dctcp_enabled =1 ; info->dctcp.dctcp_ce_state = (u16 ) ca->ce_state; info->dctcp.dctcp_alpha = ca->dctcp_alpha;
Greg Kroah-Hartman
maintainerPATCH 509/571 cgroup: fix spurious SIGKILL of CLONE_INTO_CGROUP children
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Etienne Perot <[email protected]>
commit 8e359920216689b3b79e0fe8961a77fe312a511f upstream.
Since commit b69bb476dee9 ("cgroup: fix race between fork and cgroup.kill"), the fork path snapshots the kill_seq of the child's future cgroup into kargs->kill_seq, and cgroup_post_fork() SIGKILLs the child if that cgroup's kill_seq has changed in the meantime, to catch forks racing with a cgroup.kill sweep.
For CLONE_INTO_CGROUP, however, the snapshot in cgroup_css_set_fork() is taken before the target cgroup has been resolved: kargs->cgrp is always NULL at this point (it is only set at the end of the function). So the "if (kargs->cgrp)" branch is dead code and the snapshot always records the kill_seq of the parent's cgroup. cgroup_post_fork() then compares it with the kill_seq of the target cgroup, so the child gets SIGKILLed whenever the two cgroups have been killed a different number of times.
As a result, once cgroup.kill has been written to a cgroup, every child subsequently cloned into it with clone3(CLONE_INTO_CGROUP) is killed on the spot, for as long as the cgroup exists: kill_seq is not exposed to userspace and never resets.
Re-snapshot kill_seq from the target cgroup once it has been resolved, and drop the dead branch at the early snapshot site.
This does not reopen the race fixed by b69bb476dee9. For CLONE_INTO_CGROUP, everything from the snapshot to the check in cgroup_post_fork() runs with cgroup_mutex held, and kill_seq is only ever incremented under cgroup_mutex.
tj: Updated the comment above kill_seq to reflect the new serialization rules as suggested by Shakeel Butt.
--- include/linux/cgroup-defs.h | 5 ++++- kernel/cgroup/cgroup.c | 6 ++---- 2 files changed, 6 insertions(+), 5 deletions(-)
include/linux/cgroup-defs.h +4 -1
@@ -404,7 +404,10 @@ struct cgroup {int nr_threaded_children;/* # of live threaded child cgroups */ -/* sequence number for cgroup.kill, serialized by css_set_lock. */ +/* +* Sequence number for cgroup.kill. Incremented with both cgroup_mutex +* and css_set_lock held. Readers hold either one. +*/ unsigned int kill_seq;struct kernfs_node *kn;/* cgroup kernfs entry */
kernel/cgroup/cgroup.c +2 -4
@@ -6228,10 +6228,7 @@ static int cgroup_css_set_fork(struct kespin_lock_irq (&css_set_lock); cset =task_css_set (current);get_css_set (cset); -if (kargs->cgrp) - kargs->kill_seq = kargs->cgrp->kill_seq; -else - kargs->kill_seq = cset->dfl_cgrp->kill_seq; + kargs->kill_seq = cset->dfl_cgrp->kill_seq;spin_unlock_irq (&css_set_lock);if (!(kargs->flags &CLONE_INTO_CGROUP )) {
@@ -6282,6 +6279,7 @@ static int cgroup_css_set_fork(struct keput_css_set (cset);fput (f); kargs->cgrp = dst_cgrp; + kargs->kill_seq = dst_cgrp->kill_seq;return ret; err:
Greg Kroah-Hartman
maintainerPATCH 510/571 dm cache: fix demotion stats in passthrough mode
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ming-Hung Tsai <[email protected]>
commit 2ccb8878c149443c6acf628b438c9c942c20abb2 upstream.
The demotion counter is incremented per incoming write bio before the invalidation begins, causing the demotion count to exceed the actual number of cached blocks when multiple bios target the same cached block. Additionally, the counter is incremented unconditionally regardless of invalidation failure.
Reproduce steps:
1. Create a cache device consisting of 512 cache entries
modprobe brd rd_size=262144
dmsetup create cmeta --table "0 8192 linear /dev/ram0 0" dmsetup create cdata --table "0 65536 linear /dev/ram0 8192" dmsetup create corig --table "0 65536 linear /dev/ram0 262144" dd if=/dev/zero of=/dev/mapper/cmeta bs=4k count=1 oflag=direct dmsetup create cache --table "0 65536 cache /dev/mapper/cmeta \/dev/mapper/cdata /dev/mapper/corig 128 2 metadata2 writethrough smq 0"
2. Populate the cache, and record the number of cached blocks
fio --name=populate --filename=/dev/mapper/cache --rw=randwrite --bs=4k \
--direct=1 --ioengine=libaio --iodepth=32 --io_size=2048m nr_cached=$(dmsetup status cache | awk '{split($7, a, "/"); print a[1]}')
3. Reload the cache into passthrough mode
dmsetup suspend cache
dmsetup reload cache --table "0 65536 cache /dev/mapper/cmeta \/dev/mapper/cdata /dev/mapper/corig 128 2 metadata2 passthrough smq 0" dmsetup resume cache
4. Write to the passthrough cache with multiple jobs to trigger multiple bios hitting the same cached block.
fio --filename=/dev/mapper/cache --name=test --rw=write --bs=4k \
--direct=1 --ioengine=libaio --iodepth=32 --numjobs=4
5. Check if demoted matches cached block count. These numbers should match but may differ due to overcounting per bio.
nr_demoted=$(dmsetup status cache | awk '{print $12}') echo "$nr_cached, $nr_demoted"
Fix by moving the demotion counter increment into invalidate_complete(), gated on the success flag.
--- drivers/md/dm-cache-target.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-cache-target.c +3 -1
@@ -1453,6 +1453,9 @@ static void invalidate_complete(struct dstruct bio_list bios;struct cache *cache = mg->cache; +if (success) +atomic_inc (&cache->stats.demotion); +bio_list_init (&bios);if (mg->cell) {if (dm_cell_unlock_v2 (cache->prison, mg->cell, &bios))
@@ -1697,7 +1700,6 @@ static int map_bio(struct cache *cache,if (passthrough_mode (cache)) {if (bio_data_dir (bio) ==WRITE ) {bio_drop_shared_lock (cache, bio); -atomic_inc (&cache->stats.demotion);invalidate_start (cache, cblock, block, bio);return DM_MAPIO_SUBMITTED ; }else
Greg Kroah-Hartman
maintainerPATCH 511/571 dm cache: fix issue with background work locking
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Marzinski <[email protected]>
commit bc9781c0247de107876f32929f1637db93a42b34 upstream.
dm cache used a rw_semaphore for background_work_lock. Write locks on rw_semaphores have strict owner semantics, but there was no guarantee that the process that locked background_work_lock was the same process that unlocked it. This can be easily seen using a kernel compiled with CONFIG_DEBUG_RWSEMS. Given a dm cache device <cache>, run: 'dmsetup suspend <cache> && dmsetup resume <cache>'. This will trigger a kernel warning:
DEBUG_RWSEMS_WARN_ON((rwsem_owner(sem) != current) && !rwsem_test_oflags(sem, RWSEM_NONSPINNABLE))
triggered by cache_resume(). To fix this, switch from a rw_semaphore to a spinlock and a wait queue. dm cache already has a wait queue and associated counter, migration_wait and nr_allocated_migrations, that was getting woken up when background work was getting completed, but wasn't actually used by anything. This is replaced by the background_work queue and counter.
--- drivers/md/dm-cache-target.c | 55 +++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 27 deletions(-)
drivers/md/dm-cache-target.c +28 -27
@@ -338,8 +338,6 @@ struct cache {struct list_head invalidation_requests;sector_t migration_threshold; -wait_queue_head_t migration_wait; -atomic_t nr_allocated_migrations;/* * The number of in flight migrations that are performing
@@ -395,7 +393,11 @@ struct cache { bool loaded_mappings:1; bool loaded_discards:1; -struct rw_semaphore background_work_lock; +/* background work management */ +bool background_work_allowed; +unsigned background_work_nr; +spinlock_t background_work_lock; +wait_queue_head_t background_work_wait;struct batcher committer;struct work_struct commit_ws;
@@ -486,19 +488,13 @@ static struct dm_cache_migration *alloc_memset (mg,0 ,sizeof (*mg)); mg->cache = cache; -atomic_inc (&cache->nr_allocated_migrations);return mg; }static void free_migration (struct dm_cache_migration *mg) { -struct cache *cache = mg->cache; - -if (atomic_dec_and_test (&cache->nr_allocated_migrations)) -wake_up (&cache->migration_wait); - -mempool_free (mg, &cache->migration_pool); +mempool_free (mg, &mg->cache->migration_pool); }/*----------------------------------------------------------------*/
@@ -1026,34 +1022,39 @@ static void calc_discard_block_range(strstatic void prevent_background_work (struct cache *cache) { -lockdep_off (); -down_write (&cache->background_work_lock); -lockdep_on (); +spin_lock_irq (&cache->background_work_lock); + cache->background_work_allowed = false; +wait_event_lock_irq (cache->background_work_wait, + cache->background_work_nr ==0 , + cache->background_work_lock); +spin_unlock_irq (&cache->background_work_lock); }static void allow_background_work (struct cache *cache) { -lockdep_off (); -up_write (&cache->background_work_lock); -lockdep_on (); +spin_lock_irq (&cache->background_work_lock); + cache->background_work_allowed = true; +spin_unlock_irq (&cache->background_work_lock); }static bool background_work_begin (struct cache *cache) {bool r; -lockdep_off (); - r =down_read_trylock (&cache->background_work_lock); -lockdep_on (); - +spin_lock_irq (&cache->background_work_lock); + r = cache->background_work_allowed; +if (r) + cache->background_work_nr++; +spin_unlock_irq (&cache->background_work_lock);return r; }static void background_work_end (struct cache *cache) { -lockdep_off (); -up_read (&cache->background_work_lock); -lockdep_on (); +spin_lock_irq (&cache->background_work_lock); +if (--cache->background_work_nr ==0 ) +wake_up (&cache->background_work_wait); +spin_unlock_irq (&cache->background_work_lock); }/*----------------------------------------------------------------*/
@@ -2477,9 +2478,7 @@ static int cache_create(struct cache_argspin_lock_init (&cache->lock);bio_list_init (&cache->deferred_bios); -atomic_set (&cache->nr_allocated_migrations,0 );atomic_set (&cache->nr_io_migrations,0 ); -init_waitqueue_head (&cache->migration_wait); r = -ENOMEM ;atomic_set (&cache->nr_dirty,0 );
@@ -2561,8 +2560,10 @@ static int cache_create(struct cache_arg issue_op, cache, cache->wq);dm_iot_init (&cache->tracker); -init_rwsem (&cache->background_work_lock); -prevent_background_work (cache); +init_waitqueue_head (&cache->background_work_wait); +spin_lock_init (&cache->background_work_lock); + cache->background_work_allowed = false; + cache->background_work_nr =0 ; *result = cache;return 0 ;
Greg Kroah-Hartman
maintainerPATCH 512/571 dm-crypt: fix a tiny race condition in crypt_dec_pending
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ben Cressey <[email protected]>
commit 148845aa1921d95ef5dc851c76e6a284f6657df6 upstream.
crypt_dec_pending reads io->error before calling atomic_dec_and_test. Another context, for example crypt_endio called from an interrupt, may set io->error and drop its reference between the read and the decrement. crypt_dec_pending then drops the last reference and completes the bio with the stale status - so a read that failed and was never decrypted, or a write that failed, is reported as successful.
The read was placed before the decrement by commit b35f8caa0890 ("dm
crypt: wait for endio to complete before destruction"), because that commit freed dm_crypt_io before calling bio_endio. This is no longer the case, dm_crypt_io lives in the per-bio data now.
Read io->error after atomic_dec_and_test instead. atomic_dec_and_test is fully ordered, so no additional barrier is needed.
--- drivers/md/dm-crypt.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/md/dm-crypt.c +1 -2
@@ -1740,7 +1740,6 @@ static void crypt_dec_pending(struct dm_ {struct crypt_config *cc = io->cc;struct bio *base_bio = io->base_bio; -blk_status_t error = io->error;if (!atomic_dec_and_test (&io->io_pending))return ;
@@ -1753,7 +1752,7 @@ static void crypt_dec_pending(struct dm_else kfree (io->integrity_metadata); - base_bio->bi_status = error; + base_bio->bi_status = io->error;bio_endio (base_bio); }
Greg Kroah-Hartman
maintainerPATCH 513/571 dm-ebs: fix incorrect device offset check in ebs_ctr()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Genjian Zhang <[email protected]>
commit 7ac81e2d2240f2c57bd073b0733e0b2abca38e82 upstream.
<offset> is a backing-device sector offset; ti->len is the virtual target length. Comparing them rejects valid tables, e.g.:
dmsetup create ebs0 --table "0 1048576 ebs /dev/sda 2097152 1 8" -> ebs: Invalid device offset sector (-EINVAL)
Drop the check. Bounds against the backing device are already enforced later by device_area_is_invalid() via ebs_iterate_devices().
--- drivers/md/dm-ebs-target.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/md/dm-ebs-target.c +1 -2
@@ -263,8 +263,7 @@ static int ebs_ctr(struct dm_target *ti, r = -EINVAL ;if (sscanf (argv[1 ],"%llu%c" , &tmp, &dummy) !=1 || - tmp != (sector_t )tmp || - (sector_t )tmp >= ti->len) { + tmp != (sector_t )tmp) { ti->error ="Invalid device offset sector" ; goto bad; }
Greg Kroah-Hartman
maintainerPATCH 514/571 net/iucv: fix the recvmsg window update
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryam Vargas <[email protected]>
commit fa5acd038ea657ad5033713d6916214cbd349151 upstream.
iucv_sock_recvmsg() sends the HiperSockets-only AF_IUCV_FLAG_WIN without testing the transport, so on a classic z/VM socket iucv_send_ctrl() sizes the skb through a NULL iucv->hs_dev. SO_MSGLIMIT accepts 1, so msglimit / 2 is zero and one recvmsg() on its own socket is enough for an unprivileged process to take a spurious disconnect.
It also calls iucv_send_ctrl() under spin_lock_bh(&message_q.lock), which allocates GFP_KERNEL inside a section the code treats as atomic. Sending outside that lock lets two recvmsg() reach afiucv_hs_send() at once, where msg_recv is sampled for the advertised window and subtracted after dev_queue_xmit() -- and sendmsg reaches that counter under lock_sock() while recvmsg holds no socket lock, so both can subtract the same value, the counter goes negative and the credit reaches the peer twice.
Test the transport, claim the credit with atomic_xchg() after the last error exit and hand it back if the transmit fails, and send once the lock is dropped.
--- net/iucv/af_iucv.c | 42 +++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-)
net/iucv/af_iucv.c +25 -17
@@ -206,12 +206,6 @@ static int afiucv_hs_send(struct iucv_me phs_hdr->flags = flags;if (flags ==AF_IUCV_FLAG_SYN ) phs_hdr->window = iucv->msglimit; -else if ((flags ==AF_IUCV_FLAG_WIN ) || !flags) { - confirm_recv =atomic_read (&iucv->msg_recv); - phs_hdr->window = confirm_recv; -if (confirm_recv) - phs_hdr->flags = phs_hdr->flags |AF_IUCV_FLAG_WIN ; - }memcpy (phs_hdr->destUserID, iucv->dst_user_id,8 );memcpy (phs_hdr->destAppName, iucv->dst_name,8 );memcpy (phs_hdr->srcUserID, iucv->src_user_id,8 );
@@ -246,13 +240,22 @@ static int afiucv_hs_send(struct iucv_me } skb->protocol =cpu_to_be16 (ETH_P_AF_IUCV ); +/* Claim the receive credit here, not while building the header: every +* way this frame can be dropped has now been ruled out, so the window +* is zeroed only for as long as the transmit itself takes. +*/ +if (flags ==AF_IUCV_FLAG_WIN || !flags) { + confirm_recv =atomic_xchg (&iucv->msg_recv,0 ); + phs_hdr->window = confirm_recv; +if (confirm_recv) + phs_hdr->flags = phs_hdr->flags |AF_IUCV_FLAG_WIN ; + } +atomic_inc (&iucv->skbs_in_xmit); err =dev_queue_xmit (skb);if (net_xmit_eval (err)) {atomic_dec (&iucv->skbs_in_xmit); - }else { -atomic_sub (confirm_recv, &iucv->msg_recv); -WARN_ON (atomic_read (&iucv->msg_recv) <0 ); +atomic_add (confirm_recv, &iucv->msg_recv); }return net_xmit_eval (err);
@@ -1241,6 +1244,7 @@ static int iucv_sock_recvmsg(struct sockstruct iucv_sock *iucv =iucv_sk (sk);unsigned int copied, rlen;struct sk_buff *skb, *rskb, *cskb; +bool send_win = false;int err =0 ;u32 offset;
@@ -1333,16 +1337,20 @@ static int iucv_sock_recvmsg(struct sockif (skb_queue_empty (&iucv->backlog_skb_q)) {if (!list_empty (&iucv->message_q.list))iucv_process_message_q (sk); -if (atomic_read (&iucv->msg_recv) >= - iucv->msglimit /2 ) { - err =iucv_send_ctrl (sk,AF_IUCV_FLAG_WIN ); -if (err) { - sk->sk_state =IUCV_DISCONN ; - sk->sk_state_change (sk); - } - } +if (iucv->transport ==AF_IUCV_TRANS_HIPER && +atomic_read (&iucv->msg_recv) >= + iucv->msglimit /2 ) + send_win = true; }spin_unlock_bh (&iucv->message_q.lock); + +if (send_win) { + err =iucv_send_ctrl (sk,AF_IUCV_FLAG_WIN ); +if (err) { + sk->sk_state =IUCV_DISCONN ; + sk->sk_state_change (sk); + } + } } done:
Greg Kroah-Hartman
maintainerPATCH 515/571 tipc: protect node reset trace dump with node lock
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit dddf197f29ba5e47a476dde82bf542ca2e0d5e5e upstream.
The tipc_node_reset_links trace event asks tipc_node_dump() to walk the node's link entries. Unlike the other node events that request link data, this event runs without the node lock.
This permits bearer teardown to free a link while the trace callback is dumping it:
CPU 0 CPU 1
trace_tipc_node_reset_links()
tipc_node_dump()
l = n->links[0].link
tipc_node_write_lock()
kfree(l)
n->links[0].link = NULL
tipc_node_write_unlock()
tipc_link_dump(l)tipc_link_dump() then dereferences the stale pointer. KASAN reported:
BUG: KASAN: slab-use-after-free in tipc_link_dump Read of size 4 by task poc/115 Call Trace: tipc_link_dump+0x10cb/0x16b0 tipc_node_dump+0x4bb/0x740 trace_event_raw_event_tipc_node_class+0x258/0x360 tipc_node_reset_links+0x14d/0x1a0 tipc_rcv+0x13f5/0x3030 tipc_udp_recv+0x4e3/0x670 Allocated by task 0: tipc_link_create+0x1e1/0x1020 tipc_node_check_dest+0x7d2/0x11a0 tipc_disc_rcv+0xdbf/0x1430 Freed by task 89: kfree+0x131/0x3c0 tipc_node_link_down+0x267/0x4b0 tipc_node_delete_links+0xec/0x160 bearer_disable+0x107/0x260
Take the node write lock around the trace event. This serializes the dump against tipc_node_link_down(delete=true), which frees the link under the same write lock.
--- net/tipc/node.c | 2 ++ 1 file changed, 2 insertions(+)
net/tipc/node.c +2 -0
@@ -1335,7 +1335,9 @@ static void tipc_node_reset_links(structpr_warn ("Resetting all links to %x\n" , n->addr); +tipc_node_write_lock (n);trace_tipc_node_reset_links (n, true," " ); +tipc_node_write_unlock_fast (n);for (i =0 ; i <MAX_BEARERS ; i++) {tipc_node_link_down (n, i, false); }
Greg Kroah-Hartman
maintainerPATCH 516/571 sctp: validate chunk length in the inqueue parser
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Charles Vosburgh <[email protected]>
commit 6cfc1b90cb86f4aabc69fb8e30128e07e2cdfa3a upstream.
SCTP chunks always include a four-byte generic header, but sctp_inq_pop() currently accepts shorter declared lengths. A zero-length chunk leaves chunk_end at the current header.
When ASCONF is covered by the association's SCTP-AUTH policy, sctp_assoc_bh_rcv() can continue before the state machine performs its normal chunk-length check. sctp_inq_pop() then returns the same malformed chunk repeatedly and the receive softirq can lock up.
A remote SCTP peer can trigger this after establishing an association on a kernel built with CONFIG_IP_SCTP and configured with net.sctp.addip_enable=1 and net.sctp.auth_enable=1. The reproducer did not require application credentials, a shared SCTP AUTH key, or net.sctp.addip_noauth_enable=1.
On commit f967455fb2a5 ("seg6: reset IP6CB after IPv6 decapsulation"), one zero-length ASCONF caused repeated
watchdog soft-lockup reports in a two-vCPU KVM guest. All 3 pre-trigger health probes succeeded, while 36 of 37 post-trigger probes failed. With this change, all 37 post-trigger probes succeeded and no equivalent soft-lockup signature appeared.
Reject chunks shorter than the generic SCTP header at the shared inqueue parser boundary. Mark the packet for discard before either caller can continue processing it, while preserving the four-byte generic minimum. Declared-length 1 through 4 controls and kernel-generated ASCONF traffic remained healthy. The patched sctp_hello selftest passed for IPv4 and IPv6.
The complete private reproducer and validation evidence are available directly to maintainers on request.
--- net/sctp/inqueue.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
net/sctp/inqueue.c +4 -2
@@ -206,8 +206,10 @@ new_skb: chunk->chunk_end = ((__u8 *)ch) +SCTP_PAD4 (ntohs (ch->length));skb_pull (chunk->skb,sizeof (*ch)); chunk->subh.v =NULL ;/* Subheader is no longer valid. */ - -if (chunk->chunk_end +sizeof (*ch) <=skb_tail_pointer (chunk->skb)) { +if (unlikely (ntohs (ch->length) <sizeof (*ch))) { + chunk->pdiscard =1 ; + }else if (chunk->chunk_end +sizeof (*ch) <= +skb_tail_pointer (chunk->skb)) {/* This is not a singleton */ chunk->singleton =0 ; }else if (chunk->chunk_end >skb_tail_pointer (chunk->skb)) {
Greg Kroah-Hartman
maintainerPATCH 517/571 page_pool: keep frag_offset aligned for odd-sized requests
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Schauer <[email protected]>
commit dc0df5a0c62ccea1d0e08d39a4dc9064de81d411 upstream.
page_pool_alloc_frag_netmem() rounds the requested fragment size with
size = ALIGN(size, dma_get_cache_alignment());
dma_get_cache_alignment() returns 1 unless the architecture defines ARCH_DMA_MINALIGN, which DMA-coherent architectures such as x86 do not. There the ALIGN() is a no-op and pool->frag_offset advances by the raw, unrounded size.
A single caller asking for an odd size then leaves frag_offset misaligned for every fragment carved out of that page afterwards. The pool is shared, so the damage is not confined to the caller that caused it.
The per-cpu system_page_pool used by generic XDP hits this. skb_pp_cow_data() allocates its fragments with the raw packet length:
size = min_t(u32, len, PAGE_SIZE); truesize = size; page = page_pool_dev_alloc(pool, &page_off, &truesize);
leaving frag_offset odd for whatever is carved out of that page next. Its own head allocation is already aligned -- SKB_HEAD_ALIGN(size) plus the XDP_PACKET_HEADROOM its callers pass -- so it is a later user of the shared pool that pays: page_pool_dev_alloc_va() returns a misaligned buffer, napi_build_skb() installs it as skb->head, and skb_shinfo(skb) == skb->head + skb->end is misaligned with it.
skb_shinfo()->dataref is a 4-byte atomic_t at offset 0x20, so the atomic_inc() in __skb_clone() straddles a cache line. On x86 with split lock detection -- fatal for kernel split locks by default -- this panics the machine:
Oops: Split lock detected RIP: 0010:skb_clone+0x154/0x1e0 Call Trace: <IRQ> raw_local_deliver+0x1ed/0x2c0 ip_protocol_deliver_rcu+0x54/0x1c0 ip_local_deliver_finish+0x85/0x100 ip_local_deliver+0x67/0x100 __netif_receive_skb_one_core+0x85/0xa0 process_backlog+0x87/0x130
Reproduced by attaching any generic-mode XDP program to loopback and opening a RAW IPPROTO_UDP socket, which makes raw_local_deliver() clone every locally delivered UDP packet; ordinary DNS traffic then triggers it, roughly once per 2500 clones. Observed on 6.12.101 and 7.1.8.
Tracing page_pool_alloc_frag_netmem() over one such run shows the amplification -- two odd-sized requests, nine misaligned offsets:
requested size & 7: 0: 17035 5: 1 7: 1 frag_offset & 7: 0: 17028 3: 1 4: 1 5: 1 6: 1 7: 5
and skb_pp_cow_data() returning heads that were aligned on entry:
head 0xffff8f4c86aeac00 -> 0xffff8f4c53a9a9c4 (&7=4) head 0xffff8f4d6a8a42c0 -> 0xffff8f4c4f7b7a45 (&7=5)
Round the fragment size up to at least the alignment struct skb_shared_info requires, so fragments are always suitably aligned for the objects callers build on them. Architectures needing a larger DMA alignment keep it.
This also makes the remainder computed in page_pool_alloc_netmem(),
*size = max_size - *offset;
aligned, since max_size is a power of two -- which fixes the matching misalignment of skb->end.
Verified with a controlled A/B under QEMU/KVM: same tree, same config, same compiler, same rootfs and identical traffic, differing only by this patch. A SEC("xdp.frags") XDP_PASS program on lo plus UDP datagrams larger than max_head_size drives skb_pp_cow_data()'s fragment loop, which passes raw packet lengths to the pool. Measured at the return of skb_pp_cow_data():
unpatched patched
skb_pp_cow_data calls 40800 40800
misaligned skb->head 1120 0
dataref at line offset >60 80 0
The last row counts the accesses that actually fault:
skb_shinfo()->dataref sits at head+end+0x20 and is a 4-byte atomic, so lock incl splits a 64-byte cache line only when that address lands at offset 61..63. All 80 occurrences were at offset 61; the panic reported above was at offset 62. Eliminating the misalignment removes every one of them.
Same class of bug as commit 3bed3cc4156e ("net: Do not allocate page fragments that are not skb aligned"), which fixed the older netdev_alloc_frag()/napi_alloc_frag() allocators.
--- net/core/page_pool.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/core/page_pool.c +2 -1
@@ -594,7 +594,8 @@ struct page *page_pool_alloc_frag(struct size > max_size))return NULL ; - size =ALIGN (size,dma_get_cache_alignment ()); + size = ALIGN(size, max_t(unsigned int, dma_get_cache_alignment(), + __alignof__(struct skb_shared_info ))); *offset = pool->frag_offset;if (page && *offset + size > max_size) {
Greg Kroah-Hartman
maintainerPATCH 518/571 s390/ctcm: Prevent XID null dereference
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aswin Karuvally <[email protected]>
commit b264d8422779d69febce914efc47a92a85cc382c upstream.
The mpc_validate_xid() function sets grp->saved_xid2->xid2_flag2 to 0x40 to signal XID validation error. If peer XID is NULL or r/w channel pairing mismatch happens, grp->saved_xid2 is never initialized. An attempt to set the flag in such case leads to NULL dereference.
Fix this by using the always available priv->xid->xid2_flag2 instead of grp->saved_xid2->xid2_flag2 for validation errors.
--- drivers/s390/net/ctcm_mpc.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/s390/net/ctcm_mpc.c +1 -2
@@ -824,7 +824,7 @@ static void mpc_action_go_ready(fsm_instfsm_deltimer (&grp->timer); -if (grp->saved_xid2->xid2_flag2 ==0x40 ) { +if (priv->xid->xid2_flag2 ==0x40 ) { priv->xid->xid2_flag2 =0x00 ;if (grp->estconnfunc) { grp->estconnfunc(grp->port_num, 1,
@@ -1633,7 +1633,6 @@ done:"The XID used in the MPC protocol is not valid, " "rc = %d\n", rc); priv->xid->xid2_flag2 =0x40 ; - grp->saved_xid2->xid2_flag2 =0x40 ; }return rc;
Greg Kroah-Hartman
maintainerPATCH 519/571 s390/pci: Fix leak of uninitialized kernel data in SCLP report
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Schnelle <[email protected]>
commit 8ac60ae2a307a50b599bf5d300b448d638f3ba29 upstream.
While report_error_write() checks that the provided buffer is at least as large as the header struct, but not that it is large enough to contain the report with the length claimed by report->length. If user-space provides a short buffer, meaning a larger report->length than the actually written payload, up to around 4K of kernel data from past the kmalloc(len + 1) sized buffer allocated in kernfs_fop_write_iter() will leak into the SCLP report.
However, as the entity processing the SCLP is privileged and able to access at least the page including the report, this does not leak data that entity could not access but it is still an out of bounds read and a malformed error report that should be rejected.
--- arch/s390/pci/pci_sysfs.c | 3 +++ 1 file changed, 3 insertions(+)
arch/s390/pci/pci_sysfs.c +3 -0
@@ -138,6 +138,9 @@ static ssize_t report_error_write(structif (off || (count <sizeof (*report)))return -EINVAL ; +if (count < (report->length +sizeof (*report))) +return -EINVAL ; + ret =sclp_pci_report (report, zdev->fh, zdev->fid);return ret ? ret : count;
Greg Kroah-Hartman
maintainerPATCH 520/571 ipv4: avoid divide by zero in fib_rebalance
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zihan Xi <[email protected]>
commit 5046d2880fec7d49ebed2fd2866747ee1d06ad71 upstream.
fib_rebalance() computes the total eligible nexthop weight in one pass and programs upper bounds in a second pass. A concurrent change to ignore_routes_with_linkdown can make the first pass return zero while the second pass sees an eligible nexthop, resulting in division by zero.
If the first pass reports a zero total, set each nexthop upper bound to -1 and skip the division. This matches the IPv6 fix in commit d2c26c2911dd ("ipv6: avoid divide by zero in rt6_multipath_rebalance") and preserves the lock-free rebalance path.
--- net/ipv4/fib_semantics.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/fib_semantics.c +1 -1
@@ -855,7 +855,7 @@ static void fib_rebalance(struct fib_infchange_nexthops (fi) {int upper_bound; -if (nexthop_nh->fib_nh_flags &RTNH_F_DEAD ) { +if (!total || nexthop_nh->fib_nh_flags &RTNH_F_DEAD ) { upper_bound =-1 ; }else if (ip_ignore_linkdown (nexthop_nh->fib_nh_dev) && nexthop_nh->fib_nh_flags &RTNH_F_LINKDOWN ) {
Greg Kroah-Hartman
maintainerPATCH 521/571 mm/vmalloc: acquire init_mm lock on huge vmap to avoid ptdump UAF
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 26444eb71465c9934d9d418ef69c43f61185329b ]
Currently there is a nasty race between ptdump and vmap when attempting to map a huge P4D, PUD or PMD entry:
* ptdump walks kernel page table ranges it doesn't own.
* When vmap maps ranges it tries to promote existing ones to huge page tables in vmap_try_huge_[p4d,pud,pmd]() at P4D, PUD and PMD level, freeing the lower page table in [p4d,pud,pmd]_free_[pud,pmd,pte]_page() when it succeeds.
Both of these things can happen at the same time and as a result ptdump can access a freed page table, resulting in a use-after-free and memory corruption.
This is possible because while ptdump_walk_pgd() holds both the mem hotplug lock and the mmap write lock before invoking walk_page_range_novma(), vmap takes no relevant locks at all.
Fix this by holding the mmap read lock in vmap_try_huge_*() when freeing page tables.
The read lock is sufficient: ptdump is the only walker that must be excluded and it holds the mmap write lock. Other holders of the read lock may run concurrently, but each exclusively owns the range it operates on and cannot reach the page tables freed here.
We also hold the lock while assigning the huge page table entry, which means page table walkers observe only the huge or non-huge page table entry.
We use a trylock to prevent ptdump from blocking vmap making forward progress. This is fine because it's an optimisation in any case, and thus the vmap can safely proceed regardless.
All other kernel page table walkers that touch vmalloc ranges either exclusively own the memory walked or acquire the mmap lock, so this correctly excludes those walkers.
The issue has existed as long as ptdump was available and vmap freed page tables when promoting to a huge leaf entry, that is, since commit b6bdb7517c3d ("mm/vmalloc: add interfaces to free unmapped page table") for huge ioremap, and commit 121e6f3258fe ("mm/vmalloc: hugepage vmalloc mappings") for huge vmalloc.
Since the former is the earlier of the two we choose that for our Fixes tag.
This patch is based on work by David Carlier (linked), with gratitude!
[ ljs - Open-coded missing stuff + other smaller changes. Updated commit
msg to reflect. ]
--- mm/vmalloc.c | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-)
mm/vmalloc.c +39 -6
@@ -134,6 +134,8 @@ static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end, phys_addr_t phys_addr, pgprot_t prot, unsigned int max_page_shift) { + int ret = 0; +if (max_page_shift <PMD_SHIFT )return 0 ;
@@ -149,10 +151,23 @@ static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end,if (!IS_ALIGNED (phys_addr,PMD_SIZE ))return 0 ; -if (pmd_present (*pmd) && !pmd_free_pte_page (pmd, addr)) +if (!pmd_present (*pmd)) +return pmd_set_huge (pmd, phys_addr, prot); + +/* +* Acquire the mmap read lock to exclude ptdump, which walks +* kernel page tables it does not own under the mmap write lock. +* +* Concurrent read lock holders are safe: each exclusively owns +* the range it operates on and cannot reach this page table. +*/ +if (!mmap_read_trylock (&init_mm))return 0 ; +if (pmd_free_pte_page (pmd, addr)) + ret =pmd_set_huge (pmd, phys_addr, prot); +mmap_read_unlock (&init_mm); -return pmd_set_huge (pmd, phys_addr, prot); +return ret; } static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
@@ -184,6 +199,8 @@ static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end, phys_addr_t phys_addr, pgprot_t prot, unsigned int max_page_shift) { + int ret = 0; +if (max_page_shift <PUD_SHIFT )return 0 ;
@@ -199,10 +216,17 @@ static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end,if (!IS_ALIGNED (phys_addr,PUD_SIZE ))return 0 ; -if (pud_present (*pud) && !pud_free_pmd_page (pud, addr)) +if (!pud_present (*pud)) +return pud_set_huge (pud, phys_addr, prot); + +/* See comment in vmap_try_huge_pmd(). */ +if (!mmap_read_trylock (&init_mm))return 0 ; +if (pud_free_pmd_page (pud, addr)) + ret =pud_set_huge (pud, phys_addr, prot); +mmap_read_unlock (&init_mm); -return pud_set_huge (pud, phys_addr, prot); +return ret; } static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
@@ -235,6 +259,8 @@ static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end, phys_addr_t phys_addr, pgprot_t prot, unsigned int max_page_shift) { + int ret = 0; +if (max_page_shift <P4D_SHIFT )return 0 ;
@@ -250,10 +276,17 @@ static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end,if (!IS_ALIGNED (phys_addr,P4D_SIZE ))return 0 ; -if (p4d_present (*p4d) && !p4d_free_pud_page (p4d, addr)) +if (!p4d_present (*p4d)) +return p4d_set_huge (p4d, phys_addr, prot); + +/* See comment in vmap_try_huge_pmd(). */ +if (!mmap_read_trylock (&init_mm))return 0 ; +if (p4d_free_pud_page (p4d, addr)) + ret =p4d_set_huge (p4d, phys_addr, prot); +mmap_read_unlock (&init_mm); -return p4d_set_huge (p4d, phys_addr, prot); +return ret; } static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 522/571 drm/amdgpu: Fix VCE 3 ring align_mask
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Rosca <[email protected]>
[ Upstream commit 2ee9836545e690c9e66ec203445d7705959fd7a8 ]
The largest frame is 20 dwords, so 0xf mask is too small. This was always wrong, but we were lucky with the VCE_CMD_END commands inserted after fence and vm_flush.
--- drivers/gpu/drm/amd/amdgpu/vce_v3_0.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/vce_v3_0.c +1 -1
@@ -957,7 +957,7 @@ static const struct amdgpu_ring_funcs vce_v3_0_ring_phys_funcs = {static const struct amdgpu_ring_funcs vce_v3_0_ring_vm_funcs = { .type =AMDGPU_RING_TYPE_VCE , - .align_mask =0xf , + .align_mask =0x1f , .nop =VCE_CMD_NO_OP , .support_64bit_ptrs = false, .no_user_fence = true,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 523/571 security/keys: fix missed RCU read section on lookup
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linus Torvalds <[email protected]>
commit 43a1e3744548e6fd85873e6fb43e293eb4010694 upstream.
Nicholas Carlini reports that the keyring code calls assoc_array_find() in find_key_to_update() without holding the RCU read lock, while the assoc_array_gc() code really is designed around removing the node from the tree and then freeing it after an RCU grace-period.
The regular key handling doesn't see this because holding the keyring semaphore hides any lifetime issues, but the persistent key handling uses a different model.
Instead of extending the keyring locking, just do the simple RCU locking that the assoc_array was designed for.
[ Moved the guard at the top of the function to solve a compilation issue ]
--- security/keys/keyring.c | 1 + 1 file changed, 1 insertion(+)
security/keys/keyring.c +1 -0
@@ -1105,6 +1105,7 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref, {struct key *keyring, *key;const void *object; +guard (rcu)(); keyring =key_ref_to_ptr (keyring_ref);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 524/571 net/sched: cls_u32: skip hash tables in u32_bind_class()
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhang Changzhong <[email protected]>
[ Upstream commit 6d3724e616faf952c3adcf8414fc21a828ef3709 ]
u32_walk() enumerates both struct tc_u_hnode and struct tc_u_knode through the walker callback. u32_bind_class() unconditionally casts the passed fh to tc_u_knode and accesses &n->res, so when fh is actually a tc_u_hnode, which has no tcf_result member, this results in a slab-out-of-bounds read of res->classid in tc_cls_bind_class().
The issue can be reproduced with the following commands:
tc qdisc add dev lo root handle 1: hfsc
tc class add dev lo parent 1: classid 1:1 hfsc sc rate 1000kbit
tc filter add dev lo parent 1:1 protocol ip prio 1 u32 match u32 0 0 flowid 1:1 tc class add dev lo parent 1: classid 1:2 hfsc sc rate 2000kbit
Fix this by skipping hash tables via the TC_U32_KEY(handle) check.
--- net/sched/cls_u32.c | 3 +++ 1 file changed, 3 insertions(+)
net/sched/cls_u32.c +3 -0
@@ -1318,6 +1318,9 @@ static void u32_bind_class(void *fh, u32 classid, unsigned long cl, void *q, {struct tc_u_knode *n = fh; +if (TC_U32_KEY (n->handle) ==0 ) +return ; +if (n && n->res.classid == classid) {if (cl)__tcf_bind_filter (q, &n->res, base);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 525/571 OPP: Fix race between OPP addition and lookup
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Di Shen <[email protected]>
[ Upstream commit f5e1cc9a284bff2510981643a5bca4bc4c21b81a ]
A race exists between dev_pm_opp_add_dynamic() and dev_pm_opp_find_freq_exact():
CPU0 (add) CPU1 (lookup)
------------------------------- ------------------------------
_opp_add()
mutex_lock()
list_add(&new_opp->node, head)
mutex_unlock() _opp_table_find_key()
mutex_lock()
dev_pm_opp_get(opp)
kref_get()
mutex_unlock()
kref_init(&new_opp->kref)
dev_pm_opp_put()
kref_put_mutex()The newly added OPP is inserted into the list before its kref is initialized. A concurrent lookup can find this OPP and increment its reference count while it is still uninitialized, leading to refcount corruption and a potential premature free.
Fix this by initializing ->kref and ->opp_table before making the OPP visible via list_add(). This ensures any concurrent lookup observes a fully initialized object.
--- drivers/opp/core.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/opp/core.c +3 -3
@@ -1720,12 +1720,12 @@ int _opp_add(struct device *dev, struct dev_pm_opp *new_opp,return ret; } -list_add (&new_opp->node, head); -mutex_unlock (&opp_table->lock); - new_opp->opp_table = opp_table;kref_init (&new_opp->kref); +list_add (&new_opp->node, head); +mutex_unlock (&opp_table->lock); +opp_debug_create_one (new_opp, opp_table);if (!_opp_supported_by_regulators (new_opp, opp_table)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 526/571 KVM: x86/mmu: Preserve nested TDP shadow page tables if they are used as roots
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunwoo Kim <[email protected]>
[ Upstream commit 7a2c70e777a00c32ebafd376a6fe31ebb91c5b20 ]
kvm_mmu_zap_oldest_mmu_pages() excludes a shadow page whose root_count is non-zero from top-level reclaim, because such a page cannot be freed. The path in mmu_page_zap_pte() that recursively zaps a parentless nested TDP child has no such check. As a result, a shadow page can be zapped even if the page itself can't be freed; as the comment in kvm_mmu_zap_oldest_mmu_pages() notes, zapping it will just force vCPUs to rebuild the page.
As in top-level reclaim, do not recursively prepare zapping of a nested TDP child whose root_count is non-zero.
--- arch/x86/kvm/mmu/mmu.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/mmu.c +3 -1
@@ -2336,7 +2336,9 @@ static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,* avoids retaining a large number of stale nested SPs. */ if (tdp_enabled && invalid_list && - child->role.guest_mode && !child->parent_ptes.val) + child->role.guest_mode && + !child->root_count && + !child->parent_ptes.val)return kvm_mmu_prepare_zap_page (kvm, child, invalid_list); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 527/571 net: bridge: mcast: dont truncate the port group walk on teardown
In reply to Greg Kroah-Hartman5.15-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jun Yang <[email protected]>
commit 5a3f7a683aee56e1f15c9d53041f3236767eaae7 upstream.
__br_multicast_disable_port_ctx() and br_multicast_del_port() walk port->mglist with hlist_for_each_entry_safe(). However, br_multicast_find_del_pg() can also delete other entries from the same list through br_multicast_fwd_src_remove() or __fwd_del_star_excl().
If such an entry is the iterator's saved next node, hlist_del_init() clears its ->next and terminates the walk early. The reproducer triggers this in both teardown walks, leaving port groups in the bridge mdb with a dangling ->key.port after del_nbp() frees the port:
BUG: KASAN: slab-use-after-free in __mdb_fill_info+0x1191/0x1320 __mdb_fill_info+0x1191/0x1320 br_mdb_dump+0x594/0xe40 rtnl_mdb_dump+0x1cf/0x5d0
Use hlist_del_init_rcu() to unlink the group while preserving ->next. br_multicast_del_pg() and the teardown walks run under br->multicast_lock. The GC worker must acquire the same lock before detaching the group for destruction, so the node remains alive while the walk uses the preserved pointer.
Preserving ->next means a walk can now reach a group that an earlier iteration already deleted as a side effect. That group is off mp->ports, so br_multicast_find_del_pg() would fall through its port scan and hit the trailing WARN_ON(1). Skip such groups at the top of that helper: a port group is put on port->mglist when it is created and only unlinked when it is deleted, so hlist_unhashed() identifies exactly this case.
--- net/bridge/br_multicast.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-)
net/bridge/br_multicast.c +12 -1
@@ -689,7 +689,11 @@ static void __br_multicast_del_pg(structstruct hlist_node *tmp;rcu_assign_pointer (*pp, pg->next); -hlist_del_init (&pg->mglist); +/* Keep ->next (held under multicast_lock, freed later by the GC work): +* a port->mglist teardown walk may have latched this node as its next, +* and deleting other groups of the same port must not truncate it. +*/ +hlist_del_init_rcu (&pg->mglist);br_multicast_eht_clean_sets (pg);hlist_for_each_entry_safe (ent, tmp, &pg->src_list, node)br_multicast_del_group_src (ent, false);
@@ -723,6 +727,13 @@ static void br_multicast_find_del_pg(strstruct net_bridge_mdb_entry *mp;struct net_bridge_port_group *p; +/* A teardown walk over port->mglist can reach a group that an earlier +* iteration already deleted as a side effect. It is off mp->ports by +* now, so skip it instead of falling through to the WARN_ON() below. +*/ +if (hlist_unhashed (&pg->mglist)) +return ; + mp =br_mdb_ip_get (br, &pg->key.addr);if (WARN_ON (!mp))return ;