6.1.193-rc1 review
Subsystems (6)
Greg Kroah-Hartman
maintainerPATCH 494/2857 tracing: Use __free() for expr_str() buffer
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit 988995c0552b6213b6bf16cea57258d4842c1488 ]
expr_str() allocates a temporary expression buffer and manually frees it on some error paths.
Convert the buffer to __free(kfree) and return it with return_ptr() on success. This keeps ownership handling separate from the later ERR_PTR() conversion and string-bound change.
Stable-dep-of: a0777b9e5315 ("tracing: Fix NULL dereference when copying keys for a field variable")
--- kernel/trace/trace_events_hist.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-)
kernel/trace/trace_events_hist.c +6 -8
@@ -1736,7 +1736,7 @@ static void expr_field_str(struct hist_field *field, char *expr)static char *expr_str (struct hist_field *field,unsigned int level) { -char *expr; + char *expr __free(kfree) = NULL;if (level >1 )return NULL ;
@@ -1747,7 +1747,7 @@ static char *expr_str(struct hist_field *field, unsigned int level)if (!field->operands[0 ]) {expr_field_str (field, expr); -return expr; +return_ptr (expr); }if (field->operator ==FIELD_OP_UNARY_MINUS ) {
@@ -1755,16 +1755,15 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level); -if (!subexpr) { -kfree (expr); +if (!subexpr)return NULL ; - } +strcat (expr, subexpr);strcat (expr,")" );kfree (subexpr); -return expr; +return_ptr (expr); }expr_field_str (field->operands[0 ], expr);
@@ -1783,13 +1782,12 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"*" );break ;default : -kfree (expr);return NULL ; }expr_field_str (field->operands[1 ], expr); -return expr; +return_ptr (expr); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 495/2857 tracing: Return ERR_PTR() from expr_str()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit a5ca27e8ff1c10e949af7cfe474d6d1a08fb5601 ]
expr_str() currently reports all failure cases as NULL, so callers cannot distinguish invalid recursion depth from allocation failure or later string construction errors.
Return ERR_PTR()-encoded errors from expr_str() and make parse_unary() and parse_expr() propagate them. Clear expr->name before destroying the hist field so the error pointer is not freed as a string.
Stable-dep-of: 935601a4276f ("tracing: Bound histogram expression strings with seq_buf")
--- kernel/trace/trace_events_hist.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
kernel/trace/trace_events_hist.c +20 -5
@@ -1739,11 +1739,11 @@ static char *expr_str(struct hist_field *field, unsigned int level) char *expr __free(kfree) = NULL;if (level >1 ) -return NULL ; +return ERR_PTR (-EINVAL ); expr =kzalloc (MAX_FILTER_STR_VAL ,GFP_KERNEL );if (!expr) -return NULL ; +return ERR_PTR (-ENOMEM );if (!field->operands[0 ]) {expr_field_str (field, expr);
@@ -1755,8 +1755,8 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level); -if (!subexpr) -return NULL ; +if (IS_ERR (subexpr)) +return subexpr;strcat (expr, subexpr);strcat (expr,")" );
@@ -1782,7 +1782,7 @@ static char *expr_str(struct hist_field *field, unsigned int level)strcat (expr,"*" );break ;default : -return NULL ; +return ERR_PTR (-EINVAL ); }expr_field_str (field->operands[1 ], expr);
@@ -2553,6 +2553,11 @@ static struct hist_field *parse_unary(struct hist_trigger_data *hist_data, expr->is_signed = operand1->is_signed; expr->operator =FIELD_OP_UNARY_MINUS ; expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free; + } expr->type =kstrdup_const (operand1->type,GFP_KERNEL );if (!expr->type) { ret = -ENOMEM ;
@@ -2765,6 +2770,11 @@ static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,destroy_hist_field (operand1,0 ); expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free_expr; + } }else {/* The operand sizes should be the same, so just pick one */ expr->size = operand1->size;
@@ -2778,6 +2788,11 @@ static struct hist_field *parse_expr(struct hist_trigger_data *hist_data, } expr->name =expr_str (expr,0 ); +if (IS_ERR (expr->name)) { + ret =PTR_ERR (expr->name); + expr->name =NULL ; + goto free_expr; + } }return expr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 496/2857 tracing: Bound histogram expression strings with seq_buf
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit 935601a4276f28105498609f7f98aa66e86e9c96 ]
expr_str() allocates a fixed MAX_FILTER_STR_VAL buffer and then builds expression names with a series of raw strcat() appends. Nested operands, constants, field flags, and generated field names can push the rendered string past that fixed limit before the name is attached to the hist field.
Build expression strings with seq_buf and return -E2BIG when the rendered name would exceed MAX_FILTER_STR_VAL. This keeps the existing tracing-side limit while replacing the raw append logic with bounded construction.
Stable-dep-of: a0777b9e5315 ("tracing: Fix NULL dereference when copying keys for a field variable")
--- kernel/trace/trace_events_hist.c | 57 ++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 24 deletions(-)
kernel/trace/trace_events_hist.c +33 -24
@@ -93,7 +93,6 @@ typedef u64 (*hist_field_fn_t) (struct hist_field *field,#define HIST_FIELD_OPERANDS_MAX 2#define HIST_FIELDS_MAX (TRACING_MAP_FIELDS_MAX + TRACING_MAP_VARS_MAX)#define HIST_ACTIONS_MAX 8 -#define HIST_CONST_DIGITS_MAX 21#define HIST_DIV_SHIFT 20/* For optimizing division by constants */ enum field_op_id {
@@ -1710,33 +1709,36 @@ static const char *get_hist_field_flags(struct hist_field *hist_field)return flags_str; } -static void expr_field_str (struct hist_field *field,char *expr) +static bool expr_field_str (struct hist_field *field,struct seq_buf *s) { +const char *field_name; +if (field->flags &HIST_FIELD_FL_VAR_REF ) {if (!field->system) -strcat (expr,"$" ); - }else if (field->flags &HIST_FIELD_FL_CONST ) { -char str[HIST_CONST_DIGITS_MAX ]; +seq_buf_putc (s,'$' ); + }else if (field->flags &HIST_FIELD_FL_CONST ) +seq_buf_printf (s,"%llu" , field->constant); -snprintf (str,HIST_CONST_DIGITS_MAX ,"%llu" , field->constant); -strcat (expr, str); - } + field_name =hist_field_name (field,0 ); +if (!field_name) +return false; -strcat (expr,hist_field_name (field,0 )); +seq_buf_puts (s, field_name);if (field->flags && !(field->flags &HIST_FIELD_FL_VAR_REF )) {const char *flags_str =get_hist_field_flags (field); -if (flags_str) { -strcat (expr,"." ); -strcat (expr, flags_str); - } +if (flags_str) +seq_buf_printf (s,".%s" , flags_str); } + +return !seq_buf_has_overflowed (s); }static char *expr_str (struct hist_field *field,unsigned int level) { char *expr __free(kfree) = NULL; +struct seq_buf s;if (level >1 )return ERR_PTR (-EINVAL );
@@ -1745,47 +1747,54 @@ static char *expr_str(struct hist_field *field, unsigned int level)if (!expr)return ERR_PTR (-ENOMEM ); +seq_buf_init (&s, expr,MAX_FILTER_STR_VAL ); +if (!field->operands[0 ]) { -expr_field_str (field, expr); +if (!expr_field_str (field, &s)) +return ERR_PTR (-E2BIG ); +return_ptr (expr); }if (field->operator ==FIELD_OP_UNARY_MINUS ) {char *subexpr; -strcat (expr,"-(" ); subexpr =expr_str (field->operands[0 ], ++level);if (IS_ERR (subexpr))return subexpr; -strcat (expr, subexpr); -strcat (expr,")" ); - +seq_buf_printf (&s,"-(%s)" , subexpr);kfree (subexpr); +if (seq_buf_has_overflowed (&s)) +return ERR_PTR (-E2BIG ); +return_ptr (expr); } -expr_field_str (field->operands[0 ], expr); +if (!expr_field_str (field->operands[0 ], &s)) +return ERR_PTR (-E2BIG );switch (field->operator) {case FIELD_OP_MINUS : -strcat (expr,"-" ); +seq_buf_putc (&s,'-' );break ;case FIELD_OP_PLUS : -strcat (expr,"+" ); +seq_buf_putc (&s,'+' );break ;case FIELD_OP_DIV : -strcat (expr,"/" ); +seq_buf_putc (&s,'/' );break ;case FIELD_OP_MULT : -strcat (expr,"*" ); +seq_buf_putc (&s,'*' );break ;default :return ERR_PTR (-EINVAL ); } -expr_field_str (field->operands[1 ], expr); +if (seq_buf_has_overflowed (&s) || + !expr_field_str (field->operands[1 ], &s)) +return ERR_PTR (-E2BIG );return_ptr (expr); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 497/2857 tracing: Fix NULL dereference when copying keys for a field variable
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
[ Upstream commit a0777b9e53157f1f6848a0fd0650f5465391ea81 ]
In event_hist_trigger_parse() where it needs to create actions like "onmatch", it calls:
event_hist_trigger_parse() {
create_actions() {
action_create() {
trace_action_create() {
trace_action_create_field_var() {
create_field_var_hist()Where create_field_var_hist() does a loop on the hist_data representing the keys. The issue is, if the keys uses one of the pseudo field types (like common_cpu), the hist_data field element will have NULL for its field member causing a NULL pointer dereference when accessing the key_field->field->name.
# echo 'hist:keys=common_cpu:ts0=common_timestamp.usecs' > \
events/sched/sched_waking/trigger
# echo 'my_synth u64 lat; int prio' > synthetic_events
# echo 'hist:keys=common_cpu:wakeup_lat=common_timestamp.usecs-$ts0:\
onmatch(sched.sched_waking).my_synth($wakeup_lat,prio)' > \
events/sched/sched_switch/triggerKASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017] RIP: 0010:create_field_var_hist+0x771/0x1380 Call Trace: trace_action_create_field_var+0x360/0x600 trace_action_create+0x393/0xe80 event_hist_trigger_parse+0x3e47/0x69e0 trigger_process_regex+0x1a6/0x250 event_trigger_write+0xce/0x160
Instead of accessing it directly, use the proper handler expr_field_str() to get the name.
The three previous patches are prerequisites: without them a .buckets key and a common_stacktrace key each render into a command that cannot be parsed back.
--- kernel/trace/trace_events_hist.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
@@ -3025,7 +3025,7 @@ create_field_var_hist(struct hist_trigger_data *target_hist_data, key_field = hist_data->fields[i];if (!first)seq_buf_putc (&s,',' ); -seq_buf_puts (&s, key_field->field->name); +expr_field_str (key_field, &s); first = false; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 498/2857 drm/amdgpu/uvd3.1: Fix checking whether UVD firmware keyselect was already set
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Timur Kristóf <[email protected]>
[ Upstream commit 800ea86e83e137395eba54103e5c459c2bc9965f ]
The PASS_MASK is for a different register not for UVD_FW_START. It was a mistake to check this flag. It should be enough to check that the register is non-zero.
--- drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c +1 -1
@@ -288,7 +288,7 @@ static int uvd_v3_1_fw_validate(struct amdgpu_device *adev)int i;uint32_t keysel = adev->uvd.keyselect; -if (RREG32 (mmUVD_FW_START) &UVD_FW_STATUS__PASS_MASK ) { +if (RREG32 (mmUVD_FW_START)) {dev_dbg (adev->dev,"UVD keyselect already set: 0x%x (on CPU: 0x%x)\n" ,RREG32 (mmUVD_FW_START), adev->uvd.keyselect);return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 499/2857 serial: core: fix TIOCSSERIAL and TIOCSERCONFIG on uninitialised ports
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hengyu Liang <[email protected]>
[ Upstream commit e1f46a09df93650288babb23de6e34bff73e80e6 ]
Commit 8ca59f7baee7 ("serial: fix ioctl hangup race") made uart_set_info() and uart_do_autoconfig() return -EIO when TTY_IO_ERROR is set, so that they do not run on a port that has been hung up.
However, TTY_IO_ERROR is also set on a port that could not be started, for example because its type is unknown, and by uart_shutdown(), which both functions call. As of now, setserial cannot configure a port that the kernel did not detect, and an autoconfig that follows a port, irq or type change in the same setserial call fails on any port.
The issue can be reproduced with setserial (busybox) on a port without a detected UART, for example ttyS3 of a QEMU guest:
setserial /dev/ttyS3 uart 16550A
setserial -g /dev/ttyS3
Before commit 8ca59f7baee7 ("serial: fix ioctl hangup race"), the result is:
/dev/ttyS3, UART: 16550A, Port: 0x02e8, IRQ: 3
After that commit, the result is:
setserial: can't set serial info: Input/output error /dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3
This patch will check tty_port_active() in these two functions instead. uart_hangup() clears it under the port mutex, and it stays set on an open port that could not be started.
--- drivers/tty/serial/serial_core.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/tty/serial/serial_core.c +7 -2
@@ -816,7 +816,11 @@ static int uart_set_info(struct tty_struct *tty, struct tty_port *port,upf_t old_flags, new_flags;int retval =0 ; -if (!uport ||tty_io_error (tty)) +/* +* TTY_IO_ERROR is also set on a port that could not be started, and +* this is how such a port is configured. Only refuse a hung up port. +*/ +if (!uport || !tty_port_active (port))return -EIO ; new_port = new_info->port;
@@ -1149,7 +1153,8 @@ static int uart_do_autoconfig(struct tty_struct *tty, struct uart_state *state)return -ERESTARTSYS ; uport =uart_port_check (state); -if (!uport ||tty_io_error (tty)) { +/* As in uart_set_info(), only refuse a hung up port. */ +if (!uport || !tty_port_active (port)) { ret = -EIO ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 500/2857 net/sched: sch_teql: fix slaves_lock IRQ deadlock
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 8b2043279dae25483fe1f2d926e76d41ab95c398 upstream.
This is a followup of commit e5b811fe7931 ("net/sched: sch_teql:
Introduce slaves_lock to avoid race condition and UAF") as reported by Sashiko.
The issue: master->slaves_lock serializes the master's ring of slave qdiscs. The control paths -- teql_dequeue(), teql_destroy() and teql_qdisc_init() -- take it with spin_lock_bh(), while teql_master_xmit() (the master's ndo_start_xmit) takes it with plain spin_lock().
netpoll_send_skb() wraps the transmit in local_irq_save(), and __netpoll_send_skb() asserts lockdep_assert_irqs_disabled(), so teql_master_xmit() reached from netconsole always acquires slaves_lock with hard IRQs disabled. On PREEMPT_RT spinlock_t is an rtmutex, and Documentation/locking/locktypes.rst names
local_irq_disable(); spin_lock(&lock);
as a sequence that breaks there because the rtmutex requires a fully preemptible context. This is reachable without any panic: the nbcon printer thread calls netconsole's write_thread() callback on every message. The usual remedy -- folding the IRQ disable into the lock with spin_lock_irqsave() -- is unavailable because the local_irq_save() is netpoll's, not ours.
On non-RT the same asymmetry leaves slaves_lock acquirable with hard IRQs disabled on one path and held with hard IRQs enabled on another. That is only exploitable during the panic console flush (netconsole is CON_NBCON_ATOMIC_UNSAFE, so console_is_usable() admits its write_atomic() only from nbcon_atomic_flush_unsafe(), which panic() alone calls), and even then an IRQ-saving lock does not help if the holder oopsed inside the section or was stopped by panic_other_cpus_shutdown(). So the non-RT half is hardening; the PREEMPT_RT half is the bug.
The Fix: take slaves_lock as a raw spinlock with IRQs saved at every site. Since skb_queue_purge() takes the queue's spinlock_t and may not nest inside a raw lock on PREEMPT_RT, move its call in teql_destroy() outside the raw section; dat->q is the dying qdisc's own queue and was never serialized by slaves_lock, so the move is behaviour-neutral.
The new critical sections contain only RCU pointer assignments and netdev_get_tx_queue(); skb_queue_purge(), netif_wake_queue() and dev_reset_queue() are all outside them. teql_destroy()'s ring walk is O(slaves), two pointer loads and a compare per iteration, so even a large ring is microseconds with IRQs off. Keeping the purge conditional rather than dropping it outright is the conservative call for a backport.
Some context: commit 6301f6a34ed8 ("net/sched: sch_teql: move rcu_read_lock()/spin_lock() from _bh variants") hardened the parent fix; together they addressed the master->slaves resurrection use-after-free and the xmit-side BH warning but left the reverse direction -- a hard IRQ re-entering xmit while a control path holds the lock -- unaddressed.
Conditions to recreate the bug:
- CONFIG_PREEMPT_RT, CONFIG_NET_SCH_TEQL, CONFIG_DUMMY and CONFIG_NETCONSOLE.
- Run ip link add dev teqlslave0 type dummy, bring teqlslave0 up, attach it with tc qdisc add dev teqlslave0 root teql0, and bring teql0 up.
- Configure a netconsole target on teql0 with explicit local and remote IP addresses and a remote MAC address, then emit a console message. The nbcon printer thread reaches teql_master_xmit() with hard IRQs disabled by netpoll; taking slaves_lock as a spinlock_t is invalid on PREEMPT_RT. No panic or concurrent qdisc change is required.
- Reachable by an admin with CAP_NET_ADMIN; teql devices exist only in the initial netns (no per-netns ops), so a user namespace does not suffice.
--- net/sched/sch_teql.c | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-)
net/sched/sch_teql.c +28 -17
@@ -53,7 +53,7 @@ struct teql_master {struct Qdisc_ops qops;struct net_device *dev;struct Qdisc __rcu *slaves; -spinlock_t slaves_lock;/* serializes writes to ->slaves */ +raw_spinlock_t slaves_lock;/* serializes writes to ->slaves */ struct list_head master_list;unsigned long tx_bytes;unsigned long tx_packets;
@@ -92,6 +92,7 @@ teql_dequeue(struct Qdisc *sch) {struct teql_sched_data *dat =qdisc_priv (sch);struct netdev_queue *dat_queue; +unsigned long flags;struct sk_buff *skb;struct Qdisc *q;
@@ -102,9 +103,9 @@ teql_dequeue(struct Qdisc *sch)if (skb ==NULL ) {struct net_device *m =qdisc_dev (q);if (m) { -spin_lock_bh (&dat->m->slaves_lock); +raw_spin_lock_irqsave (&dat->m->slaves_lock, flags);rcu_assign_pointer (dat->m->slaves, sch); -spin_unlock_bh (&dat->m->slaves_lock); +raw_spin_unlock_irqrestore (&dat->m->slaves_lock, flags);netif_wake_queue (m); } }else {
@@ -137,11 +138,13 @@ teql_destroy(struct Qdisc *sch)struct teql_master *master = dat->m;struct netdev_queue *txq =NULL ;bool reset_master_queue = false; +unsigned long flags; +bool purge = false;if (!master)return ; -spin_lock_bh (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags); prev =rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock));if (prev) {
@@ -169,12 +172,18 @@ teql_destroy(struct Qdisc *sch) reset_master_queue = true; } } -skb_queue_purge (&dat->q); + purge = true;break ; }while (prev !=rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock))); } -spin_unlock_bh (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags); + +/* skb_queue_purge() takes the queue's spinlock_t, which cannot nest +* inside a raw lock on PREEMPT_RT; purge after the raw section. +*/ +if (purge) +skb_queue_purge (&dat->q);if (reset_master_queue)dev_reset_queue (master->dev, txq,NULL );
@@ -187,6 +196,7 @@ static int teql_qdisc_init(struct Qdiscstruct teql_master *m = (struct teql_master *)sch->ops;struct teql_sched_data *q =qdisc_priv (sch);struct Qdisc *first; +unsigned long flags;if (dev->hard_header_len > m->dev->hard_header_len)return -EINVAL ;
@@ -203,7 +213,7 @@ static int teql_qdisc_init(struct Qdiscskb_queue_head_init (&q->q); -spin_lock_bh (&m->slaves_lock); +raw_spin_lock_irqsave (&m->slaves_lock, flags); first =rcu_dereference_protected (m->slaves,lockdep_is_held (&m->slaves_lock));if (first) {if (m->dev->flags &IFF_UP ) {
@@ -214,7 +224,7 @@ static int teql_qdisc_init(struct Qdisc (m->dev->flags & IFF_MULTICAST && !(dev->flags & IFF_MULTICAST)) || dev->mtu < m->dev->mtu) { -spin_unlock_bh (&m->slaves_lock); +raw_spin_unlock_irqrestore (&m->slaves_lock, flags);return -EINVAL ; } }else {
@@ -237,7 +247,7 @@ static int teql_qdisc_init(struct Qdisc m->dev->mtu = dev->mtu; m->dev->flags = (m->dev->flags&~FMASK )|(dev->flags&FMASK ); } -spin_unlock_bh (&m->slaves_lock); +raw_spin_unlock_irqrestore (&m->slaves_lock, flags);return 0 ; }
@@ -302,11 +312,12 @@ static inline int teql_resolve(struct skstatic netdev_tx_t teql_master_xmit (struct sk_buff *skb,struct net_device *dev) {struct teql_master *master =netdev_priv (dev); -struct Qdisc *start, *q; -int busy; -int nores;int subq =skb_get_queue_mapping (skb);struct sk_buff *skb_res =NULL ; +struct Qdisc *start, *q; +unsigned long flags; +int nores; +int busy; restart: nores =0 ;
@@ -342,13 +353,13 @@ restart: netdev_start_xmit(skb, slave, slave_txq, false) == NETDEV_TX_OK) {__netif_tx_unlock (slave_txq); -spin_lock (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)rcu_assign_pointer (master->slaves,rcu_dereference_protected (NEXT_SLAVE (q),lockdep_is_held (&master->slaves_lock))); -spin_unlock (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags);netif_wake_queue (dev); master->tx_packets++; master->tx_bytes += length;
@@ -361,13 +372,13 @@ restart: busy =1 ;break ;case 1 : -spin_lock (&master->slaves_lock); +raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)rcu_assign_pointer (master->slaves,rcu_dereference_protected (NEXT_SLAVE (q),lockdep_is_held (&master->slaves_lock))); -spin_unlock (&master->slaves_lock); +raw_spin_unlock_irqrestore (&master->slaves_lock, flags);rcu_read_unlock ();return NETDEV_TX_OK ;default :
@@ -489,7 +500,7 @@ static __init void teql_master_setup(strstruct teql_master *master =netdev_priv (dev);struct Qdisc_ops *ops = &master->qops; -spin_lock_init (&master->slaves_lock); +raw_spin_lock_init (&master->slaves_lock); master->dev = dev; ops->priv_size =sizeof (struct teql_sched_data );
Greg Kroah-Hartman
maintainerPATCH 501/2857 net/sched: sch_teql: fix use-after-free on lower qdisc drop
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: owen kwan <[email protected]>
commit 782d6bb8f9b8e9d8591181662222bf74cd3ecf79 upstream.
The issue: teql_master_xmit() tests the slave's ndo_start_xmit() return value against NETDEV_TX_OK alone. A slave that consumes the skb but returns an error code (rc < NET_XMIT_MASK, e.g. NET_XMIT_DROP) is treated as if the skb were still owned, so the loop restores skb->dev and calls __skb_pull() on it. A VLAN slave returns the result of dev_queue_xmit() from its ndo_start_xmit() (propagated since cbbef5e18307), and when the lower qdisc drops the packet that value is NET_XMIT_DROP after the skb has been freed, giving a use-after-free in teql_master_xmit().
The Fix: test for consumption with dev_xmit_complete(), which accepts NETDEV_TX_OK and every rc < NET_XMIT_MASK, matching other callers that need to distinguish consumed results from busy. Only NETDEV_TX_OK keeps the packet counted in tx_packets/tx_bytes and advances the slave; a consumed result that is neither a success nor NET_XMIT_CN ends the attempt and is charged to tx_dropped, so lower-qdisc drops are no longer reported as good transmits. NET_XMIT_CN is counted like success because it can accompany acceptance of the current packet: pfifo_head_drop drops the old head, enqueues the current skb and returns NET_XMIT_CN.
Conditions to recreate the bug:
With CONFIG_NET_SCH_TEQL,CONFIG_VLAN_8021Q and CONFIG_DUMMY enabled, add lkrdummy0 (dummy) and lkrvlan0 (VLAN id 37 on lkrdummy0); set a pfifo limit 0 root on lkrdummy0 and a teql0 root on lkrvlan0; bring teql0 up with an address and send one UDP packet to it. The VLAN xmit returns NET_XMIT_DROP from the lower qdisc while holding a freed skb.
--- net/sched/sch_teql.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
net/sched/sch_teql.c +10 -5
@@ -347,12 +347,18 @@ restart:case 0 :if (__netif_tx_trylock (slave_txq)) {unsigned int length =qdisc_pkt_len (skb); +int rc =NETDEV_TX_BUSY ; skb->dev = slave; -if (!netif_xmit_frozen_or_stopped (slave_txq) && -netdev_start_xmit (skb, slave, slave_txq, false) == -NETDEV_TX_OK ) { -__netif_tx_unlock (slave_txq); +if (!netif_xmit_frozen_or_stopped (slave_txq)) + rc =netdev_start_xmit (skb, slave, slave_txq, false); +__netif_tx_unlock (slave_txq); +if (dev_xmit_complete (rc)) { +if (rc !=NETDEV_TX_OK && rc !=NET_XMIT_CN ) { + master->tx_dropped++; +rcu_read_unlock (); +return NETDEV_TX_OK ; + }raw_spin_lock_irqsave (&master->slaves_lock, flags);if (rcu_dereference_protected (master->slaves,lockdep_is_held (&master->slaves_lock)) == q)
@@ -366,7 +372,6 @@ restart:rcu_read_unlock ();return NETDEV_TX_OK ; } -__netif_tx_unlock (slave_txq); }if (netif_xmit_stopped (netdev_get_tx_queue (dev,0 ))) busy =1 ;
Greg Kroah-Hartman
maintainerPATCH 502/2857 net/sched: fix packet reordering on requeue
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Antonio Quartulli <[email protected]>
commit 14368b9aa1017fee35d2589be7b17e0485c0f93e upstream.
dev_requeue_skb() appends requeued skbs to the tail of q->gso_skb, while dequeue_skb() takes them back one at a time from the head. If the driver returns NETDEV_TX_BUSY again for the first of them, it moves behind the skbs still parked there and is sent after them.
This showed up as heavy TCP reordering while benchmarking over veth,
which returns NETDEV_TX_BUSY whenever its ring is full since
commit dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops").
Requeue the skbs at the head of gso_skb, keeping their order. With 4 TCP streams over a veth pair with a pfifo qdisc, this removes about 1.3M out-of-order segments and 15-37k retransmits per 15 seconds, and raises throughput from about 40 to 76 Gbit/s.
--- net/sched/sch_generic.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
net/sched/sch_generic.c +9 -1
@@ -141,8 +141,11 @@ static inline void qdisc_enqueue_skb_badstatic inline void dev_requeue_skb (struct sk_buff *skb,struct Qdisc *q) { +struct sk_buff_head requeue;spinlock_t *lock =NULL ; +__skb_queue_head_init (&requeue); +if (q->flags &TCQ_F_NOLOCK ) { lock =qdisc_lock (q);spin_lock (lock);
@@ -151,7 +154,7 @@ static inline void dev_requeue_skb(strucwhile (skb) {struct sk_buff *next = skb->next; -__skb_queue_tail (&q->gso_skb, skb); +__skb_queue_tail (&requeue, skb);/* it's still part of the queue */ if (qdisc_is_percpu_stats (q)) {
@@ -167,6 +170,11 @@ static inline void dev_requeue_skb(struc skb = next; } +/* the skbs may come from the head of gso_skb, so put them back there: +* appending them would let the ones still parked overtake them +*/ +skb_queue_splice (&requeue, &q->gso_skb); +if (lock) {spin_unlock (lock);set_bit (__QDISC_STATE_MISSED, &q->state);
Greg Kroah-Hartman
maintainerPATCH 503/2857 net/sched: act_ife: do not consume the inner header on egress
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 498c631f9c6d74aad4bf43039fa3ce70ae9a8bb7 upstream.
The issue:tcf_ife_decode() unconditionally calls eth_type_trans(), which pulls ETH_HLEN. On egress this consumes the inner Ethernet header, and the device receives an skb whose data points to the L3 header:
- loopback_xmit() parses L3 data as Ethernet: the "ethertype" comes from the inner IPv4 source address, and the decapsulated packet is dropped or misparsed.
- a real NIC transmits the frame without its Ethernet header.
(The __skb_pull() BUG this used to trigger in loopback_xmit() when the remaining linear area was short is handled by "loopback: use eth_type_trans_careful()".)
The Fix:
Parse the inner Ethernet header with eth_type_trans() in both directions, then restore the egress data position and MAC length. On ingress the existing behavior is unchanged. On egress, push the inner Ethernet header back after parsing so the xmit path sees the original frame and later actions see a consistent network header.
Conditions to recreate the bug:
- egress tc filter on lo: action ife decode pipe;
- AF_PACKET SOCK_RAW frame: outer Ethernet with ETH_P_IFE, IFE metadata, inner Ethernet + a valid IPv4 ICMP echo request to a local address;
- before this patch, no echo is received; after it, the echo is delivered and answered.
--- net/sched/act_ife.c | 4 ++++ 1 file changed, 4 insertions(+)
net/sched/act_ife.c +4 -0
@@ -761,6 +761,10 @@ static int tcf_ife_decode(struct sk_buff skb->protocol =eth_type_trans (skb, skb->dev);skb_reset_network_header (skb); +if (!skb_at_tc_ingress (skb)) { +skb_push (skb,ETH_HLEN ); +skb_reset_mac_len (skb); + }return action; }
Greg Kroah-Hartman
maintainerPATCH 504/2857 driver core: Limit the messages on a refused uevent
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit a01c8e5b1dff1ce489e6b339139e744db36b8bb3 upstream.
A write to a "uevent" file which is no valid action makes kobject_synth_uevent() print a warning and uevent_store() an error every time. This is generally considered a bad thing so rate limit these messages.
--- drivers/base/core.c | 4 +++- lib/kobject_uevent.c | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-)
drivers/base/core.c +3 -1
@@ -2690,7 +2690,9 @@ static ssize_t uevent_store(struct devic rc =kobject_synth_uevent (&dev->kobj, buf, count);if (rc) { -dev_err (dev,"uevent: failed to send synthetic uevent: %d\n" , rc); +dev_err_ratelimited (dev, +"uevent: failed to send synthetic uevent: %d\n" , + rc);return rc; }
lib/kobject_uevent.c +3 -3
@@ -224,9 +224,9 @@ int kobject_synth_uevent(struct kobject out:if (r) { devpath =kobject_get_path (kobj,GFP_KERNEL ); -pr_warn ("synth uevent: %s: %s\n" , - devpath ?:"unknown device" , - msg ?:"failed to send uevent" ); +pr_warn_ratelimited ("synth uevent: %s: %s\n" , + devpath ?:"unknown device" , + msg ?:"failed to send uevent" );kfree (devpath); }return r;
Greg Kroah-Hartman
maintainerPATCH 505/2857 Drivers: hv: vmbus: Bounds check the shared ring buffer indices
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kameron Carr <[email protected]>
commit 1d287c17cc5bfd6386fe0770999be410b248d021 upstream.
In a CoCo VM the host is untrusted. Since the VMBus ring buffer read and write indices live in shared memory, the guest has to treat both as potentially malicious.
hv_ringbuffer_write() copies into the ring at write_index with no bounds checking, so the host can make the guest write packet data at any offset up to 4 GiB past the start of the ring buffer. read_index matters too:
the available space derived from both indices is the only bound on how much is copied, and an out-of-range index can make it far larger than the ring.
The fix is to validate both indices before use and to use the validated snapshot instead of re-accessing. For invalid indices, hv_ringbuffer_write() logs and returns -EIO.
One re-read of write_index is left unchecked in this patch:hv_get_ring_bufferindices() fetches it again for the prev_indices trailer. The value is only returned to the host and is not used as an offset or length for indexing. Since this is not a security issue, it is addressed later in the series.
Open-coding the bytes available arithmetic keeps the fix free of prerequisites; a later patch refactors it into a helper function.
--- drivers/hv/ring_buffer.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-)
drivers/hv/ring_buffer.c +16 -13
@@ -69,15 +69,6 @@ static void hv_signal_on_write(u32 old_w } } -/* Get the next write location for the specified ring buffer. */ -static inline u32 -hv_get_next_write_location (struct hv_ring_buffer_info *ring_info) -{ -u32 next = ring_info->ring_buffer->write_index; - -return next; -} -/* Set the next write location for the specified ring buffer. */ static inline void hv_set_next_write_location(struct hv_ring_buffer_info *ring_info,
@@ -303,6 +294,7 @@ int hv_ringbuffer_write(struct vmbus_chau32 totalbytes_towrite =sizeof (u64);u32 next_write_location;u32 old_write; +u32 read_index;u64 prev_indices;unsigned long flags;struct hv_ring_buffer_info *outring_info = &channel->outbound;
@@ -317,7 +309,20 @@ int hv_ringbuffer_write(struct vmbus_chaspin_lock_irqsave (&outring_info->ring_lock, flags); - bytes_avail_towrite =hv_get_bytes_to_write (outring_info); + read_index =READ_ONCE (outring_info->ring_buffer->read_index); + old_write =READ_ONCE (outring_info->ring_buffer->write_index); +if (unlikely (read_index >= outring_info->ring_datasize || + old_write >= outring_info->ring_datasize)) { +spin_unlock_irqrestore (&outring_info->ring_lock, flags); +pr_err_ratelimited ("outbound ring indices out of range: relid %u read %u write %u size %u\n" , + channel->offermsg.child_relid, read_index, + old_write, outring_info->ring_datasize); +return -EIO ; + } + + bytes_avail_towrite = old_write >= read_index ? + outring_info->ring_datasize - (old_write - read_index) : + read_index - old_write;/* * If there is only room for the packet, assume it is full.
@@ -339,9 +344,7 @@ int hv_ringbuffer_write(struct vmbus_cha channel->out_full_flag = false;/* Write to the ring buffer */ - next_write_location =hv_get_next_write_location (outring_info); - - old_write = next_write_location; + next_write_location = old_write;for (i =0 ; i < kv_count; i++) { next_write_location = hv_copyto_ringbuffer(outring_info,
Greg Kroah-Hartman
maintainerPATCH 506/2857 backlight: lm3630a: Cancel delayed work before destroying workqueue
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 2cf184caab8b406fdd9db126ee40d62418237456 upstream.
The interrupt handler queues delayed work to read the interrupt status. After free_irq() stops the producer, this work can still be waiting on its timer. destroy_workqueue() cannot drain delayed work that has not yet been queued by its timer, so the timer can outlive both the workqueue and the devm-allocated chip containing the work.
Cancel the delayed work synchronously after freeing the IRQ and before destroying the workqueue. This also waits for any running status read to finish before the chip's resources are released.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/video/backlight/lm3630a_bl.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/lm3630a_bl.c +1 -0
@@ -589,6 +589,7 @@ static void lm3630a_remove(struct i2c_clif (pchip->irq) {free_irq (pchip->irq, pchip); +cancel_delayed_work_sync (&pchip->work);destroy_workqueue (pchip->irqthread); } }
Greg Kroah-Hartman
maintainerPATCH 507/2857 backlight: qcom-wled: Fix NULL pointer dereference in wled_remove()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 1dbd46d4b2fb416a8202b1a8e4ef9d0cadbe075f upstream.
wled_probe() doesn't set the driver data for the platform device. As a result, platform_get_drvdata() in wled_remove() will return NULL, and the first dereference of it crashes on unbind.
Set the platform device driver data in wled_probe().
--- drivers/video/backlight/qcom-wled.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/qcom-wled.c +1 -0
@@ -1681,6 +1681,7 @@ static int wled_probe(struct platform_de wled->regmap = regmap; wled->dev = &pdev->dev; +platform_set_drvdata (pdev, wled); wled->version = (uintptr_t )of_device_get_match_data (&pdev->dev);if (!wled->version) {
Greg Kroah-Hartman
maintainerPATCH 508/2857 backlight: qcom-wled: Fix unbalanced OVP IRQ enable at probe
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 5eda6b51461932f9fd835ef9e4574650c69c4fe8 upstream.
wled_configure_ovp_irq() derives the initial state of the OVP interrupt from the hardware:
/* Keep OVP irq disabled until module is enabled */
if (!(val & WLED3_CTRL_REG_MOD_EN_MASK))
disable_irq(wled->ovp_irq);but wled->brightness, which is what the rest of the driver uses to tell whether the module is on, is left at zero.
On boards where the bootloader hands the kernel a lit backlight the two disagree. MOD_EN is already set, so the interrupt is left enabled, while wled_update_status() still believes the backlight is off and takes
if (!!brightness != !!wled->brightness)
rc = wled_module_enable(wled, !!brightness);on the first backlight update. wled_module_enable() then schedules wled_ovp_work(), which calls enable_irq() on the already enabled interrupt:
Unbalanced enable for IRQ 176
WARNING: CPU: 0 PID: 160 at kernel/irq/manage.c:774 __enable_irq+0x50/0x80 Hardware name: Xiaomi Pocophone F1 (DT) Workqueue: events wled_ovp_work Call trace: __enable_irq+0x50/0x80 enable_irq+0x48/0xa0 wled_ovp_work+0x18/0x24 process_one_work+0x1d0/0x350 worker_thread+0x13c/0x460 kthread+0x110/0x114 ret_from_fork+0x10/0x20
The bootloader is not the only way to get there. The readback runs after wledN_setup(), and wled4_setup() sets MOD_EN itself on the path where the sink configuration does not already match, as does the tail of wled_auto_string_detection(), which all three setup paths can reach through wled_auto_detection_at_init(). A cold-booted board with a dark panel can therefore reach the same disagreement.
Move the MOD_EN readback into wled_probe() and use it to seed wled->brightness, so the driver starts out agreeing with the hardware, and key the OVP interrupt off wled->brightness instead. The first backlight update then only reprograms the brightness registers and leaves both the module and the interrupt alone. The OVP interrupt also stays armed from probe whenever the module is already enabled, rather than being disabled at probe and only enabled once something writes brightness.
Note that a backlight update requesting brightness 0 before any non-zero one now really does turn the module off wherever MOD_EN was already set, where before it was silently ignored.
wled->brightness is seeded with default-brightness rather than the level the bootloader actually programmed, so the first update can still step the brightness. Reading that level back is version specific and is done in a follow-up, to keep this fix small enough to backport.
--- drivers/video/backlight/qcom-wled.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-)
drivers/video/backlight/qcom-wled.c +21 -11
@@ -1626,7 +1626,6 @@ static int wled_configure_ovp_irq(struct struct platform_device *pdev) {int rc; -u32 val; wled->ovp_irq =platform_get_irq_byname (pdev,"ovp" );if (wled->ovp_irq <0 ) {
@@ -1644,13 +1643,8 @@ static int wled_configure_ovp_irq(structreturn 0 ; } - rc =regmap_read (wled->regmap, wled->ctrl_addr + -WLED3_CTRL_REG_MOD_EN , &val); -if (rc <0 ) -return rc; - -/* Keep OVP irq disabled until module is enabled */ -if (!(val &WLED3_CTRL_REG_MOD_EN_MASK )) +/* Keep the OVP irq disabled until the module is enabled */ +if (!wled->brightness)disable_irq (wled->ovp_irq);return 0 ;
@@ -1666,6 +1660,7 @@ static int wled_probe(struct platform_destruct backlight_device *bl;struct wled *wled;struct regmap *regmap; +u32 mod_en;u32 val;int rc;
@@ -1736,6 +1731,24 @@ static int wled_probe(struct platform_deINIT_DELAYED_WORK (&wled->ovp_work, wled_ovp_work); + val =WLED_DEFAULT_BRIGHTNESS ; +of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); + +/* +* The module may already be enabled, either by a bootloader that left +* the backlight lit or by the setup above. Record that, so that the +* first brightness update does not enable an already enabled module, +* and so that the OVP irq is armed from probe rather than from that +* first update. +*/ + rc =regmap_read (wled->regmap, wled->ctrl_addr +WLED3_CTRL_REG_MOD_EN , + &mod_en); +if (rc <0 ) +return rc; + +if (mod_en &WLED3_CTRL_REG_MOD_EN_MASK ) + wled->brightness = val; + rc =wled_configure_short_irq (wled, pdev);if (rc <0 )return rc;
@@ -1744,9 +1757,6 @@ static int wled_probe(struct platform_deif (rc <0 )return rc; - val =WLED_DEFAULT_BRIGHTNESS ; -of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); -memset (&props,0 ,sizeof (struct backlight_properties )); props.type =BACKLIGHT_RAW ; props.brightness = val;
Greg Kroah-Hartman
maintainerPATCH 509/2857 backlight: qcom-wled: Fix WLED3 brightness register stride
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit e60dc9c05e0f415ef8bc63b3179abdd49830a619 upstream.
WLED3 has a 16-bit brightness register pair per string, at 0x40 + 2*n, which is what the pm8941-wled driver wrote to:
rc = regmap_bulk_write(wled->regmap, wled->addr + WLED3_CTRL_REG_VAL_BASE + 2 * i, v, 2);
The restructuring for WLED3 turned that into WLED3_SINK_REG_BRIGHT(n), defined as 0x40 + n, so the two byte writes for consecutive strings
overlap: string 1 overwrites the MSB of string 0 with its own LSB, and with the default three strings only string 1 ends up with the requested value.
Use the 2 byte stride.
--- drivers/video/backlight/qcom-wled.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/video/backlight/qcom-wled.c +1 -1
@@ -59,7 +59,7 @@#define WLED3_SINK_REG_CURR_SINK_SHFT 5/* WLED3 specific per-'string' registers below */ -#define WLED3_SINK_REG_BRIGHT (n) (0x40 + n) +#define WLED3_SINK_REG_BRIGHT (n) (0x40 + (n * 0x2))#define WLED3_SINK_REG_STR_MOD_EN (n) (0x60 + (n * 0x10))#define WLED3_SINK_REG_STR_MOD_MASK BIT(7)
Greg Kroah-Hartman
maintainerPATCH 510/2857 ksmbd: accept share config responses from ksmbd-tools before 3.5.3
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michail Andreas Michalopoulos <[email protected]>
commit 4f1ce9ffb996a524acf864316479a7806ae500c6 upstream.
ksmbd-tools releases before 3.5.2 do not have the payload_sz field in struct ksmbd_share_config_response; the field occupies the last word of their reserved[] area, so the kernel always sees payload_sz == 0 from them. ipc_validate_msg() and share_config_request() used to treat payload_sz == 0 as "legacy userspace" and skip the payload size checks.
That case was removed by
commit f25e93768fcc ("ksmbd: prevent out-of-bounds reads in share config responses").
With payload_sz == 0:
- the IPC$ (pipe) response fails the final message size comparison:
these tools always send a one-byte payload, so msg_sz is sizeof(*resp) + 1, but the expected size is now computed as sizeof(*resp) + 0;
- every other share fails "payload_sz <= veto_list_sz".
In addition, ksmbd-tools before 3.5.3 copy a global "veto files" setting into the IPC$ response, so with such a configuration IPC$ also fails the now unconditional "veto_list_sz > payload_sz" check, even though pipe shares never use a veto list.
ksmbd_ipc_share_config_request() then returns NULL and every tree connect fails with STATUS_BAD_NETWORK_NAME, so ksmbd cannot serve any share when used with these ksmbd-tools releases, for example the 3.5.1 package shipped by Ubuntu 24.04. Login still works, which makes the failure look like a configuration problem:
CIFS: VFS: BAD_NETWORK_NAME: \\127.0.0.1\IPC$
CIFS: VFS: \\127.0.0.1 failed to connect to IPC (rc=-2)
When payload_sz is zero, derive it from the size of the message actually received and store it back in the response, so that the checks in ipc_validate_msg() and the path and veto list parsing in share_config_request() all use the same bound. The response is the kernel's own copy made by handle_response(), and msg_sz has already been checked to be at least sizeof(*resp), so this cannot underflow. All checks added by that commit then apply unchanged, bounded by the bytes that really arrived, and newer ksmbd-tools that fill in payload_sz are unaffected. Also skip the veto list size check for pipe shares:share_config_request() reads neither the path nor the veto list for them.
Tested in QEMU with ksmbd-tools 3.5.1 and 3.5.7 and the in-kernel SMB client over loopback, with and without a global "veto files" setting.
--- fs/smb/server/transport_ipc.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
fs/smb/server/transport_ipc.c +15 -1
@@ -493,11 +493,25 @@ static int ipc_validate_msg(struct ipc_mif (entry->msg_sz <sizeof (struct ksmbd_share_config_response ))return -EINVAL ; +/* +* ksmbd-tools releases before 3.5.2 leave payload_sz zero. +* Derive it from the size of the message actually received so +* the checks below bound the payload for those releases too. +*/ +if (!resp->payload_sz) + resp->payload_sz = entry->msg_sz - +sizeof (struct ksmbd_share_config_response ); +if (strnlen (resp->share_name,sizeof (resp->share_name)) ==sizeof (resp->share_name))return -EINVAL ; -if (resp->veto_list_sz > resp->payload_sz) +/* +* Pipe shares carry no veto list, but ksmbd-tools before 3.5.3 +* copy a global "veto files" setting into the IPC$ response. +*/ +if (!(resp->flags &KSMBD_SHARE_FLAG_PIPE ) && + resp->veto_list_sz > resp->payload_sz)return -EINVAL ; if (resp->flags != KSMBD_SHARE_FLAG_INVALID &&
Greg Kroah-Hartman
maintainerPATCH 511/2857 ksmbd: avoid restoring only in-memory EOF after allocation change
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 9455e920aebe41217cabff3f81e90da4c407fdb6 upstream.
When SetAllocation requests a size below the allocated block count but above EOF, ksmbd truncates the file to that size and restores only the in-memory i_size. The larger EOF remains on disk and reappears after a reboot. A 3-byte file preallocated to 64 KiB can acquire a 4 KiB EOF after reducing its allocation to 4 KiB. Extending EOF this way is not a reliable way to reclaim the preallocation beyond the old EOF either.
Only use this truncate path when the requested allocation is at or below the observed EOF. A truncate to the existing EOF still lets filesystems release preallocated blocks beyond EOF. Remove the in-memory-only i_size restoration. The size check still precedes vfs_truncate() taking the inode lock, so a concurrent shrink can make the truncate extend EOF; that race also existed in the original path.
--- fs/smb/server/smb2pdu.c | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-)
fs/smb/server/smb2pdu.c +4 -11
@@ -6010,24 +6010,17 @@ static int set_file_allocation_info(strupr_err ("vfs_fallocate is failed : %d\n" , rc);return rc; } - }else if (alloc_blks < stat.blocks) { -loff_t size; - + }else if (alloc_blks < stat.blocks && + alloc_blks *512 <=i_size_read (inode)) {/* -* Allocation size could be smaller than original one -* which means allocated blocks in file should be -* deallocated. use truncate to cut out it, but inode -* size is also updated with truncate offset. -* inode size is retained by backup inode size. +* Truncate at or below EOF to discard excess allocation. +* Truncating above EOF would extend the file on disk. */ - size =i_size_read (inode); rc =ksmbd_vfs_truncate (work, fp, alloc_blks *512 );if (rc) {pr_err ("truncate failed!, err %d\n" , rc);return rc; } -if (size < alloc_blks *512 ) -i_size_write (inode, size); }return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 512/2857 ksmbd: fix extended session security negotiation for raw NTLMSSP
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Namjae Jeon <[email protected]>
commit 6868f857514bbfd2ed10b9b566664dc4a8ca039d upstream.
ksmbd_build_ntlmssp_challenge_blob() only advertises extended session security when conn->use_spnego is true. As a result, raw NTLMSSP negotiation drops NTLMSSP_NEGOTIATE_EXTENDED_SEC from the challenge even when the client requested it.
A Windows capture shows an initial SPNEGO authentication succeeding, followed by a raw NTLMSSP negotiation on the same TCP connection. The raw challenge omits extended session security, and the client does not send an AUTHENTICATE message. The unfinished session then occupies the pending session slot, causing subsequent SESSION_SETUP requests to fail with STATUS_INSUFFICIENT_RESOURCES.
Set NTLMSSP_NEGOTIATE_EXTENDED_SEC whenever the client requests it, independently of the SPNEGO wrapper, as required by [MS-NLMP].
--- fs/smb/server/auth.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
fs/smb/server/auth.c +1 -2
@@ -452,8 +452,7 @@ ksmbd_build_ntlmssp_challenge_blob(strucif (cflags &NTLMSSP_REQUEST_TARGET ) flags |=NTLMSSP_REQUEST_TARGET ; -if (conn->use_spnego && - (cflags &NTLMSSP_NEGOTIATE_EXTENDED_SEC )) +if (cflags &NTLMSSP_NEGOTIATE_EXTENDED_SEC ) flags |=NTLMSSP_NEGOTIATE_EXTENDED_SEC ;if (cflags &NTLMSSP_NEGOTIATE_KEY_XCH )
Greg Kroah-Hartman
maintainerPATCH 513/2857 ksmbd: fix overflow in dacloffset bounds check in build_sec_desc()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giorgi Kobakhia <[email protected]>
commit eb96e2a0e817807c48dc8387ca6a5249fdeae3a0 upstream.
When the large dacl_offset is provided, dacl_offset + sizeof(struct smb_acl) overflows on 32-bit builds and the check is passed, Which makes le16_to_cpu(ppdacl_ptr->size) read out-of-bounds. This only happens for dacl_offset in range [0xFFFFFFF8, 0xFFFFFFFF]. So the oob read is max 8 bytes preceding the allocated ppntsd.
unsigned int dacl_offset = le32_to_cpu(ppntsd->dacloffset);
int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset;
if (!dacl_offset ||
(dacl_offset + sizeof(struct smb_acl) > ppntsd_size))
goto out;Commit beff0bc9d69b ("ksmbd: fix overflow in dacloffset bounds check") fixes similar checks in other functions. But leaves this one out, because it is only valid for 32-bit builds.
Reproduced on 32-bit ARM with KASAN, by a client sending SMB2 SET_INFO(SEC) with dacloffset=0xfffffff8, then QUERY_INFO(SEC) on the same file:
BUG: KASAN: slab-out-of-bounds in build_sec_desc (fs/smb/server/smbacl.c:1105) Read of size 2 at addr c2a273fa by task kworker/1:1/35 CPU: 1 UID: 0 PID: 35 Comm: kworker/1:1 Not tainted 7.3.0-rc2+ #5 Workqueue: ksmbd-io handle_ksmbd_work Call trace: kasan_check_range from build_sec_desc (fs/smb/server/smbacl.c:1105) build_sec_desc from smb2_query_info (fs/smb/server/smb2pdu.c:7676) smb2_query_info from handle_ksmbd_work (fs/smb/server/server.c:160) handle_ksmbd_work from process_one_work (kernel/workqueue.c:3401) process_one_work from worker_thread (kernel/workqueue.c:3473) worker_thread from kthread (kernel/kthread.c:436)
Add overflow check.
--- fs/smb/server/smbacl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/smbacl.c +4 -1
@@ -1080,9 +1080,12 @@ int build_sec_desc(struct user_namespacestruct smb_acl *ppdacl_ptr;unsigned int dacl_offset =le32_to_cpu (ppntsd->dacloffset);int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset; +size_t dacl_struct_end;if (!dacl_offset || - (dacl_offset +sizeof (struct smb_acl ) > ppntsd_size)) +check_add_overflow (dacl_offset,sizeof (struct smb_acl ), + &dacl_struct_end) || + dacl_struct_end > (size_t )ppntsd_size) goto out; ppdacl_ptr = (struct smb_acl *)((char *)ppntsd + dacl_offset);
Greg Kroah-Hartman
maintainerPATCH 514/2857 ksmbd: ignore network devices of other namespaces
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jan Koester <[email protected]>
commit 1f5ce2b8b9164b3fcb93a18fe1e7b451c2fc6eea upstream.
With no interface list configured, ksmbd binds every interface that comes up. ksmbd_netdev_event() does not look at the device's namespace, and create_socket() opens the listener in the namespace of the task raising NETDEV_UP. A container with its own address on a bridge brings up its interface and finds port 445 in its namespace already taken by ksmbd, so an SMB server running inside the container fails with "Address already in use".
Interfaces are also matched by name only, so a container's eth0 going down would stop the listener on the host's eth0.
Only handle netdev events for devices in init_net.
--- fs/smb/server/transport_tcp.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/smb/server/transport_tcp.c +9 -0
@@ -574,6 +574,15 @@ static int ksmbd_netdev_event(struct notstruct interface *iface;int ret; +/* +* ksmbd serves the initial namespace only. create_socket() listens in +* the namespace of the task raising the event, so a container bringing +* up its own interface would get a listener on its port 445, and the +* name-only interface lookup would let its interfaces stop ours. +*/ +if (!net_eq (dev_net (netdev), &init_net)) +return NOTIFY_DONE ; +switch (event) {case NETDEV_UP :if (netif_is_bridge_port (netdev))
Greg Kroah-Hartman
maintainerPATCH 515/2857 ksmbd: preserve unreadable named streams on open
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 80c816c047f7cae3c99cc75740c1f5d2c4d97b45 upstream.
A write-only client can open an existing named stream with FILE_OPEN_IF without permission to read the underlying file. The case-insensitive lookup finds the xattr name, but querying its value length then fails with -EACCES. smb2_set_stream_name_xattr() treats every negative result as a missing stream and replaces the existing xattr with an empty value.
A failed xattr list is not proof that the stream is absent either:
for example, -ENOMEM can lead to the same empty replacement. Preserve listing errors and create a stream only for -ENOENT or -ENODATA. The latter can occur if the xattr is removed between listing its name and querying its value. Return other lookup errors without changing the stream.
A write-only FILE_OPEN now reports access denied instead of name not found. FILE_OVERWRITE_IF and FILE_SUPERSEDE on an unreadable stream also fail instead of appearing to replace it. Stream writes and EOF changes already need to read the old value, so such handles cannot update the stream after opening either.
--- fs/smb/server/smb2pdu.c | 2 ++ fs/smb/server/vfs.c | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +2 -0
@@ -2533,6 +2533,8 @@ static noinline int smb2_set_stream_name xattr_stream_size);if (rc >=0 )return 0 ; +if (rc != -ENOENT && rc != -ENODATA ) +return rc;if (fp->cdoption ==FILE_OPEN_LE ) {ksmbd_debug (SMB ,"XATTR stream name lookup failed: %d\n" , rc);
fs/smb/server/vfs.c +5 -1
@@ -1804,7 +1804,11 @@ ssize_t ksmbd_vfs_casexattr_len(struct ussize_t value_len = -ENOENT , xattr_list_len; xattr_list_len =ksmbd_vfs_listxattr (dentry, &xattr_list); -if (xattr_list_len <=0 ) +if (xattr_list_len <0 ) { + value_len = xattr_list_len; + goto out; + } +if (!xattr_list_len) goto out; for (name = xattr_list; name - xattr_list < xattr_list_len;
Greg Kroah-Hartman
maintainerPATCH 516/2857 ksmbd: reserve space for the UTF-16 terminator in stream info
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Abdifatah Suruur <[email protected]>
commit a025c4991a7d83edc4dd339e3ea86d8ff6226eca upstream.
smb_strtoUTF16() always writes a terminating zero UTF-16 unit after the converted characters, but get_file_stream_info() budgets only sizeof(struct smb2_file_stream_info) + streamlen * 2 for a stream entry and sizeof(struct smb2_file_stream_info) + 7 * 2 for the trailing "::$DATA" entry. When an entry exactly fills the 448-byte small response buffer, the terminator is written two bytes past the allocation.
Reserve one extra UTF-16 unit in both budget checks. The terminator is not part of the wire format, so the reported lengths are unchanged.
--- fs/smb/server/smb2pdu.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +3 -2
@@ -4837,7 +4837,8 @@ static void get_file_stream_info(struct ":%s", &stream_name[XATTR_NAME_STREAM_LEN]); next =sizeof (struct smb2_file_stream_info ) + streamlen *2 ; -if (next > buf_free_len) { +/* smbConvertToUTF16() also writes a terminating UTF-16 unit. */ +if (next +sizeof (__le16) > buf_free_len) {kfree (stream_buf);break ; }
@@ -4859,7 +4860,7 @@ static void get_file_stream_info(struct out:if (!S_ISDIR (stat.mode) && - buf_free_len >=sizeof (struct smb2_file_stream_info ) +7 *2 ) { + buf_free_len >=sizeof (struct smb2_file_stream_info ) + (7 +1 ) *2 ) { file_info = (struct smb2_file_stream_info *) &rsp->Buffer[nbytes]; streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
Greg Kroah-Hartman
maintainerPATCH 517/2857 ksmbd: return end of file for reads past a named streams data
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: DaeMyung Kang <[email protected]>
commit 626611dc22a3b63b3264a7a797d9dbc530234fcd upstream.
A READ on a non-empty named stream at or beyond its end fails with STATUS_INVALID_PARAMETER. ksmbd_vfs_stream_read() returns -EINVAL when the offset is not below the stream length, and smb2_read() maps -EINVAL to that status.
smb2_read() already turns a zero-byte read into STATUS_END_OF_FILE, the status a regular file returns at its end, and an empty stream already takes that path. Return 0 instead of -EINVAL so that non-empty streams do the same. Clients that read a stream until end of file otherwise get an error once they have read all of its data.
The buffered copychunk path converts a zero-byte source read to -EIO, as it does for a regular file that shrinks during copying.
--- fs/smb/server/vfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/vfs.c +1 -1
@@ -303,7 +303,7 @@ static int ksmbd_vfs_stream_read(structreturn (int )v_len;if (v_len <= *pos) { - count = -EINVAL ; + count =0 ; goto free_buf; }
Greg Kroah-Hartman
maintainerPATCH 518/2857 ksmbd: use u8 for SMB2 oplock level values
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit f622fedabbb58c8006ee21373968ae07bf8a9467 upstream.
The SMB2 oplock level is an unsigned 8-bit wire value, but smb20_oplock_break_ack() stores it in a plain char. On architectures where plain char is signed, the value 0xff becomes -1 and cannot compare equal to SMB2_OPLOCK_LEVEL_LEASE (0xff). The acknowledgment is consequently rejected with STATUS_INVALID_OPLOCK_PROTOCOL instead of the intended STATUS_INVALID_PARAMETER.
Use u8 for the request and response oplock-level variables. This preserves all wire values in their original representation.
--- fs/smb/server/smb2pdu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +1 -1
@@ -8345,7 +8345,7 @@ static void smb20_oplock_break_ack(struc__le32 status =STATUS_SUCCESS ;int ret;u64 volatile_id, persistent_id; -char req_oplevel =0 , rsp_oplevel =0 ; +u8 req_oplevel =0 , rsp_oplevel =0 ;WORK_BUFFERS (work, req, rsp);
Greg Kroah-Hartman
maintainerPATCH 519/2857 tcp: Fix potential UAF in reqsk_timer_handler().
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kuniyuki Iwashima <[email protected]>
commit 97c8a3c1f73d828de43a5a88e8a9a143efb2b661 upstream.
When TCP socket migration fails at inet_ehash_insert() in reqsk_timer_handler(), we jump to the no_ownership: label and free the new reqsk immediately with __reqsk_free().
Thus, we must stop the new reqsk's timer before jumping to the label, but the timer might be missed since the cited commit, resulting in UAF.
As we are in the original reqsk's timer context, we can safely call timer_delete_sync() for the new reqsk.
Let's pass false to __inet_csk_reqsk_queue_drop() to stop the new reqsk's timer.
--- net/ipv4/inet_connection_sock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/inet_connection_sock.c +1 -1
@@ -1098,7 +1098,7 @@ static void reqsk_timer_handler(struct tif (!inet_ehash_insert (req_to_sk (nreq),req_to_sk (oreq),NULL )) {/* delete timer */ -__inet_csk_reqsk_queue_drop (sk_listener, nreq, true); +__inet_csk_reqsk_queue_drop (sk_listener, nreq, false); goto no_ownership; }
Greg Kroah-Hartman
maintainerPATCH 520/2857 ext4: fix NULL folio dereference in mballoc
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Elliot Berman <[email protected]>
In 6.1, __filemap_get_folio() returns NULL on failure. The backported folio conversion of mballoc keeps the original IS_ERR() checks, so they are always false here. The fast-path lookup in ext4_mb_load_buddy_gfp() has no FGP_CREAT and returns NULL whenever the bitmap or buddy page of an initialised group has been evicted from the page cache, e.g. by drop_caches or memory pressure. The next block allocation from that group then oopses under ext4_mb_regular_allocator().
$ echo 3 > /proc/sys/vm/drop_caches, in 0.51 seconds) $ dd if=/dev/zero of=/mnt/b0 bs=1M count=4 conv=fsync BUG: kernel NULL pointer dereference, address: 0000000000000000 PGD 5f19067 P4D 0 Oops: 0000 [#1] PREEMPT SMP NOPTI CPU: 0 PID: 908 Comm: dd Not tainted 6.1.191 #1-NixOS Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.17.0-0-gb52ca86e094d-prebuilt.qemu.org 04/01/2014 RIP: 0010:ext4_mb_load_buddy_gfp (fs/ext4/mballoc.c:1536 (discriminator 1)) ext4 Call Trace: <TASK> ext4_mb_regular_allocator (fs/ext4/mballoc.c:1641 fs/ext4/mballoc.c:2798) ext4 ext4_mb_new_blocks (fs/ext4/mballoc.c:5793) ext4 ? ext4_find_extent (fs/ext4/extents.c:925) ext4 ext4_ext_map_blocks (fs/ext4/extents.c:4369) ext4 ...
Check for NULL instead and return -ENOMEM, as failures did before the conversion.
--- fs/ext4/mballoc.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-)
fs/ext4/mballoc.c +14 -14
@@ -1375,8 +1375,8 @@ static int ext4_mb_get_buddy_page_lock(struct super_block *sb, poff = block % blocks_per_page; folio =__filemap_get_folio (inode->i_mapping, pnum,FGP_LOCK |FGP_ACCESSED |FGP_CREAT , gfp); -if (IS_ERR (folio)) -return PTR_ERR (folio); +if (!folio) +return -ENOMEM ;BUG_ON (folio->mapping != inode->i_mapping); e4b->bd_bitmap_folio = folio; e4b->bd_bitmap =folio_address (folio) + (poff * sb->s_blocksize);
@@ -1389,8 +1389,8 @@ static int ext4_mb_get_buddy_page_lock(struct super_block *sb,/* blocks_per_page == 1, hence we need another page for the buddy */ folio =__filemap_get_folio (inode->i_mapping, block +1 ,FGP_LOCK |FGP_ACCESSED |FGP_CREAT , gfp); -if (IS_ERR (folio)) -return PTR_ERR (folio); +if (!folio) +return -ENOMEM ;BUG_ON (folio->mapping != inode->i_mapping); e4b->bd_buddy_folio = folio;return 0 ;
@@ -1533,7 +1533,7 @@ ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,/* Avoid locking the folio in the fast path ... */ folio =__filemap_get_folio (inode->i_mapping, pnum,FGP_ACCESSED ,0 ); -if (IS_ERR (folio) || !folio_test_uptodate (folio) ||folio_test_locked (folio)) { +if (!folio || !folio_test_uptodate (folio) ||folio_test_locked (folio)) {/* * folio_test_locked is employed to detect ongoing folio * migrations, since concurrent migrations can lead to
@@ -1543,11 +1543,11 @@ ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,* try to get the folio with lock in both cases to avoid * concurrency. */ -if (!IS_ERR (folio)) +if (folio)folio_put (folio); folio =__filemap_get_folio (inode->i_mapping, pnum,FGP_LOCK |FGP_ACCESSED |FGP_CREAT , gfp); -if (!IS_ERR (folio)) { +if (folio) {if (WARN_RATELIMIT (folio->mapping != inode->i_mapping,"ext4: bitmap's mapping != inode->i_mapping\n" )) {/* should never happen */
@@ -1567,8 +1567,8 @@ ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,folio_unlock (folio); } } -if (IS_ERR (folio)) { - ret =PTR_ERR (folio); +if (!folio) { + ret = -ENOMEM ; goto err; }if (!folio_test_uptodate (folio)) {
@@ -1585,12 +1585,12 @@ ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group, poff = block % blocks_per_page; folio =__filemap_get_folio (inode->i_mapping, pnum,FGP_ACCESSED ,0 ); -if (IS_ERR (folio) || !folio_test_uptodate (folio) ||folio_test_locked (folio)) { -if (!IS_ERR (folio)) +if (!folio || !folio_test_uptodate (folio) ||folio_test_locked (folio)) { +if (folio)folio_put (folio); folio =__filemap_get_folio (inode->i_mapping, pnum,FGP_LOCK |FGP_ACCESSED |FGP_CREAT , gfp); -if (!IS_ERR (folio)) { +if (folio) {if (WARN_RATELIMIT (folio->mapping != inode->i_mapping,"ext4: buddy bitmap's mapping != inode->i_mapping\n" )) {/* should never happen */
@@ -1609,8 +1609,8 @@ ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,folio_unlock (folio); } } -if (IS_ERR (folio)) { - ret =PTR_ERR (folio); +if (!folio) { + ret = -ENOMEM ; goto err; }if (!folio_test_uptodate (folio)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 521/2857 bs/ntfs3: fix NULL folio dereference in ntfs_lock_new_page()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Elliot Berman <[email protected]>
In 6.1, __filemap_get_folio() returns NULL on failure. The backport of commit 95b917a14b15 ("ntfs: Do not overwrite uptodate pages") keeps the original IS_ERR() check, which is always false here, so a failed folio allocation while reading a compressed file dereferences NULL in folio_test_uptodate(). Check for NULL and return ERR_PTR(-ENOMEM).
--- fs/ntfs3/frecord.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ntfs3/frecord.c +2 -2
@@ -2172,8 +2172,8 @@ static struct page *ntfs_lock_new_page(struct address_space *mapping, FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);struct page *page; -if (IS_ERR (folio)) -return ERR_CAST (folio); +if (!folio) +return ERR_PTR (-ENOMEM );if (!folio_test_uptodate (folio))return folio_file_page (folio, index);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 522/2857 Bluetooth: ISO: drop unbalanced sock_put() in iso_conn_ready()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
Commit 1702f12cf59a ("Bluetooth: ISO: fix use-after-free of listener socket in iso_conn_ready"), the 6.1.y backport of upstream 560bef609fa5, puts the listener when it is no longer listening. Upstream that put balances the reference taken by iso_get_sock(). On 6.1.y iso_get_sock_listen() takes no reference (it got one only in v6.8 with fa224d0c094a), and no other exit of iso_conn_ready() puts the parent.
No race is needed to hit it: shutdown() of a bound socket sets SOCK_ZAPPED and keeps BT_BOUND, so listen() still succeeds and the listener stays BT_LISTEN with SOCK_ZAPPED. Every incoming connection then takes the new branch, and the second one frees the listener while it is still on iso_sk_list and attached to its file.
Drop the put.
Found while reviewing a backport of this fix; not reproduced at runtime.
--- net/bluetooth/iso.c | 1 - 1 file changed, 1 deletion(-)
net/bluetooth/iso.c +0 -1
@@ -1536,7 +1536,6 @@ static void iso_conn_ready(struct iso_conn *conn)if (parent->sk_state !=BT_LISTEN ||sock_flag (parent,SOCK_ZAPPED )) {release_sock (parent); -sock_put (parent);return ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 523/2857 Revert "interconnect: Dont access req_list while its being manipulated"
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
This reverts commit 8401bc2c188030fb14d1cb43c402a1cf42d86dd2.
--- drivers/interconnect/core.c | 8 -------- 1 file changed, 8 deletions(-)
drivers/interconnect/core.c +0 -8
@@ -162,8 +162,6 @@ static struct icc_path *path_init(struct device *dev, struct icc_node *dst, path->num_nodes = num_nodes; -mutex_lock (&icc_bw_lock); -for (i = num_nodes -1 ; i >=0 ; i--) { node->provider->users++;hlist_add_head (&path->reqs[i].req_node, &node->req_list);
@@ -174,8 +172,6 @@ static struct icc_path *path_init(struct device *dev, struct icc_node *dst, node = node->reverse; } -mutex_unlock (&icc_bw_lock); -return path; }
@@ -783,16 +779,12 @@ void icc_put(struct icc_path *path)pr_err ("%s: error (%d)\n" , __func__, ret);mutex_lock (&icc_lock); -mutex_lock (&icc_bw_lock); -for (i =0 ; i < path->num_nodes; i++) { node = path->reqs[i].node;hlist_del (&path->reqs[i].req_node);if (!WARN_ON (!node->provider->users)) node->provider->users--; } - -mutex_unlock (&icc_bw_lock);mutex_unlock (&icc_lock);kfree_const (path->name);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 524/2857 Revert "interconnect: Fix locking for runpm vs reclaim"
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
This reverts commit ffb8917c70a4c88725ee40f9eeee9240ad1c1869.
--- drivers/interconnect/core.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-)
drivers/interconnect/core.c +2 -6
@@ -29,7 +29,6 @@ static LIST_HEAD(icc_providers);static int providers_count;static bool synced_state;static DEFINE_MUTEX (icc_lock); -static DEFINE_MUTEX (icc_bw_lock);static struct dentry *icc_debugfs_dir;static void icc_summary_show_one (struct seq_file *s,struct icc_node *n)
@@ -636,7 +635,7 @@ int icc_set_bw(struct icc_path *path, u32 avg_bw, u32 peak_bw)if (WARN_ON (IS_ERR (path) || !path->num_nodes))return -EINVAL ; -mutex_lock (&icc_bw_lock); +mutex_lock (&icc_lock); old_avg = path->reqs[0 ].avg_bw; old_peak = path->reqs[0 ].peak_bw;
@@ -668,7 +667,7 @@ int icc_set_bw(struct icc_path *path, u32 avg_bw, u32 peak_bw)apply_constraints (path); } -mutex_unlock (&icc_bw_lock); +mutex_unlock (&icc_lock);trace_icc_set_bw_end (path, ret);
@@ -972,7 +971,6 @@ void icc_node_add(struct icc_node *node, struct icc_provider *provider)return ;mutex_lock (&icc_lock); -mutex_lock (&icc_bw_lock); node->provider = provider;list_add_tail (&node->node_list, &provider->nodes);
@@ -998,7 +996,6 @@ void icc_node_add(struct icc_node *node, struct icc_provider *provider) node->avg_bw =0 ; node->peak_bw =0 ; -mutex_unlock (&icc_bw_lock);mutex_unlock (&icc_lock); }EXPORT_SYMBOL_GPL (icc_node_add);
@@ -1138,7 +1135,6 @@ void icc_sync_state(struct device *dev)return ;mutex_lock (&icc_lock); -mutex_lock (&icc_bw_lock); synced_state = true;list_for_each_entry (p, &icc_providers, provider_list) {dev_dbg (p->dev,"interconnect provider is in synced state\n" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 525/2857 net: stmmac: dont clear network statistics in .ndo_open()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jisheng Zhang <[email protected]>
[ Upstream commit 2eb85b750512cc5dc5a93d5ff00e1f83b99651db ]
FWICT, the common style in other network drivers: the network statistics are not cleared since initialization, follow the common style for stmmac.
--- drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -4
@@ -3811,10 +3811,6 @@ static int __stmmac_open(struct net_device *dev, } } -/* Extra statistics */ -memset (&priv->xstats,0 ,sizeof (struct stmmac_extra_stats )); - priv->xstats.threshold = tc; - priv->rx_copybreak =STMMAC_RX_COPYBREAK ; buf_sz = dma_conf->dma_buf_sz;
@@ -7434,6 +7430,8 @@ int stmmac_dvr_probe(struct device *device,#endif priv->msg_enable =netif_msg_init (debug, default_msg_level); + priv->xstats.threshold = tc; +/* Initialize RSS */ rxq = priv->plat->rx_queues_to_use;netdev_rss_key_fill (priv->rss.key,sizeof (priv->rss.key));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 526/2857 net: stmmac: protect updates of 64-bit statistics counters
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Petr Tesarik <[email protected]>
[ Upstream commit 38cc3c6dcc09dc3a1800b5ec22aef643ca11eab8 ]
As explained by a comment in <linux/u64_stats_sync.h>, write side of struct u64_stats_sync must ensure mutual exclusion, or one seqcount update could be lost on 32-bit platforms, thus blocking readers forever. Such lockups have been observed in real world after stmmac_xmit() on one CPU raced with stmmac_napi_poll_tx() on another CPU.
To fix the issue without introducing a new lock, split the statics into three parts:
1. fields updated only under the tx queue lock,
2. fields updated only during NAPI poll,
3. fields updated only from interrupt context,
Updates to fields in the first two groups are already serialized through other locks. It is sufficient to split the existing struct u64_stats_sync so that each group has its own.
Note that tx_set_ic_bit is updated from both contexts. Split this counter so that each context gets its own, and calculate their sum to get the total value in stmmac_get_ethtool_stats().
For the third group, multiple interrupts may be processed by different CPUs at the same time, but interrupts on the same CPU will not nest. Move fields from this group to a newly created per-cpu struct stmmac_pcpu_stats.
--- drivers/net/ethernet/stmicro/stmmac/common.h | 56 +++++--- .../net/ethernet/stmicro/stmmac/dwmac-sun8i.c | 15 +- .../net/ethernet/stmicro/stmmac/dwmac4_lib.c | 15 +- .../net/ethernet/stmicro/stmmac/dwmac_lib.c | 15 +- .../ethernet/stmicro/stmmac/dwxgmac2_dma.c | 15 +- .../ethernet/stmicro/stmmac/stmmac_ethtool.c | 129 +++++++++++------ .../net/ethernet/stmicro/stmmac/stmmac_main.c | 133 +++++++++--------- 7 files changed, 221 insertions(+), 157 deletions(-)
drivers/net/ethernet/stmicro/stmmac/common.h +40 -16
@@ -58,28 +58,51 @@#undef FRAME_FILTER_DEBUG/* #define FRAME_FILTER_DEBUG */ +struct stmmac_q_tx_stats { +u64_stats_t tx_bytes; +u64_stats_t tx_set_ic_bit; +u64_stats_t tx_tso_frames; +u64_stats_t tx_tso_nfrags; +}; + +struct stmmac_napi_tx_stats { +u64_stats_t tx_packets; +u64_stats_t tx_pkt_n; +u64_stats_t poll; +u64_stats_t tx_clean; +u64_stats_t tx_set_ic_bit; +}; +struct stmmac_txq_stats { -u64 tx_bytes; -u64 tx_packets; -u64 tx_pkt_n; -u64 tx_normal_irq_n; -u64 napi_poll; -u64 tx_clean; -u64 tx_set_ic_bit; -u64 tx_tso_frames; -u64 tx_tso_nfrags; -struct u64_stats_sync syncp; +/* Updates protected by tx queue lock. */ +struct u64_stats_sync q_syncp; +struct stmmac_q_tx_stats q; + +/* Updates protected by NAPI poll logic. */ +struct u64_stats_sync napi_syncp; +struct stmmac_napi_tx_stats napi; }____cacheline_aligned_in_smp ; +struct stmmac_napi_rx_stats { +u64_stats_t rx_bytes; +u64_stats_t rx_packets; +u64_stats_t rx_pkt_n; +u64_stats_t poll; +}; +struct stmmac_rxq_stats { -u64 rx_bytes; -u64 rx_packets; -u64 rx_pkt_n; -u64 rx_normal_irq_n; -u64 napi_poll; -struct u64_stats_sync syncp; +/* Updates protected by NAPI poll logic. */ +struct u64_stats_sync napi_syncp; +struct stmmac_napi_rx_stats napi; }____cacheline_aligned_in_smp ; +/* Updates on each CPU protected by not allowing nested irqs. */ +struct stmmac_pcpu_stats { +struct u64_stats_sync syncp; +u64_stats_t rx_normal_irq_n[MTL_MAX_TX_QUEUES ]; +u64_stats_t tx_normal_irq_n[MTL_MAX_RX_QUEUES ]; +}; +/* Extra statistic and debug information exposed by ethtool */ struct stmmac_extra_stats {/* Transmit errors */
@@ -204,6 +227,7 @@ struct stmmac_extra_stats {/* per queue statistics */ struct stmmac_txq_stats txq_stats[MTL_MAX_TX_QUEUES ];struct stmmac_rxq_stats rxq_stats[MTL_MAX_RX_QUEUES ]; +struct stmmac_pcpu_stats __percpu *pcpu_stats;unsigned long rx_dropped;unsigned long rx_errors;unsigned long tx_dropped;
drivers/net/ethernet/stmicro/stmmac/dwmac-sun8i.c +7 -8
@@ -440,8 +440,7 @@ static int sun8i_dwmac_dma_interrupt(struct stmmac_priv *priv, struct stmmac_extra_stats *x, u32 chan, u32 dir) { - struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[chan]; -struct stmmac_txq_stats *txq_stats = &priv->xstats.txq_stats[chan]; + struct stmmac_pcpu_stats *stats = this_cpu_ptr(priv->xstats.pcpu_stats);int ret =0 ;u32 v;
@@ -454,9 +453,9 @@ static int sun8i_dwmac_dma_interrupt(struct stmmac_priv *priv,if (v &EMAC_TX_INT ) { ret |= handle_tx; -u64_stats_update_begin (&txq_stats->syncp); - txq_stats->tx_normal_irq_n++; -u64_stats_update_end (&txq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->tx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); }if (v &EMAC_TX_DMA_STOP_INT )
@@ -478,9 +477,9 @@ static int sun8i_dwmac_dma_interrupt(struct stmmac_priv *priv,if (v &EMAC_RX_INT ) { ret |= handle_rx; -u64_stats_update_begin (&rxq_stats->syncp); - rxq_stats->rx_normal_irq_n++; -u64_stats_update_end (&rxq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->rx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); }if (v &EMAC_RX_BUF_UA_INT )
drivers/net/ethernet/stmicro/stmmac/dwmac4_lib.c +7 -8
@@ -171,8 +171,7 @@ int dwmac4_dma_interrupt(struct stmmac_priv *priv, void __iomem *ioaddr,const struct dwmac4_addrs *dwmac4_addrs = priv->plat->dwmac4_addrs;u32 intr_status =readl (ioaddr +DMA_CHAN_STATUS (dwmac4_addrs, chan));u32 intr_en =readl (ioaddr +DMA_CHAN_INTR_ENA (dwmac4_addrs, chan)); -struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[chan]; -struct stmmac_txq_stats *txq_stats = &priv->xstats.txq_stats[chan]; +struct stmmac_pcpu_stats *stats =this_cpu_ptr (priv->xstats.pcpu_stats);int ret =0 ;if (dir ==DMA_DIR_RX )
@@ -201,15 +200,15 @@ int dwmac4_dma_interrupt(struct stmmac_priv *priv, void __iomem *ioaddr, }/* TX/RX NORMAL interrupts */ if (likely (intr_status &DMA_CHAN_STATUS_RI )) { -u64_stats_update_begin (&rxq_stats->syncp); - rxq_stats->rx_normal_irq_n++; -u64_stats_update_end (&rxq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->rx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_rx; }if (likely (intr_status &DMA_CHAN_STATUS_TI )) { -u64_stats_update_begin (&txq_stats->syncp); - txq_stats->tx_normal_irq_n++; -u64_stats_update_end (&txq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->tx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_tx; }
drivers/net/ethernet/stmicro/stmmac/dwmac_lib.c +7 -8
@@ -162,8 +162,7 @@ static void show_rx_process_state(unsigned int status)int dwmac_dma_interrupt (struct stmmac_priv *priv,void __iomem *ioaddr,struct stmmac_extra_stats *x,u32 chan,u32 dir) { -struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[chan]; -struct stmmac_txq_stats *txq_stats = &priv->xstats.txq_stats[chan]; +struct stmmac_pcpu_stats *stats =this_cpu_ptr (priv->xstats.pcpu_stats);int ret =0 ;/* read the status register (CSR5) */ u32 intr_status =readl (ioaddr +DMA_STATUS );
@@ -215,16 +214,16 @@ int dwmac_dma_interrupt(struct stmmac_priv *priv, void __iomem *ioaddr,u32 value =readl (ioaddr +DMA_INTR_ENA );/* to schedule NAPI on real RIE event. */ if (likely (value &DMA_INTR_ENA_RIE )) { -u64_stats_update_begin (&rxq_stats->syncp); - rxq_stats->rx_normal_irq_n++; -u64_stats_update_end (&rxq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->rx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_rx; } }if (likely (intr_status &DMA_STATUS_TI )) { -u64_stats_update_begin (&txq_stats->syncp); - txq_stats->tx_normal_irq_n++; -u64_stats_update_end (&txq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->tx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_tx; }if (unlikely (intr_status &DMA_STATUS_ERI ))
drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c +7 -8
@@ -333,8 +333,7 @@ static int dwxgmac2_dma_interrupt(struct stmmac_priv *priv, struct stmmac_extra_stats *x, u32 chan, u32 dir) { - struct stmmac_rxq_stats *rxq_stats = &priv->xstats.rxq_stats[chan]; -struct stmmac_txq_stats *txq_stats = &priv->xstats.txq_stats[chan]; + struct stmmac_pcpu_stats *stats = this_cpu_ptr(priv->xstats.pcpu_stats);u32 intr_status =readl (ioaddr +XGMAC_DMA_CH_STATUS (chan));u32 intr_en =readl (ioaddr +XGMAC_DMA_CH_INT_EN (chan));int ret =0 ;
@@ -363,15 +362,15 @@ static int dwxgmac2_dma_interrupt(struct stmmac_priv *priv,/* TX/RX NORMAL interrupts */ if (likely (intr_status &XGMAC_NIS )) {if (likely (intr_status &XGMAC_RI )) { -u64_stats_update_begin (&rxq_stats->syncp); - rxq_stats->rx_normal_irq_n++; -u64_stats_update_end (&rxq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->rx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_rx; }if (likely (intr_status & (XGMAC_TI |XGMAC_TBU ))) { -u64_stats_update_begin (&txq_stats->syncp); - txq_stats->tx_normal_irq_n++; -u64_stats_update_end (&txq_stats->syncp); +u64_stats_update_begin (&stats->syncp); +u64_stats_inc (&stats->tx_normal_irq_n[chan]); +u64_stats_update_end (&stats->syncp); ret |= handle_tx; } }
drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +87 -42
170 lines not on this page · raw message
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +66 -67
273 lines not on this page · raw message
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 527/2857 x86/ioperm: Prevent NULL dereference on theoretical missing IO bitmap
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
[ Upstream commit 2d36d3b451a94899db9c965adde15492ffe6027a ]
Outside the IOPL emulation path, the IO bitmap is always expected to be allocated when TIF_IO_BITMAP is set. The paranoid WARN_ON_ONCE() handles the case where the flag and the pointer got out of sync. In this theoretical scenario, which presumes some other bug in the code that triggers the WARN_ON_ONCe(), return early, instead of continuing and dereferencing a NULL pointer.
[ mingo: Clarified the changelog. ]
--- arch/x86/kernel/process.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kernel/process.c +1 -0
@@ -432,6 +432,7 @@ void native_tss_update_io_bitmap(void)if (WARN_ON_ONCE (!iobm)) {clear_thread_flag (TIF_IO_BITMAP );native_tss_invalidate_io_bitmap (); +return ; }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 528/2857 wifi: b43: fix use-after-free in b43_bcma_remove()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Wendleder <[email protected]>
commit c6c8bc355657115664131b38c53c5ddf7d93b072 upstream.
b43_one_core_detach() frees the struct b43_wldev it is given the bus device of. b43_bcma_remove() then reads wldev->dev again to free the bus device, which is a read of freed memory.
b43_ssb_remove() does not have the problem: it takes a copy of wldev->dev at the start. Do the same here.
--- drivers/net/wireless/broadcom/b43/main.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/wireless/broadcom/b43/main.c +3 -2
@@ -5658,6 +5658,7 @@ static void b43_bcma_remove(struct bcma_ {struct b43_wldev *wldev =bcma_get_drvdata (core);struct b43_wl *wl = wldev->wl; +struct b43_bus_dev *dev = wldev->dev;/* We must cancel any work here before unregistering from ieee80211, * as the ieee80211 unreg will destroy the workqueue. */
@@ -5672,14 +5673,14 @@ static void b43_bcma_remove(struct bcma_ieee80211_unregister_hw (wl->hw); } -b43_one_core_detach (wldev->dev); +b43_one_core_detach (dev);/* Unregister HW RNG driver */ b43_rng_exit (wl);b43_leds_unregister (wl);ieee80211_free_hw (wl->hw); -kfree (wldev->dev); +kfree (dev); }static struct bcma_driver b43_bcma_driver = {
Greg Kroah-Hartman
maintainerPATCH 529/2857 SUNRPC: fix netns use-after-free in write_gssp()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zijing Yin <[email protected]>
commit e7a8721b7edb54a157623f9e31d71345333b5fb9 upstream.
While fuzzing with a customized syzkaller, I hit a refcount warning in xprt_alloc(), reached from a write to /proc/net/rpc/use-gss-proxy:
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xf8/0x120 CPU: 0 PID: 10404 Comm: syz.0.17 Not tainted 7.3.0-rc1-00096-gcfebfd3db73d Call Trace: <TASK> xprt_alloc+0x83f/0x9d0 xs_setup_xprt+0xaf/0x3c0 xs_setup_local+0x47/0x7f0 xprt_create_transport+0x16c/0x730 rpc_create+0x38e/0x7f0 gssp_rpc_create+0xe2/0x180 set_gssp_clnt+0xba/0x1b0 write_gssp+0x200/0x310 proc_reg_write+0x240/0x330 vfs_write+0x2aa/0x1050 ksys_write+0x12a/0x250 do_syscall_64+0x117/0x750 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
create_use_gss_proxy_proc_entry() stores the struct net pointer as the proc entry's private data without taking a reference on it, and an open file descriptor does not pin the namespace either, as procfs only pins the proc_dir_entry. write_gssp() reads that pointer back with pde_data() and hands it to set_gssp_clnt(), which reaches xprt_init():
xprt->xprt_net = get_net_track(net, &xprt->ns_tracker, GFP_KERNEL);
get_net_track() -> get_net() -> refcount_inc() is unconditional, so rpc_create() assumes its caller holds a reference on args.net. write_gssp() does not.
Dropping the last ns.count reference does not make the file go away. __put_net() only queues cleanup_net() on a workqueue, and the remove_proc_entry() that fences off further writes runs from the rpcsec_gss pernet .exit method, that is, from inside cleanup_net(). A write landing between those two points increments a refcount that is already zero. cleanup_net() does not re-read ns.count, so the namespace is freed anyway and the rpc_xprt -- along with the AF_LOCAL socket opened for it -- is left pointing at freed memory. The resurrected count is visible to the rest of that teardown too: with CONFIG_IPV6_MROUTE the same cleanup_net() worker then trips !mr_can_free_table() in ip6mr_free_table(), which tests check_net() on the namespace it is freeing.
It reduces to opening /proc/net/rpc/use-gss-proxy inside a new network namespace, calling setns() back to the original one to drop the last reference, and then writing "1" to the still-open descriptor.
Take the reference in write_gssp() itself and refuse the write when the namespace is already gone. This is what procfs does for every other /proc/net file: get_proc_net() is maybe_get_net(PDE_NET(PDE(inode))) and seq_open_net() returns -ENXIO when it fails. PDE_NET() cannot be reused here because the parent directory /proc/net/rpc carries no namespace pointer. Adding a .pre_exit to rpcsec_gss_net_ops so the entry is removed earlier would only narrow the window, since pre_exit also runs from cleanup_net().
Live namespaces are unaffected: a write still returns the error from set_gssp_clnt(), a write of "2" still returns -EINVAL, and reads are untouched.
--- net/sunrpc/auth_gss/svcauth_gss.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
net/sunrpc/auth_gss/svcauth_gss.c +11 -3
@@ -1449,10 +1449,18 @@ static ssize_t write_gssp(struct file *freturn res;if (i !=1 )return -EINVAL ; + +/* +* Neither the proc entry nor an open descriptor pins @net, so it +* might already be dying when rpc_create() takes its reference. +*/ +if (!maybe_get_net (net)) +return -ENXIO ; + res =set_gssp_clnt (net); -if (res) -return res; - res =set_gss_proxy (net,1 ); +if (!res) + res =set_gss_proxy (net,1 ); +put_net (net);if (res)return res;return count;
Greg Kroah-Hartman
maintainerPATCH 530/2857 smb: client: fix use-after-free in cifs_ses_add_channel()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Henry Martin <[email protected]>
commit 031278577380e7875d95aed81a2b2bcac39be923 upstream.
The error path of cifs_ses_add_channel() calls cifs_put_tcp_session() before cifs_chan_clear_need_reconnect(). The latter reaches cifs_ses_get_chan_index(), which dereferences server->terminate; if the put was the final reference, TCP_Server_Info is already freed and this is a use-after-free. Same put-then-use pattern as the recently fixed sibling in commit 717e0a25036b ("cifs: Fix server use-after-free in cifs_chan_skip_or_disable()").
Move the put last, but do not read chan->server after droppingchan_lock: chan points into ses->chans[], and once chan_count is decremented a concurrent add_channel can reuse the slot and overwrite the pointer, so the put would act on the new channel's server. Cache the pointer under chan_lock, clear the reconnect bit and decrement chan_count while still holding the reference, and release it after the unlock.
This issue was discovered by Tencent CodeBuddy Security.
--- fs/smb/client/sess.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +4 -2
@@ -650,12 +650,13 @@ cifs_ses_add_channel(struct cifs_sb_info out:if (rc && chan->server) { -cifs_put_tcp_session (chan->server,0 ); +struct TCP_Server_Info *pserver;spin_lock (&ses->chan_lock); + pserver = chan->server;/* we rely on all bits beyond chan_count to be clear */ -cifs_chan_clear_need_reconnect (ses, chan->server); +cifs_chan_clear_need_reconnect (ses, pserver); ses->chan_count--;/* * chan_count should never reach 0 as at least the primary
@@ -663,6 +664,7 @@ out:*/ WARN_ON (ses->chan_count <1 );spin_unlock (&ses->chan_lock); +cifs_put_tcp_session (pserver,0 ); }free_xid (xid);
Greg Kroah-Hartman
maintainerPATCH 531/2857 rapidio: mport_cdev: fix use-after-free in mport_mm_close()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Kim <[email protected]>
commit 0f2cd84858e67cf8e02438bf28243bcdc67aa49a upstream.
A use-after-free vulnerability was identified in mport_mm_close() in drivers/rapidio/devices/rio_mport_cdev.c, identical to the pattern previously addressed in dma_req_free().
This is observable from userspace when an application creates an mmap mapping via the RapidIO character device and subsequently unmaps it (or terminates, triggering exit_mmap()). During munmap, mport_mm_close() is invoked and drops the mapping reference via kref_put().
If kref_put() drops the last reference, mport_release_mapping() is called, which frees the underlying rio_mport_mapping structure. The subsequent mutex_unlock() then dereferences map->md to unlock buf_mutex, leading to a use-after-free:
mport_mm_close()
-> mutex_lock(&map->md->buf_mutex);
...
-> kref_put(&map->ref, mport_release_mapping); /* map is freed */
-> mutex_unlock(&map->md->buf_mutex); /* UAF: map used */Fix this by caching map->md before kref_put() and using the cached pointer for mutex unlocking, ensuring that freed memory is not accessed.
--- drivers/rapidio/devices/rio_mport_cdev.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/rapidio/devices/rio_mport_cdev.c +3 -2
@@ -2186,11 +2186,12 @@ static void mport_mm_open(struct vm_areastatic void mport_mm_close (struct vm_area_struct *vma) {struct rio_mport_mapping *map = vma->vm_private_data; +struct mport_dev *md = map->md;rmcd_debug (MMAP ,"%pad" , &map->phys_addr); -mutex_lock (&map->md->buf_mutex); +mutex_lock (&md->buf_mutex);kref_put (&map->ref, mport_release_mapping); -mutex_unlock (&map->md->buf_mutex); +mutex_unlock (&md->buf_mutex); }static const struct vm_operations_struct vm_ops = {
Greg Kroah-Hartman
maintainerPATCH 532/2857 nvmet-fc: fix use-after-free in nvmet_fc_ls_create_connection()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 2c29f8c9b9e598c09fa50aa02200136a107f6b3f upstream.
nvmet_fc_ls_create_connection() looks up the association with nvmet_fc_find_target_assoc(), which returns it with a reference held, and drops that reference as soon as the target queue has been allocated. iod->assoc is then dereferenced again by nvmet_fc_makeconnid() while building the connection id.
The queue only borrows the pointer and takes no reference of its own. Once the lookup reference is dropped the association is kept alive solely by the reference taken when it was created, so a disconnect LS or a remote port unregister running concurrently can free it before nvmet_fc_makeconnid() reads it:
BUG: KASAN: slab-use-after-free in nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) Read of size 8 at addr ffff888179f1b000 by task kworker/u9:2/1167 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 Workqueue: nvmet-wq nvmet_fc_handle_ls_rqst_work Call Trace: <TASK> dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120) print_report (mm/kasan/report.c:378 mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) </TASK> Freed by task 1167 on cpu 0 at 405.998150s: kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:78) kasan_save_free_info (mm/kasan/generic.c:584) __kasan_slab_free (mm/kasan/common.c:253 mm/kasan/common.c:285) kfree (include/linux/kasan.h:235 mm/slub.c:2705 mm/slub.c:6405 mm/slub.c:6720) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:1808 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) The buggy address belongs to the object at ffff888179f1b000 which belongs to the cache kmalloc-2k of size 2048
The buggy address is located 0 bytes inside of
freed 2048-byte region [ffff888179f1b000, ffff888179f1b800)
Hold the lookup reference until the response has been built, and drop it on the error path as well.
--- drivers/nvme/target/fc.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/nvme/target/fc.c +5 -3
@@ -1773,9 +1773,6 @@ nvmet_fc_ls_create_connection(struct nvm be16_to_cpu(rqst->connect_cmd.sqsize));if (!queue) ret =VERR_QUEUE_ALLOC_FAIL ; - -/* release get taken in nvmet_fc_find_target_assoc */ -nvmet_fc_tgt_a_put (iod->assoc); } }
@@ -1789,6 +1786,8 @@ nvmet_fc_ls_create_connection(struct nvm FCNVME_RJT_RC_INV_ASSOC :FCNVME_RJT_RC_LOGIC , FCNVME_RJT_EXP_NONE, 0); +if (iod->assoc) +nvmet_fc_tgt_a_put (iod->assoc);return ; }
@@ -1810,6 +1809,9 @@ nvmet_fc_ls_create_connection(struct nvm acc->connectid.connection_id =cpu_to_be64 (nvmet_fc_makeconnid (iod->assoc,be16_to_cpu (rqst->connect_cmd.qid))); + +/* release get taken in nvmet_fc_find_target_assoc */ +nvmet_fc_tgt_a_put (iod->assoc); }/*
Greg Kroah-Hartman
maintainerPATCH 533/2857 landlock: Fix superblock use-after-free in release_inode()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Günther Noack <[email protected]>
commit 3e271a27c46fd591d1011c7de5a644a41e2010f1 upstream.
Without this fix, release_inode() (task 1) can race with a umount operation in hook_sb_delete() (task 2). The order of operations in which the race occurs is:
* task 2: hook_sb_delete() arrives at the end of the function, waiting for landlock_superblock(sb)->inode_refs to become zero.
* task 1: release_inode(): does atomic_long_dec_and_test(), decrementing inode_refs to zero.
* task 2: gets woken up through some other means, sees that inode_refs is zero and returns. The caller is the unmount operation and proceeds to release the superblock.
* task 1: Runs wake_up_var(&landlock_superblock(sb)->inode_refs), *dereferencing the sb_security on the freed-up superblock*.
Notably, wake_up_var() does not dereference the pointer passed to it, and only uses it to determine an overapproximated set of tasks to wake up. So while it's potentially possible for an attacker to provide a different value for that pointer, this only results in the wrong set of tasks getting woken up, and in this scenario, no further tasks are actually waiting.
Nevertheless, KASAN detects it as a slab-use-after-free read on sb->s_security:
BUG: KASAN: slab-use-after-free in release_inode+0x196/0x290 Read of size 8 at addr ffff888103b6c0a8 by task repro/217 release_inode+0x196/0x290 landlock_put_object+0x71/0x90 landlock_free_rules+0x38/0xc0 landlock_put_ruleset+0x47/0x130 fop_ruleset_release+0x33/0x40 __fput+0x305/0x780 Freed by task 54: kfree+0x11c/0x390 process_scheduled_works+0x766/0xe50 worker_thread+0x7bc/0xb20
The fix is to determine &landlock_superblock(inode->i_sb)->inode_refs only once earlier in release_inode(), and later use that precalculated address for the wake_up_var() call, without having to dereference through the superblock.
--- security/landlock/fs.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
security/landlock/fs.c +5 -5
@@ -45,7 +45,7 @@ static void release_inode(struct landloc __releases(object->lock) {struct inode *const inode = object->underobj; -struct super_block *sb; +atomic_long_t *inode_refs;if (!inode) {spin_unlock (&object->lock);
@@ -61,8 +61,8 @@ static void release_inode(struct landloc* Makes sure that if the filesystem is concurrently unmounted, * hook_sb_delete() will wait for us to finish iput(). */ - sb = inode->i_sb; -atomic_long_inc (&landlock_superblock (sb)->inode_refs); + inode_refs = &landlock_superblock (inode->i_sb)->inode_refs; +atomic_long_inc (inode_refs);spin_unlock (&object->lock);/* * Because object->underobj was not NULL, hook_sb_delete() and
@@ -76,8 +76,8 @@ static void release_inode(struct landloc*/ iput (inode); -if (atomic_long_dec_and_test (&landlock_superblock (sb)->inode_refs)) -wake_up_var (&landlock_superblock (sb)->inode_refs); +if (atomic_long_dec_and_test (inode_refs)) +wake_up_var (inode_refs); }static const struct landlock_object_underops landlock_fs_underops = {
Greg Kroah-Hartman
maintainerPATCH 534/2857 lockd: Fix use-after-free in nlmsvc_retry_blocked
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit f5b7634f0f213299a07b461fb10385c8639a4ab8 upstream.
nlmsvc_retry_blocked() examines the block at the head of nlm_blocked under nlm_blocked_lock, then releases the lock before calling nlmsvc_grant_blocked() or retry_deferred_block(). The nlm_blocked list reference is all that keeps the block alive across that window. nlmsvc_grant_blocked() does take one of its own, but not until after the lock has been dropped. Unmounting the nfsd filesystem while a lock request is still blocked reaches nlmsvc_traverse_blocks(), which drops the list reference and frees the block along with the nlm_rqst hanging off it.
BUG: KASAN: slab-use-after-free in nlm_async_call+0xd6/0x230
Read of size 8 at addr ffff88811b04c808 by task lockd/8377
nlm_async_call+0xd6/0x230
nlmsvc_retry_blocked+0x61c/0x800
lockd+0x144/0x1c0
Freed by task 8392:
nlmsvc_release_block+0x231/0x290
nlmsvc_traverse_blocks+0x139/0x1b0
nlm_traverse_files+0x1aa/0xa00
nlmsvc_free_host_resources+0x12/0x60
nlm_shutdown_hosts_net+0x127/0x280
lockd_down+0xd5/0x1c0Take a reference before releasing nlm_blocked_lock and drop it once the retry has run.
--- fs/lockd/svclock.c | 2 ++ 1 file changed, 2 insertions(+)
fs/lockd/svclock.c +2 -0
@@ -1014,6 +1014,7 @@ nlmsvc_retry_blocked(void) timeout = block->b_when - jiffies;break ; } +kref_get (&block->b_count);spin_unlock (&nlm_blocked_lock); dprintk("nlmsvc_retry_blocked(%p, when=%ld)\n",
@@ -1024,6 +1025,7 @@ nlmsvc_retry_blocked(void)retry_deferred_block (block); }else nlmsvc_grant_blocked (block); +nlmsvc_release_block (block);spin_lock (&nlm_blocked_lock); }spin_unlock (&nlm_blocked_lock);
Greg Kroah-Hartman
maintainerPATCH 535/2857 media: au0828: fix use-after-free in bulk_timeout timer on disconnect
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 521030837bee352515d5ea57cc6a29581db3506e upstream.
start_urb_transfer() arms dev->bulk_timeout, whose callback au0828_bulk_timeout() queues dev->restart_streaming; that work in turn calls start_urb_transfer() and re-arms the timer.
au0828_dvb_unregister() cancels restart_streaming on disconnect but does not sync bulk_timeout. au0828_usb_release() then frees dev with kfree(), so a timer still armed or pending at that point can fire after the free and dereference dev through timer_container_of().
Sync the timer with timer_shutdown_sync() before cancel_work_sync(). The timer callback queues the work, so the timer must be stopped first; the shutdown variant is needed because the work re-arms the timer through start_urb_transfer(). The dvb->frontend == NULL early return guards the register-failure path where the timer was never set up.
This bug was found by static analysis.
--- drivers/media/usb/au0828/au0828-dvb.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/usb/au0828/au0828-dvb.c +1 -0
@@ -537,6 +537,7 @@ void au0828_dvb_unregister(struct au0828if (dvb->frontend ==NULL )return ; +timer_shutdown_sync (&dev->bulk_timeout);cancel_work_sync (&dev->restart_streaming);dvb_net_release (&dvb->net);
Greg Kroah-Hartman
maintainerPATCH 536/2857 media: cx23885: Fix use-after-free in cx23885_finidev due to race condition
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
commit 75016a992d9b03f5cc6df1414d1da35840d4feeb upstream.
In cx23885_v4l2_dev_notify_init, &dev->cx25840_work is bound with cx23885_av_work_handler, and &dev->ir_rx_work and &dev->ir_tx_work are bound with cx23885_ir_rx_work_handler and cx23885_ir_tx_work_handler. cx23885_irq can schedule these works on system_wq when an AV_CORE interrupt is received, and the IR subdevice can also schedule the IR works from its interrupt service routine via the v4l2_device notify callback.
If we remove the device, cx23885_finidev makes cleanup and the memory allocated for dev is released by kfree(dev), while the works mentioned above may still be pending or running. The sequence of operations that may lead to a UAF bug is as follows:
CPU0 CPU1
| cx23885_irq
| schedule_work(&dev->cx25840_work)
cx23885_finidev |
cx23885_input_fini(dev) |
cx23885_ir_fini(dev) |
cx23885_shutdown(dev) |
free_irq(pci_dev->irq, dev) |
pci_disable_device(pci_dev) |
cx23885_dev_unregister(dev) |
v4l2_device_unregister(v4l2_dev) |
kfree(dev) |
// dev is freed |
| cx23885_av_work_handler
| // use dev (use-after-free)Fix it by canceling the works after the IRQ handler that can schedule them has been stopped, and before proceeding with the remaining cleanup in cx23885_finidev.
Note that the flush_work() calls in cx23885_input_ir_stop() do not close this race: they only wait for works that are already queued or running at that moment, they do not prevent the IRQ handler, which is still registered at that point, from scheduling the works again afterwards, and they are skipped entirely when dev->sd_ir is NULL. The cancel_work_sync() calls are therefore placed after free_irq(), the only point at which no new work can be scheduled.
--- drivers/media/pci/cx23885/cx23885-core.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/pci/cx23885/cx23885-core.c +4 -0
@@ -2233,6 +2233,10 @@ static void cx23885_finidev(struct pci_d/* unregister stuff */ free_irq (pci_dev->irq, dev); +cancel_work_sync (&dev->cx25840_work); +cancel_work_sync (&dev->ir_rx_work); +cancel_work_sync (&dev->ir_tx_work); +pci_disable_device (pci_dev);cx23885_dev_unregister (dev);
Greg Kroah-Hartman
maintainerPATCH 537/2857 media: hackrf: fix use-after-free in hackrf_alloc_urbs() error path
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anuj Bolewar <[email protected]>
commit 6802ad4b6b267dda02209b5811edac7825c8a5f6 upstream.
hackrf_alloc_urbs() frees the URBs it allocated so far when one allocation fails, but leaves the entries in dev->urb_list[] and dev->urbs_initialized untouched. The caller, hackrf_start_streaming(), then calls hackrf_free_urbs() on the error path, which walks dev->urbs_initialized entries and calls usb_free_urb() a second time on the already-freed URBs, causing a use-after-free (slab-use-after-free Write in usb_free_urb()).
Drop the redundant cleanup loop inside hackrf_alloc_urbs() and let hackrf_free_urbs(), which the caller already invokes on error, own the cleanup of the successfully allocated URBs.
--- drivers/media/usb/hackrf/hackrf.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-)
drivers/media/usb/hackrf/hackrf.c +2 -5
@@ -665,7 +665,7 @@ static int hackrf_free_urbs(struct hackrstatic int hackrf_alloc_urbs (struct hackrf_dev *dev,bool rcv) { -int i, j; +int i;unsigned int pipe;usb_complete_t complete;
@@ -681,11 +681,8 @@ static int hackrf_alloc_urbs(struct hackfor (i =0 ; i <MAX_BULK_BUFS ; i++) {dev_dbg (dev->dev,"alloc urb=%d\n" , i); dev->urb_list[i] =usb_alloc_urb (0 ,GFP_KERNEL ); -if (!dev->urb_list[i]) { -for (j =0 ; j < i; j++) -usb_free_urb (dev->urb_list[j]); +if (!dev->urb_list[i])return -ENOMEM ; - } usb_fill_bulk_urb(dev->urb_list[i], dev->udev, pipe,
Greg Kroah-Hartman
maintainerPATCH 538/2857 media: imon: fix use-after-free in display_close via dev_dbg
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Deepanshu Kartikey <[email protected]>
commit 118a3590a4080c71c565265b05b3f92e814d7647 upstream.
ictx->dev is a raw pointer to the usb_interface's embedded device. On disconnect, usb_disconnect() can drop the last reference on the interface and free it while a userspace fd for /dev/lcd0 is still open. When that fd is later closed, display_close() dereferences the now-freed ictx->dev via dev_dbg(), causing a use-after-free.
Remove the dev_dbg() calls that dereference ictx->dev in display_close() and free_imon_context(), rather than taking a reference on the device.
--- drivers/media/rc/imon.c | 5 ----- 1 file changed, 5 deletions(-)
drivers/media/rc/imon.c +0 -5
@@ -497,16 +497,12 @@ MODULE_PARM_DESC(pad_thresh, "Thresholdstatic void free_imon_context (struct imon_context *ictx) { -struct device *dev = ictx->dev; -usb_free_urb (ictx->tx_urb);WARN_ON (ictx->dev_present_intf0);usb_free_urb (ictx->rx_urb_intf0);WARN_ON (ictx->dev_present_intf1);usb_free_urb (ictx->rx_urb_intf1);kfree_rcu (ictx, rcu); - -dev_dbg (dev,"%s: iMON context freed\n" , __func__); }/*
@@ -582,7 +578,6 @@ static int display_close(struct inode *i retval = -EIO ; }else { ictx->display_isopen = false; -dev_dbg (ictx->dev,"display port closed\n" ); }mutex_unlock (&ictx->lock);
Greg Kroah-Hartman
maintainerPATCH 539/2857 apparmor: fix a use-after-free in aa_lookupn_ns()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
commit f292873ceb4bd3a1a0f75f884361cd556e457692 upstream.
aa_lookupn_ns() takes a reference on the namespace it finds with aa_get_ns(), which is kref_get() on the reference count that the namespace is released through, without checking whether the namespace is still in use. A concurrent removal of a ":"-prefixed namespace looks the same namespace up and only then takes the parent lock to remove it, so the last reference can be dropped between the lookup and the aa_get_ns() call: the reference count then reports the increment on a zero count and the kernel classifies the following use of the object as a use-after-free. A user with CAP_MAC_ADMIN can trigger this by writing a ":<name>" removal and a ":<name>/<profile>" removal to /sys/kernel/security/apparmor/.remove concurrently.
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xc0/0xe0, CPU#6 Call Trace: <TASK> aa_lookupn_ns+0xa9/0xc0 aa_remove_profiles+0x4fb/0x730 ? __kvmalloc_node_noprof+0x219/0x5c0 ? __pfx_aa_remove_profiles+0x10/0x10 ? aa_loaddata_alloc+0x65/0x1f0 ? _copy_from_user+0x2d/0x80 ? aa_loaddata_alloc+0x111/0x1f0 profile_remove+0x2ee/0x4a0 vfs_write+0x21e/0xcf0 ? rcu_core+0x29c/0x1740 ? timerqueue_linked_add+0x1f4/0x3d0 ? __pfx_vfs_write+0x10/0x10 ? mutex_lock+0x81/0xe0 ? __pfx_mutex_lock+0x10/0x10 ? __pfx_rcu_core+0x10/0x10 ? __pfx_hrtimer_update_next_event+0x10/0x10 ? mutex_unlock+0x7b/0xd0 ? fdget_pos+0x24d/0x4b0 ksys_write+0xf7/0x1c0 ? __pfx_ksys_write+0x10/0x10 ? restore_fpregs_from_fpstate+0x37/0xc0 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
Fix by rejecting a namespace whose reference count is zero.
--- security/apparmor/include/policy_ns.h | 16 ++++++++++++++++ security/apparmor/policy_ns.c | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-)
security/apparmor/include/policy_ns.h +16 -0
@@ -121,6 +121,22 @@ static inline struct aa_ns *aa_get_ns(st }/** +* aa_get_ns_not0 - increment references count on @ns found via lookup +* @ns: namespace to increment reference count of (MAYBE NULL) +* +* Returns: pointer to @ns, if @ns is NULL returns NULL, +* NULL if @ns is being freed +* Requires: @ns must be held with valid refcount when called +*/ +static inline struct aa_ns *aa_get_ns_not0 (struct aa_ns *ns) +{ +if (ns &&aa_get_profile_not0 (ns->unconfined)) +return ns; + +return NULL ; +} + +/** * aa_put_ns - decrement refcount on @ns * @ns: namespace to put reference of *
security/apparmor/policy_ns.c +1 -1
@@ -246,7 +246,7 @@ struct aa_ns *aa_lookupn_ns(struct aa_nsstruct aa_ns *ns =NULL ;rcu_read_lock (); - ns =aa_get_ns (__aa_lookupn_ns (view, name, n)); + ns =aa_get_ns_not0 (__aa_lookupn_ns (view, name, n));rcu_read_unlock ();return ns;
Greg Kroah-Hartman
maintainerPATCH 540/2857 ata: sata_fsl: Fix use-after-free of host_priv on probe() failure
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Cassel <[email protected]>
commit 70b1196740d61aabda13b2ad0e9c1dfa2ef9cfa3 upstream.
sata_fsl_host_stop() releases hcr_base and host_priv:
static void sata_fsl_host_stop(struct ata_host *host)
{
struct sata_fsl_host_priv *host_priv = host->private_data;
iounmap(host_priv->hcr_base);
kfree(host_priv);
}->host_stop() is called by the driver core through the ata_host_stop() devres action which ata_host_start() registers, so it is called both when the device is unbound and when probe() fails after the host has been started.
The error_exit_with_cleanup label of sata_fsl_probe() releases hcr_base and host_priv as well, and it is reachable from the two device_create_file() calls which are done after the host has been activated. In that case sata_fsl_host_stop() runs on an already freed host_priv, resulting in a use-after-free and a double iounmap()/kfree().
Add a separate error label for the failures happening after the host has been activated, which only detaches the host and leaves hcr_base and host_priv to sata_fsl_host_stop().
Note that ata_host_detach() is dropped from error_exit_with_cleanup, as that label is now only reachable while host is still NULL.
--- drivers/ata/sata_fsl.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/ata/sata_fsl.c +13 -5
@@ -1500,7 +1500,7 @@ static int sata_fsl_probe(struct platfor host_priv->intr_coalescing.attr.mode =S_IRUGO |S_IWUSR ; retval =device_create_file (host->dev, &host_priv->intr_coalescing);if (retval) - goto error_exit_with_cleanup; + goto error_exit_detach; host_priv->rx_watermark.show = fsl_sata_rx_watermark_show; host_priv->rx_watermark.store = fsl_sata_rx_watermark_store;
@@ -1510,16 +1510,24 @@ static int sata_fsl_probe(struct platfor retval =device_create_file (host->dev, &host_priv->rx_watermark);if (retval) {device_remove_file (&ofdev->dev, &host_priv->intr_coalescing); - goto error_exit_with_cleanup; + goto error_exit_detach; }return 0 ; -error_exit_with_cleanup: +error_exit_detach: +/* +* Once the host has been activated, hcr_base and host_priv are +* released by sata_fsl_host_stop(), which is called by the driver core +* through the ata_host_stop() devres action registered by +* ata_host_start(). Releasing them here as well would result in a +* double iounmap() and a use-after-free. +*/ +ata_host_detach (host); -if (host) -ata_host_detach (host); +return retval; +error_exit_with_cleanup:if (hcr_base)iounmap (hcr_base);kfree (host_priv);
Greg Kroah-Hartman
maintainerPATCH 541/2857 s390/cpum_cf: Check session mask before cpu offline
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sumanth Korikkar <[email protected]>
commit 99a95985dfc85eecad97f0991a2401d2fcef294c upstream.
cfset_offline_cpu() stops counter sets for every active session without checking whether the outgoing cpu belongs to the session mask.
For example, run an hwctr session on cpu0 and a cpu bound perf event on cpu1:
lshwc -l 9999 -i 5 0:b
perf stat -C 1 -e cpum_cf/CPU_CYCLES/ sleep 120
chcpu -d 1
chcpu -e 1
Although the hwctr session does not include cpu1, cfset_offline_cpu() decrements its counter set reference count. The subsequent perf teardown decrements it again, causing it to underflow.
The perf event keeps the percpu state alive across hotplug. When cpu1 comes online, the hwctr session is started there and the reference count moves from -1 to 0. Stopping the hwctr session then decrements it to -1 again, so the zero triggered counter set disable path is skipped.
Check the session mask before stopping counter sets on the outgoing cpu. This prevents the unmatched decrement and the resulting reference count underflow.
--- arch/s390/kernel/perf_cpum_cf.c | 3 +++ 1 file changed, 3 insertions(+)
arch/s390/kernel/perf_cpum_cf.c +3 -0
@@ -1561,6 +1561,9 @@ static int cfset_offline_cpu(unsigned inmutex_lock (&cfset_ctrset_mutex);if (!list_empty (&cfset_session.head)) {list_for_each_entry (rp, &cfset_session.head, node) { +if (!cpumask_test_cpu (cpu, &rp->mask)) +continue ; + p.sets = rp->ctrset;cfset_ioctl_off (&p);cpumask_clear_cpu (cpu, &rp->mask);
Greg Kroah-Hartman
maintainerPATCH 542/2857 s390/probes: Fix wrong opcode for cgrb fixup
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiko Carstens <[email protected]>
commit d7ccab11a13475e656b9d2277900422c1bfc12c5 upstream.
The last byte of the cgrb instruction is 0xe4, however the probes code compares against 0xe6. Fix it.
--- arch/s390/lib/probes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/lib/probes.c +1 -1
@@ -99,8 +99,8 @@ int probe_get_fixup_type(u16 *insn)break ;case 0xec :switch (insn[2 ] &0xff ) { +case 0xe4 :/* cgrb */ case 0xe5 :/* clgrb */ -case 0xe6 :/* cgrb */ case 0xf6 :/* crb */ case 0xf7 :/* clrb */ case 0xfc :/* cgib */
Greg Kroah-Hartman
maintainerPATCH 543/2857 s390/signal: Fix incorrect return address in signal frame
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiko Carstens <[email protected]>
commit adc9e872f7350e3ac29c1818d8c68b0760b4ba23 upstream.
exit_to_user_mode_loop() can call arch_do_signal_or_restart() multiple times when signals are pending.
If the first call set up a vDSO system call restart by saving the real user return address and adjusting psw.addr so it points to the vDSO stub, a second call builds the signal frame with the wrong return address.
Restore psw.addr from arch_data, and set the return code to -EINTR before building the signal frame.
This requires restart_block.arch_data to be properly initialized for all tasks. Move the initialization in copy_thread() in front of the kernel thread check, so that it also covers kernel threads and their children (PID 1, usermode helpers). Only PID 0 is left uninitialized, since it never returns to user space.
--- arch/s390/kernel/process.c | 12 ++++++------ arch/s390/kernel/signal.c | 6 +++++- 2 files changed, 11 insertions(+), 7 deletions(-)
arch/s390/kernel/process.c +6 -6
@@ -134,6 +134,12 @@ int copy_thread(struct task_struct *p, c p->thread.hardirq_timer =0 ; p->thread.softirq_timer =0 ; p->thread.last_break =1 ; +/* +* s390 stores the svc return address in arch_data when calling +* sigreturn()/restart_syscall() via vdso. 1 means no valid address +* stored. +*/ + p->restart_block.arch_data =1 ; frame->sf.back_chain =0 ; frame->sf.gprs[5 ] = (unsigned long )frame +sizeof (struct stack_frame );
@@ -177,12 +183,6 @@ int copy_thread(struct task_struct *p, c p->thread.acrs[1 ] = (unsigned int )tls; } } -/* -* s390 stores the svc return address in arch_data when calling -* sigreturn()/restart_syscall() via vdso. 1 means no valid address -* stored. -*/ - p->restart_block.arch_data =1 ;return 0 ; }
arch/s390/kernel/signal.c +5 -1
@@ -491,7 +491,11 @@ void arch_do_signal_or_restart(struct pt }/* No longer in a system call */ clear_pt_regs_flag (regs,PIF_SYSCALL ); - +if (!(current->restart_block.arch_data &1 )) { + regs->psw.addr = current->restart_block.arch_data; + current->restart_block.arch_data =1 ; + regs->gprs[2 ] = -EINTR ; + }rseq_signal_deliver (&ksig, regs);if (is_compat_task ())handle_signal32 (&ksig, oldset, regs);
Greg Kroah-Hartman
maintainerPATCH 544/2857 s390/zcrypt: Fix out-of-bounds ptr advance in cca_query_crypto_facility()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Harald Freudenberger <[email protected]>
commit 9fd7fca66735307fd7afa3450882a55ef80f2add upstream.
The FQ reply parser code blindly advanced the walk pointer by a length value read directly from the hardware reply payload without checking that the advance stayed within the allocated reply buffer. A corrupt or malicious device response could push ptr beyond the cprbmem region, causing an out-of-bounds dereference or kernel memory exposure via the subsequent memcpy().
Fix this by tracking the remaining reply buffer space in a variable and validating each device-supplied length field against it before advancing or dereferencing the pointer.
--- drivers/s390/crypto/zcrypt_ccamisc.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-)
drivers/s390/crypto/zcrypt_ccamisc.c +20 -2
@@ -1583,6 +1583,7 @@ int cca_query_crypto_facility(u16 cardnru8 subfunc_code[2 ];u8 lvdata[0 ]; }__packed * prepparm; +size_t datalen;/* get already prepared memory for 2 cprbs with param block each */ rc =alloc_and_prep_cprbmem (parmbsize, &mem, &preqcblk, &prepcblk);
@@ -1628,27 +1629,44 @@ int cca_query_crypto_facility(u16 cardnr prepcblk->rpl_parmb = (u8 __user *)ptr; prepparm = (struct fqrepparm *)ptr; ptr = prepparm->lvdata; + datalen = parmbsize -2 *sizeof (u8);/* check and possibly copy reply rule array */ len = *((u16 *)ptr); +if (len > datalen) { +ZCRYPT_DBF_ERR ("%s reply rule array len %u exceeds datalen %zu\n" , + __func__, len, datalen); + rc = -EIO ; + goto out; + } + datalen -=sizeof (u16); + ptr +=sizeof (u16);if (len >sizeof (u16)) { - ptr +=sizeof (u16); len -=sizeof (u16);if (rarray && rarraylen && *rarraylen >0 ) { *rarraylen = (len > *rarraylen ? *rarraylen : len);memcpy (rarray, ptr, *rarraylen); } + datalen -= len; ptr += len; }/* check and possible copy reply var array */ len = *((u16 *)ptr); +if (len > datalen) { +ZCRYPT_DBF_ERR ("%s reply var array len %u exceeds datalen %zu\n" , + __func__, len, datalen); + rc = -EIO ; + goto out; + } + datalen -=sizeof (u16); + ptr +=sizeof (u16);if (len >sizeof (u16)) { - ptr +=sizeof (u16); len -=sizeof (u16);if (varray && varraylen && *varraylen >0 ) { *varraylen = (len > *varraylen ? *varraylen : len);memcpy (varray, ptr, *varraylen); } + datalen -= len; ptr += len; }
Greg Kroah-Hartman
maintainerPATCH 545/2857 HID: wacom: Use hdev->product in wacom_setup_touch_input_capabilities
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 86472508a7ef74b525e79a79d2d02d911a641d6b upstream.
Replace the lookup-dependent 'wacom_wac->shared->touch->product' references with 'hdev->product' inside wacom_setup_touch_input_capabilities() since 'hdev' is already available (via container_of) and represents the touch device itself.
--- drivers/hid/wacom_wac.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/hid/wacom_wac.c +9 -9
@@ -3932,8 +3932,8 @@ int wacom_setup_pen_input_capabilities(sint wacom_setup_touch_input_capabilities (struct input_dev *input_dev,struct wacom_wac *wacom_wac) { + struct hid_device *hdev = container_of(wacom_wac, struct wacom, wacom_wac)->hdev;struct wacom_features *features = &wacom_wac->features; -if (!(features->device_type &WACOM_DEVICETYPE_TOUCH ))return -ENODEV ;
@@ -3942,9 +3942,11 @@ int wacom_setup_touch_input_capabilitieselse __set_bit (INPUT_PROP_POINTER , input_dev->propbit); -if (features->type ==HID_GENERIC ) +if (features->type ==HID_GENERIC ) { +hid_dbg (hdev,"generic touch setup\n" );/* setup has already been done */ return 0 ; + } input_dev->evbit[0 ] |=BIT_MASK (EV_KEY ) |BIT_MASK (EV_ABS );__set_bit (BTN_TOUCH , input_dev->keybit);
@@ -3976,19 +3978,17 @@ int wacom_setup_touch_input_capabilities input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); -if (wacom_wac->shared->touch->product ==0x361 ) { +if (hdev->product ==0x361 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,12440 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,8640 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x360 ) { + }else if (hdev->product ==0x360 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,8960 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,5920 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x393 ) { + }else if (hdev->product ==0x393 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,6400 ,4 ,0 ); input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
@@ -4018,8 +4018,8 @@ int wacom_setup_touch_input_capabilities fallthrough;case WACOM_27QHDT : -if (wacom_wac->shared->touch->product ==0x32C || - wacom_wac->shared->touch->product ==0xF6 ) { +if (hdev->product ==0x32C || + hdev->product ==0xF6 ) { input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); wacom_wac->has_mute_touch_switch = true;
Greg Kroah-Hartman
maintainerPATCH 546/2857 HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit ba16e5ffbaa10fde960918d69af5e49f2b3fdd5e upstream.
Input subsystem guidelines require that device capabilities are advertised before the input device is registered. The Wacom driver was violating this by advertising the SW_MUTE_DEVICE capability post-registration in wacom_set_shared_values() (and duplicating it in device-specific setup cases).
Resolve this by moving the SW_MUTE_DEVICE capability setup to wacom_setup_touch_input_capabilities() for all touch devices that support it.
For generic touch devices whose capabilities depend on mute switch usages parsed from a sibling Pen/Pad interface, defer registration with -EPROBE_DEFER until the sibling has parsed its descriptors and initialized shared capabilities.
--- drivers/hid/wacom_sys.c | 93 ++++++++++++++++++++++++++++++++++++++---------- drivers/hid/wacom_wac.c | 5 ++ 2 files changed, 79 insertions(+), 19 deletions(-)
drivers/hid/wacom_sys.c +74 -19
@@ -895,19 +895,14 @@ static int wacom_add_shared_data(structlist_add_tail (&data->list, &wacom_udev_list); } -mutex_unlock (&wacom_udev_list_lock); - wacom_wac->shared = &data->shared; - retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom); -if (retval) -return retval; +if (wacom_wac->has_mute_touch_switch) +WRITE_ONCE (wacom_wac->shared->has_mute_touch_switch, true); -if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) - wacom_wac->shared->touch = hdev; -else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) - wacom_wac->shared->pen = hdev; +mutex_unlock (&wacom_udev_list_lock); + retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom);return retval; }
@@ -2306,13 +2301,12 @@ static void wacom_release_resources(strustatic void wacom_set_shared_values (struct wacom_wac *wacom_wac) { -if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { - wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch_input = wacom_wac->touch_input; - } + struct wacom *wacom = container_of(wacom_wac, struct wacom, wacom_wac); + +guard (mutex)(&wacom_udev_list_lock);if (wacom_wac->has_mute_touch_switch) { - wacom_wac->shared->has_mute_touch_switch = true; +WRITE_ONCE (wacom_wac->shared->has_mute_touch_switch, true);/* Hardware touch switch may be off. Wait until * we know the switch state to decide is_touch_on. * Softkey state should be initialized to "on" to
@@ -2322,12 +2316,67 @@ static void wacom_set_shared_values(stru wacom_wac->shared->is_touch_on = true; } -if (wacom_wac->shared->has_mute_touch_switch && - wacom_wac->shared->touch_input) { -set_bit (EV_SW , wacom_wac->shared->touch_input->evbit); -input_set_capability (wacom_wac->shared->touch_input,EV_SW , -SW_MUTE_DEVICE ); +if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { + wacom_wac->shared->type = wacom_wac->features.type; + wacom_wac->shared->touch_input = wacom_wac->touch_input; + wacom_wac->shared->touch = wacom->hdev; + }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) { +/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ +smp_store_release (&wacom_wac->shared->pen, wacom->hdev); + } +} + +static bool wacom_sibling_pending (struct wacom *wacom) +{ +const struct wacom_features *features = &wacom->wacom_wac.features; +struct hid_device *hdev = wacom->hdev; +struct usb_interface *sibling_intf; +int ifnum; + +if (features->type !=HID_GENERIC || + !(features->device_type &WACOM_DEVICETYPE_TOUCH )) +return false; + +if (wacom->wacom_wac.shared) { +/* Pairs with smp_store_release() in wacom_set_shared_values() */ +if (smp_load_acquire (&wacom->wacom_wac.shared->pen)) +return false; } + +if (!hid_is_usb (hdev) || !wacom->usbdev || !wacom->intf || + !wacom->intf->cur_altsetting) +return false; + + ifnum = wacom->intf->cur_altsetting->desc.bInterfaceNumber; + +/* +* On composite Wacom devices, the Pen interface is always interface 0. +* If the Touch interface is interface 0, there is no sibling Pen +* interface on this device (standalone touch device). +*/ +if (ifnum ==0 ) +return false; + +/* Look for the sibling Pen interface at interface 0 */ + sibling_intf =usb_ifnum_to_if (wacom->usbdev,0 ); +if (!sibling_intf || !sibling_intf->cur_altsetting) +return false; + +if (sibling_intf->cur_altsetting->desc.bInterfaceClass != +USB_INTERFACE_CLASS_HID ) +return false; + +if (sibling_intf->cur_altsetting->desc.bInterfaceSubClass ==1 && + (sibling_intf->cur_altsetting->desc.bInterfaceProtocol ==1 || + sibling_intf->cur_altsetting->desc.bInterfaceProtocol ==2 )) +return false; + +/* +* Interface 0 is a candidate HID interface on this composite device +* whose probe has not completed yet (shared->pen is NULL). Defer until +* interface 0 finishes probing and registers shared values. +*/ +return true; }static int wacom_parse_and_register (struct wacom *wacom,bool wireless)
@@ -2410,6 +2459,11 @@ static int wacom_parse_and_register(stru goto fail; } +if (wacom_sibling_pending (wacom)) { + error = -EPROBE_DEFER ; + goto fail; + } + error =wacom_setup_inputs (wacom);if (error) goto fail;
@@ -2467,6 +2521,7 @@ static int wacom_parse_and_register(stru fail_hw_stop:hid_hw_stop (hdev); +cancel_delayed_work_sync (&wacom->init_work); fail:wacom_release_resources (wacom);return error;
drivers/hid/wacom_wac.c +5 -0
@@ -3944,6 +3944,11 @@ int wacom_setup_touch_input_capabilitiesif (features->type ==HID_GENERIC ) {hid_dbg (hdev,"generic touch setup\n" ); +if (wacom_wac->has_mute_touch_switch || + (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch))) { +input_set_capability (input_dev,EV_SW ,SW_MUTE_DEVICE ); + wacom_wac->has_mute_touch_switch = true; + }/* setup has already been done */ return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 547/2857 HID: wacom: Fix Use-After-Free in wacom_intuos_pad
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit ef32877368a7013c060ef6bd03a30b6da2fe0c41 upstream.
wacom_intuos_pad() accesses wacom->shared->touch_input locklessly inside the interrupt handler context. If the Touch sibling device is disconnected, wacom_remove_shared_data() clears 'touch_input' outside any lock, creating a Time-of-Check to Time-of-Use (TOCTOU) race condition where a preempted reader in interrupt context dereferences the freed pointer, leading to a Use-After-Free.
Resolve this by introducing RCU protection for the touch_input pointer:
- Annotate 'touch_input' in wacom_shared struct with __rcu
- Wrap all lockless readers in wacom_wac.c with guard(rcu)() and rcu_dereference() using a unified wacom_report_touch_mute() helper
- Update writers in wacom_sys.c using rcu_assign_pointer()
- Call synchronize_rcu() in wacom_remove_shared_data() to ensure all active RCU readers have finished before the input device is freed
Also wrap wacom_set_shared_values() and touch/pen assignments in wacom_add_shared_data() inside the wacom_udev_list_lock to serialize concurrent probe assignments, and verify that 'shared->touch == hdev' before setting touch_input to prevent concurrent sibling probe state desynchronization.
--- drivers/hid/wacom_sys.c | 23 ++++++++++++++++------- drivers/hid/wacom_wac.c | 36 ++++++++++++++++++------------------ drivers/hid/wacom_wac.h | 2 +- 3 files changed, 35 insertions(+), 26 deletions(-)
drivers/hid/wacom_sys.c +16 -7
@@ -863,10 +863,16 @@ static void wacom_remove_shared_data(voi data = container_of(wacom_wac->shared, struct wacom_hdev_data, shared); -if (wacom_wac->shared->touch == wacom->hdev) - wacom_wac->shared->touch =NULL ; -else if (wacom_wac->shared->pen == wacom->hdev) - wacom_wac->shared->pen =NULL ; + scoped_guard(mutex, &wacom_udev_list_lock) { +if (wacom_wac->shared->touch == wacom->hdev) { + wacom_wac->shared->touch =NULL ; +rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); + }else if (wacom_wac->shared->pen == wacom->hdev) { + wacom_wac->shared->pen =NULL ; + } + } + +synchronize_rcu ();kref_put (&data->kref, wacom_release_shared_data); wacom_wac->shared =NULL ;
@@ -903,6 +909,7 @@ static int wacom_add_shared_data(structmutex_unlock (&wacom_udev_list_lock); retval =devm_add_action_or_reset (&hdev->dev, wacom_remove_shared_data, wacom); +return retval; }
@@ -2317,9 +2324,11 @@ static void wacom_set_shared_values(stru }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { - wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch_input = wacom_wac->touch_input; - wacom_wac->shared->touch = wacom->hdev; +if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) { + wacom_wac->shared->type = wacom_wac->features.type; + wacom_wac->shared->touch = wacom->hdev; +rcu_assign_pointer (wacom_wac->shared->touch_input, wacom_wac->touch_input); + } }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) {/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ smp_store_release (&wacom_wac->shared->pen, wacom->hdev);
drivers/hid/wacom_wac.c +18 -18
@@ -505,6 +505,18 @@ static void wacom_intuos_schedule_prox_e } } +static void wacom_report_touch_mute (struct wacom_wac *wacom_wac,bool mute) +{ +struct input_dev *touch_input; + +guard (rcu)(); + touch_input =rcu_dereference (wacom_wac->shared->touch_input); +if (touch_input) { +input_report_switch (touch_input,SW_MUTE_DEVICE , mute); +input_sync (touch_input); + } +} +static int wacom_intuos_pad (struct wacom_wac *wacom) {struct wacom_features *features = &wacom->features;
@@ -645,12 +657,8 @@ static int wacom_intuos_pad(struct wacominput_report_key (input,KEY_CONTROLPANEL , menu);input_report_key (input,KEY_INFO , info); -if (wacom->shared && wacom->shared->touch_input) { -input_report_switch (wacom->shared->touch_input, -SW_MUTE_DEVICE , - !wacom->shared->is_touch_on); -input_sync (wacom->shared->touch_input); - } +if (wacom->shared) +wacom_report_touch_mute (wacom, !wacom->shared->is_touch_on);input_report_abs (input,ABS_RX , strip1);input_report_abs (input,ABS_RY , strip2);
@@ -2189,7 +2197,7 @@ static void wacom_wac_pad_event(struct h*/ if ((equivalent_usage ==WACOM_HID_WD_MUTE_DEVICE ) || (equivalent_usage ==WACOM_HID_WD_TOUCHONOFF )) { -if (wacom_wac->shared->touch_input) { +if (wacom_wac->shared) {bool *is_touch_on = &wacom_wac->shared->is_touch_on;if (equivalent_usage ==WACOM_HID_WD_MUTE_DEVICE && value)
@@ -2197,9 +2205,7 @@ static void wacom_wac_pad_event(struct helse if (equivalent_usage ==WACOM_HID_WD_TOUCHONOFF ) *is_touch_on = value; -input_report_switch (wacom_wac->shared->touch_input, -SW_MUTE_DEVICE , !(*is_touch_on)); -input_sync (wacom_wac->shared->touch_input); +wacom_report_touch_mute (wacom_wac, !(*is_touch_on)); }return ; }
@@ -3356,11 +3362,8 @@ static int wacom_wireless_irq(struct wacif ((wacom->shared->type ==INTUOSHT || wacom->shared->type ==INTUOSHT2 ) && - wacom->shared->touch_input && wacom->shared->touch_max) { -input_report_switch (wacom->shared->touch_input, -SW_MUTE_DEVICE , data[5 ] &0x40 ); -input_sync (wacom->shared->touch_input); +wacom_report_touch_mute (wacom, data[5 ] &0x40 ); } pid =get_unaligned_be16 (&data[6 ]);
@@ -3395,11 +3398,8 @@ static int wacom_status_irq(struct wacomif ((features->type ==INTUOSHT || features->type ==INTUOSHT2 ) && - wacom_wac->shared->touch_input && features->touch_max) { -input_report_switch (wacom_wac->shared->touch_input, -SW_MUTE_DEVICE , data[8 ] &0x40 ); -input_sync (wacom_wac->shared->touch_input); +wacom_report_touch_mute (wacom_wac, data[8 ] &0x40 ); }if (data[9 ] &0x02 ) {/* wireless module is attached */
drivers/hid/wacom_wac.h +1 -1
@@ -287,7 +287,7 @@ struct wacom_shared {/* for wireless device to access USB interfaces */ unsigned touch_max;int type; -struct input_dev *touch_input; +struct input_dev __rcu *touch_input;struct hid_device *pen;struct hid_device *touch;bool has_mute_touch_switch;
Greg Kroah-Hartman
maintainerPATCH 548/2857 HID: wacom: Fix Use-After-Free in wacom_bamboo_pad
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 3a523ecf9ac3fdd33f5eb31c43937ee44135395b upstream.
wacom_bamboo_pad_pen_event() accesses wacom->shared->pen locklessly relative to wacom_remove_shared_data() which nullifies it. This can lead to a Use-After-Free if the sibling device is removed while events are being processed.
Resolve this by introducing RCU protection for pen and touch pointers:
- Annotate 'pen' and 'touch' in wacom_shared struct with __rcu.
- Wrap lockless readers in wacom_bamboo_pad_pen_event() with rcu_read_lock() and rcu_dereference().
- Update writers in wacom_sys.c using rcu_assign_pointer().
- Use rcu_dereference_protected for comparisons under wacom_udev_list_lock.
- Also use rcu_access_pointer in wacom_sibling_pending() and wacom_mode_change_work() to avoid warnings (while lockless access in the latter remains a pre-existing issue).
--- drivers/hid/wacom_sys.c | 40 ++++++++++++++++++++++++++-------------- drivers/hid/wacom_wac.c | 13 ++++++------- drivers/hid/wacom_wac.h | 4 ++-- 3 files changed, 34 insertions(+), 23 deletions(-)
drivers/hid/wacom_sys.c +26 -14
@@ -864,11 +864,18 @@ static void wacom_remove_shared_data(voi shared); scoped_guard(mutex, &wacom_udev_list_lock) { -if (wacom_wac->shared->touch == wacom->hdev) { - wacom_wac->shared->touch =NULL ; +struct hid_device *touch = +rcu_dereference_protected (wacom_wac->shared->touch, +lockdep_is_held (&wacom_udev_list_lock)); +struct hid_device *pen = +rcu_dereference_protected (wacom_wac->shared->pen, +lockdep_is_held (&wacom_udev_list_lock)); + +if (touch == wacom->hdev) { +rcu_assign_pointer (wacom_wac->shared->touch,NULL );rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); - }else if (wacom_wac->shared->pen == wacom->hdev) { - wacom_wac->shared->pen =NULL ; + }else if (pen == wacom->hdev) { +rcu_assign_pointer (wacom_wac->shared->pen,NULL ); } }
@@ -2324,14 +2331,17 @@ static void wacom_set_shared_values(stru }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) { -if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) { +struct hid_device *touch = +rcu_dereference_protected (wacom_wac->shared->touch, +lockdep_is_held (&wacom_udev_list_lock)); + +if (touch == wacom->hdev || !touch) { wacom_wac->shared->type = wacom_wac->features.type; - wacom_wac->shared->touch = wacom->hdev; +rcu_assign_pointer (wacom_wac->shared->touch, wacom->hdev);rcu_assign_pointer (wacom_wac->shared->touch_input, wacom_wac->touch_input); } }else if (wacom_wac->features.device_type &WACOM_DEVICETYPE_PEN ) { -/* Pairs with smp_load_acquire() in wacom_sibling_pending() */ -smp_store_release (&wacom_wac->shared->pen, wacom->hdev); +rcu_assign_pointer (wacom_wac->shared->pen, wacom->hdev); } }
@@ -2347,8 +2357,7 @@ static bool wacom_sibling_pending(structreturn false;if (wacom->wacom_wac.shared) { -/* Pairs with smp_store_release() in wacom_set_shared_values() */ -if (smp_load_acquire (&wacom->wacom_wac.shared->pen)) +if (rcu_access_pointer (wacom->wacom_wac.shared->pen))return false; }
@@ -2818,16 +2827,19 @@ static void wacom_mode_change_work(strucbool is_direct = wacom->wacom_wac.is_direct_mode;int error =0 ; -if (shared->pen) { - wacom1 =hid_get_drvdata (shared->pen); +struct hid_device *pen =rcu_access_pointer (shared->pen); +struct hid_device *touch =rcu_access_pointer (shared->touch); + +if (pen) { + wacom1 =hid_get_drvdata (pen);wacom_release_resources (wacom1);hid_hw_stop (wacom1->hdev); wacom1->wacom_wac.has_mode_change = true; wacom1->wacom_wac.is_direct_mode = is_direct; } -if (shared->touch) { - wacom2 =hid_get_drvdata (shared->touch); +if (touch) { + wacom2 =hid_get_drvdata (touch);wacom_release_resources (wacom2);hid_hw_stop (wacom2->hdev); wacom2->wacom_wac.has_mode_change = true;
drivers/hid/wacom_wac.c +6 -7
@@ -3267,6 +3267,7 @@ static int wacom_bpt_irq(struct wacom_wastatic void wacom_bamboo_pad_pen_event (struct wacom_wac *wacom,unsigned char *data) { +struct hid_device *pen;unsigned char prefix;/*
@@ -3279,13 +3280,11 @@ static void wacom_bamboo_pad_pen_event(s prefix = data[0 ]; data[0 ] =WACOM_REPORT_BPAD_PEN ; -/* -* actually reroute the event. -* No need to check if wacom->shared->pen is valid, hid_input_report() -* will check for us. -*/ -hid_input_report (wacom->shared->pen,HID_INPUT_REPORT , data, -WACOM_PKGLEN_PENABLED ,1 ); +guard (rcu)(); + pen =rcu_dereference (wacom->shared->pen); +if (pen) +hid_input_report (pen,HID_INPUT_REPORT , data, +WACOM_PKGLEN_PENABLED ,1 ); data[0 ] = prefix; }
drivers/hid/wacom_wac.h +2 -2
@@ -288,8 +288,8 @@ struct wacom_shared {unsigned touch_max;int type;struct input_dev __rcu *touch_input; -struct hid_device *pen; -struct hid_device *touch; +struct hid_device __rcu *pen; +struct hid_device __rcu *touch;bool has_mute_touch_switch;bool is_touch_on; };
Greg Kroah-Hartman
maintainerPATCH 549/2857 HID: wacom: Redesign shared sibling data lifecycle
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 480c9cb14ae81f8e112ff83f8778b3d7b9324dc8 upstream.
The Wacom driver coordinates state between sibling interfaces of the same physical device using a shared structure 'wacom_shared' inside 'wacom_hdev_data'. The driver kept a volatile representative pointer 'data->dev' pointing to a sibling 'hid_device' for physical path comparisons during sibling matching.
This pointer management is fragile. When the representative device is disconnected, wacom_remove_shared_data() failed to clear/update 'data->dev', leading to a Use-After-Free vulnerability when subsequent sibling probes dereference the dangling 'data->dev' pointer.
Resolve this issue by redesigning the sibling data lifecycle:
- Eliminate the volatile 'data->dev' representative pointer completely
- Redesign 'wacom_hdev_data' to store stable static copies of the required attributes upon first allocation: 'phys' path string, 'vendor', 'product' IDs and the sibling's 'device_type'
- Use these static attributes for stable sibling matching in wacom_are_sibling() and wacom_get_hdev_data()
This ensures sibling matching remains safe and stable even if individual siblings are dynamically added or removed.
To secure the lifecycle against concurrent probe/disconnect races:
- Switch kref_put() to kref_put_mutex() in wacom_remove_shared_data() to serialize refcount drops with list traversal and lookup
- Modify wacom_release_shared_data() to assume the list lock is already held
Also, do not accumulate the 'device_type' capability flag during subsequent sibling probes. Keeping only the first probed sibling's device_type exactly preserves the original sibling matching behavior without introducing side effects.
--- drivers/hid/wacom_sys.c | 70 +++++++++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +46 -24
@@ -745,27 +745,47 @@ static void wacom_retrieve_hid_descriptostruct wacom_hdev_data {struct list_head list;struct kref kref; -struct hid_device *dev; +char phys[64 ]; +__u32 vendor; +__u32 product; +__u32 device_type;struct wacom_shared shared; }; +static bool wacom_compare_device_paths (struct hid_device *hdev_a, +const char *phys_b,char separator) +{ +const char *p1 =strrchr (hdev_a->phys, separator); +const char *p2 =strrchr (phys_b, separator); +int n1, n2; + +if (!p1 || !p2) +return false; + + n1 = p1 - hdev_a->phys; + n2 = p2 - phys_b; + +if (n1 != n2 || n1 <=0 || n2 <=0 ) +return false; + +return !strncmp (hdev_a->phys, phys_b, n1); +} +static LIST_HEAD (wacom_udev_list);static DEFINE_MUTEX (wacom_udev_list_lock);static bool wacom_are_sibling (struct hid_device *hdev, -struct hid_device *sibling) +struct wacom_hdev_data *data) {struct wacom *wacom =hid_get_drvdata (hdev);struct wacom_features *features = &wacom->wacom_wac.features; -struct wacom *sibling_wacom =hid_get_drvdata (sibling); -struct wacom_features *sibling_features = &sibling_wacom->wacom_wac.features;__u32 oVid = features->oVid ? features->oVid : hdev->vendor;__u32 oPid = features->oPid ? features->oPid : hdev->product;/* The defined oVid/oPid must match that of the sibling */ -if (features->oVid !=HID_ANY_ID && sibling->vendor != oVid) +if (features->oVid !=HID_ANY_ID && data->vendor != oVid)return false; -if (features->oPid !=HID_ANY_ID && sibling->product != oPid) +if (features->oPid !=HID_ANY_ID && data->product != oPid)return false;/*
@@ -773,11 +793,11 @@ static bool wacom_are_sibling(struct hid* device path, while those with different VID/PID must share * the same physical parent device path. */ -if (hdev->vendor == sibling->vendor && hdev->product == sibling->product) { -if (!hid_compare_device_paths (hdev, sibling,'/' )) +if (hdev->vendor == data->vendor && hdev->product == data->product) { +if (!wacom_compare_device_paths (hdev, data->phys,'/' ))return false; }else { -if (!hid_compare_device_paths (hdev, sibling,'.' )) +if (!wacom_compare_device_paths (hdev, data->phys,'.' ))return false; }
@@ -790,7 +810,7 @@ static bool wacom_are_sibling(struct hid* devices. */ if ((features->device_type &WACOM_DEVICETYPE_DIRECT ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + !(data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/*
@@ -798,17 +818,17 @@ static bool wacom_are_sibling(struct hid* devices. */ if (!(features->device_type &WACOM_DEVICETYPE_DIRECT ) && - (sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + (data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/* Pen devices may only be siblings of touch devices */ if ((features->device_type &WACOM_DEVICETYPE_PEN ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_TOUCH )) + !(data->device_type &WACOM_DEVICETYPE_TOUCH ))return false;/* Touch devices may only be siblings of pen devices */ if ((features->device_type &WACOM_DEVICETYPE_TOUCH ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_PEN )) + !(data->device_type &WACOM_DEVICETYPE_PEN ))return false;/*
@@ -824,7 +844,7 @@ static struct wacom_hdev_data *wacom_get/* Try to find an already-probed interface from the same device */ list_for_each_entry (data, &wacom_udev_list, list) { -if (hid_compare_device_paths (hdev, data->dev,'/' )) { +if (wacom_compare_device_paths (hdev, data->phys,'/' )) {kref_get (&data->kref);return data; }
@@ -832,7 +852,7 @@ static struct wacom_hdev_data *wacom_get/* Fallback to finding devices that appear to be "siblings" */ list_for_each_entry (data, &wacom_udev_list, list) { -if (wacom_are_sibling (hdev, data->dev)) { +if (wacom_are_sibling (hdev, data)) {kref_get (&data->kref);return data; }
@@ -846,18 +866,15 @@ static void wacom_release_shared_data(ststruct wacom_hdev_data *data = container_of(kref, struct wacom_hdev_data, kref); -mutex_lock (&wacom_udev_list_lock);list_del (&data->list); -mutex_unlock (&wacom_udev_list_lock); -kfree (data); }static void wacom_remove_shared_data (void *res) { -struct wacom *wacom = res; +struct wacom *res_wacom = res;struct wacom_hdev_data *data; -struct wacom_wac *wacom_wac = &wacom->wacom_wac; +struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;if (wacom_wac->shared) { data = container_of(wacom_wac->shared, struct wacom_hdev_data,
@@ -871,17 +888,19 @@ static void wacom_remove_shared_data(voircu_dereference_protected (wacom_wac->shared->pen,lockdep_is_held (&wacom_udev_list_lock)); -if (touch == wacom->hdev) { +if (touch == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->touch,NULL );rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); - }else if (pen == wacom->hdev) { + }else if (pen == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->pen,NULL ); } }synchronize_rcu (); -kref_put (&data->kref, wacom_release_shared_data); +if (kref_put_mutex (&data->kref, wacom_release_shared_data, &wacom_udev_list_lock)) +mutex_unlock (&wacom_udev_list_lock); + wacom_wac->shared =NULL ; } }
@@ -904,7 +923,10 @@ static int wacom_add_shared_data(struct }kref_init (&data->kref); - data->dev = hdev; +strscpy (data->phys, hdev->phys,sizeof (data->phys)); + data->vendor = hdev->vendor; + data->product = hdev->product; + data->device_type = wacom_wac->features.device_type;list_add_tail (&data->list, &wacom_udev_list); }
Greg Kroah-Hartman
maintainerPATCH 550/2857 HID: wacom: Setup SW_MUTE_DEVICE according to the order of input registration
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit 97ce491bcef2d231b8d51cee8e579183319a5ba4 upstream.
The refactored SW_MUTE_DEVICE code assumed that stylus will be the first regiestered input. In reality, touch can be registered before stylus, such as the Wacom Cintiq Pro 13 and 16.
This patch covers both touch-first and stylus-first cases.
--- drivers/hid/wacom_wac.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
drivers/hid/wacom_wac.c +30 -3
@@ -3943,10 +3943,18 @@ int wacom_setup_touch_input_capabilitiesif (features->type ==HID_GENERIC ) {hid_dbg (hdev,"generic touch setup\n" ); -if (wacom_wac->has_mute_touch_switch || - (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch))) { + +/* +* This is to setup the touch switch for those devices that report +* pen interface first. The setup can only be done here since this +* routine is only called once. When we are here, the shared +* has_mute_touch_switch has been set by the pad. + +* There are two ways of reporting inputs from firmware: stylus first +* or touch first. This path covers the stylus input first case. +*/ +if (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch)) {input_set_capability (input_dev,EV_SW ,SW_MUTE_DEVICE ); - wacom_wac->has_mute_touch_switch = true; }/* setup has already been done */ return 0 ;
@@ -4369,7 +4377,26 @@ int wacom_setup_pad_input_capabilities(sbreak ;case INTUOSHT3_BT : +break ; +case HID_GENERIC : +if (wacom_wac->shared) { +/* +* The setup of touch switch capability can only be done +* here for those devices, such as Cintiq Pro 13 and 16, +* that have touch input registered before stylus and pad +* inputs. +* +* There are two ways of reporting inputs from firmware: +* stylus first or touch first. This path covers the touch +* input first case. +*/ +if (wacom_wac->has_mute_touch_switch && + wacom_wac->shared->touch_input) { +input_set_capability (wacom_wac->shared->touch_input, +EV_SW ,SW_MUTE_DEVICE ); + } + }break ;default :
Greg Kroah-Hartman
maintainerPATCH 551/2857 HID: wacom: Write shared touch initial status only once
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit cae3031c691dff0be61a26bc64e31a6939010d5c upstream.
For consistency with how the shared has_mute_touch_switch is handled during registration, let's apply WRITE_ONCE to is_touch_on too.
--- drivers/hid/wacom_sys.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/wacom_sys.c +1 -1
@@ -2349,7 +2349,7 @@ static void wacom_set_shared_values(stru* match historic default. */ if (wacom_wac->is_soft_touch_switch) - wacom_wac->shared->is_touch_on = true; +WRITE_ONCE (wacom_wac->shared->is_touch_on, true); }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) {
Greg Kroah-Hartman
maintainerPATCH 552/2857 klist: avoid accesses after waking klist_remove()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.
klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().
On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.
Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().
--- lib/klist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@#include <linux/klist.h> #include <linux/export.h> #include <linux/sched.h> +#include <linux/sched/task.h> /* * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *kWARN_ON (!knode_dead (n));list_del (&n->n_node); +knode_set_klist (n,NULL );spin_lock (&klist_remove_lock);list_for_each_entry_safe (waiter, tmp, &klist_remove_waiters, list) { +struct task_struct *p; +if (waiter->node != n)continue ; + p = waiter->process; +get_task_struct (p);list_del (&waiter->list); - waiter->woken =1 ; +/* Publish only after the final waiter and n accesses */ +smp_store_release (&waiter->woken,1 );mb (); -wake_up_process (waiter->process); +wake_up_process (p); +put_task_struct (p); }spin_unlock (&klist_remove_lock); -knode_set_klist (n,NULL ); }static int klist_dec_and_del (struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)for (;;) {set_current_state (TASK_UNINTERRUPTIBLE ); -if (waiter.woken) +/* Pairs with the release store in klist_release() */ +if (smp_load_acquire (&waiter.woken))break ;schedule (); }
Greg Kroah-Hartman
maintainerPATCH 553/2857 fbdev: atmel_lcdfb: Prevent FIFO work after removal
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yibo Tan <[email protected]>
commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.
The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.
The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.
KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.
Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.
--- drivers/video/fbdev/atmel_lcdfb.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1171,6 +1171,9 @@ static int __init atmel_lcdfb_probe(stru/* Initialize PWM for contrast or backlight ("off") */ init_contrast (sinfo); +/* Some LCDC recovery operations require process context. */ +INIT_WORK (&sinfo->task, atmel_lcdfb_task); +/* interrupt */ ret =request_irq (sinfo->irq_base, atmel_lcdfb_interrupt,0 , pdev->name, info);if (ret) {
@@ -1178,10 +1181,6 @@ static int __init atmel_lcdfb_probe(stru goto unmap_mmio; } -/* Some operations on the LCDC might sleep and -* require a preemptible task context */ -INIT_WORK (&sinfo->task, atmel_lcdfb_task); - ret =atmel_lcdfb_init_fbinfo (sinfo);if (ret <0 ) {dev_err (dev,"init fbinfo failed: %d\n" , ret);
@@ -1217,8 +1216,8 @@ reset_drvdata:dev_set_drvdata (dev,NULL );fb_dealloc_cmap (&info->cmap); unregister_irqs: -cancel_work_sync (&sinfo->task);free_irq (sinfo->irq_base, info); +cancel_work_sync (&sinfo->task); unmap_mmio:exit_backlight (sinfo);iounmap (sinfo->mmio);
@@ -1255,6 +1254,7 @@ static int __exit atmel_lcdfb_remove(strreturn 0 ; sinfo = info->par; +free_irq (sinfo->irq_base, info);cancel_work_sync (&sinfo->task);exit_backlight (sinfo);atmel_lcdfb_power_control (sinfo,0 );
@@ -1263,7 +1263,6 @@ static int __exit atmel_lcdfb_remove(strclk_put (sinfo->lcdc_clk);clk_put (sinfo->bus_clk);fb_dealloc_cmap (&info->cmap); -free_irq (sinfo->irq_base, info);iounmap (sinfo->mmio);release_mem_region (info->fix.mmio_start, info->fix.mmio_len);if (platform_get_resource (pdev,IORESOURCE_MEM ,1 )) {
Greg Kroah-Hartman
maintainerPATCH 554/2857 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.
dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().
Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.
BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47 Workqueue: events console_callback Call Trace: fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) display_to_var (drivers/video/fbdev/core/fbcon.c:998) fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182) redraw_screen (drivers/tty/vt/vt.c:994) complete_change_console (drivers/tty/vt/vt_ioctl.c:1141) console_callback (drivers/tty/vt/vt.c:3358) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 28 bytes inside of freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
--- drivers/video/fbdev/udlfb.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1336,6 +1336,11 @@ static int dlfb_setup_modes(struct dlfb_ goto error; } +if (dlfb->fb_count) { + result = -EINVAL ; + goto error; + } +fb_destroy_modelist (&info->modelist);memset (&info->monspecs,0 ,sizeof (info->monspecs));
Greg Kroah-Hartman
maintainerPATCH 555/2857 HID: hiddev: keep state alive through disconnect unlock
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yousef Alhouseen <[email protected]>
commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.
mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.
Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.
--- drivers/hid/usbhid/hiddev.c | 37 +++++++++++++++++++------------------ include/linux/hiddev.h | 2 ++ 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {struct mutex thread_lock; }; +static void hiddev_put (struct hiddev *hiddev) +{ +if (refcount_dec_and_test (&hiddev->refcount)) +kfree (hiddev); +} +/* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, structstatic int hiddev_release (struct inode * inode,struct file * file) {struct hiddev_list *list = file->private_data; +struct hiddev *hiddev = list->hiddev;unsigned long flags; -spin_lock_irqsave (&list->hiddev->list_lock, flags); +spin_lock_irqsave (&hiddev->list_lock, flags);list_del (&list->node); -spin_unlock_irqrestore (&list->hiddev->list_lock, flags); +spin_unlock_irqrestore (&hiddev->list_lock, flags); -mutex_lock (&list->hiddev->existancelock); -if (!--list->hiddev->open) { -if (list->hiddev->exist) { -hid_hw_close (list->hiddev->hid); -hid_hw_power (list->hiddev->hid,PM_HINT_NORMAL ); - }else { -mutex_unlock (&list->hiddev->existancelock); -kfree (list->hiddev); -vfree (list); -return 0 ; - } +mutex_lock (&hiddev->existancelock); +if (!--hiddev->open && hiddev->exist) { +hid_hw_close (hiddev->hid); +hid_hw_power (hiddev->hid,PM_HINT_NORMAL ); } -mutex_unlock (&list->hiddev->existancelock); +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev);vfree (list);return 0 ;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *spin_unlock_irq (&hiddev->list_lock); file->private_data = list; +refcount_inc (&hiddev->refcount);return 0 ;
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hiINIT_LIST_HEAD (&hiddev->list);spin_lock_init (&hiddev->list_lock);mutex_init (&hiddev->existancelock); +refcount_set (&hiddev->refcount,1 ); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist =1 ;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_deviceif (hiddev->open) {hid_hw_close (hiddev->hid);wake_up_interruptible (&hiddev->wait); -mutex_unlock (&hiddev->existancelock); - }else { -mutex_unlock (&hiddev->existancelock); -kfree (hiddev); } +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev); }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@#ifndef _HIDDEV_H#define _HIDDEV_H +#include <linux/refcount.h> #include <uapi/linux/hiddev.h>
@@ -24,6 +25,7 @@ struct hiddev {int minor;int exist;int open; +refcount_t refcount;struct mutex existancelock;wait_queue_head_t wait;struct hid_device *hid;
Greg Kroah-Hartman
maintainerPATCH 556/2857 io_uring/io-wq: save worker type before dropping its reference
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.
io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.
Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.
--- io_uring/io-wq.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1343,14 +1343,16 @@ static void io_wq_cancel_tw_create(strucwhile ((cb =task_work_cancel_match (wq->task, io_task_work_match, wq)) !=NULL ) {struct io_worker *worker; +bool free_worker; worker = container_of(cb, struct io_worker, create_work); -io_worker_cancel_cb (worker);/* * Only the worker continuation helper has worker allocated and -* hence needs freeing. +* hence needs freeing. Save this before dropping its reference. */ -if (cb->func == create_worker_cont) + free_worker = cb->func == create_worker_cont; +io_worker_cancel_cb (worker); +if (free_worker)kfree (worker); } }
Greg Kroah-Hartman
maintainerPATCH 557/2857 KVM: PPC: Book3S HV: Add SRCU protection for virtual-mode HPT hcalls
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 61a39797bb136243c48b46e2586d8a9e2cea6a89 upstream.
The virtual-mode HPT hcall handlers (H_ENTER, H_REMOVE, H_BULK_REMOVE, H_CLEAR_REF, H_CLEAR_MOD) call into book3s_hv_rm_mmu.c, which accesses memslots via kvm_memslots_raw(). kvm_memslots_raw() uses rcu_dereference_raw_check() to bypass SRCU lockdep annotation checking. This is safe in real mode because the entire guest entry/exit is wrapped in srcu_read_lock/unlock inside kvmppc_run_core() and kvmhv_run_single_vcpu().
However, since commit 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults"), these same handlers are also executed in virtual mode via kvmppc_pseries_do_hcall(), which runs after SRCU has already been released on guest exit.
A concurrent KVM_SET_USER_MEMORY_REGION deletion or move can therefore call synchronize_srcu_expedited() — which does not wait for this thread — and then kfree(slot) and vfree(slot->arch.rmap) while the hcall handler still holds a raw pointer to the memslot. lock_rmap() then writes to freed vmalloc memory, leading to use-after-free and memory corruption. Because kvm_memslots_raw() suppresses lockdep checks, this race is entirely silent.
Fix this by factoring out the 7 HPT hcall handlers (H_REMOVE, H_ENTER, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, H_BULK_REMOVE) into a helper function, kvmppc_pseries_do_hpt_hcall(), and wrapping its call site in srcu_read_lock(&kvm->srcu) / srcu_read_unlock(&kvm->srcu, idx). Targeting only the HPT hcalls avoids wrapping non-HPT hcalls that sleep (such as H_CONFER, H_REGISTER_VPA, H_PAGE_INIT) or handlers that already acquire SRCU internally (such as H_RTAS).
--- arch/powerpc/kvm/book3s_hv.c | 70 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 35 deletions(-)
arch/powerpc/kvm/book3s_hv.c +35 -35
@@ -1085,6 +1085,38 @@ static long kvmppc_h_rpt_invalidate(strureturn H_SUCCESS ; } +static long kvmppc_pseries_do_hpt_hcall (struct kvm_vcpu *vcpu,unsigned long req) +{ +switch (req) { +case H_REMOVE : +return kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_ENTER : +return kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 ), +kvmppc_get_gpr (vcpu,7 )); +case H_READ : +return kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_MOD : +return kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_REF : +return kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_PROTECT : +return kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_BULK_REMOVE : +return kvmppc_h_bulk_remove (vcpu); + } + +return H_FUNCTION ; +} +int kvmppc_pseries_do_hcall (struct kvm_vcpu *vcpu) {struct kvm *kvm = vcpu->kvm;
@@ -1100,47 +1132,15 @@ int kvmppc_pseries_do_hcall(struct kvm_vswitch (req) {case H_REMOVE : - ret =kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_ENTER : - ret =kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 ), -kvmppc_get_gpr (vcpu,7 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_READ : - ret =kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_MOD : - ret =kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_REF : - ret =kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_PROTECT : - ret =kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_BULK_REMOVE : - ret =kvmppc_h_bulk_remove (vcpu); + idx =srcu_read_lock (&kvm->srcu); + ret =kvmppc_pseries_do_hpt_hcall (vcpu, req); +srcu_read_unlock (&kvm->srcu, idx);if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
Greg Kroah-Hartman
maintainerPATCH 558/2857 media: cx23885: unregister DVB bus when SP2 CI setup fails
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.
The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.
Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/media/pci/cx23885/cx23885-dvb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1160,8 +1160,12 @@ static int dvb_register_ci_mac(struct cx info.platform_data = &sp2_config;request_module (info.type); client_ci =i2c_new_client_device (&i2c_bus->i2c_adap, &info); -if (!i2c_client_has_driver (client_ci)) +if (IS_ERR (client_ci)) +return PTR_ERR (client_ci); +if (!client_ci->dev.driver) { +i2c_unregister_device (client_ci);return -ENODEV ; + }if (!try_module_get (client_ci->dev.driver->owner)) {i2c_unregister_device (client_ci);return -ENODEV ;
@@ -1204,7 +1208,7 @@ static int dvb_register(struct cx23885_tint (*p_set_voltage)(struct dvb_frontend *fe,enum fe_sec_voltage voltage) =NULL ;int mfe_shared =0 ;/* bus not shared by default */ -int ret; +int ret = -EINVAL ;/* Get the first frontend */ fe0 =vb2_dvb_get_frontend (&port->frontends,1 );
@@ -2586,8 +2590,10 @@ static int dvb_register(struct cx23885_t goto frontend_detach; ret =dvb_register_ci_mac (port); -if (ret) +if (ret) { +vb2_dvb_unregister_bus (&port->frontends); goto frontend_detach; + }return 0 ;
@@ -2618,7 +2624,7 @@ frontend_detach: port->gate_ctrl =NULL ;vb2_dvb_dealloc_frontends (&port->frontends); -return -EINVAL ; +return ret; }int cx23885_dvb_register (struct cx23885_tsport *port)
Greg Kroah-Hartman
maintainerPATCH 559/2857 media: gspca: use vb2_video_unregister_device() on disconnect
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.
gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.
gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().
Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.
--- drivers/media/usb/gspca/gspca.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1643,9 +1643,8 @@ void gspca_disconnect(struct usb_interfa#endif v4l2_device_disconnect (&gspca_dev->v4l2_dev); -video_unregister_device (&gspca_dev->vdev); -mutex_unlock (&gspca_dev->usb_lock); +vb2_video_unregister_device (&gspca_dev->vdev);/* (this will call gspca_release() immediately or on last close) */ v4l2_device_put (&gspca_dev->v4l2_dev);
Greg Kroah-Hartman
maintainerPATCH 560/2857 media: imx-jpeg: cancel timeout worker when streaming stops
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 78fdfbf117c409273eecbfa7a528ef42358a0e38 upstream.
Each per-fd context ctx owns a delayed_work (ctx->task_timer, callback mxc_jpeg_device_run_timeout) armed via schedule_delayed_work() at the end of mxc_jpeg_device_run() to recover a stalled encode/decode job. The only existing cancellation is cancel_delayed_work() in the frame-done IRQ handler, which de-queues a pending work item but does not wait for a callback that has already started, and it only runs when a frame completes.
When the fd is closed while a job is in flight (the frame-done IRQ has not fired yet), nothing syncs the worker before mxc_jpeg_release() frees ctx with kfree() after v4l2_m2m_ctx_release(). A queued or executing mxc_jpeg_device_run_timeout() can then recover ctx through container_of(&ctx->task_timer) and dereference it (ctx->mxc_jpeg, slot_data, dev_warn) after ctx has been freed.
Cancel the worker from mxc_jpeg_stop_streaming(). The cancel cannot live in mxc_jpeg_release(): mxc_jpeg_device_run() arms the timer while holding only hw_lock, not the mxc_jpeg->lock mutex that release holds, so a cancel in release could still race a concurrent mxc_jpeg_device_run() that re-arms the timer afterwards. mxc_jpeg_stop_streaming() instead runs inside v4l2_m2m_ctx_release() -> vb2_queue_release(), i.e. after v4l2_m2m_cancel_job() has set TRANS_ABORT and waited for any in-flight job to finish (so __v4l2_m2m_try_queue() will not queue and v4l2_m2m_try_run() will not run any further job for this context, which prevents mxc_jpeg_device_run() from re-arming the timer) and before the m2m context is freed. cancel_delayed_work_sync() removes a pending work item and waits for a running callback, so the worker can no longer race with the subsequent kfree(). The cancel is placed before the buffer-release loop so a concurrently running timeout callback cannot race with it over the same buffers. If the frame-done IRQ canceled a still-pending timer, this cancel is a no-op; if the timeout callback has already started, it waits for the callback to finish. The same mxc_jpeg_stop_streaming() call is also reached from VIDIOC_STREAMOFF, which drains the worker early, although STREAMOFF itself does not free ctx -- the use-after-free arises only when the fd is later closed.
This bug was found by static analysis.
--- drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c +2 -0
@@ -1263,6 +1263,8 @@ static void mxc_jpeg_stop_streaming(strudev_dbg (ctx->mxc_jpeg->dev,"Stop streaming ctx=%p" , ctx); +cancel_delayed_work_sync (&ctx->task_timer); +/* Release all active buffers */ for (;;) {if (V4L2_TYPE_IS_OUTPUT (q->type))
Greg Kroah-Hartman
maintainerPATCH 561/2857 media: redrat3: fix UAF in probe error path leaving rc device registered
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
commit af452b9e01331b5338a1e5141624f17607239207 upstream.
redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.
KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648 Read of size 1 at addr ffff888051fda758 by task udevd/7464 Call Trace: string_nocheck lib/vsprintf.c:648 [inline] string+0x216/0x2d0 lib/vsprintf.c:730 vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945 vscnprintf+0x41/0x90 lib/vsprintf.c:3014 sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761 input_dev_show_name+0x58/0x70 drivers/input/input.c:1282 Allocated by task 10: redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023 Freed by task 10: redrat3_delete drivers/media/rc/redrat3.c:466 [inline] redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124
Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().
When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.
Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.
When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.
This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.
--- drivers/media/rc/redrat3.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -977,6 +977,7 @@ static int redrat3_dev_probe(struct usb_struct device *dev = &intf->dev;struct usb_host_interface *uhi;struct redrat3_dev *rr3; +struct rc_dev *rc;struct usb_endpoint_descriptor *ep;struct usb_endpoint_descriptor *ep_narrow =NULL ;struct usb_endpoint_descriptor *ep_wide =NULL ;
@@ -1121,9 +1122,12 @@ static int redrat3_dev_probe(struct usb_return 0 ; led_free: +rc_unregister_device (rr3->rc);led_classdev_unregister (&rr3->led); redrat_free: + rc = rr3->rc;redrat3_delete (rr3, rr3->udev); +rc_free_device (rc); no_endpoints:return retval;
Greg Kroah-Hartman
maintainerPATCH 562/2857 serial: core: shut down initialized port on removal
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Putko <[email protected]>
commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 upstream.
When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.
If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.
This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:
BUG: KASAN: slab-use-after-free in string+0x476/0x570 Call Trace: string+0x476/0x570 vsnprintf+0x422/0x1300 seq_printf+0x... show_interrupts+...
Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).
--- drivers/tty/serial/serial_core.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3263,6 +3263,13 @@ void uart_remove_one_port(struct uart_drif (uart_console (uport))unregister_console (uport->cons); + scoped_guard(mutex, &port->mutex) { + port->console = false; + +if (tty_port_initialized (port)) +uart_shutdown (NULL , state); + } +/* * Free the port IO and memory resources, if any. */
Greg Kroah-Hartman
maintainerPATCH 563/2857 xen-blkfront: unbind irq before tearing down ring and shadow requests
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuchao Zhang <[email protected]>
commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc upstream.
In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.
While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.
Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.
Message-ID: <[email protected]>
--- drivers/block/xen-blkfront.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1211,6 +1211,14 @@ static void blkif_free_ring(struct blkfrint i, j, segs;/* +* Interrupt teardown must be done ahead of freeing queue-related +* data, otherwise the interrupt handler can race with the cleanup. +*/ +if (rinfo->irq) +unbind_from_irqhandler (rinfo->irq, rinfo); + rinfo->evtchn = rinfo->irq =0 ; + +/* * Remove indirect pages, this only happens when using indirect * descriptors but not persistent grants */
@@ -1292,10 +1300,6 @@ free_shadow:/* Free resources associated with old device channel. */ xenbus_teardown_ring ((void **)&rinfo->ring.sring, info->nr_ring_pages, rinfo->ring_ref); - -if (rinfo->irq) -unbind_from_irqhandler (rinfo->irq, rinfo); - rinfo->evtchn = rinfo->irq =0 ; }static void blkif_free (struct blkfront_info *info,int suspend)
Greg Kroah-Hartman
maintainerPATCH 564/2857 wifi: ath9k: delete channel-context timers on deinit
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
commit 81394dfb9a7905472957628b560ae894eae3a30f upstream.
ath9k_deinit_channel_context() cancels chanctx_work but does not delete the offchannel and sched timers set up by ath9k_init_channel_context(). If either timer fires after deinit (e.g. during driver unload or suspend), it accesses sc->sc_ah which may already be freed by ath9k_hw_deinit(), causing a use-after-free.
Delete both timers with timer_shutdown_sync() before cancelling the work item.
--- drivers/net/wireless/ath/ath9k/channel.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath9k/channel.c +2 -0
@@ -1368,6 +1368,8 @@ void ath9k_init_channel_context(struct avoid ath9k_deinit_channel_context (struct ath_softc *sc) { +timer_shutdown_sync (&sc->sched.timer); +timer_shutdown_sync (&sc->offchannel.timer);cancel_work_sync (&sc->chanctx_work); }
Greg Kroah-Hartman
maintainerPATCH 565/2857 usb: gadget: fix refcount underflow in gadgetfs_bind() error path
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Quang Le Kien <[email protected]>
commit cb3b441f2698455a48e9a023d5f7f4e3fcb94c73 upstream.
gadgetfs_bind() calls get_dev() only on the success path, but gadgetfs_unbind() called from the enomem error label unconditionally calls put_dev(). When bind fails (e.g. ENOMEM), put_dev() fires without a matching get_dev(), leaving the refcount unbalanced.
A subsequent close of the ep0 file descriptor calls dev_release() -> put_dev() which hits zero and frees the object; then gadgetfs_kill_sb() calls put_dev(the_device) again on the already-freed pointer, triggering a refcount underflow and use-after-free.
Fix by calling get_dev() at the start of gadgetfs_bind(), before any error path that invokes gadgetfs_unbind(), so the reference is always balanced regardless of whether bind succeeds or fails.
--- drivers/usb/gadget/legacy/inode.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/gadget/legacy/inode.c +2 -1
@@ -1682,6 +1682,8 @@ static int gadgetfs_bind(struct usb_gadg dev->gadget = gadget; gadget->ep0->driver_data = dev; +get_dev (dev); +/* preallocate control response and buffer */ dev->req =usb_ep_alloc_request (gadget->ep0,GFP_KERNEL );if (!dev->req)
@@ -1696,7 +1698,6 @@ static int gadgetfs_bind(struct usb_gadgspin_lock_irq (&dev->lock); dev->state =STATE_DEV_UNCONNECTED ;spin_unlock_irq (&dev->lock); -get_dev (dev);return 0 ; enomem:
Greg Kroah-Hartman
maintainerPATCH 566/2857 ufs: use u64 for directory size in ufs_last_byte
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: YANXIN LI <[email protected]>
commit 1eff23433e73d7da4f9e3529d2701e34962b161f upstream.
ufs1_read_inode() and ufs2_read_inode() copy the untrusted 64-bit on-disk size into inode->i_size. ufs_last_byte() then truncates that value to an unsigned int before calculating the valid extent of a directory folio.
A directory size of exactly 4 GiB is truncated to zero. In ufs_find_entry(), subtracting the requested record length from that zero forms an endpoint almost 4 GiB beyond the mapped folio. A crafted UFS2 image produces:
BUG: KASAN: use-after-free in ufs_find_entry+0x583/0x6e0 [ufs] Read of size 1 ... ufs_find_entry ufs_inode_by_name ufs_lookup __lookup_slow path_lookupat
The KASAN classification reflects that the adjacent physical page was free; the source-level operation is an out-of-folio read. A controlled UFS1 test with CONFIG_UFS_FS_WRITE enabled also made ufs_find_entry() return a directory entry from an adjacent anonymous page. unlink() then passed that pointer to ufs_delete_entry(), which cleared the adjacent page's 3
2-bit d_ino. This write result reproduced three out of three times.
UFS normally requires a privileged mount path. A relevant boundary is a privileged automounter or image-processing service handling an attacker-supplied filesystem. The write primitive additionally requires UFS1 to be mounted read-write with CONFIG_UFS_FS_WRITE enabled; the read is reachable with read-only UFS2.
Keep the intermediate size arithmetic at 64 bits so non-final pages are bounded at PAGE_SIZE. With this change, the same controlled tests reach the real on-disk directory entry and produce no adjacent-page write or KASAN report. A reproducer and full validation logs are available on request.
The vulnerable helper is present in v7.2-rc3, v7.1, v6.18.38, v6.12.95, v6.6.111, and upstream master at 1229e2e57a5c. Runtime reproduction and fix validation were performed in an x86-64 QEMU guest running v7.2-rc3 with generic KASAN.
--- fs/ufs/dir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ufs/dir.c +1 -1
@@ -211,7 +211,7 @@ fail:static unsigned ufs_last_byte (struct inode *inode,unsigned long page_nr) { -unsigned last_byte = inode->i_size; +u64 last_byte = inode->i_size; last_byte -= page_nr <<PAGE_SHIFT ;if (last_byte >PAGE_SIZE )
Greg Kroah-Hartman
maintainerPATCH 567/2857 resource: report a devm_request_resource() conflict under the lock
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
commit d2f7bdfdeac8137e942b32e0badc40e181127d7b upstream.
devm_request_resource() calls request_resource_conflict(), which takes resource_lock, tries to insert the new resource and returns a pointer to the conflicting resource after dropping the lock. The error message is then formatted from that pointer: conflict->name and the %pR argument read the name, start, end, flags and desc of a resource that nothing pins any more. The owner of the conflicting resource may call release_resource() and free it the moment the lock is dropped.
The conflicting resource normally belongs to another device. With two devices whose drivers claim overlapping regions (two PCI host bridges whose "ranges" windows overlap, two instances of a controller on the same aperture, or a stale claim an administrator is replacing), the following interleaving reads freed memory:
CPU 0: driver B probe CPU 1: driver A unbind
devm_request_resource(devB, root, resB)
request_resource_conflict()
write_lock(&resource_lock)
__request_resource() -> resA
write_unlock(&resource_lock)
devres_release_all(devA)
devm_resource_release()
release_resource(resA)
put_device() -> kfree(resA)
dev_err(..., resA->name, resA) use after freeBoth halves are reachable from userspace on any kernel: a write to the "unbind" file of the driver that holds the region and a write to the "bind" file of the driver that wants it. One in-tree path is drivers/pci/bus.c devm_request_pci_bus_resources(), called from host bridge probe for every bridge window; the windows are the embedded struct resource of kzalloc'ed resource_entry objects that pci_free_resource_list() frees when the other bridge is released. In the common case the "resource collision" message is garbled; with the slab object poisoned (CONFIG_SLUB_DEBUG) or reused, formatting conflict->name oopses, and KASAN reports a slab-use-after-free read in devm_request_resource(). All of this happens in a probe that is already failing with -EBUSY. The window is a few hundred instructions wide and exists only when two devices actually collide, so the race has not been observed outside of analysis.
Do the same here: take resource_lock, insert with __request_resource() and print the diagnostic while the lock still keeps the conflicting resource in the tree, then drop the lock. The return values and the devres handling are unchanged.
The change was built for x86_64 and RISC-V; the resource KUnit tests pass on both.
Found by formal verification of kernel/resource.c against the kernel binary.
--- kernel/resource.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/resource.c +7 -2
@@ -1546,10 +1546,15 @@ int devm_request_resource(struct device *ptr = new; - conflict =request_resource_conflict (root, new); -if (conflict) { +/* Report a conflict while the lock still keeps it in the tree. */ +write_lock (&resource_lock); + conflict =__request_resource (root, new); +if (conflict)dev_err (dev,"resource collision: %pR conflicts with %s %pR\n" , new, conflict->name, conflict); +write_unlock (&resource_lock); + +if (conflict) {devres_free (ptr);return -EBUSY ; }
Greg Kroah-Hartman
maintainerPATCH 568/2857 phy: core: Fix race-condition between _of_phy_get() and try_module_get()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryan O'Donoghue <[email protected]>
commit 090055ee629523092688da42428558ba56d4272f upstream.
Sashiko asked during a patch review if the existing usage pattern had a race condition; specifically in of_phy_get() if it was possible between returning from _of_phy_get() and running try_module_get() that a module might be unbound leading to use-after-free.
Looking at the code this appears to be so, there is no linkage between the phy and module under a synchronisation primitive.
Using the phy_provider_mutex in phy_get() will ensure there is a link between the returned phy pointer and the module_get() bumping the module reference count.
Amend phy_get(), of_phy_get() and devm_of_phy_get_by_index() to fix the same usage pattern.
phy_provider_unregister() must take the phy_provider_mutex so amending phy_get()/of_phy_get() to take that same mutex guarantees there is no use-after-free.
--- drivers/phy/phy-core.c | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-)
drivers/phy/phy-core.c +30 -15
@@ -117,13 +117,13 @@ static struct phy *phy_find(struct devicconst char *dev_id =dev_name (dev);struct phy_lookup *p, *pl =NULL ; -mutex_lock (&phy_provider_mutex); +lockdep_assert_held (&phy_provider_mutex); +list_for_each_entry (p, &phys, node)if (!strcmp (p->dev_id, dev_id) && !strcmp (p->con_id, con_id)) { pl = p;break ; } -mutex_unlock (&phy_provider_mutex);return pl ? pl->phy :ERR_PTR (-ENODEV ); }
@@ -572,6 +572,8 @@ static struct phy *_of_phy_get(struct destruct phy *phy =NULL ;struct of_phandle_args args; +lockdep_assert_held (&phy_provider_mutex); + ret =of_parse_phandle_with_args (np,"phys" ,"#phy-cells" , index, &args);if (ret)
@@ -583,11 +585,10 @@ static struct phy *_of_phy_get(struct de goto out_put_node; } -mutex_lock (&phy_provider_mutex); phy_provider =of_phy_provider_lookup (args.np);if (IS_ERR (phy_provider) || !try_module_get (phy_provider->owner)) { phy =ERR_PTR (-EPROBE_DEFER ); - goto out_unlock; + goto out_put_node; }if (!of_device_is_available (args.np)) {
@@ -601,8 +602,6 @@ static struct phy *_of_phy_get(struct de out_put_module:module_put (phy_provider->owner); -out_unlock: -mutex_unlock (&phy_provider_mutex); out_put_node:of_node_put (args.np);
@@ -626,15 +625,21 @@ struct phy *of_phy_get(struct device_nodif (con_id) index =of_property_match_string (np,"phy-names" , con_id); +mutex_lock (&phy_provider_mutex); + phy =_of_phy_get (np, index);if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (of_phy_get);
@@ -741,6 +746,7 @@ struct phy *phy_get(struct device *dev,struct phy *phy;struct device_link *link; +mutex_lock (&phy_provider_mutex);if (dev->of_node) {if (string) index = of_property_match_string(dev->of_node, "phy-names",
@@ -751,15 +757,18 @@ struct phy *phy_get(struct device *dev, }else {if (string ==NULL ) {dev_WARN (dev,"missing string\n" ); -return ERR_PTR (-EINVAL ); + phy =ERR_PTR (-EINVAL ); + goto out_unlock; } phy =phy_find (dev, string); }if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev);
@@ -768,6 +777,8 @@ struct phy *phy_get(struct device *dev,dev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (phy_get);
@@ -907,15 +918,17 @@ struct phy *devm_of_phy_get_by_index(strif (!ptr)return ERR_PTR (-ENOMEM ); +mutex_lock (&phy_provider_mutex); phy =_of_phy_get (np, index);if (IS_ERR (phy)) {devres_free (ptr); -return phy; + goto out_unlock; }if (!try_module_get (phy->ops->owner)) {devres_free (ptr); -return ERR_PTR (-EPROBE_DEFER ); + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; }get_device (&phy->dev);
@@ -928,6 +941,8 @@ struct phy *devm_of_phy_get_by_index(strdev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (devm_of_phy_get_by_index);
Greg Kroah-Hartman
maintainerPATCH 569/2857 media: rc: fintek-cir: process a full RX buffer instead of overflowing it
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weigang He <[email protected]>
commit d1febef1bcfa7bbc401729f994c375b91a833911 upstream.
fintek_get_rx_ir_data() drains the CIR RX FIFO into fintek->buf[], which holds RX_BUF_LEN (32) bytes, for as long as CIR_STATUS reports pending RX data:
do {
sample = fintek_cir_reg_read(fintek, CIR_RX_DATA);
...
fintek->buf[fintek->pkts] = sample;
fintek->pkts++;
...
} while (status & rx_irqs);Nothing bounds fintek->pkts. If the hardware reports data for more than RX_BUF_LEN reads in one interrupt, the loop writes past the end of buf[], starting with the pkts counter that follows it in struct fintek_dev.
Hand a full buffer to fintek_process_rx_ir_data(), which parses the samples and resets fintek->pkts, before storing the next sample. This keeps the parser state consistent and drops no samples. The loop still relies on the status register to terminate.
The driver does not document the hardware FIFO depth, so it is not known whether a working device can trigger this.
Found by static analysis tool CodeQL.
--- drivers/media/rc/fintek-cir.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/fintek-cir.c +4 -0
@@ -340,6 +340,10 @@ static void fintek_get_rx_ir_data(struct sample =fintek_cir_reg_read (fintek,CIR_RX_DATA );fit_dbg ("%s: sample: 0x%02x" , __func__, sample); +/* Process a full buffer before storing the next sample. */ +if (fintek->pkts >=RX_BUF_LEN ) +fintek_process_rx_ir_data (fintek); + fintek->buf[fintek->pkts] = sample; fintek->pkts++;
Greg Kroah-Hartman
maintainerPATCH 570/2857 media: rc: mce_kbd: Fix inconsistent locking of keylock
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 29ee25fa9beb3232808e6d0b3e8ebfb0427cb820 upstream.
data->keylock is taken with spin_lock() in ir_mce_kbd_decode(), which runs in the raw IR decode kthread with local interrupts enabled, but with spin_lock_irqsave() in mce_kbd_rx_timeout(), the rx_timeout timer callback, which runs in softirq context.
If the decode kthread is holding keylock via spin_lock() when a timer interrupt fires on the same CPU and the softirq runs mce_kbd_rx_timeout(), the softirq spins forever waiting for a lock that only the now-preempted kthread can release, while the kthread cannot run again until the softirq gives up the CPU. This deadlocks the CPU.
--- drivers/media/rc/ir-mce_kbd-decoder.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/media/rc/ir-mce_kbd-decoder.c +3 -2
@@ -218,6 +218,7 @@ static int ir_mce_kbd_decode(struct rc_dstruct mce_kbd_dec *data = &dev->raw->mce_kbd;u32 scancode;unsigned long delay; +unsigned long flags;struct lirc_scancode lsc = {};if (!is_timing_event (ev)) {
@@ -318,7 +319,7 @@ again: scancode = data->body &0xffffff ;dev_dbg (&dev->dev,"keyboard data 0x%08x\n" , data->body); -spin_lock (&data->keylock); +spin_lock_irqsave (&data->keylock, flags);if (scancode) { delay =usecs_to_jiffies (dev->timeout) +msecs_to_jiffies (100 );
@@ -328,7 +329,7 @@ again: }/* Pass data to keyboard buffer parser */ ir_mce_kbd_process_keyboard_data (dev, scancode); -spin_unlock (&data->keylock); +spin_unlock_irqrestore (&data->keylock, flags); lsc.rc_proto =RC_PROTO_MCIR2_KBD ;break ;case MCIR2_MOUSE_NBITS :
Greg Kroah-Hartman
maintainerPATCH 571/2857 ocfs2/heartbeat: unlink live slots when their node is missing
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 3ccd24c3f7a577b84a532cb027f1378385b82ef6 upstream.
o2hb_shutdown_slot() returns immediately when its node is no longer in the configfs registry. A slot can still be linked in o2hb_live_slots when that lookup fails. Region teardown or startup-error cleanup then frees the slot array without removing its embedded list member.
With the same peer live in another region, the next list update can follow a predecessor into the freed array. Reusing the node number can also make a later insertion encounter that stale member.
Always remove the slot under o2hb_live_lock, even when node lookup fails. Preserve aggregate membership accounting and the last-region DOWN
callback: the existing callback interface explicitly permits a NULL node for DOWN events. Only drop the node reference when lookup returned one. This closes both normal release and startup-abort paths without changing the publication or callback locking protocol.
Also require a configured node before admitting a new live slot in o2hb_check_slot(). The early live-bitmap check is not held through
admission: the last live slot in another region can be removed in between. Without a node, admission can then queue an UP event with a NULL argument and hit the event helper's BUG_ON. Existing live slots can still leave and generate NULL-node DOWN events.
A controlled probe-instrumented test reproduced this while stopping one of two regions after removing the peer from configfs. Its KASAN report includes:
BUG: KASAN: slab-use-after-free in __list_del_entry_valid_or_report+0x1e0/0x210 Read of size 8 at addr ffff888106a4ac60 by task o2hb-pmbd0058_b/497 Call Trace: <TASK> dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 kasan_report+0xe0/0x110 __list_del_entry_valid_or_report+0x1e0/0x210 o2hb_do_disk_heartbeat+0x1591/0x2c50 o2hb_thread+0x1ed/0xe70 kthread+0x351/0x460 ret_from_fork+0x659/0x940 ret_from_fork_asm+0x1a/0x30 </TASK> Allocated by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_noprof+0x2de/0x780 o2hb_region_dev_store+0x7c2/0x1b60 configfs_write_iter+0x2f9/0x4f0 vfs_write+0x639/0x1010 ksys_write+0x111/0x200 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x308/0x580 o2hb_unmap_slot_data+0x1db/0x330 o2hb_region_release+0x14b/0x4f0 config_item_cleanup+0x14b/0x230 config_item_put+0x79/0x90 configfs_rmdir+0x58a/0x910 vfs_rmdir+0x2e8/0x820 filename_rmdir+0x3b1/0x520 __x64_sys_rmdir+0x4b/0x70 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f
--- fs/ocfs2/cluster/heartbeat.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/ocfs2/cluster/heartbeat.c +8 -4
@@ -860,8 +860,11 @@ static void o2hb_shutdown_slot(struct o2int queued =0 ; node =o2nm_get_node_by_num (slot->ds_node_num); -if (!node) -return ; +/* +* The node may have been removed from the node table while this +* region's slot is still linked. The list member must still be +* removed before the region releases its slot array. +*/ spin_lock (&o2hb_live_lock);if (!list_empty (&slot->ds_live_item)) {
@@ -883,7 +886,8 @@ static void o2hb_shutdown_slot(struct o2if (queued)o2hb_run_event_list (&event); -o2nm_node_put (node); +if (node) +o2nm_node_put (node); }static void o2hb_set_quorum_device (struct o2hb_region *reg)
@@ -1018,7 +1022,7 @@ static int o2hb_check_slot(struct o2hb_r fire_callbacks:/* dead nodes only come to life after some number of * changes at any time during their dead time */ -if (list_empty (&slot->ds_live_item) && +if (node &&list_empty (&slot->ds_live_item) && slot->ds_changed_samples >=O2HB_LIVE_THRESHOLD ) {mlog (ML_HEARTBEAT ,"Node %d (id 0x%llx) joined my region\n" , slot->ds_node_num, (long long )slot->ds_last_generation);
Greg Kroah-Hartman
maintainerPATCH 572/2857 ocfs2/dlm: hold a lock reference across grant AST enqueue
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 71743471204e21113295c786e5cfa570294234a4 upstream.
A newly granted remote lock must remain alive until its grant AST is queued. dlmlock_master() publishes the lock on res->granted with its base and queue references, then drops res->spinlock before calling dlm_queue_ast(). The resource's reserved AST count does not retain the lock itself.
This can fail when a peer dies with an immediately grantable CREATE buffered on its socket. O2NET's node-down callback flushes receive work before DLM cleanup, but the flush only waits for work queued on entry. A data-ready callback that already selected the socket container can queue new receive work after the flush advances its work color. Socket shutdown does not discard bytes already queued for TCP receive.
The late receive work and DLM node-down cleanup can interleave as follows (the lock reference operations shown are before this fix):
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered CREATE dlmlock_master()
lock res->spinlock add lock to granted unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put queue/base refs
free lock
unlock res->spinlock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
DLM cleanup holds res->spinlock while dlm_free_dead_locks() drops the queue and base references. The CREATE handler no longer holds that spinlock when __dlm_queue_ast() reads the lock, before taking its AST list reference.
Take a temporary lock reference under res->spinlock when a grant AST will be queued, and drop it after dlm_queue_ast(). This keeps the lock alive across cleanup until the AST path has taken its own reference, without reversing the existing AST/resource lock order.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __dlm_queue_ast+0x8a4/0xc00
Read of size 8 at addr ffff88810ead5940 by task kworker/u16:3/52
CPU: 3 UID: 0 PID: 52 Comm: kworker/u16:3 Not tainted 7.3.0-rc4-next-20260921-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: o2net o2net_rx_until_empty
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __dlm_queue_ast+0x8a4/0xc00
kasan_report+0xe0/0x110
? __dlm_queue_ast+0x8a4/0xc00
__dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? do_raw_spin_lock+0x130/0x270
? __pfx___dlm_queue_ast+0x10/0x10
? __pfx_do_raw_spin_lock+0x10/0x10
? _raw_spin_unlock_irqrestore+0x45/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
dlm_queue_ast+0x46/0x70
dlmlock_master+0x51f/0xf50
? __pfx_dlmlock_master+0x10/0x10
? dlm_create_lock_handler+0x2b2/0x870
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
dlm_create_lock_handler+0x35b/0x870
? __pfx_dlm_create_lock_handler+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
? kvm_clock_get_cycles+0x31/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_dlm_create_lock_handler+0x10/0x10
o2net_rx_until_empty+0x1dae/0x32c0
? reacquire_held_locks+0xdd/0x200
? __pfx_o2net_rx_until_empty+0x10/0x10
? lock_acquire+0x190/0x300
? process_one_work+0x935/0x1b40
? process_one_work+0x834/0x1b40
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? srso_alias_return_thunk+0x5/0xfbef5
process_one_work+0x9a8/0x1b40
? __pfx_process_one_work+0x10/0x10
? lock_acquire+0x190/0x300
? lock_is_held_type+0x8f/0x100
? srso_alias_return_thunk+0x5/0xfbef5
worker_thread+0x65c/0xe40
? srso_alias_return_thunk+0x5/0xfbef5
? __kthread_parkme+0x177/0x220
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_worker_thread+0x10/0x10
kthread+0x351/0x460
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_kthread+0x10/0x10
ret_from_fork+0x659/0x940
? __pfx_ret_from_fork+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __switch_to+0x74f/0xf70
? __pfx_kthread+0x10/0x10
ret_from_fork_asm+0x1a/0x30
</TASK>
Allocated by task 52:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_slab_alloc+0x89/0x90
kmem_cache_alloc_noprof+0x20b/0x5c0
dlm_new_lock+0x39/0x5f0
dlm_create_lock_handler+0x16e/0x870
o2net_rx_until_empty+0x1dae/0x32c0
process_one_work+0x9a8/0x1b40
worker_thread+0x65c/0xe40
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 603:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kmem_cache_free+0x242/0x580
dlm_lock_release+0x1df/0x2f0
dlm_lock_put+0x51/0x80
__dlm_hb_node_down+0x15be/0x2710
dlm_hb_node_down_cb+0x6c/0xa0
o2hb_run_event_list+0x34a/0x500
o2hb_do_disk_heartbeat+0x1a07/0x2950
o2hb_thread+0x1ed/0xdc0
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810ead5900
which belongs to the cache o2dlm_lock of size 184
The buggy address is located 64 bytes inside of
freed 184-byte region [ffff88810ead5900, ffff88810ead59b8)[Page and shadow memory dumps omitted.]
--- fs/ocfs2/dlm/dlmlock.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
fs/ocfs2/dlm/dlmlock.c +6 -2
@@ -138,6 +138,8 @@ static enum dlm_status dlmlock_master(st res->lockname.len)) { kick_thread = 1; call_ast = 1; + /* Keep the lock alive through AST enqueue. */ + dlm_lock_get(lock); } else { mlog(0, "%s: returning DLM_NORMAL to " "node %u for reco lock\n", dlm->name,
@@ -166,10 +168,12 @@ static enum dlm_status dlmlock_master(stwake_up (&res->wq);/* either queue the ast or release it */ -if (call_ast) +if (call_ast) {dlm_queue_ast (dlm, lock); -else +dlm_lock_put (lock); + }else {dlm_lockres_release_ast (dlm, res); + }dlm_lockres_calc_usage (dlm, res);if (kick_thread)
Greg Kroah-Hartman
maintainerPATCH 573/2857 ocfs2/dlm: hold the lookup reference across convert AST enqueue
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 125fe08ff6cfa064e1212f586f01993ee45c0330 upstream.
dlm_convert_lock_handler() drops the reference it took when it found the lock on res->granted at its leave label, one statement before it calls dlm_queue_ast(). dlm_free_dead_locks() takes res->spinlock and drops the list and base references, so a peer death landing in that gap leaves the handler's own put as the one that frees the lock, and __dlm_queue_ast() then reads lock->lockres from freed memory.
The handler is registered next to dlm_create_lock_handler(), so a convert message buffered on a dying peer's socket arrives on the same o2net receive work that o2net_disconnect_node() does not wait for. The two can interleave as follows, with the reference counts as they are before this fix:
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered convert_lock dlm_convert_lock_handler()
find lock on res->granted dlm_lock_get() refs = 3 lock res->spinlock __dlmconvert_master()
call_ast = 1
unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put list ref refs = 2
put base ref refs = 1
unlock res->spinlock
dlm_lock_put() refs = 0
free lock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
__dlmconvert_master() only moves the lock between lists, so the count entering the gap is base, list and lookup. Drop the lookup reference after the AST is queued instead of before it and the race ends with the one __dlm_queue_ast() took, which dlm_flush_asts() releases later with ast_pending cleared and ast_list unlinked. No extra get is needed, and the normal case ends with the same count as before.
dlmconvert_master() has the same shape but is only reached from dlmlock() for a lock this node owns, which dlm_free_dead_locks() never matches.
--- fs/ocfs2/dlm/dlmconvert.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ocfs2/dlm/dlmconvert.c +7 -3
@@ -534,15 +534,19 @@ int dlm_convert_lock_handler(struct o2ne } leave: -if (lock) -dlm_lock_put (lock); -/* either queue the ast or release it, if reserved */ if (call_ast)dlm_queue_ast (dlm, lock);else if (ast_reserved)dlm_lockres_release_ast (dlm, res); +/* +* Keep the lock alive through AST enqueue: a concurrent +* dlm_free_dead_locks() drops the list and base references. +*/ +if (lock) +dlm_lock_put (lock); +if (kick_thread)dlm_kick_thread (dlm, res);
Greg Kroah-Hartman
maintainerPATCH 574/2857 ocfs2: cancel quota sync work before freeing quota info
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 1dd1f005026d52642b994d63baa16b0b31f3b14f upstream.
OCFS2 quota info owns dqi_sync_work and must outlive both its timer and qsync_work_fn(). ocfs2_local_free_info() frees that owner without cancelling the work, relying on the quota suspend/disable wrappers.
Loading quotas on a read-only to read-write remount can successfully queue the work in ocfs2_global_read_info() and then fail while attaching a dquot to an existing inode in add_dquot_ref(). The quota core unwinds that failure directly through dquot_disable(), bypassing the OCFS2 wrapper:
Remount task (s_umount write) Timer/workqueue
ocfs2_global_read_info()
schedules dqi_sync_work
add_dquot_ref() returns an error
dquot_disable()
ocfs2_local_free_info()
frees oinfo
delayed-work timer expires qsync_work_fn() reads oinfo
The timer core can then write to the freed embedded timer, or qsync_work_fn() can read oinfo->dqi_gqinode before its s_umount trylock. The outer ocfs2_disable_quotas() cleanup skips the failed type because dquot_disable() has already cleared its loaded state.
Cancel dqi_sync_work synchronously at the start of ocfs2_local_free_info(), before dropping the global inode or freeing any owner state. The work is initialized whenever read_file_info() succeeds. dquot_disable() holds s_umount for write, so the callback skips its quota scan via down_read_trylock() and can finish without waiting for teardown. The synchronous cancel also handles its self-rearm.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __run_timers+0x9e9/0xa10
Write of size 8 at addr ffff888111b0aad0 by task swapper/3/0
Call Trace:
<IRQ>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __run_timers+0x9e9/0xa10
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __run_timers+0x9e9/0xa10
kasan_report+0xe0/0x110
? __run_timers+0x9e9/0xa10
__run_timers+0x9e9/0xa10
? __pfx___run_timers+0x10/0x10
? __lock_acquire+0x5a3/0x2140
? __pfx_do_raw_spin_lock+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
timer_expire_remote+0xfa/0x160
? __pfx_timer_expire_remote+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
tmigr_handle_remote_up+0x4ba/0x9d0
? __pfx_tmigr_handle_remote_up+0x10/0x10
? tmigr_handle_remote+0x21a/0x340
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? __pfx_tmigr_handle_remote_up+0x10/0x10
__walk_groups_from+0x5a/0x160
tmigr_handle_remote+0x24f/0x340
? __pfx_tmigr_handle_remote+0x10/0x10
? lock_acquire+0x190/0x300
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
run_timer_softirq+0x222/0x270
? __pfx_run_timer_softirq+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xb8/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
handle_softirqs+0x1fa/0x8d0
? __pfx_handle_softirqs+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? _raw_spin_unlock+0x23/0x40
? srso_alias_return_thunk+0x5/0xfbef5
? __hrtimer_rearm_deferred+0x1fb/0x5d0
__irq_exit_rcu+0x113/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
</IRQ>
<TASK>
asm_sysvec_apic_timer_interrupt+0x1a/0x20
? ct_kernel_exit.constprop.0+0xc5/0xf0
? do_idle+0x3ae/0x650
default_idle+0x9/0x10
default_idle_call+0x6c/0xb0
do_idle+0x3ae/0x650
? cpuhp_online_idle+0x9c/0xb0
? __pfx_do_idle+0x10/0x10
? __entry_text_end+0x1020f6/0x1020f9
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
cpu_startup_entry+0x54/0x60
start_secondary+0x223/0x2d0
? __pfx_start_secondary+0x10/0x10
common_startup_64+0x13e/0x158
</TASK>
Allocated by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_local_read_info+0x181/0x1580
dquot_load_quota_sb+0x69e/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_local_free_info+0x47b/0x800
dquot_disable+0x5d9/0x17a0
dquot_load_quota_sb+0xd3c/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888111b0a800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 720 bytes inside of
freed 1024-byte region [ffff888111b0a800, ffff888111b0ac00)Host details, register and page dumps omitted.
--- fs/ocfs2/quota_local.c | 3 +++ 1 file changed, 3 insertions(+)
fs/ocfs2/quota_local.c +3 -0
@@ -813,6 +813,9 @@ static int ocfs2_local_free_info(structint mark_clean =1 , len;int status =0 ; +/* Quota-core error paths can bypass ocfs2_disable_quotas(). */ +cancel_delayed_work_sync (&oinfo->dqi_sync_work); +iput (oinfo->dqi_gqinode);ocfs2_simple_drop_lockres (OCFS2_SB (sb), &oinfo->dqi_gqlock);ocfs2_lock_res_free (&oinfo->dqi_gqlock);
Greg Kroah-Hartman
maintainerPATCH 575/2857 ocfs2: fix chunk number of the first chunk in a local quota file
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiaming Zhang <[email protected]>
commit 4effccfd50baee4f325694964aeee997dca7bd96 upstream.
Mounting a crafted OCFS2 image can corrupt kernel memory. When the local quota file header of such an image claims zero chunks, the first quota entry allocated during the mount gets a chunk number taken from a kernel pointer, and releasing that entry clears a bit far outside the chunk bitmap.
The write will corrupt the data stored at that address, and the corruption may lead to a system crash or damage unrelated data. Mounting requires CAP_SYS_ADMIN, so it takes an untrusted image, such as removable media or a loop mount of a file from elsewhere.
Since the chunk number comes from a kernel pointer, the address of the bit that gets cleared differs from boot to boot, and the issue has been reported under several titles:
- BUG: unable to handle kernel paging request in ocfs2_local_release_dquot
- KASAN: use-after-free Write in ocfs2_local_release_dquot
- KASAN: slab-out-of-bounds Write in ocfs2_local_release_dquot
- KASAN: slab-use-after-free Write in ocfs2_local_release_dquot
- KFENCE: use-after-free write in ocfs2_local_release_dquot
Note that none of these is a use-after-free in the quota code: the chunk and its buffer head are alive. The bit that gets cleared lies far outside the bitmap. KASAN and KFENCE name each report based on the object occupying that address, which explains why the same issue is reported under so many different titles. In the report I sent, the address fell in a free page, which KASAN labels use-after-free.
There are known reproducers. Both a syzkaller and a C reproducer are available from the Google Drive link [1] in my report thread. The issue was found by our modified syzkaller, not a theoretical thing found by an LLM. I have not seen it outside fuzzing, so it is not affecting me in the real world.
The local quota file in OCFS2 is divided into chunks, and each chunk begins with a header block holding a bitmap of the quota entries that chunk has handed out. Chunks are numbered from zero, and that number is used to convert the file offset of an entry back into a bit position in the bitmap. ocfs2_local_quota_add_chunk() appends a new chunk to the in-memory list and numbers it one past the chunk that was last:
list_add_tail(&chunk->qc_chunk, &oinfo->dqi_chunk); chunk->qc_num = list_entry(chunk->qc_chunk.prev, struct ocfs2_quota_chunk, qc_chunk)->qc_num + 1;
The predecessor is looked up after the new chunk is added to the list, so if the list was empty, the prev pointer is the list head itself. The head is the dqi_chunk member of struct ocfs2_mem_dqinfo and is not a chunk, so reading qc_num through it lands 16 bytes past the start of the head, on the dqi_gqinode pointer that follows it. The first chunk of the file is then numbered with the lower half of a kernel pointer instead of 0.
The list is empty when the local quota file header claims the file has no chunks. ocfs2_local_read_info() takes dqi_chunks from that header without validating it, so an image with dqi_chunks == 0 takes this path when the first quota entry is allocated.
ocfs2_create_local_dquot() turns the bad number into a file offset with ol_dqblk_off(), which shifts a 32-bit block number left by the block size bits, so the top bits of such a large block number are lost. ocfs2_local_release_dquot() turns the offset back into a bit index with ol_dqblk_chunk_off(), using the full chunk number, so the lost bits push that index far outside the bitmap, and clearing it corrupts unrelated memory.
Compute the chunk number before putting the chunk on the list, and use 0 when the list is empty.
--- fs/ocfs2/quota_local.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/ocfs2/quota_local.c +6 -3
@@ -1071,10 +1071,13 @@ static struct ocfs2_quota_chunk *ocfs2_l goto out; } +if (list_empty (&oinfo->dqi_chunk)) + chunk->qc_num =0 ; +else + chunk->qc_num =list_entry (oinfo->dqi_chunk.prev, + struct ocfs2_quota_chunk, + qc_chunk)->qc_num +1 ;list_add_tail (&chunk->qc_chunk, &oinfo->dqi_chunk); - chunk->qc_num =list_entry (chunk->qc_chunk.prev, - struct ocfs2_quota_chunk, - qc_chunk)->qc_num +1 ; chunk->qc_headerbh = bh; *offset =0 ;return chunk;
Greg Kroah-Hartman
maintainerPATCH 576/2857 ocfs2: pin refcount trees before dropping the lookup lock
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 8c714a074074af7ae59233c1fa6ef9d7aa710462 upstream.
A refcount tree returned to ocfs2_lock_refcount_tree() must stay alive until that caller releases its operation reference. However, ocfs2_get_refcount_tree() returns the cached pointer after dropping osb_lock, and the caller only takes its kref afterwards. The registry reference does not protect this gap from concurrent removal.
This can happen when another node frees a refcount root and reuses its block with a different generation while this mount retains the old cached tree. Two local operations on different inodes sharing the new root, such as data CoW and an external xattr update, can then look up the same stale tree. Their inode locks are independent, and both the REFCOUNT DLM lock and rf_sem are acquired after the first operation reference.
The following ordering is possible, with no other operation references:
Data CoW Xattr update
-------- ------------
Look up the old tree under
osb_lock, then drop osb_lock
Look up the same tree and take a kref Acquire the tree locks and read the
new on-disk generation
Erase the old tree under osb_lock Unlock and drop the operation kref Drop the registry kref, freeing tree
Take a kref through the
freed tree pointer
The final kref_get() accesses freed rf_getcnt storage, and subsequent accesses in ocfs2_lock_refcount_tree() also use the freed allocation.
Take the operation reference in ocfs2_get_refcount_tree() before releasing osb_lock, including when an insertion loses to another lookup. Removal must acquire the same lock, so it cannot drop the registry reference before the lookup has pinned the tree. Keep the existing unlock and error path puts. The two callers that already hold the refcount tree lock keep their borrowed lookup behavior and do not acquire an extra reference.
KASAN report as below:
BUG: KASAN: slab-use-after-free in ocfs2_lock_refcount_tree+0x94a/0x9b0
Read of size 4 at addr ffff888117212820 by task python3/497[Kernel and hardware identification omitted.]
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? ocfs2_lock_refcount_tree+0x94a/0x9b0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? ocfs2_lock_refcount_tree+0x94a/0x9b0
kasan_report+0xe0/0x110
? ocfs2_lock_refcount_tree+0x94a/0x9b0
ocfs2_lock_refcount_tree+0x94a/0x9b0
? __pfx_ocfs2_lock_refcount_tree+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? ocfs2_refcount_cow+0x3b6/0xd90
? srso_alias_return_thunk+0x5/0xfbef5
? __kmalloc_cache_noprof+0x28d/0x610
? ocfs2_refcount_cow+0x3b6/0xd90
ocfs2_refcount_cow+0x410/0xd90
? __pfx_ocfs2_refcount_cow+0x10/0x10
? __pfx___might_resched+0x10/0x10
? down_write+0x11a/0x1f0
? __pfx_down_write+0x10/0x10
? ocfs2_inode_unlock+0x1a9/0x260
? __pfx_ocfs2_inode_unlock+0x10/0x10
? ocfs2_file_write_iter+0x1413/0x1d30
ocfs2_file_write_iter+0x157b/0x1d30
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_acquire+0x190/0x300
? __x64_sys_pwrite64+0x1b7/0x220
? __pfx___might_resched+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? security_file_permission+0x26/0x80
? srso_alias_return_thunk+0x5/0xfbef5
? lock_is_held_type+0x8f/0x100
vfs_write+0x639/0x1010
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_vma_under_rcu+0x154/0x4a0
? __pfx_vfs_write+0x10/0x10
? lock_release+0x121/0x290
? srso_alias_return_thunk+0x5/0xfbef5
__x64_sys_pwrite64+0x1b7/0x220
? __pfx___x64_sys_pwrite64+0x10/0x10
? irqentry_exit+0xbe/0x820
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on_prepare+0x11d/0x150
? srso_alias_return_thunk+0x5/0xfbef5
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f[Register dump omitted.]
</TASK>
Allocated by task 491:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_allocate_refcount_tree+0x49/0x1a0
ocfs2_create_refcount_tree+0x5d7/0x1630
ocfs2_attach_refcount_tree+0x57d/0x1100
__ocfs2_reflink.isra.0+0x1c4/0x1940
ocfs2_reflink+0x501/0x9b0
ocfs2_reflink_ioctl+0x6b2/0x920
ocfs2_ioctl+0x538/0x640
__x64_sys_ioctl+0x163/0x1d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 498:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_lock_refcount_tree+0x672/0x9b0
ocfs2_xattr_set+0x72c/0x2530
ocfs2_xattr_user_set+0xaf/0xf0
__vfs_setxattr+0x143/0x1b0
__vfs_setxattr_noperm+0x112/0x5b0
__vfs_setxattr_locked+0xfe/0x2b0
vfs_setxattr+0x13c/0x370
do_setxattr+0x128/0x170
filename_setxattr+0x147/0x190
path_setxattrat+0x1ac/0x260
__x64_sys_setxattr+0xcb/0x140
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888117212800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 32 bytes inside of
freed 1024-byte region [ffff888117212800, ffff888117212c00)[Page and memory dumps omitted.]
--- fs/ocfs2/refcounttree.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-)
fs/ocfs2/refcounttree.c +9 -6
@@ -348,8 +348,10 @@ ocfs2_allocate_refcount_tree(struct ocfsreturn new; } +/* Callers without the refcount tree lock must request a reference. */ static int ocfs2_get_refcount_tree (struct ocfs2_super *osb,u64 rf_blkno, -struct ocfs2_refcount_tree **ret_tree) +struct ocfs2_refcount_tree **ret_tree, +bool get_ref) {int ret =0 ;struct ocfs2_refcount_tree *tree, *new =NULL ;
@@ -406,6 +408,8 @@ static int ocfs2_get_refcount_tree(struc new =NULL ; out: +if (get_ref) +ocfs2_refcount_tree_get (tree); *ret_tree = tree; osb->osb_ref_tree_lru = tree;
@@ -479,14 +483,12 @@ int ocfs2_lock_refcount_tree(struct ocfsstruct ocfs2_refcount_block *rb; again: - ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree, true);if (ret) {mlog_errno (ret);return ret; } -ocfs2_refcount_tree_get (tree); - ret =__ocfs2_lock_refcount_tree (osb, tree, rw);if (ret) {mlog_errno (ret);
@@ -2330,7 +2332,8 @@ int ocfs2_decrease_refcount(struct inode goto out; } - ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, + &tree, false);if (ret) {mlog_errno (ret); goto out;
@@ -2565,7 +2568,7 @@ int ocfs2_prepare_refcount_change_for_deBUG_ON (!ocfs2_is_refcount_inode (inode)); ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), - refcount_loc, &tree); + refcount_loc, &tree, false);if (ret) {mlog_errno (ret); goto out;
Greg Kroah-Hartman
maintainerPATCH 577/2857 ovl: do not copy up an xattr value that was never read
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 755b5c5c9277be251a51623d6065abab948c61bc upstream.
Copy-up stores uninitialized kernel memory in an xattr of the upper file, where the user can read it.
ovl_copy_xattr() may only pass bytes to ovl_do_setxattr() that ovl_do_getxattr() has read. When the read fails with -ERANGE the function asks for the size again, and if the new size fits the buffer it stores the buffer although nothing was read into it. The buffer comes from kvmalloc(), or it still holds the value of the previous xattr.
A FUSE lower layer that answers every sized GETXATTR with -ERANGE made copy-up store 4096 bytes that the server never sent, with a kernel pointer in them, as an xattr of the upper file.
Fix this by failing the copy-up with -EIO when the size that follows -ERANGE fits the buffer.
--- fs/overlayfs/copy_up.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/overlayfs/copy_up.c +5 -1
@@ -95,8 +95,12 @@ int ovl_copy_xattr(struct super_block *s } retry: size =ovl_do_getxattr (oldpath, name, value, value_size); -if (size == -ERANGE ) +if (size == -ERANGE ) { size =ovl_do_getxattr (oldpath, name,NULL ,0 ); +/* Nothing was read into value, so it must not be used */ +if (size >=0 && size <= value_size) + size = -EIO ; + }if (size <0 ) { error = size;
Greg Kroah-Hartman
maintainerPATCH 578/2857 ovl: fix a torn path in ovl_get_redirect()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 2001cd7ca5560198131e46c6ca3c3472b06145c2 upstream.
A hard link of a metacopy file that races with a rename of an ancestor stores a redirect to the wrong lower file.
Each component of an absolute redirect must be the name that a dentry has in the parent that the walk continues with. ovl_get_redirect() copies the name under d_lock and calls dget_parent() after the unlock, and the callers for a hard link hold no lock that stops a rename across directories. A rename between the two steps combines the old name with the new parent.
With delays in ovl_get_redirect(), an unprivileged user hard-linked a metacopy file while renaming its ancestor to another directory, the stored redirect named another lower path, and after a remount the file showed the data of a root-only file.
Fix this by taking the parent first and checking it again under d_lock.
--- fs/overlayfs/dir.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +13 -1
@@ -991,7 +991,19 @@ static char *ovl_get_redirect(struct denconst char *name;int thislen; +/* +* A rename can move d to another directory at any time. Hold +* d_lock to copy the name that d has in this very parent, or +* else the path mixes the old name with the new parent. +*/ + tmp =dget_parent (d);spin_lock (&d->d_lock); +if (unlikely (tmp != d->d_parent)) { +spin_unlock (&d->d_lock); +dput (tmp); +continue ; + } + name =ovl_dentry_get_redirect (d);if (name) { thislen =strlen (name);
@@ -1004,13 +1016,13 @@ static char *ovl_get_redirect(struct denif (thislen + (name[0 ] !='/' ) > buflen) { ret =ERR_PTR (-EXDEV );spin_unlock (&d->d_lock); +dput (tmp); goto out_put; } buflen -= thislen;memcpy (&buf[buflen], name, thislen);spin_unlock (&d->d_lock); - tmp =dget_parent (d);dput (d); d = tmp;
Greg Kroah-Hartman
maintainerPATCH 579/2857 ovl: read the nlink xattr of every indexed non-dir
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit eb644ed5c6d9afdb1554c41cef1f39d150fbc554 upstream.
With nfs_export=on, data written through a file handle to a lower file, i.e. a file that exists only in a lower layer of the overlay, can be lost on the next mount. A lookup of the file by name then returns -EIO. Also, a file with one name reports st_nlink 2 once it has been copied to the upper layer. After such a file is removed, its file handle can still open it until the next mount.
Before a lower file is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.
The index directory is $workdir/index, where $workdir is the directory given by the workdir= option. Each entry is named after the file handle of a lower inode, so that overlayfs can get from the handle to the copied up inode.
With nfs_export=on, copy up indexes every non-directory: it copies the file to an entry in the index directory and then hard links that entry into the upper directory. The index entry is an extra link to the upper inode, so overlayfs stores the link count that users should see in the overlay.nlink xattr.
A file can also be opened by handle, either by an NFS client or by a process with CAP_DAC_READ_SEARCH calling open_by_handle_at(). If the file is not in the dcache, its overlay dentry is disconnected, i.e. it has no parent yet. Copy up then creates the index entry but no hard link in the upper directory. The index entry has i_nlink 1 and holds the only copy of the data written to the file.
ovl_get_nlink() reads the stored count. Its caller passes a default, which the function returns if there is no stored count. If the lower inode has i_nlink 1, the function returns the default without reading the xattr. That was correct as long as only lower files with multiple links were indexed.
On the next mount, ovl_verify_index() looks for orphans, i.e. index entries of files whose last name was removed. For an index entry with i_nlink 1, it passes a default of 0 to ovl_get_nlink() and treats a result of 0 as an orphan. Here the lower inode also has i_nlink 1, so the result is the default. ovl_indexdir_cleanup() then replaces the entry with a whiteout, which in the index marks a file as deleted. The written data is lost.
A lookup by name then returns -EIO, because a whiteout as the index entry of a lower file that still exists is a bad index.
ovl_get_inode() gets the wrong count the same way. Its default is the i_nlink of the upper inode, which includes the index entry, so a copied up file with one name reports st_nlink 2.
When that name is removed, the count drops to 1 rather than 0. ovl_nlink_end() replaces the index entry with a whiteout only at a count of 0, so the entry stays, and the handle of the removed file still opens it.
Reproduced by writing through open_by_handle_at() to an uncached lower file with one link. After a remount the data was lost, and the name returned EIO.
Fix this by adding an argument to ovl_get_nlink() that says whether the caller found an index entry, and by skipping the xattr only if the caller found none.
Known gaps:
- An index entry that a kernel without this patch left behind for a removed file now stays, and the handle of that file keeps working. The entry has i_nlink 1 and a stored count of 1, just like the entry of a file that was only written by handle. Without this patch, the next mount treated it as an orphan.
--- fs/overlayfs/inode.c | 14 +++++++++++--- fs/overlayfs/namei.c | 2 +- fs/overlayfs/overlayfs.h | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-)
fs/overlayfs/inode.c +11 -3
@@ -976,7 +976,7 @@ int ovl_set_nlink_lower(struct dentry *d }unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback) {int nlink_diff;
@@ -984,7 +984,15 @@ unsigned int ovl_get_nlink(struct ovl_fschar buf[13 ];int err; -if (!lowerdentry || !upperdentry ||d_inode (lowerdentry)->i_nlink ==1 ) +if (!lowerdentry || !upperdentry) +return fallback; + +/* +* A lower inode with one link is not indexed on copy up, unless all +* files are indexed for NFS export. If the caller found an index entry, +* then the xattr holds the union nlink, whatever the lower nlink is. +*/ +if (!indexed &&d_inode (lowerdentry)->i_nlink ==1 )return fallback; err = ovl_getxattr_upper(ofs, upperdentry, OVL_XATTR_NLINK,
@@ -1239,7 +1247,7 @@ struct inode *ovl_get_inode(struct super/* Recalculate nlink for non-dir due to indexing */ if (!is_dir) nlink =ovl_get_nlink (ofs, lowerdentry, upperdentry, - nlink); + oip->index, nlink);set_nlink (inode, nlink); ino = key->i_ino; }else {
fs/overlayfs/namei.c +1 -1
@@ -599,7 +599,7 @@ int ovl_verify_index(struct ovl_fs *ofs,if (err) goto fail; -if (ovl_get_nlink (ofs, origin.dentry, index,0 ) ==0 ) +if (ovl_get_nlink (ofs, origin.dentry, index, true,0 ) ==0 ) goto orphan; }
fs/overlayfs/overlayfs.h +1 -1
@@ -581,7 +581,7 @@ static inline bool ovl_dir_is_real(strucint ovl_set_nlink_upper (struct dentry *dentry);int ovl_set_nlink_lower (struct dentry *dentry);unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback);int ovl_setattr (struct user_namespace *mnt_userns,struct dentry *dentry,struct iattr *attr);
Greg Kroah-Hartman
maintainerPATCH 580/2857 xfs: check fork type against dabtree block magic number
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 43030b72a11a532e7e3c21ac84a8625425b4201b upstream.
LOLLM complains that we fail to flag dabtree blocks that should never be associated with the file fork -- data forks can't point to xattr leaves, and attr forks can't point to dirent blocks. Add the missing checks.
--- fs/xfs/scrub/dabtree.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/dabtree.c +12 -0
@@ -392,6 +392,10 @@ xchk_da_btree_block( XFS_BLFT_ATTR_LEAF_BUF); blk->magic =XFS_ATTR_LEAF_MAGIC ; blk->hashval =xfs_attr_leaf_lasthash (blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_ATTR_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -401,6 +405,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAFN_BUF); blk->magic =XFS_DIR2_LEAFN_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -410,6 +418,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAF1_BUF); blk->magic =XFS_DIR2_LEAF1_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
Greg Kroah-Hartman
maintainerPATCH 581/2857 xfs: mark overfull dabtree node blocks as corrupt
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f61c91a2e5994fa81141d6c06dadae1fed206018 upstream.
LOLLM observes that we need to range-check the dabtree node record count before using it to index an array. Fix that.
--- fs/xfs/scrub/dabtree.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/xfs/scrub/dabtree.c +4 -0
@@ -433,6 +433,10 @@ xchk_da_btree_block( node = blk->bp->b_addr;xfs_da3_node_hdr_from_disk (ip->i_mount, &nodehdr, node); btree = nodehdr.btree; +if (nodehdr.count > dargs->geo->node_ents) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + } *pmaxrecs = nodehdr.count; blk->hashval =be32_to_cpu (btree[*pmaxrecs -1 ].hashval);if (level ==0 ) {
Greg Kroah-Hartman
maintainerPATCH 582/2857 xfs: jump out of xchk_bmap_check_rmap if fatal signals
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 49d300a51442bd64b627645b7b0b1cd66e492905 upstream.
LOLLM observes that we never check for fatal signals inside the loop that checks file fork mappings against the rmapbt. This can lead to lengthy delays in responding to a ^C, so add some bailout checks.
--- fs/xfs/scrub/bmap.c | 7 +++++++ 1 file changed, 7 insertions(+)
fs/xfs/scrub/bmap.c +7 -0
@@ -467,6 +467,10 @@ xchk_bmap_check_rmap(struct xfs_ifork *ifp;struct xfs_scrub *sc = sbcri->sc;bool have_map; +int error =0 ; + +if (xchk_should_terminate (sc, &error)) +return error;/* Is this even the right fork? */ if (rec->rm_owner != sc->ip->i_ino)
@@ -498,6 +502,9 @@ xchk_bmap_check_rmap(*/ check_rec = *rec;while (have_map) { +if (xchk_should_terminate (sc, &error)) +return error; +if (irec.br_startoff != check_rec.rm_offset)xchk_fblock_set_corrupt (sc, sbcri->whichfork, check_rec.rm_offset);
Greg Kroah-Hartman
maintainerPATCH 583/2857 ksmbd: serialize directory emptiness checks with readdir
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yongjun Gwon <[email protected]>
[ Upstream commit 7220980b2423d06a0604516129bfa4cec8a697ae ]
SMB2 QUERY_DIRECTORY holds fp->readdir_lock while it calls iterate_dir() on fp->filp. An SMB2 SET_INFO request with FILE_DISPOSITION_INFORMATION can resolve the same FileId and call ksmbd_vfs_empty_dir() on the same filp without that lock.
iterate_dir()'s inode read lock permits concurrent readers and does not serialize per-file iterator state. ext4 stores its dx readdir cursor and fname RB tree in file->private_data. Concurrent reset or refill can therefore free a fname node while the other worker still traverses it or retains its RB-tree link, resulting in use-after-free accesses.
An authenticated SMB client with list and delete rights on a directory in a writable KSMBD share backed by ext4 can trigger this when the directory takes the dx readdir path. The client overlaps an SMB2 QUERY_DIRECTORY request with an SMB2 SET_INFO request carrying FILE_DISPOSITION_INFORMATION on one live FileId.
In one x86_64 SMP KASAN multi-shot guest using ksmbd-for-next at 171df27077fb, the unmodified kernel reported a cross-worker use-after-free before a panic. The first report's access and free stacks show the two request paths directly (trimmed):
BUG: KASAN: slab-use-after-free in ext4_htree_store_dirent+0x488/0x550 Read of size 8 by task kworker/2:0/29 Workqueue: ksmbd-io handle_ksmbd_work Call Trace: ext4_htree_store_dirent+0x488/0x550 htree_dirblock_to_tree+0x535/0x990 ext4_htree_fill_tree+0x319/0xba0 ext4_readdir+0x175a/0x2f40 iterate_dir+0x1b6/0x630 smb2_query_dir+0x1003/0x1cc0 Freed by task 279: free_rb_tree_fname+0x67/0xc0 ext4_readdir+0x13a9/0x2f40 iterate_dir+0x1b6/0x630 ksmbd_vfs_empty_dir+0xa2/0x100 smb2_set_info+0x2ffa/0x45d0
Take fp->readdir_lock across the entire emptiness check. This places both iterators over that handle's filp in the same lock domain while preserving the disposition status handling. The exact code change completed a warning-free x86_64 KASAN bzImage build. Tracing three request pairs showed that the two iterate_dir() calls no longer overlapped and the expected statuses were preserved. A further 1,600 reproducer iterations completed with expected statuses and no KASAN report, Oops, or panic.
The reproducer and complete guest configuration are available privately to maintainers on request.
--- fs/smb/server/smb2pdu.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-)
fs/smb/server/smb2pdu.c +8 -3
@@ -6085,6 +6085,7 @@ static int set_file_disposition_info(struct ksmbd_work *work, struct smb2_file_disposition_info *file_info) {struct inode *inode; +int err;if (!(fp->daccess &FILE_DELETE_LE )) {pr_err ("no right to delete : 0x%x\n" , fp->daccess);
@@ -6093,9 +6094,13 @@ static int set_file_disposition_info(struct ksmbd_work *work, inode =file_inode (fp->filp);if (file_info->DeletePending) { -if (S_ISDIR (inode->i_mode) && -ksmbd_vfs_empty_dir (fp) == -ENOTEMPTY ) -return -EBUSY ; +if (S_ISDIR (inode->i_mode)) { +mutex_lock (&fp->readdir_lock); + err =ksmbd_vfs_empty_dir (fp); +mutex_unlock (&fp->readdir_lock); +if (err == -ENOTEMPTY ) +return -EBUSY ; + }smb_break_all_levII_oplock (work, fp,0 );ksmbd_set_inode_pending_delete (fp); }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 584/2857 EDAC/mc: Really fix error path ordering in edac_mc_alloc()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jean Delvare <[email protected]>
The backport of 51520e03e70d ("EDAC/mc: Fix error path ordering in edac_mc_alloc()") to stable kernel branches is incomplete due to a different memory allocation scheme. In v6.19 and earlier, the device initialization must be moved further up so that all jumps to the error label are covered.
--- drivers/edac/edac_mc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/edac/edac_mc.c +3 -3
@@ -365,13 +365,13 @@ struct mem_ctl_info *edac_mc_alloc(unsigned int mc_num,if (!mci)return NULL ; + mci->dev.release = mci_release; +device_initialize (&mci->dev); + mci->layers =kcalloc (n_layers,sizeof (struct edac_mc_layer ),GFP_KERNEL );if (!mci->layers) goto error; - mci->dev.release = mci_release; -device_initialize (&mci->dev); - mci->pvt_info =kzalloc (sz_pvt,GFP_KERNEL );if (!mci->pvt_info) goto error;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 585/2857 ufs: fix ufs_read_cylinder() failure handling
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Al Viro <[email protected]>
commit 0bfd3e1078c537cd66a8addb1c01835de4234a4c upstream.
1) ufs_load_cylinder() should return NULL on ufs_read_cylinder() failures. ufs_error() is not enough. As it is, IO failure on attempt to read a part of cylinder group metadata is likely to end up with an oops.
2) we drop the wrong buffer heads when undoing sb_bread() on IO failure halfway through the read - we need to brelse() what we've got from sb_bread(), TYVM...
--- fs/ufs/cylinder.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-)
fs/ufs/cylinder.c +18 -13
@@ -26,7 +26,7 @@* Read cylinder group into cache. The memory space for ufs_cg_private_info * structure is already allocated during ufs_read_super. */ -static void ufs_read_cylinder (struct super_block * sb, +static bool ufs_read_cylinder (struct super_block *sb,unsigned cgno,unsigned bitmap_nr) {struct ufs_sb_info * sbi =UFS_SB (sb);
@@ -46,9 +46,11 @@ static void ufs_read_cylinder (struct super_block * sb,* We have already the first fragment of cylinder group block in buffer */ UCPI_UBH (ucpi)->bh[0 ] = sbi->s_ucg[cgno]; -for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) -if (!(UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i))) +for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) { +UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i); +if (!UCPI_UBH (ucpi)->bh[i]) goto failed; + } sbi->s_cgno[bitmap_nr] = cgno; ucpi->c_cgx =fs32_to_cpu (sb, ucg->cg_cgx);
@@ -77,13 +79,14 @@ static void ufs_read_cylinder (struct super_block * sb, goto failed; }UFSD ("EXIT\n" ); -return ; +return true; failed:for (j =1 ; j < i; j++) -brelse (sbi->s_ucg[j]); +brelse (UCPI_UBH (ucpi)->bh[j]); sbi->s_cgno[bitmap_nr] =UFS_CGNO_EMPTY ;ufs_error (sb,"ufs_read_cylinder" ,"can't read cylinder group block %u" , cgno); +return false; }/*
@@ -166,15 +169,14 @@ struct ufs_cg_private_info * ufs_load_cylinder (UFSD ("EXIT (FAILED)\n" );return NULL ; } -else { -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; - } }else { -ufs_read_cylinder (sb, cgno, cgno); -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; +if (unlikely (!ufs_read_cylinder (sb, cgno, cgno))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } } +UFSD ("EXIT\n" ); +return sbi->s_ucpi[cgno]; }/* * Cylinder group number cg is in cache but it was not last used,
@@ -205,7 +207,10 @@ struct ufs_cg_private_info * ufs_load_cylinder ( sbi->s_ucpi[j] = sbi->s_ucpi[j-1 ]; } sbi->s_ucpi[0 ] = ucpi; -ufs_read_cylinder (sb, cgno,0 ); +if (unlikely (!ufs_read_cylinder (sb, cgno,0 ))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } }UFSD ("EXIT\n" );return sbi->s_ucpi[0 ];
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 586/2857 media: usbtv: drop redundant device reference
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
[ Upstream commit dbc6798b80481a20f9aff671bc4d529eae63c9e8 ]
Driver core holds a reference to the USB interface and its parent USB device while the interface is bound to a driver and there is no need to take additional references unless the structures are needed after disconnect.
Drop the redundant device reference to reduce cargo culting, make it easier to spot drivers where an extra reference is needed, and reduce the risk of memory leaks when drivers fail to release it.
Stable-dep-of: cb705f75d03e ("media: usbtv: fix null-pointer dereference on disconnect")
--- drivers/media/usb/usbtv/usbtv-core.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +1 -3
@@ -91,7 +91,7 @@ static int usbtv_probe(struct usb_interface *intf,if (usbtv ==NULL )return -ENOMEM ; usbtv->dev = dev; - usbtv->udev =usb_get_dev (interface_to_usbdev (intf)); + usbtv->udev =interface_to_usbdev (intf); usbtv->iso_size = size;
@@ -119,7 +119,6 @@ static int usbtv_probe(struct usb_interface *intf, usbtv_video_fail:usb_set_intfdata (intf,NULL ); -usb_put_dev (usbtv->udev);kfree (usbtv);return ret;
@@ -137,7 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); -usb_put_dev (usbtv->udev); usbtv->udev =NULL ;/* the usbtv structure will be deallocated when v4l2 will be
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 587/2857 media: usbtv: fix null-pointer dereference on disconnect
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aleksandr Nogikh <[email protected]>
[ Upstream commit cb705f75d03e946a4514488beb9e3bac9bcdb2e6 ]
A null-pointer dereference can occur in usb_make_path() when called from usbtv_querycap() (and other ioctl handlers) during device disconnection.
Oops: general protection fault, probably for non-canonical address 0xdffffc000000000a: 0000 [#1] SMP KASAN NOPTI KASAN: null-ptr-deref in range [0x0000000000000050-0x0000000000000057] RIP: 0010:usb_make_path include/linux/usb.h:985 [inline] RIP: 0010:usbtv_querycap+0x9c/0x100 drivers/media/usb/usbtv/usbtv-video.c:612 ... Call Trace: <TASK> v4l_querycap+0x236/0x470 drivers/media/v4l2-core/v4l2-ioctl.c:1106 __video_do_ioctl+0x8af/0xc70 drivers/media/v4l2-core/v4l2-ioctl.c:3133 video_usercopy+0x860/0x1430 drivers/media/v4l2-core/v4l2-ioctl.c:3475 v4l2_ioctl+0x18d/0x1e0 drivers/media/v4l2-core/v4l2-dev.c:366 vfs_ioctl fs/ioctl.c:51 [inline] __do_sys_ioctl fs/ioctl.c:597 [inline] __se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline] do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94
This happens due to a race condition between the USB device disconnect routine (usbtv_disconnect()) and V4L2 ioctls. When the device is disconnected, usbtv_disconnect() sets usbtv->udev = NULL without holding the usbtv->v4l2_lock mutex. Concurrently, an ioctl handler like usbtv_querycap() can be executing under the v4l2_lock and attempt to use usbtv->udev, leading to a crash.
To fix this, move the usbtv->udev = NULL assignment into usbtv_video_free() and protect it with mutex_lock(&usbtv->v4l2_lock). This ensures that no non-queue ioctl handler can run concurrently with the pointer being nullified. If an ioctl is already running, the mutex will block the disconnect path until the ioctl finishes. If an ioctl is blocked waiting for the lock, it will acquire it after the disconnect routine releases it, but will then check video_is_registered() (which was cleared by vb2_video_unregister_device()) and safely return -ENODEV.
Acquiring v4l2_lock after vb2_video_unregister_device() avoids reintroducing a historical deadlock issue, and usbtv_audio_free() remains safe as it is called before usbtv_video_free().
--- drivers/media/usb/usbtv/usbtv-core.c | 2 -- drivers/media/usb/usbtv/usbtv-video.c | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +0 -2
@@ -136,8 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); - usbtv->udev =NULL ; -/* the usbtv structure will be deallocated when v4l2 will be done using it */ v4l2_device_put (&usbtv->v4l2_dev);
drivers/media/usb/usbtv/usbtv-video.c +4 -0
@@ -969,5 +969,9 @@ void usbtv_video_free(struct usbtv *usbtv)vb2_video_unregister_device (&usbtv->vdev);v4l2_device_disconnect (&usbtv->v4l2_dev); +mutex_lock (&usbtv->v4l2_lock); + usbtv->udev =NULL ; +mutex_unlock (&usbtv->v4l2_lock); +v4l2_device_put (&usbtv->v4l2_dev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 588/2857 xfs: reject out-of-range attribute value lengths in xfs_attr_copy_value
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 0643549ffecaeb716c0b75590a9b76dfa5eb35b3 upstream.
xfs_attr_copy_value() takes the value length as a signed int and, for a remote xattr, is handed args->rmtvaluelen. That field is filled from the on-disk __be32 xfs_attr_leaf_name_remote.valuelen in xfs_attr3_leaf_getvalue(), so a crafted length such as 0x80000000 is stored into the signed rmtvaluelen as a negative number.
The "buffer too small" guard in xfs_attr_copy_value() is a signed comparison:
if (args->valuelen < valuelen) return -ERANGE;
A negative valuelen therefore compares as smaller than the caller's buffer size, skips the -ERANGE path, and is then used as a copy length, leading to an out-of-bounds copy of a full remote block into a small getxattr(2) buffer on a mounted crafted image.
Reject a value length that is negative or larger than the maximum xattr size before it is used, so a bogus on-disk length can no longer slip through the value copier.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +11 -0
@@ -517,6 +517,17 @@ xfs_attr_copy_value( int valuelen) {/* +* A value length that is negative or larger than the maximum xattr +* size is on-disk corruption. The remote value length is an on-disk +* __be32 stored into the signed args->rmtvaluelen, so a crafted value +* such as 0x80000000 becomes negative and would slip past the +* "args->valuelen < valuelen" check below and be used as a copy +* length. Reject it before that can happen. +*/ +if (valuelen <0 || valuelen >XFS_XATTR_SIZE_MAX ) +return -EFSCORRUPTED ; + +/* * No copy if all we have to do is get the length */ if (!args->valuelen) {
Greg Kroah-Hartman
maintainerPATCH 589/2857 xfs: reject remote xattr entries with an out-of-range value length
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 15ccd92a782a0253f4a17895f3d3f71e5c1d1973 upstream.
xfs_attr3_leaf_verify_entry() validates a remote attribute entry's name but never bounds its on-disk value length (xfs_attr_leaf_name_remote. valuelen, a __be32). A crafted leaf with valuelen = 0x80000000 passes the verifier and the CRC.
That length is later assigned into the signed int args->rmtvaluelen (xfs_attr3_leaf_getvalue), becoming negative, which slips past the signed -ERANGE check in xfs_attr_copy_value(); a getxattr() with a small buffer then memcpy()s a full remote block into the small kvalue buffer (xfs_attr_rmtval_copyout) -- a heap out-of-bounds write with attacker-controlled content, from an unprivileged getxattr(2) on a mounted crafted image.
Reject remote entries whose value length exceeds XFS_XATTR_SIZE_MAX in the leaf verifier, so the malicious block is rejected at read time.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +2 -0
@@ -295,6 +295,8 @@ xfs_attr3_leaf_verify_entry(if (!(ent->flags &XFS_ATTR_INCOMPLETE ) && rentry->valueblk ==0 )return __this_address; +if (be32_to_cpu (rentry->valuelen) >XFS_XATTR_SIZE_MAX ) +return __this_address; }if (name_end > buf_end)
Greg Kroah-Hartman
maintainerPATCH 590/2857 xfs: bound inode fork length against the fork size during log recovery
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 9232301894a06e664d8de2da97175cf98419bd16 upstream.
xlog_recover_inode_commit_pass2() copies an inode log item's data/attr fork region into the inode buffer using the on-log region length without bounding it against the fork capacity, e.g.:
len = item->ri_buf[2].iov_len; memcpy(XFS_DFORK_DPTR(dip), src, len);
The only guard is an ASSERT, which is a no-op on production kernels (CONFIG_XFS_DEBUG off), and xfs_dinode_verify() runs only after the copy. A crafted image with a dirty log can therefore drive a heap out-of-bounds write at mount time. The XFS_ILOG_DBROOT sibling already passes XFS_DFORK_DSIZE as a bound; the DDATA/DEXT and ADATA/AEXT memcpy paths did not.
Bound each logged fork region against the destination fork size before copying it, and reject the log item with -EFSCORRUPTED when it does not fit. Because the recovered inode is only verified after the fork data has been copied in, the checks are done up front, before any memcpy into the on-disk inode.
--- fs/xfs/xfs_inode_item_recover.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
fs/xfs/xfs_inode_item_recover.c +19 -1
@@ -467,6 +467,25 @@ xlog_recover_inode_commit_pass2(ASSERT (!(fields &XFS_ILOG_DFORK ) || (len ==xlog_calc_iovec_len (in_f->ilf_dsize))); +/* +* The recovered inode is verified only after the fork data has been +* copied into it, so bound each logged fork region against the size of +* its fork now, before the memcpy below can overrun the on-disk inode. +* The DBROOT/ABROOT cases already bound their copies against the fork +* size. +*/ +if ((fields & (XFS_ILOG_DDATA |XFS_ILOG_DEXT )) && + item->ri_buf[2 ].iov_len >XFS_DFORK_DSIZE (dip, mp)) { + error = -EFSCORRUPTED ; + goto out_release; + } +if ((fields & (XFS_ILOG_ADATA |XFS_ILOG_AEXT )) && + item->ri_buf[(fields &XFS_ILOG_DFORK ) ?3 :2 ].iov_len > +XFS_DFORK_ASIZE (dip, mp)) { + error = -EFSCORRUPTED ; + goto out_release; + } +switch (fields &XFS_ILOG_DFORK ) {case XFS_ILOG_DDATA :case XFS_ILOG_DEXT :
@@ -506,7 +525,6 @@ xlog_recover_inode_commit_pass2(case XFS_ILOG_ADATA :case XFS_ILOG_AEXT : dest =XFS_DFORK_APTR (dip); -ASSERT (len <=XFS_DFORK_ASIZE (dip, mp));memcpy (dest, src, len);break ;
Greg Kroah-Hartman
maintainerPATCH 591/2857 xfs: check for fragments when full-extent sharing matches
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 95e213c1ddb40dfb0a8178ed35c9f29992a320e1 upstream.
LOLLM noticed that xchk_refcountbt_process_rmap_fragments returns early if there are enough rmap records that overlap the space referenced by a refcountbt record to match the refcount in that refcountbt record. Unfortunately, it never checks the fragment list in this case, so it won't find the discrepancy between the rmap and refcount btrees.
--- fs/xfs/scrub/refcount.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/refcount.c +4 -1
@@ -159,8 +159,11 @@ xchk_refcountbt_process_rmap_fragments(xfs_nlink_t target_nr; target_nr = refchk->refcount - refchk->seen; -if (target_nr ==0 ) +if (target_nr ==0 ) { +if (!list_empty (&refchk->fragments)) + refchk->seen =0 ;return ; + }/* * There are (refchk->rc.rc_refcount - refchk->nr refcount)
Greg Kroah-Hartman
maintainerPATCH 592/2857 xfs: only written file data blocks can be shared
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 634b63baf05062988456a0bd5df2696c14ea2949 upstream.
LOLLM noticed that xchk_refcountbt_rmap_check (and its rt equivalent) will count any rmap owner towards the shared count. However, the only blocks that can be shared between xfs files are written file data blocks; and the only blocks that can have single-refcount entries are COW staging extents. Fix the checking code.
--- fs/xfs/scrub/refcount.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/refcount.c +12 -0
@@ -114,6 +114,18 @@ xchk_refcountbt_rmap_check(return 0 ; } +/* +* The refcount btree should only have records for written file data +* blocks or for COW staging blocks. +*/ +if ((XFS_RMAP_NON_INODE_OWNER (rec->rm_owner) && + rec->rm_owner !=XFS_RMAP_OWN_COW ) || + (rec->rm_flags & (XFS_RMAP_ATTR_FORK |XFS_RMAP_BMBT_BLOCK | +XFS_RMAP_UNWRITTEN ))) { +xchk_btree_xref_set_corrupt (refchk->sc, cur,0 ); +return 0 ; + } +if (rec->rm_startblock <= refchk->bno && rm_last >= rc_last) {/* * The rmap overlaps the refcount record, so we can confirm
Greg Kroah-Hartman
maintainerPATCH 593/2857 xfs: opportunistically skip btree block checks
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4ce244b234c251963fca6dff9de6edf26a209d08 upstream.
LOLLM notices that both callers of xchk_btree_get_block will return early if *pblock is NULL after a successful return. However, xchk_btree_get_block itself can return 0 after flagging a corruption. There's no point in continuing after we've found a corruption, so null the pointer out.
--- fs/xfs/scrub/btree.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/xfs/scrub/btree.c +8 -0
@@ -550,6 +550,14 @@ xchk_btree_get_block( level, *pbp);if (failed_at) {xchk_btree_set_corrupt (bs->sc, bs->cur, level); +/* +* The btree block fails basic checks, so we know it's corrupt. +* There's no need to continue looking for corruptions, so we +* null out pblock. If *pbp is non-null then it's also +* attached to the transaction so we won't leak it despite the +* 0 return code. +*/ + *pblock =NULL ;return 0 ; }if (*pbp)
Greg Kroah-Hartman
maintainerPATCH 594/2857 xfs: propagate errors while checking null siblings
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit e5bde75a816b3549942f4b09a8bf09006b7ea9de upstream.
LOLLM observes that if xfs_da3_path_shift returns an error here, scrub doesn't handle it the way that it handles most runtime errors. Instead, it drops the error and keeps going, even though that's not how that's supposed to work. Fix that by calling xchk_da_process_error to set corruption flags and then jump out of the flow of execution.
--- fs/xfs/scrub/dabtree.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/xfs/scrub/dabtree.c +3 -2
@@ -236,9 +236,10 @@ xchk_da_btree_block_check_sibling(if (sibling ==0 ) { error =xfs_da3_path_shift (ds->state, altpath, direction, false, &retval); -if (error ==0 && retval ==0 ) +if (!xchk_da_process_error (ds, level, &error)) + goto out; +if (retval ==0 )xchk_da_set_corrupt (ds, level); - error =0 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 595/2857 xfs: range-check bc_levels array access in scrub tracepoints
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 73b7276b8a4b5eb272f3c3b36ea3042e786f4741 upstream.
LOLLM noticed xchk_btree()'s odd habit of passing cur->bc_nlevels to xchk_btree_ptr_ok when we're checking the pointer to the root block at the start of the btree scan. This enables us to skip checking the pointer for an inode btree's root (since it doesn't have one) but doesn't handle per-AG btrees quite correctly. There isn't a problem for __xfs_btree_check_ptr itself, but the corruption tracepoint naively walks off the end of bc_level[]. Fix that by adding a helper to do an implicit range check.
--- fs/xfs/scrub/trace.c | 13 +++++++++++++ fs/xfs/scrub/trace.h | 10 +++++----- 2 files changed, 18 insertions(+), 5 deletions(-)
fs/xfs/scrub/trace.c +13 -0
@@ -21,6 +21,9 @@ xchk_btree_cur_fsbno( struct xfs_btree_cur *cur, int level) { +if (level <0 ) +return NULLFSBLOCK ; +if (level < cur->bc_nlevels && cur->bc_levels[level].bp)return XFS_DADDR_TO_FSB (cur->bc_mp,xfs_buf_daddr (cur->bc_levels[level].bp));
@@ -32,6 +35,16 @@ xchk_btree_cur_fsbno(return NULLFSBLOCK ; } +static inline int +xchk_btree_cur_ptr ( +const struct xfs_btree_cur *cur, +int level) +{ +if (level >=0 && level < cur->bc_nlevels) +return cur->bc_levels[level].ptr; +return -1 ; +} +/* * We include this last to have the helpers above available for the trace * event implementations.
fs/xfs/scrub/trace.h +5 -5
@@ -348,7 +348,7 @@ TRACE_EVENT(xchk_btree_op_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->error = error; __entry->ret_ip = ret_ip; ),
@@ -389,7 +389,7 @@ TRACE_EVENT(xchk_ifork_btree_op_error, __entry->type = sc->sm->sm_type; __entry->btnum = cur->bc_btnum; __entry->level = level; - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); __entry->error = error;
@@ -431,7 +431,7 @@ TRACE_EVENT(xchk_btree_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->ret_ip = ret_ip; ), TP_printk("dev %d:%d type %s btree %s level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -471,7 +471,7 @@ TRACE_EVENT(xchk_ifork_btree_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->ret_ip = ret_ip; ), TP_printk("dev %d:%d ino 0x%llx fork %s type %s btree %s level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -511,7 +511,7 @@ DECLARE_EVENT_CLASS(xchk_sbtree_class, __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); __entry->level = level; __entry->nlevels = cur->bc_nlevels; - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); ), TP_printk("dev %d:%d type %s btree %s agno 0x%x agbno 0x%x level %d nlevels %d ptr %d", MAJOR(__entry->dev), MINOR(__entry->dev),
Greg Kroah-Hartman
maintainerPATCH 596/2857 smb: client: fix buffer overflow in SMB2_tcon()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luxiao Xu <[email protected]>
commit 73cc469b0ff7551f8537ea919709973e6dc4f514 upstream.
In SMB2_tcon(), unc_path is allocated with a fixed buffer size of MAX_SHARENAME_LENGTH * 2 bytes (672 bytes). However, the user-controlled UNC path (tree) length is passed to cifs_strtoUTF16(), which assumes the destination buffer is large enough and writes strlen(tree) + 1 UTF-16 code units.
Commit 62a1a439e0fd ("cifs: clean up handling of unc= option") removed the length check on UNC mount options, allowing mount paths to exceed MAX_SHARENAME_LENGTH while retaining the fixed-size buffer allocation in SMB2_tcon(). Consequently, an oversized UNC string causes cifs_strtoUTF16() to write past the end of the heap object, resulting in a slab-out-of-bounds write. Furthermore, if a tree exceeds MAX_TREE_SIZE characters, strscpy() truncates it in cifs_tcon::tree_name, causing subsequent reconnects or failovers to fail.
Fix this by first verifying that the length of tree does not exceed MAX_TREE_SIZE, returning -EINVAL if it does. Then, dynamically allocate unc_path based on the length of tree so that it safely accommodates all UTF-16 code units for paths within MAX_TREE_SIZE.
--- fs/smb/client/smb2pdu.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
fs/smb/client/smb2pdu.c +9 -3
@@ -1917,8 +1917,6 @@ static inline void cifs_stats_fail_inc(scifs_stats_inc (&tcon->stats.smb2_stats.smb2_com_failed[code]); } -#define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */) -/* These are similar values to what Windows uses */ static inline void init_copy_chunk_defaults (struct cifs_tcon *tcon) {
@@ -1952,7 +1950,15 @@ SMB2_tcon(const unsigned int xid, structif (!server || !tree)return -EIO ; - unc_path =kmalloc (MAX_SHARENAME_LENGTH *2 ,GFP_KERNEL ); + total_len =strlen (tree); +if (total_len >MAX_TREE_SIZE ) { +cifs_server_dbg (VFS |ONCE , +"%s: tree name exceeded %u characters\n" , + __func__,MAX_TREE_SIZE ); +return -EINVAL ; + } + + unc_path =kmalloc ((total_len +1 ) *sizeof (*unc_path),GFP_KERNEL );if (unc_path ==NULL )return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 597/2857 smb: client: fix fiemap wild read on empty truncated response
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Abdifatah Suruur <[email protected]>
commit f5baa17a0f316c235d61623ac8e8fb32c2b3c0cc upstream.
smb3_fiemap() treats -E2BIG from SMB2_ioctl() as a truncated range blob and loops for the next chunk. If the server reports STATUS_BUFFER_OVERFLOW with OutputCount == 0, SMB2_ioctl() returns -E2BIG with out_data == NULL and out_data_len == 0, and the existing length checks accept the empty result. The loop then evaluates
next = out_data[num - 1].file_offset + ...
with num == 0, reading 16 bytes before NULL.
Reject a truncated range blob that contains no range, so the resume offset is never computed from an empty response. Also require the last range in a truncated blob to advance the resume offset without overflowing, and to stay within the requested range; a malicious or broken server could otherwise make no progress or underflow len and loop forever. Free the previous response buffer before retrying.
Reproduced on 6.6.87.2 with a malicious SMB2 server that answers FSCTL_QUERY_ALLOCATED_RANGES with STATUS_BUFFER_OVERFLOW and OutputCount == 0; an FS_IOC_FIEMAP ioctl on the mount oopses in cifs_fiemap() with CR2 = fffffffffffffff8. The code path is unchanged on mainline.
--- fs/smb/client/smb2ops.c | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-)
fs/smb/client/smb2ops.c +27 -3
@@ -4170,6 +4170,15 @@ static int smb3_fiemap(struct cifs_tcon goto out; } +/* +* A truncated range blob must contain at least one range, otherwise +* there is no offset to resume from and out_data is NULL. +*/ +if (!last_blob && out_data_len ==0 ) { + rc = -EINVAL ; + goto out; + } + num = out_data_len /sizeof (struct file_allocated_range_buffer );for (i =0 ; i < num; i++) { flags =0 ;
@@ -4190,10 +4199,25 @@ static int smb3_fiemap(struct cifs_tcon }if (!last_blob) { - next =le64_to_cpu (out_data[num -1 ].file_offset) + -le64_to_cpu (out_data[num -1 ].length); - len = len - (next - start); +u64 last_start, last_len; + + last_start =le64_to_cpu (out_data[num -1 ].file_offset); + last_len =le64_to_cpu (out_data[num -1 ].length); + +if (check_add_overflow (last_start, last_len, &next) || + next <= start) { + rc = -EINVAL ; + goto out; + } +if (next - start >= len) { + rc =0 ; + goto out; + } + + len -= next - start; start = next; +kfree (out_data); + out_data =NULL ; goto again; }
Greg Kroah-Hartman
maintainerPATCH 598/2857 pNFS: Fix CB_NOTIFY_DEVICEID CHANGE to consume ndc_immediate
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit a0cb76dc3b2919af8257fc08b4f9a79a35442483 upstream.
decode_devicenotify_args() gated the trailing ndc_immediate on cbd_layout_type rather than cbd_notify_type, so the flag was never consumed and a multi-item cnda_changes<> misaligned after the first entry.
--- fs/nfs/callback_xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfs/callback_xdr.c +1 -1
@@ -313,7 +313,7 @@ __be32 decode_devicenotify_args(struct smemcpy (dev->cbd_dev_id.data, p,NFS4_DEVICEID4_SIZE ); p +=XDR_QUADLEN (NFS4_DEVICEID4_SIZE ); -if (dev->cbd_layout_type ==NOTIFY_DEVICEID4_CHANGE ) { +if (dev->cbd_notify_type ==NOTIFY_DEVICEID4_CHANGE ) { p =xdr_inline_decode (xdr,sizeof (uint32_t ));if (unlikely (p ==NULL )) { status =htonl (NFS4ERR_BADXDR );
Greg Kroah-Hartman
maintainerPATCH 599/2857 pnfs/blocklayout: Complete a device upcall only on its own reply
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit acfbea6c5e27c68d6b6d12849eb2b7f8466ccf06 upstream.
bl_pipe_downcall() wakes bl_resolve_deviceid() on any write of the right size, without checking that blkmapd has read the upcall being replied to. A write that arrives first returns the waiter while its struct rpc_pipe_msg is still queued on the pipe, which then holds a list_head into a dead stack frame. Reaching the pipe takes root, so the trigger is a broken or hostile blkmapd.
The wait has two further defects. bl_resolve_deviceid() sets TASK_UNINTERRUPTIBLE only after rpc_queue_upcall() has made the message visible, so a reply that lands in between wakes a running task and the schedule() that follows sleeps forever holding bl_mutex. And nn->bl_mount_reply is never reset, so when the pipe purges an unread upcall the waiter takes the previous reply as its own.
Move the message into struct nfs_net, where bl_mutex already limits the pipe to one upcall per net namespace. Accept a reply only while blkmapd has read the whole message and no earlier reply has been taken, and reject any other write with -EINVAL. Wait for that reply on a completion so it cannot slip past the sleep, and check msg->errno before trusting it.
--- fs/nfs/blocklayout/blocklayout.h | 5 --- fs/nfs/blocklayout/rpc_pipefs.c | 58 ++++++++++++++++++++++++--------------- fs/nfs/netns.h | 5 ++- 3 files changed, 41 insertions(+), 27 deletions(-)
fs/nfs/blocklayout/blocklayout.h +0 -5
@@ -155,11 +155,6 @@ BLK_LSEG2EXT(struct pnfs_layout_segmentreturn BLK_LO2EXT (lseg->pls_layout); } -struct bl_pipe_msg { -struct rpc_pipe_msg msg; -wait_queue_head_t *bl_wq; -}; -struct bl_msg_hdr {u8 type;u16 totallen;/* length of entire message, including hdr itself */
fs/nfs/blocklayout/rpc_pipefs.c +37 -21
104 lines not on this page · raw message
fs/nfs/netns.h +4 -1
@@ -10,6 +10,8 @@#include <net/net_namespace.h> #include <net/netns/generic.h> #include <linux/sunrpc/stats.h> +#include <linux/sunrpc/rpc_pipe_fs.h> +#include <linux/completion.h> struct bl_dev_msg {int32_t status;
@@ -21,8 +23,9 @@ struct nfs_netns_client;struct nfs_net {struct cache_detail *nfs_dns_resolve;struct rpc_pipe *bl_device_pipe; +struct rpc_pipe_msg bl_pipe_msg;struct bl_dev_msg bl_mount_reply; -wait_queue_head_t bl_wq; +struct completion bl_done;struct mutex bl_mutex;struct list_head nfs_client_list;struct list_head nfs_volume_list;
Greg Kroah-Hartman
maintainerPATCH 600/2857 pnfs/blocklayout: Complete a device upcall when the pipe is closed
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 2a25cc8e984610828a526086313b8a7aeefe507d upstream.
Once blkmapd has read a whole upcall, rpc_pipe_read() unlinks the message from every pipe list, so the purges in rpc_pipe_release() and rpc_close_pipes() no longer reach it. bl_upcall_ops supplies no .release_pipe callback, and bl_pipe_destroy_msg() returns without completing the upcall because a downcall is expected to follow. A daemon that exits between the read and the write therefore strands its waiter: bl_resolve_deviceid() sleeps in wait_for_completion() and never returns, and it holds nn->bl_mutex across that wait, so every later device resolution in the net namespace blocks behind it.
Add a .release_pipe that completes an upcall blkmapd has consumed and left unanswered. Completing an upcall retires it, so a message the framework has already purged is no longer in flight and is not completed a second time here.
--- fs/nfs/blocklayout/rpc_pipefs.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
fs/nfs/blocklayout/rpc_pipefs.c +21 -0
@@ -151,10 +151,31 @@ static void bl_pipe_destroy_msg(struct rcomplete (&nn->bl_done); } +/* +* An upcall blkmapd has consumed is off every pipe list, so the +* purges in rpc_pipe_release() and rpc_close_pipes() cannot reach it. +* No downcall can arrive once the pipe is closed; release its waiter +* here. +*/ +static void bl_release_pipe (struct inode *inode) +{ +struct nfs_net *nn =net_generic (inode->i_sb->s_fs_info, nfs_net_id); +struct rpc_pipe *pipe = nn->bl_device_pipe; + +spin_lock (&pipe->lock); +if (rpc_msg_is_inflight (&nn->bl_pipe_msg)) { + nn->bl_pipe_msg.copied =0 ; + nn->bl_pipe_msg.errno = -EPIPE ; +complete (&nn->bl_done); + } +spin_unlock (&pipe->lock); +} +static const struct rpc_pipe_ops bl_upcall_ops = { .upcall = rpc_pipe_generic_upcall, .downcall = bl_pipe_downcall, .destroy_msg = bl_pipe_destroy_msg, + .release_pipe = bl_release_pipe, }; static struct dentry *nfs4blocklayout_register_sb(struct super_block *sb,
Greg Kroah-Hartman
maintainerPATCH 601/2857 NFSv4.1/pnfs: suspend pNFS on NFS4ERR_TOOSMALL from LAYOUTGET
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 28c950413605fb5b6cb3863c5e3274ea69701097 upstream.
If the layout for the requested range is larger than the size the client advertised in loga_maxcount, RFC 8881 Section 18.43.3 has the metadata server return NFS4ERR_TOOSMALL. The client caps loga_maxcount at a single page, so a flexfiles server that stripes a layout segment across several dozen data servers produces this error today.
The client has no handling for it: nfs4_stat_to_errno() maps the error to -ETOOSMALL during decode, which nothing in the layoutget path recognizes and nfs_error_is_fatal() does not consider fatal, so pnfs_update_layout() clears the layout fail bit and returns no segment. The I/O falls back to the MDS, but because no fail bit was set, every subsequent pageio attempt sends another LAYOUTGET that is doomed to the same NFS4ERR_TOOSMALL. Files whose layouts do not fit the reply buffer never use pNFS and pay an extra round trip on every pageio.
Map -ETOOSMALL to -EMSGSIZE in the layoutget exception handler and have pnfs_update_layout() treat it like NFS4ERR_LAYOUTUNAVAILABLE:
mark the layout mode as failed and fall back to I/O through the MDS.
--- fs/nfs/nfs4proc.c | 8 ++++++++ fs/nfs/pnfs.c | 2 ++ 2 files changed, 10 insertions(+)
fs/nfs/nfs4proc.c +8 -0
@@ -9711,6 +9711,14 @@ nfs4_layoutget_handle_exception(struct r status = -EOVERFLOW ; goto out;/* +* NFS4ERR_TOOSMALL means the layout for the requested range +* exceeds what the client advertised in loga_maxcount (see +* RFC8881 section 18.43.3). +*/ +case -ETOOSMALL : + status = -EMSGSIZE ; + goto out; +/* * NFS4ERR_LAYOUTTRYLATER is a conflict with another client * (or clients) writing to the same RAID stripe except when * the minlength argument is 0 (see RFC5661 section 18.43.3).
fs/nfs/pnfs.c +2 -0
@@ -2195,6 +2195,8 @@ lookup_again:break ;case -ENODATA :/* The server returned NFS4ERR_LAYOUTUNAVAILABLE */ +case -EMSGSIZE : +/* The layout exceeded loga_maxcount (NFS4ERR_TOOSMALL) */ pnfs_layout_set_fail_bit ( lo,pnfs_iomode_to_fail_bit (iomode)); lseg =NULL ;
Greg Kroah-Hartman
maintainerPATCH 602/2857 NFSv4/filelayout: Anchor page coalescing on pattern_offset
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 7f2d221b01f356b6bb3bb6efef998f8b28339824 upstream.
filelayout_pg_test() bounds page coalescing to a single stripe unit using an offset relative to pls_range.offset, but the data server is selected by nfs4_fl_calc_j_index() using an offset relative to pattern_offset. When a segment's pattern_offset and range offset are not congruent modulo the stripe unit, the coalescing window is shifted off the DS-selection grid, so a coalesced I/O can straddle a stripe boundary and send the bytes past it to the wrong data server.
Anchor coalescing on pattern_offset to match nfs4_fl_calc_j_index(). Stripe-congruent segments, including the common whole-file pattern_offset 0 case, are unchanged.
--- fs/nfs/filelayout/filelayout.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
fs/nfs/filelayout/filelayout.c +4 -4
@@ -804,7 +804,7 @@ filelayout_pg_test(struct nfs_pageio_desunsigned int size;u64 p_stripe, r_stripe;u32 stripe_offset; -u64 segment_offset = pgio->pg_lseg->pls_range.offset; +u64 pattern_offset =FILELAYOUT_LSEG (pgio->pg_lseg)->pattern_offset;u32 stripe_unit =FILELAYOUT_LSEG (pgio->pg_lseg)->stripe_unit;/* calls nfs_generic_pg_test */
@@ -816,8 +816,8 @@ filelayout_pg_test(struct nfs_pageio_des/* see if req and prev are in the same stripe */ if (prev) { - p_stripe = (u64 )req_offset (prev) - segment_offset; - r_stripe = (u64 )req_offset (req) - segment_offset; + p_stripe = (u64 )req_offset (prev) - pattern_offset; + r_stripe = (u64 )req_offset (req) - pattern_offset;do_div (p_stripe, stripe_unit);do_div (r_stripe, stripe_unit);
@@ -826,7 +826,7 @@ filelayout_pg_test(struct nfs_pageio_des }/* calculate remaining bytes in the current stripe */ -div_u64_rem ((u64 )req_offset (req) - segment_offset, +div_u64_rem ((u64 )req_offset (req) - pattern_offset, stripe_unit, &stripe_offset);WARN_ON_ONCE (stripe_offset > stripe_unit);
Greg Kroah-Hartman
maintainerPATCH 603/2857 nfsd: clear XDR padding in GETXATTR replies
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit daba58690339ae86f1ebeb5197aa1369fae37e57 upstream.
nfsd4_vbuf_to_stream() uses a raw memcpy() for the first fragment of an attribute value. xdr_reserve_space() aligns the reservation but does not initialize the extra bytes. If the complete value fits in that fragment, the loop that clears padding for the final fragment is never entered.
A remote client reading an attribute whose length is not a multiple of four can therefore receive one to three stale bytes from the response page.
Encode the first fragment with xdr_encode_opaque_fixed(), matching the final-fragment path and ensuring that any XDR padding is zeroed.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -5044,7 +5044,7 @@ nfsd4_vbuf_to_stream(struct xdr_stream *if (!p)return nfserr_resource; -memcpy (p, buf, cplen); +xdr_encode_opaque_fixed (p, buf, cplen); buf += cplen; buflen -= cplen;
Greg Kroah-Hartman
maintainerPATCH 604/2857 NFSD: copy SETXATTR data from all XDR buffer segments
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit b01319947c69b0e3ea0fcd4b675eb892f9cad8a0 upstream.
nfsd4_vbuf_from_vector() manually copies the head followed by whole pages starting at offset zero. This assumes that all remaining data starts at the beginning of the page array and that no data is stored in the tail.
However, nfsd4_decode_setxattr() passes an xdr_buf returned by xdr_stream_subsegment(). Such a sub-buffer can have a nonzero page_base and can span its page and tail segments. Ignoring that layout can copy the wrong bytes into the value passed to vfs_setxattr().
Use read_bytes_from_xdr_buf(), which observes the complete xdr_buf layout.
--- fs/nfsd/nfs4xdr.c | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-)
fs/nfsd/nfs4xdr.c +3 -16
@@ -2117,10 +2117,8 @@ static __be32 nfsd4_vbuf_from_vector(struct nfsd4_compoundargs *argp, struct xdr_buf *xdr, char **bufp, u32 buflen) { - struct page **pages = xdr->pages; struct kvec *head = xdr->head; -char *tmp, *dp; -u32 len; +char *tmp;if (buflen <= head->iov_len) {/*
@@ -2135,19 +2133,8 @@ nfsd4_vbuf_from_vector(struct nfsd4_compif (tmp ==NULL )return nfserr_jukebox; - dp = tmp; -memcpy (dp, head->iov_base, head->iov_len); - buflen -= head->iov_len; - dp += head->iov_len; - -while (buflen >0 ) { - len =min_t (u32, buflen,PAGE_SIZE ); -memcpy (dp,page_address (*pages), len); - - buflen -= len; - dp += len; - pages++; - } +if (read_bytes_from_xdr_buf (xdr,0 , tmp, buflen)) +return nfserr_bad_xdr; *bufp = tmp;return 0 ;
Greg Kroah-Hartman
maintainerPATCH 605/2857 NFSD: Do not send CB_RECALL_ANY to NFSv4.0 clients
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 95ff0c079b9cab91f2327beb4197a3bc48c71f55 upstream.
deleg_reaper() sends CB_RECALL_ANY to every ACTIVE client holding delegations, but CB_RECALL_ANY is an NFSv4.1 operation. An NFSv4.0 client's callback service accepts only CB_GETATTR and CB_RECALL, so it replies OP_ILLEGAL. The decoder maps the unexpected opnum to -EIO, and nfsd4_cb_done() marks the client's callback channel down.
Nothing brings the channel back. nfsd4_run_cb_work() sets NFSD4_CB_UP only for a minor version above zero, and the only nfsd4_probe_callback() call site an NFSv4.0 client reaches is nfsd4_setclientid_confirm(). One visit from the reaper therefore leaves the channel marked down until the client re-establishes its clientid. RENEW then returns NFS4ERR_CB_PATH_DOWN for as long as the client holds delegations. nfsd4_cb_channel_good() stops returning true, so the client is granted no further delegations.
Skip clients at minor version zero.
--- fs/nfsd/nfs4state.c | 2 ++ 1 file changed, 2 insertions(+)
fs/nfsd/nfs4state.c +2 -0
@@ -6463,6 +6463,8 @@ deleg_reaper(struct nfsd_net *nn)list_for_each_safe (pos, next, &nn->client_lru) { clp = list_entry(pos, struct nfs4_client, cl_lru); +if (clp->cl_minorversion ==0 ) +continue ;if (clp->cl_state !=NFSD4_ACTIVE )continue ;if (list_empty (&clp->cl_delegations))
Greg Kroah-Hartman
maintainerPATCH 606/2857 NFSD: Dont complete a cld upcall the daemon has not read
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 7f4bf851aca4e18940ebf2bddf4ba6783802ee81 upstream.
cld_pipe_downcall() matches a reply to its upcall on the xid alone. A write that arrives before the daemon has read that upcall completes __cld_pipe_upcall() while its struct rpc_pipe_msg is still queued on the pipe. The waiter returns, its stack frame goes away, and the pipe keeps a list_head that points into it. The next rpc_queue_upcall() walks that pointer:
BUG: KASAN: vmalloc-out-of-bounds in __list_add_valid_or_report Read of size 8 at addr ffffc90007027950 by task syz.0.96/13066 __list_add_valid_or_report+0x6a/0x130 rpc_queue_upcall cld_pipe_upcall nfsd4_cld_grace_start nfsd4_cld_tracking_init
The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Record whether the daemon has consumed the whole message and complete only when it has. cld_pipe_destroy_msg() runs on every path by which the pipe releases a message, so it can maintain that flag under cn_lock. nfsdcld sends its -EINPROGRESS downcalls only after reading the upcall, so the new check does not break the GraceStart record stream.
--- fs/nfsd/nfs4recover.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-)
fs/nfsd/nfs4recover.c +20 -3
@@ -724,6 +724,8 @@ struct cld_upcall {struct list_head cu_list;struct cld_net *cu_net;struct completion cu_done; +/* daemon has read the whole upcall; protected by cn_lock */ +bool cu_inflight;union {struct cld_msg_hdr cu_hdr;struct cld_msg cu_msg;
@@ -883,6 +885,13 @@ cld_pipe_downcall(struct file *filp, conspin_lock (&cn->cn_lock);list_for_each_entry (tmp, &cn->cn_list, cu_list) {if (get_unaligned (&tmp->cu_u.cu_hdr.cm_xid) == xid) { +/* +* Completing now would return the waiter +* while its message is still queued on the +* pipe. +*/ +if (!tmp->cu_inflight) +break ; cup = tmp;if (status != -EINPROGRESS )list_del_init (&cup->cu_list);
@@ -891,9 +900,9 @@ cld_pipe_downcall(struct file *filp, con }spin_unlock (&cn->cn_lock); -/* couldn't find upcall? */ +/* no upcall to complete? */ if (!cup) { -dprintk ("%s: couldn't find upcall -- xid=%u\n" , __func__, xid); +dprintk ("%s: no completable upcall -- xid=%u\n" , __func__, xid);return -EINVAL ; }
@@ -913,8 +922,16 @@ cld_pipe_destroy_msg(struct rpc_pipe_msgstruct cld_msg *cmsg = msg->data; struct cld_upcall *cup = container_of(cmsg, struct cld_upcall, cu_u.cu_msg); +struct cld_net *cn = cup->cu_net; + +/* +* errno >= 0 means the daemon read the whole message and a +* downcall will complete the upcall. +*/ +spin_lock (&cn->cn_lock); + cup->cu_inflight = msg->errno >=0 ; +spin_unlock (&cn->cn_lock); -/* errno >= 0 means we got a downcall */ if (msg->errno >=0 )return ;
Greg Kroah-Hartman
maintainerPATCH 607/2857 nfsd: dont modify a session slot when replaying its cached reply
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit 2987838317501ff67b672ac2a441fe34b7729f3d upstream.
nfsd4_sequence() claims a session slot by setting NFSD4_SLOT_INUSE under nn->client_lock. A reply served from the slot's reply cache does not claim it, and that distinction lived only in cstate->status, which nfsd4_sequence() set to nfserr_replay_cache. Commit cc028a10a48c ("NFSD: Hoist status code encoding into XDR encoder functions") moved nfsd4_proc_compound()'s cstate->status assignment below the out:
label, and the replay path's goto out was the one path that relied on skipping it. The test in nfsd4_sequence_done() therefore no longer identifies a replay, and every replay now stores its reply and clears NFSD4_SLOT_INUSE as though it owned the slot.
NFSD4_SLOT_INUSE is the interlock: check_slot_seqid() rejects every sequence id for a slot that is in use, before replay_matches_cache() runs. A replay never sets it, so two replays can be in flight on the same slot at once. One can read slot->sl_cred under nn->client_lock while the other's completion frees and rebuilds it from the XDR encoder without that lock. Two completions can also collide with each other and release the same group_info twice. free_svc_cred() leaves cr_uid, cr_gid and cr_flavor intact, so the reader passes every earlier test in same_creds() and dereferences a NULL cr_group_info.
Quoted 1 line
From a 6.12.91 production server:
BUG: kernel NULL pointer dereference, address: 0000000000000004 CPU: 63 UID: 0 PID: 39015 Comm: nfsd RIP: 0010:same_creds+0x38/0xa0 [nfsd] RDX: 0000000000000000 Call Trace: nfsd4_sequence+0x6a8/0x910 [nfsd] nfsd4_proc_compound+0x345/0x670 [nfsd] nfsd_dispatch+0x100/0x220 [nfsd] svc_process_common+0x311/0x700 [sunrpc] svc_process+0x131/0x1c0 [sunrpc] svc_recv+0x7ef/0x9c0 [sunrpc] nfsd+0xa3/0x100 [nfsd] Kernel panic - not syncing: Fatal exception
Since v6.14 a live session's slot table can shrink, and the unowned store becomes a use-after-free write. nfsd4_sequence() defers the shrink while a slot is in use, but it tests NFSD4_SLOT_INUSE, which a replay does not set, so free_session_slots() can kfree() the slot the replay still holds in cstate->slot.
Record the claim in cstate->slot_owned when nfsd4_sequence() accepts a request and test that in nfsd4_sequence_done(), so only the request that claimed the slot updates its cached reply and clears NFSD4_SLOT_INUSE. svc_generic_init_request() zeroes the compound response before each request, so the flag starts clear.
--- fs/nfsd/nfs4state.c | 7 ++++++- fs/nfsd/xdr4.h | 1 + 2 files changed, 7 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +6 -1
@@ -4158,6 +4158,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, s slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS ; cstate->slot = slot; + cstate->slot_owned = true; cstate->session = session; cstate->clp = clp;
@@ -4190,7 +4191,11 @@ nfsd4_sequence_done(struct nfsd4_compounstruct nfsd4_compound_state *cs = &resp->cstate;if (nfsd4_has_session (cs)) { -if (cs->status != nfserr_replay_cache) { +/* +* Only the request that claimed the slot may update its +* cached reply and clear NFSD4_SLOT_INUSE. +*/ +if (cs->slot_owned) {nfsd4_store_cache_entry (resp); cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE ; }
fs/nfsd/xdr4.h +1 -0
@@ -60,6 +60,7 @@ struct nfsd4_compound_state {struct nfsd4_slot *slot;int data_offset;bool spo_must_allowed; +bool slot_owned;size_t iovlen;u32 minorversion;__be32 status;
Greg Kroah-Hartman
maintainerPATCH 608/2857 NFSD: Fail a pool_threads read whose reply does not fit
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit e27c63245903402ccfdb46c576462981a7e032e3 upstream.
The reply to a pool_threads read is the list of per-pool thread counts, formatted into a buffer of SIMPLE_TRANSACTION_LIMIT bytes. snprintf() truncates its last write and strlen() measures only what fit, so a reply too long for that buffer ends mid-number with no terminating newline. A pool running 4096 threads is reported as 40. Nothing marks the reply as incomplete, so an administrator reads a plausible but wrong count.
Take snprintf()'s return value, which reports the truncation strlen() cannot see, and fail the read with -ENAMETOOLONG when the list does not fit. That is the errno svc_one_xprt_name() already returns for the same condition.
--- fs/nfsd/nfsctl.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/nfsd/nfsctl.c +8 -4
@@ -460,7 +460,7 @@ static ssize_t write_pool_threads(structchar *mesg = buf;int i;int rv; -int len; +size_t len;int npools;int *nthreads;struct net *net =netns (file);
@@ -505,9 +505,13 @@ static ssize_t write_pool_threads(struct mesg = buf; size =SIMPLE_TRANSACTION_LIMIT ; -for (i =0 ; i < npools && size >0 ; i++) { -snprintf (mesg, size,"%d%c" , nthreads[i], (i == npools-1 ?'\n' :' ' )); - len =strlen (mesg); +for (i =0 ; i < npools; i++) { + len =snprintf (mesg, size,"%d%c" , nthreads[i], + (i == npools -1 ?'\n' :' ' )); +if (len >= size) { + rv = -ENAMETOOLONG ; + goto out_free; + } size -= len; mesg += len; }
Greg Kroah-Hartman
maintainerPATCH 609/2857 nfsd: Fix id-to-name cache entry leak in idtoname_parse()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
commit 8ca3b74c0c447af17d0e27e76658a3d4cae3c5ba upstream.
idtoname_lookup() returns the id-to-name cache entry with a new reference. The name is parsed between the lookup and the update call, and when the parsed name is malformed (negative length or longer than IDMAP_NAMESZ), idtoname_parse() jumps to the error label without dropping the reference returned by idtoname_lookup(), leaking the cache entry.
Release the reference with cache_put() before taking the error exit.
--- fs/nfsd/nfs4idmap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/nfsd/nfs4idmap.c +3 -1
@@ -252,8 +252,10 @@ idtoname_parse(struct cache_detail *cd,/* Name */ error = -EINVAL ; len =qword_get (&buf, buf1,PAGE_SIZE ); -if (len <0 || len >=IDMAP_NAMESZ ) +if (len <0 || len >=IDMAP_NAMESZ ) { +cache_put (&res->h, cd); goto out; + }if (len ==0 )set_bit (CACHE_NEGATIVE , &ent.h.flags);else
Greg Kroah-Hartman
maintainerPATCH 610/2857 nfsd: hold cl_lock in client_has_openowners()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>
commit 5336899b5491eaa2ac22c2925d87daab2b140eb3 upstream.
client_has_openowners() walks clp->cl_openowners and reads so_stateids without clp->cl_lock. nfs4_put_stateowner() unhashes that openowner under cl_lock and then frees it, so a concurrent EXCHANGE_ID with mismatched creds can use-after-free the nfs4_openowner.
BUG: KASAN: slab-use-after-free in client_has_state+0x10a/0x140 fs/nfsd/nfs4state.c:3718 client_has_openowners() nfsd4_exchange_id nfsd4_proc_compound nfsd_dispatch svc_process
Take clp->cl_lock while client_has_openowners() walks the openowner list.
--- fs/nfsd/nfs4state.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
fs/nfsd/nfs4state.c +9 -3
@@ -3351,12 +3351,18 @@ nfsd4_set_ex_flags(struct nfs4_client *nstatic bool client_has_openowners (struct nfs4_client *clp) {struct nfs4_openowner *oo; +bool found = false; +spin_lock (&clp->cl_lock);list_for_each_entry (oo, &clp->cl_openowners, oo_perclient) { -if (!list_empty (&oo->oo_owner.so_stateids)) -return true; +if (!list_empty (&oo->oo_owner.so_stateids)) { + found = true; +break ; + } } -return false; +spin_unlock (&clp->cl_lock); + +return found; }static bool client_has_state (struct nfs4_client *clp)
Greg Kroah-Hartman
maintainerPATCH 611/2857 nfsd: honour client-provided attributes for NFS4_CREATE_EXCLUSIVE4_1
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: NeilBrown <[email protected]>
commit ddfabbc7840891e09cd500ab97c9cd36b650ec24 upstream.
When a file is created with a v4.1 OPEN which requests NFS4_CREATE_EXCLUSIVE4_1, the request can include attributes to be set. However when the mtime/atime are set to hold the verifier, the other ia_valid flags are cleared, so no attributes requested by the client are used.
This code was originally written for NFSv3 where NFS3_CREATE_EXCLUSIVE never includes attributes. When it was updated for v4.1, the fact that an exclusive create CAN include attributes was not handled properly.
--- fs/nfsd/nfs4proc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/nfsd/nfs4proc.c +2 -2
@@ -356,8 +356,8 @@ nfsd4_create_file(struct svc_rqst *rqstpif ((iap->ia_valid &ATTR_SIZE ) && (iap->ia_size ==0 )) iap->ia_valid &= ~ATTR_SIZE ;if (nfsd4_create_is_exclusive (open->op_createmode)) { - iap->ia_valid =ATTR_MTIME |ATTR_ATIME | -ATTR_MTIME_SET |ATTR_ATIME_SET ; + iap->ia_valid |=ATTR_MTIME |ATTR_ATIME | +ATTR_MTIME_SET |ATTR_ATIME_SET ; iap->ia_mtime.tv_sec = v_mtime; iap->ia_atime.tv_sec = v_atime; iap->ia_mtime.tv_nsec =0 ;
Greg Kroah-Hartman
maintainerPATCH 612/2857 nfsd: preflight SEQUENCE replies before accepting a slot
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 35ff1a7a7e3835c3e974bc5c45d335897564ceae upstream.
nfsd4_sequence() narrows the reply buffer to the session's cached reply limit before it accepts the slot seqid. A client may negotiate ca_maxresponsesize_cached down to NFSD_MIN_HDR_SEQ_SZ, and nfsd4_alloc_slot() then gives every slot a zero-length sl_data[]. A COMPOUND tag can fill that narrowed buffer until it holds the SEQUENCE opcode but not the status word that follows. nfsd4_encode_operation() returns without running nfsd4_encode_sequence(), so cstate.data_offset stays zero. It leaves op->status at nfs_ok as well, so the COMPOUND is treated as having succeeded.
nfsd4_store_cache_entry() declines to cache a lone SEQUENCE that returned an error. That test reads the status the operation reported, so it passes here. The copy starts at offset zero and takes the whole reply, RPC and COMPOUND headers included, into the zero-length sl_data[]. The COMPOUND tag is copied along with it, so the client picks most of the bytes written past the end of the slot:
BUG: KASAN: slab-out-of-bounds in read_bytes_from_xdr_buf+0x1bc/0x390 Write of size 80 at addr ffff888003a549cd by task kunit_try_catch/24 __asan_memcpy+0x38/0x60 read_bytes_from_xdr_buf+0x1bc/0x390 nfsd4_sequence_done+0x5b0/0x810 nfs4svc_encode_compoundres+0x1bf/0x240
Check that the fixed-size SEQUENCE result, plus room for a following operation's error status, fits the negotiated limit before narrowing the buffer and consuming the slot seqid. The slot and its reply cache are left unchanged, as RFC 8881 Section 2.10.6.1.2 requires of an error returned from SEQUENCE.
--- fs/nfsd/nfs4state.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +18 -1
@@ -4070,6 +4070,7 @@ __be32 nfsd4_sequence(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, union nfsd4_op_u *u) { + struct nfsd4_compoundargs *args = rqstp->rq_argp;struct nfsd4_sequence *seq = &u->sequence;struct nfsd4_compoundres *resp = rqstp->rq_resp;struct xdr_stream *xdr = resp->xdr;
@@ -4079,6 +4080,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, sstruct nfsd4_conn *conn;__be32 status;int buflen; +u32 maxlen, respsize;struct net *net =SVC_NET (rqstp);struct nfsd_net *nn =net_generic (net, nfsd_net_id);
@@ -4150,7 +4152,22 @@ nfsd4_sequence(struct svc_rqst *rqstp, s session->se_fchannel.maxresp_sz; status = (seq->cachethis) ? nfserr_rep_too_big_to_cache : nfserr_rep_too_big; -if (xdr_restrict_buflen (xdr, buflen - rqstp->rq_auth_slack)) +if (buflen < rqstp->rq_auth_slack) + goto out_put_session; + maxlen = buflen - rqstp->rq_auth_slack; + +/* +* A SEQUENCE result too large for maxlen never reaches +* nfsd4_encode_sequence(), so cstate.data_offset stays zero and +* the reply cache overruns the slot. +*/ + respsize =nfsd4_max_reply (rqstp, &args->ops[0 ]); +if (!nfsd4_last_compound_op (rqstp)) + respsize +=COMPOUND_ERR_SLACK_SPACE ; +if (xdr->buf->len + respsize > maxlen) + goto out_put_session; + +if (xdr_restrict_buflen (xdr, maxlen)) goto out_put_session;svc_reserve (rqstp, buflen);
Greg Kroah-Hartman
maintainerPATCH 613/2857 nfsd: propagate SETXATTR value decode errors
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit cfcfe0b38a66bbc4122c78a2b75e1b97b3534761 upstream.
nfsd4_decode_setxattr() stores the status returned while assembling a non-empty attribute value, but then unconditionally returns nfs_ok. An allocation failure can therefore leave a NULL value buffer paired with a non-zero length and allow compound processing to continue.
Return the decoder status so that the operation stops on the original error.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -2251,7 +2251,7 @@ nfsd4_decode_setxattr(struct nfsd4_compo &setxattr->setxa_buf, size); } -return nfs_ok; +return status; } static __be32
Greg Kroah-Hartman
maintainerPATCH 614/2857 NFSD: Reject an oversized principal hash from nfsdcld
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit dbed9418c48906dae1a7bc328fb3bc0d0d0020c8 upstream.
__cld_pipe_inprogress_downcall() takes the principal hash length from the daemon's GraceStart downcall without checking it against the cc_princhash payload it describes, which holds at most SHA256_DIGEST_SIZE bytes. The length is stored verbatim in the reclaim record, and nfsd4_cld_check_v2() later hands it to memcmp() against a digest array of SHA256_DIGEST_SIZE bytes on the stack. A length up to U8_MAX reads past the end of that array, and the stray bytes can only make the comparison fail, denying the client its reclaim. The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Reject a length larger than the wire field, as the existing check on the client name length does.
--- fs/nfsd/nfs4recover.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/nfsd/nfs4recover.c +5 -0
@@ -806,6 +806,11 @@ __cld_pipe_inprogress_downcall(const str name.len = namelen;if (get_user (princhashlen, &ci->cc_princhash.cp_len))return -EFAULT ; +if (princhashlen >SHA256_DIGEST_SIZE ) { +dprintk ("%s: invalid princhashlen (%u)" , + __func__, princhashlen); +return -EINVAL ; + }if (princhashlen >0 ) { princhashcopy = memdup_user( &ci->cc_princhash.cp_data,
Greg Kroah-Hartman
maintainerPATCH 615/2857 NFSD: Resolve the recall-any mask names in the trace format
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit c563a1f0679566d7d586802e5346591d0af8da78 upstream.
RCA4_TYPE_MASK_* are enum constants, so the preprocessor cannot fold them into the print format that show_rca_mask() builds for the nfsd_cb_recall_any event. Nothing declares an eval map for them either, so trace_event_eval_update() has no substitution to apply at module load, and the event's format file ships the enumerator names verbatim. trace-cmd and perf cannot decode the bmval0 field.
Declare the eval maps for the nine mask bits show_rca_mask() decodes. The format then carries the shift counts as integers, the same shape the SUNRPC trace points already emit from their BIT() flag decoders.
--- include/trace/misc/nfs.h | 10 ++++++++++ 1 file changed, 10 insertions(+)
include/trace/misc/nfs.h +10 -0
@@ -359,6 +359,16 @@ TRACE_DEFINE_ENUM(IOMODE_ANY); { IOMODE_RW, "RW" }, \ { IOMODE_ANY, "ANY" }) +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_RDATA_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_WDATA_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_DIR_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_FILE_LAYOUT ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_BLK_LAYOUT ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OBJ_LAYOUT_MIN ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OBJ_LAYOUT_MAX ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OTHER_LAYOUT_MIN ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OTHER_LAYOUT_MAX ); +#define show_rca_mask (x) \ __print_flags(x, "|", \ { BIT(RCA4_TYPE_MASK_RDATA_DLG), "RDATA_DLG" }, \
Greg Kroah-Hartman
maintainerPATCH 616/2857 nfsd: zero NFSv4 COMPOUND tag padding
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 3f1181cb09c85499286c7f462d93530b0ebcafcc upstream.
nfs4svc_encode_compoundres() copies the tag bytes into reserved XDR space and skips directly to the aligned end of the field. xdr_reserve_space() rounds the reservation up but does not initialize the padding bytes.
A remote client can choose a tag length that is not a multiple of four, causing one to three stale bytes from the response page to be returned in the COMPOUND reply.
Use xdr_encode_opaque_fixed() to copy the tag and clear its XDR padding.
--- fs/nfsd/nfs4xdr.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
fs/nfsd/nfs4xdr.c +1 -2
@@ -5545,8 +5545,7 @@ nfs4svc_encode_compoundres(struct svc_rq rqstp->rq_next_page = xdr->page_ptr +1 ; *p++ =htonl (resp->taglen); -memcpy (p, resp->tag, resp->taglen); - p +=XDR_QUADLEN (resp->taglen); + p =xdr_encode_opaque_fixed (p, resp->tag, resp->taglen); *p++ =htonl (resp->opcnt);nfsd4_sequence_done (resp);
Greg Kroah-Hartman
maintainerPATCH 617/2857 SUNRPC: keep the first error in svc_register()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Layton <[email protected]>
commit 9ed91d7c4698e611ea5bfca45076008def831fb3 upstream.
svc_register() assigns every pg_rpcbind_set() result to the same "error" variable and returns the last one, so a later result erases an earlier failure.
Keep the first error instead of the last.
--- net/sunrpc/svc.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
net/sunrpc/svc.c +6 -3
@@ -1115,13 +1115,16 @@ int svc_register(const struct svc_serv *for (progp = serv->sv_program; progp; progp = progp->pg_next) {for (i =0 ; i < progp->pg_nvers; i++) { +int ret; - error = progp->pg_rpcbind_set (net, progp, i, + ret = progp->pg_rpcbind_set (net, progp, i, family, proto, port); -if (error <0 ) { +if (ret <0 ) {printk (KERN_WARNING "svc: failed to register " "%sv%u RPC service (errno %d).\n" , - progp->pg_name, i, -error); + progp->pg_name, i, -ret); +if (!error) + error = ret;break ; } }
Greg Kroah-Hartman
maintainerPATCH 618/2857 sunrpc: pin gss module across auth_domain RCU free
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit b64d21116374688c33302a6704387c27d1156d72 upstream.
A gss auth_domain stores a raw pointer to svcauthops_gss in dom->flavour, and its release queues svcauth_gss_domain_release_rcu() via call_rcu(). Both live in auth_rpcgss.ko text, and nothing pins the module while a domain referencing it is reachable. rmmod auth_rpcgss can therefore unmap that text while an NFSD export still holds a reference to the domain.
The export cache is one such holder. When the export is finally released, the domain reference drops from module text:
svc_export_put()
auth_domain_put(exp->ex_client)
auth_domain_release()
dom->flavour->domain_release(dom) /* into module text */
svcauth_gss_domain_release()
call_rcu(&dom->rcu_head,
svcauth_gss_domain_release_rcu)Once auth_rpcgss is unloaded, the domain_release call lands in unmapped memory. The rcu_barrier() in exit_rpcsec_gss() does not
help: it waits only for callbacks already queued, and this one is not queued until the export goes away.
NFSD's NFSv4 objects import symbols from auth_rpcgss.ko, so only a server built without CONFIG_NFSD_V4 can unload auth_rpcgss while exports still name a gss domain.
Take a module reference in svcauth_gss_register_pseudoflavor() before publishing the domain and drop it at the end of svcauth_gss_domain_release_rcu(). The rcu_barrier() then holds the module image until this callback has returned.
--- net/sunrpc/auth_gss/svcauth_gss.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/sunrpc/auth_gss/svcauth_gss.c +8 -0
@@ -872,12 +872,18 @@ svcauth_gss_register_pseudoflavor(u32 ps new->h.flavour = &svcauthops_gss; new->pseudoflavor = pseudoflavor; +if (!try_module_get (svcauthops_gss.owner)) { + stat = -ENODEV ; + goto out_free_name; + } + test =auth_domain_lookup (name, &new->h);if (test != &new->h) {pr_warn ("svc: duplicate registration of gss pseudo flavour %s.\n" , name); stat = -EADDRINUSE ;auth_domain_put (test); +module_put (svcauthops_gss.owner); goto out_free_name; }return test;
@@ -1900,9 +1906,11 @@ svcauth_gss_domain_release_rcu(struct rc { struct auth_domain *dom = container_of(head, struct auth_domain, rcu_head); struct gss_domain *gd = container_of(dom, struct gss_domain, h); +struct module *owner = dom->flavour->owner;kfree (dom->name);kfree (gd); +module_put (owner); } static void
Greg Kroah-Hartman
maintainerPATCH 619/2857 SUNRPC: Reject a socket that already has an svc_sock attached
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 0995447b8059c4d23853cdcddbe789c4a2b6bb88 upstream.
Writing the same socket descriptor to /proc/fs/nfsd/portlist twice attaches a second svc_sock to one socket. svc_setup_socket() saves the socket's callbacks before installing its own, so the second attach records svc_write_space() as the old write_space callback. svc_udp_init() invokes that callback by way of svc_sock_setbufsize(), and svc_write_space() then calls itself until the kernel stack is exhausted:
BUG: TASK stack guard page was hit at ffffc900037d7ff8 svc_write_space+0x90/0x2b0 net/sunrpc/svcsock.c:429 svc_write_space+0xe6/0x2b0 net/sunrpc/svcsock.c:430 ... 700 more ... svc_sock_setbufsize+0x18d/0x220 net/sunrpc/svcsock.c:386 svc_udp_init net/sunrpc/svcsock.c:854 [inline] svc_setup_socket+0xb2f/0x1090 net/sunrpc/svcsock.c:1498 svc_addsock+0x2fd/0x760 net/sunrpc/svcsock.c:1547 __write_ports_addfd fs/nfsd/nfsctl.c:742 [inline] write_ports+0xa5b/0xcc0 fs/nfsd/nfsctl.c:861 nfsctl_transaction_write+0x106/0x1a0 fs/nfsd/nfsctl.c:112
svc_data_ready() and svc_tcp_state_change() chain through their saved callbacks the same way, so a TCP descriptor added twice recurses on the next incoming segment instead. Reaching any of this takes a writer on portlist, and the nfsd filesystem sets no FS_USERNS_MOUNT, so the reproducer needs CAP_SYS_ADMIN in the initial user namespace.
Reject a socket that already carries sk_user_data. svc_setup_socket() overwrites that field unconditionally, so a socket some other consumer has claimed is one NFSD would corrupt whether or not the callbacks recurse.
--- net/sunrpc/svcsock.c | 3 +++ 1 file changed, 3 insertions(+)
net/sunrpc/svcsock.c +3 -0
@@ -1375,6 +1375,9 @@ int svc_addsock(struct svc_serv *serv, s err = -EISCONN ;if (so->state >SS_UNCONNECTED ) goto out; + err = -EBUSY ; +if (so->sk->sk_user_data) + goto out; err = -ENOENT ;if (!try_module_get (THIS_MODULE )) goto out;
Greg Kroah-Hartman
maintainerPATCH 620/2857 SUNRPC: trace an accepted transport before publishing it
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhiling Zou <[email protected]>
commit 06f90cf104fc21ee01e7ef1eb80e092173089b9f upstream.
svc_handle_xprt() publishes a newly accepted transport before tracing it. svc_add_new_temp_xprt() places the transport on sv_tempsocks and clears XPT_BUSY, so another nfsd thread can dequeue it at once. If the peer has already closed the connection, that thread runs svc_delete_xprt(), which drops the list reference, the only reference the new transport holds. trace_svc_xprt_accept() then reads the transport's addresses and network namespace from freed memory.
Before publication the accepting thread owns the transport
exclusively: XPT_BUSY is still set from svc_xprt_init() and the transport is on no list. Emit the tracepoint there.
--- net/sunrpc/svc_xprt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/svc_xprt.c +1 -1
@@ -831,8 +831,8 @@ static int svc_handle_xprt(struct svc_rq newxpt = xprt->xpt_ops->xpo_accept (xprt);if (newxpt) { newxpt->xpt_cred =get_cred (xprt->xpt_cred); -svc_add_new_temp_xprt (serv, newxpt);trace_svc_xprt_accept (newxpt, serv->sv_name); +svc_add_new_temp_xprt (serv, newxpt); }else {module_put (xprt->xpt_class->xcl_owner); }
Greg Kroah-Hartman
maintainerPATCH 621/2857 sunrpc: treat empty auth.unix.gid replies as negative entries
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit a12cc0930235b86b934ade7c077a1935c2ac333d upstream.
When rpc.mountd cannot resolve a uid (getpwuid() or getgrouplist() failure, e.g. while winbind or sssd is briefly unreachable), it answers the auth.unix.gid upcall with zero groups. unix_gid_parse() installs that as a valid positive entry, and svcauth_unix_set_client() then replaces the credential's group list with the empty one on every request, RPCSEC_GSS included via svcauth_gss_set_client(). One failed lookup strips that uid of all supplementary groups on every export for up to mountd's configured TTL (30 minutes by default), long after the NSS backend has recovered.
mountd cannot send an empty list for a successful lookup, since getgrouplist(3) always includes at least the user's primary group, so a zero-group reply can only mean the lookup failed. Record it as a negative entry: unix_gid_find() then returns -ENOENT and svcauth_unix_set_client() keeps the groups the RPC credential already carries. This is the fallback that
commit 3fc605a2aa38 ("[PATCH] knfsd: allow the server to provide a gid list when using AUTH_UNIX authentication") promised when no answer is available, and the same state try_to_negate_entry() already creates when no listener holds the channel open.
--- net/sunrpc/svcauth_unix.c | 7 +++++++ 1 file changed, 7 insertions(+)
net/sunrpc/svcauth_unix.c +7 -0
@@ -536,6 +536,13 @@ static int unix_gid_parse(struct cache_dif (ugp) {struct cache_head *ch; ug.h.flags =0 ; +/* +* mountd sends at least the user's primary group on +* success, so an empty list can only mean the lookup +* failed. Keep the credential's own groups instead. +*/ +if (gids ==0 ) +set_bit (CACHE_NEGATIVE , &ug.h.flags); ug.h.expiry_time = expiry; ch = sunrpc_cache_update(cd, &ug.h, &ugp->h,
Greg Kroah-Hartman
maintainerPATCH 622/2857 KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit bf260dc9e7b8bfcd06c1a8e739797b1cf0917c72 upstream.
When the pCPU where the VMCB was most recently used is switched, reset the ASID generation in both VMCBs, triggering new ASID allocation for the immediate VMRUN as well as the next VMRUN on the other VMCB.
The ASID is shared between vmcb01 and vmcb02, and gets flushed on every nested transition. However, since pCPU tracking is done per VMCB, it is possible for one VMCB to allocate a new ASID when migrated to a new pCPU, and then the other VMCB reuses that ASID on the old pCPU. This can result in the same ASID being used by multiple vCPUs on the old pCPU.
Example scenario:
- vCPU runs on pCPU A, vmcb01 is active, asid=1.
- vCPU migrates to pCPU B, vmcb01 pCPU changes, new asid=2.
- Another vCPU runs on pCPU A and allocates asid=2 as well.
- vCPU migrates back to pCPU A, and then switches to vmcb02 before it runs again with vmcb01.
- No pCPU switch is detected for vmcb02, so VMRUN is done with asid=2.
- Two vCPUs end up using asid=2 on the same pCPU.
Keep the VMCB dirtying to the active VMCB only. Clean bits are tracked by a pCPU for each VMCB, so do not unnecessarily dirty a VMCB if its pCPU does not change.
Additionally, initialize the tracked pCPU for vmcb02 to -1 on nested enablement as hardening, so that a new ASID allocation is always triggered when nested is disabled and re-enabled.
No performance regression was noticed when overcommitting L1 vCPUs in L0 (to force rescheduling), pinning L1 <-> L2 vCPUs, and running CPUID in a tight loop bouncing between 2 vCPUs in L2.
An alternative (and perhaps more proper) fix would be tracking the ASID per-VMCB instead (e.g. [1]). However, that's a more involved change, and it would result in having different ASIDs for L1 and L2 without actually properly maintaining them. It would probably work because all TLB flushes target the current VMCB, and the other VMCB is always flushed on nested transitions, but the code ends up in an arguably more fragile state. Punt a proper clean fix to an incoming (and overdue) overhaul of SVM's ASID usage [2].
[1] https://lore.kernel.org/lkml/[email protected]
[2] https://lore.kernel.org/kvm/[email protected]
--- arch/x86/kvm/svm/nested.c | 1 + arch/x86/kvm/svm/svm.c | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/nested.c +1 -0
@@ -1125,6 +1125,7 @@ int svm_allocate_nested(struct vcpu_svm goto err_free_vmcb02;svm_vcpu_init_msrpm (&svm->vcpu, svm->nested.msrpm); + svm->nested.vmcb02.cpu =-1 ; svm->nested.initialized = true;return 0 ;
arch/x86/kvm/svm/svm.c +15 -4
@@ -3495,14 +3495,25 @@ static void pre_svm_run(struct kvm_vcpustruct vcpu_svm *svm =to_svm (vcpu);/* -* If the previous vmrun of the vmcb occurred on a different physical -* cpu, then mark the vmcb dirty and assign a new asid. Hardware's -* vmcb clean bits are per logical CPU, as are KVM's asid assignments. +* If the previous VMRUN of the VMCB occurred on a different physical +* cpu, then mark the VMCB dirty as hardware's clean bits are per pCPU. +* +* Reset the ASID generation in both VMCBs. This will lead to assigning +* a new ASID now, and then again when switching to the other VMCB. +* However, this is needed as the ASID is shared between the VMCBs, and +* otherwise it would be possible to use an ASID allocated on one pCPU +* on another, for example: +* - vCPU migrates from pCPU A to pCPU B, allocates a new ASID. +* - vCPU migrates back to pCPU A, and then switches the VMCB. +* - The new VMCB does not detect a pCPU change and runs on pCPU A with +* the new ASID allocated on pCPU B, which is potentially used by +* another vCPU/VM. */ if (unlikely (svm->current_vmcb->cpu != vcpu->cpu)) { - svm->current_vmcb->asid_generation =0 ;vmcb_mark_all_dirty (svm->vmcb); svm->current_vmcb->cpu = vcpu->cpu; + svm->vmcb01.asid_generation =0 ; + svm->nested.vmcb02.asid_generation =0 ; }if (sev_guest (vcpu->kvm))
Greg Kroah-Hartman
maintainerPATCH 623/2857 KVM: Use goto to handle errors during memslot preparation
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 23a205797cec86f391d0be886b9bc741e1262063 upstream.
Use a goto to unwind early memslot changes if preparing for a memslot operation fails. This will allow moving the creation of guest_memfd bindings into kvm_set_memslot() without needing to copy+paste the unwind logic.
No functional change intended.
--- virt/kvm/kvm_main.c | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-)
virt/kvm/kvm_main.c +16 -15
@@ -1866,21 +1866,8 @@ static int kvm_set_memslot(struct kvm *k } r =kvm_prepare_memory_region (kvm, old, new, change); -if (r) { -/* -* For DELETE/MOVE, revert the above INVALID change. No -* modifications required since the original slot was preserved -* in the inactive slots. Changing the active memslots also -* release slots_arch_lock. -*/ -if (change ==KVM_MR_DELETE || change ==KVM_MR_MOVE ) { -kvm_activate_memslot (kvm, invalid_slot, old); -kfree (invalid_slot); - }else { -mutex_unlock (&kvm->slots_arch_lock); - } -return r; - } +if (r) + goto err;/* * For DELETE and MOVE, the working slot is now active as the INVALID
@@ -1912,6 +1899,20 @@ static int kvm_set_memslot(struct kvm *kkvm_commit_memory_region (kvm, old, new, change);return 0 ; + +err: +/* +* For DELETE/MOVE, revert the above INVALID change. No modifications +* required since the original slot was preserved in the inactive slots. +* Changing the active memslots also release slots_arch_lock. +*/ +if (change ==KVM_MR_DELETE || change ==KVM_MR_MOVE ) { +kvm_activate_memslot (kvm, invalid_slot, old); +kfree (invalid_slot); + }else { +mutex_unlock (&kvm->slots_arch_lock); + } +return r; } static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
Greg Kroah-Hartman
maintainerPATCH 624/2857 KVM: x86/mmu: Bug the VM if KVM calcs a CPU role with EFER.LMA=1 && CR4.PAE=0
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 34dacbe7ae93f2d3c26cd0bf3e08200b1fa2c180 upstream.
Bug the VM if KVM attempts to construct a CPU role with the should-be- impossible combination of long mode being active without PAE paging being enabled. KVM's MMU construction assumes that EFER.LMA can be set if and only CR4.PAE is set, and will create a completely invalid MMU if that assumption fails. FNAME(walk_addr_generic) already has sanity checks to try and mitigate the fallout, but attempt to catch such bugs earlier, as this is (at least) the second time KVM has had bugs that escaped into FNAME(walk_addr_generic), and it's entirely possible the bad state could cause problems elsewhere.
--- arch/x86/kvm/mmu/mmu.c | 3 +++ 1 file changed, 3 insertions(+)
arch/x86/kvm/mmu/mmu.c +3 -0
@@ -4990,6 +4990,9 @@ kvm_calc_cpu_role(struct kvm_vcpu *vcpu,return role; } +if (KVM_BUG_ON (____is_efer_lma (regs) && !____is_cr4_pae (regs), vcpu->kvm)) + *(u64 *)®s->efer &= ~EFER_LMA ; + role.base.efer_nx =____is_efer_nx (regs); role.base.cr0_wp =____is_cr0_wp (regs); role.base.smep_andnot_wp =____is_cr4_smep (regs) && !____is_cr0_wp (regs);
Greg Kroah-Hartman
maintainerPATCH 625/2857 KVM: x86: Preserve DR6.BLD (Bus Lock Detect) when delivering #DB payload
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 719a1d58bf43edd03b271df90b67c58c1e9a7da4 upstream.
Preserve Bus Lock Detect if it isn't present in the payload. Unlike RTM, which is explicitly modified on every #DB, DR6.BLD is modified if and only if the #DB is due to a (coincident) Bus Lock Detect.
Per Intel's SDM:
Other debug exceptions do not modify this bit.
And AMD's APM
All other #DB exceptions leave DR6[BLD] unmodified,
Restore the explicit RTM handling that was clobbered by commit 9a3ecd5e2aa1 ("KVM: X86: Rename DR6_INIT to DR6_ACTIVE_LOW"), as the semantics of any given bit are feature specific, i.e. are obviously not consistent for active-high versus active-low. In other words, while the bug was technically introduced when support for Bus Lock Detect was added, it's really that attempt to genericize handling of active-low bits that set KVM up to fail.
--- arch/x86/kvm/x86.c | 52 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 22 deletions(-)
arch/x86/kvm/x86.c +30 -22
@@ -574,30 +574,37 @@ void kvm_deliver_exception_payload(strucswitch (ex->vector) {case DB_VECTOR :/* -* "Certain debug exceptions may clear bit 0-3. The -* remaining contents of the DR6 register are never -* cleared by the processor". -*/ - vcpu->arch.dr6 &= ~DR_TRAP_BITS ; -/* -* In order to reflect the #DB exception payload in guest -* dr6, three components need to be considered: active low -* bit, FIXED_1 bits and active high bits (e.g. DR6_BD, -* DR6_BS and DR6_BT) -* DR6_ACTIVE_LOW contains the FIXED_1 and active low bits. -* In the target guest dr6: -* FIXED_1 bits should always be set. -* Active low bits should be cleared if 1-setting in payload. -* Active high bits should be set if 1-setting in payload. +* DR6 is a mess. Reserved/unused bits are fixed-to-1, and so +* to maintain backwards compatibility with existing software, +* features that use previously-reserved bits have active-low +* semantics, i.e. clear the bit when the feature is present in +* the payload. +* +* Further complicating matters, some DR6 bits are preserved by +* hardware, while others are explicitly modified on every #DB. +* The trap bits are always set based on the payload, as is the +* RTM flag (but it's active low). All other bits are modified +* if and only if a relevant debug exception occurs, e.g. BD, +* BS, and BT are never cleared by hardware, and BLD is never +* set by hardware (when supported, excepting RESET). * -* Note, the payload is compatible with the pending debug -* exceptions/exit qualification under VMX, that active_low bits -* are active high in payload. -* So they need to be flipped for DR6. +* Lastly, the payload does NOT have active-low semantics, e.g. +* so that it's compatible VMX's pending debug exceptions and +* qualification fields, and to avoid bleeding the DR6 madness +* into other KVM code. +* +* To compute DR6: +* +* 1. "Reset" the bits that are modified on all #DBs +* 2. Clear active-low bits that are present in the payload. +* 3. Set active-high bits that are present in the payload. +* 4. Clear fixed-0 bits. +* 5. Set fixed-1 bits. */ - vcpu->arch.dr6 |=DR6_ACTIVE_LOW ; - vcpu->arch.dr6 |= ex->payload; - vcpu->arch.dr6 ^= ex->payload &DR6_ACTIVE_LOW ; + vcpu->arch.dr6 &= ~DR_TRAP_BITS ; + vcpu->arch.dr6 |=DR6_RTM ; + vcpu->arch.dr6 &= ~(ex->payload &DR6_ACTIVE_LOW ); + vcpu->arch.dr6 |= (ex->payload & ~DR6_ACTIVE_LOW );/* * The #DB payload is defined as compatible with the 'pending
@@ -606,6 +613,7 @@ void kvm_deliver_exception_payload(struc* breakpoint), it is reserved and must be zero in DR6. */ vcpu->arch.dr6 &= ~BIT (12 ); + vcpu->arch.dr6 |=DR6_FIXED_1 ;break ;case PF_VECTOR : vcpu->arch.cr2 = ex->payload;
Greg Kroah-Hartman
maintainerPATCH 626/2857 KVM: x86: Request event processing for exception VM-Exits
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Loc Nguyen <[email protected]>
commit 88b23a2e8286b7016c3b58dc10093cf28c22aa3d upstream.
Request event processing whenever kvm_queue_exception_vmexit() queues an exception VM-Exit. Most callers reach the helper through kvm_multiple_exception(), which already sets KVM_REQ_EVENT, but nested asynchronous page faults call it directly.
Without another event request, vcpu_enter_guest() skips kvm_check_and_inject_events() and re-enters L2. A subsequent VM-Exit can clear the pending exception while reconstructing vectoring state, losing the synthetic #PF VM-Exit. The APF reason remains PAGE_NOT_PRESENT and a later regular #PF can consume the stale value.
Setting KVM_REQ_EVENT in the common helper ensures that L1 receives the queued VM-Exit before KVM re-enters L2.
--- arch/x86/kvm/x86.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/x86.c +2 -0
@@ -631,6 +631,8 @@ static void kvm_queue_exception_vmexit(s {struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit; +kvm_make_request (KVM_REQ_EVENT , vcpu); + ex->vector = vector; ex->injected = false; ex->pending = true;
Greg Kroah-Hartman
maintainerPATCH 627/2857 KVM: x86: Zero reserved synic flags when delivering message to avoid stack leak
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 2616f497506a772db53e7bb1024cde50b4c165e0 upstream.
Ensure all reserved flags are zeroed when setting the msg_pending flag as part of SynIC message delivery, as setting only msg_pending can leak seven bits of kernel stack data to the guest. E.g. gcc typically uses a bitwise-OR to set the msg_pending flag, without initializing the on-stack variable.
Precisely zero the flags, e.g. as opposed to zeroing the entire structure, to make it somewhat more obvious that the flags *need* to be zeroed. E.g. it would be quite easy to misread the initial read of guest memory and think that zeroing the entire structure is completely superfluous.
--- arch/x86/kvm/hyperv.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/hyperv.c +2 -0
@@ -772,7 +772,9 @@ static int synic_deliver_msg(struct kvm_if (no_retry)return 0 ; + hv_hdr.message_flags.asu8 =0 ; hv_hdr.message_flags.msg_pending =1 ; + r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_flags, msg_off +
Greg Kroah-Hartman
maintainerPATCH 628/2857 KVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit abbbe5ff83e7c9ed3a4d61b73011f1df7bf87907 upstream.
kvmppc_hv_find_lock_hpte() requires virtual-mode callers to run with preemption disabled, because it can return with HPTE_V_HVLOCK still held until the caller later unlocks the HPTE. Existing virtual-mode callers in book3s_64_mmu_hv.c already follow that rule.
Two virtual-mode call paths do not:
1. kvmppc_handle_exit_hv() calls kvmppc_hpte_hv_fault() for hash-mode data-side and instruction-side faults after guest exit, with preemption already enabled. kvmppc_hpte_hv_fault() calls kvmppc_hv_find_lock_hpte() directly.
2. kvmppc_pseries_do_hcall() executes virtual-mode handlers for HPT hcalls via kvmppc_pseries_do_hpt_hcall() with preemption enabled. The handlers for H_ENTER, H_REMOVE, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, and H_BULK_REMOVE spin on try_lock_hpte() or lock_rmap(), and H_ENTER also reaches kvmppc_do_h_enter(), which uses arch_spin_lock() on kvm->mmu_lock. That raw lock choice is intentional because kvmppc_do_h_enter() is also used by real-mode callers, so the correct fix is to establish the proper preemption context at the virtual-mode caller boundary.
If a vCPU thread is preempted while holding HPTE_V_HVLOCK, any other thread on the same CPU trying to acquire the same bit-lock can spin indefinitely. The same applies to lock_rmap() users and to the H_ENTER path while holding the raw mmu_lock.
Fix this by adding preempt_disable()/preempt_enable() pairs around the two kvmppc_hpte_hv_fault() call sites in kvmppc_handle_exit_hv(), and around the kvmppc_pseries_do_hpt_hcall() invocation in kvmppc_pseries_do_hcall(). Targeting only the HPT hcall helper avoids wrapping non-HPT hcalls (such as H_RTAS, H_CONFER, H_REGISTER_VPA) that perform page faults, blocking memory allocations, or context switches.
--- arch/powerpc/kvm/book3s_hv.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/powerpc/kvm/book3s_hv.c +6 -0
@@ -1138,9 +1138,11 @@ int kvmppc_pseries_do_hcall(struct kvm_vcase H_CLEAR_REF :case H_PROTECT :case H_BULK_REMOVE : +preempt_disable (); idx =srcu_read_lock (&kvm->srcu); ret =kvmppc_pseries_do_hpt_hcall (vcpu, req);srcu_read_unlock (&kvm->srcu, idx); +preempt_enable ();if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
@@ -1750,8 +1752,10 @@ static int kvmppc_handle_exit_hv(structelse vsid = vcpu->arch.fault_gpa; +preempt_disable (); err =kvmppc_hpte_hv_fault (vcpu, vcpu->arch.fault_dar, vsid, vcpu->arch.fault_dsisr, true); +preempt_enable ();if (err ==0 ) { r =RESUME_GUEST ; }else if (err ==-1 || err ==-2 ) {
@@ -1795,8 +1799,10 @@ static int kvmppc_handle_exit_hv(structelse vsid = vcpu->arch.fault_gpa; +preempt_disable (); err =kvmppc_hpte_hv_fault (vcpu, vcpu->arch.fault_dar, vsid, vcpu->arch.fault_dsisr, false); +preempt_enable ();if (err ==0 ) { r =RESUME_GUEST ; }else if (err ==-1 ) {
Greg Kroah-Hartman
maintainerPATCH 629/2857 KVM: PPC: Fix get_d_signext() 12-bit displacement for paired-single D-form
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 31895b0ff96778b524c74b43a108090581271603 upstream.
get_d_signext() has two compounding bugs since its introduction in 2010:
1. The extraction mask 0x8FF silently drops bits 8-10 of the 12-bit D field (PPC ISA bits 21-23), corrupting any displacement that has any of those bits set.
2. The sign-magnitude idiom "-(d & 0x7ff)" is wrong for two's-complement:
for D=0xFFC (encoding of -4) it returns -252 instead of -4.
Together these errors produce a wrong effective address for psq_l, psq_lu, psq_st, and psq_stu whenever the displacement is negative or is a positive value >= 0x100 with bits 8-10 set — essentially any real-world paired- single stack-relative access.
The D field occupies the bottom 12 bits of the instruction word (confirmed by the adjacent W and I extractions via inst_get_field(inst,16,16) and inst_get_field(inst,17,19)). Replace the open-coded logic with the standard sign_extend32(inst & 0xfff, 11), which correctly performs two's-complement sign extension from 12 bits to 32 bits.
--- arch/powerpc/kvm/book3s_paired_singles.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-)
arch/powerpc/kvm/book3s_paired_singles.c +1 -6
@@ -479,12 +479,7 @@ static bool kvmppc_inst_is_paired_singlestatic int get_d_signext (u32 inst) { -int d = inst &0x8ff ; - -if (d &0x800 ) -return -(d &0x7ff ); - -return (d &0x7ff ); +return sign_extend32 (inst &0xfff ,11 ); } static int kvmppc_ps_three_in(struct kvm_vcpu *vcpu, bool rc,
Greg Kroah-Hartman
maintainerPATCH 630/2857 HID: zydacron: validate key report length
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 9932c9af185f8586e883d44ca562c12f4487c762 upstream.
The HID core invokes raw_event callbacks before validating the report length. zc_raw_event() verifies the report ID in byte zero and then reads the key code from byte one for report IDs 0x02 and 0x03 without checking that the second byte is present.
A one-byte report reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in zc_raw_event+0x54c/0x580 Read of size 1 by task hidtrigger/93 Call Trace: zc_raw_event+0x54c/0x580 __hid_input_report+0x2ef/0x3a0 inject_store+0x479/0x490 [faketrans]
Require both the report ID and key code before processing the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-zydacron.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-zydacron.c +3 -0
@@ -114,6 +114,9 @@ static int zc_raw_event(struct hid_devicunsigned key;unsigned short index; +if (size <2 ) +return 0 ; +if (report->id == data[0 ] && (hdev->claimed &HID_CLAIMED_INPUT )) {/* break keys */
Greg Kroah-Hartman
maintainerPATCH 631/2857 HID: amd_sfh: Remove unsupported motion-state field from accelerometer report
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Basavaraj Natikar <[email protected]>
commit 6ff86122906357687735dd379c6279e3b2fa26af upstream.
The accelerometer HID report descriptor declares a trailing motion-state field (usage 0x0451), but the Sensor Fusion Hub never reports this data, so each accelerometer input report is one byte shorter than the descriptor advertises.
This was previously harmless because hid-core zero-padded short reports. Since commit 0a3fe972a7cb ("HID: core: Mitigate potential OOB by removing bogus memset()") such reports are rejected instead:
hid-sensor-hub 0020:1022:0001.0003: Event data for report 1 was too short (15 vs 14)
As a result the accelerometer input events are dropped and screen auto-rotation stops working on AMD SFH systems.
Remove the motion-state field from the accelerometer report descriptor and drop the unused in_accel_shake_detection member, so the descriptor matches the report actually provided by the hardware.
--- drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_desc.h | 2 -- drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_report_desc.h | 7 ------- 2 files changed, 9 deletions(-)
drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_desc.h +0 -2
@@ -48,8 +48,6 @@ struct accel3_input_report {int in_accel_x_value;int in_accel_y_value;int in_accel_z_value; -/* include if required to support the "shake" event */ -u8 in_accel_shake_detection; } __packed;struct gyro_feature_report {
drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_report_desc.h +0 -7
@@ -169,13 +169,6 @@ static const u8 accel3_report_descriptor0x95 ,1 ,/* HID report count (1) */ 0x55 ,0x0E ,/* HID unit exponent(0x0E) */ 0X81 ,0x02 ,/* HID Input (Data_Arr_Abs) */ - -0x0A ,0x51 ,0x04 ,/* HID usage sensor data motion state */ -0x15 ,0 ,/* HID logical Min_8(0) False = Still*/ -0x25 ,1 ,/* HID logical Min_8(1) True = In motion */ -0x75 ,8 ,/* HID report size(8) */ -0x95 ,1 ,/* HID report count (1) */ -0X81 ,0x02 ,/* HID Input (Data_Arr_Abs) */ 0xC0 /* HID end collection */ };
Greg Kroah-Hartman
maintainerPATCH 632/2857 HID: amd_sfh: Use report type from request node
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Basavaraj Natikar <[email protected]>
commit 85f1bea97f1909f81577cfcf3e4db9017e7f5337 upstream.
Use report type from request node while sending feature and input reports to HID core. The cli_data report type array is never assigned and feature reports are sent as input reports.
--- drivers/hid/amd-sfh-hid/amd_sfh_client.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hid/amd-sfh-hid/amd_sfh_client.c +2 -2
@@ -90,7 +90,7 @@ void amd_sfh_work(struct work_struct *wo cli_data->feature_report[current_index]);if (report_size)hid_input_report (cli_data->hid_sensor_hubs[current_index], - cli_data->report_type[current_index], + node_type, cli_data->feature_report[current_index], report_size,0 );else pr_err ("AMDSFH: Invalid report size\n" );
@@ -99,7 +99,7 @@ void amd_sfh_work(struct work_struct *wo report_size = mp2_ops->get_in_rep (current_index, sensor_index, report_id, in_data);if (report_size)hid_input_report (cli_data->hid_sensor_hubs[current_index], - cli_data->report_type[current_index], + node_type, in_data->input_report[current_index], report_size,0 );else pr_err ("AMDSFH: Invalid report size\n" );
Greg Kroah-Hartman
maintainerPATCH 633/2857 HID: core: Fix out-of-bounds left shift by 32 in s32ton()
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alan Stern <[email protected]>
commit 5fe63b415c636c7f4f6848a8e53bdd4bbf0c300d upstream.
Syzbot reported an out-of-bounds shift (32-bit integer shifted left by
32) in the s32ton() routine in the HID core. This routine converts a signed 32-bit integer to a signed n-bit integer, and it caps the value of n at 32. But when n == 32 there's no need to do anything; it can simply return the input value. This will avoid calculating (1 << n) when n is 32, which was the cause of the invalid shift.
--- drivers/hid/hid-core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hid/hid-core.c +2 -2
@@ -1368,8 +1368,8 @@ static u32 s32ton(__s32 value, unsignedif (!value || !n)return 0 ; -if (n >32 ) - n =32 ; +if (n >=32 ) +return (u32 ) value; a = value >> (n -1 );
Greg Kroah-Hartman
maintainerPATCH 634/2857 HID: cougar: reject short special-key reports
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c6c0df8a4b73a0d563c5e64de640ef5ff525fc82 upstream.
The HID core invokes raw_event callbacks before validating the report length. cougar_raw_event() reads the key code and action from offsets one and two without checking that those bytes are present. A short report on the special interface can therefore cause an out-of-bounds read.
Consume reports that do not contain the action field before accessing the fixed offsets, consistent with the callback's handling of other reports on the special interface.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cougar.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-cougar.c +3 -0
@@ -270,6 +270,9 @@ static int cougar_raw_event(struct hid_dif (!shared->enabled || !shared->input)return -EPERM ; +if (size <=COUGAR_FIELD_ACTION ) +return -EPERM ; + code = data[COUGAR_FIELD_CODE ]; action = data[COUGAR_FIELD_ACTION ];for (i =0 ; cougar_mapping[i][0 ]; i++) {
Greg Kroah-Hartman
maintainerPATCH 635/2857 HID: cp2112: validate response report lengths
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit fc54e71a063c0dcc4bceba6d0f71805a9b84082d upstream.
The HID core invokes raw_event callbacks before validating the report length. cp2112_raw_event() reads every field of a transfer status response without checking size. For a data response, it reads the length at offset two and copies that many bytes from offset three, again without ensuring that the input report contains them.
Require a complete transfer status structure. For data responses, first require the header and then ensure the clamped payload length fits in the received report before copying it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cp2112.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/hid/hid-cp2112.c +8 -1
@@ -1434,6 +1434,9 @@ static int cp2112_raw_event(struct hid_dswitch (data[0 ]) {case CP2112_TRANSFER_STATUS_RESPONSE : +if (size <sizeof (*xfer)) +return 0 ; +hid_dbg (hdev,"xfer status: %02x %02x %04x %04x\n" , xfer->status0, xfer->status1,be16_to_cpu (xfer->retries),be16_to_cpu (xfer->length));
@@ -1467,11 +1470,16 @@ static int cp2112_raw_event(struct hid_datomic_set (&dev->xfer_avail,1 );break ;case CP2112_DATA_READ_RESPONSE : +if (size <3 ) +return 0 ; +hid_dbg (hdev,"read response: %02x %02x\n" , data[1 ], data[2 ]); dev->read_length = data[2 ];if (dev->read_length >sizeof (dev->read_data)) dev->read_length =sizeof (dev->read_data); +if (dev->read_length > size -3 ) +return 0 ;memcpy (dev->read_data, &data[3 ], dev->read_length);atomic_set (&dev->read_avail,1 );
@@ -1498,4 +1506,3 @@ module_hid_driver(cp2112_driver);MODULE_DESCRIPTION ("Silicon Labs HID USB to SMBus master bridge" );MODULE_AUTHOR ("David Barksdale <[email protected]>" );MODULE_LICENSE ("GPL" ); -
Greg Kroah-Hartman
maintainerPATCH 636/2857 HID: elo: reject short touchscreen reports
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1cb92fcb2ac344d78737e3c5cb7b061dfb2850b1 upstream.
The HID core invokes raw_event callbacks before validating the report length. elo_raw_event() only checks the first-byte packet marker before elo_process_data() reads coordinates, flags, and pressure through offset seven. A truncated packet beginning with the expected marker can therefore cause an out-of-bounds read.
Require the complete eight-byte SmartSet packet before parsing it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-elo.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-elo.c +3 -0
@@ -85,6 +85,9 @@ static int elo_raw_event(struct hid_deviif (!(hdev->claimed &HID_CLAIMED_INPUT ) ||list_empty (&hdev->inputs))return 0 ; +if (size <ELO_SMARTSET_PACKET_SIZE ) +return 0 ; + hidinput = list_first_entry(&hdev->inputs, struct hid_input, list);switch (report->id) {
Greg Kroah-Hartman
maintainerPATCH 637/2857 HID: logitech-dj: validate unnumbered keyboard reports
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c2deafcb4c8227771f768d77ed3c0a489250e9b2 upstream.
The HID core invokes raw_event callbacks before validating the report length. For an unnumbered keyboard report, logi_dj_raw_event() uses the second byte as temporary storage while prepending a report ID. A one-byte report therefore makes both the initial write and the later restoration access data beyond the received report.
Reject unnumbered keyboard reports that do not provide the temporary byte.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-logitech-dj.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-logitech-dj.c +3 -0
@@ -1682,6 +1682,9 @@ static int logi_dj_raw_event(struct hid_if (!hdev->report_enum[HID_INPUT_REPORT ].numbered) {if (djrcv_dev->unnumbered_application ==HID_GD_KEYBOARD ) { +if (size <2 ) +return false; +/* * For the keyboard, we can reuse the same report by * using the second byte which is constant in the USB
Greg Kroah-Hartman
maintainerPATCH 638/2857 HID: mcp2221: validate response report length
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1ae40774d386b7a51e4799200106429a7e14e8ec upstream.
MCP2221 responses are 64-byte reports, but mcp2221_raw_event() currently accepts any report of at least four bytes. Several response handlers read far beyond that minimum. In particular, the I2C status response reads offset 20 and copies ADC samples starting at offset 50. Other GPIO, SRAM, and flash response handlers also access fixed offsets beyond byte three.
The HID core invokes raw_event callbacks before validating the report length, so a truncated response can cause an out-of-bounds read. Require a complete protocol report before dispatching any response handler.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-mcp2221.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/hid-mcp2221.c +1 -1
@@ -748,7 +748,7 @@ static int mcp2221_raw_event(struct hid_u8 *buf;struct mcp2221 *mcp =hid_get_drvdata (hdev); -if (size <4 ) +if (size <sizeof (mcp->txbuf))return 0 ;switch (data[0 ]) {
Greg Kroah-Hartman
maintainerPATCH 639/2857 HID: picoLCD: check for fb_deferred_io_init() error
In reply to Greg Kroah-Hartman6.1-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
commit feade898fc958ff355101adf12d5632272e64220 upstream.
fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.
Currently picolcd_init_framebuffer() ignores its return value.
Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.
When the file is subsequently opened, fb_open() will dereference a NULL pointer (calling fb_deferred_io_open()).
Fix this by checking for the error.
Also correct cleanup ordering - defio is initialised after the sysfs file, so cleanup defio first.
--- drivers/hid/hid-picolcd_fb.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/hid/hid-picolcd_fb.c +9 -3
@@ -558,17 +558,23 @@ int picolcd_init_framebuffer(struct pico goto err_cleanup; } -fb_deferred_io_init (info); + error =fb_deferred_io_init (info); +if (error) { +dev_err (dev,"failed to initialize deferred I/O\n" ); + goto err_sysfs; + } + error =register_framebuffer (info);if (error) {dev_err (dev,"failed to register framebuffer\n" ); - goto err_sysfs; + goto err_defio; }return 0 ; +err_defio: +fb_deferred_io_cleanup (info); err_sysfs:device_remove_file (dev, &dev_attr_fb_update_rate); -fb_deferred_io_cleanup (info); err_cleanup: data->fb_info =NULL ;