6.12.115-rc1 review
Greg Kroah-Hartman
maintainerPATCH 137/247 ext4: free the sbi after a grace period
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
[ Upstream commit c17b44266a1f9fcb49b894d4611d1254bf1aa313 ]
ext4_get_link() follows a symlink that keeps its target in a data block in rcu pathwalk mode with ext4_getblk(EXT4_GET_BLOCKS_CACHED_NOWAIT). That reads s_mount_state in the ASSERT() of ext4_getblk() and again in ext4_es_lookup_extent(), and the lookup bumps the extent status hit or miss counter, all through sb->s_fs_info.
ext4_put_super() destroys those counters, clears sb->s_fs_info and frees the sbi without waiting for a grace period. A pathwalk that is still in ext4_get_link() when the last reference to the mount goes away then dereferences a NULL s_fs_info, the freed sbi or the destroyed percpu counters.
With a pathwalk held up in ext4_get_link() while the last reference goes away:
KASAN: null-ptr-deref in range [0x00000000000000a8-0x00000000000000af] RIP: 0010:ext4_getblk+0xf0/0x640 Call Trace: <TASK> ext4_get_link+0x26c/0x410 pick_link+0xf96/0x1780 step_into_slowpath+0x9b8/0x1250 path_lookupat+0x484/0xb00 filename_lookup+0x1f1/0x5b0 vfs_statx+0xd7/0x3b0 vfs_fstatat+0x4d/0x90 __do_sys_newfstatat+0xa0/0x100 do_syscall_64+0x10e/0x5e0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
So far that has been hard to hit. umount(2) waits for a grace period in namespace_unlock() before it drops the mount, so only a mount whose last reference goes away elsewhere, like the close of a file or a chdir out of a lazily unmounted directory, can race a walker.
Keep sb->s_fs_info and free the sbi together with the extent status counters after a grace period. Split the counters out of ext4_es_unregister_shrinker() for that. The shrinker still gets wasted in ext4_put_super(), the counters go with the sbi.
--- fs/ext4/ext4.h | 2 ++ fs/ext4/extents_status.c | 7 ++++++- fs/ext4/extents_status.h | 1 + fs/ext4/super.c | 13 +++++++++++-- 4 files changed, 20 insertions(+), 3 deletions(-)
fs/ext4/ext4.h +2 -0
@@ -1663,6 +1663,8 @@ struct ext4_sb_info {struct list_head s_es_list;/* List of inodes with reclaimable extents */ long s_es_nr_inode;struct ext4_es_stats s_es_stats; +/* ext4_get_link() reads the sbi in rcu pathwalk */ +struct rcu_head s_rcu;struct mb_cache *s_ea_block_cache;struct mb_cache *s_ea_inode_cache;spinlock_t s_es_lock____cacheline_aligned_in_smp ;
fs/ext4/extents_status.c +6 -1
@@ -1766,12 +1766,17 @@ int ext4_es_register_shrinker(struct ext4_sb_info *sbi) }void ext4_es_unregister_shrinker (struct ext4_sb_info *sbi) +{ +shrinker_free (sbi->s_es_shrinker); +} + +/* ext4_get_link() bumps the hit and miss counters in rcu pathwalk */ +void ext4_es_destroy_stats (struct ext4_sb_info *sbi) {percpu_counter_destroy (&sbi->s_es_stats.es_stats_cache_hits);percpu_counter_destroy (&sbi->s_es_stats.es_stats_cache_misses);percpu_counter_destroy (&sbi->s_es_stats.es_stats_all_cnt);percpu_counter_destroy (&sbi->s_es_stats.es_stats_shk_cnt); -shrinker_free (sbi->s_es_shrinker); }/*
fs/ext4/extents_status.h +1 -0
@@ -237,6 +237,7 @@ static inline void ext4_es_store_pblock_status(struct extent_status *es,extern int ext4_es_register_shrinker (struct ext4_sb_info *sbi);extern void ext4_es_unregister_shrinker (struct ext4_sb_info *sbi); +extern void ext4_es_destroy_stats (struct ext4_sb_info *sbi);extern int ext4_seq_es_shrinker_info_show (struct seq_file *seq,void *v);
fs/ext4/super.c +11 -2
@@ -1289,6 +1289,14 @@ static void ext4_flex_groups_free(struct ext4_sb_info *sbi) } } +static void ext4_put_sbi_rcu (struct rcu_head *head) +{ + struct ext4_sb_info *sbi = container_of(head, struct ext4_sb_info, s_rcu); + +ext4_es_destroy_stats (sbi); +kfree (sbi); +} +static void ext4_put_super (struct super_block *sb) {struct ext4_sb_info *sbi =EXT4_SB (sb);
@@ -1381,7 +1389,6 @@ static void ext4_put_super(struct super_block *sb)ext4_stop_mmpd (sbi);brelse (sbi->s_sbh); - sb->s_fs_info =NULL ;/* * Now that we are completely done shutting down the * superblock, we need to actually destroy the kobject.
@@ -1396,7 +1403,8 @@ static void ext4_put_super(struct super_block *sb)#if IS_ENABLED (CONFIG_UNICODE )utf8_unload (sb->s_encoding);#endif -kfree (sbi); +/* ext4_get_link() reads the sbi and the counters in rcu pathwalk */ +call_rcu (&sbi->s_rcu, ext4_put_sbi_rcu); }static struct kmem_cache *ext4_inode_cachep;
@@ -5659,6 +5667,7 @@ failed_mount8: __maybe_unused } failed_mount3a:ext4_es_unregister_shrinker (sbi); +ext4_es_destroy_stats (sbi); failed_mount3:/* flush s_sb_upd_work before sbi destroy */ flush_work (&sbi->s_sb_upd_work);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 138/247 ASoC: SOF: ipc4-topology: Fix shift-out-of-bounds for aggregated ALH capture
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Ujfalusi <[email protected]>
[ Upstream commit 746de48c3a250f0c264105dcbfcdf0c5001e970b ]
When ch_count is smaller than blob->alh_cfg.device_count (e.g. a mono capture stream, such as a SmartMic, aggregated across multiple SDW links), step = ch_count / blob->alh_cfg.device_count truncates to 0. The subsequent GENMASK(step - 1, 0) then underflows step - 1 (u32) to UINT_MAX, causing GENMASK()'s internal shift to use an out-of-bounds exponent:
UBSAN: shift-out-of-bounds in sound/soc/sof/ipc4-topology.c:2363:13 shift exponent 18446744069414584384 is too large for 64-bit type 'long unsigned int'
Treat ch_count < device_count the same way as the existing "channels equal to output reference channels" case: apply the same ch_mask to every aggregated device instead of trying to split channels that can't be evenly divided.
--- sound/soc/sof/ipc4-topology.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
sound/soc/sof/ipc4-topology.c +14 -2
@@ -1973,8 +1973,20 @@ sof_ipc4_prepare_copier_module(struct snd_sof_widget *swidget, ch_map >>=4 ; } - step = ch_count / blob->alh_cfg.device_count; - mask =GENMASK (step -1 ,0 ); +if (ch_count < blob->alh_cfg.device_count) { +/* +* When there are fewer channels than aggregated devices +* (e.g. a mono capture stream split across multiple links), +* set step = 0 to ensure all the ch_mask is applied to all +* alh mappings. +*/ + mask = ch_mask; + step =0 ; + }else { + step = ch_count / blob->alh_cfg.device_count; + mask =GENMASK (step -1 ,0 ); + } +/* * Set each gtw_cfg.node_id to blob->alh_cfg.mapping[] * for all widgets with the same stream name
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 139/247 drm/xe: Bump LRU for external objects on exec and rebind
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Hellström <[email protected]>
[ Upstream commit d2ce8fcd778ee6d92748c92d23a56d4416c29d86 ]
The VM's private BOs get their LRU position refreshed in bulk via ttm_lru_bulk_move_tail() on vm->lru_bulk_move, both after a successful non-LR exec and after the LR preempt-fence rebind worker runs. External objects (BOs potentially shared across VMs) are never added to that per-VM bulk move list, so their LRU position is never refreshed by either path. This makes external objects in active use look more evictable than they are.
Add xe_vm_bump_lru(), which, under a single lru_lock critical section, performs the bulk move of the VM's private BOs and bumps each external object locked by the drm_exec transaction. Use it from both the non-LR exec path and the LR rebind worker, replacing the open-coded bulk move.
--- drivers/gpu/drm/xe/xe_exec.c | 7 ++----- drivers/gpu/drm/xe/xe_vm.c | 31 ++++++++++++++++++++++++++++--- drivers/gpu/drm/xe/xe_vm.h | 2 ++ 3 files changed, 32 insertions(+), 8 deletions(-)
drivers/gpu/drm/xe/xe_exec.c +2 -5
@@ -330,11 +330,8 @@ int xe_exec_ioctl(struct drm_device *dev, void *data, struct drm_file *file)xe_sched_job_push (job);xe_vm_reactivate_rebind (vm); -if (!err && !xe_vm_in_lr_mode (vm)) { -spin_lock (&xe->ttm.lru_lock); -ttm_lru_bulk_move_tail (&vm->lru_bulk_move); -spin_unlock (&xe->ttm.lru_lock); - } +if (!err && !xe_vm_in_lr_mode (vm)) +xe_vm_bump_lru (vm, exec);if (mode ==EXEC_MODE_LR )xe_hw_engine_group_resume_faulting_lr_jobs (group);
drivers/gpu/drm/xe/xe_vm.c +28 -3
@@ -439,6 +439,33 @@ int xe_vm_validate_rebind(struct xe_vm *vm, struct drm_exec *exec,return 0 ; } +/** +* xe_vm_bump_lru() - Bump the LRU position of BOs used by a submission +* @vm: The vm for which we are bumping LRUs. +* @exec: The struct drm_exec with the locked GEM objects. +* +* Move the VM's private BOs, and all external objects locked by @exec, +* to the LRU tail. Private BOs are moved in bulk using @vm's +* &xe_vm.lru_bulk_move. External objects, which may be shared with other +* VMs, are not part of that bulk move and are bumped individually. +*/ +void xe_vm_bump_lru (struct xe_vm *vm,struct drm_exec *exec) +{ +spinlock_t *lru_lock = &vm->xe->ttm.lru_lock; +struct drm_gem_object *obj; + +spin_lock (lru_lock); +ttm_lru_bulk_move_tail (&vm->lru_bulk_move); +drm_exec_for_each_locked_object (exec, obj) { +if (!drm_gpuvm_is_extobj (&vm->gpuvm, obj)) +continue ; + +ttm_bo_move_to_lru_tail (&gem_to_xe_bo (obj)->ttm); +cond_resched_lock (lru_lock); + } +spin_unlock (lru_lock); +} +static int xe_preempt_work_begin (struct drm_exec *exec,struct xe_vm *vm,bool *done) {
@@ -552,9 +579,7 @@ static void preempt_rebind_work_func(struct work_struct *w)#undef retry_required -spin_lock (&vm->xe->ttm.lru_lock); -ttm_lru_bulk_move_tail (&vm->lru_bulk_move); -spin_unlock (&vm->xe->ttm.lru_lock); +xe_vm_bump_lru (vm, &exec);/* Point of no return. */ arm_preempt_fences (vm, &preempt_fences);
drivers/gpu/drm/xe/xe_vm.h +2 -0
@@ -248,6 +248,8 @@ int xe_vm_lock_vma(struct drm_exec *exec, struct xe_vma *vma);int xe_vm_validate_rebind (struct xe_vm *vm,struct drm_exec *exec,unsigned int num_fences); +void xe_vm_bump_lru (struct xe_vm *vm,struct drm_exec *exec); +/** * xe_vm_resv() - Return's the vm's reservation object * @vm: The vm
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 140/247 tracing: Keep the predicate limit separate from program capacity
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Taeyang Lee <[email protected]>
[ Upstream commit 803aa6fc2dbea25ab9d3ed19eca1c96d0ab17445 ]
predicate_parse() adds two to nr_preds to reserve the terminal TRUE and FALSE entries. It also uses that increased value as the limit for parsed predicates. If the initial count is smaller than the number actually parsed, the program can fill the allocation and subsequent accesses can go past its end.
Keep nr_preds as the predicate limit and use a separate value for the allocation size. This leaves space for both terminal entries and a zeroed entry when parsing stops at the limit.
--- kernel/trace/trace_events_filter.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
kernel/trace/trace_events_filter.c +3 -4
@@ -482,18 +482,17 @@ predicate_parse(const char *str, int nr_parens, int nr_preds,int len;int N =0 ;int i; - - nr_preds +=2 ;/* For TRUE and FALSE */ +int nr_preds_alloc = nr_preds +2 ;/* For TRUE and FALSE */ op_stack =kmalloc_array (nr_parens,sizeof (*op_stack),GFP_KERNEL );if (!op_stack)return ERR_PTR (-ENOMEM ); - prog_stack =kcalloc (nr_preds,sizeof (*prog_stack),GFP_KERNEL ); + prog_stack =kcalloc (nr_preds_alloc,sizeof (*prog_stack),GFP_KERNEL );if (!prog_stack) {parse_error (pe, -ENOMEM ,0 ); goto out_free; } - inverts =kmalloc_array (nr_preds,sizeof (*inverts),GFP_KERNEL ); + inverts =kmalloc_array (nr_preds_alloc,sizeof (*inverts),GFP_KERNEL );if (!inverts) {parse_error (pe, -ENOMEM ,0 ); goto out_free;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 141/247 io_uring/cancel: dont spin on local work the task cant run
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>
[ Upstream commit fddcf4c5321b3ea5f72166c3fd36a9d1c34f80c7 ]
io_uring_cancel_generic() refuses to sleep while any ring on the exiting task's tctx has local work pending. It assumes the task is that ring's submitter and that the next io_uring_try_cancel_requests() pass will run the work. This does not hold for a ring that was still IORING_SETUP_R_DISABLED when the task got its tctx node from io_uring_create() or io_ringfd_register(). The submitter is set later by IORING_REGISTER_ENABLE_RINGS, possibly from another task, and only the submitter may run local work on an IORING_SETUP_DEFER_TASKRUN ring. To the exiting task the work stays pending forever, the loop never reaches schedule(), and the task trips the WARN_ON_ONCE() once and then spins in do_exit().
An unprivileged user can set this up at will by creating a disabled ring, having a child enable it and stop, posting to the ring with IORING_OP_MSG_RING and exiting with a request in flight that only the child can complete. The exiting thread burns a CPU until the child runs or dies, and with panic_on_warn set the WARN panics the kernel.
Fix by skipping the sleep only when io_allowed_defer_tw_run() allows the task to run the work. This is reasonable since work it cannot run cannot complete any of its requests either, so nothing is lost by sleeping. Drop the WARN_ON_ONCE() since handing a disabled ring to another thread is a supported scenario, not a bug state.
--- io_uring/io_uring.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
io_uring/io_uring.c +3 -4
@@ -3190,12 +3190,11 @@ __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)prepare_to_wait (&tctx->wait, &wait,TASK_INTERRUPTIBLE );io_run_task_work ();io_uring_drop_tctx_refs (current); +/* only skip the sleep for local work this task may run */ xa_for_each (&tctx->xa, index, node) { -if (!llist_empty (&node->ctx->work_llist)) { -WARN_ON_ONCE (node->ctx->submitter_task && - node->ctx->submitter_task != current); +if (!llist_empty (&node->ctx->work_llist) && +io_allowed_defer_tw_run (node->ctx)) goto end_wait; - } }/* * If we've seen completions, retry without waiting. This
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 142/247 virtio: set skb owner of virtio_transport_reset_no_sock() reply
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bobby Eshleman <[email protected]>
[ Upstream commit a6ae12a599e0f16bc01a38bcfe8d0278a26b5ee0 ]
Associate reply packets with the sending socket. When vsock must reply with an RST packet and there exists a sending socket (e.g., for loopback), setting the skb owner to the socket correctly handles reference counting between the skb and sk (i.e., the sk stays alive until the skb is freed).
This allows the net namespace to be used for socket lookups for the duration of the reply skb's lifetime, preventing race conditions between the namespace lifecycle and vsock socket search using the namespace pointer.
Stable-dep-of: dee44f41f206 ("vsock/virtio: validate packet source for connected sockets")
--- net/vmw_vsock/virtio_transport_common.c | 6 ++++++ 1 file changed, 6 insertions(+)
net/vmw_vsock/virtio_transport_common.c +6 -0
@@ -1313,6 +1313,12 @@ static int virtio_transport_reset_no_sock(const struct virtio_transport *t, .op = VIRTIO_VSOCK_OP_RST, .type = le16_to_cpu(hdr->type), .reply = true, + +/* Set sk owner to socket we are replying to (may be NULL for +* non-loopback). This keeps a reference to the sock and +* sock_net(sk) until the reply skb is freed. +*/ + .vsk = vsock_sk(skb->sk), };struct sk_buff *reply;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 143/247 vsock/virtio: validate packet source for connected sockets
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit dee44f41f206becb41c492899c1996cfd7f82a1b ]
virtio_transport_recv_pkt() looks up sockets first by the full source and destination tuple, then by destination only in the bound table. The fallback is needed for listening and connecting sockets, but sockets remain in the bound table after connect(), so it can also return a non-listening socket.
The fallback does not validate the source address. In TCP_SYN_SENT, a RESPONSE from an unrelated source can transition the victim socket to TCP_ESTABLISHED while its stored remote address remains unchanged. Subsequent RW packets from that source are delivered through the same destination-only fallback.
This was reproduced with capability-empty processes under different UIDs. The attacker discovered the target tuple through unprivileged AF_VSOCK sock_diag and caused the victim socket to read 16 attacker-chosen bytes; the intended peer-side socket read 0 of those 16 bytes.
Add vsock_check_source() to validate the transport, source port and source CID against the peer stored in a non-listening socket. The local transport is the CID exception because its packets are generated internally with VMADDR_CID_LOCAL as their source, including connections using CID aliases.
Use the helper after lock_sock() in the virtio receive path.
--- include/net/af_vsock.h | 3 +++ net/vmw_vsock/af_vsock.c | 32 +++++++++++++++++++++++++ net/vmw_vsock/virtio_transport_common.c | 3 ++- 3 files changed, 37 insertions(+), 1 deletion(-)
include/net/af_vsock.h +3 -0
@@ -216,6 +216,9 @@ void vsock_remove_connected(struct vsock_sock *vsk);struct sock *vsock_find_bound_socket (struct sockaddr_vm *addr);struct sock *vsock_find_connected_socket (struct sockaddr_vm *src,struct sockaddr_vm *dst); +bool vsock_check_source (const struct vsock_sock *vsk, +const struct vsock_transport *transport, +const struct sockaddr_vm *src);void vsock_remove_sock (struct vsock_sock *vsk);void vsock_for_each_connected_socket (struct vsock_transport *transport,void (*fn)(struct sock *sk));
net/vmw_vsock/af_vsock.c +32 -0
@@ -335,6 +335,38 @@ struct sock *vsock_find_connected_socket(struct sockaddr_vm *src, }EXPORT_SYMBOL_GPL (vsock_find_connected_socket); +/** +* vsock_check_source - validate a packet source against a socket peer +* @vsk: socket receiving the packet +* @transport: transport receiving the packet +* @src: source address from the packet +* +* Return: true if the packet arrived on the socket's assigned transport and +* its source matches the stored peer. Loopback packets are generated +* internally and always use the local CID as their source, including +* connections using a valid CID alias. +* +* The caller must hold the socket lock and must not call this for listening +* sockets, which accept packets from any source and have no assigned +* transport. +*/ +bool vsock_check_source (const struct vsock_sock *vsk, +const struct vsock_transport *transport, +const struct sockaddr_vm *src) +{ +if (vsk->transport != transport) +return false; + +if (src->svm_port != vsk->remote_addr.svm_port) +return false; + +if (src->svm_cid == vsk->remote_addr.svm_cid) +return true; + +return transport->get_local_cid () ==VMADDR_CID_LOCAL ; +} +EXPORT_SYMBOL_GPL (vsock_check_source); +void vsock_remove_sock (struct vsock_sock *vsk) {/* Transport reassignment must not remove the binding. */
net/vmw_vsock/virtio_transport_common.c +2 -1
@@ -1837,7 +1837,8 @@ void virtio_transport_recv_pkt(struct virtio_transport *t,* lock_sock (note: listener sockets are not assigned to any transport) */ if (sock_flag (sk,SOCK_DONE ) || - (sk->sk_state !=TCP_LISTEN && vsk->transport != &t->transport)) { + (sk->sk_state !=TCP_LISTEN && + !vsock_check_source (vsk, &t->transport, &src))) { (void )virtio_transport_reset_no_sock (t, skb);release_sock (sk);sock_put (sk);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 144/247 ipv4: udp: Create exceptions before socket matching
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ido Schimmel <[email protected]>
[ Upstream commit 4c3499f79f8c7e8561266bcc220a18538cec0458 ]
Currently, when ICMP Fragmentation Needed and Redirect Message packets are locally delivered and quote a UDP packet, a FIB nexthop exception (FNHE) is only created if the kernel can match the UDP packet to an existing socket.
This behavior allows off-path attackers to conduct a side-channel attack on the FNHE cache in order to discover the ephemeral port used by a connected UDP socket.
Commit 6457378fe796 ("ipv4: use siphash instead of Jenkins in fnhe_hashfun()") and commit 67d6d681e15b ("ipv4: make exception cache less predictible") tried to mitigate such attacks by making it harder for attackers to discover hash collisions in the FNHE cache and by randomizing the number of exceptions a hash bucket can hold, respectively. Unfortunately, both of the mitigations can be bypassed.
Instead, mitigate such attacks by always creating a FNHE, even before trying to find a matching socket. Do that by calling ipv4_update_pmtu() and ipv4_redirect(), the helpers used when the quoted packet did not originate from a socket.
This means that guesses (right or wrong) from an off-path attacker will always result in a FNHE being created or updated in the cache that the attacker can observe.
Pass an oif of 0, in a similar fashion to icmp_err(). This is also the oif used by the socket path for sockets that are not bound to a device.
Note that this does not allow attackers to create FNHEs that they could not create before, as both helpers can already be reached with little to no validation. For example, by sending an ICMP error that quotes an ICMP Echo Reply or one that quotes a UDP source port that matches a wildcard socket.
Also note that in the good case (matched socket) the above scheme comes at the cost of an extra route lookup, as the no socket helpers perform their own lookup before the one performed by ipv4_sk_update_pmtu() / ipv4_sk_redirect(). When the two resolve to different nexthops, it also results in two exceptions being created for the same destination IP. One in the FNHE cache of the nexthop resolved by the no socket helpers and another in the FNHE cache of the nexthop used by the socket.
--- net/ipv4/udp.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
net/ipv4/udp.c +10 -1
@@ -869,7 +869,16 @@ int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)int udp_err (struct sk_buff *skb,u32 info) { -return __udp4_lib_err (skb, info,dev_net (skb->dev)->ipv4.udp_table); +const int type =icmp_hdr (skb)->type; +const int code =icmp_hdr (skb)->code; +struct net *net =dev_net (skb->dev); + +if (type ==ICMP_DEST_UNREACH && code ==ICMP_FRAG_NEEDED ) +ipv4_update_pmtu (skb, net, info,0 ,IPPROTO_UDP ); +else if (type ==ICMP_REDIRECT ) +ipv4_redirect (skb, net,0 ,IPPROTO_UDP ); + +return __udp4_lib_err (skb, info, net->ipv4.udp_table); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 145/247 workqueue: release pwq pools by pool type
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Breno Leitao <[email protected]>
[ Upstream commit 3180ee71b676845603274c66f6bb5528939cf470 ]
Add is_percpu_pool() and test the pool directly for per cpu. Convert the other open-coded pool->cpu checks -- in put_unbound_pool(), pool_allowed_cpus() and the workqueue watchdog -- to the same helper.
No functional change.
Use a single-evaluation macro for is_percpu_pool() so the predicate conversion does not add a function. Keep the existing watchdog stall accounting; only its pool-type check needs to change. This preserves the release-path context needed by the pending-pwq lifetime fix.
Stable-dep-of: cf9c8aaea0d4 ("workqueue: Fix unbound pool lifetime for pending pwqs")
--- kernel/workqueue.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
kernel/workqueue.c +6 -4
@@ -1559,6 +1559,8 @@ work_func_t wq_worker_last_func(struct task_struct *task)return worker->last_func; } +#define is_percpu_pool (pool) ((pool)->cpu >= 0) +/** * wq_node_nr_active - Determine wq_node_nr_active to use * @wq: workqueue of interest
@@ -2683,7 +2685,7 @@ static struct worker *alloc_worker(int node)static cpumask_t *pool_allowed_cpus (struct worker_pool *pool) { -if (pool->cpu <0 && pool->attrs->affn_strict) +if (!is_percpu_pool (pool) && pool->attrs->affn_strict)return pool->attrs->__pod_cpumask;else return pool->attrs->cpumask;
@@ -4969,7 +4971,7 @@ static void put_unbound_pool(struct worker_pool *pool)return ;/* sanity checks */ -if (WARN_ON (!(pool->cpu <0 )) || +if (WARN_ON (is_percpu_pool (pool)) ||WARN_ON (!list_empty (&pool->worklist)))return ;
@@ -5121,7 +5123,7 @@ static void pwq_release_workfn(struct kthread_work *work)mutex_unlock (&wq->mutex); } -if (wq->flags &WQ_UNBOUND ) { +if (!is_percpu_pool (pool)) {mutex_lock (&wq_pool_mutex);put_unbound_pool (pool);mutex_unlock (&wq_pool_mutex);
@@ -7639,7 +7641,7 @@ static void wq_watchdog_timer_fn(struct timer_list *unused)/* did we stall? */ if (time_after (now, ts + thresh)) { lockup_detected = true; -if (pool->cpu >=0 && !(pool->flags &POOL_BH )) { +if (is_percpu_pool (pool) && !(pool->flags &POOL_BH )) { pool->cpu_stall = true; cpu_pool_stall = true; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 146/247 workqueue: Fix unbound pool lifetime for pending pwqs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yao Kai <[email protected]>
[ Upstream commit cf9c8aaea0d47410df8708bec195889f3a85cd3c ]
KASAN reports a use-after-free of an unbound worker_pool in node_activate_pending_pwq():
BUG: KASAN: slab-use-after-free in _raw_spin_trylock+0x6d/0x120 Read of size 4 at addr ffff8880089ce000 by task kworker/u22:0/318 CPU: 1 UID: 0 PID: 318 Comm: kworker/u22:0 Not tainted 7.2.0 #1 PREEMPT(lazy) Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014 Workqueue: 0x0 (flush-8:0) Call Trace: <TASK> dump_stack_lvl+0x53/0x70 print_report+0xce/0x610 kasan_report+0xce/0x100 _raw_spin_trylock+0x6d/0x120 pwq_dec_nr_in_flight+0x4b4/0xcb0 process_one_work+0x921/0x11a0 worker_thread+0x4d0/0xd20 kthread+0x2de/0x3c0 ret_from_fork+0x3aa/0x620 ret_from_fork_asm+0x1a/0x30 </TASK> Allocated by task 311: alloc_pwq+0x439/0xca0 apply_wqattrs_prepare+0x75e/0xd10 apply_workqueue_attrs_locked+0x44/0xa0 wq_nice_store+0x350/0x450 Freed by task 0: kfree+0x127/0x3b0 rcu_core+0x523/0x1780 handle_softirqs+0x1b3/0x610 Last potentially related work creation: put_unbound_pool+0x3f3/0x7d0 pwq_release_workfn+0x494/0x8e0 kthread_worker_fn+0x1ff/0x790
Canceling the last inactive work skips pwq_dec_nr_active(), so an empty pwq can remain on pending_pwqs when its refcnt reaches zero. pwq_release_workfn() currently puts the pool before removing that pwq. If this drops the last pool reference, the pool can be RCU-freed while the pwq remains reachable, and node_activate_pending_pwq() may trylock the freed pool->lock.
Remove the pwq from pending_pwqs before putting the pool.
--- kernel/workqueue.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/workqueue.c +6 -6
@@ -5123,12 +5123,6 @@ static void pwq_release_workfn(struct kthread_work *work)mutex_unlock (&wq->mutex); } -if (!is_percpu_pool (pool)) { -mutex_lock (&wq_pool_mutex); -put_unbound_pool (pool); -mutex_unlock (&wq_pool_mutex); - } -if (!list_empty (&pwq->pending_node)) {struct wq_node_nr_active *nna =wq_node_nr_active (pwq->wq, pwq->pool->node);
@@ -5138,6 +5132,12 @@ static void pwq_release_workfn(struct kthread_work *work)raw_spin_unlock_irq (&nna->lock); } +if (!is_percpu_pool (pool)) { +mutex_lock (&wq_pool_mutex); +put_unbound_pool (pool); +mutex_unlock (&wq_pool_mutex); + } +kfree_rcu (pwq, rcu);/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 147/247 i2c: viai2c-wmt: Replace dev_err() with dev_err_probe() in probe function
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Enrico Zanda <[email protected]>
[ Upstream commit 3b7d8d151a7ebebc5257766110c102ab173b5844 ]
This simplifies the code while improving log.
Stable-dep-of: aaabefc79b0f ("i2c: viai2c-wmt: Fix clock leak in wmt_i2c_probe()")
--- drivers/i2c/busses/i2c-viai2c-wmt.c | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-)
drivers/i2c/busses/i2c-viai2c-wmt.c +7 -13
@@ -44,16 +44,13 @@ static int wmt_i2c_reset_hardware(struct viai2c *i2c)int err; err =clk_prepare_enable (i2c->clk); -if (err) { -dev_err (i2c->dev,"failed to enable clock\n" ); -return err; - } +if (err) +return dev_err_probe (i2c->dev, err,"failed to enable clock\n" ); err =clk_set_rate (i2c->clk,20000000 );if (err) { -dev_err (i2c->dev,"failed to set clock = 20Mhz\n" );clk_disable_unprepare (i2c->clk); -return err; +return dev_err_probe (i2c->dev, err,"failed to set clock = 20Mhz\n" ); }writew (0 , i2c->base +VIAI2C_REG_CR );
@@ -121,10 +118,9 @@ static int wmt_i2c_probe(struct platform_device *pdev) "failed to request irq %i\n", i2c->irq); i2c->clk =of_clk_get (np,0 ); -if (IS_ERR (i2c->clk)) { -dev_err (&pdev->dev,"unable to request clock\n" ); -return PTR_ERR (i2c->clk); - } +if (IS_ERR (i2c->clk)) +return dev_err_probe (&pdev->dev,PTR_ERR (i2c->clk), +"unable to request clock\n" ); err =of_property_read_u32 (np,"clock-frequency" , &clk_rate);if (!err && clk_rate ==I2C_MAX_FAST_MODE_FREQ )
@@ -139,10 +135,8 @@ static int wmt_i2c_probe(struct platform_device *pdev) adap->dev.of_node = pdev->dev.of_node; err =wmt_i2c_reset_hardware (i2c); -if (err) { -dev_err (&pdev->dev,"error initializing hardware\n" ); +if (err)return err; - } err =i2c_add_adapter (adap);if (err)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 148/247 i2c: viai2c-wmt: Fix clock leak in wmt_i2c_probe()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
[ Upstream commit aaabefc79b0ff0018e8e3832169bbe359d0551fc ]
In wmt_i2c_probe(), i2c->clk is acquired using of_clk_get(). If any subsequent operation fails or when the module is unloaded, the clock reference count is never decremented via clk_put(), leading to a resource leak.
Switch to devm_clk_get() so that the clock is automatically managed and released.
--- drivers/i2c/busses/i2c-viai2c-wmt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/i2c/busses/i2c-viai2c-wmt.c +1 -1
@@ -117,7 +117,7 @@ static int wmt_i2c_probe(struct platform_device *pdev)return dev_err_probe (&pdev->dev, err,"failed to request irq %i\n" , i2c->irq); - i2c->clk =of_clk_get (np,0 ); + i2c->clk =devm_clk_get (&pdev->dev,NULL );if (IS_ERR (i2c->clk))return dev_err_probe (&pdev->dev,PTR_ERR (i2c->clk),"unable to request clock\n" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 149/247 futex: Fix mm reuse handling for FUT_OFF_MMSHARED
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jann Horn <[email protected]>
[ Upstream commit 3267512ad1c2cc0c7768c5b014dc2cceb398a801 ]
A FUT_OFF_MMSHARED futex is a shared futex that refers to an MM. It is possible for a process to wait on a shared futex with a different MM because a FUT_OFF_INODE waiter can be requeued onto a FUT_OFF_MMSHARED futex by another process.
This can cause FUT_OFF_MMSHARED waiters on a freed MM to consume wakeups intended for a newly allocated MM at the same address.
Fix it by keying FUT_OFF_MMSHARED using a unique 64-bit per-MM ID. Leave private futexes as before to avoid influencing the performance of the hotpath.
(Multi-threaded processes typically implicitly use FUT_OFF_MMSHARED by setting clear_child_tid such that it points into anonymous memory, which causes mm_release() in a multi-threaded mm to perform FUTEX_WAKE.)
--- include/linux/futex.h | 14 +++++++----- include/linux/mm_types.h | 3 +++ kernel/fork.c | 3 +++ kernel/futex/core.c | 47 ++++++++++++++++++++-------------------- 4 files changed, 39 insertions(+), 28 deletions(-)
include/linux/futex.h +9 -5
@@ -23,26 +23,30 @@ struct task_struct;* 01 : Shared futex (PTHREAD_PROCESS_SHARED) * mapped on a file (reference on the underlying inode) * 10 : Shared futex (PTHREAD_PROCESS_SHARED) -* (but private mapping on an mm, and reference taken on it) +* (but private mapping on an mm) */ -#define FUT_OFF_INODE 1/* We set bit 0 if key has a reference on inode */ -#define FUT_OFF_MMSHARED 2/* We set bit 1 if key has a reference on mm */ +#define FUT_OFF_INODE 1/* We set bit 0 if shared key identifies an inode */ +#define FUT_OFF_MMSHARED 2/* We set bit 1 if shared key identifies an mm */ union futex_key { +/* For FUT_OFF_INODE */ struct {u64 i_seq;unsigned long pgoff;unsigned int offset; } shared; + +/* For FUT_OFF_MMSHARED or private */ struct {union { -struct mm_struct *mm; -u64 __tmp; +struct mm_struct *mm;/* for private */ +u64 mm_seq;/* for FUT_OFF_MMSHARED */ };unsigned long address;unsigned int offset; } private; +struct {u64 ptr;unsigned long word;
include/linux/mm_types.h +3 -0
@@ -945,6 +945,9 @@ struct mm_struct {*/ seqcount_t mm_lock_seq;#endif +#ifdef CONFIG_FUTEX +atomic64_t futex_unique_id; +#endif unsigned long hiwater_rss;/* High-watermark of RSS usage */
kernel/fork.c +3 -0
@@ -1304,6 +1304,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,#endif mm_init_uprobes_state (mm);hugetlb_count_init (mm); +#ifdef CONFIG_FUTEX +atomic64_set (&mm->futex_unique_id,0 ); +#endif if (current->mm) { mm->flags =mmf_init_flags (current->mm->flags);
kernel/futex/core.c +24 -23
85 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 150/247 drm/i915/dmc: Harden DMC firmware payload parsing
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dibin Moolakadan Subrahmanian <[email protected]>
[ Upstream commit 8bb1858db453cd4250e3b633f5d2d09206024ca6 ]
Validate the conversion of the DMC firmware size from dwords to bytes using check_mul_overflow() before calculating the firmware payload size.
Reject zero-length payloads and zero MMIO counts in the DMC firmware header so malformed firmware is caught early. Also set dmc_fw_size only after the payload allocation succeeds.
--- drivers/gpu/drm/i915/display/intel_dmc.c | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-)
drivers/gpu/drm/i915/display/intel_dmc.c +16 -5
@@ -796,7 +796,7 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc, }/* Cache the dmc header info. */ -if (mmio_count > mmio_count_max) { +if (!mmio_count || mmio_count > mmio_count_max) {drm_err (&i915->drm,"DMC firmware has wrong mmio count %u\n" , mmio_count);return 0 ; }
@@ -819,13 +819,21 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,disable_dmc_evt (i915, dmc_id, dmc_info->mmioaddr[i], dmc_info->mmiodata[i]) ? " (disabling)" : ""); } - dmc_info->mmio_count = mmio_count; - dmc_info->start_mmioaddr = start_mmioaddr; rem_size -= header_len_bytes;/* fw_size is in dwords, so multiplied by 4 to convert into bytes. */ - payload_size = dmc_header->fw_size *4 ; +if (check_mul_overflow (dmc_header->fw_size,4u , &payload_size)) { +drm_err (&i915->drm,"DMC fw_size too large (%u dwords)\n" , + dmc_header->fw_size); +return 0 ; + } + +if (!payload_size) { +drm_err (&i915->drm,"DMC firmware has empty payload\n" ); +return 0 ; + } +if (rem_size < payload_size) goto error_truncated;
@@ -833,12 +841,15 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,drm_err (&i915->drm,"DMC FW too big (%u bytes)\n" , payload_size);return 0 ; } - dmc_info->dmc_fw_size = dmc_header->fw_size; dmc_info->payload =kmalloc (payload_size,GFP_KERNEL );if (!dmc_info->payload)return 0 ; + dmc_info->mmio_count = mmio_count; + dmc_info->start_mmioaddr = start_mmioaddr; + dmc_info->dmc_fw_size = dmc_header->fw_size; + payload = (u8 *)(dmc_header) + header_len_bytes;memcpy (dmc_info->payload, payload, payload_size);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 151/247 tracing: Fix ignored return value of resize_buffer_duplicate_size()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dmitry Kandybka <[email protected]>
[ Upstream commit 3110d09bb98e3ac66482a7b257548a1683ec6c1a ]
When tr->allocated_snapshot is true, resize_buffer_duplicate_size() is called to update the snapshot buffer size. However, its return value was not checked. In case of a failed resize this could lead next snapshot being incomplete.
Add resize_buffer_duplicate_size() result check and return error if resize fails.
Compile tested only.
Found by Linux Verification Center (linuxtesting.org) with SVACE.
--- kernel/trace/trace.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
kernel/trace/trace.c +4 -1
@@ -7275,9 +7275,12 @@ tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt,if (iter->cpu_file !=RING_BUFFER_ALL_CPUS )return -EINVAL ;#endif -if (tr->allocated_snapshot) +if (tr->allocated_snapshot) { ret =resize_buffer_duplicate_size (&tr->max_buffer, &tr->array_buffer, iter->cpu_file); +if (ret <0 ) +return ret; + } ret =tracing_arm_snapshot_locked (tr);if (ret)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 152/247 drm/amdgpu: free the userptr ranges when a CS fails after parser_bos
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit 1b4da805a0ba354a549ce07459c871c17dd94fe0 ]
amdgpu_cs_parser_bos() allocates an HMM range for every userptr entry of the BO list and looks up the user pages. Those ranges are only freed when amdgpu_cs_parser_bos() itself fails or when amdgpu_cs_submit() checks them under the notifier lock. If amdgpu_cs_patch_jobs(), amdgpu_cs_vm_handling(), amdgpu_cs_sync_rings() or the early part of amdgpu_cs_submit() fails, nothing frees them: neither amdgpu_cs_parser_fini() nor amdgpu_bo_list_free() touch e->range.
Each such CS then leaks the range, its hmm_pfns array (8 bytes per page of the userptr BO) and the BO reference the range holds. An IB on a ring that patches the CS in place (e.g. VCN) with an unmapped va_start fails in amdgpu_cs_patch_ibs() and takes this path.
Free the ranges on those error paths. Ranges amdgpu_cs_submit() already dropped are NULL, so freeing them again is a no-op.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c +6 -0
@@ -1449,6 +1449,7 @@ static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser)int amdgpu_cs_ioctl (struct drm_device *dev,void *data,struct drm_file *filp) {struct amdgpu_device *adev =drm_to_adev (dev); +struct amdgpu_bo_list_entry *e;struct amdgpu_cs_parser parser;int r;
@@ -1503,6 +1504,11 @@ int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)return 0 ; error_backoff: +/* amdgpu_cs_submit() only drops the ranges once it got that far. */ +amdgpu_bo_list_for_each_userptr_entry (e, parser.bo_list) { +amdgpu_ttm_tt_get_user_pages_done (e->bo->tbo.ttm, e->range); + e->range =NULL ; + }mutex_unlock (&parser.bo_list->bo_list_mutex); error_fini:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 153/247 sched_ext: Fix stall when a task enqueued with SCX_ENQ_LAST lands back on its CPUs local DSQ
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tejun Heo <[email protected]>
[ Upstream commit 7a9df76679633cf26e0fea882a684012c6ec245a ]
With SCX_OPS_ENQ_LAST, the last runnable task on a CPU is passed to ops.enqueue() instead of being kept running. Exiting tasks without SCX_OPS_ENQ_EXITING, migration disabled tasks without SCX_OPS_ENQ_MIGRATION_DISABLED and tasks on an offline rq skip ops.enqueue() and go straight to the local DSQ. This happens in put_prev_task_scx() after the pick has settled on idle, so nothing reschedules the CPU, which idles with the task queued until an unrelated wakeup lands on it or the watchdog fires.
scx_mitosis, which sets SCX_OPS_ENQ_LAST without SCX_OPS_ENQ_EXITING, hit this during mass cgroup teardown: exiting tasks stuck in exit_mmap() for over 40 seconds.
A task put on the local DSQ runs, as anywhere else. If the SCX_ENQ_LAST enqueue left the task on this CPU's local DSQ, set need_resched on the task being switched in, as proxy_resched_idle() does. resched_curr() would flag the task being put instead, and __schedule() clears that right after the pick.
--- kernel/sched/ext.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)
kernel/sched/ext.c +14 -4
@@ -730,8 +730,9 @@ enum scx_enq_flags {* %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the * %SCX_ENQ_LAST flag set. * -* The BPF scheduler is responsible for triggering a follow-up -* scheduling event. Otherwise, Execution may stall. +* If the task is queued on the local DSQ of the CPU it was running on, +* it continues to run. Otherwise, the CPU goes idle. A scheduler that +* wants a full dispatch cycle on the CPU should kick it. */ SCX_ENQ_LAST = 1LLU << 41,
@@ -3083,8 +3084,7 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p,/* * If @p is runnable but we're about to enter a lower * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell -* ops.enqueue() that @p is the only one available for this cpu, -* which should trigger an explicit follow-up scheduling event. +* ops.enqueue() that @p is the only one available for this cpu. * * Core scheduling can force this CPU idle while @p stays * runnable. @p's cookie then won't match the core's, so skip
@@ -3094,6 +3094,16 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p,WARN_ON_ONCE (sched_cpu_cookie_match (rq, p) && !static_branch_unlikely (&scx_ops_enq_last));do_enqueue_task (rq, p,SCX_ENQ_LAST ,-1 ); + +/* +* A task put on the local DSQ runs, as anywhere else. +* Here the insert can't reschedule on its own: the pick +* has settled on @next and @p is still curr, so +* resched_curr() would flag @p and __schedule() clears +* that right after the pick. Flag @next instead. +*/ +if (p->scx.dsq == &rq->scx.local_dsq) +set_tsk_need_resched (next); }else {do_enqueue_task (rq, p,0 ,-1 ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 154/247 cifs: add revalidation on FSCTL failure in smb2_duplicate_extents()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Frank Sorenson <[email protected]>
[ Upstream commit 53676a5e28231186c9f56d87b7998b640699bc15 ]
smb2_duplicate_extents() has no handling for FSCTL_DUPLICATE_EXTENTS_TO_FILE failure: when the FSCTL fails, local inode metadata may be stale from the pre-extension or from concurrent remote writes, but is never refreshed.
Force revalidation on FSCTL failure and use i_size_read() for the pre-extension check.
--- fs/smb/client/smb2ops.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/smb/client/smb2ops.c +6 -1
@@ -2292,7 +2292,7 @@ smb2_duplicate_extents(const unsigned int xid, trgtfile->fid.volatile_fid, tcon->tid, tcon->ses->Suid, src_off, dest_off, len); inode =d_inode (trgtfile->dentry); -if (inode->i_size < dest_off + len) { +if (i_size_read (inode) < dest_off + len) { rc =smb2_set_file_size (xid, tcon, trgtfile, dest_off + len, false);if (rc) goto duplicate_extents_out;
@@ -2318,6 +2318,11 @@ smb2_duplicate_extents(const unsigned int xid,if (ret_data_len >0 )cifs_dbg (FYI ,"Non-zero response length in duplicate extents\n" ); +if (rc) { +CIFS_I (inode)->time =0 ;/* force reval */ +cifs_invalidate_cache (inode,0 ); + } + duplicate_extents_out:if (rc) trace_smb3_clone_err(xid, srcfile->fid.volatile_fid,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 155/247 xfs: dont hold buffer locks across sync transaction commit in xfs_sync_sb_buf
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yun Zhou <[email protected]>
[ Upstream commit 41a28c865d1d5843f8cb9e0af17a8f4d9e2961ff ]
xfs_sync_sb_buf() holds sb/rtsb buffer locks across a synchronous xfs_trans_commit(), which flushes the CIL push workqueue internally. If shutdown occurs during the CIL push, xfs_buf_item_unpin() needs to lock these buffers to fail them, causing a deadlock:
setlabel: holds buf lock -> flush_workqueue(xfs-cil)
CIL push worker: xfs_buf_item_unpin -> xfs_buf_lock(same buf)
Remove the xfs_trans_bhold() calls so that commit releases the buffer locks normally. After the sync commit, re-acquire the buffers via mp->m_sb_bp / mp->m_rtsb_bp for the on-disk writeback.
--- fs/xfs/libxfs/xfs_sb.c | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-)
fs/xfs/libxfs/xfs_sb.c +7 -10
@@ -1186,26 +1186,23 @@ xfs_sync_sb_buf( struct xfs_mount *mp) {struct xfs_trans *tp; -struct xfs_buf *bp;int error; error =xfs_trans_alloc (mp, &M_RES (mp)->tr_sb,0 ,0 ,0 , &tp);if (error)return error; - bp =xfs_trans_getsb (tp);xfs_log_sb (tp); -xfs_trans_bhold (tp, bp);xfs_trans_set_sync (tp); error =xfs_trans_commit (tp);if (error) - goto out; -/* -* write out the sb buffer to get the changes to disk -*/ - error =xfs_bwrite (bp); -out: -xfs_buf_relse (bp); +return error; + +/* Re-acquire and write the sb to disk. */ +xfs_buf_lock (mp->m_sb_bp); + error =xfs_bwrite (mp->m_sb_bp); +xfs_buf_unlock (mp->m_sb_bp); +return error; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 156/247 rose: clear stale N(R)/N(S) before (re)transmitting a data frame
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_kick() transmits a skb_clone() of each data frame and keeps the original on ack_queue. The clone shares its data buffer with the original, so the sequence numbers that rose_send_iframe() ORs into byte 2 of the header are also left in the queued original.
After a RESET, rose_requeue_frames() puts those originals back on the write queue and rose_kick() sends them again with vs/vr restarted at zero. rose_send_iframe() only ORs the new values into byte 2, so the retransmitted frame carries the bitwise OR of the old and new N(R) and N(S). The peer rejects the invalid N(R) with a new RESET REQUEST, the frames are requeued again, and the two nodes reset each other forever.
This was observed on a live FPAC network: a White Pages circuit between two nodes looping on RESET REQUEST / RESET CONFIRMATION / DATA at about 2000 frames per second, with DATA frames resent as "R3 S7" right after a reset instead of "R0 S0", until the application was restarted.
Clear everything but the M bit before setting the sequence numbers, as x25_send_iframe() does for modulo 8 circuits.
--- net/rose/rose_out.c | 1 + 1 file changed, 1 insertion(+)
net/rose/rose_out.c +1 -0
@@ -34,6 +34,7 @@ static void rose_send_iframe(struct sock *sk, struct sk_buff *skb)if (skb ==NULL )return ; + skb->data[2 ] &=ROSE_M_BIT ; skb->data[2 ] |= (rose->vr <<5 ) &0xE0 ; skb->data[2 ] |= (rose->vs <<1 ) &0x0E ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 157/247 netrom: linearize and validate lengths in nr_rx_frame()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Fort <[email protected]>
Linearize skb and add targeted length checks in nr_rx_frame() to prevent out-of-bounds reads when processing malformed NET/ROM frames.
- Require skb to be linear and at least NR_NETWORK_LEN + NR_TRANSPORT_LEN (20 bytes) before reading network/transport fields.
- For the existing sockets path, ensure NR_CONNACK includes the window byte (>= 21 bytes), which nr_state1_machine() reads.
- For CONNREQ handling, ensure window (byte 20) and user address (bytes 21-27) are present (>= 28 bytes), and do so before nr_find_listener() so no listener reference can leak.
- Preserve existing BPQ extension handling:
- NR_CONNACK len == 22 -> 1 extra byte (TTL)
- NR_CONNREQ len == 37 -> 2 extra bytes (timeout)
nr_route_frame() only guarantees 15 bytes before handing a frame addressed to a local node to nr_rx_frame(), so a short frame received from any AX.25 neighbour is enough to trigger the over-read.
[F6BVP: v4 never reached mainline (whitespace-damaged posting, subsystem
removed in 7.1); rebased onto mod-orphan, added comments. Tested on a two-VM QEMU bench (6.12.94, mkiss link): an AX.25 peer sends CONNREQ frames truncated to 20 and 27 bytes; without this patch both are accepted as connections, the user callsign being read past the end of the frame; with it only the complete 35-byte CONNREQ is accepted.
v2: apply the CONNACK length check to a plain CONNACK only, so that 20-byte CONNACK|CHOKE refusals and resets are no longer dropped (reported by Sasha Levin). Same fix submitted to mod-orphan.]
--- net/netrom/af_netrom.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-)
net/netrom/af_netrom.c +21 -1
@@ -885,6 +885,11 @@ int nr_rx_frame(struct sk_buff *skb, struct net_device *dev)* skb->data points to the netrom frame start */ +if (skb_linearize (skb)) +return 0 ; +if (skb->len <NR_NETWORK_LEN +NR_TRANSPORT_LEN ) +return 0 ; + src = (ax25_address *)(skb->data +0 ); dest = (ax25_address *)(skb->data +7 );
@@ -927,6 +932,17 @@ int nr_rx_frame(struct sk_buff *skb, struct net_device *dev) }if (sk !=NULL ) { +/* +* nr_state1_machine() reads the window size at byte 20, but +* only for a plain CONNACK. A CONNACK with the choke flag set +* is a refusal or a reset, sent as a 20-byte frame by +* __nr_transmit_reply(), and must not be dropped here. +*/ +if (frametype ==NR_CONNACK && !flags && + skb->len <NR_NETWORK_LEN +NR_TRANSPORT_LEN +1 ) { +sock_put (sk); +return 0 ; + }bh_lock_sock (sk);skb_reset_transport_header (skb);
@@ -961,10 +977,14 @@ int nr_rx_frame(struct sk_buff *skb, struct net_device *dev)return 0 ; } - sk =nr_find_listener (dest); +/* Need window (byte 20) and user address (bytes 21-27) */ +if (skb->len <NR_NETWORK_LEN +NR_TRANSPORT_LEN +1 +AX25_ADDR_LEN ) +return 0 ; user = (ax25_address *)(skb->data +21 ); + sk =nr_find_listener (dest); +if (sk ==NULL ||sk_acceptq_is_full (sk) || (make =nr_make_new (sk)) ==NULL ) {nr_transmit_refusal (skb,0 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 158/247 netrom: require full NET/ROM headers in nr_route_frame()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Greg Kroah-Hartman <[email protected]>
nr_route_frame() only checked that an incoming frame was long enough for the two network layer addresses and the time-to-live byte, and did so against skb->len without making sure the bytes were in the linear part of the skb.
A valid NET/ROM network frame always carries the 5-byte transport header as well, so anything shorter than NR_NETWORK_LEN + NR_TRANSPORT_LEN (20 bytes) is malformed, whether it is for this node or in transit. Use pskb_may_pull() for that length, as suggested in review, so the header fields are also guaranteed to be linear before they are read here or later in nr_rx_frame().
[F6BVP: taken from the nr_route.c part of Greg's "netrom: do some basic forms of validation on incoming frames"; the nr_rx_frame() part is handled separately. Switched from a skb->len test to pskb_may_pull() following Simon Horman's review.]
--- net/netrom/nr_route.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
net/netrom/nr_route.c +4 -3
@@ -755,10 +755,11 @@ int nr_route_frame(struct sk_buff *skb, ax25_cb *ax25)struct sk_buff *nskb, *oskb;/* -* Reject malformed packets early. Check that it contains at least 2 -* addresses and 1 byte more for Time-To-Live +* Reject malformed packets early. Check that it contains at least +* the network and transport headers (20 bytes), and that they are +* in the linear part of the skb. */ -if (skb->len <2 *sizeof (ax25_address) +1 ) +if (!pskb_may_pull (skb,NR_NETWORK_LEN +NR_TRANSPORT_LEN ))return 0 ; nr_src = (ax25_address *)(skb->data +0 );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 159/247 net: netrom: validate source address in nr_find_socket()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mashiro Chen <[email protected]>
nr_find_socket() dispatches incoming NR_INFO frames into a connected socket by matching the frame's circuit index/id pair (bytes[15-16]) against the socket's my_index/my_id. It performs no validation of the frame's source callsign against the socket's dest_addr.
This means any node on the network can craft an NR_INFO frame with a guessed or brute-forced circuit index/id pair and have it accepted into an arbitrary STATE_3 connection as if it came from the legitimate peer. Circuit IDs are assigned sequentially starting at (1,1), making them predictable in practice.
Combined with other receive path bugs, this lets a third party feed frames into a circuit it does not own. nr_find_peer() already checks the source address for CONNREQ; do the same for the other frame types.
Fix by adding a source address parameter to nr_find_socket() and requiring it to match the socket's recorded dest_addr for all frame-dispatch lookups. The internal nr_find_next_circuit() caller, which only checks for circuit ID availability, passes NULL to skip the source check.
[F6BVP: rebased on mod-orphan; dropped the reference to an unassigned CVE from the changelog. Checked that every caller other than nr_find_next_circuit() is in nr_rx_frame() for non-CONNREQ frames, whose network source is the remote node recorded in dest_addr.]
--- net/netrom/af_netrom.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
net/netrom/af_netrom.c +7 -4
@@ -162,7 +162,8 @@ static struct sock *nr_find_listener(ax25_address *addr)/* * Find a connected NET/ROM socket given my circuit IDs. */ -static struct sock *nr_find_socket (unsigned char index,unsigned char id) +static struct sock *nr_find_socket (unsigned char index,unsigned char id, +const ax25_address *src) {struct sock *s;
@@ -170,7 +171,8 @@ static struct sock *nr_find_socket(unsigned char index, unsigned char id)sk_for_each (s, &nr_list) {struct nr_sock *nr =nr_sk (s); -if (nr->my_index == index && nr->my_id == id) { +if (nr->my_index == index && nr->my_id == id && + (!src || !ax25cmp (&nr->dest_addr, src))) {sock_hold (s); goto found; }
@@ -219,7 +221,8 @@ static unsigned short nr_find_next_circuit(void) j = id %256 ;if (i !=0 && j !=0 ) { -if ((sk=nr_find_socket (i, j)) ==NULL ) + sk =nr_find_socket (i, j,NULL ); +if (!sk)break ;sock_put (sk); }
@@ -928,7 +931,7 @@ int nr_rx_frame(struct sk_buff *skb, struct net_device *dev)if (frametype ==NR_CONNREQ ) sk =nr_find_peer (circuit_index, circuit_id, src);else - sk =nr_find_socket (circuit_index, circuit_id); + sk =nr_find_socket (circuit_index, circuit_id, src); }if (sk !=NULL ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 160/247 netrom: bound fragment reassembly in nr_queue_rx_frame()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
nr_sock.fraglen is an unsigned short, but nr_sendmsg() accepts messages of up to 65536 bytes, which nr_output() then splits into NR_INFO frames with the MORE flag. Reassembling such a message on the receiving side makes fraglen wrap to 0, so alloc_skb() returns a buffer far smaller than the data copied into it just after. The same happens with any stream of MORE fragments that adds up to more than 65535 bytes.
Mashiro Chen proposed rejecting fragments once the total would exceed USHRT_MAX by returning 1 to the caller. Review pointed out that this return value makes nr_state3_machine() put the frame back on the resequencing queue after nr_queue_rx_frame() has already pulled its headers, and that the limit would reject a legitimate 65536-byte message.
Instead:
- make fraglen an unsigned int, so a full 64 KiB message fits;
- when a message would grow beyond 65536 bytes, drop what has been gathered so far, consume the frame and return 0, so the caller does not retry it;
- discard the remaining fragments of that message up to its last fragment, using a new NR_COND_FRAG_DISCARD condition bit, rather than delivering its tail as a separate message.
--- include/net/netrom.h | 3 ++- net/netrom/nr_in.c | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-)
include/net/netrom.h +2 -1
@@ -46,6 +46,7 @@ enum {#define NR_COND_REJECT 0x02#define NR_COND_PEER_RX_BUSY 0x04#define NR_COND_OWN_RX_BUSY 0x08 +#define NR_COND_FRAG_DISCARD 0x10#define NR_DEFAULT_T1 120000/* Outstanding frames - 120 seconds */ #define NR_DEFAULT_T2 5000/* Response delay - 5 seconds */
@@ -74,7 +75,7 @@ struct nr_sock {unsigned short vs, vr, va, vl;unsigned char n2, n2count;unsigned long t1, t2, t4, idle; -unsigned short fraglen; +unsigned int fraglen;struct timer_list t1timer;struct timer_list t2timer;struct timer_list t4timer;
net/netrom/nr_in.c +26 -0
@@ -26,6 +26,9 @@#include <linux/interrupt.h> #include <net/netrom.h> +/* nr_sendmsg() never sends more than this in one message */ +#define NR_MAX_REASM_LEN 65536 +static int nr_queue_rx_frame (struct sock *sk,struct sk_buff *skb,int more) {struct sk_buff *skbo, *skbn = skb;
@@ -35,6 +38,29 @@ static int nr_queue_rx_frame(struct sock *sk, struct sk_buff *skb, int more)nr_start_idletimer (sk); +/* Rest of a message already found to be too long: drop it */ +if (nr->condition &NR_COND_FRAG_DISCARD ) { +if (!more) + nr->condition &= ~NR_COND_FRAG_DISCARD ; +kfree_skb (skb); +return 0 ; + } + +/* +* Give up on a message that would grow beyond what a peer may +* send. The frame is consumed rather than handed back to the +* caller, which would queue it again after skb_pull(). +*/ +if ((more || nr->fraglen >0 ) && + nr->fraglen + skb->len >NR_MAX_REASM_LEN ) { +skb_queue_purge (&nr->frag_queue); + nr->fraglen =0 ; +if (more) + nr->condition |=NR_COND_FRAG_DISCARD ; +kfree_skb (skb); +return 0 ; + } +if (more) { nr->fraglen += skb->len;skb_queue_tail (&nr->frag_queue, skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 161/247 ax25: fix OOB read after address header strip in ax25_rcv()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ashutosh Desai <[email protected]>
A crafted AX.25 frame with a valid address header but no control byte causes skb->len to reach zero after skb_pull() strips the header. The subsequent reads of skb->data[0] (control) and skb->data[1] (PID) are then out of bounds.
Linearize the skb after confirming the device is an AX.25 interface. Guard with skb->len < 1 after the pull - one byte suffices for LAPB control frames which have no PID byte. Add a separate skb->len < 2 check inside the UI branch before accessing the PID byte.
[F6BVP: v5 as posted on netdev; the author withdrew it only because the subsystem was being removed from the kernel that day. Applied unchanged.]
--- net/ax25/ax25_in.c | 9 +++++++++ 1 file changed, 9 insertions(+)
net/ax25/ax25_in.c +9 -0
@@ -199,6 +199,9 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev,if ((ax25_dev =ax25_dev_ax25dev (dev)) ==NULL ) goto free; +if (skb_linearize (skb)) + goto free; +/* * Parse the address header. */
@@ -217,6 +220,9 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev,*/ skb_pull (skb,ax25_addr_size (&dp)); +if (skb->len <1 ) + goto free; +/* For our port addresses ? */ if (ax25cmp (&dest, dev_addr) ==0 && dp.lastrepeat +1 == dp.ndigi) mine =1 ;
@@ -227,6 +233,9 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev,/* UI frame - bypass LAPB processing */ if ((*skb->data & ~0x10 ) ==AX25_UI && dp.lastrepeat +1 == dp.ndigi) { +if (skb->len <2 ) + goto free; +skb_set_transport_header (skb,2 );/* skip control and pid */ ax25_send_to_raw (&dest, skb, skb->data[1 ]);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 162/247 ax25: check frame length in ax25_decode() and ax25_rx_iframe()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
Two more reads on the receive path assume bytes that a short frame does not have:
- On a connection set up with SABME (modulo 128), ax25_decode() reads a two-byte control field for I and S frames (frame[1]) without checking that the second byte is there.
- ax25_rx_iframe() reads the PID byte of an I frame without checking that anything is left after the control field, so an I frame made of its control field alone is dispatched on a byte past its end. The same function also receives reassembled segments.
Return AX25_ILLEGAL from ax25_decode() when the control field is incomplete, which the state machines already handle as a malformed frame, and drop an I frame that has no PID byte. The first check in ax25_decode() also covers an empty frame on its own, independently of the length check proposed for ax25_rcv().
--- net/ax25/ax25_in.c | 4 ++++ net/ax25/ax25_subr.c | 7 +++++++ 2 files changed, 11 insertions(+)
net/ax25/ax25_in.c +4 -0
@@ -104,6 +104,10 @@ int ax25_rx_iframe(ax25_cb *ax25, struct sk_buff *skb)if (skb ==NULL )return 0 ; +/* An I frame must at least carry its PID byte */ +if (skb->len <1 ) +return 0 ; +ax25_start_idletimer (ax25); pid = *skb->data;
net/ax25/ax25_subr.c +7 -0
@@ -102,6 +102,9 @@ int ax25_decode(ax25_cb *ax25, struct sk_buff *skb, int *ns, int *nr, int *pf) frame = skb->data; *ns = *nr = *pf =0 ; +if (skb->len <1 ) +return frametype; +if (ax25->modulus ==AX25_MODULUS ) {if ((frame[0 ] &AX25_S ) ==0 ) { frametype =AX25_I ;/* I frame - carries NR/NS/PF */
@@ -118,6 +121,10 @@ int ax25_decode(ax25_cb *ax25, struct sk_buff *skb, int *ns, int *nr, int *pf) }skb_pull (skb,1 ); }else { +/* I and S frames carry a two-byte control field here */ +if ((frame[0 ] &AX25_U ) !=3 && skb->len <2 ) +return frametype; +if ((frame[0 ] &AX25_S ) ==0 ) { frametype =AX25_I ;/* I frame - carries NR/NS/PF */ *ns = (frame[0 ] >>1 ) &0x7F ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 163/247 net: ax25: fix integer overflow in ax25_rx_fragment()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mashiro Chen <[email protected]>
ax25_rx_fragment() accumulates fragment lengths into ax25_cb->fraglen, which is an unsigned short. When the total exceeds 65535, fraglen wraps around to a small value. The subsequent alloc_skb(fraglen) allocates a too-small buffer, and skb_put() in the copy loop triggers skb_over_panic().
Add pskb_may_pull(skb, 1) at function entry to ensure the segmentation header byte is in the linear data area before dereferencing skb->data. This also rejects zero-length skbs, which the original code did not check for.
Two issues in the overflow error path are also fixed:
First, the current skb, after skb_pull(skb, 1), is neither enqueued nor freed before returning 1, leaking it. Add kfree_skb(skb) before the return.
Second, ax25->fraglen is not reset after skb_queue_purge(). Add ax25->fraglen = 0 to restore a consistent state.
[F6BVP: v4 as posted on netdev; it was set aside only because the subsystem was being removed from the kernel. Applied unchanged.]
--- net/ax25/ax25_in.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
net/ax25/ax25_in.c +10 -0
@@ -35,12 +35,22 @@ static int ax25_rx_fragment(ax25_cb *ax25, struct sk_buff *skb) {struct sk_buff *skbn, *skbo; +if (!pskb_may_pull (skb,1 )) +return 0 ; +if (ax25->fragno !=0 ) {if (!(*skb->data &AX25_SEG_FIRST )) {if ((ax25->fragno -1 ) == (*skb->data &AX25_SEG_REM )) {/* Enqueue fragment */ ax25->fragno = *skb->data &AX25_SEG_REM ;skb_pull (skb,1 );/* skip fragno */ +if (ax25->fraglen + skb->len >USHRT_MAX ) { +kfree_skb (skb); +skb_queue_purge (&ax25->frag_queue); + ax25->fragno =0 ; + ax25->fraglen =0 ; +return 1 ; + } ax25->fraglen += skb->len;skb_queue_tail (&ax25->frag_queue, skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 164/247 netrom: use a single lock for the node and neighbour lists
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
NET/ROM routing uses three kinds of locks: nr_node_list_lock, nr_neigh_list_lock and a lock in every nr_node. They are taken in opposite orders on different paths:
- nr_del_node() and nr_dec_obs() take the node list lock, then a node lock, then the neighbour list lock (through nr_remove_neigh());
- nr_add_node(), called for every frame received from a neighbour, holds a node lock and takes the neighbour list lock;
- nr_rt_device_down() takes the neighbour list lock, then the node list lock, then each node lock.
Taking an interface down while routes are being changed or frames are coming in can therefore deadlock, which is what the open syzbot reports against nr_del_node(), nr_remove_neigh() and nr_rt_device_down() show. Fixing the order case by case was tried several times and never covered every combination.
As suggested by Jakub, replace all three with one nr_route_lock that covers both lists and the routes of every node. The per-node lock goes
away: with the lists and routes[] under the same lock it no longer protects anything, and routing tables are small and change rarely. nr_remove_neigh() gets a variant for callers that already hold the lock. Node refcounting is unchanged apart from the hold/put pair that nr_node_lock()/nr_node_unlock() used to add around each critical section.
nr_route_frame() still calls ax25_send_frame() with the lock held, as it did under the node lock, so the lock is documented as never to be taken with an AX.25 list lock held; nr_link_failed() is called from AX.25 with only linkfail_lock held.
No change in behaviour otherwise; the other issues found on the way (unlocked updates of nr_neigh->ax25 and failed, duplicate entries from concurrent nr_add_node(), a reference leak in nr_rt_device_down()) are left for separate patches.
--- include/net/netrom.h | 15 ----- net/netrom/nr_route.c | 133 +++++++++++++++++++----------------------- 2 files changed, 59 insertions(+), 89 deletions(-)
include/net/netrom.h +0 -15
@@ -115,7 +115,6 @@ struct nr_node {unsigned char count;struct nr_route routes[3 ];refcount_t refcount; -spinlock_t node_lock; };/*********************************************************************
@@ -145,20 +144,6 @@ static __inline__ void nr_neigh_put(struct nr_neigh *nr_neigh) } } -/* nr_node_lock and nr_node_unlock also hold/put the node's refcounter. -*/ -static __inline__void nr_node_lock (struct nr_node *nr_node) -{ -nr_node_hold (nr_node); -spin_lock_bh (&nr_node->node_lock); -} - -static __inline__void nr_node_unlock (struct nr_node *nr_node) -{ -spin_unlock_bh (&nr_node->node_lock); -nr_node_put (nr_node); -} -#define nr_neigh_for_each (__nr_neigh, list) \ hlist_for_each_entry(__nr_neigh, list, neigh_node)
net/netrom/nr_route.c +59 -74
408 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 165/247 netrom: look up and update routes in one critical section
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
nr_add_node(), nr_del_node(), nr_add_neigh() and nr_del_neigh() look up a node or neighbour with nr_node_get()/nr_neigh_get_dev(), which take and drop the routing lock, and only then take the lock again to change the routes. In between, another task can unlink the object they found. nr_add_node() can then store a neighbour that is no longer on nr_neigh_list in a node's routes; that route's reference becomes the last one, and the next time the route is dropped the neighbour is freed and read again straight away:
nr_neigh->count--; nr_neigh_put(nr_neigh); /* frees it */ if (nr_neigh->count == 0 && ...) /* use after free */
This is what syzbot reports in nr_add_node() (evicting the worst of three routes) and in nr_dec_obs() through nr_rt_ioctl(). Lizhi Xu analysed the first race; the fix posted then filtered neighbours by refcount and was not taken.
Now that one lock covers both lists and the routes, do the lookup and the update in a single critical section in all four functions, using new __nr_node_get()/__nr_neigh_get_dev() variants that expect the lock to be held. A node or neighbour found there stays linked while it is used, so a route can no longer outlive its neighbour's list entry. Concurrent additions of the same node or neighbour no longer create duplicate entries either.
Also factor the "drop one route's use of a neighbour" sequence into nr_neigh_route_put_locked(), which reads count and locked before dropping the reference, and use it in nr_add_node(), nr_del_node() and nr_dec_obs().
nr_add_node() is also called from nr_route_frame() in softirq context, where the kmemdup(GFP_KERNEL) of the digipeater list could sleep; the neighbour creation shared with nr_add_neigh() now allocates with GFP_ATOMIC, like the rest of nr_add_node() already did.
This depends on "netrom: use a single lock for the node and neighbour lists".
--- net/netrom/nr_route.c | 264 ++++++++++++++++++++++-------------------- 1 file changed, 138 insertions(+), 126 deletions(-)
net/netrom/nr_route.c +138 -126
@@ -47,38 +47,44 @@ static DEFINE_SPINLOCK(nr_route_lock);static HLIST_HEAD (nr_node_list);static HLIST_HEAD (nr_neigh_list); -static struct nr_node *nr_node_get (ax25_address *callsign) +static struct nr_node *__nr_node_get (ax25_address *callsign) { -struct nr_node *found =NULL ;struct nr_node *nr_node; -spin_lock_bh (&nr_route_lock); +lockdep_assert_held (&nr_route_lock); +nr_node_for_each (nr_node, &nr_node_list)if (ax25cmp (callsign, &nr_node->callsign) ==0 ) {nr_node_hold (nr_node); - found = nr_node; -break ; +return nr_node; } +return NULL ; +} + +static struct nr_node *nr_node_get (ax25_address *callsign) +{ +struct nr_node *found; + +spin_lock_bh (&nr_route_lock); + found =__nr_node_get (callsign);spin_unlock_bh (&nr_route_lock);return found; } -static struct nr_neigh *nr_neigh_get_dev (ax25_address *callsign, -struct net_device *dev) +static struct nr_neigh *__nr_neigh_get_dev (ax25_address *callsign, +struct net_device *dev) { -struct nr_neigh *found =NULL ;struct nr_neigh *nr_neigh; -spin_lock_bh (&nr_route_lock); +lockdep_assert_held (&nr_route_lock); +nr_neigh_for_each (nr_neigh, &nr_neigh_list)if (ax25cmp (callsign, &nr_neigh->callsign) ==0 && nr_neigh->dev == dev) {nr_neigh_hold (nr_neigh); - found = nr_neigh; -break ; +return nr_neigh; } -spin_unlock_bh (&nr_route_lock); -return found; +return NULL ; }static void nr_remove_neigh_locked (struct nr_neigh *nr_neigh);
@@ -96,6 +102,66 @@ static void re_sort_routes(struct nr_node *nr_node, int x, int y) } } +/* +* Allocate a neighbour and link it into nr_neigh_list. The list holds one +* reference and the caller gets another one. Called with nr_route_lock held. +*/ +static struct nr_neigh *nr_neigh_create_locked (ax25_address *callsign, +ax25_digi *ax25_digi, +struct net_device *dev, +unsigned int quality, +unsigned char locked) +{ +struct nr_neigh *nr_neigh; + +lockdep_assert_held (&nr_route_lock); + + nr_neigh =kmalloc (sizeof (*nr_neigh),GFP_ATOMIC ); +if (!nr_neigh) +return NULL ; + + nr_neigh->callsign = *callsign; + nr_neigh->digipeat =NULL ; + nr_neigh->ax25 =NULL ; + nr_neigh->dev = dev; + nr_neigh->quality = quality; + nr_neigh->locked = locked; + nr_neigh->count =0 ; + nr_neigh->number = nr_neigh_no++; + nr_neigh->failed =0 ; +refcount_set (&nr_neigh->refcount,1 ); + +if (ax25_digi && ax25_digi->ndigi >0 ) { + nr_neigh->digipeat =kmemdup (ax25_digi,sizeof (*ax25_digi), +GFP_ATOMIC ); +if (!nr_neigh->digipeat) { +kfree (nr_neigh); +return NULL ; + } + } + +hlist_add_head (&nr_neigh->neigh_node, &nr_neigh_list); +nr_neigh_hold (nr_neigh); + +return nr_neigh; +} + +/* +* Drop one route's use of a neighbour. The neighbour is unlinked when no +* route uses it any more and it was not added explicitly; count and locked +* are read before the route's reference is dropped, since that reference +* may be the last one. Called with nr_route_lock held. +*/ +static void nr_neigh_route_put_locked (struct nr_neigh *nr_neigh) +{ +lockdep_assert_held (&nr_route_lock); + + nr_neigh->count--; +if (nr_neigh->count ==0 && !nr_neigh->locked) +nr_remove_neigh_locked (nr_neigh); +nr_neigh_put (nr_neigh); +} +/* * Add a new route to a node, and in the process add the node and the * neighbour if it is new.
@@ -106,7 +172,7 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic, {struct nr_node *nr_node;struct nr_neigh *nr_neigh; -int i, found; +int i, found, ret =0 ;struct net_device *odev;if ((odev=nr_dev_get (nr)) !=NULL ) {/* Can't add routes to ourself */
@@ -114,9 +180,15 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,return -EINVAL ; } - nr_node =nr_node_get (nr); +/* +* Look up and update under one critical section, so that a node or +* neighbour found here cannot be unlinked before it is used. +*/ +spin_lock_bh (&nr_route_lock); + + nr_node =__nr_node_get (nr); - nr_neigh =nr_neigh_get_dev (ax25, dev); + nr_neigh =__nr_neigh_get_dev (ax25, dev);/* * The L2 link to a neighbour has failed in the past
@@ -127,14 +199,12 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,if (nr_neigh !=NULL && nr_neigh->failed !=0 && quality ==0 ) {struct nr_node *nr_nodet; -spin_lock_bh (&nr_route_lock);nr_node_for_each (nr_nodet, &nr_node_list) {for (i =0 ; i < nr_nodet->count; i++)if (nr_nodet->routes[i].neighbour == nr_neigh)if (i < nr_nodet->which) nr_nodet->which = i; } -spin_unlock_bh (&nr_route_lock); }if (nr_neigh !=NULL )
@@ -143,43 +213,19 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,if (quality ==0 && nr_neigh !=NULL && nr_node !=NULL ) {nr_neigh_put (nr_neigh);nr_node_put (nr_node); -return 0 ; + goto out; }if (nr_neigh ==NULL ) { -if ((nr_neigh =kmalloc (sizeof (*nr_neigh),GFP_ATOMIC )) ==NULL ) { +unsigned int q =READ_ONCE (sysctl_netrom_default_path_quality); + + nr_neigh =nr_neigh_create_locked (ax25, ax25_digi, dev, q,0 ); +if (!nr_neigh) {if (nr_node)nr_node_put (nr_node); -return -ENOMEM ; - } - - nr_neigh->callsign = *ax25; - nr_neigh->digipeat =NULL ; - nr_neigh->ax25 =NULL ; - nr_neigh->dev = dev; - nr_neigh->quality =READ_ONCE (sysctl_netrom_default_path_quality); - nr_neigh->locked =0 ; - nr_neigh->count =0 ; - nr_neigh->number = nr_neigh_no++; - nr_neigh->failed =0 ; -refcount_set (&nr_neigh->refcount,1 ); - -if (ax25_digi !=NULL && ax25_digi->ndigi >0 ) { - nr_neigh->digipeat =kmemdup (ax25_digi, -sizeof (*ax25_digi), -GFP_KERNEL ); -if (nr_neigh->digipeat ==NULL ) { -kfree (nr_neigh); -if (nr_node) -nr_node_put (nr_node); -return -ENOMEM ; - } + ret = -ENOMEM ; + goto out; } - -spin_lock_bh (&nr_route_lock); -hlist_add_head (&nr_neigh->neigh_node, &nr_neigh_list); -nr_neigh_hold (nr_neigh); -spin_unlock_bh (&nr_route_lock); }if (quality !=0 &&ax25cmp (nr, ax25) ==0 && !nr_neigh->locked)
@@ -187,9 +233,9 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,if (nr_node ==NULL ) {if ((nr_node =kmalloc (sizeof (*nr_node),GFP_ATOMIC )) ==NULL ) { -if (nr_neigh) -nr_neigh_put (nr_neigh); -return -ENOMEM ; +nr_neigh_put (nr_neigh); + ret = -ENOMEM ; + goto out; } nr_node->callsign = *nr;
@@ -206,15 +252,12 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,nr_neigh_hold (nr_neigh); nr_neigh->count++; -spin_lock_bh (&nr_route_lock);hlist_add_head (&nr_node->node_node, &nr_node_list);/* refcount initialized at 1 */ -spin_unlock_bh (&nr_route_lock);nr_neigh_put (nr_neigh); -return 0 ; + goto out; } -spin_lock_bh (&nr_route_lock);if (quality !=0 )strscpy (nr_node->mnemonic, mnemonic);
@@ -245,11 +288,7 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic, }else {/* It must be better than the worst */ if (quality > nr_node->routes[2 ].quality) { - nr_node->routes[2 ].neighbour->count--; -nr_neigh_put (nr_node->routes[2 ].neighbour); - -if (nr_node->routes[2 ].neighbour->count ==0 && !nr_node->routes[2 ].neighbour->locked) -nr_remove_neigh_locked (nr_node->routes[2 ].neighbour); +nr_neigh_route_put_locked (nr_node->routes[2 ].neighbour); nr_node->routes[2 ].quality = quality; nr_node->routes[2 ].obs_count = obs_count;
@@ -283,9 +322,10 @@ static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic, }nr_neigh_put (nr_neigh); -spin_unlock_bh (&nr_route_lock);nr_node_put (nr_node); -return 0 ; +out: +spin_unlock_bh (&nr_route_lock); +return ret; }static void nr_remove_node_locked (struct nr_node *nr_node)
@@ -304,13 +344,6 @@ static void nr_remove_neigh_locked(struct nr_neigh *nr_neigh)nr_neigh_put (nr_neigh); } -static void nr_remove_neigh (struct nr_neigh *nr_neigh) -{ -spin_lock_bh (&nr_route_lock); -nr_remove_neigh_locked (nr_neigh); -spin_unlock_bh (&nr_route_lock); -} -/* * "Delete" a node. Strictly speaking remove a route to a node. The node * is only deleted if no routes are left to it.
@@ -319,28 +352,25 @@ static int nr_del_node(ax25_address *callsign, ax25_address *neighbour, struct n {struct nr_node *nr_node;struct nr_neigh *nr_neigh; -int i; +int i, ret = -EINVAL ; - nr_node =nr_node_get (callsign); +spin_lock_bh (&nr_route_lock); + + nr_node =__nr_node_get (callsign);if (nr_node ==NULL ) -return -EINVAL ; + goto out; - nr_neigh =nr_neigh_get_dev (neighbour, dev); + nr_neigh =__nr_neigh_get_dev (neighbour, dev);if (nr_neigh ==NULL ) {nr_node_put (nr_node); -return -EINVAL ; + goto out; } -spin_lock_bh (&nr_route_lock);for (i =0 ; i < nr_node->count; i++) {if (nr_node->routes[i].neighbour == nr_neigh) { - nr_neigh->count--; -nr_neigh_put (nr_neigh); - -if (nr_neigh->count ==0 && !nr_neigh->locked) -nr_remove_neigh_locked (nr_neigh); +nr_neigh_route_put_locked (nr_neigh);nr_neigh_put (nr_neigh); nr_node->count--;
@@ -360,16 +390,15 @@ static int nr_del_node(ax25_address *callsign, ax25_address *neighbour, struct n }nr_node_put (nr_node); } -spin_unlock_bh (&nr_route_lock); - -return 0 ; + ret =0 ; + goto out; } }nr_neigh_put (nr_neigh); -spin_unlock_bh (&nr_route_lock);nr_node_put (nr_node); - -return -EINVAL ; +out: +spin_unlock_bh (&nr_route_lock); +return ret; }/*
@@ -379,44 +408,25 @@ static int __must_check nr_add_neigh(ax25_address *callsign, ax25_digi *ax25_digi, struct net_device *dev, unsigned int quality) { struct nr_neigh *nr_neigh; +int ret =0 ; - nr_neigh =nr_neigh_get_dev (callsign, dev); +spin_lock_bh (&nr_route_lock); + + nr_neigh =__nr_neigh_get_dev (callsign, dev);if (nr_neigh) { nr_neigh->quality = quality; nr_neigh->locked =1 ; -nr_neigh_put (nr_neigh); -return 0 ; - } - -if ((nr_neigh =kmalloc (sizeof (*nr_neigh),GFP_ATOMIC )) ==NULL ) -return -ENOMEM ; - - nr_neigh->callsign = *callsign; - nr_neigh->digipeat =NULL ; - nr_neigh->ax25 =NULL ; - nr_neigh->dev = dev; - nr_neigh->quality = quality; - nr_neigh->locked =1 ; - nr_neigh->count =0 ; - nr_neigh->number = nr_neigh_no++; - nr_neigh->failed =0 ; -refcount_set (&nr_neigh->refcount,1 ); - -if (ax25_digi !=NULL && ax25_digi->ndigi >0 ) { - nr_neigh->digipeat =kmemdup (ax25_digi,sizeof (*ax25_digi), -GFP_KERNEL ); -if (nr_neigh->digipeat ==NULL ) { -kfree (nr_neigh); -return -ENOMEM ; - } + }else { + nr_neigh =nr_neigh_create_locked (callsign, ax25_digi, dev, + quality,1 ); +if (!nr_neigh) + ret = -ENOMEM ; } +if (nr_neigh) +nr_neigh_put (nr_neigh); -spin_lock_bh (&nr_route_lock); -hlist_add_head (&nr_neigh->neigh_node, &nr_neigh_list); -/* refcount is initialized at 1 */ spin_unlock_bh (&nr_route_lock); - -return 0 ; +return ret; }/*
@@ -427,17 +437,23 @@ static int nr_del_neigh(ax25_address *callsign, struct net_device *dev, unsigned {struct nr_neigh *nr_neigh; - nr_neigh =nr_neigh_get_dev (callsign, dev); +spin_lock_bh (&nr_route_lock); + + nr_neigh =__nr_neigh_get_dev (callsign, dev); -if (nr_neigh ==NULL )return -EINVAL ; +if (nr_neigh ==NULL ) { +spin_unlock_bh (&nr_route_lock); +return -EINVAL ; + } nr_neigh->quality = quality; nr_neigh->locked =0 ;if (nr_neigh->count ==0 ) -nr_remove_neigh (nr_neigh); +nr_remove_neigh_locked (nr_neigh);nr_neigh_put (nr_neigh); +spin_unlock_bh (&nr_route_lock);return 0 ; }
@@ -463,11 +479,7 @@ static int nr_dec_obs(void)case 1 :/* From 1 -> 0 */ nr_neigh = s->routes[i].neighbour; - nr_neigh->count--; -nr_neigh_put (nr_neigh); - -if (nr_neigh->count ==0 && !nr_neigh->locked) -nr_remove_neigh_locked (nr_neigh); +nr_neigh_route_put_locked (nr_neigh); s->count--;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 166/247 netrom: fix reference count leak in nr_rt_device_down
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Junjie Cao <[email protected]>
When a device goes down, nr_rt_device_down() clears the routes that use this device. However, it fails to drop the per-route reference to the neighbour (nr_neigh): neither nr_neigh->count nor its refcount is decremented when the route is removed.
Mirror the behaviour of nr_dec_obs() / nr_del_node() by decrementing nr_neigh->count and calling nr_neigh_put(), so that the neighbour reference is properly released when a device goes down.
[F6BVP: rebased on the single nr_route_lock; the list reference is still dropped last by nr_remove_neigh_locked(), so the neighbour stays valid while its routes are removed.]
--- net/netrom/nr_route.c | 3 +++ 1 file changed, 3 insertions(+)
net/netrom/nr_route.c +3 -0
@@ -526,6 +526,9 @@ void nr_rt_device_down(struct net_device *dev)nr_node_for_each_safe (t, node2t, &nr_node_list) {for (i =0 ; i < t->count; i++) {if (t->routes[i].neighbour == s) { + s->count--; +nr_neigh_put (s); + t->count--;switch (i) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 167/247 netrom: clear nr_neigh->ax25 under the routing lock in nr_link_failed()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
nr_route_frame() swaps nr_neigh->ax25 for the ax25_cb returned by ax25_send_frame() and puts the old one while holding nr_route_lock. nr_link_failed(), called by AX.25 when that link fails, looks the neighbour up under the lock but then clears nr_neigh->ax25, puts the ax25_cb and bumps nr_neigh->failed after dropping it. If a frame is routed to the same neighbour at that moment, both paths can see the same ax25_cb and put it twice.
Do the whole of nr_link_failed() in one critical section. The neighbour no longer needs a temporary reference, since it cannot be unlinked while the lock is held.
This depends on "netrom: use a single lock for the node and neighbour lists".
--- net/netrom/nr_route.c | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-)
net/netrom/nr_route.c +10 -9
@@ -715,34 +715,35 @@ void nr_link_failed(ax25_cb *ax25, int reason)struct nr_neigh *s, *nr_neigh =NULL ;struct nr_node *nr_node =NULL ; +/* +* nr_route_frame() replaces nr_neigh->ax25 under nr_route_lock; +* clear it and drop its reference under the same lock, so that the +* two paths cannot both put the same ax25_cb. +*/ spin_lock_bh (&nr_route_lock);nr_neigh_for_each (s, &nr_neigh_list) {if (s->ax25 == ax25) { -nr_neigh_hold (s); nr_neigh = s;break ; } } -spin_unlock_bh (&nr_route_lock);if (nr_neigh ==NULL ) -return ; + goto out; nr_neigh->ax25 =NULL ;ax25_cb_put (ax25); -if (++nr_neigh->failed <READ_ONCE (sysctl_netrom_link_fails_count)) { -nr_neigh_put (nr_neigh); -return ; - } -spin_lock_bh (&nr_route_lock); +if (++nr_neigh->failed <READ_ONCE (sysctl_netrom_link_fails_count)) + goto out; +nr_node_for_each (nr_node, &nr_node_list) {if (nr_node->which < nr_node->count && nr_node->routes[nr_node->which].neighbour == nr_neigh) nr_node->which++; } +out:spin_unlock_bh (&nr_route_lock); -nr_neigh_put (nr_neigh); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 168/247 netrom: fix nr_node leak when nr_del_node() removes the last route
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
nr_del_node() takes a reference on the node with its lookup. When the route it deletes is not the last one, it drops that reference before returning. When it is the last one, it only unlinks the node with nr_remove_node_locked(), which drops the list's reference, and returns still holding its own: the unlinked node is never freed.
Seen with kmemleak on a live node after adding and then deleting a route to a dummy node with nrparms (SIOCADDRT then SIOCDELRT): the 96-byte nr_node allocated by nr_add_node(), callsign and mnemonic of the dummy node in its hex dump, is reported as unreferenced.
Drop the lookup reference in both cases.
--- net/netrom/nr_route.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/netrom/nr_route.c +2 -1
@@ -388,8 +388,9 @@ static int nr_del_node(ax25_address *callsign, ax25_address *neighbour, struct ncase 2 :break ; } -nr_node_put (nr_node); } +/* Drop the reference taken by __nr_node_get() */ +nr_node_put (nr_node); ret =0 ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 169/247 rose: clear through routes when a neighbour is removed from the tables
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
When the last route using a neighbour is deleted (SIOCDELRT) or all routes are cleared (SIOCRSCLRRT), rose_del_node() and rose_clear_routes() take the neighbour out of rose_neigh_list, but the through routes in rose_route_list that still use it are left alone. No frame can reach them any more, so they stay in the table for ever, holding their neighbour references, and neither end of the relayed connection is told: the caller and the called station keep a circuit that goes nowhere. rose_clear_routes() even says it keeps neighbours with active connections, which it does not.
This shows up on every node that relays traffic when its routing daemon restarts: FPAC clears and reloads the routes, the neighbours are recreated under new numbers, and the old through routes remain listed with neighbours that no longer exist.
Clear them when the neighbour is removed, as rose_link_failed() does when a link fails, but send the CLEAR to both halves since the removed neighbour's link may still be up, and cut the local connections using it. rose_route_list_lock is taken under rose_node_list_lock and rose_neigh_list_lock, the order rose_route_frame() and rose_link_failed() already use.
Tested in QEMU with a lockdep and KASAN kernel, three nodes A - B - C with A calling C through B: before, the through route stays on B after SIOCDELRT or SIOCRSCLRRT and A is never told; after, the entry is gone and both A and C get a CLEAR (cause 0x09) within a second. No lockdep, KASAN or refcount report.
--- net/rose/rose_route.c | 49 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-)
net/rose/rose_route.c +47 -2
@@ -285,6 +285,49 @@ static void rose_remove_route(struct rose_route *rose_route) } } +/* +* A neighbour is being removed from the tables while its link may still +* be up (route deleted or routes cleared by the configuration). Clear the +* through routes using it, on both sides since both can still be reached, +* instead of leaving them in rose_route_list for ever: no frame can reach +* them once the neighbour is gone. Local connections using it are cut too, +* as rose_link_failed() does. +* +* Caller is holding rose_node_list_lock and rose_neigh_list_lock, taken +* before rose_route_list_lock as in rose_route_frame() and +* rose_link_failed(). +*/ +static void rose_neigh_clear_routes (struct rose_neigh *rose_neigh) +{ +struct rose_route *rose_route, *s; + +spin_lock_bh (&rose_route_list_lock); + + rose_route = rose_route_list; +while (rose_route !=NULL ) { + s = rose_route->next; + +if (rose_route->neigh1 == rose_neigh || + rose_route->neigh2 == rose_neigh) { +if (rose_route->neigh1 !=NULL ) +rose_transmit_clear_request (rose_route->neigh1, + rose_route->lci1, +ROSE_OUT_OF_ORDER ,0 ); +if (rose_route->neigh2 !=NULL ) +rose_transmit_clear_request (rose_route->neigh2, + rose_route->lci2, +ROSE_OUT_OF_ORDER ,0 ); +rose_remove_route (rose_route); + } + + rose_route = s; + } + +spin_unlock_bh (&rose_route_list_lock); + +rose_kill_by_neigh (rose_neigh); +} +/* * "Delete" a node. Strictly speaking remove a route to a node. The node * is only deleted if no routes are left to it.
@@ -333,6 +376,7 @@ static int rose_del_node(struct rose_route_struct *rose_route,rose_neigh_put (rose_neigh);if (rose_neigh->count ==0 ) { +rose_neigh_clear_routes (rose_neigh);rose_remove_neigh (rose_neigh);rose_neigh_put (rose_neigh); }
@@ -547,8 +591,8 @@ void rose_route_device_down(struct net_device *dev)#endif /* -* Clear all nodes and neighbours out, except for neighbours with -* active connections going through them. +* Clear all nodes and neighbours out, with the through routes and +* connections using those neighbours. * Do not clear loopback neighbour and nodes. */ static int rose_clear_routes (void )
@@ -579,6 +623,7 @@ static int rose_clear_routes(void) rose_neigh = rose_neigh->next;if (!s->loopback) { +rose_neigh_clear_routes (s);rose_remove_neigh (s);rose_neigh_put (s); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 170/247 rose: restart the link of a neighbour created over a live AX.25 connection
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
A new neighbour starts with restarted == 0 and waits for the first frame sent to it to start the restart procedure. But when a neighbour is removed from the routing tables and added back (SIOCDELRT then SIOCADDRT, or SIOCRSCLRRT followed by a reload of the routes), the AX.25 connection to it outlives the old entry. The other end has seen nothing:
it still regards the link as restarted and will not restart it. On this end rose_get_neigh() only hands out restarted neighbours to through calls, so no frame is ever sent to the new neighbour and nothing starts the restart either. Every call relayed through that neighbour is then refused until one of the two ends happens to originate a call of its own over the link, or the AX.25 connection drops.
This happens on a relay node each time its routing daemon restarts: FPAC clears and reloads the routes, the neighbours come back as "restart no" while /proc/net/ax25 still shows their connections established.
When rose_add_node() creates a neighbour and an AX.25 connection to it already exists, send the RESTART REQUEST right away and start T0, as rose_transmit_link() does for the first frame. Nothing changes when there is no connection yet: the link is still brought up on demand.
Tested in QEMU with a lockdep and KASAN kernel, three nodes A - B - C with A calling C through B, then B removing and re-adding its route to C (or clearing and reloading all its routes): before, the neighbour stays "restart no" on B and A's calls to C are refused for as long as the test runs; after, the neighbour is restarted within three seconds and the first call goes through. No lockdep, KASAN or refcount report.
--- include/net/rose.h | 1 + net/rose/rose_link.c | 20 ++++++++++++++++++++ net/rose/rose_route.c | 10 ++++++++++ 3 files changed, 31 insertions(+)
include/net/rose.h +1 -0
@@ -237,6 +237,7 @@ void rose_link_rx_restart(struct sk_buff *, struct rose_neigh *, unsigned short);void rose_transmit_clear_request (struct rose_neigh *,unsigned int ,unsigned char ,unsigned char ); +void rose_link_restart (struct rose_neigh *neigh);void rose_transmit_link (struct sk_buff *,struct rose_neigh *);/* rose_loopback.c */
net/rose/rose_link.c +20 -0
@@ -259,6 +259,26 @@ void rose_transmit_clear_request(struct rose_neigh *neigh, unsigned int lci, unskfree_skb (skb); } +/* +* A neighbour has just been created while an AX.25 connection to it is +* already up, e.g. it was removed from the routing tables and added back. +* The other end still regards the link as restarted and will not restart it, +* and through calls only use restarted neighbours, so nothing would ever +* restart it from this end either: do it now. +*/ +void rose_link_restart (struct rose_neigh *neigh) +{ +if (neigh->loopback || neigh->restarted ||rose_t0timer_running (neigh)) +return ; + +if (!rose_link_up (neigh)) +return ; + +rose_transmit_restart_request (neigh); + neigh->dce_mode =0 ; +rose_start_t0timer (neigh); +} +void rose_transmit_link (struct sk_buff *skb,struct rose_neigh *neigh) {unsigned char *dptr;
net/rose/rose_route.c +10 -0
@@ -53,6 +53,7 @@ static int __must_check rose_add_node(struct rose_route_struct *rose_route, {struct rose_node *rose_node, *rose_tmpn, *rose_tmpp;struct rose_neigh *rose_neigh; +bool new_neigh = false;int i, res =0 ;spin_lock_bh (&rose_node_list_lock);
@@ -125,6 +126,7 @@ static int __must_check rose_add_node(struct rose_route_struct *rose_route, rose_neigh->next = rose_neigh_list; rose_neigh_list = rose_neigh; + new_neigh = true; }/*
@@ -192,6 +194,14 @@ static int __must_check rose_add_node(struct rose_route_struct *rose_route, } out: +/* +* The AX.25 connection of a neighbour that was removed from the tables +* outlives it. If it is still there, the other end will not restart +* the link: do it from here. +*/ +if (new_neigh && res ==0 ) +rose_link_restart (rose_neigh); +spin_unlock_bh (&rose_neigh_list_lock);spin_unlock_bh (&rose_node_list_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 171/247 ax25: serialise the transmission of I frames on a connection
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
ax25_kick() takes frames off the write queue, numbers them from V(S) and moves them to the ack queue, with no lock. It is called from process context by the senders (ax25_output()) and from softirq context by the receive path and the timers. A connection used by ROSE or NET/ROM carries several circuits, so ax25_output() can run for the same connection on two CPUs at once, and against the receive path. Both then read the same V(S) and two different I frames are sent under the same N(S). The peer keeps the first and rejects the second; the go-back-N that follows resends whatever the ack queue holds for that number, and one of the two frames is never sent again while the AX.25 counters look consistent on both sides. The layer above sees a hole: a ROSE circuit receives its frames out of sequence, ignores them, and stays frozen with its window full.
Seen on a live ROSE node relaying several circuits over one AX.25 link:
fm F6BVP-9 to F6BVP-13 ctl I55^ pid=1(X.25) len 254 LCI 030 DATA S2
fm F6BVP-9 to F6BVP-13 ctl I55^ pid=1(X.25) len 254 LCI 02E DATA S2
fm F6BVP-13 to F6BVP-9 ctl REJ6v
Add a lock to the ax25_cb covering V(S), V(A) and the write and ack queues, taken in ax25_kick(), ax25_frames_acked() and ax25_requeue_frames(). The frames are not sent with the lock held, since ax25_transmit_buffer() may end up in ax25_disconnect(): ax25_kick() puts the numbered frames on a transmit queue which is emptied, in order, by one context at a time once the lock is dropped.
Tested in QEMU, two 4-CPU nodes with lockdep and KASAN over a KISS serial link, four ROSE circuits each sending 400 numbered messages at the same time: before, every circuit freezes and 300 to 600 of the 1600 messages get through; after, no sender is blocked and more than 1500 get through (the ROSE side needs "rose: process received frames and send with the socket locked" for the rest: 1600/1600 in order on six runs out of six with both). No lockdep, KASAN or refcount report.
[F6BVP: v2: in ax25_frames_acked(), loop on what skb_dequeue() returns
instead of on skb_peek(): ax25_clear_queues() purges the ack queue without ax25->lock, so skb_dequeue() could return NULL and __skb_queue_tail() dereference it in softirq context (reported by Sasha Levin). Same fix submitted to mod-orphan.]
--- include/net/ax25.h | 5 ++++ net/ax25/af_ax25.c | 2 ++ net/ax25/ax25_out.c | 56 ++++++++++++++++++++++++++++++++++++++++---- net/ax25/ax25_subr.c | 37 ++++++++++++++++++++++------- 4 files changed, 88 insertions(+), 12 deletions(-)
include/net/ax25.h +5 -0
@@ -252,6 +252,11 @@ typedef struct ax25_cb {struct sk_buff_head reseq_queue;struct sk_buff_head ack_queue;struct sk_buff_head frag_queue; +/* I frames numbered by ax25_kick(), waiting to go to the device */ +struct sk_buff_head xmit_queue; +/* serialises V(S)/V(A) and the write, ack and xmit queues */ +spinlock_t lock; +unsigned char xmit_running;unsigned char window;struct timer_list timer, dtimer;struct sock *sk;/* Backlink to socket */
net/ax25/af_ax25.c +2 -0
@@ -537,6 +537,8 @@ ax25_cb *ax25_create_cb(void)skb_queue_head_init (&ax25->frag_queue);skb_queue_head_init (&ax25->ack_queue);skb_queue_head_init (&ax25->reseq_queue); +skb_queue_head_init (&ax25->xmit_queue); +spin_lock_init (&ax25->lock);ax25_setup_timers (ax25);
net/ax25/ax25_out.c +52 -4
92 lines not on this page · raw message
net/ax25/ax25_subr.c +29 -8
@@ -34,6 +34,7 @@ void ax25_clear_queues(ax25_cb *ax25) {skb_queue_purge (&ax25->write_queue);skb_queue_purge (&ax25->ack_queue); +skb_queue_purge (&ax25->xmit_queue);skb_queue_purge (&ax25->reseq_queue);skb_queue_purge (&ax25->frag_queue); }
@@ -45,31 +46,51 @@ void ax25_clear_queues(ax25_cb *ax25)*/ void ax25_frames_acked (ax25_cb *ax25,unsigned short nr) { +struct sk_buff_head acked;struct sk_buff *skb; +__skb_queue_head_init (&acked); +/* -* Remove all the ack-ed frames from the ack queue. +* Remove all the ack-ed frames from the ack queue. ax25_kick() may be +* filling it from another CPU: move V(A) and the queue together, and +* free the frames once the lock is dropped. */ -if (ax25->va != nr) { -while (skb_peek (&ax25->ack_queue) !=NULL && ax25->va != nr) { - skb =skb_dequeue (&ax25->ack_queue); -kfree_skb (skb); - ax25->va = (ax25->va +1 ) % ax25->modulus; - } +spin_lock_bh (&ax25->lock); +/* +* ax25_clear_queues() purges the ack queue without ax25->lock: test +* what skb_dequeue() returns, not what skb_peek() saw before it. +*/ +while (ax25->va != nr && (skb =skb_dequeue (&ax25->ack_queue)) !=NULL ) { +__skb_queue_tail (&acked, skb); + ax25->va = (ax25->va +1 ) % ax25->modulus; } +spin_unlock_bh (&ax25->lock); + +__skb_queue_purge (&acked); }void ax25_requeue_frames (ax25_cb *ax25) { +struct sk_buff_head stale;struct sk_buff *skb; +__skb_queue_head_init (&stale); +/* * Requeue all the un-ack-ed frames on the output queue to be picked * up by ax25_kick called from the timer. This arrangement handles the -* possibility of an empty output queue. +* possibility of an empty output queue. Copies that ax25_kick() has +* numbered but not sent yet are stale: they will be sent again. */ +spin_lock_bh (&ax25->lock); +while ((skb =skb_dequeue (&ax25->xmit_queue)) !=NULL ) +__skb_queue_tail (&stale, skb);while ((skb =skb_dequeue_tail (&ax25->ack_queue)) !=NULL )skb_queue_head (&ax25->write_queue, skb); +spin_unlock_bh (&ax25->lock); + +__skb_queue_purge (&stale); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 172/247 rose: process received frames and send with the socket locked
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_kick() takes frames off the write queue, numbers them from V(S) and moves them to the ack queue. It runs from rose_sendmsg() in process context and from rose_process_rx_frame() in softirq context, and neither holds the socket lock. When a frame for the socket is received on one CPU while a process is sending on another, both read the same V(S) and two different frames go out under the same N(S), or the queues and V(S)/V(A) are updated by one while the other walks them. The peer drops the frames it sees as out of sequence, and since ROSE has no REJ and no retransmission in state 3 the data is lost for good: messages go missing from the stream, or the window fills and the circuit freezes.
The timers already take the socket lock and retry when a process owns it. Do the same for the two remaining paths: rose_sendmsg() calls rose_kick() under lock_sock(), and received frames go through rose_rcv_frame(), which takes bh_lock_sock() and queues the frame on the socket backlog when a process owns the socket, as NET/ROM and X.25 do.
Tested in QEMU, two 4-CPU nodes with lockdep and KASAN over a KISS serial link, four ROSE circuits each sending 400 numbered messages at the same time (together with the AX.25 fix "ax25: serialise the transmission of I frames on a connection", without which the same happens one layer down): before, 60 to 90 of the 1600 messages are missing from the streams; after, 1600/1600 delivered in order on six runs out of six. No lockdep, KASAN or refcount report.
--- include/net/rose.h | 2 ++ net/rose/af_rose.c | 5 +++++ net/rose/rose_in.c | 31 +++++++++++++++++++++++++++++++ net/rose/rose_loopback.c | 2 +- net/rose/rose_route.c | 2 +- 5 files changed, 40 insertions(+), 2 deletions(-)
include/net/rose.h +2 -0
@@ -227,6 +227,8 @@ void rose_setup(struct net_device *);/* rose_in.c */ int rose_process_rx_frame (struct sock *,struct sk_buff *); +int rose_rcv_frame (struct sock *sk,struct sk_buff *skb); +int rose_backlog_rcv (struct sock *sk,struct sk_buff *skb);/* rose_link.c */ void rose_start_ftimer (struct rose_neigh *);
net/rose/af_rose.c +5 -0
@@ -598,6 +598,7 @@ static int rose_create(struct net *net, struct socket *sock, int protocol, rose =rose_sk (sk);sock_init_data (sock, sk); + sk->sk_backlog_rcv = rose_backlog_rcv;skb_queue_head_init (&rose->ack_queue);#ifdef M_BIT
@@ -637,6 +638,7 @@ static struct sock *rose_make_new(struct sock *osk) rose =rose_sk (sk);sock_init_data (NULL , sk); + sk->sk_backlog_rcv = rose_backlog_rcv;skb_queue_head_init (&rose->ack_queue);#ifdef M_BIT
@@ -1326,7 +1328,10 @@ static int rose_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)skb_queue_tail (&sk->sk_write_queue, skb);/* Shove it onto the queue */ #endif +/* The receive path and the timers run rose_kick() too */ +lock_sock (sk);rose_kick (sk); +release_sock (sk);return len; }
net/rose/rose_in.c +31 -0
@@ -309,3 +309,34 @@ int rose_process_rx_frame(struct sock *sk, struct sk_buff *skb)return queued; } + +/* +* Frames for a socket are processed with the socket locked, as the timers +* already do: rose_kick() may be running in rose_sendmsg() on another CPU, +* and two of them reading the same V(S) send two different frames under the +* same N(S). If a process owns the socket the frame goes to its backlog and +* is processed when the socket is released. Returns non-zero if the skb has +* been consumed. +*/ +int rose_rcv_frame (struct sock *sk,struct sk_buff *skb) +{ +int queued; + +bh_lock_sock (sk); +if (!sock_owned_by_user (sk)) + queued =rose_process_rx_frame (sk, skb); +else + queued = !sk_add_backlog (sk, skb,READ_ONCE (sk->sk_rcvbuf) + +READ_ONCE (sk->sk_sndbuf)); +bh_unlock_sock (sk); + +return queued; +} + +int rose_backlog_rcv (struct sock *sk,struct sk_buff *skb) +{ +if (!rose_process_rx_frame (sk, skb)) +kfree_skb (skb); + +return 0 ; +}
net/rose/rose_loopback.c +1 -1
@@ -107,7 +107,7 @@ static void rose_loopback_timer(struct timer_list *unused) sk =rose_find_socket (lci_o, rose_loopback_neigh);if (sk) { -if (rose_process_rx_frame (sk, skb) ==0 ) +if (rose_rcv_frame (sk, skb) ==0 )kfree_skb (skb);continue ; }
net/rose/rose_route.c +1 -1
@@ -1017,7 +1017,7 @@ int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25) }else {skb_reset_transport_header (skb); - res =rose_process_rx_frame (sk, skb); + res =rose_rcv_frame (sk, skb); goto out; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 173/247 ax25: dont create two connections for the same link in ax25_send_frame()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
ax25_send_frame() looks for an existing connection with ax25_find_cb() and, when there is none, creates one and adds it to the list. The lookup and the insertion are not done under the same lock, so two callers sending to a neighbour at the same time both find nothing and both create a control block: the same link ends up with several connections, each sending its own SABM, and the frames queued on the ones that lose are never delivered.
ROSE and NET/ROM call ax25_send_frame() for every frame they send to a neighbour, from process context and from softirq context, so this happens as soon as several circuits start together on a link that is not established yet.
Add ax25_cb_add_unique(), which searches the list and inserts the new control block under ax25_list_lock, and returns the existing connection when another sender got there first; ax25_send_frame() then drops its own control block and queues the frame on that connection. The SABM is only sent once the control block is known to be the one in the list.
Tested in QEMU, two 4-CPU nodes with lockdep and KASAN over a KISS serial link, eight ROSE calls started at the same instant with no AX.25 connection up: before, /proc/net/ax25 shows four connections for the same pair of callsigns on three runs out of three; after, one. No lockdep, KASAN or refcount report.
--- include/net/ax25.h | 1 + net/ax25/af_ax25.c | 49 ++++++++++++++++++++++++++++++++++++++------- net/ax25/ax25_out.c | 16 ++++++++++++--- 3 files changed, 56 insertions(+), 10 deletions(-)
include/net/ax25.h +1 -0
@@ -311,6 +311,7 @@ static inline __be16 ax25_type_trans(struct sk_buff *skb, struct net_device *devextern struct hlist_head ax25_list;extern spinlock_t ax25_list_lock;void ax25_cb_add (ax25_cb *); +ax25_cb *ax25_cb_add_unique (ax25_cb *ax25);struct sock *ax25_find_listener (ax25_address *,int ,struct net_device *,int );struct sock *ax25_get_socket (ax25_address *,ax25_address *,int ); ax25_cb *ax25_find_cb(const ax25_address *, ax25_address *, ax25_digi *,
net/ax25/af_ax25.c +42 -7
73 lines not on this page · raw message
net/ax25/ax25_out.c +13 -3
@@ -32,7 +32,7 @@ static DEFINE_SPINLOCK(ax25_frag_lock);ax25_cb *ax25_send_frame (struct sk_buff *skb,int paclen,const ax25_address *src,ax25_address *dest,ax25_digi *digi,struct net_device *dev) {ax25_dev *ax25_dev; -ax25_cb *ax25; +ax25_cb *ax25, *existing;/* * Take the default packet length for the device if zero is
@@ -82,6 +82,18 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *sr } } +/* +* Another sender may have created the connection since the lookup +* above: the list is searched again and the new control block added +* under one lock. If we lost, use the other one. +*/ + existing =ax25_cb_add_unique (ax25); +if (existing) { +ax25_cb_put (ax25); +ax25_output (existing, paclen, skb); +return existing; + } +switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL ]) {case AX25_PROTO_STD_SIMPLEX :case AX25_PROTO_STD_DUPLEX :
@@ -104,8 +116,6 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *sr*/ ax25_cb_hold (ax25); -ax25_cb_add (ax25); - ax25->state =AX25_STATE_1 ;ax25_start_heartbeat (ax25);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 174/247 ax25: read the connections ax25_dev only once when walking ax25_list
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
ax25_kill_by_device() detaches a connection from a device that goes down by setting s->ax25_dev to NULL. It does so after it has dropped ax25_list_lock, while the connection is still on ax25_list.
__ax25_find_cb() and ax25_find_listener() walk that list and test s->ax25_dev against NULL before they dereference it, but they load the pointer a second time for the dereference. ax25_send_to_raw() dereferences it without any test. If ax25_kill_by_device() clears the pointer in between, the walker dereferences NULL:
Oops: general protection fault, probably for non-canonical address KASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017] RIP: 0010:ax25_find_cb+0x121/0x330 [ax25] ax25_send_frame+0xdc/0x980 [ax25] rose_send_frame+0xce/0x270 [rose] rose_transmit_restart_request+0x1b3/0x260 [rose] rose_transmit_link+0x31d/0x560 [rose] rose_write_internal+0x3ab/0x15b0 [rose] rose_release+0x2b2/0x4b0 [rose]
Load the pointer once in the three walkers and use that value, and add the missing NULL test to ax25_send_to_raw(). The ax25_dev itself cannot go away under the walker: ax25_kill_by_device() has to take ax25_list_lock again, in ax25_cb_del(), before the device teardown gets as far as freeing it.
The oops above was obtained on 6.12.94 with KASAN, after 382 seconds of the syzbot C reproducer of the ax25_find_cb() use-after-free report, with the interface brought up again in a loop, while testing an earlier version of the next patch. With this series the same test runs for 600 seconds without an oops.
--- net/ax25/af_ax25.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
net/ax25/af_ax25.c +12 -6
@@ -91,7 +91,7 @@ static void ax25_kill_by_device(struct net_device *dev)if (!sk) {spin_unlock_bh (&ax25_list_lock);ax25_disconnect (s,ENETUNREACH ); - s->ax25_dev =NULL ; +WRITE_ONCE (s->ax25_dev,NULL );ax25_cb_del (s);spin_lock_bh (&ax25_list_lock); goto again;
@@ -100,7 +100,7 @@ static void ax25_kill_by_device(struct net_device *dev)spin_unlock_bh (&ax25_list_lock);lock_sock (sk);ax25_disconnect (s,ENETUNREACH ); - s->ax25_dev =NULL ; +WRITE_ONCE (s->ax25_dev,NULL );if (sk->sk_socket) {netdev_put (ax25_dev->dev, &s->dev_tracker);
@@ -172,6 +172,7 @@ void ax25_cb_add(ax25_cb *ax25)struct sock *ax25_find_listener (ax25_address *addr,int digi,struct net_device *dev,int type) { +ax25_dev *ax25_dev;ax25_cb *s;spin_lock (&ax25_list_lock);
@@ -181,7 +182,8 @@ struct sock *ax25_find_listener(ax25_address *addr, int digi,if (s->sk && !ax25cmp (&s->source_addr, addr) && s->sk->sk_type == type && s->sk->sk_state ==TCP_LISTEN ) {/* If device is null we match any device */ -if (s->ax25_dev ==NULL || s->ax25_dev->dev == dev) { + ax25_dev =READ_ONCE (s->ax25_dev); +if (ax25_dev ==NULL || ax25_dev->dev == dev) {sock_hold (s->sk);spin_unlock (&ax25_list_lock);return s->sk;
@@ -226,14 +228,16 @@ static ax25_cb *__ax25_find_cb(const ax25_address *src_addr, ax25_address *dest_addr, ax25_digi *digi, struct net_device *dev) { +ax25_dev *ax25_dev;ax25_cb *s;ax25_for_each (s, &ax25_list) {if (s->sk && s->sk->sk_type !=SOCK_SEQPACKET )continue ; -if (s->ax25_dev ==NULL ) + ax25_dev =READ_ONCE (s->ax25_dev); +if (ax25_dev ==NULL )continue ; -if (ax25cmp (&s->source_addr, src_addr) ==0 &&ax25cmp (&s->dest_addr, dest_addr) ==0 && s->ax25_dev->dev == dev) { +if (ax25cmp (&s->source_addr, src_addr) ==0 &&ax25cmp (&s->dest_addr, dest_addr) ==0 && ax25_dev->dev == dev) {if (digi !=NULL && digi->ndigi !=0 ) {if (s->digipeat ==NULL )continue ;
@@ -293,15 +297,17 @@ ax25_cb *ax25_cb_add_unique(ax25_cb *ax25)void ax25_send_to_raw (ax25_address *addr,struct sk_buff *skb,int proto) { +ax25_dev *ax25_dev;ax25_cb *s;struct sk_buff *copy;spin_lock (&ax25_list_lock);ax25_for_each (s, &ax25_list) { + ax25_dev =READ_ONCE (s->ax25_dev);if (s->sk !=NULL &&ax25cmp (&s->source_addr, addr) ==0 && s->sk->sk_type ==SOCK_RAW && s->sk->sk_protocol == proto && - s->ax25_dev->dev == skb->dev && + ax25_dev && ax25_dev->dev == skb->dev &&atomic_read (&s->sk->sk_rmem_alloc) <= s->sk->sk_rcvbuf) {if ((copy =skb_clone (skb,GFP_ATOMIC )) ==NULL )continue ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 175/247 ax25: wait for ax25_send_frame() before detaching the connections of a device
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
A connection created by ax25_send_frame(), for ROSE, NET/ROM or IP over AX.25, points to the ax25_dev of its device without holding a reference on it. It relies on ax25_kill_by_device() to detach it when the device goes down, before ax25_dev_device_down() frees the ax25_dev.
On NETDEV_DOWN the two run one after the other. In between, the ax25_dev is still on ax25_dev_list, so ax25_send_frame() still finds it, creates a connection and adds it to ax25_list after ax25_kill_by_device() has finished walking that list. The connection is left with a pointer to an ax25_dev that is freed a moment later, which ax25_find_cb() and the AX.25 timers then dereference:
BUG: KASAN: slab-use-after-free in ax25_find_cb+0x2ed/0x330 [ax25] Read of size 8 at addr ffff8880031e8c10 by task repro/3287 ax25_find_cb+0x2ed/0x330 [ax25] rose_transmit_link+0xea/0x560 [rose] rose_write_internal+0x3ab/0x15b0 [rose] rose_release+0x2b2/0x4b0 [rose] Allocated by: ax25_dev_device_up, ax25_device_event Freed by: kfree_rcu_monitor, queued from ax25_device_event The buggy address is located 16 bytes inside of freed 256-byte region, cache kmalloc-256
This is the trace of the syzbot report below. An earlier commit, "rose:
use timer_shutdown_sync() for t0timer teardown", attributed that report to the ROSE t0 timer; the freed object in the report is the ax25_dev, as it is here.
A connection that is on the list in time is not safe either while it is still being set up: ax25_kill_by_device() can detach it, clearing its ax25_dev pointer, between the moment ax25_send_frame() adds it and the moment it starts the link and queues the frame, which then dereference NULL.
Make the two exclude each other with RCU. ax25_send_frame() now runs entirely under rcu_read_lock() and gives up when the device is no longer marked up. ax25_kill_by_device() clears device_up and calls synchronize_rcu() before it walks the list: once that returns, every connection ax25_send_frame() was working on is complete and on the list, and no new one can appear behind the walk. This adds one RCU grace period to taking an AX.25 interface down.
Tested on 6.12.94 with KASAN and lockdep, with the modules of this tree and the rest of this series:
- with a 100 ms delay inserted between ax25_kill_by_device() and ax25_dev_device_down(), a single "ifconfig bpq0 down" during eight ROSE call requests left connections on the list and ended in a use-after-free in ax25_heartbeat_expiry(); with the series the list is empty after the down and there is no report;
- the syzbot C reproducer, with the interface brought up again in a loop, caused 217 KASAN reports and a panic after 41 seconds; with the series it ran for 600 seconds without any report;
- 60 plain "ifconfig bpq0 down" / "up" under 20 ROSE call requests per second, and a ROSE call through a three node chain over mkiss, behave as before;
- eight ROSE calls started at the same instant still end up on a single AX.25 connection.
--- net/ax25/af_ax25.c | 12 +++++++++++- net/ax25/ax25_out.c | 38 ++++++++++++++++++++------------------ 2 files changed, 31 insertions(+), 19 deletions(-)
net/ax25/af_ax25.c +11 -1
@@ -81,7 +81,17 @@ static void ax25_kill_by_device(struct net_device *dev)if ((ax25_dev =ax25_dev_ax25dev (dev)) ==NULL )return ; - ax25_dev->device_up = false; +WRITE_ONCE (ax25_dev->device_up, false); + +/* +* ax25_send_frame() creates connections that hold no reference on +* the ax25_dev: they rely on the walk below to detach them before the +* ax25_dev is freed. It runs under rcu_read_lock() and gives up when +* device_up is clear, so once this returns every connection it was +* setting up is complete and on the list, and no new one can appear +* behind the walk. +*/ +synchronize_rcu ();spin_lock_bh (&ax25_list_lock); again:
net/ax25/ax25_out.c +20 -18
@@ -34,34 +34,34 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *srax25_dev *ax25_dev;ax25_cb *ax25, *existing; +/* +* The connection made or used here holds no reference on the +* ax25_dev. ax25_kill_by_device() clears device_up, waits for the RCU +* readers and only then detaches the connections of the device: stay +* under the RCU read lock until the frame is queued, and do not start +* anything on a device that is going down. +*/ +rcu_read_lock (); + ax25_dev =ax25_dev_ax25dev (dev); +if (!ax25_dev || !READ_ONCE (ax25_dev->device_up)) { +rcu_read_unlock (); +return NULL ; + } +/* * Take the default packet length for the device if zero is * specified. */ -if (paclen ==0 ) { -rcu_read_lock (); - ax25_dev =ax25_dev_ax25dev (dev); -if (!ax25_dev) { -rcu_read_unlock (); -return NULL ; - } +if (paclen ==0 ) paclen = ax25_dev->values[AX25_VALUES_PACLEN ]; -rcu_read_unlock (); - }/* * Look for an existing connection. */ if ((ax25 =ax25_find_cb (src, dest, digi, dev)) !=NULL ) {ax25_output (ax25, paclen, skb); -return ax25;/* It already existed */ - } - -rcu_read_lock (); - ax25_dev =ax25_dev_ax25dev (dev); -if (!ax25_dev) {rcu_read_unlock (); -return NULL ; +return ax25;/* It already existed */ }if ((ax25 =ax25_create_cb ()) ==NULL ) {
@@ -69,7 +69,6 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *srreturn NULL ; }ax25_fillin_cb (ax25, ax25_dev); -rcu_read_unlock (); ax25->source_addr = *src; ax25->dest_addr = *dest;
@@ -78,6 +77,7 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *sr ax25->digipeat =kmemdup (digi,sizeof (*digi),GFP_ATOMIC );if (ax25->digipeat ==NULL ) {ax25_cb_put (ax25); +rcu_read_unlock ();return NULL ; } }
@@ -91,10 +91,11 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *srif (existing) {ax25_cb_put (ax25);ax25_output (existing, paclen, skb); +rcu_read_unlock ();return existing; } -switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL ]) { +switch (ax25_dev->values[AX25_VALUES_PROTOCOL ]) {case AX25_PROTO_STD_SIMPLEX :case AX25_PROTO_STD_DUPLEX :ax25_std_establish_data_link (ax25);
@@ -121,6 +122,7 @@ ax25_cb *ax25_send_frame(struct sk_buff *skb, int paclen, const ax25_address *srax25_start_heartbeat (ax25);ax25_output (ax25, paclen, skb); +rcu_read_unlock ();return ax25;/* We had to create it */ }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 176/247 ax25: dont accept frames on a device that is going down
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
ax25_rcv() creates a connection on an incoming SABM, for a listening socket or for a callsign registered by ROSE or NET/ROM. Like the ones made by ax25_send_frame(), it holds no reference on the ax25_dev and relies on ax25_kill_by_device() to detach it before the ax25_dev is freed. If it is added to ax25_list after ax25_kill_by_device() has walked the list, it is left pointing to a freed ax25_dev.
ax25_rcv() is called from the packet type handler, under rcu_read_lock(), and ax25_kill_by_device() now clears device_up and waits for the RCU readers before its walk. Drop the frame when device_up is clear: a frame that gets past the test is fully processed before the walk starts, and none is processed behind it.
The window is much smaller than for ax25_send_frame(): the core already drops what is received on a device that is no longer running, so only a frame that was queued before the device was stopped and is processed late can hit it. I could not exercise it. The change was checked for regressions only: incoming connections still work in the ROSE tests of the previous patch, where every AX.25 link is opened by an incoming SABM on one side.
--- net/ax25/af_ax25.c | 12 ++++++------ net/ax25/ax25_in.c | 9 +++++++++ 2 files changed, 15 insertions(+), 6 deletions(-)
net/ax25/af_ax25.c +6 -6
@@ -84,12 +84,12 @@ static void ax25_kill_by_device(struct net_device *dev)WRITE_ONCE (ax25_dev->device_up, false);/* -* ax25_send_frame() creates connections that hold no reference on -* the ax25_dev: they rely on the walk below to detach them before the -* ax25_dev is freed. It runs under rcu_read_lock() and gives up when -* device_up is clear, so once this returns every connection it was -* setting up is complete and on the list, and no new one can appear -* behind the walk. +* ax25_send_frame() and ax25_rcv() create connections that hold no +* reference on the ax25_dev: they rely on the walk below to detach +* them before the ax25_dev is freed. Both run under rcu_read_lock() +* and give up when device_up is clear, so once this returns every +* connection they were setting up is complete and on the list, and +* no new one can appear behind the walk. */ synchronize_rcu ();
net/ax25/ax25_in.c +9 -0
@@ -216,6 +216,15 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev,if (skb_linearize (skb)) goto free; +/* +* A connection made below on an incoming SABM holds no reference on +* the ax25_dev either. We are called under rcu_read_lock(), which +* ax25_kill_by_device() waits for after it has cleared device_up: +* leave a device that is going down alone. +*/ +if (!READ_ONCE (ax25_dev->device_up)) + goto free; +/* * Parse the address header. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 177/247 ax25: send a private copy of each I frame
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
ax25_kick() keeps every I frame on the ack queue until it is acknowledged and hands a clone of it to the device. After a REJ or a T1 timeout the frame goes back to the write queue and ax25_kick() clones it again. A clone shares its data with the original, so ax25_send_iframe() and ax25_transmit_buffer() write the control field and the address header of the new clone in the very bytes used by the previous one. If the previous clone is still waiting in the device queue, its control field is rewritten there: it leaves with the N(R) current at the time of the retransmission, not the one it was sent with.
Frames queued behind it, an RR for instance, were built in between with a lower N(R). The peer then receives an N(R) lower than one it has already been given. ax25_validate_nr() rejects it and ax25_std_nr_error_recovery() resets the link with a SABM, in the middle of a transfer. The layers above pay for it: on a ROSE circuit, the frames replayed after the reset carry stale sequence numbers and the circuit is reset as well, with loss of data.
Hand a private copy to the device instead. The frames are small (256 bytes of data by default) and the link is slow, the extra copy is not measurable.
Found on a test bench: two virtual machines with four CPUs each, a 6.12.94 kernel with KASAN and lockdep, one ROSE circuit over an AX.25 link on a serial line (mkiss), 192 messages each way in bursts of 24, and three REJ frames injected by one side. Instrumentation showed that frames reached the driver in the order they were given to dev_queue_xmit(), that V(R) never went backwards on the sender, and that the driver nevertheless saw frames whose N(R) was lower than the one before.
Counting, on the receiver, the frames whose N(R) is lower than the previous one:
- this code plus the two pending AX.25 fixes used on the bench (REJ guard, requeue on re-establishment): 4 runs, 13 such frames, 4 link resets; with this patch: 6 runs, none, no link reset;
- the same with the transmit serialisation patches for AX.25 and ROSE on top: link resets in most runs before; with this patch: 6 runs, none, no link reset, no ROSE reset, 192/192 messages both ways in every run.
--- net/ax25/ax25_out.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
net/ax25/ax25_out.c +10 -1
@@ -341,7 +341,16 @@ void ax25_kick(ax25_cb *ax25) ax25->vs = start; do { - if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) { + /* + * Send a private copy, not a clone. The frame stays on the + * ack queue and is sent again after a REJ or a T1 timeout, + * while the previous copy may still be waiting in the device + * queue. A clone shares its data with the original: building + * the frame again would rewrite the control field, and so + * the N(R), of the copy already queued. + */ + skbn = skb_copy(skb, GFP_ATOMIC); + if (!skbn) { skb_queue_head(&ax25->write_queue, skb); break; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 178/247 rose: clear the circuits of a neighbour that restarts the link
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
A Restart Request is the X.25 way to say that every virtual circuit of a link is gone. rose_link_rx_restart() only marks the neighbour as restarted and answers with a Restart Confirmation: the sockets and the through routes that used the link are left as they were.
That is harmless on a link coming up, nothing is established yet. It is not when the other end restarts its AX.25 and ROSE stack while we keep the link: the first thing it sends is a SABM, which resets our AX.25 connection without bringing it down, then a Restart Request. Its circuits are gone, ours stay in state 3 forever:
- a frame for a logical channel that the other end does not know is dropped silently by rose_route_frame(), so no Clear Request ever comes back;
- no timer watches the acknowledgement of data in state 3, and the idle timer is off by default;
- the through routes stay in /proc/net/rose_routes and the remote ends of those calls are never told.
The stale entries are not just a leak. The restarted end allocates its logical channel numbers afresh, so a new circuit can get the number of a stale through route on the same link, and whatever still arrives on the stale half is then relayed into the new circuit.
Seen on a live network: a node that restarts its stack from cron left, on each of three neighbours, a data circuit with five unacknowledged frames that never moved again, and five through routes on the node that relays for the others.
Clear them when a Restart Request arrives on a link that is already
up: send a Clear Request to the other half of each through route and drop the route, and disconnect the local sockets, as rose_link_failed() does when the link goes down. The loop of rose_del_route_by_neigh() is moved to a helper for that, since the caller here already holds rose_route_list_lock. Nothing is sent to the restarting neighbour: it has no circuit left, and a Clear Request could hit a call it has just placed on a reused channel number.
A link that is not up yet is left alone: nothing can be established over it, and the sockets found there are calls waiting in neigh->queue for the restart to complete.
Tested with three QEMU guests in a line, A - B - C, on a kernel with lockdep and KASAN. A calls C through B and B calls C, both circuits stay open, then C destroys and recreates its AX.25 interface, reloads its routes and calls B. Before: both circuits are still open a minute later, B keeps the through route, nobody is told. After: A and B get the circuit cleared (cause 0x09) within a second of the Restart Request, B has no through route left, and the new call from C goes through at the first attempt. Four runs, no lockdep, KASAN or refcount report.
--- include/net/rose.h | 1 + net/rose/rose_link.c | 8 ++++++++ net/rose/rose_route.c | 44 +++++++++++++++++++++++++++++++++---------- 3 files changed, 43 insertions(+), 10 deletions(-)
include/net/rose.h +1 -0
@@ -269,6 +269,7 @@ struct rose_neigh *rose_get_neigh(rose_address *, unsigned char *, unsigned char *, int);int rose_rt_ioctl (unsigned int ,void __user *);void rose_link_failed (ax25_cb *,int ); +void rose_link_restarted (struct rose_neigh *);int rose_route_frame (struct sk_buff *,ax25_cb *);void rose_rt_free (void );
net/rose/rose_link.c +8 -0
@@ -142,6 +142,14 @@ void rose_link_rx_restart(struct sk_buff *skb, struct rose_neigh *neigh, unsigneswitch (frametype) {case ROSE_RESTART_REQUEST : +/* +* A Restart Request on a link that is already up means that +* the other end has lost its virtual circuits, clear ours. +* Nothing is established over a link that is not up yet, and +* the calls waiting in neigh->queue must be left alone. +*/ +if (neigh->restarted) +rose_link_restarted (neigh);rose_stop_t0timer (neigh); neigh->restarted =1 ; neigh->dce_mode = (skb->data[3 ] ==ROSE_DTE_ORIGINATED );
net/rose/rose_route.c +34 -10
62 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 179/247 ax25: send unacknowledged I frames again when a link is re-established
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
When a connection goes back through state 1 from state 3 or 4 (invalid N(R), FRMR, illegal frame), the UA that re-establishes it resets V(S), V(A) and V(R) but leaves the I frames that were waiting for their acknowledgment in the ack queue. From then on every acknowledgment frees the frame at the head of the queue, an old one, instead of the one it is for, so the queue keeps that many frames too many for ever:
- they stay charged to the socket that sent them, whose send memory is never given back;
- they are sent again by the next go-back-N, long after the event, and the peer gets duplicates;
- they were not sent again when the link came back, so the layer above lost them.
Seen on a live ROSE node: an AX.25 connection in state 3 with V(S) == V(A), empty write queue and 18 frames in its ack queue, and the ROSE sockets using it showing a send queue that never drains.
Requeue those frames when the UA is received, as is already done when the peer resets the link with a SABM in state 3 or 4. Same change in the DAMA slave state machine.
Like that existing path, this can send again a frame that the peer had received just before the reset: AX.25 has no way to know. The layer above sees a duplicate instead of a silent loss. ROSE drops an exact duplicate, but resets the circuit when the replayed frame carries an N(R) that is no longer valid. On the nodes below those resets came with link re-establishments caused by a late N(R), which "ax25: send a private copy of each I frame" removes: with both patches the node that is instrumented saw no re-establishment and no reset in 49 hours, against five resets in the 47 hours before.
Tested in QEMU (6.12.94 with lockdep and KASAN), two nodes over a mkiss serial link, one ROSE circuit, 40 messages 150 ms apart, the link forced through state 1 three times by an injected FRMR. Before:
6 runs of 6 deliver 40/40 and leave one frame in the ack queue, the ROSE socket keeps 960 bytes of send memory. After: 6 of 6 deliver 40/40 and the send memory goes back to zero. No lockdep, KASAN or refcount report.
On four production nodes since 3 October 2026, six since 6 October. A relay node that had 18 to 20 such frames on one link is sampled every
hour: 124 samples and 1301 link states in five days, none with a frame left in an ack queue.
--- net/ax25/ax25_ds_in.c | 2 ++ net/ax25/ax25_std_in.c | 8 ++++++++ 2 files changed, 10 insertions(+)
net/ax25/ax25_ds_in.c +2 -0
@@ -58,6 +58,8 @@ static int ax25_ds_state1_machine(ax25_cb *ax25, struct sk_buff *skb, int framet ax25->vr =0 ; ax25->state =AX25_STATE_3 ; ax25->n2count =0 ; +/* I frames left unacknowledged by a link reset: send them again */ +ax25_requeue_frames (ax25);if (ax25->sk !=NULL ) {bh_lock_sock (ax25->sk); ax25->sk->sk_state =TCP_ESTABLISHED ;
net/ax25/ax25_std_in.c +8 -0
@@ -66,6 +66,14 @@ static int ax25_std_state1_machine(ax25_cb *ax25, struct sk_buff *skb, int frame ax25->vr =0 ; ax25->state =AX25_STATE_3 ; ax25->n2count =0 ; +/* +* The link may have been re-established from state +* 3 or 4 with I frames still waiting for their +* acknowledgment. V(S) and V(A) start again from +* zero: send those frames again, as is done when +* the peer resets the link with a SABM. +*/ +ax25_requeue_frames (ax25);if (ax25->sk !=NULL ) {bh_lock_sock (ax25->sk); ax25->sk->sk_state =TCP_ESTABLISHED ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 180/247 rose: bring up the link of the preferred route passed over by a connect request
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
For a connect request rose_get_neigh() walks the routes that match the address, from the most specific to the least specific, and takes the first neighbour whose link is restarted. A neighbour whose link is down is only used when no matching route at all has a restarted neighbour.
A node that has both an exact route to a neighbouring node and a wide route through a relay therefore never uses the exact route once its link is down: the relay is restarted, it is always found first, and since no frame is ever sent over the direct link nothing brings it up again. The calls keep going through the relay, which may have no route other than back to the calling node and then clears them. Seen on a node whose White Pages daemon calls an adjacent node: every call goes to the relay and comes back as CLEAR REQUEST "not obtainable", for as long as the node runs.
Keep sending the call to the restarted neighbour, so that a call never waits for a link that may not answer, but when a neighbour of a more specific route, or an earlier neighbour of the same route, was passed over because its link is down, start the restart procedure on that link. If the other end answers, the next call finds the link restarted and uses it. A link that has just failed is left alone for link_fail_timeout, and nothing is done while a restart is under way.
Frames in transit are handled as before.
Tested in QEMU with a lockdep and KASAN kernel, three nodes A - B - C where B has an exact route to C over their direct link and a wide route through A, and the link B - A is restarted while B - C is not. Before, every call from B to C goes to A and is cleared there, and the direct link stays down. After, the first call still goes to A, the direct link is restarted within 20 ms and the following calls go through it. With C switched off no call waits: they all go to A at once, the restart is attempted once, and after the AX.25 connection gives up the link is left alone for link_fail_timeout. A call from A to C in transit through B gets the same answer before and after. No lockdep, KASAN or refcount report.
--- include/net/rose.h | 1 + net/rose/rose_link.c | 14 ++++++++++++++ net/rose/rose_route.c | 14 ++++++++++++++ 3 files changed, 29 insertions(+)
include/net/rose.h +1 -0
@@ -240,6 +240,7 @@ void rose_link_rx_restart(struct sk_buff *, struct rose_neigh *,void rose_transmit_clear_request (struct rose_neigh *,unsigned int ,unsigned char ,unsigned char );void rose_link_restart (struct rose_neigh *neigh); +void rose_link_bring_up (struct rose_neigh *neigh);void rose_transmit_link (struct sk_buff *,struct rose_neigh *);/* rose_loopback.c */
net/rose/rose_link.c +14 -0
@@ -287,6 +287,20 @@ void rose_link_restart(struct rose_neigh *neigh)rose_start_t0timer (neigh); } +/* +* Start the restart procedure on a link that is down without waiting for +* a frame to send over it. Nothing is done while a restart is under way. +*/ +void rose_link_bring_up (struct rose_neigh *neigh) +{ +if (neigh->loopback || neigh->restarted ||rose_t0timer_running (neigh)) +return ; + +rose_transmit_restart_request (neigh); + neigh->dce_mode =0 ; +rose_start_t0timer (neigh); +} +void rose_transmit_link (struct sk_buff *skb,struct rose_neigh *neigh) {unsigned char *dptr;
net/rose/rose_route.c +14 -0
@@ -741,6 +741,7 @@ struct rose_neigh *rose_get_neigh(rose_address *addr, unsigned char *cause, unsigned char *diagnostic, int route_frame) {struct rose_neigh *res =NULL ; +struct rose_neigh *down =NULL ;struct rose_node *node;int failed =0 ;int i;
@@ -752,8 +753,21 @@ struct rose_neigh *rose_get_neigh(rose_address *addr, unsigned char *cause,if (node->neighbour[i]->restarted) { res = node->neighbour[i];rose_neigh_hold (node->neighbour[i]); +/* +* A neighbour of a more specific route +* was passed over because its link is +* down: this call does not wait for it, +* but have the link brought up for the +* next ones. +*/ +if (down) +rose_link_bring_up (down); goto out; } +/* The first one is the preferred one. */ +if (!route_frame && !down && + !rose_ftimer_running (node->neighbour[i])) + down = node->neighbour[i]; } } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 181/247 ax25: dont free an incoming SABM skb left on the listeners queue
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
When a SABM comes in for a listening socket, ax25_rcv() creates the new socket, puts the skb on the listener's receive queue and only then allocates the digipeater path. If that allocation fails, the skb is freed with kfree_skb() while it is still linked on the queue, and the accept backlog count taken by sk_acceptq_added() is never given back. The next accept() or the close of the listener then walks a queue that contains a freed skb.
Allocate the path before the skb is queued, so that the error path only has to free an skb nobody else knows about and to destroy the new socket. The later allocation remains for a connection that has no listening socket.
Only reachable when the atomic allocation fails for a call that comes through digipeaters. Regression tested in QEMU (6.12.94 with lockdep and KASAN): 14 incoming connections to a listening socket, each accepted, served and closed, before and after; no report.
--- net/ax25/ax25_in.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-)
net/ax25/ax25_in.c +20 -3
@@ -383,6 +383,24 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev, } ax25 =sk_to_ax25 (make); + +/* +* Get the digipeater path before the skb goes on the +* listener's queue: once queued it belongs to that queue +* and cannot simply be freed if the allocation fails. +*/ +if (dp.ndigi && !ax25->digipeat) { + ax25->digipeat =kmalloc (sizeof (ax25_digi),GFP_ATOMIC ); +if (!ax25->digipeat) { +kfree_skb (skb); +ax25_destroy_socket (ax25); +bh_unlock_sock (sk); +sock_put (sk); + +return 0 ; + } + } +skb_set_owner_r (skb, make);skb_queue_head (&sk->sk_receive_queue, skb);
@@ -406,14 +424,13 @@ static int ax25_rcv(struct sk_buff *skb, struct net_device *dev, ax25->dest_addr = src;/* -* Sort out any digipeated paths. +* Sort out any digipeated paths. A socket made from a listener +* already has its path allocated, see above. */ if (dp.ndigi && !ax25->digipeat && (ax25->digipeat =kmalloc (sizeof (ax25_digi),GFP_ATOMIC )) ==NULL ) {kfree_skb (skb);ax25_destroy_socket (ax25); -if (sk) -sock_put (sk);return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 182/247 mm/pagewalk: fix stale walk->action escaping walk_pmd_range()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunwoo Kim <[email protected]>
[ Upstream commit aedf2efd18977e0cef7eb963166e2b1fcc0aa321 ]
If ->pmd_entry() sets walk->action = ACTION_AGAIN, the pmd_none() check is retried. The PMD entry may be cleared at the point of retry.
In this case, if walk->ops->install_pte is not specified, the code continues to the next PMD entry in the range without resetting walk->action to ACTION_SUBTREE.
This leaves walk->action erroneously set to ACTION_AGAIN, which is incorrect.
This was incorrect but not problematic up until commit 3b89863c3fa4 ("mm/pagewalk: fix race between concurrent split and refault") which updated walk_pud_range() to check for walk->action == ACTION_AGAIN upon walk_pmd_range()'s return, causing the PUD walk to be retried.
In this case this results in duplicate walk callbacks being invoked, which is erroneous and will break any caller that is not idempotent with respect to this (and waste time for those which are). The result is an out-of-bounds write, triggered by a local fuzzer:
[ 2.272695] ================================================================== [ 2.273471] BUG: KASAN: slab-out-of-bounds in __mincore_unmapped_range+0x14f/0x190 [ 2.274302] Write of size 1 at addr ffff888008d9b000 by task poc/106 [ 2.274966] [ 2.275154] CPU: 0 UID: 1000 PID: 106 Comm: poc Not tainted 7.2.0-rc6-00429-ga7c7074b58d2 #55 PREEMPT(lazy) [ 2.275159] 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 [ 2.275164] Call Trace: [ 2.275170] <TASK> [ 2.275172] dump_stack_lvl+0x53/0x70 [ 2.275200] print_report+0xd0/0x630 [ 2.275210] ? __pfx__raw_spin_lock_irqsave+0x10/0x10 [ 2.275219] ? irqentry_exit+0xd2/0x670 [ 2.275224] ? irqentry_exit+0xd2/0x670 [ 2.275226] ? __virt_addr_valid+0xef/0x1a0 [ 2.275239] ? __mincore_unmapped_range+0x14f/0x190 [ 2.275242] kasan_report+0xce/0x100 [ 2.275245] ? __mincore_unmapped_range+0x14f/0x190 [ 2.275248] __mincore_unmapped_range+0x14f/0x190 [ 2.275252] mincore_unmapped_range+0x45/0x70 [ 2.275254] walk_pgd_range+0xafc/0xfc0 [ 2.275261] ? __pfx_walk_pgd_range+0x10/0x10 [ 2.275264] ? __update_load_avg_se+0x3d1/0x670 [ 2.275275] __walk_page_range+0xc0/0x310 [ 2.275278] ? __pfx_find_vma+0x10/0x10 [ 2.275281] ? finish_task_switch.isra.0+0x16d/0x4f0 [ 2.275290] walk_page_range_mm_unsafe+0x26f/0x3a0 [ 2.275293] ? __pfx_mtree_load+0x10/0x10 [ 2.275298] ? __pfx_walk_page_range_mm_unsafe+0x10/0x10 [ 2.275302] ? __free_frozen_pages+0x54d/0x7e0 [ 2.275308] __do_sys_mincore+0x132/0x380 [ 2.275311] do_syscall_64+0xf9/0x540 [ 2.275316] entry_SYSCALL_64_after_hwframe+0x77/0x7f [ 2.275322] RIP: 0033:0x422ccd [ 2.275326] Code: b3 66 2e 0f 1f 84 00 00 00 00 00 66 90 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b8 ff ff ff f7 d8 64 89 01 48 [ 2.275329] RSP: 002b:00007fffffffec18 EFLAGS: 00000287 ORIG_RAX: 000000000000001b [ 2.275337] RAX: ffffffffffffffda RBX: 0000000000000066 RCX: 0000000000422ccd [ 2.275339] RDX: 00000000004d0940 RSI: 0000000001000000 RDI: 00007ffff4000000 [ 2.275340] RBP: 00000000004d0940 R08: 0000000000000100 R09: 0000000000000100 [ 2.275342] R10: 0000000000000100 R11: 0000000000000287 R12: 20c49ba5e353f7cf [ 2.275343] R13: 00000000004990d3 R14: 0000000000000000 R15: 0000000000000001 [ 2.275346] </TASK> [ 2.275347] [ 2.296904] The buggy address belongs to the object at ffff888008d9b000 [ 2.296904] which belongs to the cache sigqueue of size 80 [ 2.298151] The buggy address is located 0 bytes inside of [ 2.298151] allocated 80-byte region [ffff888008d9b000, ffff888008d9b050) [ 2.299408] [ 2.299601] The buggy address belongs to the physical page: [ 2.300191] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x8d9b [ 2.301001] flags: 0x100000000000000(node=0|zone=1) [ 2.301535] page_type: f5(slab) [ 2.301884] raw: 0100000000000000 ffff888107e46780 dead000000000122 0000000000000000 [ 2.302687] raw: 0000000000000000 0000000800240024 00000000f5000000 0000000000000000 [ 2.303489] page dumped because: kasan: bad access detected [ 2.304092] [ 2.304276] Memory state around the buggy address: [ 2.304801] ffff888008d9af00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 2.305567] ffff888008d9af80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 2.306340] >ffff888008d9b000: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 2.307115] ^ [ 2.307474] ffff888008d9b080: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 2.308237] ffff888008d9b100: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 2.308997] ==================================================================
A specific example of this breaking things is mincore which walks an internal cursor data structure a byte at a time on assumption that page table entry callbacks are called only once for each entry.
Fix the problem by resetting walk->action to ACTION_SUBTREE prior to the none check.
The pattern also exists in walk_pud_range() so fix it there too.
This issue was found through AI-based fuzzing.
--- mm/pagewalk.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
mm/pagewalk.c +2 -4
@@ -108,6 +108,7 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, pmd =pmd_offset (pud, addr); do { again: + walk->action = ACTION_SUBTREE; next = pmd_addr_end(addr, end); if (pmd_none(*pmd)) { if (ops->pte_hole)
@@ -117,8 +118,6 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,continue ; } - walk->action =ACTION_SUBTREE ; -/* * This implies that each ->pmd_entry() handler * needs to know about pmd_trans_huge() pmds
@@ -167,6 +166,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, pud =pud_offset (p4d, addr); do { again: + walk->action = ACTION_SUBTREE; next = pud_addr_end(addr, end); if (pud_none(*pud)) { if (ops->pte_hole)
@@ -176,8 +176,6 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,continue ; } - walk->action =ACTION_SUBTREE ; -if (ops->pud_entry) err = ops->pud_entry (pud, addr, next, walk);if (err)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 183/247 block: avoid potential deadlock on zone revalidation failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Damien Le Moal <[email protected]>
commit 3dd63dba8f9cb6990a40af7ed66ee0159f475819 upstream.
If revalidating the zones of a zoned block device with blk_revalidate_disk_zones() fails during a SCSI disk rescan, the following lockdep splat is thrown:
[ 347.251859] [ T11230] sda: failed to revalidate zones
[ 347.261380] [ T11230] ======================================================
[ 347.263882] [ T11230] WARNING: possible circular locking dependency detected
[ 347.266353] [ T11230] 7.1.0+ #1194 Not tainted
[ 347.268052] [ T11230] ------------------------------------------------------
[ 347.270537] [ T11230] tcsh/11230 is trying to acquire lock:
[ 347.272555] [ T11230] ffffffff8f91d400 (wq_pool_mutex){+.+.}-{4:4}, at: destroy_workqueue+0x15d/0x8d0
[ 347.275914] [ T11230]
but task is already holding lock:
[ 347.278646] [ T11230] ffff88812fa1bcc0 (&q->q_usage_counter(io)#5){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x16/0x30
[ 347.282503] [ T11230]
which lock already depends on the new lock.[ 347.286239] [ T11230]
the existing dependency chain (in reverse order) is:
[ 347.289408] [ T11230]
-> #2 (&q->q_usage_counter(io)#5){++++}-{0:0}:
[ 347.292437] [ T11230] blk_alloc_queue+0x5ca/0x750
[ 347.294379] [ T11230] blk_mq_alloc_queue+0x14c/0x240
[ 347.296375] [ T11230] scsi_alloc_sdev+0x871/0xd10 [scsi_mod]
[ 347.298619] [ T11230] scsi_probe_and_add_lun+0x600/0xc50 [scsi_mod]
[ 347.301056] [ T11230] __scsi_scan_target+0x187/0x3b0 [scsi_mod]
[ 347.303385] [ T11230] scsi_scan_channel+0xf2/0x180 [scsi_mod]
[ 347.305651] [ T11230] scsi_scan_host_selected+0x20b/0x2d0 [scsi_mod]
[ 347.308119] [ T11230] do_scan_async+0x42/0x420 [scsi_mod]
[ 347.310276] [ T11230] async_run_entry_fn+0x94/0x5a0
[ 347.312284] [ T11230] process_one_work+0x8da/0x1690
[ 347.314287] [ T11230] worker_thread+0x5fe/0x1010
[ 347.316216] [ T11230] kthread+0x358/0x450
[ 347.317675] [ T11230] ret_from_fork+0x5b9/0x8e0
[ 347.319181] [ T11230] ret_from_fork_asm+0x11/0x20
[ 347.320778] [ T11230]
-> #1 (fs_reclaim){+.+.}-{0:0}:
[ 347.322890] [ T11230] fs_reclaim_acquire+0xd5/0x120
[ 347.324464] [ T11230] __kmalloc_cache_node_noprof+0x39/0x620
[ 347.326223] [ T11230] init_rescuer+0x19b/0x560
[ 347.327697] [ T11230] workqueue_init+0x33b/0x6a0
[ 347.329224] [ T11230] kernel_init_freeable+0x2eb/0x600
[ 347.330881] [ T11230] kernel_init+0x1c/0x140
[ 347.332334] [ T11230] ret_from_fork+0x5b9/0x8e0
[ 347.333847] [ T11230] ret_from_fork_asm+0x11/0x20
[ 347.335360] [ T11230]
-> #0 (wq_pool_mutex){+.+.}-{4:4}:
[ 347.337510] [ T11230] __lock_acquire+0xdea/0x2260
[ 347.339030] [ T11230] lock_acquire+0x187/0x2f0
[ 347.340495] [ T11230] __mutex_lock+0x1ab/0x2600
[ 347.341464] [ T11230] destroy_workqueue+0x15d/0x8d0
[ 347.342485] [ T11230] disk_free_zone_resources+0xd5/0x560
[ 347.343577] [ T11230] blk_revalidate_disk_zones+0x620/0xac7
[ 347.344723] [ T11230] sd_zbc_revalidate_zones+0x1dd/0x790 [sd_mod]
[ 347.345938] [ T11230] sd_revalidate_disk+0xc66/0x8e60 [sd_mod]
[ 347.347112] [ T11230] scsi_rescan_device+0x1f9/0x310 [scsi_mod]
[ 347.348318] [ T11230] store_rescan_field+0x19/0x20 [scsi_mod]
[ 347.349507] [ T11230] kernfs_fop_write_iter+0x3d2/0x5e0
[ 347.350565] [ T11230] vfs_write+0x469/0x1000
[ 347.351484] [ T11230] ksys_write+0x116/0x250
[ 347.352403] [ T11230] do_syscall_64+0xf0/0x6e0
[ 347.353361] [ T11230] entry_SYSCALL_64_after_hwframe+0x4b/0x53
[ 347.354533] [ T11230]
other info that might help us debug this:[ 347.356432] [ T11230] Chain exists of:
wq_pool_mutex --> fs_reclaim --> &q->q_usage_counter(io)#5[ 347.358919] [ T11230] Possible unsafe locking scenario:
[ 347.360307] [ T11230] CPU0 CPU1
[ 347.361327] [ T11230] ---- ----
[ 347.362340] [ T11230] lock(&q->q_usage_counter(io)#5);
[ 347.363344] [ T11230] lock(fs_reclaim);
[ 347.364526] [ T11230] lock(&q->q_usage_counter(io)#5);
[ 347.365968] [ T11230] lock(wq_pool_mutex);
[ 347.366811] [ T11230]
*** DEADLOCK ***This happens because SCSI disk rescan is executed from a work context and a failure of blk_revalidate_disk_zones() causes a call to disk_free_zone_resources() which will free the disk zone write plug workqueue.
Avoid this by delaying the destruction of the disk zone write plug workqueue to disk_release(). Do this by introducing the function disk_release_zone_resources() and using this new function from disk_release(). This new function destroys the zone write plugs workqueue and calls disk_free_zone_resources(), thus allowing to remove the call to destroy_workqueue() from disk_free_zone_resources(). disk_alloc_zone_resources() is modified to not create the disk zone write plug work queue if it already exists.
[ stanleyjhu: 6.12.y has no zone write plug kthread worker and does not
use WQ_PERCPU, so only the workqueue part applies:
disk_alloc_zone_resources() reuses an existing workqueue, disk_free_zone_resources() drains it instead of destroying it, and the new disk_release_zone_resources() destroys it from disk_release(). ]
--- block/blk-zoned.c | 37 +++++++++++++++++++++++++++---------- block/blk.h | 4 ++-- block/genhd.c | 2 +- 3 files changed, 30 insertions(+), 13 deletions(-)
block/blk-zoned.c +27 -10
@@ -1408,11 +1408,20 @@ static int disk_alloc_zone_resources(struct gendisk *disk,if (!disk->zone_wplugs_pool) goto free_hash; - disk->zone_wplugs_wq = -alloc_workqueue ("%s_zwplugs" ,WQ_MEM_RECLAIM |WQ_HIGHPRI , - pool_size, disk->disk_name); -if (!disk->zone_wplugs_wq) - goto destroy_pool; +/* +* We may already have a zone write plug workqueue as this function may +* be called after disk_free_zone_resources(), which does not destroy +* the workqueue (the zone write plugs workqueue is destroyed at +* disk_release() time). +*/ +if (!disk->zone_wplugs_wq) { + disk->zone_wplugs_wq = +alloc_workqueue ("%s_zwplugs" , +WQ_MEM_RECLAIM |WQ_HIGHPRI , + pool_size, disk->disk_name); +if (!disk->zone_wplugs_wq) + goto destroy_pool; + }return 0 ;
@@ -1469,15 +1478,13 @@ static unsigned int disk_set_conv_zones_bitmap(struct gendisk *disk,return nr_conv_zones; } -void disk_free_zone_resources (struct gendisk *disk) +static void disk_free_zone_resources (struct gendisk *disk) {if (!disk->zone_wplugs_pool)return ; -if (disk->zone_wplugs_wq) { -destroy_workqueue (disk->zone_wplugs_wq); - disk->zone_wplugs_wq =NULL ; - } +if (disk->zone_wplugs_wq) +drain_workqueue (disk->zone_wplugs_wq);disk_destroy_zone_wplugs_hash_table (disk);
@@ -1496,6 +1503,16 @@ void disk_free_zone_resources(struct gendisk *disk) disk->nr_zones =0 ; } +void disk_release_zone_resources (struct gendisk *disk) +{ +if (disk->zone_wplugs_wq) { +destroy_workqueue (disk->zone_wplugs_wq); + disk->zone_wplugs_wq =NULL ; + } + +disk_free_zone_resources (disk); +} +static inline bool disk_need_zone_resources (struct gendisk *disk) {/*
block/blk.h +2 -2
@@ -489,7 +489,7 @@ static inline struct bio *blk_queue_bounce(struct bio *bio,#ifdef CONFIG_BLK_DEV_ZONED void disk_init_zone_resources (struct gendisk *disk); -void disk_free_zone_resources (struct gendisk *disk); +void disk_release_zone_resources (struct gendisk *disk);static inline bool bio_zone_write_plugging (struct bio *bio) {return bio_flagged (bio,BIO_ZONE_WRITE_PLUGGING );
@@ -550,7 +550,7 @@ int blkdev_zone_mgmt_ioctl(struct block_device *bdev, blk_mode_t mode,static inline void disk_init_zone_resources (struct gendisk *disk) { } -static inline void disk_free_zone_resources (struct gendisk *disk) +static inline void disk_release_zone_resources (struct gendisk *disk) { }static inline bool bio_zone_write_plugging (struct bio *bio)
block/genhd.c +1 -1
@@ -1219,7 +1219,7 @@ static void disk_release(struct device *dev)disk_release_events (disk);kfree (disk->random); -disk_free_zone_resources (disk); +disk_release_zone_resources (disk);xa_destroy (&disk->part_tbl); disk->queue->disk =NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 184/247 Revert "srcu: Use irq_work to start GP in tiny SRCU"
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
This reverts commit 2127e6b79d9d579ea538a350d1bbe859e39814d5.
--- include/linux/srcutiny.h | 4 ---- kernel/rcu/srcutiny.c | 19 +------------------ 2 files changed, 1 insertion(+), 22 deletions(-)
include/linux/srcutiny.h +0 -4
@@ -11,7 +11,6 @@#ifndef _LINUX_SRCU_TINY_H#define _LINUX_SRCU_TINY_H -#include <linux/irq_work_types.h> #include <linux/swait.h> struct srcu_struct {
@@ -25,21 +24,18 @@ struct srcu_struct {struct rcu_head *srcu_cb_head;/* Pending callbacks: Head. */ struct rcu_head **srcu_cb_tail;/* Pending callbacks: Tail. */ struct work_struct srcu_work;/* For driving grace periods. */ -struct irq_work srcu_irq_work;/* Defer schedule_work() to irq work. */ #ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map;#endif /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */ };void srcu_drive_gp (struct work_struct *wp); -void srcu_tiny_irq_work (struct irq_work *irq_work);#define __SRCU_STRUCT_INIT (name, __ignored, ___ignored) \ { \ .srcu_wq = __SWAIT_QUEUE_HEAD_INITIALIZER(name.srcu_wq), \ .srcu_cb_tail = &name.srcu_cb_head, \ .srcu_work = __WORK_INITIALIZER(name.srcu_work, srcu_drive_gp), \ - .srcu_irq_work = { .func = srcu_tiny_irq_work }, \ __SRCU_DEP_MAP_INIT(name) \ }
kernel/rcu/srcutiny.c +1 -18
@@ -9,7 +9,6 @@*/ #include <linux/export.h> -#include <linux/irq_work.h> #include <linux/mutex.h> #include <linux/preempt.h> #include <linux/rcupdate_wait.h>
@@ -38,7 +37,6 @@ static int init_srcu_struct_fields(struct srcu_struct *ssp) ssp->srcu_idx_max =0 ;INIT_WORK (&ssp->srcu_work, srcu_drive_gp);INIT_LIST_HEAD (&ssp->srcu_work.entry); -init_irq_work (&ssp->srcu_irq_work, srcu_tiny_irq_work);return 0 ; }
@@ -82,7 +80,6 @@ EXPORT_SYMBOL_GPL(init_srcu_struct);void cleanup_srcu_struct (struct srcu_struct *ssp) {WARN_ON (ssp->srcu_lock_nesting[0 ] || ssp->srcu_lock_nesting[1 ]); -irq_work_sync (&ssp->srcu_irq_work);flush_work (&ssp->srcu_work);WARN_ON (ssp->srcu_gp_running);WARN_ON (ssp->srcu_gp_waiting);
@@ -171,20 +168,6 @@ void srcu_drive_gp(struct work_struct *wp) }EXPORT_SYMBOL_GPL (srcu_drive_gp); -/* -* Use an irq_work to defer schedule_work() to avoid acquiring the workqueue -* pool->lock while the caller might hold scheduler locks, causing lockdep -* splats due to workqueue_init() doing a wakeup. -*/ -void srcu_tiny_irq_work (struct irq_work *irq_work) -{ -struct srcu_struct *ssp; - - ssp = container_of(irq_work, struct srcu_struct, srcu_irq_work); -schedule_work (&ssp->srcu_work); -} -EXPORT_SYMBOL_GPL (srcu_tiny_irq_work); -static void srcu_gp_start_if_needed (struct srcu_struct *ssp) {unsigned long cookie;
@@ -198,7 +181,7 @@ static void srcu_gp_start_if_needed(struct srcu_struct *ssp)WRITE_ONCE (ssp->srcu_idx_max, cookie);if (!READ_ONCE (ssp->srcu_gp_running)) {if (likely (srcu_init_done)) -irq_work_queue (&ssp->srcu_irq_work); +schedule_work (&ssp->srcu_work);else if (list_empty (&ssp->srcu_work.entry))list_add (&ssp->srcu_work.entry, &srcu_boot_list); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 185/247 net_sched: codel: fix stale state for empty flows in fq_codel
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jonas Köppeler <[email protected]>
[ Upstream commit 815980fe6dbb01ad4007e8b260a45617f598b76d ]
When codel_dequeue() finds an empty queue, it resets vars->dropping but does not reset vars->first_above_time. The reference CoDel algorithm (Nichols & Jacobson, ACM Queue 2012) resets both:
dodeque_result codel_queue_t::dodeque(time_t now) {
...
if (r.p == NULL) {
first_above_time = 0; // <-- Linux omits this
}
...
}Note that codel_should_drop() does reset first_above_time when called with a NULL skb, but codel_dequeue() returns early before ever calling codel_should_drop() in the empty-queue case. The post-drop code paths do reach codel_should_drop(NULL) and correctly reset the timer, so a dropped packet breaks the cycle -- but the next delivered packet re-arms first_above_time and the cycle repeats.
For sparse flows such as ICMP ping (one packet every 200ms-1s), the first packet arms first_above_time, the flow goes empty, and the second packet arrives after the interval has elapsed and gets dropped. The pattern repeats, producing sustained loss on flows that are not actually congested.
Test: veth pair, fq_codel, BQL disabled, 30000 iptables rules in the consumer namespace (NAPI-64 cycle ~14ms, well above fq_codel's 5ms target), ping at 5 pps under UDP flood:
Before fix: 26% ping packet loss
After fix: 0% ping packet loss
Fix by resetting first_above_time to zero in the empty-queue path of codel_dequeue(), matching the reference algorithm.
--- include/net/codel_impl.h | 1 + 1 file changed, 1 insertion(+)
include/net/codel_impl.h +1 -0
@@ -158,6 +158,7 @@ static struct sk_buff *codel_dequeue(void *ctx,bool drop;if (!skb) { + vars->first_above_time =0 ; vars->dropping = false;return skb; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 186/247 Bluetooth: L2CAP: refuse __l2cap_chan_add if chan already has conn
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pauli Virtanen <[email protected]>
[ Upstream commit 86b55991d3cd690e73c5ef8d20b75ae4905b357a ]
l2cap_chan may be linked to l2cap_conn at most once. This is assumed in several places, eg l2cap_chan_del cleanup.
There is a TOCTOU race where the invariant is violated:
[Task 1] [Task 2]
l2cap_chan_connect l2cap_sock_bind
l2cap_chan_lock lock_sock
l2cap_state_change if (sk->sk_state != BT_OPEN)
chan->state = BT_CONNECT
l2cap_sock_state_change_cb chan->state = BT_BOUND
sk->sk_state = BT_BOUND
lock_sock <------------------ release_sock
sk->sk_state = BT_CONNECTl2cap_sock_connect() does not check sk->sk_state, so since chan->state is now BT_BOUND, subsequent connect() ends up with second __l2cap_chan_add.
Explicitly document and check the invariant in __l2cap_chan_add with WARN_ON_ONCE. The only callsite where it could be hit is l2cap_chan_connect, so add pre-check there to avoid relying on chan->state. chan->state read/write is not properly guarded currently so there can be other TOCTOUC problems.
Add l2cap_lock_chan in l2cap_sock_bind() to guard chan->state write.
--- net/bluetooth/l2cap_core.c | 7 ++++++- net/bluetooth/l2cap_sock.c | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_core.c +6 -1
@@ -625,6 +625,10 @@ void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan)BT_DBG ("conn %p, psm 0x%2.2x, dcid 0x%4.4x" , conn,__le16_to_cpu (chan->psm), chan->dcid); +/* Caller must ensure l2cap_chan is linked to l2cap_conn only once */ +if (WARN_ON_ONCE (chan->conn ||test_bit (FLAG_DEL , &chan->flags))) +return ; + conn->disc_reason =HCI_ERROR_REMOTE_USER_TERM ; chan->conn =l2cap_conn_get (conn);
@@ -7388,7 +7392,8 @@ int l2cap_chan_connect(struct l2cap_chan *chan, __le16 psm, u16 cid, } } -if (cid &&__l2cap_get_chan_by_dcid (conn, cid)) { +if ((cid &&__l2cap_get_chan_by_dcid (conn, cid)) || chan->conn || +test_bit (FLAG_DEL , &chan->flags)) {hci_conn_drop (hcon); err = -EBUSY ; goto chan_unlock;
net/bluetooth/l2cap_sock.c +2 -0
@@ -112,6 +112,7 @@ static int l2cap_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)return -EINVAL ; } +l2cap_chan_lock (chan);lock_sock (sk);if (sk->sk_state !=BT_OPEN ) {
@@ -177,6 +178,7 @@ static int l2cap_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) done:release_sock (sk); +l2cap_chan_unlock (chan);return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 187/247 tracing: Reject incomplete event filter expressions
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 1fdc4164e488916402badddbb1f51e9380dabb91 upstream.
A non-empty expression normally finishes in predicate_parse()'s inner loop, which resolves the pending logical operators before jumping to finalization. If the input ends after an operator, possibly followed by unary '!' tokens, the outer loop instead falls through with unresolved operator state.
For example, "common_pid == 1 || common_pid == 2 &&" leaves prog[0].target equal to -1. The second pass then reads prog[-1] before the forward-jump check can reject it. Depending on adjacent slab contents, it can also copy an out-of-bounds word into a branch target that passes the forward-only check. A self-targeted perf tracepoint counting event can reach this path through PERF_EVENT_IOC_SET_FILTER.
Reject the outer-loop fallthrough when a predicate has already been parsed. This ensures that non-empty expressions only reach finalization after the inner loop has resolved their operators. Keep the existing no-filter error for input that has no predicates. Add a regression test for trailing logical operators and unary negations.
--- kernel/trace/trace_events_filter.c | 6 ++ tools/testing/selftests/ftrace/test.d/filter/event-filter-incomplete.tc | 24 ++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tools/testing/selftests/ftrace/test.d/filter/event-filter-incomplete.tc
kernel/trace/trace_events_filter.c +6 -0
@@ -595,6 +595,12 @@ predicate_parse(const char *str, int nr_ top--;/* #12 */ } } +/* Only the inner loop can complete a non-empty expression. */ +if (N ) { + ret = -EINVAL ; +parse_error (pe,FILT_ERR_INVALID_FILTER , ptr - str); + goto out_free; + } out:if (top != op_stack) {/* Too many '(' */
tools/testing/selftests/ftrace/test.d/filter/event-filter-incomplete.tc new file +24 -0
@@ -0,0 +1,24 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event filter - reject incomplete logical expressions +# requires: events/sched/sched_switch/filter +# flags: instance + +filter=events/sched/sched_switch/filter + +for base in \ + 'common_pid == 1' \ + 'common_pid == 1 || common_pid == 2' \ + 'common_pid == 1 && common_pid == 2' \ + '!(common_pid == 1 || common_pid == 2)' +do + printf '%s' "$base" > "$filter" + for tail in '&&' '||' '&& !' '|| !' '&& !! ' '|| !! '; do + if printf '%s' "$base $tail" > "$filter" 2>/dev/null; then + echo "Accepted incomplete filter: $base $tail" + exit_fail + fi + done +done + +echo 0 > "$filter"
Greg Kroah-Hartman
maintainerPATCH 188/247 tracing: Save the event file instead of the compatible histogram
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
commit d5c42664fc094899af9aae5300b27fe8fdb658ef upstream.
create_field_var_hist() creates a histogram on the matched event to supply a field variable, and records it on the target so it can be torn down later:
hist_data = find_compatible_hist(target_hist_data, file); ... /* Save the compatible histogram information */ var_hist->hist_data = hist_data;
hist_data is not the histogram it creates. It is one that was already there, whose keys the new one copies. The saved pointer has a single user, unregister_field_var_hists(), which runs when the target is removed:
file = hist_data->field_var_hists[i]->hist_data->event_file;
find_compatible_hist() matches on keys alone, so it can pick one with no variables of its own. check_var_refs() then returns false and the user can remove it while the target still points at it:
BUG: KASAN: slab-use-after-free in event_hist_trigger_free+0x2b2/0x320 Read of size 8 at addr ffff8880093b90e0 by task init/1 Freed by task 1: kfree+0x154/0x420 event_hist_trigger_free+0x1d5/0x320 event_hist_trigger_parse+0x35f3/0x69e0 trigger_process_regex+0x1a6/0x250
Save the event file instead. It is all the dereference ever wanted, and it does not go away when the user removes a trigger.
--- kernel/trace/trace_events_hist.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
kernel/trace/trace_events_hist.c +4 -4
@@ -542,7 +542,7 @@ struct field_var { };struct field_var_hist { -struct hist_trigger_data *hist_data; +struct trace_event_file *file;char *cmd; };
@@ -3077,8 +3077,8 @@ create_field_var_hist(struct hist_triggereturn ERR_PTR (-ENOMEM ); } -/* Save the compatible histogram information */ - var_hist->hist_data = hist_data; +/* Needed to remove the histogram when the target goes away */ + var_hist->file = file;/* Create the new histogram with our variable */ ret = event_hist_trigger_parse(&trigger_hist_cmd, file,
@@ -6299,7 +6299,7 @@ static void unregister_field_var_hists(sint ret;for (i =0 ; i < hist_data->n_field_var_hists; i++) { - file = hist_data->field_var_hists[i]->hist_data->event_file; + file = hist_data->field_var_hists[i]->file; cmd = hist_data->field_var_hists[i]->cmd; ret =event_hist_trigger_parse (&trigger_hist_cmd, file,"!hist" ,"hist" , cmd);
Greg Kroah-Hartman
maintainerPATCH 189/247 tracing: Unregister field variable histograms when the command fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
commit 91c14d6c13096091c56304120aaa26e479130b8b upstream.
An action that names a field on another event needs that field as a variable, so create_field_var_hist() registers a second hist trigger on that event to provide it, and records it in target_hist_data->field_var_hists[].
If a later part of the same command fails, create_actions() returns an error and event_hist_trigger_parse() jumps to out_free. The write fails with -EINVAL and sched_switch gets no trigger, but:
# echo 'hist:keys=pid:ts0=common_timestamp.usecs' >> \
events/sched/sched_waking/trigger
# echo 'my_synth u64 lat; int a; int b' >> synthetic_events
# echo 'hist:keys=next_pid:wakeup_lat=common_timestamp.usecs-$ts0:\
onmatch(sched.sched_waking).my_synth($wakeup_lat,prio,nosuchfld)'\
>> events/sched/sched_switch/trigger
# cat events/sched/sched_waking/trigger
hist:keys=pid:vals=hitcount:ts0=common_timestamp.usecs:sort=hitcount:size=2048:clock=global [active]
hist:keys=pid:vals=hitcount:synthetic_prio=prio:sort=hitcount:size=2048 [active]The second histogram is the one created for 'prio'. It is still active and still counting.
out_free reaches destroy_field_var_hists(), which frees the field_var_hists[] entries, but never unregister_field_var_hists(), which is what removes the triggers and runs only from event_hist_trigger_free(). The entry is freed and the trigger is left with nothing tracking it.
Unregister the field variable histograms in out_free as well, and record each one as soon as its trigger is registered rather than after the lookup that follows it, so no exit can leave a registered trigger untracked. The entry then belongs to field_var_hists[] and is released by destroy_field_var_hists(), so freeing it on that exit would be a double free.
--- kernel/trace/trace_events_hist.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_events_hist.c +6 -6
@@ -3093,20 +3093,18 @@ create_field_var_hist(struct hist_triggekfree (cmd); + n = target_hist_data->n_field_var_hists; + target_hist_data->field_var_hists[n] = var_hist; + target_hist_data->n_field_var_hists++; +/* If we can't find the variable, something went wrong */ event_var =find_synthetic_field_var (target_hist_data, subsys_name, event_name, field_name);if (IS_ERR_OR_NULL (event_var)) { -kfree (var_hist->cmd); -kfree (var_hist);hist_err (tr,HIST_ERR_SYNTH_VAR_NOT_FOUND ,errpos (field_name));return ERR_PTR (-EINVAL ); } - n = target_hist_data->n_field_var_hists; - target_hist_data->field_var_hists[n] = var_hist; - target_hist_data->n_field_var_hists++; -return event_var; }
@@ -6915,6 +6913,8 @@ static int event_hist_trigger_parse(strutrigger_data_free (trigger_data); +unregister_field_var_hists (hist_data); +destroy_hist_data (hist_data); goto out; }
Greg Kroah-Hartman
maintainerPATCH 190/247 tracing: Fix 64-bit and signed histogram fields on 32-bit kernels
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
commit 443d23176812803d0fa182b8d05ef066a7b8271f upstream.
DEFINE_HIST_FIELD_FN() reads a trace event field and widens it to the u64 the histogram uses as a key or a value:
type *addr = (type *)(event + hist_field->field->offset); return (u64)(unsigned long)*addr;
unsigned long is 32 bits on a 32-bit kernel, so the intermediate cast discards the upper half of a 64-bit field, and widens a signed field by zero extension from 32 bits rather than sign extension from its own width. Five of the eight instantiations are wrong there: s64, u64, s32, s16 and s8.
The cast came in with commit 79e577cbce4c ("tracing: Support string type key properly"), which also added hist_field_dynstring() and hist_field_pstring(). Those convert a char * to u64 and do warn without an unsigned long in between on 32-bit. DEFINE_HIST_FIELD_FN() converts an integer and never a pointer, so it gains nothing from the cast and only loses information.
Drop the intermediate cast and let the usual arithmetic conversions widen *addr according to its own type. unsigned long is 64 bits on LP64, so the two forms are identical there and 64-bit kernels are unaffected.
--- kernel/trace/trace_events_hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
@@ -460,7 +460,7 @@ static u64 hist_field_unary_minus(struct { \type *addr = (type *)(event + hist_field->field->offset); \ \ -return (u64 )(unsigned long )*addr; \ +return (u64)*addr; \ }DEFINE_HIST_FIELD_FN (s64);
Greg Kroah-Hartman
maintainerPATCH 191/247 tracing/histograms: Verify event_call identity when updating synth_event refcount
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 3403d9bb27ebc3572bd048620746b4414e073bf9 upstream.
In event_hist_trigger_parse() and hist_unreg_all(), the histogram registration and unregistration paths look up find_synth_event() using trace_event_name(file->event_call) and adjust se->ref if a match is found.
Because find_synth_event() only compares the event basename, registering or removing a histogram on a non-synthetic trace event whose basename matches a synthetic event erroneously modifies the synthetic event's reference count. If a histogram is registered on the non-synthetic event before the synthetic event is created and removed afterwards, se->ref is decremented without a matching increment, allowing the synthetic event to be freed while an active histogram action still holds a pointer to it.
Introduce find_synth_event_call() to verify that &se->call matches file->event_call before adjusting se->ref.
--- kernel/trace/trace_events_hist.c | 11 +++-------- kernel/trace/trace_events_synth.c | 10 ++++++++++ kernel/trace/trace_synth.h | 1 + 3 files changed, 14 insertions(+), 8 deletions(-)
kernel/trace/trace_events_hist.c +3 -8
@@ -6725,7 +6725,6 @@ static void hist_unreg_all(struct trace_struct event_trigger_data *test, *n;struct hist_trigger_data *hist_data;struct synth_event *se; -const char *se_name;lockdep_assert_held (&event_mutex);
@@ -6738,8 +6737,7 @@ static void hist_unreg_all(struct trace_list_del_rcu (&test->list);trace_event_trigger_enable_disable (file,0 ); - se_name =trace_event_name (file->event_call); - se =find_synth_event (se_name); + se =find_synth_event_call (file->event_call);if (se) se->ref--;
@@ -6763,7 +6761,6 @@ static int event_hist_trigger_parse(strustruct hist_trigger_data *hist_data;char *param, *filter, *p, *start;struct synth_event *se; -const char *se_name;bool remove;int ret =0 ;
@@ -6857,8 +6854,7 @@ static int event_hist_trigger_parse(stru }event_trigger_unregister (cmd_ops, file, glob+1 , trigger_data); - se_name =trace_event_name (file->event_call); - se =find_synth_event (se_name); + se =find_synth_event_call (file->event_call);if (se) se->ref--; ret =0 ;
@@ -6893,8 +6889,7 @@ static int event_hist_trigger_parse(struif (ret) goto out_unreg; - se_name =trace_event_name (file->event_call); - se =find_synth_event (se_name); + se =find_synth_event_call (file->event_call);if (se) se->ref++; out:
kernel/trace/trace_events_synth.c +10 -0
@@ -857,6 +857,16 @@ struct synth_event *find_synth_event(conreturn NULL ; } +struct synth_event *find_synth_event_call (struct trace_event_call *call) +{ +struct synth_event *se; +const char *name; + + name =trace_event_name (call); + se =find_synth_event (name); +return se && &se->call == call ? se :NULL ; +} +static struct trace_event_fields synth_event_fields_array[] = { { .type =TRACE_FUNCTION_TYPE , .define_fields = synth_event_define_fields },
kernel/trace/trace_synth.h +1 -0
@@ -37,5 +37,6 @@ struct synth_event { };extern struct synth_event *find_synth_event (const char *name); +extern struct synth_event *find_synth_event_call (struct trace_event_call *call);#endif /* __TRACE_SYNTH_H */
Greg Kroah-Hartman
maintainerPATCH 192/247 io-wq: order the exit bit against worker creation task work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
Commit 0e5663856b69219ef2f02e04bac9f5c5be19718a upstream.
io_wq_exit_workers() cancels task work for queued worker creation with task_work_cancel_match(). That has a plain load of task->task_works.
io_queue_worker_create() adds the new entry and tests IO_WQ_BIT_EXIT to cancel it if the workqueue is already on its way out.
That must be ordered. task_work_add() has a full barrier via cmpxchg(). But io_wq_exit_start() sets the bit with set_bit() which doesn't have any memory ordering.
So afaict, on weakly ordered architectures the exiting task may load task_works before the store of the bit is visible. The other side tests the bit before the store is visible as well. So the entry remains queued with worker_refs and the exiting task waits on worker_done indefinitely.
If the task still has rings then io_uring_del_tctx_node() provides the barrier via test_and_set_bit() in io_wq_set_exit_on_idle(). When it has closed all rings though that barrier is gone.
Add the barrier after the set_bit().
--- io_uring/io-wq.c | 2 ++ 1 file changed, 2 insertions(+)
io_uring/io-wq.c +2 -0
@@ -1234,6 +1234,8 @@ static bool io_task_work_match(struct cavoid io_wq_exit_start (struct io_wq *wq) {set_bit (IO_WQ_BIT_EXIT , &wq->state); +/* Pairs with task_work_add() in io_queue_worker_create(). */ +smp_mb__after_atomic (); }static void io_wq_cancel_tw_create (struct io_wq *wq)
Greg Kroah-Hartman
maintainerPATCH 193/247 io_uring/waitid: own the request before clearing ->head
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit c254eec4364b9f4b4cbdce43be3fb4df5a651a70 upstream.
io_waitid_remove_wq() only takes the wait queue lock if ->head is set. io_waitid_wait() clears ->head first thing, before it tries to become the owner of the request by bumping ->refs. If somebody else owns the request at that point, nothing keeps it from completing the request while the wake up handler is still going to touch it:
CPU0 (io_waitid_wait) CPU1 (io_waitid, holds a ref)list_del_init(&wait->entry)smp_store_release(&iw->head, NULL)
__do_wait() finds another child
io_waitid_remove_wq()
// ->head == NULL, no locking
io_waitid_finish(), IOU_COMPLETE
// request freed and reusedatomic_fetch_inc(&iw->refs)
The same goes for __io_waitid_cancel() if it claims the request in that window. ->refs is part of the per opcode data of the request, so this increments whatever the next user of the request keeps there. If that happens to be zero, the handler concludes that it owns the request, and queues io_waitid_cb() for it. With the window held open by a delay, and the request reused for a receive that is waiting for data:
BUG: KASAN: slab-use-after-free in __wake_up_common+0x1ca/0x1f0 __wake_up_sync_key+0x36/0x50 sock_def_readable+0xf1/0x420 unix_stream_sendmsg+0x60b/0x1110 Allocated by task 87: io_arm_apoll+0x1ed/0x940 Freed by task 87: __io_submit_flush_completions+0x118d/0x1a10 tctx_task_work_run+0x327/0x950
Only clear ->head once the handler owns the request. If it doesn't, the owner finds ->head set and has to wait for the lock, which is held by the caller of the handler. Deleting the already deleted entry again is harmless.
--- io_uring/waitid.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
io_uring/waitid.c +8 -2
@@ -291,12 +291,18 @@ static int io_waitid_wait(struct wait_qureturn 0 ;list_del_init (&wait->entry); -smp_store_release (&iw->head,NULL ); -/* cancel is in progress */ +/* +* Cancel or issue is in progress. Leave ->head alone, so that whoever +* owns the request has to take the wait queue lock, which we hold, +* before it can complete and free it. +*/ if (atomic_fetch_inc (&iw->refs) &IO_WAITID_REF_MASK )return 1 ; +/* pairs with the smp_load_acquire() in io_waitid_remove_wq() */ +smp_store_release (&iw->head,NULL ); + req->io_task_work.func = io_waitid_cb;__io_req_task_work_add (req,IOU_F_TWQ_IN_WAKE );return 1 ;
Greg Kroah-Hartman
maintainerPATCH 194/247 io_uring/cmd: dont leave list poison in ->hash_node
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 4c83e39f4d1944d7146fd06094f2c8053238d55c upstream.
io_uring_cmd_del_cancelable() uses hlist_del() to take a command off ->cancelable_uring_cmd, which leaves LIST_POISON1/2 behind in ->hash_node. Requests are recycled through the request cache without being reinitialised, and not every user of ->hash_node sets it up before it is used:
If a vectored futex wait is woken while futex_wait_multiple_setup() is still queueing the futexes, io_futexv_wait() doesn't add the request to ->futex_list, and leaves the completion to the task_work queued by the wake up. io_futexv_complete() ends in __io_futex_complete(), whose hlist_del_init() is fine for a request that is unhashed, which is how all other users of the node leave it. If the request was a cancelable uring_cmd in its previous life, e.g. a ublk FETCH_REQ, it writes through LIST_POISON2:
Oops: general protection fault, probably for non-canonical address KASAN: maybe wild-memory-access in range [0xdead000000000120-...] RIP: 0010:io_futexv_complete+0x219/0x420 Call Trace: tctx_task_work_run+0x804/0x950 tctx_task_work+0x71/0xa0 task_work_run+0x118/0x200
Leave the node unhashed.
--- io_uring/uring_cmd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
io_uring/uring_cmd.c +1 -1
@@ -85,7 +85,7 @@ static void io_uring_cmd_del_cancelable( cmd->flags &= ~IORING_URING_CMD_CANCELABLE ;io_ring_submit_lock (ctx, issue_flags); -hlist_del (&req->hash_node); +hlist_del_init (&req->hash_node);io_ring_submit_unlock (ctx, issue_flags); }
Greg Kroah-Hartman
maintainerPATCH 195/247 io_uring/wait: dont spin on a stuck overflow list
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 34f5a664c34d3cb62f6bec7f4156754594a7d25b upstream.
As long as IO_CHECK_CQ_OVERFLOW_BIT is set, io_cqring_wait_schedule() returns right away, before it gets to look at signals or arms the timeout, for io_cqring_wait() to flush the overflow list. If that doesn't empty the list, and the CQ ring doesn't hold the number of events the caller wants, the loop starts over, with the same result. The task spins in the kernel, and can't be killed.
The assumption is that this can't happen: if CQEs can't be flushed, the ring is full, and min_events is capped to the size of the ring. But:
- With IORING_SETUP_CQE_MIXED a 32b CQE needs two contiguous entries. It is stuck on the list if a single one is free, and then the ring holds less than cq_entries events. A single threaded application that asks for as many events as the ring has entries never gets out of io_uring_enter().
- Whether the ring is full is up to the CQ head, which the application can write to. While one thread waits for events on an empty ring, another one can move the head back so that the ring looks full and have a CQE overflow. The waiter can't be stopped any more, not even by SIGKILL.
Only the application can make room in the CQ ring. Return to it if the list could not be flushed.
--- io_uring/io_uring.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
io_uring/io_uring.c +11 -2
@@ -2608,9 +2608,18 @@ static int io_cqring_wait(struct io_ring check_cq =READ_ONCE (ctx->check_cq);if (unlikely (check_cq)) { -/* let the caller flush overflows, retry */ -if (check_cq &BIT (IO_CHECK_CQ_OVERFLOW_BIT )) +if (check_cq &BIT (IO_CHECK_CQ_OVERFLOW_BIT )) {io_cqring_do_overflow_flush (ctx); +/* +* No room for what has overflown. It takes the +* application to change that, so return to it. +*/ +if (test_bit (IO_CHECK_CQ_OVERFLOW_BIT , + &ctx->check_cq)) { + ret =0 ; +break ; + } + }if (check_cq &BIT (IO_CHECK_CQ_DROPPED_BIT )) { ret = -EBADR ;break ;
Greg Kroah-Hartman
maintainerPATCH 196/247 io_uring/io-wq: dont lose the signal that ends work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 63c103279a95e82280092f2f4232e91e8117a252 upstream.
When a thread exits, only its tracked requests are cancelled. Then its io-wq is torn down. io_wq_exit_workers() signals every worker, to get it out of an interruptible sleep, and waits for all of them to exit. Before they do, they go through the work that is left. Unbounded work is cancelled. Bounded work is run, as it is expected to end by itself.
Not all of it does. An open has no file yet, so it counts as bounded, and the open of a FIFO waits for the other end. That is what the signal is for. But the workers are signalled once, and a worker that hasn't started the work by then loses the signal:
io_wq_exit_workers() io_worker_handle_work()
io_wq_worker_wake()
set TIF_NOTIFY_SIGNAL
io_assign_current_work()
io_run_task_work()
clear TIF_NOTIFY_SIGNAL
io_wq_submit_work()
fifo_open()
wait_for_partner()
wait_for_completion_timeout()The thread never gets out of do_exit():
IORING_OP_OPENAT of a FIFO without a writer, IOSQE_ASYNC exit of the thread that has submitted it
hangs in more than 9 of 10 attempts (4 CPUs, KVM), until the process is killed.
Set TIF_NOTIFY_SIGNAL for bounded work that is started with IO_WQ_BIT_EXIT set. The bit is set before the workers are signalled, and it is tested after the flag has been cleared, with clear_notify_signal() providing the barrier. So either the flag stays, or the bit is seen.
Work that is started while the io-wq exits is treated like work that is being run at that time: it isn't interrupted unless it waits interruptibly.
--- io_uring/io-wq.c | 7 +++++++ 1 file changed, 7 insertions(+)
io_uring/io-wq.c +7 -0
@@ -598,9 +598,16 @@ static void io_worker_handle_work(struct next_hashed =wq_next_work (work); +/* +* io_wq_exit_workers() signals us once, so that we +* don't sleep for ever. If that was before this work +* became the current one, the signal is gone. +*/ if (do_kill && (atomic_read (&work->flags) &IO_WQ_WORK_UNBOUND ))atomic_or (IO_WQ_WORK_CANCEL , &work->flags); +else if (do_kill) +set_notify_signal (current); wq->do_work (work);io_assign_current_work (worker,NULL );
Greg Kroah-Hartman
maintainerPATCH 197/247 io_uring/io-wq: dont hide a link from cancellations
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 436d48a2ed13112d2d27085325838e5bce6b4507 upstream.
A task that exits cancels its tracked requests and waits until they are gone. io_uring_cancel_generic() looks everywhere a request can be, and goes to sleep if it found nothing to cancel. It is woken up each time one of the requests of the task is completed by task work or freed.
When io-wq is done with a request that has a link, there is a time in which the next request of the link can't be found:
io_worker_handle_work()
io_assign_current_work(worker, NULL)
io_wq_free_work(work)
io_req_find_next() // takes the link off the request
io_free_req() // task work for the task
io_assign_current_work(worker, linked)
io_run_task_work()
cond_resched()
worker->cur_work = linked
It is not pending, it is not the current work of a worker, and it is not yet on the list that it is about to be parked on. If the pass that the exiting task makes because of io_free_req() falls into that time, it finds nothing and the task goes to sleep. The worker then runs the link, which IO_WQ_BIT_EXIT doesn't prevent for bounded work. If that parks the request nothing is completed or freed, and nobody wakes up the task. If it is the process that exits it can't be killed any more either.
NOP, IOSQE_ASYNC | IOSQE_IO_LINK
FUTEX_WAIT, FUTEX2_PRIVATE
exit of the thread, or of the process, up to 63us later
With four of these per round 5 to 8 of 10,000 rounds hang (4 CPUs, KVM):
io_uring_cancel_generic
do_exit
Commit f8b632e89a10 ("io_uring: tighten task exit cancellations") is about the same gap, and makes the task look again for whatever happens before io_free_req().
Free the request once the link is the current work of the worker, or pending. Whoever is woken up by that can find the link, until it is parked where cancellations look as well. To do so split io_wq_free_work() in two.
[ 6.12: io-wq still calls back through io_wq_data, so a ->put_work callback
is added next to ->free_work. io_wq_put_work() keeps the link check of 6.12, without the REQ_F_CQE_SKIP condition that commit 5530a5102e3c adds in 7.3 ]
--- io_uring/io-wq.c | 22 ++++++++++++++++++---- io_uring/io-wq.h | 4 +++- io_uring/io_uring.c | 29 +++++++++++++++++++++-------- io_uring/io_uring.h | 3 ++- io_uring/tctx.c | 1 + 5 files changed, 45 insertions(+), 14 deletions(-)
io_uring/io-wq.c +18 -4
@@ -98,6 +98,7 @@ enum {struct io_wq {unsigned long state; +put_work_fn *put_work;free_work_fn *free_work;io_wq_work_fn *do_work;
@@ -593,8 +594,9 @@ static void io_worker_handle_work(struct/* handle a whole dependent link */ do { bool do_kill = test_bit(IO_WQ_BIT_EXIT, &wq->state); - struct io_wq_work *next_hashed, *linked; + struct io_wq_work *next_hashed, *linked, *done = work; unsigned int hash = io_get_work_hash(work); + bool last; next_hashed = wq_next_work(work);
@@ -611,7 +613,7 @@ static void io_worker_handle_work(struct wq->do_work (work);io_assign_current_work (worker,NULL ); - linked = wq->free_work (work); + last = wq->put_work (work, &linked); work = next_hashed;if (!work && linked && !io_wq_is_hashed (linked)) { work = linked;
@@ -620,6 +622,13 @@ static void io_worker_handle_work(structio_assign_current_work (worker, work);if (linked)io_wq_enqueue (wq, linked); +/* +* Not before the link is current or pending work again. +* This may be the last time that a task is woken up +* which exits and looks for requests to cancel. +*/ +if (last) + wq->free_work (done);if (hash !=-1U && !next_hashed) {/* serialize hash clear with wake_up() */
@@ -920,9 +929,13 @@ static bool io_wq_worker_wake(struct io_static void io_run_cancel (struct io_wq_work *work,struct io_wq *wq) {do { +struct io_wq_work *linked; +atomic_or (IO_WQ_WORK_CANCEL , &work->flags); wq->do_work (work); - work = wq->free_work (work); +if (wq->put_work (work, &linked)) + wq->free_work (work); + work = linked; }while (work); }
@@ -1174,7 +1187,7 @@ struct io_wq *io_wq_create(unsigned bounint ret, i;struct io_wq *wq; -if (WARN_ON_ONCE (!data->free_work || !data->do_work)) +if (WARN_ON_ONCE (!data->put_work || !data->free_work || !data->do_work))return ERR_PTR (-EINVAL );if (WARN_ON_ONCE (!bounded))return ERR_PTR (-EINVAL );
@@ -1185,6 +1198,7 @@ struct io_wq *io_wq_create(unsigned bounrefcount_inc (&data->hash->refs); wq->hash = data->hash; + wq->put_work = data->put_work; wq->free_work = data->free_work; wq->do_work = data->do_work;
io_uring/io-wq.h +3 -1
@@ -21,7 +21,8 @@ enum io_wq_cancel { IO_WQ_CANCEL_NOTFOUND, /* work not found */ }; -typedef struct io_wq_work *(free_work_fn )(struct io_wq_work *); +typedef bool (put_work_fn )(struct io_wq_work *,struct io_wq_work **); +typedef void (free_work_fn )(struct io_wq_work *);typedef void (io_wq_work_fn )(struct io_wq_work *);struct io_wq_hash {
@@ -40,6 +41,7 @@ struct io_wq_data {struct io_wq_hash *hash;struct task_struct *task;io_wq_work_fn *do_work; +put_work_fn *put_work;free_work_fn *free_work; };
io_uring/io_uring.c +21 -8
@@ -1770,17 +1770,30 @@ int io_poll_issue(struct io_kiocb *req, IO_URING_F_COMPLETE_DEFER); } -struct io_wq_work *io_wq_free_work (struct io_wq_work *work) +/* +* io-wq is done with @work. Returns true if it held the last reference, and +* hands out the next request of the link then. The caller has to make sure +* that cancellations can find the latter before it calls io_wq_free_work(). +*/ +bool io_wq_put_work (struct io_wq_work *work,struct io_wq_work **linked) { struct io_kiocb *req = container_of(work, struct io_kiocb, work);struct io_kiocb *nxt =NULL ; -if (req_ref_put_and_test_atomic (req)) { -if (req->flags &IO_REQ_LINK_FLAGS ) - nxt =io_req_find_next (req); -io_free_req (req); - } -return nxt ? &nxt->work :NULL ; + *linked =NULL ; +if (!req_ref_put_and_test_atomic (req)) +return false; + +if (req->flags &IO_REQ_LINK_FLAGS ) + nxt =io_req_find_next (req); +if (nxt) + *linked = &nxt->work; +return true; +} + +void io_wq_free_work (struct io_wq_work *work) +{ +io_free_req (container_of(work ,struct io_kiocb ,work )); }void io_wq_submit_work (struct io_wq_work *work)
@@ -1791,7 +1804,7 @@ void io_wq_submit_work(struct io_wq_workbool needs_poll = false;int ret =0 , err = -ECANCELED ; -/* one will be dropped by ->io_wq_free_work() after returning to io-wq */ +/* one will be dropped by ->put_work() after returning to io-wq */ if (!(req->flags &REQ_F_REFCOUNT ))__io_req_set_refcount (req,2 );else
io_uring/io_uring.h +2 -1
@@ -101,7 +101,8 @@ int io_submit_sqes(struct io_ring_ctx *cint io_do_iopoll (struct io_ring_ctx *ctx,bool force_nonspin);void __io_submit_flush_completions (struct io_ring_ctx *ctx); -struct io_wq_work *io_wq_free_work (struct io_wq_work *work); +bool io_wq_put_work (struct io_wq_work *work,struct io_wq_work **linked); +void io_wq_free_work (struct io_wq_work *work);void io_wq_submit_work (struct io_wq_work *work);void io_free_req (struct io_kiocb *req);
io_uring/tctx.c +1 -0
@@ -35,6 +35,7 @@ static struct io_wq *io_init_wq_offload( data.hash = hash; data.task = task; + data.put_work = io_wq_put_work; data.free_work = io_wq_free_work; data.do_work = io_wq_submit_work;
Greg Kroah-Hartman
maintainerPATCH 198/247 io_uring: dont flood a cancelling task with task_work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 22e643e61b9b6299b42ff7d88bab48bccada8a5d upstream.
io_ring_exit_work() asks each task which has used the ring to remove its tctx node, by task_work, and repeats that until the list is empty. io_tctx_exit_cb() doesn't touch the node while the task is in io_uring_cancel_generic(), which removes all the nodes at its end. So the work item queues the callback again as soon as it has completed, for nothing.
That is more than a waste of time. task_work_run() only returns when it finds the list empty. If the rings are released from inside the cancellation, because requests of other rings held the last references to their files, up to 64 work items keep sending callbacks to the one task which is running them. It never finds the list empty, never gets back to the cancellation, the nodes stay, and so it goes on: a task with 60 pairs of rings which poll each other ran 280000 callbacks in 5 seconds, 20 seconds after exit_group(). It ends when all the senders happen to be late at the same time. Until then the task keeps a CPU and the work items busy.
An exiting task can't be killed meanwhile. execve() cancels the requests in the same way, so a live task can get stuck there as well, for minutes. If it takes more than five, the work items run into the WARN_ON_ONCE(time_after(jiffies, timeout)) of io_ring_exit_work(). No privilege is needed for any of this.
If the callback has met a task in cancellation, wait a little before it is sent again. Nobody has to wake the work item up for that: either the node is gone by then, or it is the turn of the next round.
--- io_uring/io_uring.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
io_uring/io_uring.c +11 -1
@@ -2873,6 +2873,7 @@ struct io_tctx_exit {struct callback_head task_work;struct completion completion;struct io_ring_ctx *ctx; +bool in_cancel; };static __cold void io_tctx_exit_cb (struct callback_head *cb)
@@ -2887,7 +2888,8 @@ static __cold void io_tctx_exit_cb(struc* tctx can be NULL if the queueing of this task_work raced with * work cancelation off the exec path. */ -if (tctx && !atomic_read (&tctx->in_cancel)) + work->in_cancel = tctx &&atomic_read (&tctx->in_cancel); +if (tctx && !work->in_cancel)io_uring_del_tctx_node ((unsigned long )work->ctx);complete (&work->completion); }
@@ -2981,6 +2983,14 @@ static __cold void io_ring_exit_work(str* wait is marked as interruptible. */ wait_for_completion_interruptible (&exit.completion); +/* +* The task removes the node when it is done with its +* cancellation. Give it the time for that: it doesn't get back +* to it as long as it finds new task_work each time it has run +* the old one, and we may be one of many who send it. +*/ +if (exit.in_cancel) +schedule_timeout_idle (HZ /20 );mutex_lock (&ctx->uring_lock); }mutex_unlock (&ctx->uring_lock);
Greg Kroah-Hartman
maintainerPATCH 199/247 io_uring/io-wq: dont strand work when a worker exits
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit ad41f325be1271b22d99353819c90f0d5e45acc8 upstream.
A worker exits if its idle timeout fired and it isn't the last one, if its affinity was changed, or if the wq is marked exit-on-idle. It decides so after it found the work list empty, and until io_worker_exit() is through it stays on the free list and in ->nr_running:
worker io_wq_enqueue()io_acct_run_queue() == false
queues work
io_acct_activate_free_worker()
wake_up_process(worker)
// found one, nothing to createacct->nr_workers--
breakio_worker_exit()
Nobody is going to look at the work. If other workers exist, it has to wait until one of them finishes what it is blocked on or hits its idle timeout. If not, which is possible for the affinity and the exit-on-idle case, it sits there until something else is queued. For exit-on-idle it takes a task that closes its last ring and sets up a new one while the workers are on their way out.
Make the worker take itself off the free list when it gives up its ->nr_workers slot, then leave ->nr_running, and only then take the final look at the work list. That look and queueing work are both done under acct->lock, so either the worker sees the work and stays, or the enqueue side sees that the worker is gone and wakes or creates another one. If it wants to stay and finds that its slot has been taken, a worker has been created in its place, which is going to look at the work list, and it can leave after all.
[ 6.12: ->nr_workers and the free list are under wq->lock, there is no
acct->workers_lock ]
--- io_uring/io-wq.c | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-)
io_uring/io-wq.c +37 -1
@@ -647,6 +647,37 @@ static void io_worker_handle_work(struct }while (1 ); } +/* +* The worker has decided to exit, and has given up its ->nr_workers slot and +* its place on the free list. io_wq_enqueue() may have picked it from that +* list, or seen it running, after it last looked at the work list. Leave +* ->nr_running as well and check again. Returns false if the worker has to +* stay. +*/ +static bool io_worker_retire (struct io_wq_acct *acct,struct io_worker *worker) +{ +struct io_wq *wq = worker->wq; + +/* turns io_wq_dec_running() and the scheduler hooks into no-ops */ +clear_bit (IO_WORKER_F_UP , &worker->flags); +atomic_dec (&acct->nr_running); +if (!io_acct_run_queue (acct)) +return true; +raw_spin_unlock (&acct->lock); + +raw_spin_lock (&wq->lock); +if (acct->nr_workers >= acct->max_workers) { +/* a worker was created in our place, the work is its business */ +raw_spin_unlock (&wq->lock); +return true; + } + acct->nr_workers++; +raw_spin_unlock (&wq->lock); +atomic_inc (&acct->nr_running); +set_bit (IO_WORKER_F_UP , &worker->flags); +return false; +} +static int io_wq_worker (void *data) {struct io_worker *worker = data;
@@ -680,9 +711,14 @@ static int io_wq_worker(void *data)*/ if (last_timeout && (exit_mask || acct->nr_workers >1 )) { acct->nr_workers--; +if (test_and_clear_bit (IO_WORKER_F_FREE , &worker->flags)) +hlist_nulls_del_init_rcu (&worker->nulls_node);raw_spin_unlock (&wq->lock);__set_current_state (TASK_RUNNING ); -break ; +if (io_worker_retire (acct, worker)) +break ; + last_timeout = false; +continue ; } last_timeout = false;__io_worker_idle (wq, worker);
Greg Kroah-Hartman
maintainerPATCH 200/247 io_uring/io-wq: dont exit with a creation pending
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit e231d2e8f80d3649ecd3851b7f2abdfbe606c04b upstream.
A worker that is the last one to go to sleep while work is pending asks for another worker. io_wq_dec_running() bumps ->nr_running on behalf of the new worker and queues create_worker_cb() as task_work for the owner of the io-wq. Until that has run, everybody else takes it that a worker is running which is going to look after the work list: io_wq_enqueue() doesn't create one, and other workers that go to sleep don't find themselves to be the last.
If the worker that made the request exits, io_worker_exit() cancels the task_work, and io_worker_cancel_cb() drops ->nr_running without a look at the work list:
worker A worker B io_wq_enqueue()
blocks, work is pending
nr_running++
queues create_worker_cb()
wakes, handles the work
idle timeout, decides to exit
picks up work 1
queues work 2 B is on the free list
still: wakes B
work 1 blocks
nr_running 2 -> 1io_worker_exit()
io_worker_cancel_cb()
nr_running 1 -> 0
Work 2 has to wait for work 1, although there is room for more workers. It takes an owner that doesn't get around to run its task_work for the time of the idle timeout, less if the worker exits because its affinity was changed or the io-wq is marked exit-on-idle.
Let the worker stay around until its request has been dealt with. Only the worker itself sets ->create_state, so it can't be set behind its back once it has decided to leave.
--- io_uring/io-wq.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
io_uring/io-wq.c +5 -1
@@ -708,8 +708,12 @@ static int io_wq_worker(void *data)/* * Last sleep timed out. Exit if we're not the last worker, * or if someone modified our affinity. +* Not as long as a request of ours for another worker is +* pending, though. It is accounted as a running worker, which +* others rely on, and io_worker_exit() would cancel it. */ -if (last_timeout && (exit_mask || acct->nr_workers >1 )) { +if (last_timeout && (exit_mask || acct->nr_workers >1 ) && + !test_bit (0 , &worker->create_state)) { acct->nr_workers--;if (test_and_clear_bit (IO_WORKER_F_FREE , &worker->flags))hlist_nulls_del_init_rcu (&worker->nulls_node);
Greg Kroah-Hartman
maintainerPATCH 201/247 io_uring/io-wq: let cancel find picked up hashed work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit e9efeb4fc97b0879512a3c3b995ed448f2487e12 upstream.
io_get_next_work() takes all the work items that share a hash off the work list in one go, and the worker runs them one after the other. Only the one it is working on is visible as ->cur_work. The others are neither on the list nor current, so io_wq_cancel_cb() can't find them.
IORING_OP_ASYNC_CANCEL and IORING_REGISTER_SYNC_CANCEL return -ENOENT for a request that has not even been started, e.g. a buffered write queued behind another write to the same file that is blocked, and the request is carried out. The cancellation done for a task or ring that goes away gets there in the end, as it keeps trying, but it has to wait for each item to become current.
Keep a pointer to the remainder of the chain next to ->cur_work, and have io_wq_worker_cancel() look at it. The items on it belong to the worker, which needs ->lock to move on to the next one. Matching work is flagged with IO_WQ_WORK_CANCEL and fails with -ECANCELED when its turn comes. The worker isn't signalled for it, that would interrupt the unrelated work it is busy with. As the request isn't gone yet, it is reported like running work, with -EALREADY.
--- io_uring/io-wq.c | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-)
io_uring/io-wq.c +29 -6
@@ -54,6 +54,8 @@ struct io_worker {struct io_wq *wq;struct io_wq_work *cur_work; +/* rest of the hashed chain ->cur_work was taken off the list with */ +struct io_wq_work *next_work;raw_spinlock_t lock;struct completion ref_done;
@@ -535,6 +537,17 @@ static struct io_wq_work *io_get_next_woreturn NULL ; } +static void __io_assign_current_work (struct io_worker *worker, +struct io_wq_work *work) +{ +raw_spin_lock (&worker->lock); + worker->cur_work = work; +/* stays valid while in between two items of a chain */ +if (work) + worker->next_work =wq_next_work (work); +raw_spin_unlock (&worker->lock); +} +static void io_assign_current_work (struct io_worker *worker,struct io_wq_work *work) {
@@ -543,9 +556,7 @@ static void io_assign_current_work(struccond_resched (); } -raw_spin_lock (&worker->lock); - worker->cur_work = work; -raw_spin_unlock (&worker->lock); +__io_assign_current_work (worker, work); }/*
@@ -576,9 +587,7 @@ static void io_worker_handle_work(struct* work list, but isn't yet discoverable as the * current work item for this worker. */ -raw_spin_lock (&worker->lock); - worker->cur_work = work; -raw_spin_unlock (&worker->lock); +__io_assign_current_work (worker, work); }raw_spin_unlock (&acct->lock);
@@ -1083,6 +1092,7 @@ static bool __io_wq_worker_cancel(structstatic bool io_wq_worker_cancel (struct io_worker *worker,void *data) {struct io_cb_cancel_data *match = data; +struct io_wq_work *work;/* * Hold the lock to avoid ->cur_work going out of scope, caller
@@ -1091,6 +1101,19 @@ static bool io_wq_worker_cancel(struct iraw_spin_lock (&worker->lock);if (__io_wq_worker_cancel (worker, match, worker->cur_work)) match->nr_running++; +/* +* Hashed work is taken off the work list a chain at a time, what the +* worker hasn't started yet can only be found here. It doesn't move on +* without the lock. Just mark the work, it fails once it is its turn. +*/ +for (work = worker->next_work; work; work =wq_next_work (work)) { +if (match->nr_running && !match->cancel_all) +break ; +if (match->fn (work, match->data)) { +atomic_or (IO_WQ_WORK_CANCEL , &work->flags); + match->nr_running++; + } + }raw_spin_unlock (&worker->lock);return match->nr_running && !match->cancel_all;
Greg Kroah-Hartman
maintainerPATCH 202/247 io_uring/poll: dont lose a cancel as io-wq arms poll
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 6d2d4c2530e95ff6ddeb98195d49d99dbca14369 upstream.
A request on a pollable file that was forced to io-wq is issued without blocking there. If that ends in -EAGAIN, io_wq_submit_work() arms poll for it and returns. It looks at IO_WQ_WORK_CANCEL once, before it issues the request.
Somebody who wants to cancel the request in between finds it running:
io-wq worker io_try_cancel()
io_wq_submit_work()
IO_WQ_WORK_CANCEL isn't set
io_issue_sqe() = -EAGAIN
io_async_cancel_one()
sets IO_WQ_WORK_CANCEL signals the worker = -EALREADY
io_poll_cancel() = -ENOENT
...
= -ENOENT
io_arm_poll_handler() = IO_APOLL_OK
return
Nobody looks at the flag again, and the signal doesn't matter to a worker that doesn't sleep. The request is armed as if nothing had happened:
- a linked timeout completes with -ENOENT, and the request it was meant to limit waits for as long as it takes.
- IORING_OP_ASYNC_CANCEL returns -EALREADY, and the request stays.
- IORING_REGISTER_SYNC_CANCEL waits for the request to complete if it gets -EALREADY. Since commit 5623eb1ed035 ("io_uring/tctx: add separate lock for list of tctx's in ctx") it doesn't sleep but spins, so its next attempt finds the armed poll.
The same goes for a multishot poll, recv or accept that is armed from io-wq.
With a read of an empty pipe, IOSQE_ASYNC, and a linked timeout of 5ms or a cancel in the same submission, in a guest that is slow enough (TCG, KASAN), the request is lost in 21 of 24 rounds of 40 or 100 attempts.
While it arms poll from io-wq, __io_arm_poll_handler() owns the request. Look at the flag once the request is in the hash table. The table is searched and the request is added with ->uring_lock held, and the flag is set before the search. So either the search finds the request, or it came first and the flag is seen. With the request marked as cancelled, the task work that is queued, right away or because ownership can't be released, fails it with -ECANCELED.
What the canceller is told doesn't change. In this window a linked timeout still completes with -ENOENT rather than -ETIME, a cancel request with -EALREADY, and one with IORING_ASYNC_CANCEL_ALL or _ANY with a count that doesn't include the request. But the request is cancelled, so what is new is a request that completes with -ECANCELED after such a result.
This doesn't help in two cases:
- IORING_ASYNC_CANCEL_ALL and _ANY, if the work is flagged after the test added here, while io-wq still has it as the current work of the worker. io_cancel_cb() stamps it with the sequence of the cancel, so the search of the hash table on behalf of the same cancel takes it for done and skips it.
- requests that are parked elsewhere by io-wq, like IORING_OP_FUTEX_WAIT and IORING_OP_WAITID. They have the same problem.
--- io_uring/poll.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
io_uring/poll.c +12 -0
@@ -656,6 +656,18 @@ static int __io_arm_poll_handler(structio_poll_add_hash (req); +/* +* Whoever tried to cancel the request while io-wq was running it has +* flagged the work item. If it searched the hash table before the +* request got there it found nothing, and it won't come back. Both +* the search and the insertion are done with ->uring_lock held, and +* the flag is set before the search. If the search came first, +* the flag is visible by now. +*/ +if (ipt->owning && + (atomic_read (&req->work.flags) &IO_WQ_WORK_CANCEL )) +io_poll_mark_cancelled (req); +if (mask && (poll->events &EPOLLET ) &&io_poll_can_finish_inline (req, ipt)) {__io_poll_execute (req, mask,0 );
Greg Kroah-Hartman
maintainerPATCH 203/247 io_uring: dont lose a cancel as io-wq parks a request
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 5cb049d2203d7a81a1c1a737c8df4575e71078e3 upstream.
IORING_OP_FUTEX_WAIT, IORING_OP_FUTEX_WAITV and IORING_OP_WAITID don't block. They put the request on a list of the ring, where a wake up or a cancellation finds it, and return IOU_ISSUE_SKIP_COMPLETE. They do so as well if they are run by io-wq, e.g. because of IOSQE_ASYNC.
io_wq_submit_work() looks at IO_WQ_WORK_CANCEL once, before it issues the request. Somebody who wants to cancel the request after that, and before it is on the list, finds it running:
io-wq worker io_try_cancel()
io_wq_submit_work()
IO_WQ_WORK_CANCEL isn't set
io_async_cancel_one()
sets IO_WQ_WORK_CANCEL
signals the worker
= -EALREADY
...
io_futex_cancel() = -ENOENT
...
io_futex_wait()
adds the request to ->futex_list
= IOU_ISSUE_SKIP_COMPLETENobody looks at the flag again. IORING_OP_ASYNC_CANCEL returns -EALREADY and the request stays.
It is the problem that "io_uring/poll: don't lose a cancel as io-wq arms poll" deals with for poll.
Look at the flag once the request is on the list, and cancel it if it is set. The lists are searched and the requests are added with ->uring_lock held, and the flag is set before the search. So either the search finds the request, or it came first and the flag is seen.
What the canceller is told doesn't change, see the other patch, also for IORING_ASYNC_CANCEL_ALL and _ANY.
[ 6.12: __io_futex_cancel() and __io_waitid_cancel() take the ctx as well.
futex_wait_setup() returns with the hash bucket locked and the futex_q not queued yet, so io_futex_wait() queues it before the check, with ->uring_lock still held ]
--- io_uring/futex.c | 7 +++++-- io_uring/io_uring.h | 17 +++++++++++++++++ io_uring/waitid.c | 2 ++ 3 files changed, 24 insertions(+), 2 deletions(-)
io_uring/futex.c +5 -2
@@ -307,6 +307,8 @@ int io_futexv_wait(struct io_kiocb *req,*/ __set_current_state (TASK_RUNNING );hlist_add_head (&req->hash_node, &ctx->futex_list); +if (io_wq_cancel_seen (req, issue_flags)) +__io_futex_cancel (ctx, req); }else { iof->futexv_unqueued =1 ;if (woken !=-1 )
@@ -348,9 +350,10 @@ int io_futex_wait(struct io_kiocb *req, &ifd->q, &hb);if (!ret) {hlist_add_head (&req->hash_node, &ctx->futex_list); -io_ring_submit_unlock (ctx, issue_flags); -futex_queue (&ifd->q, hb,NULL ); +if (io_wq_cancel_seen (req, issue_flags)) +__io_futex_cancel (ctx, req); +io_ring_submit_unlock (ctx, issue_flags);return IOU_ISSUE_SKIP_COMPLETE ; }
io_uring/io_uring.h +17 -0
@@ -251,6 +251,23 @@ static inline void io_ring_submit_lock(slockdep_assert_held (&ctx->uring_lock); } +/* +* For a handler that is run by io-wq and parks the request on a list where +* cancellations find it, rather than completing it. Whoever tried to cancel +* the request before that found it running. It has flagged the work item, +* has searched the list in vain, and won't come back. To be called with +* ->uring_lock held, which the search needs as well, once the request is on +* the list: if the search came first, the flag is visible. +*/ +static inline bool io_wq_cancel_seen (struct io_kiocb *req, +unsigned int issue_flags) +{ +lockdep_assert_held (&req->ctx->uring_lock); + +return (issue_flags &IO_URING_F_IOWQ ) && + (atomic_read (&req->work.flags) &IO_WQ_WORK_CANCEL ); +} +static inline void io_commit_cqring (struct io_ring_ctx *ctx) {/* order cqe stores with ring update */
io_uring/waitid.c +2 -0
@@ -375,6 +375,8 @@ int io_waitid(struct io_kiocb *req, unsi* a waitqueue callback, or if someone cancels it. */ if (!io_waitid_drop_issue_ref (req)) { +if (io_wq_cancel_seen (req, issue_flags)) +__io_waitid_cancel (ctx, req, true);io_ring_submit_unlock (ctx, issue_flags);return IOU_ISSUE_SKIP_COMPLETE ; }
Greg Kroah-Hartman
maintainerPATCH 204/247 io_uring/cancel: dont forget that the work was running
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 8aa0e5db4845fb5ac11abe40d7b1cac0656c3ee3 upstream.
If the request to be cancelled is being run by io-wq, io_async_cancel_one() flags the work, signals the worker and returns -EALREADY. Since commit ccbf726171b7 ("io_uring: perform poll removal even if async work removal is successful") io_try_cancel() goes on regardless, as poll may be armed for the request. If it isn't, and nothing else turns up, the result is the -ENOENT of the last search.
__io_async_cancel() makes up for that. On -ENOENT it tries the io-wq of every task that uses the ring, and that of the caller is one of them. So the work is found a second time, and the result is -EALREADY after all.
Unless the worker is done with it by then. If the work is flagged before io_wq_submit_work() looks at IO_WQ_WORK_CANCEL, all the worker does is to queue the request to be failed by task work. Then it isn't anywhere to be found until the task work has run, and
- IORING_REGISTER_SYNC_CANCEL returns -ENOENT,
- IORING_OP_ASYNC_CANCEL completes with -ENOENT,
for a request that they have just cancelled, and that completes with -ECANCELED.
With a read of an empty pipe, IOSQE_ASYNC, and a sync cancel right behind it, 1 to 3 of 1,000,000 calls return -ENOENT, and 50 to 110 with IORING_SETUP_DEFER_TASKRUN (4 CPUs, KVM). Nothing is written to the pipe, and all of these reads end with -ECANCELED.
Remember that the work was found. IORING_OP_ASYNC_CANCEL completes with -EALREADY, as it does if the worker is a bit slower. For IORING_REGISTER_SYNC_CANCEL it means to try again, which ends with 0.
The result of a linked timeout, which calls io_try_cancel() by itself, and the number that is returned for IORING_ASYNC_CANCEL_ALL and _ANY don't change.
--- io_uring/cancel.c | 13 ++++++++++++- io_uring/cancel.h | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-)
io_uring/cancel.c +12 -1
@@ -115,6 +115,8 @@ int io_try_cancel(struct io_uring_task **/ if (!ret)return 0 ; +if (ret == -EALREADY ) + cd->running = true; ret =io_poll_cancel (ctx, cd, issue_flags);if (ret != -ENOENT )
@@ -171,6 +173,7 @@ static int __io_async_cancel(struct io_cstruct io_tctx_node *node;int ret, nr =0 ; + cd->running = false; do { ret = io_try_cancel(tctx, cd, issue_flags); if (ret == -ENOENT)
@@ -192,7 +195,15 @@ static int __io_async_cancel(struct io_c } }io_ring_submit_unlock (ctx, issue_flags); -return all ? nr : ret; +if (all) +return nr; +/* +* The worker may be done with the work that was found running, and +* flagged, above. That isn't the same as not having found it. +*/ +if (ret == -ENOENT && cd->running) + ret = -EALREADY ; +return ret; }int io_async_cancel (struct io_kiocb *req,unsigned int issue_flags)
io_uring/cancel.h +2 -0
@@ -11,6 +11,8 @@ struct io_cancel_data {u8 opcode;u32 flags;int seq; +/* io_try_cancel() has found it being run by io-wq, and flagged it */ +bool running; };int io_async_cancel_prep (struct io_kiocb *req,const struct io_uring_sqe *sqe);
Greg Kroah-Hartman
maintainerPATCH 205/247 io_uring/cancel: recognize "no timeout" on 32-bit
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 3774e4d4c8533da2caae95556c4d635c7c4f45b8 upstream.
IORING_REGISTER_SYNC_CANCEL waits without a limit if both fields of io_uring_sync_cancel_reg::timeout are -1. io_sync_cancel() compares them with -1UL. They are of type long long. With a long of 32 bits -1UL is 4294967295, which is what it stays when it is converted for the comparison, and the fields are never equal to it.
So { -1, -1 } is taken for a timeout. ktime_set() takes the nanoseconds as an unsigned long, so what becomes of it is -1s + 4294967295ns = 3.29s.
If the request is being run by io-wq and can't be interrupted, the call returns -ETIME after that time, rather than waiting for the request to be gone. On i386, with a buffered read from a null_blk device that takes 4s to complete a request, IOSQE_ASYNC, that is what each call does.
--- io_uring/cancel.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
io_uring/cancel.c +1 -1
@@ -315,7 +315,7 @@ int io_sync_cancel(struct io_ring_ctx *cif (ret != -EALREADY ) goto out; -if (sc.timeout.tv_sec !=-1UL || sc.timeout.tv_nsec !=-1UL ) { +if (sc.timeout.tv_sec !=-1 || sc.timeout.tv_nsec !=-1 ) {struct timespec64 ts = { .tv_sec = sc.timeout.tv_sec, .tv_nsec = sc.timeout.tv_nsec
Greg Kroah-Hartman
maintainerPATCH 206/247 io_uring/cancel: let CANCEL_ALL find parked requests
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit fe6ca13c98b1223f6005f32913ebd32e4df64b77 upstream.
A cancellation with IORING_ASYNC_CANCEL_ALL or _ANY goes on until it finds nothing more. A request may stay where it was found for a while after it has been cancelled, so each one that matches is stamped with the sequence number of the cancellation, and is skipped from then on.
io_cancel_cb() does so for io-wq work as well. There is no need to:
pending work is taken off the list, and the workers are looked at once per call. And it does harm. A request that is run by io-wq may be parked while it still is the current work of the worker: poll gets armed for it, or it is put on ->futex_list or ->waitid_list.
io-wq worker io_try_cancel()
io_wq_submit_work()
io_arm_poll_handler()
io_poll_add_hash()
io_async_cancel_one()
io_cancel_cb()
stamps the request
sets IO_WQ_WORK_CANCEL = -EALREADY
io_poll_cancel()
skips the request
= -ENOENT
io_assign_current_work(NULL)
The flag comes too late for the worker to see it, and the search that would have found the request takes it for done. The cancellation returns, and the request stays.
With a multishot poll, IOSQE_ASYNC, and IORING_OP_ASYNC_CANCEL with IORING_ASYNC_CANCEL_ALL up to 63us later, that happens to 4 of 1,000 requests (4 CPUs, KVM).
Take the stamp off again if the work matches. If the request is found on one of the lists it gets a new one, and io_cancel_cb() doesn't match it a second time.
__io_async_cancel() tries the io-wq of the caller twice. So far the stamp has kept it from counting work that is running there the second time. Skip it instead, so that the number that is returned stays the same.
--- io_uring/cancel.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
io_uring/cancel.c +13 -1
@@ -70,7 +70,16 @@ static bool io_cancel_cb(struct io_wq_wo struct io_kiocb *req = container_of(work, struct io_kiocb, work);struct io_cancel_data *cd = data; -return io_cancel_req_match (req, cd); +if (!io_cancel_req_match (req, cd)) +return false; +/* +* Pending work is gone once it has matched. Work that is running may +* park the request where the same cancellation looks next. Don't make +* it skip the request as one that it has dealt with. +*/ +if (cd->flags & (IORING_ASYNC_CANCEL_ALL |IORING_ASYNC_CANCEL_ANY )) + req->cancel_seq_set = false; +return true; } static int io_async_cancel_one(struct io_uring_task *tctx,
@@ -187,6 +196,9 @@ static int __io_async_cancel(struct io_cio_ring_submit_lock (ctx, issue_flags); ret = -ENOENT ;list_for_each_entry (node, &ctx->tctx_list, ctx_node) { +/* has been done above, don't count what is running there */ +if (all && node->task->io_uring == tctx) +continue ; ret =io_async_cancel_one (node->task->io_uring, cd);if (ret != -ENOENT ) {if (!all)
Greg Kroah-Hartman
maintainerPATCH 207/247 io_uring: wake ring pollers for local task_work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit b88902d8745a701d24275d012f0830e3628e2a22 upstream.
With IORING_SETUP_DEFER_TASKRUN completions are queued as local work, and only become CQEs when the submitter enters the kernel to wait for events. For an application that finds out via poll() or epoll on the ring fd when it is time to do that, io_uring_poll() reports EPOLLIN if local work is pending.
That only helps if the work is there at the time of the call. When DEFER_TASKRUN was added, io_req_local_work_add() did io_cqring_wake(), which took care of tasks sleeping in poll() as well. Then polling got a wait queue of its own, ->poll_wq, and the wake up in io_req_local_work_add() was replaced by waking the submitter directly. Since then ->poll_wq is only woken when CQEs are committed, which for such a ring is done by the very task that is waiting to be told to:
submitter completion
poll(ring_fd)
io_uring_poll() // nothing yet
schedule()
io_req_local_work_add()
// ->cq_wait_nr: nobody waits// sleeps on
Wake ->poll_wq when the first entry is put on the work list. Like for the eventfd, that must not be done right away if the work is queued from a wake up handler, as the chain of wake ups could get back to the wait queue whose lock is held. Use an RCU callback in that case, with a reference to the ring.
[ 6.12: the code is in io_uring.c, ->poll_activated is a bitfield, and
there is no IOU_F_TWQ_IN_WAKE to tell a wake up handler apart, so the wake up always goes through the RCU callback ]
--- include/linux/io_uring_types.h | 3 +++ io_uring/io_uring.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+)
include/linux/io_uring_types.h +3 -0
@@ -403,6 +403,9 @@ struct io_ring_ctx {u32 iowq_limits[2 ];struct callback_head poll_wq_task_work; +/* deferred ->poll_wq wake up for local task_work */ +struct rcu_head poll_wq_rcu; +atomic_t poll_wq_rcu_pending;struct list_head defer_list;#ifdef CONFIG_NET_RX_BUSY_POLL
io_uring/io_uring.c +28 -0
@@ -1143,6 +1143,31 @@ void tctx_task_work(struct callback_headWARN_ON_ONCE (ret); } +static void io_poll_wq_wake_rcu (struct rcu_head *rcu) +{ + struct io_ring_ctx *ctx = container_of(rcu, struct io_ring_ctx, + poll_wq_rcu); + +atomic_set (&ctx->poll_wq_rcu_pending,0 ); +io_poll_wq_wake (ctx); +percpu_ref_put (&ctx->refs); +} + +/* +* io_uring_poll() reports pending local work as EPOLLIN, as it takes a trip to +* the kernel to turn it into CQEs. Let those know who are asleep already. +* This may be called from a wake up handler with some wait queue lock held, +* and this wake up could lead back to it. Do it from a clean context. +*/ +static void io_local_work_wake_poll (struct io_ring_ctx *ctx) +{ +if (!wq_has_sleeper (&ctx->poll_wq) || +atomic_xchg (&ctx->poll_wq_rcu_pending,1 )) +return ; +percpu_ref_get (&ctx->refs); +call_rcu_hurry (&ctx->poll_wq_rcu, io_poll_wq_wake_rcu); +} +static inline void io_req_local_work_add (struct io_kiocb *req,struct io_ring_ctx *ctx,unsigned flags)
@@ -1202,6 +1227,9 @@ static inline void io_req_local_work_addatomic_or (IORING_SQ_TASKRUN , &ctx->rings->sq_flags);if (ctx->has_evfd)io_eventfd_signal (ctx, flags &IOU_F_TWQ_IN_WAKE ); +/* whoever sets the flag wakes ->poll_wq afterwards */ +if (ctx->poll_activated) +io_local_work_wake_poll (ctx); } nr_wait =atomic_read (&ctx->cq_wait_nr);
Greg Kroah-Hartman
maintainerPATCH 208/247 io_uring/wait: look at all CQ waiters on wake up
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 356f92f2412686f822383b784fa102924407457a upstream.
io_wake_function() returns -1 if the waiter it is called for doesn't have enough events yet, which makes __wake_up_common() stop walking the wait queue. That assumes that the waiters behind it can't be satisfied either. Each waiter has its own target though, computed from the min_complete it passed in:
thread A: io_uring_enter(GETEVENTS, min_complete = 10) // queued first thread B: io_uring_enter(GETEVENTS, min_complete = 1)
one CQE is posted: A isn't woken, and B isn't even considered
B keeps sleeping with the event it asked for sitting in the CQ ring, until A's demand is met or a timeout or signal ends the wait.
Return 0 to carry on with the next waiter. Only waiters whose condition is met are woken, like before.
--- io_uring/io_uring.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
io_uring/io_uring.c +2 -1
@@ -2384,7 +2384,8 @@ static int io_wake_function(struct wait_*/ if (io_should_wake (iowq) ||io_has_work (iowq->ctx))return autoremove_wake_function (curr, mode, wake_flags, key); -return -1 ; +/* keep going, a waiter further down may be content with less */ +return 0 ; }int io_run_task_work_sig (struct io_ring_ctx *ctx)
Greg Kroah-Hartman
maintainerPATCH 209/247 io_uring/poll: drop stale double poll entry on rearm
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit f2dbe87968a3aef74a11c025776d293b80964d3f upstream.
A file that uses two wait queues for poll, e.g. a tty, gets a second io_poll entry, which IORING_OP_POLL_ADD keeps in ->async_data until the request is freed. io_poll_add() can run more than once for a request
though: IORING_OP_POLL_REMOVE with one of the update flags disarms and rearms it, and io_poll_task_func() reissues it if a wake up turns out to be spurious. The second poll_wait() of the new round then finds *poll_ptr set, with ->head cleared by the disarm, and __io_queue_proc() fails what it takes for a third wait queue with -EINVAL.
For an update that means that the poll request is completed with -ECANCELED, while the update itself reports success. For a spurious wake up, e.g. tcsetattr() on the polled tty, the poll request fails with -EINVAL.
Free the old entry and clear the poll flags before arming, which is what io_arm_apoll() does for internal polling. All entries have been removed from their wait queues at that point.
--- io_uring/poll.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
io_uring/poll.c +12 -0
@@ -996,6 +996,18 @@ int io_poll_add(struct io_kiocb *req, unif (req->ctx->flags & (IORING_SETUP_SQPOLL |IORING_SETUP_SINGLE_ISSUER )) req->flags |=REQ_F_HASH_LOCKED ; +/* +* A poll update or a spurious wake up arms the request again. Forget +* the entries of the previous round like io_arm_apoll() does, a stale +* second entry would be taken for a third wait queue. +*/ +if (req_has_async_data (req)) { +kfree (req->async_data); + req->async_data =NULL ; + req->flags &= ~REQ_F_ASYNC_DATA ; + } + req->flags &= ~(REQ_F_SINGLE_POLL |REQ_F_DOUBLE_POLL ); + ret =__io_arm_poll_handler (req, poll, &ipt, poll->events, issue_flags);if (ret >0 ) {io_req_set_res (req, ipt.result_mask,0 );
Greg Kroah-Hartman
maintainerPATCH 210/247 io_uring/timeout: dont skip over reached sequences
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit c6c0b3eba88c3b13ca11ea112404982e86d58f7a upstream.
io_flush_timeouts() copes with the wrap of the CQ sequence by looking at the distance from ->cq_last_tm_flush. That relies on the target of each pending timeout being at or ahead of the last flush.
io_timeout() breaks that. It sets ->cq_last_tm_flush to the current sequence, on the assumption that nothing has been posted since the last flush. That isn't true. A multishot request posts its CQEs right when it is issued or retried, but they are committed, and the timeouts flushed, at the end of the submission or task_work run:
X: IORING_OP_TIMEOUT, off == 1 target_seq == N + 1
io_submit_sqes()
multishot recv, posts two CQEs sequence == N + 2
Y: IORING_OP_TIMEOUT, off == 100 ->cq_last_tm_flush = N + 2 io_flush_timeouts()
X: events_needed = N + 1 - (N + 2) // 0xffffffff
events_got = 0 // not yet
X isn't completed although the completions it was waiting for have happened, only its timer can end it now. And as the list is sorted and the walk ends at the first timeout that isn't due, it gets in the way of the ones behind it. The insertion sort has the same problem, it measures the distance of the pending targets from the current sequence.
->cq_last_tm_flush only needs to be brought up to date if no timeout is waiting for a sequence, as io_flush_timeouts() isn't called before the first one is set up. Otherwise it is current enough. Timeouts with a sequence come first in the list, so looking at the first entry will do. Use the last flush as the base for the insertion sort as well.
--- io_uring/timeout.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-)
io_uring/timeout.c +14 -7
@@ -574,8 +574,9 @@ int io_timeout(struct io_kiocb *req, uns struct io_timeout *timeout = io_kiocb_to_cmd(req, struct io_timeout);struct io_ring_ctx *ctx = req->ctx;struct io_timeout_data *data = req->async_data; +struct io_timeout *first;struct list_head *entry; -u32 tail, off = timeout->off; +u32 tail, base, off = timeout->off;spin_lock_irq (&ctx->timeout_lock);
@@ -592,11 +593,17 @@ int io_timeout(struct io_kiocb *req, uns tail =data_race (ctx->cached_cq_tail) -atomic_read (&ctx->cq_timeouts); timeout->target_seq = tail + off; -/* Update the last seq here in case io_flush_timeouts() hasn't. -* This is safe because ->completion_lock is held, and submissions -* and completions are never mixed in the same ->completion_lock section. +/* +* Update the last seq here in case io_flush_timeouts() hasn't, it only +* gets called once sequences are in use. Leave it alone if there are +* timeouts waiting for one. CQEs may have been posted since the last +* flush, and a target that has been reached must not fall behind it. */ - ctx->cq_last_tm_flush = tail; + first = list_first_entry_or_null(&ctx->timeout_list, struct io_timeout, + list); +if (!first ||io_is_timeout_noseq (cmd_to_io_kiocb (first))) + ctx->cq_last_tm_flush = tail; + base = ctx->cq_last_tm_flush;/* * Insertion sort, ensuring the first entry in the list is always
@@ -608,8 +615,8 @@ int io_timeout(struct io_kiocb *req, unsif (io_is_timeout_noseq (nxt))continue ; -/* nxt.seq is behind @tail, otherwise would've been completed */ -if (off >= nextt->target_seq - tail) +/* no target is behind the last flush, see io_flush_timeouts() */ +if (timeout->target_seq - base >= nextt->target_seq - base)break ; } add:
Greg Kroah-Hartman
maintainerPATCH 211/247 io_uring/timeout: keep repeat count on multishot update
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 3dc2a32cd356ee382aa4a8c7d844c53b2c0ad83b upstream.
IORING_TIMEOUT_UPDATE clears ->off of the timeout it updates, to turn a timeout that waits for a number of completions into a pure one. For a multishot timeout ->off isn't a sequence though, it tells whether the number of repeats is limited: io_timeout_finish() only looks at ->repeats if ->off is set.
A multishot timeout that was set up to fire N times hence fires forever once its interval has been updated. Leave ->off alone for those, they are never treated as sequence timeouts anyway.
--- io_uring/timeout.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
io_uring/timeout.c +3 -1
@@ -407,8 +407,10 @@ static int io_timeout_update(struct io_rif (IS_ERR (req))return PTR_ERR (req); - timeout->off =0 ;/* noseq */ data = req->async_data; +/* for a multishot request this isn't a sequence, keep the repeats */ +if (!(data->flags &IORING_TIMEOUT_MULTISHOT )) + timeout->off =0 ;/* noseq */ data->ts = *ts;list_add_tail (&timeout->list, &ctx->timeout_list);
Greg Kroah-Hartman
maintainerPATCH 212/247 io_uring/wait: no early -ETIME if min_wait finds work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 83cce67298ab1f4d2e9205a49f56975475cdb154 upstream.
When the min wait time is over and there is work to run, which for DEFER_TASKRUN includes task_work that was queued lazily and didn't wake the waiter, io_cqring_min_timer_wakeup() ends the wait via io_cqring_timer_wakeup(). That flags it as timed out. io_cqring_wait() runs the work, leaves the loop, and returns 0 if the CQ ring holds something.
Running task_work doesn't have to result in a CQE, though. A poll wake up can turn out to be spurious, for instance if somebody else has read the data by the time the request is retried. The application then gets -ETIME once the min wait time has passed, no matter how far away the timeout it asked for is.
Wake the task without declaring a timeout. From now on a single CQE satisfies the wait, like in the case where the timer is switched over to the normal timeout. If running the work doesn't post one, the loop in io_cqring_wait() goes back to sleep with the normal timeout.
--- io_uring/io_uring.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
io_uring/io_uring.c +10 -3
@@ -2435,9 +2435,16 @@ static enum hrtimer_restart io_cqring_miif (iowq->timeout ==KTIME_MAX ||ktime_compare (iowq->min_timeout, iowq->timeout) >=0 ) goto out_wake; -/* work we may need to run, wake function will see if we need to wake */ -if (io_has_work (ctx)) - goto out_wake; +/* +* Work we need to run. It isn't known if that is going to post a CQE, +* so this isn't a timeout. Carry on with the normal one if it doesn't. +*/ +if (io_has_work (ctx)) { + iowq->min_timeout =0 ; + iowq->cq_tail = iowq->cq_min_tail +1 ; +wake_up_process (iowq->wq.private); +return HRTIMER_NORESTART ; + }/* got events since we started waiting, min timeout is done */ if (iowq->cq_min_tail !=READ_ONCE (ctx->rings->cq.tail)) goto out_wake;
Greg Kroah-Hartman
maintainerPATCH 213/247 io_uring/napi: make stale entries time out after 60s
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 9c151648780d89e5446e5f89f3fa2e416c3bb911 upstream.
With dynamic tracking a NAPI id that hasn't been seen for a minute is meant to be dropped from the list the ring busy polls. The timeout is added to jiffies, but it is defined as 60 * SEC_CONVERSION, and SEC_CONVERSION isn't the number of jiffies in a second. It is the internal factor of __timespec64_to_jiffies(), HZ scaled up by SEC_JIFFIE_SC bits. For HZ=1000 that is 1000 << 22, which puts the timeout at about eight years. On 32-bit the multiplication overflows.
So entries are never removed, and every id that a socket of the ring ever had keeps being polled on each wait.
--- io_uring/napi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
io_uring/napi.c +1 -1
@@ -6,7 +6,7 @@ #ifdef CONFIG_NET_RX_BUSY_POLL /* Timeout for cleanout of stale entries. */ -#define NAPI_TIMEOUT (60 * SEC_CONVERSION) +#define NAPI_TIMEOUT (60 * HZ) struct io_napi_entry { unsigned int napi_id;
Greg Kroah-Hartman
maintainerPATCH 214/247 io_uring/napi: dont busy poll past an expired timeout
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 21ed976c12f6b77d7ea028a4fe9a08e69a56179f upstream.
__io_napi_busy_loop() caps the busy poll time to what is left until the timeout of the wait. The difference is negative if the timeout has passed already, which is what an application gets if it uses IORING_ENTER_ABS_TIMER with a time that isn't in the future any more. The min_t(u64, ...) turns that into a huge value, so the cap has no effect and the wait, which should return right away, spins for the full busy poll time first.
--- io_uring/napi.c | 2 ++ 1 file changed, 2 insertions(+)
io_uring/napi.c +2 -0
@@ -288,6 +288,8 @@ void __io_napi_busy_loop(struct io_ring_if (iowq->timeout !=KTIME_MAX ) {ktime_t dt =ktime_sub (iowq->timeout,io_get_time (ctx)); +/* an absolute timeout may have passed already */ + dt =max_t (ktime_t, dt,0 ); iowq->napi_busy_poll_dt =min_t (u64, iowq->napi_busy_poll_dt, dt); }
Greg Kroah-Hartman
maintainerPATCH 215/247 io_uring/kbuf: handle index wrap in last buffer check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 6e773b5161506a4d0e739eb3aa4667d28f20219c upstream.
io_ring_buffer_select() flags the request with REQ_F_BL_EMPTY if it takes the last buffer of the ring. Head and tail are 16-bit counters, but "head + 1" is computed as an int. If head is 65535 and tail has wrapped to 0, that compares 65536 to 0 and the flag isn't set.
A bundle receive relies on the flag to tell that there is no point in trying to get more data. Without it, it goes for another round, finds no buffer, and the request, which has received data, is marked as failed on account of the -ENOBUFS. That severs a link, and ends a multishot.
--- io_uring/kbuf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
io_uring/kbuf.c +1 -1
@@ -181,7 +181,7 @@ static struct io_br_sel io_ring_buffer_sif (unlikely (tail == head))return sel; -if (head +1 == tail) +if ((__u16)(head +1 ) == tail) req->flags |=REQ_F_BL_EMPTY ; buf =io_ring_head_to_buf (br, head, bl->mask);
Greg Kroah-Hartman
maintainerPATCH 216/247 io_uring/sqpoll: let the thread sleep on disabled rings
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit d492dcbb3b81c1c2d0aabef41fa1307093f3a556 upstream.
__io_sq_thread() doesn't submit anything as long as the ring has IORING_SETUP_R_DISABLED set. The check that keeps the SQPOLL thread from going to sleep while the SQ ring holds entries doesn't know about that. If an application fills in SQEs first and enables the ring later, the thread finds that there is work each time it is about to sleep, goes around, doesn't submit it, and so on. It uses up a CPU until the ring gets enabled.
Entries in the SQ ring of a disabled ring are no reason to stay awake. io_register_enable_rings() clears the flag and then wakes the thread, and the flag is looked at after prepare_to_wait(), so the thread can't miss that.
--- io_uring/sqpoll.c | 7 +++++++ 1 file changed, 7 insertions(+)
io_uring/sqpoll.c +7 -0
@@ -387,6 +387,13 @@ static int io_sq_thread(void *data)*/ smp_mb__after_atomic (); +/* +* Nothing gets submitted before the ring is +* enabled, which comes with a wake up. +*/ +if (READ_ONCE (ctx->flags) &IORING_SETUP_R_DISABLED ) +continue ; +if (io_sqring_entries (ctx)) { needs_sched = false;break ;
Greg Kroah-Hartman
maintainerPATCH 217/247 io_uring: dont pass restart error codes to userspace
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit e1a64bc64897f4c2fe460922c345f2ed8f889b5f upstream.
-ERESTARTSYS and friends are instructions for the system call exit code, which either restarts the call or turns them into -EINTR. They are not supposed to be seen by applications. A request isn't a system call, nobody looks at what it returns before that is put into a CQE.
The read/write and the networking opcodes convert these codes to -EINTR by hand. The others don't. An io-wq worker that is blocked in the open of a FIFO, a tty or some other device, or in a splice from an empty pipe, and that gets interrupted because the request is cancelled, completes it with -512:
IORING_OP_OPENAT, IOSQE_ASYNC // FIFO without a writer
IORING_OP_ASYNC_CANCEL // -EALREADY, worker is signalled
CQE of the open: res == -512
There are more candidates, like whatever a file system or driver returns from ->flush(), ->fsync(), ->fallocate() or ->uring_cmd(), or breaking a lease or delegation.
Take care of it in io_issue_sqe(), which all of them go through. The helper is moved from rw.c as is. The cost is a compare and a branch that is not taken per request.
--- io_uring/io_uring.c | 5 +++++ io_uring/io_uring.h | 18 ++++++++++++++++++ io_uring/rw.c | 18 ------------------ 3 files changed, 23 insertions(+), 18 deletions(-)
io_uring/io_uring.c +5 -0
@@ -1773,6 +1773,9 @@ static int io_issue_sqe(struct io_kiocb }if (ret ==IOU_OK ) { +/* not all handlers take care of the internal restart codes */ +if (unlikely (req->cqe.res <= -ERESTARTSYS )) + req->cqe.res =io_fixup_restart_res (req->cqe.res);if (issue_flags &IO_URING_F_COMPLETE_DEFER )io_req_complete_defer (req);else
@@ -1788,6 +1791,8 @@ static int io_issue_sqe(struct io_kiocbif ((req->ctx->flags &IORING_SETUP_IOPOLL ) && def->iopoll_queue)io_iopoll_req_issued (req, issue_flags); } +if (unlikely (ret <= -ERESTARTSYS )) + ret =io_fixup_restart_res (ret);return ret; }
io_uring/io_uring.h +18 -0
@@ -203,6 +203,24 @@ static __always_inline bool io_fill_cqe_return true; } +static inline ssize_t io_fixup_restart_res (ssize_t ret) +{ +switch (ret) { +case -ERESTARTSYS : +case -ERESTARTNOINTR : +case -ERESTARTNOHAND : +case -ERESTART_RESTARTBLOCK : +/* +* We can't just restart the syscall, since previously +* submitted sqes may already be in progress. Just fail +* this IO with EINTR. +*/ +return -EINTR ; +default : +return ret; + } +} +static inline void req_set_fail (struct io_kiocb *req) { req->flags |=REQ_F_FAIL ;
io_uring/rw.c +0 -18
@@ -560,24 +560,6 @@ static void io_complete_rw_iopoll(structsmp_store_release (&req->iopoll_completed,1 ); } -static inline ssize_t io_fixup_restart_res (ssize_t ret) -{ -switch (ret) { -case -ERESTARTSYS : -case -ERESTARTNOINTR : -case -ERESTARTNOHAND : -case -ERESTART_RESTARTBLOCK : -/* -* We can't just restart the syscall, since previously -* submitted sqes may already be in progress. Just fail -* this IO with EINTR. -*/ -return -EINTR ; -default : -return ret; - } -} -static inline void io_rw_done (struct kiocb *kiocb,ssize_t ret) {/* IO was queued async, completion will happen later */
Greg Kroah-Hartman
maintainerPATCH 218/247 io_uring/net: dont retry recv on uncommitted buffers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 8444de681a179e41a4eb92d5bbe770a0677074a6 upstream.
Commit 41b70df5b38b ("io_uring/net: commit partial buffers on retry") commits ring provided buffers when a receive is going to be retried after a partial transfer, so that another request using the same buffer group can't be handed the memory the first one keeps receiving into. It commits the number of bytes received so far. That does the job for a single buffer which is consumed as a whole, but the request hangs on to all it has mapped:
- For a buffer ring with IOU_PBUF_RING_INC only these bytes are consumed. The rest of the buffer stays at the head of the ring.
- For a bundle only the buffers which hold these bytes are consumed, the others that were peeked stay in the ring.
In both cases the next receive with that buffer group gets memory that the retried request is still going to write to, and whoever comes last overwrites the data of the other. What the retry fills isn't committed at all, as the buffer list isn't known any more at that point. So the kernel hands it out again later on, while the CQE tells the application that it was used, and for an incremental buffer that it is done with.
The remainder can't be committed in advance: if the request ends up receiving less, there is no way to tell the application that more was consumed than the CQE accounts for. Complete the request with what it has got instead of retrying it. MSG_WAITALL is no longer honoured for receives into incremental buffers or multi buffer bundles, they can return a short count, with the request marked as failed like for other short MSG_WAITALL transfers.
--- io_uring/net.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-)
io_uring/net.c +22 -2
@@ -500,6 +500,24 @@ static int io_bundle_nbufs(struct io_asyreturn nbufs; } +/* +* A receive that is retried after a partial transfer keeps writing to what it +* has mapped. io_net_kbuf_recyle() only commits what was filled so far, which +* takes a buffer out of circulation if it's a single one that is consumed as a +* whole. The tail of an incrementally consumed buffer, or the yet unused +* buffers of a bundle, would be up for grabs. They can't be committed in +* advance either, the CQE has no way to tell if they end up not being used. +*/ +static bool io_net_kbuf_can_retry (struct io_kiocb *req, +struct io_buffer_list *bl, +struct io_async_msghdr *kmsg) +{ +/* not ring provided, or committed at selection time */ +if (!(req->flags &REQ_F_BUFFERS_COMMIT )) +return true; +return !(bl->flags &IOBL_INC ) &&iter_is_ubuf (&kmsg->msg.msg_iter); +} +static int io_net_kbuf_recyle (struct io_kiocb *req,struct io_buffer_list *bl,struct io_async_msghdr *kmsg,int len) {
@@ -1086,7 +1104,8 @@ retry_multishot:return IOU_ISSUE_SKIP_COMPLETE ;return -EAGAIN ; } -if (ret >0 &&io_net_retry (sock, flags)) { +if (ret >0 &&io_net_retry (sock, flags) && +io_net_kbuf_can_retry (req, sel.buf_list, kmsg)) { sr->done_io += ret;return io_net_kbuf_recyle (req, sel.buf_list, kmsg, ret); }
@@ -1233,7 +1252,8 @@ retry_multishot:return IOU_ISSUE_SKIP_COMPLETE ;return -EAGAIN ; } -if (ret >0 &&io_net_retry (sock, flags)) { +if (ret >0 &&io_net_retry (sock, flags) && +io_net_kbuf_can_retry (req, sel.buf_list, kmsg)) { sr->len -= ret; sr->buf += ret; sr->done_io += ret;
Greg Kroah-Hartman
maintainerPATCH 219/247 io_uring/timeout: no ABS update of multishot timeouts
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit b088ae34d4da730dc647261b893a6eb622fe5e1f upstream.
IORING_TIMEOUT_MULTISHOT can't be combined with IORING_TIMEOUT_ABS, prep rejects that, as the request is armed again with the same value each time it fires. IORING_TIMEOUT_UPDATE doesn't check and takes an absolute time for a multishot timeout. The first expiry is as asked for, but io_timeout_complete() then arms the timer with ->mode of the original request, i.e. it uses the absolute time as the interval. With CLOCK_MONOTONIC the next expiry is an uptime away, with CLOCK_REALTIME more than fifty years.
Fail such an update with -EINVAL, and do so before the timeout is touched.
--- io_uring/timeout.c | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-)
io_uring/timeout.c +26 -12
@@ -254,22 +254,29 @@ static enum hrtimer_restart io_timeout_freturn HRTIMER_NORESTART ; } -static struct io_kiocb *io_timeout_extract (struct io_ring_ctx *ctx, -struct io_cancel_data *cd) +static struct io_kiocb *io_timeout_find (struct io_ring_ctx *ctx, +struct io_cancel_data *cd) __must_hold(&ctx->timeout_lock) {struct io_timeout *timeout; -struct io_timeout_data *io; -struct io_kiocb *req =NULL ;list_for_each_entry (timeout, &ctx->timeout_list, list) { -struct io_kiocb *tmp =cmd_to_io_kiocb (timeout); +struct io_kiocb *req =cmd_to_io_kiocb (timeout); -if (io_cancel_req_match (tmp, cd)) { - req = tmp; -break ; - } +if (io_cancel_req_match (req, cd)) +return req; } +return NULL ; +} + +static struct io_kiocb *io_timeout_extract (struct io_ring_ctx *ctx, +struct io_cancel_data *cd) + __must_hold(&ctx->timeout_lock) +{ +struct io_kiocb *req =io_timeout_find (ctx, cd); +struct io_timeout *timeout; +struct io_timeout_data *io; +if (!req)return ERR_PTR (-ENOENT );
@@ -400,14 +407,21 @@ static int io_timeout_update(struct io_r __must_hold(&ctx->timeout_lock) {struct io_cancel_data cd = { .ctx = ctx, .data = user_data, }; -struct io_kiocb *req =io_timeout_extract (ctx, &cd); +struct io_kiocb *req =io_timeout_find (ctx, &cd); struct io_timeout *timeout = io_kiocb_to_cmd(req, struct io_timeout);struct io_timeout_data *data; -if (IS_ERR (req)) -return PTR_ERR (req); +if (!req) +return -ENOENT ; data = req->async_data; +/* multishot requests only make sense with rel values */ +if ((data->flags &IORING_TIMEOUT_MULTISHOT ) && mode ==HRTIMER_MODE_ABS ) +return -EINVAL ; + + req =io_timeout_extract (ctx, &cd); +if (IS_ERR (req)) +return PTR_ERR (req);/* for a multishot request this isn't a sequence, keep the repeats */ if (!(data->flags &IORING_TIMEOUT_MULTISHOT )) timeout->off =0 ;/* noseq */
Greg Kroah-Hartman
maintainerPATCH 220/247 io_uring/timeout: dont end a linked timeout with 1
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit c74193430febdd120e35936dda3e5aeec3a54405 upstream.
A linked timeout that fires cancels the request it is linked to, and completes with -ETIME if that worked out:
ret = io_try_cancel(req->tctx, &cd, 0); ... io_req_set_res(req, ret ?: -ETIME, 0);
io_try_cancel() returns 0 or an error, except for requests that are parked on ->futex_list or ->waitid_list. io_futex_cancel() and io_waitid_cancel() return the number of requests that they have cancelled, and io_try_cancel() hands it on.
So the linked timeout of an IORING_OP_FUTEX_WAIT, IORING_OP_FUTEX_WAITV or IORING_OP_WAITID that it has cancelled completes with 1, each time.
The waitid test of liburing checks for that 1, and has to be changed to expect -ETIME, which is what the linked timeout of any other request completes with.
--- io_uring/timeout.c | 3 +++ 1 file changed, 3 insertions(+)
io_uring/timeout.c +3 -0
@@ -317,6 +317,9 @@ static void io_req_task_link_timeout(str }; ret =io_try_cancel (req->task->io_uring, &cd,0 ); +/* a number of requests for futex and waitid */ +if (ret >0 ) + ret =0 ; }io_req_set_res (req, ret ?: -ETIME ,0 );io_req_task_complete (req, ts);
Greg Kroah-Hartman
maintainerPATCH 221/247 io_uring: look up the file before queueing to io-wq
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 98bc044d5a5374f8d3605fe55a8e2df6d6fc3f82 upstream.
io_prep_async_work() decides by the file of a request what kind of work it is for io-wq. I/O on regular files and block devices is bounded work, limited to min(SQ entries, 4 * CPUs) workers, for anything else that may block indefinitely the limit is RLIMIT_NPROC. Writes to a regular file are hashed by the inode, so that they are run one after the other instead of having a bunch of workers fight for the inode lock.
Since the file is only assigned when a request is issued, a request that is queued without an attempt to issue it, REQ_F_FORCE_ASYNC, doesn't have one at that point. io_prep_async_work() takes that for "not a regular file or block device":
- Reads and writes end up as unbound work. 32 reads with IOSQE_ASYNC from a slow block device on a ring with 4 SQ entries get 32 workers, not 4.
- Writes aren't hashed. Four buffered writes to one file get four workers, three of which do nothing but wait for the lock.
The late assignment is for the benefit of links, where a request may use a fixed file that one of its predecessors installs. By the time a request gets to io_queue_iowq() these are done, it is as good as issued. Assign the file there.
io_assign_file() moves up and is forced inline. With a third caller the compiler may stop inlining it, and every request that is issued would pay for a call.
IORING_OP_SPLICE is left as it is, unbound and not hashed. The file of the request is where it writes to, which says nothing about how long it
takes: a splice from an empty pipe or a socket into a regular file waits for its input. As bounded work, four of these on a ring with 4 SQ entries keep all other bounded work of the task from running, and as hashed work one of them blocks all writes to that file.
REQ_F_FORCE_ASYNC is not only set for IOSQE_ASYNC. What changes, and brings back what was the case before the file assignment was deferred:
- Requests with IOSQE_ASYNC or IOSQE_IO_DRAIN, and all requests that are submitted while a drain is active: reads and writes on regular files and block devices count against the limit for bounded workers, including the one set with IORING_REGISTER_IOWQ_MAX_WORKERS, so fewer of them run at the same time.
- Of these, writes to one regular file are run one at a time, unless they are O_DIRECT and the filesystem has FOP_DIO_PARALLEL_WRITE.
- IORING_OP_FALLOCATE and IORING_OP_FTRUNCATE, which always go to io-wq, are run one at a time per file, and in turn with these writes.
- The descriptor or the fixed file slot is looked up when the request is queued, not when a worker gets around to it, so closing or replacing it in between no longer has an effect on the request.
--- io_uring/io_uring.c | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-)
io_uring/io_uring.c +29 -14
@@ -481,17 +481,46 @@ static void io_prep_async_link(struct io } } +/* Called for every request that is issued: keep it inline */ +static __always_inline bool io_assign_file(struct io_kiocb *req, +const struct io_issue_def *def, +unsigned int issue_flags) +{ +if (req->file || !def->needs_file) +return true; + +if (req->flags &REQ_F_FIXED_FILE ) + req->file =io_file_get_fixed (req, req->cqe.fd, issue_flags); +else + req->file =io_file_get_normal (req, req->cqe.fd); + +return !!req->file; +} +static void io_queue_iowq (struct io_kiocb *req) {struct io_uring_task *tctx = req->task->io_uring;BUG_ON (!tctx); +lockdep_assert_held (&req->ctx->uring_lock);if ((current->flags &PF_KTHREAD ) || !tctx->io_wq) {io_req_task_queue_fail (req, -ECANCELED );return ; } +/* +* The file is looked up as late as possible, as it may be the result +* of an earlier request of the link. This one is up now, and what kind +* of work it is depends on the file. If that fails, leave the error +* handling to the worker. +* +* Not for a splice: whatever it writes to, it may wait for its input +* for ever. It has to remain unbound work that isn't hashed. +*/ +if (req->opcode !=IORING_OP_SPLICE ) +io_assign_file (req, &io_issue_defs[req->opcode],0 ); +/* init ->work of the whole link before punting */ io_prep_async_link (req);
@@ -1724,20 +1753,6 @@ queue:spin_unlock (&ctx->completion_lock); } -static bool io_assign_file (struct io_kiocb *req,const struct io_issue_def *def, -unsigned int issue_flags) -{ -if (req->file || !def->needs_file) -return true; - -if (req->flags &REQ_F_FIXED_FILE ) - req->file =io_file_get_fixed (req, req->cqe.fd, issue_flags); -else - req->file =io_file_get_normal (req, req->cqe.fd); - -return !!req->file; -} -#define REQ_ISSUE_SLOW_FLAGS (REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)static int io_issue_sqe (struct io_kiocb *req,unsigned int issue_flags)
Greg Kroah-Hartman
maintainerPATCH 222/247 io_uring/poll: avoid retry wakeup loss when dropping ownership
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Juanlu Herrero <[email protected]>
Commit 937d38dcacd675dc0572d6c9b6743960df3128ed upstream.
If a wakeup sets IO_POLL_RETRY_FLAG between the owning task consuming the existing instance of IO_POLL_RETRY_FLAG and the loop check of io_poll_check_events(), then we stall on processing the request until an unrelated wakeup comes along.
Using atomic_cmpxchg instead of atomic_sub_return to guarantee both the count v and poll_refs are 0 and no wake-ups are missed.
--- io_uring/poll.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
io_uring/poll.c +2 -1
@@ -350,7 +350,8 @@ static int io_poll_check_events(struct i* Release all references, retry if someone tried to restart * task_work while we were executing it. */ - }while (atomic_sub_return (v, &req->poll_refs) &IO_POLL_REF_MASK ); + v &=IO_POLL_REF_MASK ; + }while (atomic_cmpxchg (&req->poll_refs, v,0 ) != v);io_napi_add (req);return IOU_POLL_NO_ACTION ;
Greg Kroah-Hartman
maintainerPATCH 223/247 io_uring/timeout: dont put a sequence target behind the last flush
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jens Axboe <[email protected]>
Commit fdfce905a58edea053ee7b68b5bd4348dd1b36e0 upstream.
io_timeout_fn() and io_kill_timeout() bump ->cq_timeouts when a timeout fires, but its CQE is only posted later from task_work. Until then the sequence io_timeout() computes is one below the last flush per fired timeout. Now that ->cq_last_tm_flush is kept while sequence timeouts are pending, a timeout armed in that window with a small offset gets a target behind the base. Its distance from the base wraps, and it's never completed by events, only by its timer. With DEFER_TASKRUN that window is as wide as the application makes it, as submission runs before the local task_work.
Nothing but those in flight CQEs separates the two, so use the last flush as the base for the target when the sequence is behind it.
--- io_uring/timeout.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
io_uring/timeout.c +9 -1
@@ -610,7 +610,6 @@ int io_timeout(struct io_kiocb *req, uns } tail =data_race (ctx->cached_cq_tail) -atomic_read (&ctx->cq_timeouts); - timeout->target_seq = tail + off;/* * Update the last seq here in case io_flush_timeouts() hasn't, it only
@@ -625,6 +624,15 @@ int io_timeout(struct io_kiocb *req, uns base = ctx->cq_last_tm_flush;/* +* A fired timeout bumps ->cq_timeouts before its CQE is posted, which +* leaves the sequence behind the last flush until it is. Nothing else +* separates the two then, so count from the flush. +*/ +if ((s32)(tail - base) <0 ) + tail = base; + timeout->target_seq = tail + off; + +/* * Insertion sort, ensuring the first entry in the list is always * the one we need first. */
Greg Kroah-Hartman
maintainerPATCH 224/247 io_uring/timeout: dont flush with the sequence behind the last flush
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jens Axboe <[email protected]>
Commit 85f85d573ffa7772e1ad4504d0cec5113a5c5cf1 upstream.
io_flush_timeouts() measures the events since the last flush as the distance of the current sequence from ->cq_last_tm_flush. A fired timeout bumps ->cq_timeouts before its CQE is posted, so until it is the sequence can be behind the last flush, and the distance wraps:
last flush: seq 100, cq_last_tm_flush = 100
Y: IORING_OP_TIMEOUT, off 50, target_seq 150 pure timeout A fires, cq_timeouts = 1 task_work posts A's CQE, cached_cq_tail = 101 pure timeout B fires before the flush, cq_timeouts = 2 io_flush_timeouts(): seq = 99, events_got = 0xffffffff
Y, and every sequence timeout behind it, is ended with -ETIME although no event happened. Two timeouts expiring close together is all it takes, a completion with IOSQE_CQE_SKIP_SUCCESS after a single one does it too.
Nothing but those in flight CQEs separates the two, so count from the last flush when the sequence is behind it, as io_timeout() does.
--- io_uring/timeout.c | 8 ++++++++ 1 file changed, 8 insertions(+)
io_uring/timeout.c +8 -0
@@ -113,6 +113,14 @@ __cold void io_flush_timeouts(struct io_spin_lock_irq (&ctx->timeout_lock); seq = ctx->cached_cq_tail -atomic_read (&ctx->cq_timeouts); +/* +* A fired timeout bumps ->cq_timeouts before its CQE is posted, which +* leaves the sequence behind the last flush until it is. No event has +* happened then, see io_timeout(). +*/ +if ((s32)(seq - ctx->cq_last_tm_flush) <0 ) + seq = ctx->cq_last_tm_flush; +list_for_each_entry_safe (timeout, tmp, &ctx->timeout_list, list) {struct io_kiocb *req =cmd_to_io_kiocb (timeout);u32 events_needed, events_got;
Greg Kroah-Hartman
maintainerPATCH 225/247 io_uring/timeout: dont lose a cancel as io-wq arms a timeout
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jens Axboe <[email protected]>
Commit 89f193dc3ef462059387e9691bf6af4b1808379a upstream.
An IORING_OP_TIMEOUT run by io-wq, because of IOSQE_ASYNC, has the same problem as poll, futex and waitid. io_wq_submit_work() looks at IO_WQ_WORK_CANCEL once, before it issues the request. A cancel in between flags the work, gets -EALREADY, and searches ->timeout_list in vain, while the worker then adds the request and starts the timer:
io-wq worker io_try_cancel()
io_wq_submit_work()
IO_WQ_WORK_CANCEL isn't set
io_async_cancel_one()
sets IO_WQ_WORK_CANCEL = -EALREADY
io_timeout_cancel() = -ENOENT
io_timeout()
adds the request to ->timeout_list
hrtimer_start()
= IOU_ISSUE_SKIP_COMPLETE
Nobody looks at the flag again, and the timeout runs its course. At ring exit, io_uring_try_cancel_requests() cancels io-wq work and then kills the timeouts the same way, so an exiting task can get stuck for the full duration of such a timeout.
Look at the flag under ->timeout_lock, which the search takes as well, and fail the request if it is set. If the search came first, the flag is visible. If it comes later, it finds the request on the list.
--- io_uring/io_uring.h | 14 ++++++++++---- io_uring/timeout.c | 7 +++++++ 2 files changed, 17 insertions(+), 4 deletions(-)
io_uring/io_uring.h +10 -4
@@ -274,16 +274,22 @@ static inline void io_ring_submit_lock(s* cancellations find it, rather than completing it. Whoever tried to cancel * the request before that found it running. It has flagged the work item, * has searched the list in vain, and won't come back. To be called with -* ->uring_lock held, which the search needs as well, once the request is on -* the list: if the search came first, the flag is visible. +* the lock the search takes held: if the search came first, the flag is +* visible. For most lists that is ->uring_lock, timeouts use ->timeout_lock. */ +static inline bool __io_wq_cancel_seen (struct io_kiocb *req, +unsigned int issue_flags) +{ +return (issue_flags &IO_URING_F_IOWQ ) && + (atomic_read (&req->work.flags) &IO_WQ_WORK_CANCEL ); +} +static inline bool io_wq_cancel_seen (struct io_kiocb *req,unsigned int issue_flags) {lockdep_assert_held (&req->ctx->uring_lock); -return (issue_flags &IO_URING_F_IOWQ ) && - (atomic_read (&req->work.flags) &IO_WQ_WORK_CANCEL ); +return __io_wq_cancel_seen (req, issue_flags); }static inline void io_commit_cqring (struct io_ring_ctx *ctx)
io_uring/timeout.c +7 -0
@@ -607,6 +607,13 @@ int io_timeout(struct io_kiocb *req, unsspin_lock_irq (&ctx->timeout_lock); +/* the list is searched under ->timeout_lock, see io_wq_cancel_seen() */ +if (__io_wq_cancel_seen (req, issue_flags)) { +spin_unlock_irq (&ctx->timeout_lock); +io_req_task_queue_fail (req, -ECANCELED ); +return IOU_ISSUE_SKIP_COMPLETE ; + } +/* * sqe->off holds how many events that need to occur for this * timeout event to be satisfied. If it isn't set, then this is
Greg Kroah-Hartman
maintainerPATCH 226/247 io_uring/poll: dont loop on HUP with multiple references
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jens Axboe <[email protected]>
Commit cf1d5c9d335e2c673811da641531da82cb01393a upstream.
io_poll_check_events() drops down to one reference when a multishot request sees HUP with more than one, so that the loop goes around once more. It did so by subtracting one less than it had. With the cmpxchg that only takes the local count down: the exchange fails, the next pass reads the unchanged count, and goes through the same motions again. The loop then only ends once io_poll_issue() stops the request.
Drop the extra references from the counter instead, and loop once more without trying the exchange. The next pass sees one reference, like it did before, and ends unless a wake up came in.
--- io_uring/poll.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
io_uring/poll.c +12 -4
@@ -264,12 +264,14 @@ static inline void io_poll_execute(struc*/ static int io_poll_check_events (struct io_kiocb *req,struct io_tw_state *ts) { +bool again;int v;if (unlikely (io_should_terminate_tw (req->ctx)))return -ECANCELED ; do { + again = false; v = atomic_read(&req->poll_refs); if (unlikely(v != 1)) {
@@ -331,9 +333,15 @@ static int io_poll_check_events(struct i }else {int ret; -/* multiple refs and HUP, ensure we loop once more */ -if ((req->cqe.res & (POLLHUP |POLLRDHUP )) && v !=1 ) - v--; +/* +* Multiple refs and HUP, ensure we loop once more. Drop +* down to one ref now, so the next pass ends unless a +* wake up came in. +*/ +if ((req->cqe.res & (POLLHUP |POLLRDHUP )) && v !=1 ) { +atomic_sub (v -1 , &req->poll_refs); + again = true; + } ret =io_poll_issue (req, ts);if (ret ==IOU_STOP_MULTISHOT )return IOU_POLL_REMOVE_POLL_USE_RES ;
@@ -351,7 +359,7 @@ static int io_poll_check_events(struct i* task_work while we were executing it. */ v &=IO_POLL_REF_MASK ; - }while (atomic_cmpxchg (&req->poll_refs, v,0 ) != v); + }while (again ||atomic_cmpxchg (&req->poll_refs, v,0 ) != v);io_napi_add (req);return IOU_POLL_NO_ACTION ;
Greg Kroah-Hartman
maintainerPATCH 227/247 io_uring/net: keep recv buffer select length within MAX_RW_COUNT
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tamaki Yanagawa <[email protected]>
Commit 96262cfab554cf11412de7a6247f0e82c94e130f upstream.
Since commit dcbd1c054848 ("io_uring/net: let io_recv_buf_select return the length of the buffer region"), io_recv_buf_select() returns the selected length as an int. For a non-bundle recv with sqe->len == 0 the length comes from the ring provided buffer, which can be up to 4G, so a buffer of 2G or more makes io_recv() fail the request with a bogus negative result (e.g. -2147483648) instead of receiving into it. Clamp the length to MAX_RW_COUNT, which import_ubuf() limits the transfer to anyway.
--- io_uring/net.c | 2 ++ 1 file changed, 2 insertions(+)
io_uring/net.c +2 -0
@@ -1188,6 +1188,8 @@ static int io_recv_buf_select(struct io_ *sel =io_buffer_select (req, &len, issue_flags);if (!sel->addr)return -ENOBUFS ; +/* ring provided buffers can be up to 4G, keep len an int */ + len =min_t (size_t, len,MAX_RW_COUNT ); sr->buf = sel->addr; sr->len = len; map_ubuf:
Greg Kroah-Hartman
maintainerPATCH 228/247 io_uring/wait: wake real-time waiters from hard interrupt context
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Austin Schuh <[email protected]>
Commit 5b01d5955ac206e38097f777eff6ab2a8b948c41 upstream.
Since commit cebf123c634a ("io_uring: implement our own schedule timeout handling"), a CQ wait with a timeout sleeps on io_uring's own hrtimer instead of an hrtimer sleeper. On PREEMPT_RT, an hrtimer that isn't marked for hard interrupt expiry expires in the per-CPU ktimers thread, which runs at SCHED_FIFO 1. A real-time task waiting in io_uring_enter() is therefore not woken at its deadline while any other real-time task is runnable on its CPU: the wakeup waits until every one of them has blocked.
hrtimer sleepers, which schedule_hrtimeout_range_clock() used to give io_uring, don't have this problem: __hrtimer_setup_sleeper() marks the timer hard when the sleeping task is in a real-time or deadline class. Both of io_uring's callbacks are fine in hard interrupt context:io_cqring_timer_wakeup() sets a flag and calls wake_up_process(), and io_cqring_min_timer_wakeup() only reads ring state, under RCU, before doing the same or re-arming the timer. Apply the sleeper rule to them.
Measured on a Jetson Orin Nano running 6.18.39-rt with this change
backported: a SCHED_FIFO 40 task waits in io_uring_enter() for 40,000 deadlines 500us apart, while a SCHED_FIFO 20 task runs bursts of up to 1ms on the same CPU. Before, 6,647 wakeups were more than 100us late, the latest by 1,040us, and 2,758 deadlines passed without a wakeup at all. After, none were more than 100us late and the latest was 18us.
This mirrors epoll: epoll_pwait2() waits on an hrtimer sleeper, so its timeout is already hard for real-time tasks, and on the same setup it was never more than 17us late.
--- io_uring/io_uring.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
io_uring/io_uring.c +12 -2
@@ -48,6 +48,7 @@#include <linux/uio.h> #include <linux/bits.h> +#include <linux/sched/rt.h> #include <linux/sched/signal.h> #include <linux/fs.h> #include <linux/file.h>
@@ -2495,12 +2496,21 @@ out_wake:return io_cqring_timer_wakeup (timer); } +/* Same policy as for hrtimer sleepers, see __hrtimer_setup_sleeper(). */ +static enum hrtimer_mode io_cqring_timer_mode (void ) +{ +if (IS_ENABLED (CONFIG_PREEMPT_RT ) &&rt_or_dl_task_policy (current)) +return HRTIMER_MODE_ABS_HARD ; +return HRTIMER_MODE_ABS ; +} +static int io_cqring_schedule_timeout (struct io_wait_queue *iowq,clockid_t clock_id,ktime_t start_time) { +enum hrtimer_mode mode =io_cqring_timer_mode ();ktime_t timeout; -hrtimer_init_on_stack (&iowq->t, clock_id,HRTIMER_MODE_ABS ); +hrtimer_init_on_stack (&iowq->t, clock_id, mode);if (iowq->min_timeout) { timeout =ktime_add_ns (iowq->min_timeout, start_time); iowq->t.function = io_cqring_min_timer_wakeup;
@@ -2510,7 +2520,7 @@ static int io_cqring_schedule_timeout(st }hrtimer_set_expires_range_ns (&iowq->t, timeout,0 ); -hrtimer_start_expires (&iowq->t,HRTIMER_MODE_ABS ); +hrtimer_start_expires (&iowq->t, mode);if (!READ_ONCE (iowq->hit_timeout))schedule ();
Greg Kroah-Hartman
maintainerPATCH 229/247 io_uring/waitid: prevent cancel reference wrap
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Junyeong Lee <[email protected]>
Commit 98787d3fa4e99564d2b2bc21255b21f670c450d0 upstream.
io_waitid packs the cancellation state into bit 31 of ->refs and uses bits 30:0 as a 31-bit reference counter:
#define IO_WAITID_CANCEL_FLAG BIT(31) #define IO_WAITID_REF_MASK GENMASK(30, 0)
__io_waitid_cancel() marks a request canceled, then increments the low bits of ->refs to claim completion ownership. When another path owns the request, the increment remains even though cancellation returns false. The request remains discoverable by cancellation, so repeated failed attempts can wrap the 31-bit reference field to zero. A later cancellation can claim ownership and complete the request a second time.
Use atomic_fetch_or() when setting the cancel flag and inspect the old flag value. The first cancel attempt continues to the existing ownership increment, preserving its wake and issuer handoff semantics. Later attempts see the cancel flag and return without incrementing the reference field.
This makes repeated failed cancellation attempts idempotent while leaving the first-cancel state transitions unchanged.
--- io_uring/waitid.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
io_uring/waitid.c +5 -2
@@ -161,9 +161,12 @@ static bool __io_waitid_cancel(struct io/* * Mark us canceled regardless of ownership. This will prevent a -* potential retry from a spurious wakeup. +* potential retry from a spurious wakeup. Only the first cancel +* attempt should take a reference for the ownership handoff. */ -atomic_or (IO_WAITID_CANCEL_FLAG , &iw->refs); +if (atomic_fetch_or (IO_WAITID_CANCEL_FLAG , &iw->refs) & +IO_WAITID_CANCEL_FLAG ) +return false;/* claim ownership */ if (atomic_fetch_inc (&iw->refs) &IO_WAITID_REF_MASK )
Greg Kroah-Hartman
maintainerPATCH 230/247 keys: Avoid the owner account dereference in named keyring lookup
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 51409aaa01f8602552c336009fd22b226b0cdf1d upstream.
Named keyring lookup must keep the storage containing the owner UID alive through the namespace mapping check. find_keyring_by_name() reads keyring->user->uid under keyring_name_lock, but that lock protects the keyring's name entry and allocation, not its separate key_user.
A named session-keyring join can overlap a privileged KEYCTL_CHOWN on another CPU. If the keyring holds the last reference to its old dynamic key_user and the ownership transfer succeeds, the following ordering is possible:
Named join Chown
find_keyring_by_name() keyctl_chown_key()
read_lock(keyring_name_lock) down_write(key->sem)
load old keyring->user
replace key->user and key->uid
up_write(key->sem)
key_put(key)
key_user_put(old user): free
read old user->uid
read_unlock(keyring_name_lock)Chown neither takes keyring_name_lock nor key_session_mutex, so it can free the old account between the pointer load and the UID read. The lookup then reads freed memory even though the keyring itself is alive.
Use keyring->uid for the mapping check. key_alloc() initializes this inline owner UID and keyctl_chown_key() updates it on chown. The existing name lock keeps its containing keyring allocated throughout the check, so lookup no longer depends on the account's lifetime. This also matches the owner UID used by the permission check.
KASAN report as below:
BUG: KASAN: slab-use-after-free in find_keyring_by_name+0x577/0x5d0
Read of size 4 at addr ffff8881128ae2ec by task keycase/500--- security/keys/keyring.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
security/keys/keyring.c +1 -1
@@ -1158,7 +1158,7 @@ struct key *find_keyring_by_name(const c* grants Search permission and that hasn't been revoked */ list_for_each_entry (keyring, &ns->keyring_name_list, name_link) { -if (!kuid_has_mapping (ns, keyring->user->uid)) +if (!kuid_has_mapping (ns, keyring->uid))continue ;if (test_bit (KEY_FLAG_REVOKED , &keyring->flags))
Greg Kroah-Hartman
maintainerPATCH 231/247 keys: Check the authorization payload in process keyring searches
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 0a0ec45bf577a9b4d4960567f20d3877ef480de9 upstream.
An authorization payload and its saved credentials must remain valid while search_process_keyrings_rcu() searches the requestor's keyrings. The function validates the authorization key, then separately loads payload.data[0] and unconditionally reads rka->cred. Validation does not prevent request_key_auth_revoke() from clearing the payload.
A request-key helper can assume authority and fork a descendant that inherits the authorization key. If the descendant misses in its own keyrings, it falls back to the saved requestor credentials. Successful target instantiation invalidates the authorization key without clearing the payload. After the helper exits, UMH_WAIT_PROC returns to the requester, which calls complete_request_key() and revokes that key.
With the descendant paused after validation, the paths can interleave as follows:
1. The descendant enters search_process_keyrings_rcu() under RCU and key_validate() succeeds.
2. The helper instantiates the target, invalidates the authorization key, and exits.
3. The requester resumes from UMH_WAIT_PROC, calls complete_request_key(), and revokes the authorization key. request_key_auth_revoke() sets its payload pointer to NULL.
4. The descendant loads NULL and dereferences rka->cred.
This NULL dereference can oops the kernel. RCU delays payload disposal but does not prevent the pointer from being cleared.
Load the payload with dereference_key_rcu() and require a non-NULL result before validating the authorization key and searching its saved credentials. A non-NULL payload and its credentials remain alive for the caller's RCU read-side section; a cleared payload skips the fallback search and follows the existing error selection.
KASAN report as below:
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000005: 0000 [#1] SMP KASAN NOPTI
KASAN: null-ptr-deref in range [0x0000000000000028-0x000000000000002f]
RIP: 0010:search_process_keyrings_rcu+0x32b/0x790--- security/keys/process_keys.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
security/keys/process_keys.c +2 -3
@@ -556,9 +556,8 @@ key_ref_t search_process_keyrings_rcu(st ) {const struct cred *cred = ctx->cred; -if (key_validate (cred->request_key_auth) ==0 ) { - rka = ctx->cred->request_key_auth->payload.data[0 ]; - + rka =dereference_key_rcu (cred->request_key_auth); +if (rka &&key_validate (cred->request_key_auth) ==0 ) {//// was search_process_keyrings() [ie. recursive] ctx->cred = rka->cred; key_ref =search_cred_keyrings_rcu (ctx);
Greg Kroah-Hartman
maintainerPATCH 232/247 keys: Protect the type name while describing a key
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit fced7238b7e80cf8aa688d5af976e4aa6e33c329 upstream.
keyctl_describe_key() must keep the key type's name alive until kasprintf() has consumed it. The retained key reference keeps the key and its description alive, but does not pin the module providing its type. The name is passed to kasprintf() without holding key->sem.
kvasprintf() uses the saved name pointer in two formatting passes, with a GFP_KERNEL allocation between them. With AF_RXRPC=m, a task that passes View permission before type retirement can overlap a privileged module unload in this order:
1. KEYCTL_DESCRIBE looks up the key, saves key->type->name in the kasprintf() arguments and completes the first formatting pass.
2. While the formatter is delayed before its second pass, af_rxrpc_exit() calls unregister_key_type(), which removes the type from the registry and waits for key_gc_keytype().
3. The collector takes key->sem for writing, retypes the retained key to key_type_dead and completes retirement. Unregistration and module exit return, allowing free_module() to release the type and name.
4. The formatter resumes its second pass and reads the saved name from released module storage, which can fault in string().
Hold key->sem for reading across kasprintf(). The collector then cannot retype the key or complete retirement until both formatting passes have finished. If retirement wins the lock first, formatting uses the core key_type_dead name instead. Release the semaphore immediately after kasprintf(), including on allocation failure, before copying to userspace.
Oops report as below:
BUG: unable to handle page fault for address: fffffbfff8054794
#PF: supervisor read access in kernel mode
#PF: error_code(0x0000) - not-present page
RIP: 0010:string+0x23f/0x470
Call Trace:
vsnprintf+0x330/0x1110--- security/keys/keyctl.c | 2 ++ 1 file changed, 2 insertions(+)
security/keys/keyctl.c +2 -0
@@ -677,12 +677,14 @@ okay:/* calculate how much information we're going to return */ ret = -ENOMEM ; +down_read (&key->sem); infobuf =kasprintf (GFP_KERNEL ,"%s;%d;%d;%08x;" , key->type->name,from_kuid_munged (current_user_ns (), key->uid),from_kgid_munged (current_user_ns (), key->gid), key->perm); +up_read (&key->sem);if (!infobuf) goto error2; infolen =strlen (infobuf);
Greg Kroah-Hartman
maintainerPATCH 233/247 keys: make keyring indexes independent of kernel addresses
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit de891c73c1cf41ac8de12c07fa2c84d6a912ad0c upstream.
KEYCTL_READ returns the serial numbers in a keyring in associative-array traversal order. The first word of the index is a public, deterministic hash of the type pointer, domain pointer and description. An unprivileged user can therefore insert keys with known descriptions, predict their order for each possible KASLR slide, and recover the kernel image address. On an x86-64 build with 16 MiB alignment, 45 user keys suffice to distinguish the candidate slides.
Remove the addresses from the whole index, not just its first hash word. Assign each key type and domain a nonzero 64-bit ID and hash those IDs and the description with a once-initialized SipHash key. Use the full IDs in the later index chunks as well. Truncating or hashing the IDs there would lose the guarantee that distinct type/domain/description tuples have a differing index bit.
Allocate IDs lazily since private key types need not be registered. Cache them in the index key so tree walks and copies of an existing index do not need to dereference a type descriptor that may have been unregistered. Keep the 32-bit chunk layout and diff_objects() bit offsets consistent, and retain the separate root slot for keyrings used by recursive search. The key comparison, permissions and userspace data format are unchanged; only the address-dependent in-memory ordering is replaced.
--- include/linux/key-type.h | 1 include/linux/key.h | 5 + security/keys/keyring.c | 150 +++++++++++++++++++++++++---------------------- 3 files changed, 86 insertions(+), 70 deletions(-)
include/linux/key-type.h +1 -0
@@ -158,6 +158,7 @@ struct key_type { const void *in, const void *in2);/* internal fields */ +atomic64_t index_id;/* Opaque keyring index ID */ struct list_head link;/* link in types list */ struct lock_class_key lock_class;/* key->sem lock class */ } __randomize_layout;
include/linux/key.h +5 -0
@@ -107,6 +107,7 @@ struct keyring_name;struct key_tag {struct rcu_head rcu; +atomic64_t index_id;/* Opaque keyring index ID */ refcount_t usage;bool removed;/* T when subject removed */ };
@@ -129,6 +130,8 @@ struct keyring_index_key {struct key_type *type;struct key_tag *domain_tag;/* Domain of operation */ const char *description; +u64 type_id;/* Cached index IDs */ +u64 domain_id; };union key_payload {
@@ -251,6 +254,8 @@ struct key {struct key_type *type;/* type of key */ struct key_tag *domain_tag;/* Domain of operation */ char *description; +u64 type_id; +u64 domain_id; }; };
security/keys/keyring.c +80 -70
224 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 234/247 keys: Protect the read method check against type removal
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 925c84e3cc21caf09de92d9bcafab0147790debf upstream.
keyctl_read_key() checks key->type->read without holding key->sem. A reference keeps the key alive, but does not pin the module containing its type. A surviving RxRPC key can therefore be read while AF_RXRPC is being unloaded:
KEYCTL_READ task Module unload and key GC
---------------- ------------------------
lookup_user_key()
permission / possession checks
load key->type
af_rxrpc_exit()
unregister_key_type()
GC: down_write(key->sem)
GC: retype to key_type_dead
GC: up_write(key->sem)
unregister_key_type() returns
free_module()read saved type's read member
The final access can read freed module storage. The read invocation in __keyctl_read_key() is already protected by key->sem, but the earlier method check is outside that critical section.
Move the method check into __keyctl_read_key(), after key_validate() and under its existing read hold on key->sem. The check and invocation then use the same protected type for length queries and every read retry. The GC cannot retype the key until the semaphore is released, and type unregistration waits for that GC pass before the module can be freed.
Return -EOPNOTSUPP when validation succeeds and the type has no read method. A temporary buffer may now be allocated before this result; allocation and copying to userspace remain outside the semaphore.
--- security/keys/keyctl.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-)
security/keys/keyctl.c +6 -7
@@ -808,8 +808,12 @@ static long __keyctl_read_key(struct keydown_read (&key->sem); ret =key_validate (key); -if (ret ==0 ) - ret = key->type->read (key, buffer, buflen); +if (ret ==0 ) { +if (key->type->read) + ret = key->type->read (key, buffer, buflen); +else + ret = -EOPNOTSUPP ; + }up_read (&key->sem);return ret; }
@@ -863,11 +867,6 @@ long keyctl_read_key(key_serial_t keyid,/* the key is probably readable - now try to read it */ can_read_key: -if (!key->type->read) { - ret = -EOPNOTSUPP ; - goto key_put_out; - } -if (!buffer || !buflen) {/* Get the key length from the read method */ ret =__keyctl_read_key (key,NULL ,0 );
Greg Kroah-Hartman
maintainerPATCH 235/247 KEYS: Fix key_reject_and_link() race with keyring restriction
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adrian Martinez <[email protected]>
commit 0b157166e612b70f98a332b6c7be7eac6f8e9593 upstream.
The restrict_link check in key_reject_and_link() is done before taking the keyring semaphore, racing with a concurrent keyring_restrict() that installs the restriction while holding the semaphore in write mode.
Move the check to after __key_link_lock(), so it is done under the semaphore, matching the pattern used in __key_create_or_update().
--- security/keys/key.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
security/keys/key.c +10 -3
@@ -587,11 +587,18 @@ int key_reject_and_link(struct key *key, ret = -EBUSY ;if (keyring) { -if (keyring->restrict_link) -return -EPERM ; - link_ret =__key_link_lock (keyring, &key->index_key);if (link_ret ==0 ) { +/* +* Check the restriction under the keyring semaphore. +* keyring_restrict() installs it while holding the +* semaphore, so testing it beforehand races with a +* concurrent restriction install. +*/ +if (keyring->restrict_link) { +__key_link_end (keyring, &key->index_key, edit); +return -EPERM ; + } link_ret =__key_link_begin (keyring, &key->index_key, &edit);if (link_ret <0 )__key_link_end (keyring, &key->index_key, edit);
Greg Kroah-Hartman
maintainerPATCH 236/247 KEYS: trusted: Fix blob allocation size in tpm2_key_decode()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefano Garzarella <[email protected]>
commit 11077cbcc2695f71c944a84a5f08c6672ab759f1 upstream.
tpm2_key_decode() allocates 4 bytes more than needed. The ASN.1 callbacks tpm2_key_priv() and tpm2_key_pub() provide the lengths of TPM2B_PRIVATE and TPM2B_PUBLIC, so ctx.priv_len and ctx.pub_len already account for the 2-byte size field each of those structures starts with.
I noticed this while reviewing commit 114f00d738f1 ("KEYS: trusted:
Fix tpm2_load_cmd() boundary check"), which correctly reports ctx.priv_len + ctx.pub_len as the decoded blob size [1].
Let's allocate exactly that amount, matching the data copied into the blob.
[1] https://lore.kernel.org/linux-integrity/apfoKo-BdwaLXtkT@sgarzare-redhat/
--- security/keys/trusted-keys/trusted_tpm2.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
security/keys/trusted-keys/trusted_tpm2.c +1 -1
@@ -124,7 +124,7 @@ static int tpm2_key_decode(struct trusteif (ctx.priv_len + ctx.pub_len >MAX_BLOB_SIZE )return -EINVAL ; - blob =kmalloc (ctx.priv_len + ctx.pub_len +4 ,GFP_KERNEL ); + blob =kmalloc (ctx.priv_len + ctx.pub_len,GFP_KERNEL );if (!blob)return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 237/247 keys/trusted_keys: return immediately after TPM unseal failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srish Srinivasan <[email protected]>
commit f92d0ccb05bf9089072cb067dda0dffd5394c4ef upstream.
trusted_tpm_unseal() proceeds to pcrlock() when the TPM unseal operation fails. If pcrlock() succeeds, its return value overwrites the unseal error, causing key instantiation to succeed.
Return immediately when unseal fails to preserve the original error.
--- security/keys/trusted-keys/trusted_tpm1.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
security/keys/trusted-keys/trusted_tpm1.c +3 -1
@@ -970,8 +970,10 @@ static int trusted_tpm_unseal(struct tru ret =tpm2_unseal_trusted (chip, p, options); else ret =key_unseal (p, options); -if (ret <0 ) +if (ret <0 ) {pr_info ("key_unseal failed (%d)\n" , ret); + goto out; + }if (options->pcrlock) { ret =pcrlock (options->pcrlock);
Greg Kroah-Hartman
maintainerPATCH 238/247 asymmetric_keys: reject trust keys without IDs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 9695df3b1db4ac4534274d38ee16e3b9b0bf910e upstream.
The PKCS#8 parser deliberately leaves the asym_key_ids payload slot empty. key_or_keyring_common() unconditionally dereferences that slot when a PKCS#8 key is supplied to a key_or_keyring restriction. Both the plain and :chain forms reach this branch, allowing an unprivileged caller to trigger a NULL pointer dereference through KEYCTL_RESTRICT_KEYRING followed by add_key().
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000000 KASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007] RIP: 0010:key_or_keyring_common (crypto/asymmetric_keys/restrict.c:205 crypto/asymmetric_keys/restrict.c:279) Call Trace: <TASK> __key_create_or_update (security/keys/key.c:884) key_create_or_update (security/keys/key.c:1021) __do_sys_add_key (security/keys/keyctl.c:134) do_syscall_64 (arch/x86/entry/common.c:52 arch/x86/entry/common.c:83) entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:130) </TASK> Kernel panic - not syncing: Fatal exception
Reject an asymmetric restriction key without key IDs. A PKCS#8 private key cannot identify the signer of a candidate certificate and is not a valid trust anchor.
--- crypto/asymmetric_keys/restrict.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
crypto/asymmetric_keys/restrict.c +6 -2
@@ -240,10 +240,14 @@ static int key_or_keyring_common(structif (IS_ERR (key)) key =NULL ; }else if (trusted->type == &key_type_asymmetric) { +const struct asymmetric_key_ids *kids;const struct asymmetric_key_id **signer_ids; - signer_ids = (const struct asymmetric_key_id **) -asymmetric_key_ids (trusted)->id; + kids =asymmetric_key_ids (trusted); +if (!kids) +return -ENOKEY ; + + signer_ids = (const struct asymmetric_key_id **)kids->id;/* * The auth_ids come from the candidate key (the
Greg Kroah-Hartman
maintainerPATCH 239/247 ftrace: Initialize modname and offset in print_rec()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aaron Ahmed <[email protected]>
commit e1f339ff3b83857b93baf8b88186275a413d445e upstream.
print_rec() leaves 'modname' and 'offset' uninitialized and kallsyms_lookup() only sets them on success. When the lookup fails like when a module is being loaded or unloaded, 'modname' holds a garbage value, passes the 'if (modname)' check, and is dereferenced by seq_printf().
Oops: general protection fault RIP: 0010:string+0x48/0xe0 Call Trace: vsnprintf+0x1f5/0x650 seq_printf+0x8e/0xb0 print_rec+0x6c/0xc0 t_show+0x4c/0x440 seq_read_iter+0x119/0x480
This can be triggered by reading available_filter_functions while a module is being loaded or unloaded.
Initialize both variables so a failed lookup skips the module name.
--- kernel/trace/ftrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/trace/ftrace.c +2 -2
@@ -4316,9 +4316,9 @@ subsys_initcall(ftrace_check_for_weak_fustatic int print_rec (struct seq_file *m,unsigned long ip) { -unsigned long offset; +unsigned long offset =0 ;char str[KSYM_SYMBOL_LEN ]; -char *modname; +char *modname =NULL ;const char *ret; ret =kallsyms_lookup (ip,NULL , &offset, &modname, str);
Greg Kroah-Hartman
maintainerPATCH 240/247 coredump: hold RCU while releasing parked threads
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 61d58591aa0188bf2463e263962256316ff8b576 upstream.
coredump_finish() releases the parked threads by clearing ->task in their core_thread entry and calling wake_up_process() on each of them. It does that without holding a reference on the task and without being inside rcu.
But calling wake_up_process(task) without rcu here isn't safe. A parked thread doesn't need that wakeup to leave. A spurious wakeup or a preemption after the store is enough for the task to go away.
So if the coredump client is preempted between the store and wake_up_process() the thread can exit and be freed in the meantime and try_to_wake_up() takes pi_lock in freed memory.
Hold rcu across the loop.
--- fs/coredump.c | 3 +++ 1 file changed, 3 insertions(+)
fs/coredump.c +3 -0
@@ -474,6 +474,8 @@ static void coredump_finish(bool core_du current->signal->core_state =NULL ;spin_unlock_irq (¤t->sighand->siglock); +/* A released thread may exit and be freed before it is woken. */ +guard (rcu)();while ((curr = next) !=NULL ) { next = curr->next; task = curr->task;
@@ -482,6 +484,7 @@ static void coredump_finish(bool core_du* ->task == NULL before we read ->next. */ smp_mb (); +/* Any wakeup now lets the thread exit, rcu keeps it alive. */ curr->task =NULL ;wake_up_process (task); }
Greg Kroah-Hartman
maintainerPATCH 241/247 signal: only SIGKILL and the freezers interrupt a coredumping task
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 563d606b93d7a1d23512832fc252d32c68860d87 upstream.
For quite a while now coredump has allowed either SIGKILL or freezing to interrupt an ongoing coredump. Since we seem to like it complicated "freezing" can mean a lot of things:
(1) Power Management induced freezing
(2) cgroup v1 freezer controller induced freezing
(3) cgroup v2 freezer controller induced freezing
So (1) and (2) are handled by checking freezing() but (3) isn't.
(3) uses cgroup_freeze_task() which sets JOBCTL_TRAP_FREEZE and calls signal_wake_up() on every task in the cgroup. The trap isn't handled by the coredump code.
Which means the current logic is inconsistent. Power and cgroup v1 freeze and abort the coredump. With cgroup v2 it depends on where the core goes. A dump to a file completes and the cgroup v2 freeze has to wait for it to finish. When dumping to a pipe or socket the dump is interrupted at the next write because of trap's TIF_SIGPENDING. Which is it? Let's be consistent and align (1)-(3): freezing interrupts an ongoing coredump and doesn't make it wait until the dump is done.
All three freezers go through signal_wake_up() and so set TIF_SIGPENDING on the dumper. And once zap_threads() has set core_state that flag can't mean anything else anymore. prepare_signal() drops every signal but SIGKILL for the group, the dying threads don't retarget shared signals to the dumper, and zap_process() cleared the pending job control traps. So the flag is the thing to check. Let dump_interrupted() test task_sigpending() and nothing else. That is also what the pipe and socket writes already fail on. TIF_NOTIFY_SIGNAL is left out on purpose, task work must not cut a dump short.
A seized tracee that gets PTRACE_INTERRUPT during the dump is cut short the same way. It already was for pipes and sockets.
The one freeze that check can miss is one requested before the dump started. zap_threads() clears TIF_SIGPENDING and the cgroup v2 freezer only wakes a task once while its JOBCTL_TRAP_FREEZE isn't part of JOBCTL_PENDING_MASK and survives zap_process(). So refuse to start the dump when freezing() is true or the trap is pending. The task then exits without dumping, which is what happens today when the freeze interrupts the dump at the first write.
--- fs/coredump.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-)
fs/coredump.c +5 -8
@@ -420,7 +420,9 @@ static int zap_threads(struct task_strucint nr = -EAGAIN ;spin_lock_irq (&tsk->sighand->siglock); -if (!(signal->flags &SIGNAL_GROUP_EXIT ) && !signal->group_exec_task) { +/* A freeze requested before the dump would be lost with TIF_SIGPENDING. */ +if (!(signal->flags &SIGNAL_GROUP_EXIT ) && !signal->group_exec_task && + !freezing (tsk) && !(tsk->jobctl &JOBCTL_TRAP_FREEZE )) {/* Allow SIGKILL, see prepare_signal() */ signal->core_state = core_state; nr =zap_process (signal, exit_code);
@@ -492,13 +494,8 @@ static void coredump_finish(bool core_dustatic bool dump_interrupted (void ) { -/* -* SIGKILL or freezing() interrupt the coredumping. Perhaps we -* can do try_to_freeze() and check __fatal_signal_pending(), -* but then we need to teach dump_write() to restart and clear -* TIF_SIGPENDING. -*/ -return fatal_signal_pending (current) ||freezing (current); +/* Only SIGKILL and the freezers set it after zap_threads(). */ +return task_sigpending (current); }static void wait_for_dump_helpers (struct file *file)
Greg Kroah-Hartman
maintainerPATCH 242/247 signal: dont retarget shared signals in a dying thread group
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit c0e659511d4f49087da095a95799edb5b775a705 upstream.
If the calling thread has blocked a signal then retarget_shared_pending() slingshots a shared pending signal to a sibling thread. Today it only skips PF_EXITING threads but not a coredumping thread.
But if SIGNAL_GROUP_EXIT is set no thread in the thread-group can dequeue such signals anymore as get_signal() sends SIGKILL to every thread and prepare_signal() drops any other signal.
exit_signals() also returns early on SIGNAL_GROUP_EXIT. But neither sigprocmask() nor the mask restore in sigtimedwait() do.
Say a thread sleeps in sigtimedwait() and a sibling thread crashes. The sleeping thread gets woken by the zap call. It restores its mask on the way out and retargets a signal that was queued for the coredumping process. That means TIF_SIGPENDING is set on the coredumping task which zap_threads() had cleared. So a blocking write sees TIF_SIGPENDING and truncates the dump.
Stop retargeting signals when SIGNAL_GROUP_EXIT is set and avoid needlessly truncating coredumps.
--- kernel/signal.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/signal.c +4 -0
@@ -2999,6 +2999,10 @@ static void retarget_shared_pending(strusigset_t retarget;struct task_struct *t; +/* Nobody dequeues them in a dying group, see get_signal(). */ +if (tsk->signal->flags &SIGNAL_GROUP_EXIT ) +return ; +sigandsets (&retarget, &tsk->signal->shared_pending.signal, which);if (sigisemptyset (&retarget))return ;
Greg Kroah-Hartman
maintainerPATCH 243/247 ptrace: refuse to change the signal mask of a user worker
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit cabc249e6560bee7bdfee9fbcb7ce4e951dcfd41 upstream.
A user worker is created with every signal other than SIGKILL and SIGSTOP blocked. It never runs user code and that mask is what keeps get_signal() from dequeuing anything else for it. complete_signal() never picks a thread that blocks the signal, tkill() queues on the worker but nothing dequeues it. ptrace_signal() requeues an injected signal that the tracee blocks.
PTRACE_SETSIGMASK is the only way to change that mask from the outside. A tracer that clears it makes the worker eligible for every signal. Whatever the worker then dequeues it can only act on by leaving.
Refuse PTRACE_SETSIGMASK for a user worker with -EPERM, the way ptrace_attach() refuses a kernel thread. A worker is guaranteed to only ever dequeue SIGKILL or SIGSTOP and an injected signal stays pending on it, which is what already happens when the mask isn't touched.
Taking the request and quietly leaving the mask alone was the other option, the way set_current_blocked() keeps SIGKILL and SIGSTOP unblocked whatever userspace asks for. But then a tracer gets success back with nothing changed and no way to tell that apart from a mask that took effect.
--- kernel/ptrace.c | 6 ++++++ 1 file changed, 6 insertions(+)
kernel/ptrace.c +6 -0
@@ -1086,6 +1086,12 @@ int ptrace_request(struct task_struct *ccase PTRACE_SETSIGMASK : {sigset_t new_set; +/* A user worker only ever takes SIGKILL and SIGSTOP. */ +if (child->flags &PF_USER_WORKER ) { + ret = -EPERM ; +break ; + } +if (addr !=sizeof (sigset_t)) { ret = -EINVAL ;break ;
Greg Kroah-Hartman
maintainerPATCH 244/247 fork: release the files of a failed fork after sched_cancel_fork()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 296a98c1fa50778c3b31eebed1a3f903f9684349 upstream.
Reorder copy_process() cleanup so sched_fork() taking scx_fork_rwsem scx_pre_fork() is safe and isn't held around exiting files. Right now, a fork that fails while another thread closed the bpf link fd will deadlock against its own read side. It also blocks every fork on the system:
copy_process() holds scx_fork_rwsem for read
exit_files()
close_files()
filp_close_sync()
bpf_scx_unreg()
kthread_flush_work() waits for the disable work
scx_root_disable()
percpu_down_write(&scx_fork_rwsem)
Simply release the child's files after sched_cancel_fork() dropped the lock. The task starts out as a copy of its parent so p->files points to the parent's table until copy_files() replaces it. exit_files() must not run for a fork that failed before that. Clear p->files up front so exit_files() is a no-op for those and make copy_files() set it explicitly for CLONE_FILES.
--- kernel/fork.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
kernel/fork.c +6 -3
@@ -1814,6 +1814,7 @@ static int copy_files(unsigned long clonif (clone_flags &CLONE_FILES ) {atomic_inc (&oldf->count); + tsk->files = oldf;return 0 ; }
@@ -2305,6 +2306,8 @@ __latent_entropy struct task_struct *copINIT_LIST_HEAD (&p->sibling);rcu_copy_process (p); p->vfork_done =NULL ; +/* Set by copy_files(), exit_files() on the error path skips NULL. */ + p->files =NULL ;spin_lock_init (&p->alloc_lock);init_sigpending (&p->pending);
@@ -2402,7 +2405,7 @@ __latent_entropy struct task_struct *cop goto bad_fork_cleanup_semundo; retval =copy_fs (clone_flags, p);if (retval) - goto bad_fork_cleanup_files; + goto bad_fork_cleanup_semundo; retval =copy_sighand (clone_flags, p);if (retval) goto bad_fork_cleanup_fs;
@@ -2681,8 +2684,6 @@ bad_fork_cleanup_sighand:__cleanup_sighand (p->sighand); bad_fork_cleanup_fs:exit_fs (p);/* blocking */ -bad_fork_cleanup_files: -exit_files (p);/* blocking */ bad_fork_cleanup_semundo:exit_sem (p); bad_fork_cleanup_security:
@@ -2693,6 +2694,8 @@ bad_fork_cleanup_perf:perf_event_free_task (p); bad_fork_sched_cancel_fork:sched_cancel_fork (p); +/* ->release() of a file may need scx_fork_rwsem for write. */ +exit_files (p);/* blocking */ bad_fork_cleanup_policy:lockdep_free_task (p);#ifdef CONFIG_NUMA
Greg Kroah-Hartman
maintainerPATCH 245/247 pid_namespace: prevent TIF_NOTIFY_SIGNAL from interrupting the reaper
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 5c0985dd3c32fc2bbd0e8beaf13cf52cd97376a2 upstream.
Since commit 7fea700e04bd ("zap_pid_ns_processes: clear TIF_NOTIFY_SIGNAL along with TIF_SIGPENDING") zap_pid_ns_processes() clears TIF_NOTIFY_SIGNAL before every kernel_wait4() call. Otherwise kernel_wait4() doesn't sleep and returns -ERESTARTSYS if signal_pending() is true and the reaper busy-waits.
But clearing TIF_NOTIFY_SIGNAL doesn't fix it. It can get raised again. For example, klp_send_signals() sets it raw against any task that hasn't transitioned yet. And it keeps sending it until the livepatch finishes.
The sleep loop waiting for pid_allocated to drop has the same problem and it doesn't even clear anything. So a schedule() in TASK_INTERRUPTIBLE returns immediately.
Use a no_notify_signal guard. signal_pending() will ignore TIF_NOTIFY_SIGNAL and the pid namespace reaper sleeps until a child exits or free_pid() wakes it.
--- kernel/pid_namespace.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/pid_namespace.c +2 -1
@@ -216,9 +216,10 @@ void zap_pid_ns_processes(struct pid_nam* kernel_wait4() will also block until our children traced from the * parent namespace are detached and become EXIT_DEAD. */ +/* Task work must not busy-loop the reaper, see signal_pending(). */ +guard (no_notify_signal)();do {clear_thread_flag (TIF_SIGPENDING ); -clear_thread_flag (TIF_NOTIFY_SIGNAL ); rc =kernel_wait4 (-1 ,NULL , __WALL,NULL ); }while (rc != -ECHILD );
Greg Kroah-Hartman
maintainerPATCH 246/247 signal: allow taks to temporarily block TIF_NOTIFY_SIGNAL
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 22b7f491be8f93ff72de0a3fe02b8ee9e64d3f21 upstream.
TIF_NOTIFY_SIGNAL is used to kick a task in uninterruptible sleep to return to userspace and run task work and then go back to sleep. This mechanism works well but breaks e.g., coredumps. dump_interrupted() only allows fatal signals to interrupt a coredump and the whole regular write path going to actual filesystems is impervious to TIF_NOTIFY_SIGNAL as well.
Add PF_NO_NOTIFY_SIGNAL and helpers to raise and restore it. This is the same approach as memalloc_nofs_save(). signal_pending() will not report a fake pending signal via TIF_NOTIFY_SIGNAL if inside a PF_NO_NOTIFY_SIGNAL section.
No functional changes.
--- include/linux/sched.h | 2 +- include/linux/sched/signal.h | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-)
include/linux/sched.h +1 -1
@@ -1712,7 +1712,7 @@ extern struct pid __rcu *cad_pid;* I am cleaning dirty pages from some other bdi. */ #define PF_KTHREAD 0x00200000/* I am a kernel thread */ #define PF_RANDOMIZE 0x00400000/* Randomize virtual address space */ -#define PF__HOLE__00800000 0x00800000 +#define PF_NO_NOTIFY_SIGNAL 0x00800000/* see no_notify_signal_save() */ #define PF__HOLE__01000000 0x01000000#define PF__HOLE__02000000 0x02000000#define PF_NO_SETAFFINITY 0x04000000/* Userland is not allowed to meddle with cpus_mask */
include/linux/sched/signal.h +25 -2
@@ -2,6 +2,7 @@#ifndef _LINUX_SCHED_SIGNAL_H#define _LINUX_SCHED_SIGNAL_H +#include <linux/cleanup.h> #include <linux/rculist.h> #include <linux/signal.h> #include <linux/sched.h>
@@ -380,14 +381,36 @@ static inline int task_sigpending(structreturn unlikely (test_tsk_thread_flag (p,TIF_SIGPENDING )); } +/* Prevent TIF_NOTIFY_SIGNAL from interrupting this task. */ +static inline unsigned int no_notify_signal_save (void ) +{ +unsigned int flags = current->flags; + + current->flags |=PF_NO_NOTIFY_SIGNAL ; +return flags; +} + +/* Restore the previous PF_NO_NOTIFY_SIGNAL state. */ +static inline void no_notify_signal_restore (unsigned int flags) +{ +current_restore_flags (flags,PF_NO_NOTIFY_SIGNAL ); +} + +DEFINE_LOCK_GUARD_0 (no_notify_signal, + _T->flags =no_notify_signal_save (), +no_notify_signal_restore (_T->flags), + unsigned int flags) +static inline int signal_pending (struct task_struct *p) {/* * TIF_NOTIFY_SIGNAL isn't really a signal, but it requires the same * behavior in terms of ensuring that we break out of wait loops -* so that notify signal callbacks can be processed. +* so that notify signal callbacks can be processed. Not for a task +* that asked not to be interrupted by it, see no_notify_signal_save(). */ -if (unlikely (test_tsk_thread_flag (p,TIF_NOTIFY_SIGNAL ))) +if (unlikely (test_tsk_thread_flag (p,TIF_NOTIFY_SIGNAL )) && +likely (!(READ_ONCE (p->flags) &PF_NO_NOTIFY_SIGNAL )))return 1 ;return task_sigpending (p); }
Greg Kroah-Hartman
maintainerPATCH 247/247 fanotify: Fix crash in fanotify_init(2)
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
commit 0c0214df28f0dba8de084cb4dedc0c459dfbc083 upstream.
The rrror handling in fanotify_init(2) is buggy and overwrites 'fd' before calling put_unused_fd() leading to possible access beyond the end of fd bitmap. Fix it.
--- fs/notify/fanotify/fanotify_user.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/notify/fanotify/fanotify_user.c +1 -1
@@ -1552,8 +1552,8 @@ SYSCALL_DEFINE2(fanotify_init, unsigned file =anon_inode_getfile_fmode ("[fanotify]" , &fanotify_fops, group, f_flags,FMODE_NONOTIFY );if (IS_ERR (file)) { - fd =PTR_ERR (file);put_unused_fd (fd); + fd =PTR_ERR (file); goto out_destroy_group; }fd_install (fd, file);
# Librecast Test Results
044/044 [ OK ] liblcrq
010/010 [ OK ] libmld
120/120 [ OK ] liblibrecast
CPU/kernel: Linux auntie 6.12.115-rc1-gadc8e434cf08 #1 SMP PREEMPT_DYNAMIC Wed Oct 28 17:52:53 -00 2026 x86_64 AMD Ryzen 9 9950X 16-Core Processor AuthenticAMD GNU/Linux
Quoted 9 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
The whole patch series can be found in one patch at:
Quoted 8 lines
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.thanks,
greg k-h
On ARCH_BRCMSTB using 32-bit and 64-bit ARM kernels, build tested on BMIPS_GENERIC:
Signature · 1 line
Florian
Am 28.10.2026 um 17:56 schrieb Greg Kroah-Hartman:
Quoted 4 lines
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Builds, boots and works on my 2-socket Ivy Bridge Xeon E5-2697v2 server. No dmesg oddities or regressions found.
Beste Grüße,
Peter Schneider
Signature · 8 lines
Climb the mountain not to plant your flag, but to embrace the challenge, enjoy the air and behold the view. Climb it so you can see the world, not so the world can see you. -- David McCullough Jr. OpenPGP: 0xA3828BD796CCE11A8CADE8866E3A92C92C3FF244 Download: https://www.peters-netzplatz.de/download/pschneider1968_pub.asc https://keys.mailvelope.com/pks/lookup?op=get&[email protected] https://keys.mailvelope.com/pks/lookup?op=get&[email protected]
Greg Kroah-Hartman wrote on Wed, Oct 28, 2026 at 05:56:43PM +0100:
Quoted 5 lines
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Quoted 8 lines
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
The whole patch series can be found in one patch at:
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.
Tested adc8e434cf08 ("Linux 6.12.115-rc1") on:
- arm i.MX6ULL (Armadillo 640)
- arm64 i.MX8MP (Armadillo G4)
- arm64 i.MX8ULP (Armadillo IoT A9E)
No obvious regression in dmesg or basic tests:
Signature · 1 line
Dominique Martinett
Hi!
Quoted 4 lines
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
CIP testing did not find any problems here:
https://gitlab.com/cip-project/cip-testing/linux-stable-rc-ci/-/tree/linux-6.12.y
Best regards,
Pavel
Hi!
Quoted 4 lines
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
What is up with these?
They don't have usual "Commit upstream XXX" markings. They do have commit ids in the sign-off area (which is a logical place), except that those hashes don't exist in mainline.
Best regards,
Pavel
Quoted 273 lines
Bernard Pidoux <[email protected]>
rose: purge rose_neigh->queue on final teardownBernard Pidoux <[email protected]>
ax25: bound REJ-driven fast retransmits with the existing N2 counterBernard Pidoux <[email protected]>
rose: hold a reference on incoming sockets queued foraccept()Bernard Pidoux <[email protected]>
rose: don't warn on stray CALL_ACCEPTED/CLEAR_CONFIRMATION in state 3Bernard Pidoux <[email protected]>
rose: usetimer_shutdown_sync()for t0timer teardownBernard Pidoux <[email protected]>
rose: guardrose_transmit_link()against a NULL neighbourBernard Pidoux <[email protected]>
rose: keep the route needed for routing loop detectionBernard Pidoux <[email protected]>
rose: don't free fd-owned sockets when reaping in the heartbeatBernard Pidoux <[email protected]>
rose: clear neighbour pointer inrose_kill_by_device()Bernard Pidoux <[email protected]>
rose: release netdev ref and destroy orphaned incoming socketsBernard Pidoux <[email protected]>
rose: disconnect orphanedSTATE_2sockets when device is goneBernard Pidoux <[email protected]>
rose: setSOCK_DESTROYinrose_kill_by_device()for prompt cleanup-------------
Diffstat:
Makefile | 4 +- arch/nios2/include/asm/checksum.h | 2 +- arch/s390/mm/fault.c | 11 +- arch/s390/pci/pci_sysfs.c | 3 + arch/x86/hyperv/hv_init.c | 3 +- arch/x86/kernel/kvm.c | 32 +- arch/x86/kvm/mmu/mmu.c | 4 +- arch/x86/kvm/vmx/nested.c | 4 +- block/blk-zoned.c | 37 +- block/blk.h | 4 +- block/bsg-lib.c | 13 +- block/genhd.c | 2 +- crypto/asymmetric_keys/restrict.c | 8 +- drivers/base/regmap/internal.h | 1 + drivers/base/regmap/regcache-maple.c | 9 +- drivers/base/regmap/regcache.c | 18 +- drivers/gpio/gpio-mxc.c | 69 ++-- drivers/gpio/gpiolib.c | 9 +- drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c | 6 + drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c | 23 +- drivers/gpu/drm/amd/amdgpu/sdma_v3_0.c | 25 +- drivers/gpu/drm/amd/amdgpu/vce_v3_0.c | 2 +- drivers/gpu/drm/drm_exec.c | 77 +++-- drivers/gpu/drm/i915/display/intel_dmc.c | 21 +- drivers/gpu/drm/vc4/vc4_hdmi.c | 20 +- drivers/gpu/drm/xe/xe_exec.c | 7 +- drivers/gpu/drm/xe/xe_vm.c | 31 +- drivers/gpu/drm/xe/xe_vm.h | 2 + drivers/hv/channel_mgmt.c | 12 +- drivers/hv/connection.c | 1 - drivers/hv/vmbus_drv.c | 1 - drivers/i2c/busses/i2c-qcom-cci.c | 4 +- drivers/i2c/busses/i2c-viai2c-wmt.c | 22 +- drivers/md/dm-cache-target.c | 59 ++-- drivers/md/dm-crypt.c | 3 +- drivers/md/dm-ebs-target.c | 3 +- drivers/md/dm-integrity.c | 6 +- drivers/net/ethernet/broadcom/genet/bcmgenet.c | 10 + drivers/net/wireless/intersil/p54/fwio.c | 42 ++- drivers/pci/pci.c | 15 +- drivers/pinctrl/pinctrl-amd.c | 9 + drivers/pinctrl/qcom/pinctrl-ipq5018.c | 10 +- drivers/power/supply/ds2780_battery.c | 2 +- drivers/power/supply/generic-adc-battery.c | 9 +- drivers/s390/net/ctcm_mpc.c | 3 +- drivers/scsi/libiscsi.c | 14 +- drivers/scsi/libsas/sas_expander.c | 14 +- drivers/scsi/mpi3mr/mpi3mr_app.c | 2 +- drivers/scsi/scsi_transport_fc.c | 6 +- drivers/scsi/scsi_transport_iscsi.c | 2 +- drivers/scsi/scsi_transport_sas.c | 6 +- drivers/scsi/st.c | 18 +- drivers/scsi/xen-scsifront.c | 1 + drivers/soc/tegra/fuse/tegra-apbmisc.c | 2 +- drivers/spi/spi-tegra114.c | 7 + drivers/target/iscsi/iscsi_target_configfs.c | 26 +- drivers/ufs/core/ufs_bsg.c | 2 +- fs/afs/internal.h | 2 + fs/afs/super.c | 2 +- fs/autofs/waitq.c | 25 +- fs/coredump.c | 16 +- fs/ext4/ext4.h | 2 + fs/ext4/extents_status.c | 7 +- fs/ext4/extents_status.h | 1 + fs/ext4/super.c | 13 +- fs/fat/dir.c | 44 ++- fs/fcntl.c | 4 +- fs/namei.c | 3 +- fs/notify/fanotify/fanotify_user.c | 25 +- fs/notify/mark.c | 11 + fs/ntfs3/ntfs_fs.h | 1 + fs/ntfs3/super.c | 29 +- fs/ocfs2/dlm/dlmcommon.h | 2 + fs/ocfs2/dlm/dlmdebug.c | 5 +- fs/ocfs2/dlm/dlmrecovery.c | 2 +- fs/open.c | 23 +- fs/pipe.c | 6 +- fs/smb/client/cifssmb.c | 13 +- fs/smb/client/connect.c | 21 +- fs/smb/client/smb2ops.c | 7 +- fs/smb/server/smb2pdu.c | 5 + fs/tracefs/event_inode.c | 16 +- fs/unicode/utf8-core.c | 21 +- fs/xfs/libxfs/xfs_sb.c | 17 +- fs/xfs/xfs_fsmap.c | 2 +- fs/xfs/xfs_ioctl.c | 2 +- fs/xfs/xfs_iops.c | 2 +- include/drm/drm_exec.h | 15 +- include/linux/bsg-lib.h | 3 +- include/linux/cgroup-defs.h | 5 +- include/linux/fs.h | 6 +- include/linux/fsnotify_backend.h | 1 + include/linux/futex.h | 14 +- include/linux/huge_mm.h | 2 +- include/linux/io_uring_types.h | 3 + include/linux/ipv6.h | 22 ++ include/linux/key-type.h | 1 + include/linux/key.h | 5 + include/linux/maple_tree.h | 4 + include/linux/mm_types.h | 3 + include/linux/power_supply.h | 6 +- include/linux/sched.h | 2 +- include/linux/sched/signal.h | 27 +- include/linux/sched/user.h | 8 +- include/linux/srcutiny.h | 4 - include/linux/unicode.h | 1 + include/net/af_vsock.h | 3 + include/net/ax25.h | 6 + include/net/codel_impl.h | 1 + include/net/ipv6.h | 2 - include/net/netfilter/nf_tables_ipv6.h | 4 +- include/net/netrom.h | 18 +- include/net/rose.h | 45 ++- include/uapi/asm-generic/fcntl.h | 1 - io_uring/cancel.c | 29 +- io_uring/cancel.h | 2 + io_uring/futex.c | 7 +- io_uring/io-wq.c | 110 +++++- io_uring/io-wq.h | 4 +- io_uring/io_uring.c | 167 +++++++-- io_uring/io_uring.h | 44 ++- io_uring/kbuf.c | 2 +- io_uring/napi.c | 4 +- io_uring/net.c | 26 +- io_uring/poll.c | 41 ++- io_uring/rw.c | 18 - io_uring/sqpoll.c | 7 + io_uring/tctx.c | 1 + io_uring/timeout.c | 91 +++-- io_uring/uring_cmd.c | 2 +- io_uring/waitid.c | 19 +- kernel/cgroup/cgroup.c | 6 +- kernel/events/core.c | 33 +- kernel/exit.c | 2 +- kernel/fork.c | 12 +- kernel/futex/core.c | 47 +-- kernel/pid_namespace.c | 5 +- kernel/printk/printk.c | 2 +- kernel/ptrace.c | 6 + kernel/rcu/srcutiny.c | 19 +- kernel/sched/ext.c | 18 +- kernel/signal.c | 4 + kernel/trace/ftrace.c | 4 +- kernel/trace/ring_buffer.c | 13 +- kernel/trace/trace.c | 13 +- kernel/trace/trace_events_filter.c | 15 +- kernel/trace/trace_events_hist.c | 52 +-- kernel/trace/trace_events_synth.c | 10 + kernel/trace/trace_probe.c | 3 +- kernel/trace/trace_synth.h | 1 + kernel/watch_queue.c | 16 +- kernel/workqueue.c | 24 +- mm/filemap.c | 9 - mm/huge_memory.c | 81 +++-- mm/internal.h | 6 + mm/khugepaged.c | 3 + mm/pagewalk.c | 6 +- net/ax25/af_ax25.c | 81 ++++- net/ax25/ax25_ds_in.c | 2 + net/ax25/ax25_in.c | 55 ++- net/ax25/ax25_out.c | 121 +++++-- net/ax25/ax25_std_in.c | 44 +++ net/ax25/ax25_subr.c | 44 ++- net/bluetooth/l2cap_core.c | 7 +- net/bluetooth/l2cap_sock.c | 2 + net/bridge/br_multicast.c | 13 +- net/bridge/br_netfilter_ipv6.c | 2 +- net/bridge/netfilter/nf_conntrack_bridge.c | 4 +- net/core/page_pool.c | 3 +- net/ipv4/fib_semantics.c | 2 +- net/ipv4/tcp.c | 18 +- net/ipv4/tcp_cong.c | 4 +- net/ipv4/tcp_dctcp.c | 4 +- net/ipv4/tcp_minisocks.c | 2 +- net/ipv4/tcp_output.c | 2 +- net/ipv4/udp.c | 11 +- net/ipv6/calipso.c | 6 +- net/ipv6/ip6_input.c | 2 +- net/ipv6/ip6_offload.c | 7 +- net/ipv6/output_core.c | 7 +- net/iucv/af_iucv.c | 42 ++- net/mac802154/ieee802154_i.h | 7 +- net/mac802154/main.c | 1 + net/mac802154/scan.c | 51 ++- net/mptcp/protocol.c | 14 +- net/netfilter/ipvs/ip_vs_xmit.c | 2 +- net/netfilter/nf_conntrack_ovs.c | 2 +- net/netfilter/nf_log_syslog.c | 2 +- net/netfilter/nft_byteorder.c | 51 ++- net/netlink/af_netlink.c | 10 +- net/netrom/af_netrom.c | 33 +- net/netrom/nr_in.c | 26 ++ net/netrom/nr_route.c | 383 +++++++++++---------- net/rds/rdma_transport.c | 38 +- net/rose/af_rose.c | 73 +++- net/rose/rose_in.c | 44 ++- net/rose/rose_link.c | 47 +++ net/rose/rose_loopback.c | 2 +- net/rose/rose_out.c | 1 + net/rose/rose_route.c | 200 +++++++++-- net/rose/rose_timer.c | 87 ++++- net/sched/act_api.c | 11 +- net/sched/cls_flower.c | 5 + net/sched/sch_cake.c | 2 +- net/sctp/inqueue.c | 6 +- net/sctp/socket.c | 33 +- net/socket.c | 54 ++- net/tipc/node.c | 2 + net/vmw_vsock/af_vsock.c | 49 ++- net/vmw_vsock/virtio_transport_common.c | 9 +- samples/pidfd/Makefile | 2 +- security/keys/key.c | 13 +- security/keys/keyctl.c | 15 +- security/keys/keyring.c | 150 ++++---- security/keys/process_keys.c | 5 +- security/keys/trusted-keys/trusted_tpm1.c | 4 +- security/keys/trusted-keys/trusted_tpm2.c | 2 +- sound/soc/codecs/cs42l52.c | 2 +- sound/soc/codecs/cs42l56.c | 2 +- sound/soc/codecs/max98371.c | 2 +- sound/soc/codecs/nau8822.c | 4 +- sound/soc/codecs/pcm3168a.c | 2 +- sound/soc/codecs/wm8978.c | 4 +- sound/soc/intel/avs/pcm.c | 2 +- sound/soc/sof/ipc4-topology.c | 16 +- sound/soc/stm/stm32_spdifrx.c | 2 +- tools/gpio/Makefile | 6 + tools/power/x86/turbostat/turbostat.c | 11 +- .../test.d/filter/event-filter-incomplete.tc | 24 ++ 229 files changed, 3065 insertions(+), 1216 deletions(-)
Greg Kroah-Hartman
maintainerQuoted 13 lines · Pavel Machek
Hi!
Quoted 4 lines
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
What is up with these?
They don't have usual "Commit upstream XXX" markings. They do have commit ids in the sign-off area (which is a logical place), except that those hashes don't exist in mainline.
Quoted 7 lines
Best regards,
PavelSigned-off-by Bernard Pidoux <[email protected]>(cherry picked from commit 741a4863ad570889c75f7a8e404567d8f3e46335)Signed-off-by Sasha Levin <[email protected]>
These are coming from the out-of-tree rose repo as this code has been dropped from the newer kernel versions.
thanks,
greg k-h
Quoted 8 lines · On Wed, 28 Oct 2026 17:56:43 +0100 Greg Kroah-Hartman…
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
Boot-tested under QEMU for Rust x86_64, arm64 and riscv64; built-tested for loongarch64:
Thanks!
Cheers,
Miguel
Quoted 9 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
The whole patch series can be found in one patch at:
Quoted 8 lines
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.thanks,
greg k-h
Built and booted successfully on RISC-V RV64 (HiFive Unmatched).
Quoted 7 lines · On Wed, 28 Oct 2026 17:56:43 +0100 Greg Kroah-Hartman…
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
This rc kernel passes DAMON functionality test [1] on my test machine.
[1] https://github.com/damonitor/damon-tests/tree/next/corr
Thanks,
SJ
[...]
Quoted 9 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
The whole patch series can be found in one patch at:
Quoted 9 lines
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.thanks,
greg k-h
Compiled and booted on my test system. No dmesg regressions.
thanks,
-- Shuah
Quoted 4 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Built, booted, and tested on hardware for x86_64:
- Intel N100
No regressions found.
Thanks!
Sean
Quoted 8 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
Quoted 7 lines
The whole patch series can be found in one patch at:
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.-------------
Tested on AMD amd64 12-core and 4-core systems
and on Intel x86-64 4-core and x86 1-core systems
Quoted 9 lines · Greg Kroah-Hartman
This is the start of the stable review cycle for the 6.12.115 release. There are 247 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.
Responses should be made by Fri, 30 Oct 2026 16:59:22 +0000. Anything received after that time might be too late.
The whole patch series can be found in one patch at:
Quoted 8 lines
https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.12.115-rc1.gzor in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.gitlinux-6.12.y
and the diffstat can be found below.thanks,
greg k-h
Tested on an amd64 laptop (Lenovo ThinkPad T14 Gen 1). Working well, no regressions observed.
Signature · 1 line
-Barry K. Nathan <[email protected]>