Skip to contentSkip to conversation

6.18.66-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 995 messages Nov 25 Page 9 of 9

Subsystems (3)
lore
Share & tools
lore
author maintainer
#908 lore raw

PATCH 907/990 usb: usbtest: prevent divide by zero in simple_io() with zero length

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: YuanZhe Liu <[email protected]>

commit fdaca138694111153f96c7d76877734b9dbf0e01 upstream.

A divide error oops was observed in simple_io():

	usbtest 1-1:1.0: TEST 3:  write/1 0..0 bytes 16307 times
	Oops: divide error: 0000 [#1] SMP KASAN
	RIP: 0010:simple_io+0x2c4/0x540 drivers/usb/misc/usbtest.c:497

The variable-length tests (test 3 and test 4) compute the next URB size with "len %= max", where max is the original urb->transfer_buffer_length. However, when a zero-length transfer is requested (param->length == 0), simple_alloc_urb() still returns a valid URB with transfer_buffer_length set to 0. On the first vary update, "len %= max" divides by zero and the kernel oopses.

Commit 564e69893c63 ("USB: usbtest: prevent a divide by zero bug") added the equivalent zero check to alloc_sglist(), which covers the scatterlist tests (test 7/8), but the single-URB variable-length path in simple_io() was left unprotected.

Fix this by returning -EINVAL early from simple_io() when vary is requested but max is zero, so the divide by zero never occurs. Zero-length transfers without vary remain valid for the other callers of simple_io().

---
 drivers/usb/misc/usbtest.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/usb/misc/usbtest.c +3 -0
@@ -466,6 +466,9 @@ static int simple_io(
 	int			retval = 0;
 	unsigned long		expire;
 
+	if (vary && !max)
+		return -EINVAL;
+
 	urb->context = &completion;
 	while (retval == 0 && iterations-- > 0) {
 		init_completion(&completion);
author maintainer
#909 lore raw

PATCH 908/990 usb: typec: ucsi: Set ucsi->connector before enabling notifications

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Uttkarsh Aggarwal <[email protected]>

commit 5b4b83c2ffe8740f6f3e54ea4d4962a62c063ef1 upstream.

In ucsi_init(), ucsi->connector is assigned only after the UCSI_SET_NOTIFICATION_ENABLE command completes. But once that command is sent, the PPM is free to raise a connector change notification at any time, which is handled through:

    ucsi_notify_common() -> ucsi_connector_change()

ucsi_connector_change() indexes into ucsi->connector to get the connector and schedule its work item. If this notification arrives before ucsi_init() reaches the "ucsi->connector = connector;" line, ucsi->connector is still NULL and the driver crashes dereferencing it.

Fix this by setting ucsi->connector right after the connectors are registered, before notifications are enabled, so it is always valid by the time a connector change event can be delivered. Also clear ucsi->connector in the err_unregister path so it isn't left pointing at freed memory if a later step in ucsi_init() fails.

---
 drivers/usb/typec/ucsi/ucsi.c |   10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/ucsi.c +9 -1
@@ -2041,6 +2041,14 @@ static int ucsi_init(struct ucsi *ucsi)
 			goto err_unregister;
 	}
 
+	/*
+	 * Set ucsi->connector before enabling notifications. A connector
+	 * change event can be handled as soon as the notifications are
+	 * enabled below, and ucsi_connector_change() indexes into
+	 * ucsi->connector, so it must not be NULL at that point.
+	 */
+	ucsi->connector = connector;
+
 	/* Enable all supported notifications */
 	ntfy = ucsi_get_supported_notifications(ucsi);
 	command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
@@ -2048,7 +2056,6 @@ static int ucsi_init(struct ucsi *ucsi)
 	if (ret < 0)
 		goto err_unregister;
 
-	ucsi->connector = connector;
 	ucsi->ntfy = ntfy;
 
 	mutex_lock(&ucsi->ppm_lock);
@@ -2062,6 +2069,7 @@ static int ucsi_init(struct ucsi *ucsi)
 	return 0;
 
 err_unregister:
+	ucsi->connector = NULL;
 	for (con = connector; con->port; con++)
 		ucsi_unregister_port(con);
 	for (i = 0; i < ucsi->cap.num_connectors; i++)
author maintainer
#910 lore raw

PATCH 909/990 usb: xhci: disable the correct slot on alloc_dev failure

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xu Rao <[email protected]>

commit 2f2fe3201029ffc215b46ac40a0a9587715bc43a upstream.

xhci_alloc_dev() stores the Slot ID returned by the Enable Slot command in the local slot_id variable. udev->slot_id is updated only after xhci_alloc_virt_device() succeeds.

If endpoint resource reservation or virtual device allocation fails before that update, the error path passes udev->slot_id to xhci_disable_and_free_slot(). During initial enumeration this is slot 0. When reallocating a device whose virtual device is missing or belongs to another usb_device, udev->slot_id may contain a stale Slot ID. The newly enabled slot can therefore remain active, or the wrong slot can be disabled.

Pass slot_id, which identifies the slot enabled by this invocation. xhci_disable_and_free_slot() already handles a missing xhci->devs entry.

---
 drivers/usb/host/xhci.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/usb/host/xhci.c +1 -1
@@ -4299,7 +4299,7 @@ int xhci_alloc_dev(struct usb_hcd *hcd,
 	return 1;
 
 disable_slot:
-	xhci_disable_and_free_slot(xhci, udev->slot_id);
+	xhci_disable_and_free_slot(xhci, slot_id);
 
 	return 0;
 }
author maintainer
#911 lore raw

PATCH 910/990 usb: gadget: f_mass_storage: take filesem in nofua store to fix backing-file UAF

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yu Zhang <[email protected]>

commit 450fa94d7ae9fc91c3df525f5d1322bf8fecf7b2 upstream.

fsg_store_nofua() syncs the LUN's backing file when switching from async to sync mode:

	if (!nofua && curlun->nofua)
		fsg_lun_fsync_sub(curlun);

fsg_lun_fsync_sub() dereferences curlun->filp (vfs_fsync(filp)). Unlike every other store that touches the backing file -- fsg_store_ro() and fsg_store_cdrom() (down_read), fsg_store_file() (down_write) -- fsg_store_nofua() holds no filesem while doing so.

A concurrent close of the backing file runs under down_write(filesem) and does fput(curlun->filp) in fsg_lun_close() (fsg_store_file() with an empty path, the SCSI START_STOP eject in do_start_stop(), or forced_eject), so it can free the file while fsg_store_nofua() is dereferencing it:

	BUG: KASAN: slab-use-after-free in vfs_fsync+0x20/0xe0
	 vfs_fsync+0x20/0xe0
	 fsg_lun_fsync_sub+0xa0/0xd0
	 fsg_store_nofua+0x138/0x160
	 configfs_write_iter+0x1a7/0x250
	 vfs_write+0x5df/0x940
	Allocated by task 3459:
	 fsg_store_file+0x150/0x1f0
	 configfs_write_iter+0x1a7/0x250
	Freed by task 3459:
	 __fput+0x456/0x6c0
	 __fput_deferred+0x10d/0x330
	 fsg_store_file+0x9e/0x1f0
	 configfs_write_iter+0x1a7/0x250

Hold filesem for read around the fsync in fsg_store_nofua() so the backing file cannot be closed underneath it. The lock is only needed when the fsync actually runs, so it is taken only in that branch.

Reproduced on a mass_storage gadget over dummy_hcd by writing lun.N/nofua (1 then 0) from one task while another task rewrites and clears lun.N/file.

---
 drivers/usb/gadget/function/f_mass_storage.c |    8 ++++++--
 drivers/usb/gadget/function/storage_common.c |    7 +++++--
 drivers/usb/gadget/function/storage_common.h |    3 ++-
 3 files changed, 13 insertions(+), 5 deletions(-)
drivers/usb/gadget/function/f_mass_storage.c +6 -2
@@ -2668,8 +2668,9 @@ static ssize_t nofua_store(struct device
 			   const char *buf, size_t count)
 {
 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
+	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
 
-	return fsg_store_nofua(curlun, buf, count);
+	return fsg_store_nofua(curlun, filesem, buf, count);
 }
 
 static ssize_t file_store(struct device *dev, struct device_attribute *attr,
@@ -3247,7 +3248,10 @@ static ssize_t fsg_lun_opts_nofua_show(s
 static ssize_t fsg_lun_opts_nofua_store(struct config_item *item,
 				       const char *page, size_t len)
 {
-	return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len);
+	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
+	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
+
+	return fsg_store_nofua(opts->lun, &fsg_opts->common->filesem, page, len);
 }
 
 CONFIGFS_ATTR(fsg_lun_opts_, nofua);
drivers/usb/gadget/function/storage_common.c +5 -2
@@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *cur
 }
 EXPORT_SYMBOL_GPL(fsg_store_ro);
 
-ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count)
+ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem,
+			const char *buf, size_t count)
 {
 	bool		nofua;
 	int		ret;
@@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *
 		return ret;
 
 	/* Sync data when switching from async mode to sync */
-	if (!nofua && curlun->nofua)
+	if (!nofua && curlun->nofua) {
+		guard(rwsem_read)(filesem);
 		fsg_lun_fsync_sub(curlun);
+	}
 
 	curlun->nofua = nofua;
 
drivers/usb/gadget/function/storage_common.h +2 -1
@@ -210,7 +210,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *c
 ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf);
 ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem,
 		     const char *buf, size_t count);
-ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count);
+ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem,
+			const char *buf, size_t count);
 ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
 		       const char *buf, size_t count);
 ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem,
author maintainer
#912 lore raw

PATCH 911/990 usb: gadget: f_midi: fix UAF race during IN request handling

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sonali Pradhan <[email protected]>

commit 78a8d6537f1de34770e460edee360b556ef40427 upstream.

f_midi_disable() drains and frees pre-allocated IN requests from in_req_fifo without holding midi->transmit_lock. If f_midi_transmit() runs concurrently on the workqueue, f_midi_do_transmit() can peek a request from in_req_fifo and write into its buffer while f_midi_disable() frees it, leading to a use-after-free.

Additionally, when usb_ep_queue() fails in f_midi_do_transmit() (such as with -ESHUTDOWN when the endpoint is disabled concurrently), it resets req->length = 0 and returns active instead of the error code, causing the do-while loop in f_midi_transmit() to keep spinning under midi->transmit_lock until the substream is drained.

Fix this by acquiring midi->transmit_lock in f_midi_disable() while releasing IN requests from in_req_fifo, and returning the error code from f_midi_do_transmit() when usb_ep_queue() fails so f_midi_transmit() aborts immediately and drops active substreams.

Fixes e1e3d7ec5da3 ("usb: gadget: f_midi: pre-allocate IN requests")
Cc stable <[email protected]>
---
 drivers/usb/gadget/function/f_midi.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/usb/gadget/function/f_midi.c +4 -0
@@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_fu
 	struct f_midi *midi = func_to_midi(f);
 	struct usb_composite_dev *cdev = f->config->cdev;
 	struct usb_request *req = NULL;
+	unsigned long flags;
 
 	DBG(cdev, "disable\n");
 
@@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_fu
 	usb_ep_disable(midi->out_ep);
 
 	/* release IN requests */
+	spin_lock_irqsave(&midi->transmit_lock, flags);
 	while (kfifo_get(&midi->in_req_fifo, &req))
 		free_ep_req(midi->in_ep, req);
+	spin_unlock_irqrestore(&midi->transmit_lock, flags);
 
 	f_midi_drop_out_substreams(midi);
 }
@@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_m
 		ERROR(midi, "%s failed to queue req: %d\n",
 		      midi->in_ep->name, err);
 		req->length = 0; /* Re-use request next time. */
+		return err;
 	} else {
 		/* Upon success, put request at the back of the queue. */
 		kfifo_skip(&midi->in_req_fifo);
author maintainer
#913 lore raw

PATCH 912/990 usb: gadget: f_ncm: restart the TX timer if the TX freelist is empty

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cosmin Tanislav <[email protected]>

commit 78585f90feb3bbaf3b1c642294c8c47e451dc3cf upstream.

ncm_wrap_ntb() aggregates datagrams into a pending NTB, which is sent either when it becomes full, or after 300us since the NTB was started, using ndo_start_xmit() (eth_start_xmit()).

ndo_start_xmit() returns NETDEV_TX_BUSY when the TX freelist is empty.

For regular packets this is fine since the networking core will requeue them, but for timer-flushed packets there is no logic to handle this situation, and HRTIMER_NORESTART is returned from ncm_tx_timeout() without checking eth_start_xmit()'s return value.

Under sustained TX saturation the request freelist is empty most of the time. Since the timer is never restarted, small packets keep getting accumulated into the NTB, until either TX_MAX_NUM_DPE packets are stored or NTB_DEFAULT_IN_SIZE is reached, which is an unknown amount of time.

Check the return value of ndo_start_xmit() and restart the timer after another 300us.

---
 drivers/usb/gadget/function/f_ncm.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/usb/gadget/function/f_ncm.c +6 -1
@@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeo
 {
 	struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer);
 	struct net_device *netdev = READ_ONCE(ncm->netdev);
+	netdev_tx_t ret;
 
 	if (netdev) {
 		/* XXX This allowance of a NULL skb argument to ndo_start_xmit
@@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeo
 		 *
 		 * This will call directly into u_ether's eth_start_xmit()
 		 */
-		netdev->netdev_ops->ndo_start_xmit(NULL, netdev);
+		ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev);
+		if (ret == NETDEV_TX_BUSY) {
+			hrtimer_forward_now(data, TX_TIMEOUT_NSECS);
+			return HRTIMER_RESTART;
+		}
 	}
 	return HRTIMER_NORESTART;
 }
author maintainer
#914 lore raw

PATCH 913/990 usb: gadget: u_serial: fix NULL deref in gs_close() after failed open

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Brian Ellis <[email protected]>

commit ea6cf69ad03c8d85138830c0d2c3b946b5ae231d upstream.

gs_close() opens with

	struct gs_port *port = tty->driver_data;
	...
	spin_lock_irq(&port->port_lock);

and never checks port. gs_open() assigns tty->driver_data only on the port.count 0 -> 1 edge, so any failure earlier in gs_open() leaves it NULL, and tty_open() calls tty_release(), and hence ->close(), when ->open() fails.

syzbot hit exactly this on arm64. Fault injection failed the kfifo_alloc() of the write buffer in gs_open():

   __kfifo_alloc_node+0x10c/0x208 lib/kfifo.c:44
   gs_open+0x144/0x514 drivers/usb/gadget/function/u_serial.c:636
   tty_open+0x404/0x89c drivers/tty/tty_io.c:2137

and the tty core's close of the failed open then took port_lock through the NULL port:

  BUG: unable to handle kernel paging request in gs_close
  KASAN: null-ptr-deref in range [0x00000000000003a0-0x00000000000003a7]
  Call trace:
   spin_lock_irq include/linux/spinlock.h:372 [inline]
   gs_close+0xac/0x65c drivers/usb/gadget/function/u_serial.c:698
   tty_release+0x2c4/0xffc drivers/tty/tty_io.c:1745
   tty_open+0x46c/0x89c drivers/tty/tty_io.c:2146

Return early instead. There is nothing to release when the open never got far enough to claim the port.

Unlike the check reverted by commit f6c7bc4a6823 ("Revert "usb: gadget:
u_serial: Add null pointer check in gs_start_io""), this is not hiding a
race: the tty core calls ->close() for an ->open() that failed by design, so driver_data is legitimately unset on that path.

---
 drivers/usb/gadget/function/u_serial.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/usb/gadget/function/u_serial.c +3 -0
@@ -695,6 +695,9 @@ static void gs_close(struct tty_struct *
 	struct gs_port *port = tty->driver_data;
 	struct gserial	*gser;
 
+	if (!port)
+		return;
+
 	spin_lock_irq(&port->port_lock);
 
 	if (port->port.count != 1) {
author maintainer
#915 lore raw

PATCH 914/990 usb: gadget: u_serial: pin ports while TTYs are installed

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Krystian Kaniewski <[email protected]>

commit 1981b53c2b52a00f0f4b9eb87183c9aedc8dac5d upstream.

A slab-use-after-free can occur when gserial_free_line() frees struct gs_port while it is still reachable through an installed TTY. The port->port.count value tracks successful opens, but it is zero before gs_open() and again after gs_close(), before TTY cleanup has finished. Teardown can therefore free gs_port while tty_init_dev() or release_tty() still accesses its tty_port.

Manage gs_port lifetime with tty_port references. Take a reference in gs_install(), drop it in gs_cleanup(), and move the final free to gs_port_destruct(). Unregister the TTY device before dropping the owner reference.

Keep each minor reserved until the old port is destroyed so an installed TTY for one generation cannot overlap a replacement at the same minor. Publish the new port before device registration so the cdev and add uevent never expose a TTY before gs_install() can pin it. Since commit 8df07fe93573 ("tty: fix saved termios reset race"), u_serial registration no longer frees saved termios. On registration failure, unpublish the port before dropping its owner reference.

Check in gs_open() that the installed port is still the published generation. Track failures after a successful install so close callbacks issued by the TTY core do not decrement port->port.count for opens that never incremented it.

---
 drivers/usb/gadget/function/u_serial.c |  167 ++++++++++++++++++++++++++-------
 1 file changed, 134 insertions(+), 33 deletions(-)
drivers/usb/gadget/function/u_serial.c +134 -33
@@ -70,10 +70,28 @@
  *	gserial->ioport == usb_ep->driver_data ... gs_port
  *	gs_port->port_usb ... gserial
  *
- * gs_port <---> tty_struct ... links will be null when the TTY file
- * isn't opened; managed by gs_open()/gs_close()
- *	gserial->port_tty ... tty_struct
- *	tty_struct->driver_data ... gserial
+ * gs_port <---> tty_struct:
+ *	tty->driver_data refers to gs_port from install through cleanup,
+ *	pinning the port via tty_port reference counting.
+ *	gs_port->port.tty exists only while the port is open.
+ *
+ * Each entry in ports[] is guarded by ports[i].lock and models three states:
+ *   - Free:      !port && !reserved
+ *   - Published:  port &&  reserved
+ *   - Retiring:   !port &&  reserved
+ *
+ * A minor remains reserved until gs_port_destruct() runs upon final tty_port
+ * release, preventing minor reuse while cleanup of the installed TTY is still
+ * underway. The owner reference is retained through device unregister so the
+ * destructor releases the reservation only after device teardown is complete.
+ *
+ * open_close_failures tracks failed gs_open() calls where port->port.count
+ * was not incremented. The TTY core calls gs_close() on open failure to tear
+ * down the tty; tracking failures as aggregate credits allows gs_close() to
+ * consume a credit and exit without decrementing port->port.count. Credits
+ * are aggregate rather than paired with individual files (another gs_close()
+ * can consume a failed open's credit before that file's own close runs).
+ * It is protected by tty_lock.
  */
 
 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
@@ -128,6 +146,7 @@ struct gs_port {
 	wait_queue_head_t	close_wait;
 	bool			suspended;	/* port suspended */
 	bool			start_delayed;	/* delay start when suspended */
+	unsigned int		open_close_failures; /* protected by tty_lock */
 	struct async_icount	icount;
 
 	/* REVISIT this state ... */
@@ -135,8 +154,9 @@ struct gs_port {
 };
 
 static struct portmaster {
-	struct mutex	lock;			/* protect open/close */
+	struct mutex	lock;			/* protect open/close and port slot */
 	struct gs_port	*port;
+	bool		reserved;
 } ports[MAX_U_SERIAL_PORTS];
 
 #define GS_CLOSE_TIMEOUT		15		/* seconds */
@@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gs
 
 /* TTY Driver */
 
+static int gs_install(struct tty_driver *driver, struct tty_struct *tty)
+{
+	struct gs_port *port;
+	struct tty_port *tport;
+	int ret;
+
+	mutex_lock(&ports[tty->index].lock);
+	port = ports[tty->index].port;
+	if (!port) {
+		mutex_unlock(&ports[tty->index].lock);
+		return -ENODEV;
+	}
+
+	tport = tty_port_get(&port->port);
+	if (!tport) {
+		mutex_unlock(&ports[tty->index].lock);
+		return -ENODEV;
+	}
+
+	ret = tty_port_install(tport, driver, tty);
+	if (ret) {
+		mutex_unlock(&ports[tty->index].lock);
+		tty_port_put(tport);
+		return ret;
+	}
+
+	tty->driver_data = port;
+	mutex_unlock(&ports[tty->index].lock);
+
+	return 0;
+}
+
+static void gs_cleanup(struct tty_struct *tty)
+{
+	tty_port_put(tty->port);
+}
+
 /*
- * gs_open sets up the link between a gs_port and its associated TTY.
- * That link is broken *only* by TTY close(), and all driver methods
- * know that.
+ * gs_open associates an open TTY with its gs_port.
+ *
+ * There are two TTY-to-port relationships: port->port.tty exists from the
+ * first successful open until final close, while tty->driver_data is assigned
+ * during gs_install() and remains valid through gs_cleanup().
  */
 static int gs_open(struct tty_struct *tty, struct file *file)
 {
 	int		port_num = tty->index;
-	struct gs_port	*port;
+	struct gs_port	*port = tty->driver_data;
 	int		status = 0;
 
 	mutex_lock(&ports[port_num].lock);
-	port = ports[port_num].port;
-	if (!port) {
+	if (ports[port_num].port != port) {
 		status = -ENODEV;
-		goto out;
+		goto fail_unlock;
 	}
 
 	spin_lock_irq(&port->port_lock);
@@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tt
 		if (status) {
 			pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
 				 port_num, tty, file);
-			goto out;
+			goto fail_unlock;
 		}
 
 		spin_lock_irq(&port->port_lock);
@@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tt
 	if (port->port.count++)
 		goto exit_unlock_port;
 
-	tty->driver_data = port;
 	port->port.tty = tty;
 
 	/* if connected, start the I/O stream */
@@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tt
 
 exit_unlock_port:
 	spin_unlock_irq(&port->port_lock);
-out:
+	mutex_unlock(&ports[port_num].lock);
+	return status;
+
+fail_unlock:
+	port->open_close_failures++;
 	mutex_unlock(&ports[port_num].lock);
 	return status;
 }
@@ -698,6 +759,11 @@ static void gs_close(struct tty_struct *
 	if (!port)
 		return;
 
+	if (port->open_close_failures > 0) {
+		port->open_close_failures--;
+		return;
+	}
+
 	spin_lock_irq(&port->port_lock);
 
 	if (port->port.count != 1) {
@@ -912,8 +978,10 @@ static int gs_get_icount(struct tty_stru
 }
 
 static const struct tty_operations gs_tty_ops = {
+	.install =		gs_install,
 	.open =			gs_open,
 	.close =		gs_close,
+	.cleanup =		gs_cleanup,
 	.write =		gs_write,
 	.put_char =		gs_put_char,
 	.flush_chars =		gs_flush_chars,
@@ -1206,14 +1274,41 @@ static void gs_console_exit(struct gs_po
 
 #endif
 
-static int
+static void gs_port_destruct(struct tty_port *tport)
+{
+	struct gs_port *port = container_of(tport, struct gs_port, port);
+	unsigned int port_num = port->port_num;
+
+	mutex_lock(&ports[port_num].lock);
+	if (WARN_ON(ports[port_num].port))
+		ports[port_num].port = NULL;
+	WARN_ON(!ports[port_num].reserved);
+	if (gs_tty_driver)
+		gs_tty_driver->ports[port_num] = NULL;
+	ports[port_num].reserved = false;
+	mutex_unlock(&ports[port_num].lock);
+
+	kfifo_free(&port->port_write_buf);
+	kfree(port);
+}
+
+static const struct tty_port_operations gs_port_ops = {
+	.destruct = gs_port_destruct,
+};
+
+static struct gs_port *
 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
 {
 	struct gs_port	*port;
 	int		ret = 0;
 
 	mutex_lock(&ports[port_num].lock);
-	if (ports[port_num].port) {
+	if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) {
+		ret = -EBUSY;
+		goto out;
+	}
+
+	if (ports[port_num].reserved) {
 		ret = -EBUSY;
 		goto out;
 	}
@@ -1225,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct
 	}
 
 	tty_port_init(&port->port);
+	port->port.ops = &gs_port_ops;
 	spin_lock_init(&port->port_lock);
 	init_waitqueue_head(&port->drain_wait);
 	init_waitqueue_head(&port->close_wait);
@@ -1238,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct
 	port->port_num = port_num;
 	port->port_line_coding = *coding;
 
+	ports[port_num].reserved = true;
 	ports[port_num].port = port;
+	mutex_unlock(&ports[port_num].lock);
+	return port;
+
 out:
 	mutex_unlock(&ports[port_num].lock);
-	return ret;
+	return ERR_PTR(ret);
 }
 
 static int gs_closed(struct gs_port *port)
@@ -1261,8 +1361,7 @@ static void gserial_free_port(struct gs_
 	/* wait for old opens to finish */
 	wait_event(port->close_wait, gs_closed(port));
 	WARN_ON(port->port_usb != NULL);
-	tty_port_destroy(&port->port);
-	kfree(port);
+	tty_port_put(&port->port);
 }
 
 void gserial_free_line(unsigned char port_num)
@@ -1279,15 +1378,15 @@ void gserial_free_line(unsigned char por
 	ports[port_num].port = NULL;
 	mutex_unlock(&ports[port_num].lock);
 
-	gserial_free_port(port);
 	tty_unregister_device(gs_tty_driver, port_num);
+	gserial_free_port(port);
 }
 EXPORT_SYMBOL_GPL(gserial_free_line);
 
 int gserial_alloc_line_no_console(unsigned char *line_num)
 {
 	struct usb_cdc_line_coding	coding;
-	struct gs_port			*port;
+	struct gs_port			*port = ERR_PTR(-EBUSY);
 	struct device			*tty_dev;
 	int				ret;
 	int				port_num;
@@ -1298,19 +1397,20 @@ int gserial_alloc_line_no_console(unsign
 	coding.bDataBits = USB_CDC_1_STOP_BITS;
 
 	for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
-		ret = gs_port_alloc(port_num, &coding);
-		if (ret == -EBUSY)
-			continue;
-		if (ret)
+		port = gs_port_alloc(port_num, &coding);
+		if (IS_ERR(port)) {
+			ret = PTR_ERR(port);
+			if (ret == -EBUSY)
+				continue;
 			return ret;
+		}
 		break;
 	}
-	if (ret)
-		return ret;
+	if (IS_ERR(port))
+		return PTR_ERR(port);
 
 	/* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
 
-	port = ports[port_num].port;
 	tty_dev = tty_port_register_device(&port->port,
 			gs_tty_driver, port_num, NULL);
 	if (IS_ERR(tty_dev)) {
@@ -1319,14 +1419,15 @@ int gserial_alloc_line_no_console(unsign
 
 		ret = PTR_ERR(tty_dev);
 		mutex_lock(&ports[port_num].lock);
+		WARN_ON(ports[port_num].port != port);
 		ports[port_num].port = NULL;
 		mutex_unlock(&ports[port_num].lock);
-		gserial_free_port(port);
-		goto err;
+		tty_port_put(&port->port);
+		return ret;
 	}
+
 	*line_num = port_num;
-err:
-	return ret;
+	return 0;
 }
 EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console);
 
author maintainer
#916 lore raw

PATCH 915/990 usb: dwc3: gadget: Clear delayed stop on End Transfer completion

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit f2bd20f92a7dc68980a6098397503067192ce63a upstream.

When an End Transfer command times out outside of the SETUP phase, the driver sets DWC3_EP_DELAY_STOP to retry it on the next SETUP phase. If the command completes in the meantime, the flag is left set. Requests queued to the endpoint are then deferred, and the retry may end a transfer that is started later.

Clear DWC3_EP_DELAY_STOP when the End Transfer command completes.

---
 drivers/usb/dwc3/gadget.c |    1 +
 1 file changed, 1 insertion(+)
drivers/usb/dwc3/gadget.c +1 -0
@@ -3861,6 +3861,7 @@ static void dwc3_gadget_endpoint_command
 	if (dep->stream_capable)
 		dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
 
+	dep->flags &= ~DWC3_EP_DELAY_STOP;
 	dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
 	dwc3_gadget_ep_cleanup_cancelled_requests(dep);
author maintainer
#917 lore raw

PATCH 916/990 usb: dwc3: gadget: Issue no-op Start Transfer only for stream endpoints

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit e616d91e02881983e5dadf6980c4aa08123800b3 upstream.

The function driver may re-enable an endpoint before the End Transfer command issued on ep disable completes. The no-op Start Transfer issued on ep enable then fails with "No Resource".

Only stream endpoints need the no-op Start Transfer to initiate a stream. Other bulk and interrupt endpoints start their transfer when a request is queued. Skip it for those endpoints, and move it to a helper to be reused.

---
 drivers/usb/dwc3/gadget.c |   97 +++++++++++++++++++++++-----------------------
 1 file changed, 50 insertions(+), 47 deletions(-)
drivers/usb/dwc3/gadget.c +50 -47
@@ -906,6 +906,54 @@ static int dwc3_gadget_resize_tx_fifos(s
 	return 0;
 }
 
+static int dwc3_gadget_ep_start_noop_transfer(struct dwc3_ep *dep)
+{
+	struct dwc3_gadget_ep_cmd_params params;
+	struct dwc3		*dwc = dep->dwc;
+	struct dwc3_trb		*trb;
+	dma_addr_t		trb_dma;
+	u32			cmd;
+	int			ret;
+
+	memset(&params, 0, sizeof(params));
+	trb = &dep->trb_pool[0];
+	trb_dma = dwc3_trb_dma_offset(dep, trb);
+
+	params.param0 = upper_32_bits(trb_dma);
+	params.param1 = lower_32_bits(trb_dma);
+
+	cmd = DWC3_DEPCMD_STARTTRANSFER;
+
+	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
+	if (ret < 0)
+		return ret;
+
+	/*
+	 * For streams, at start, there maybe a race where the host primes the
+	 * endpoint before the function driver queues a request to initiate a
+	 * stream. In that case, the controller will not see the prime to
+	 * generate the ERDY and start stream. To workaround this, issue a
+	 * no-op TRB as normal, but end it immediately. As a result, when the
+	 * function driver queues the request, the next START_TRANSFER command
+	 * will cause the controller to generate an ERDY to initiate the
+	 * stream.
+	 */
+	dwc3_stop_active_transfer(dep, false, true);
+
+	/*
+	 * All stream eps will reinitiate stream on NoStream rejection.
+	 *
+	 * However, if the controller is capable of TXF_FLUSH_BYPASS, then IN
+	 * direction endpoints will automatically restart the stream without
+	 * the driver initiation.
+	 */
+	if (!dep->direction ||
+	    !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
+		dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
+
+	return 0;
+}
+
 /**
  * __dwc3_gadget_ep_enable - initializes a hw endpoint
  * @dep: endpoint to be initialized
@@ -971,55 +1019,10 @@ static int __dwc3_gadget_ep_enable(struc
 	 * Issue StartTransfer here with no-op TRB so we can always rely on No
 	 * Response Update Transfer command.
 	 */
-	if (usb_endpoint_xfer_bulk(desc) ||
-			usb_endpoint_xfer_int(desc)) {
-		struct dwc3_gadget_ep_cmd_params params;
-		struct dwc3_trb	*trb;
-		dma_addr_t trb_dma;
-		u32 cmd;
-
-		memset(&params, 0, sizeof(params));
-		trb = &dep->trb_pool[0];
-		trb_dma = dwc3_trb_dma_offset(dep, trb);
-
-		params.param0 = upper_32_bits(trb_dma);
-		params.param1 = lower_32_bits(trb_dma);
-
-		cmd = DWC3_DEPCMD_STARTTRANSFER;
-
-		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
+	if (dep->stream_capable) {
+		ret = dwc3_gadget_ep_start_noop_transfer(dep);
 		if (ret < 0)
 			return ret;
-
-		if (dep->stream_capable) {
-			/*
-			 * For streams, at start, there maybe a race where the
-			 * host primes the endpoint before the function driver
-			 * queues a request to initiate a stream. In that case,
-			 * the controller will not see the prime to generate the
-			 * ERDY and start stream. To workaround this, issue a
-			 * no-op TRB as normal, but end it immediately. As a
-			 * result, when the function driver queues the request,
-			 * the next START_TRANSFER command will cause the
-			 * controller to generate an ERDY to initiate the
-			 * stream.
-			 */
-			dwc3_stop_active_transfer(dep, false, true);
-
-			/*
-			 * All stream eps will reinitiate stream on NoStream
-			 * rejection.
-			 *
-			 * However, if the controller is capable of
-			 * TXF_FLUSH_BYPASS, then IN direction endpoints will
-			 * automatically restart the stream without the driver
-			 * initiation.
-			 */
-			if (!dep->direction ||
-			    !(dwc->hwparams.hwparams9 &
-			      DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
-				dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
-		}
 	}
 
 out:
author maintainer
#918 lore raw

PATCH 917/990 usb: dwc3: gadget: Recover from End Transfer timeout

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit 61575534fb05d52d36979f38976ece74649f091a upstream.

If the End Transfer command times out, the endpoint resource is never released and every subsequent Start Transfer to the endpoint fails with "No Resource". Schedule an error recovery to reset the controller.

---
 drivers/usb/dwc3/gadget.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/usb/dwc3/gadget.c +5 -0
@@ -1754,6 +1754,8 @@ static int __dwc3_gadget_get_frame(struc
 	return DWC3_DSTS_SOFFN(reg);
 }
 
+static void dwc3_schedule_err_recovery(struct dwc3 *dwc);
+
 /**
  * __dwc3_stop_active_transfer - stop the current active transfer
  * @dep: isoc endpoint
@@ -1797,6 +1799,9 @@ static int __dwc3_stop_active_transfer(s
 		dev_err_ratelimited(dep->dwc->dev,
 				"end transfer failed: %d\n", ret);
 
+	if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE)
+		dwc3_schedule_err_recovery(dep->dwc);
+
 	dep->resource_index = 0;
 
 	if (!interrupt)
author maintainer
#919 lore raw

PATCH 918/990 usb: dwc3: gadget: Reject requests to a disabled endpoint

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit 5eb11b1647b0534b3a61a21473d77ebf4ffbed7c upstream.

__dwc3_gadget_ep_disable() releases the lock while giving back requests, and DWC3_EP_ENABLED is only cleared afterward. A function driver can queue a new request in this window, and the driver would start a transfer on an endpoint that is already disabled in hardware.

Clear DWC3_EP_ENABLED before giving back the requests, and reject requests queued to an endpoint that is not enabled.

---
 drivers/usb/dwc3/gadget.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/usb/dwc3/gadget.c +4 -1
@@ -1087,6 +1087,8 @@ static int __dwc3_gadget_ep_disable(stru
 	reg &= ~DWC3_DALEPENA_EP(dep->number);
 	dwc3_writel(dwc, DWC3_DALEPENA, reg);
 
+	dep->flags &= ~DWC3_EP_ENABLED;
+
 	dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
 
 	dep->stream_capable = false;
@@ -1998,7 +2000,8 @@ static int __dwc3_gadget_ep_queue(struct
 {
 	struct dwc3		*dwc = dep->dwc;
 
-	if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
+	if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc ||
+	    !dwc->pullups_connected || !dwc->connected) {
 		dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
 				dep->name);
 		return -ESHUTDOWN;
author maintainer
#920 lore raw

PATCH 919/990 usb: dwc3: gadget: Reset endpoint flags on controller start

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit 7c9bc134e5b3315e0456cda9e8e59c752309ea78 upstream.

The flags of a disabled endpoint may be preserved while its End Transfer command is pending. If the command never completes, the stale flags persist across a soft disconnect or an error recovery, and the endpoint can't be used again.

Reset the flags of all non-control endpoints when starting the controller.

---
 drivers/usb/dwc3/gadget.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/usb/dwc3/gadget.c +10 -0
@@ -2958,6 +2958,7 @@ static int __dwc3_gadget_start(struct dw
 {
 	struct dwc3_ep		*dep;
 	int			ret = 0;
+	u32			epnum;
 	u32			reg;
 
 	/*
@@ -3015,6 +3016,15 @@ static int __dwc3_gadget_start(struct dw
 		return ret;
 	}
 
+	for (epnum = 2; epnum < dwc->num_eps; epnum++) {
+		dep = dwc->eps[epnum];
+		if (!dep)
+			continue;
+
+		dep->flags &= (DWC3_EP_TXFIFO_RESIZED |
+			       DWC3_EP_RESOURCE_ALLOCATED);
+	}
+
 	dep = dwc->eps[0];
 	dep->flags = 0;
 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
author maintainer
#921 lore raw

PATCH 920/990 usb: dwc3: gadget: Track a timed out End Transfer

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit af91c6322e633504aa45de278f5d520f39d127be upstream.

If an End Transfer command with CMDIOC times out, the driver clears the resource index but keeps DWC3_EP_TRANSFER_STARTED without setting DWC3_EP_END_TRANSFER_PENDING. The command is still outstanding, but a later stop issues another End Transfer with resource index 0, and the next Start Transfer fails with "No Resource".

Mark the timed out End Transfer as pending so that no other command is issued to the endpoint until it completes. For any other failure, there is no outstanding command, so clear DWC3_EP_TRANSFER_STARTED.

---
 drivers/usb/dwc3/gadget.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/usb/dwc3/gadget.c +2 -2
@@ -1806,9 +1806,9 @@ static int __dwc3_stop_active_transfer(s
 
 	dep->resource_index = 0;
 
-	if (!interrupt)
+	if (!interrupt || (ret && ret != -ETIMEDOUT))
 		dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
-	else if (!ret)
+	else
 		dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
 
 	dep->flags &= ~DWC3_EP_DELAY_STOP;
author maintainer
#922 lore raw

PATCH 921/990 usb: dwc3: gadget: Wait for End Transfer completion on ep disable

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Thinh Nguyen <[email protected]>

commit 1338410c21a5710b7ba88057034d35367ba0f054 upstream.

The End Transfer command on ep disable is issued without interrupt, and the endpoint flags are cleared right after a fixed delay. The command may not have completed by then. If the function driver re-enables the endpoint and queues a request, the next Start Transfer fails with "No Resource".

Issue the End Transfer command with interrupt on ep disable, and keep DWC3_EP_END_TRANSFER_PENDING and DWC3_EP_TRANSFER_STARTED until the command completes. Defer the no-op Start Transfer of a stream endpoint re-enabled in the meantime to the command completion.

---
 drivers/usb/dwc3/core.h   |    4 +++-
 drivers/usb/dwc3/ep0.c    |    2 +-
 drivers/usb/dwc3/gadget.c |   42 +++++++++++++++++++++++++++++++++++-------
 3 files changed, 39 insertions(+), 9 deletions(-)
drivers/usb/dwc3/core.h +3 -1
@@ -772,6 +772,7 @@ struct dwc3_ep {
 #define DWC3_EP_TXFIFO_RESIZED		BIT(12)
 #define DWC3_EP_DELAY_STOP             BIT(13)
 #define DWC3_EP_RESOURCE_ALLOCATED	BIT(14)
+#define DWC3_EP_PENDING_NOOP_START	BIT(15)
 
 	/* This last one is specific to EP0 */
 #define DWC3_EP0_DIR_IN			BIT(31)
@@ -1687,7 +1688,8 @@ int dwc3_send_gadget_ep_cmd(struct dwc3_
 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
 		u32 param);
 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc);
-void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status);
+void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status,
+			  bool interrupt);
 #else
 static inline int dwc3_gadget_init(struct dwc3 *dwc)
 { return 0; }
drivers/usb/dwc3/ep0.c +1 -1
@@ -315,7 +315,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc
 		if (dwc->connected)
 			dwc3_stop_active_transfer(dwc3_ep, false, true);
 		else
-			dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN);
+			dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN, false);
 	}
 }
 
drivers/usb/dwc3/gadget.c +35 -7

87 lines not on this page · raw message

author maintainer
#923 lore raw

PATCH 922/990 usb: dwc3: xilinx: fix system suspend and resume PHY handling

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Radhey Shyam Pandey <[email protected]>

commit 2fad8d241a6833d0c7aeafa0ab596e83c7b4ec9c upstream.

System suspend and resume error paths do not handle PHY and clock resources correctly. Suspend calls phy_exit() without first powering off the PHY and ignores failures, while resume can leave clocks enabled if PHY reinitialization fails.

Propagate errors to the PM core and unwind resources to ensure a consistent state on suspend and resume failures.

Fixes d6edcdc1ef06 ("usb: dwc3: xilinx: fix usb3 non-wakeup source resume failure")
Cc stable <[email protected]>
Assisted-by Claude:claude-opus-5
---
 drivers/usb/dwc3/dwc3-xilinx.c |   24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)
drivers/usb/dwc3/dwc3-xilinx.c +21 -3
@@ -395,13 +395,26 @@ static int __maybe_unused dwc3_xlnx_runt
 static int __maybe_unused dwc3_xlnx_suspend(struct device *dev)
 {
 	struct dwc3_xlnx *priv_data = dev_get_drvdata(dev);
+	int ret;
+
+	ret = phy_power_off(priv_data->usb3_phy);
+	if (ret < 0)
+		return ret;
 
-	phy_exit(priv_data->usb3_phy);
+	ret = phy_exit(priv_data->usb3_phy);
+	if (ret < 0)
+		goto err_phy_power_on;
 
 	/* Disable the clocks */
 	clk_bulk_disable(priv_data->num_clocks, priv_data->clks);
 
 	return 0;
+
+err_phy_power_on:
+	if (phy_power_on(priv_data->usb3_phy))
+		dev_err(dev, "failed to restore PHY power after suspend error\n");
+
+	return ret;
 }
 
 static int __maybe_unused dwc3_xlnx_resume(struct device *dev)
@@ -415,15 +428,20 @@ static int __maybe_unused dwc3_xlnx_resu
 
 	ret = phy_init(priv_data->usb3_phy);
 	if (ret < 0)
-		return ret;
+		goto err_clk_disable;
 
 	ret = phy_power_on(priv_data->usb3_phy);
 	if (ret < 0) {
 		phy_exit(priv_data->usb3_phy);
-		return ret;
+		goto err_clk_disable;
 	}
 
 	return 0;
+
+err_clk_disable:
+	clk_bulk_disable(priv_data->num_clocks, priv_data->clks);
+
+	return ret;
 }
 
 static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = {
author maintainer
#924 lore raw

PATCH 923/990 w1: dont hold list_mutex while a slave is torn down

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 7ef382cb0ae0b2d6df4fbc5c822cd80394308839 upstream.

When the last reference to a slave is dropped, w1_unref_slave() holds list_mutex of the master until the slave has been freed. In between it calls the ->remove_slave() callback of the family driver and device_unregister(). Both wait for others: for the sysfs callbacks which are running, and in the case of w1_therm also for the file therm_bulk_read of the master and for everybody who is talking to the sensor. None of those can therefore take list_mutex, although the callbacks of therm_bulk_read walk the list which it protects.

The mutex is only needed to make the decrement of the reference count and the removal from the list one step for w1_search_slave() and w1_slave_search_device(), which look the slave up in the list and, in the first case, take a reference. Once the slave is off the list, nobody can find it any more. Drop the mutex at that point.

The callers which hold the mutex of the master, which serialises attaching and detaching, are not affected. The one which does not is w1_process_cb(), when it drops the last reference to a slave which has been detached while a netlink command for it was queued. Somebody who attaches a slave with the same ID through sysfs or netlink at that very moment used to wait until the old device was gone. Now the registration of the new device may fail because the name is still in use.

This is a preparation for "w1: w1_therm: lock the list of slaves for the bulk read".

---
 drivers/w1/w1.c |   13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/w1/w1.c +10 -3
@@ -776,16 +776,24 @@ int w1_unref_slave(struct w1_slave *sl)
 {
 	struct w1_master *dev = sl->master;
 	int refcnt;
+
+	/*
+	 * Once it is off the list nobody can find the slave and take a new
+	 * reference.  The lock must not be held any longer than that: the rest
+	 * waits for sysfs callbacks and for users of the family data.
+	 */
 	mutex_lock(&dev->list_mutex);
 	refcnt = atomic_sub_return(1, &sl->refcnt);
+	if (refcnt == 0)
+		list_del(&sl->w1_slave_entry);
+	mutex_unlock(&dev->list_mutex);
+
 	if (refcnt == 0) {
 		struct w1_netlink_msg msg;
 
 		dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__,
 			sl->name, sl);
 
-		list_del(&sl->w1_slave_entry);
-
 		memset(&msg, 0, sizeof(msg));
 		memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id));
 		msg.type = W1_SLAVE_REMOVE;
@@ -799,7 +807,6 @@ int w1_unref_slave(struct w1_slave *sl)
 		kfree(sl);
 	}
 	atomic_dec(&dev->refcnt);
-	mutex_unlock(&dev->list_mutex);
 	return refcnt;
 }
 
author maintainer
#925 lore raw

PATCH 924/990 w1: ds2482: set the strong pull-up with its byte

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit e4f673632fa8292a2922bcfbb39519b08016b382 upstream.

The eight channels of a DS2482-800 are eight independent 1-wire masters for the w1 core, but share one I2C device. Each bus operation consists of several I2C transfers: select the channel, send the command, poll the status, set the read pointer, read the result. access_lock keeps the operations of the channels apart.

ds2482_w1_set_pullup() polls the status, writes the configuration and polls again without the lock. Polling sets the read pointer of the device to the status register. In the middle of a read on another channel, after that one has set the pointer to the data register, this makes the read return the status instead of the data. The cached copy of the pointer in pdev->read_prt can go wrong as well.

The lock alone is not enough. The strong pull-up is a setting of the whole chip which is used up by the next byte. If an operation of another channel gets in before the byte it was meant for, that channel gets the pull-up, and the sensor converts without power.

So only note the request in ds2482_w1_set_pullup(), and write the configuration in ds2482_w1_write_byte(), under the lock and after the channel has been selected. The w1 core calls the former right before the latter, under the bus mutex of the channel.

Fixes 9c95bb6f25ff ("w1: ds2482: Added 1-Wire pull-up support to the driver")
Cc stable <[email protected]>
---
 drivers/w1/masters/ds2482.c |   36 +++++++++++++++++++++---------------
 1 file changed, 21 insertions(+), 15 deletions(-)
drivers/w1/masters/ds2482.c +21 -15
@@ -103,6 +103,7 @@ struct ds2482_data;
 struct ds2482_w1_chan {
 	struct ds2482_data	*pdev;
 	u8			channel;
+	bool			spu;	/* strong pullup after the next byte */
 	struct w1_bus_master	w1_bm;
 };
 
@@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *d
 	if (pdev->w1_count > 1)
 		ds2482_set_channel(pdev, pchan->channel);
 
+	if (pchan->spu) {
+		pchan->spu = false;
+		/* the wait above and this one are crucial, otherwise devices
+		 * might not be powered long enough, causing e.g. a w1_therm
+		 * sensor to provide wrong conversion results
+		 */
+		/* note: it seems like both SPU and APU have to be set! */
+		ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG,
+				     ds2482_calculate_config(DS2482_REG_CFG_SPU |
+							     DS2482_REG_CFG_APU));
+		ds2482_wait_1wire_idle(pdev);
+	}
+
 	/* Send the write byte command */
 	ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte);
 
@@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data
 static u8 ds2482_w1_set_pullup(void *data, int delay)
 {
 	struct ds2482_w1_chan *pchan = data;
-	struct ds2482_data    *pdev = pchan->pdev;
-	u8 retval = 1;
 
 	/* if delay is non-zero activate the pullup,
 	 * the strong pullup will be automatically deactivated
 	 * by the master, so do not explicitly deactive it
+	 *
+	 * The setting is used up by the next byte on any channel of the chip:
+	 * ds2482_w1_write_byte() makes it, in one go with the byte.
 	 */
-	if (delay) {
-		/* both waits are crucial, otherwise devices might not be
-		 * powered long enough, causing e.g. a w1_therm sensor to
-		 * provide wrong conversion results
-		 */
-		ds2482_wait_1wire_idle(pdev);
-		/* note: it seems like both SPU and APU have to be set! */
-		retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG,
-			ds2482_calculate_config(DS2482_REG_CFG_SPU |
-						DS2482_REG_CFG_APU));
-		ds2482_wait_1wire_idle(pdev);
-	}
+	if (!delay)
+		return 1;
 
-	return retval;
+	pchan->spu = true;
+	return 0;
 }
 
 
author maintainer
#926 lore raw

PATCH 925/990 w1: ds2805: use the bus mutex to talk on the bus

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit a2e52ccce044e13d2695bb1bbdc07942727f28dd upstream.

Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver takes the mutex of the master in the callbacks of its eeprom file instead.

That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master.

Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire.

---
 drivers/w1/slaves/w1_ds2805.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/w1/slaves/w1_ds2805.c +4 -4
@@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct fi
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */
 	while (todo > 0) {
@@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct fi
 		off += W1_F0D_READ_MAXLEN;
 	}
 
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct f
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Can only write data in blocks of the size of the scratchpad */
 	addr = off;
@@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct f
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
author maintainer
#927 lore raw

PATCH 926/990 w1: ds28e04: use the bus mutex to talk on the bus

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 5bc51235d0ad4a4991e38f4e9dc3440738296850 upstream.

Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver, which was merged shortly afterwards, takes the mutex of the master in the callbacks of its eeprom and pio files instead.

That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master.

Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire.

---
 drivers/w1/slaves/w1_ds28e04.c |   18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/w1/slaves/w1_ds28e04.c +9 -9
@@ -123,7 +123,7 @@ static ssize_t eeprom_read(struct file *
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	if (w1_enable_crccheck) {
 		min_page = (off >> W1_PAGE_BITS);
@@ -140,7 +140,7 @@ static ssize_t eeprom_read(struct file *
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -253,7 +253,7 @@ static ssize_t eeprom_write(struct file
 		}
 	}
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Can only write data to one page at a time */
 	idx = 0;
@@ -271,7 +271,7 @@ static ssize_t eeprom_write(struct file
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -290,9 +290,9 @@ static ssize_t pio_read(struct file *fil
 	if (off != 0 || count != 1 || buf == NULL)
 		return -EINVAL;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	ret = w1_f1C_read(sl, W1_1C_REG_LOGIC_STATE, count, buf);
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return ret;
 }
@@ -310,11 +310,11 @@ static ssize_t pio_write(struct file *fi
 	if (off != 0 || count != 1 || buf == NULL)
 		return -EINVAL;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Write the PIO data */
 	if (w1_reset_select_slave(sl)) {
-		mutex_unlock(&sl->master->mutex);
+		mutex_unlock(&sl->master->bus_mutex);
 		return -1;
 	}
 
@@ -328,7 +328,7 @@ static ssize_t pio_write(struct file *fi
 
 	w1_read_block(sl->master, &ack, sizeof(ack));
 
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	/* check for acknowledgement */
 	if (ack != 0xAA)
author maintainer
#928 lore raw

PATCH 927/990 w1: netlink: drop the slave after the bus is unlocked

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 847fa880a3e1b2fdbbf72d89e830566108457637 upstream.

w1_process_cb() executes the commands of a netlink message with bus_mutex held, and drops the reference to the slave which the message was addressed to before it unlocks the mutex. If the slave has been detached in the meantime, this is the last reference, and w1_unref_slave() tears the slave down on the spot. That waits

- in device_unregister(), for the sysfs callbacks of the slave which are running, and

- in w1_therm_remove_slave(), for the readers which have taken a reference to the family data,

and both kinds take bus_mutex to talk to the slave. Whoever is waiting for the mutex at that moment is never going to finish, and neither is the thread of the bus master.

Unlock the bus first. The reference keeps the slave, and with it the master, alive until then.

---
 drivers/w1/w1_netlink.c |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/w1/w1_netlink.c +5 -3
@@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_mast
 	if (!cmd || err)
 		w1_netlink_queue_status(node->block, node->msg, cmd, err);
 
+	dev->priv = NULL;
+	mutex_unlock(&dev->bus_mutex);
+
 	/* ref taken in w1_search_slave or w1_search_master_id when building
-	 * the block
+	 * the block.  If it is the last one, the slave is removed, which waits
+	 * for users of the bus.
 	 */
 	if (sl)
 		w1_unref_slave(sl);
 	else
 		atomic_dec(&dev->refcnt);
-	dev->priv = NULL;
-	mutex_unlock(&dev->bus_mutex);
 
 	mutex_lock(&dev->list_mutex);
 	list_del(&async_cmd->async_entry);
author maintainer
#929 lore raw

PATCH 928/990 w1: remove the masters files before taking its locks

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit dfc57752ec53c3cc6105656d3037fb2f5e80e9cc upstream.

__w1_remove_master_device() calls w1_destroy_master_attributes() with both the mutex of the master and list_mutex held. Removing the files waits for the callbacks which are running, and nearly all of them take one of these two locks:

__w1_remove_master_device() read() of .../w1_master_slaves

    mutex_lock(&dev->mutex)               kernfs active reference
    mutex_lock(&dev->list_mutex)          w1_master_attribute_show_slaves()
    w1_destroy_master_attributes()          mutex_lock(&md->list_mutex)
      sysfs_remove_group()                    waits
        waits for the reference

The files are readable for everybody, and a bus master goes away when, for instance, a DS2490 USB adapter is unplugged.

Remove the files first, before the locks are taken. That has to be done before the slaves are detached and not afterwards: as long as the files exist, a write to w1_master_add could attach a new slave behind the back of this function, which would then wait for the reference count of the master for ever. And it is done before the thread is stopped, because a write to w1_master_search wakes the thread up.

---
 drivers/w1/w1_int.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/w1/w1_int.c +7 -1
@@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1
 	mutex_unlock(&w1_mlock);
 
 	set_bit(W1_ABORT_SEARCH, &dev->flags);
+
+	/*
+	 * This waits for the callbacks, which take the locks below. One of
+	 * them wakes the thread up.
+	 */
+	w1_destroy_master_attributes(dev);
+
 	kthread_stop(dev->thread);
 
 	mutex_lock(&dev->mutex);
@@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1
 		w1_slave_detach(sl);
 		mutex_lock(&dev->list_mutex);
 	}
-	w1_destroy_master_attributes(dev);
 	mutex_unlock(&dev->list_mutex);
 	mutex_unlock(&dev->mutex);
 	atomic_dec(&dev->refcnt);
author maintainer
#930 lore raw

PATCH 929/990 w1: use the bus mutex for the "rw" file

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 8599e08648c0b4913ea7b202511f1294d176e793 upstream.

Commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") gave the bus a mutex of its own, because the lock which protects the list of slaves is held while a slave is removed, which waits for the sysfs callbacks of the slave, so these must not take it. It converted all the slave drivers, but not the "rw" file of the default family in w1.c, which still takes the mutex of the master to talk on the bus. That has two consequences:

- A deadlock. w1_process() holds the mutex of the master while it searches the bus and detaches the slaves which have gone:

w1_process() read() of .../rw
mutex_lock(&dev->mutex) kernfs active reference
w1_search_process() rw_read()
w1_slave_detach() mutex_lock(&master->mutex)
w1_unref_slave() waits
device_unregister()
waits for the reference

The file is readable for everybody.

- The accesses through this file are not serialised with those of the slave drivers, which take bus_mutex, so that two transactions can get mixed up on the wire.

Take bus_mutex here as well. It also excludes the search, which takes it for every pass.

---
 drivers/w1/w1.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/w1/w1.c +4 -4
@@ -116,7 +116,7 @@ static ssize_t rw_write(struct file *fil
 {
 	struct w1_slave *sl = kobj_to_w1_slave(kobj);
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	if (w1_reset_select_slave(sl)) {
 		count = 0;
 		goto out_up;
@@ -125,7 +125,7 @@ static ssize_t rw_write(struct file *fil
 	w1_write_block(sl->master, buf, count);
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 	return count;
 }
 
@@ -135,9 +135,9 @@ static ssize_t rw_read(struct file *filp
 {
 	struct w1_slave *sl = kobj_to_w1_slave(kobj);
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	w1_read_block(sl->master, buf, count);
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 	return count;
 }
 
author maintainer
#931 lore raw

PATCH 930/990 w1: w1_therm: leave the slaves of other families alone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit c0eadd2e06e52563cae2b80491e56eb9712eb727 upstream.

The file therm_bulk_read belongs to the bus master. Its callbacks walk all the slaves of the bus and look at sl->family_data as if every slave were a temperature sensor. A 1-wire bus can carry other devices too:

- The family data of a slave which is driven by another driver, such as w1_ds2433, w1_ds250x, w1_ds28e04 or w1_ds28e17, is a structure of that driver. bulk_read_support() takes whatever is at the offset of specific_functions for a pointer and dereferences it, and if the result happens not to be 0, the callbacks write the state of the conversion into that foreign structure.

- For a slave without family data, which is the case for most of the other drivers and for the default family, trigger_bulk_read() gives up with -ENODEV. A single serial number chip on the bus is enough to make the bulk read unusable for all the sensors.

Only look at the slaves whose family is one of ours. A bulk conversion now works on a bus with other devices.

Fixes 57c76221d5af ("w1_therm: adding bulk read support to trigger multiple conversion on bus")
Cc stable <[email protected]>
---
 drivers/w1/slaves/w1_therm.c |   37 +++++++++++++++++++++++--------------
 1 file changed, 23 insertions(+), 14 deletions(-)
drivers/w1/slaves/w1_therm.c +23 -14
@@ -907,6 +907,19 @@ static inline bool bulk_read_support(str
 }
 
 /**
+ * bulk_read_slave() - check if a slave of the bus takes part in a bulk read
+ * @sl: any slave on the list of the master
+ *
+ * The family data of the slaves of other families is none of our business.
+ *
+ * Return: true if it is one of our devices and supports bulk read
+ */
+static bool bulk_read_slave(struct w1_slave *sl)
+{
+	return device_family(sl) && sl->family_data && bulk_read_support(sl);
+}
+
+/**
  * conversion_time() - get the Tconv for the slave
  * @sl: device to get the conversion time
  *
@@ -1497,9 +1510,7 @@ static int trigger_bulk_read(struct w1_m
 	 * so we can apply a strong pullup if required
 	 */
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (!sl->family_data)
-			goto error;
-		if (bulk_read_support(sl)) {
+		if (bulk_read_slave(sl)) {
 			int t_cur = conversion_time(sl);
 
 			t_conv = max(t_cur, t_conv);
@@ -1537,7 +1548,7 @@ static int trigger_bulk_read(struct w1_m
 			/* set a flag to instruct that converT pending */
 			list_for_each_entry(sl,
 				&dev_master->slist, w1_slave_entry) {
-				if (bulk_read_support(sl))
+				if (bulk_read_slave(sl))
 					SLAVE_CONVERT_TRIGGERED(sl) = -1;
 			}
 
@@ -1566,7 +1577,7 @@ mt_unlock:
 set_flag:
 	/* set a flag to register convsersion is done */
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (bulk_read_support(sl))
+		if (bulk_read_slave(sl))
 			SLAVE_CONVERT_TRIGGERED(sl) = 1;
 	}
 error:
@@ -1934,16 +1945,14 @@ static ssize_t therm_bulk_read_show(stru
 	int ret = 0;
 
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (sl->family_data) {
-			if (bulk_read_support(sl)) {
-				if (SLAVE_CONVERT_TRIGGERED(sl) == -1) {
-					ret = -1;
-					goto show_result;
-				}
-				if (SLAVE_CONVERT_TRIGGERED(sl) == 1)
-					/* continue to check other slaves */
-					ret = 1;
+		if (bulk_read_slave(sl)) {
+			if (SLAVE_CONVERT_TRIGGERED(sl) == -1) {
+				ret = -1;
+				goto show_result;
 			}
+			if (SLAVE_CONVERT_TRIGGERED(sl) == 1)
+				/* continue to check other slaves */
+				ret = 1;
 		}
 	}
 show_result:
author maintainer
#932 lore raw

PATCH 931/990 drm/amdkfd: skip GPUs without a VM when checkpointing the BO mappings

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jesse Zhang <[email protected]>

commit 1a5ca15b558bf0e6621602c84e0a633d237dd052 upstream.

criu_checkpoint_bos() asks every device of the process whether a BO is mapped there, passing its drm_priv, which is NULL for the devices the process never acquired a VM on. On navi48 with its iGPU, checkpointing a process which acquired the VM of the dGPU only:

  Oops: general protection fault, probably for non-canonical address 0xdffffc000000002f: 0000 [#1] SMP KASAN NOPTI
  KASAN: null-ptr-deref in range [0x0000000000000178-0x000000000000017f]
  RIP: 0010:amdgpu_amdkfd_bo_mapped_to_dev+0x35/0x160 [amdgpu]
   kfd_ioctl_criu+0x30d1/0x4aa0 [amdgpu]
   kfd_ioctl+0x767/0xb10 [amdgpu]

Nothing can be mapped on such a device, skip it.

Fixes f9e292cbba21 ("drm/amdkfd: kfd_bo_mapped_dev support partition")
(cherry picked from commit 794381c358d344d8fcf8b9e6426aa2bac0a7d1f7)
---
 drivers/gpu/drm/amd/amdkfd/kfd_chardev.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +3 -1
@@ -1996,7 +1996,9 @@ static int criu_checkpoint_bos(struct kf
 				bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo);
 
 			for (i = 0; i < p->n_pdds; i++) {
-				if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem))
+				/* nothing is mapped on a GPU without a VM */
+				if (p->pdds[i]->drm_priv &&
+				    amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem))
 					bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id;
 			}
 
author maintainer
#933 lore raw

PATCH 932/990 drm/amdgpu: fix the error handling of amdgpu_vm_init_entities()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jesse Zhang <[email protected]>

commit de0f2a6eabd019a3129025862bffca934a5d7180 upstream.

When initializing the immediate entity fails, amdgpu_vm_init_entities() destroys that entity which was never set up, and when initializing the delayed entity fails, it returns without destroying the immediate one.

On navi48, with the allocation of the immediate entity's scheduler list failing through failslab while opening the render node:

  Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI
  KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]
  RIP: 0010:do_raw_spin_lock+0x7b/0x280
   _raw_spin_lock+0x3c/0x50
   drm_sched_rq_remove_entity+0x90/0x2a0 [gpu_sched]
   drm_sched_entity_kill+0x86/0x5a0 [gpu_sched]
   drm_sched_entity_fini+0x23/0x270 [gpu_sched]
   drm_sched_entity_destroy+0x24/0x30 [gpu_sched]
   amdgpu_vm_init_entities+0xc7/0x100 [amdgpu]
   amdgpu_vm_init+0x5d1/0x1480 [amdgpu]
   amdgpu_driver_open_kms+0x2b1/0xd10 [amdgpu]

Only destroy the immediate entity once it exists and the delayed one failed.

Fixes 55bf196f60df ("drm/amdgpu: reset VM when an error is detected")
(cherry picked from commit 2f538f57501a71baeb7116ff7485f9a7025e4fb9)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +7 -3
@@ -527,11 +527,15 @@ static int amdgpu_vm_init_entities(struc
 				  adev->vm_manager.vm_pte_scheds,
 				  adev->vm_manager.vm_pte_num_scheds, NULL);
 	if (r)
+		return r;
+
+	r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
+				  adev->vm_manager.vm_pte_scheds,
+				  adev->vm_manager.vm_pte_num_scheds, NULL);
+	if (r)
 		goto error;
 
-	return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
-				     adev->vm_manager.vm_pte_scheds,
-				     adev->vm_manager.vm_pte_num_scheds, NULL);
+	return 0;
 
 error:
 	drm_sched_entity_destroy(&vm->immediate);
author maintainer
#934 lore raw

PATCH 933/990 USB: serial: garmin_gps: validate packet data length in nat_receive()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hui Peng <[email protected]>

commit ca783a2d55b3361493917ad4a3573715ba902503 upstream.

In nat_receive() (called from garmin_write() when userspace writes to /dev/ttyUSBn in MODE_NATIVE mode), while garmin_data_p->insize is less than GARMIN_PKTHDR_LENGTH (12), the loop copies up to 12 bytes into garmin_data_p->inbuffer. Once garmin_data_p->insize reaches GARMIN_PKTHDR_LENGTH, nat_receive() computes the total packet size as:

  len = GARMIN_PKTHDR_LENGTH + getDataLength(garmin_data_p->inbuffer);

Because getDataLength() returns a signed int from __le32_to_cpup(), a 12-byte header with a negative 32-bit length field (such as 0xfffffff5, i.e., -11) causes len to underflow to a small positive value (12 + (-11) = 1) without any bounds check at that point. Then garmin_data_p->insize

Quoted 1 line

= len (12 >= 1) evaluates to true and nat_receive() calls

garmin_write_bulk(port, inbuffer, 1, 0), which allocates a 1-byte slab buffer via kmemdup() and immediately reads 4 bytes from it in getLayerId(buffer) (and again in garmin_write_bulk_callback() when the URB completes):

  BUG: KASAN: slab-out-of-bounds in garmin_write_bulk.constprop.0+0x3eb/0x500
  Read of size 4 at addr ffff888002cc0ba0 by task init/1
  Call Trace:
   <TASK>
   dump_stack_lvl+0x70/0xa0
   print_report+0x153/0x4c6
   kasan_report+0xf1/0x120
   garmin_write_bulk.constprop.0+0x3eb/0x500
   garmin_write+0x60f/0x1450
   serial_write+0x123/0x200
   n_tty_write+0x8ea/0xeb0
   file_tty_write.isra.0+0x44f/0x7a0
   vfs_write+0x671/0xd20

Validate the unsigned 32-bit data length (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH, matching the existing len >= GPS_IN_BUFSIZ bound) in nat_receive() as soon as the 12-byte header is present, resetting insize and returning -EINVPKT on invalid lengths so garmin_write_bulk() is only ever called with a full valid packet header (12 <= len < GPS_IN_BUFSIZ).

Tested in QEMU against Linux 7.3.0-rc3 by emulating a Garmin USB GPS device (091e:0003) via dummy_hcd + raw-gadget, switching /dev/ttyUSB0 to MODE_NATIVE via PRIV_PKTID_SET_MODE, and writing a 12-byte native packet with data length 0xfffffff5: on the unfixed kernel this triggers KASAN slab-out-of-bounds reads in garmin_write_bulk() and garmin_write_bulk_callback(), whereas on the fixed kernel nat_receive() rejects the packet with -EINVPKT and 0 KASAN faults.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Assisted-by LLM
[ johan: move comment and dev_dbg(); add comment about redundant check ]
---
 drivers/usb/serial/garmin_gps.c |   19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)
drivers/usb/serial/garmin_gps.c +12 -7
@@ -749,11 +749,7 @@ static int nat_receive(struct garmin_dat
 			len = GARMIN_PKTHDR_LENGTH;
 
 		if (len >= GPS_IN_BUFSIZ) {
-			/* seems to be an invalid packet, ignore rest
-			   of input */
-			dev_dbg(&garmin_data_p->port->dev,
-				"%s - packet size too large: %d\n",
-				__func__, len);
+			/* should never end up here given the dlen check below */
 			garmin_data_p->insize = 0;
 			count = 0;
 			result = -EINVPKT;
@@ -772,8 +768,17 @@ static int nat_receive(struct garmin_dat
 
 		/* do we have a complete packet ? */
 		if (garmin_data_p->insize >= GARMIN_PKTHDR_LENGTH) {
-			len = GARMIN_PKTHDR_LENGTH+
-			   getDataLength(garmin_data_p->inbuffer);
+			u32 dlen = getDataLength(garmin_data_p->inbuffer);
+
+			if (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH) {
+				/* invalid packet, ignore rest of input */
+				dev_dbg(&garmin_data_p->port->dev, "%s - invalid length: %u\n",
+					__func__, dlen);
+				garmin_data_p->insize = 0;
+				result = -EINVPKT;
+				break;
+			}
+			len = GARMIN_PKTHDR_LENGTH + dlen;
 			if (garmin_data_p->insize >= len) {
 				garmin_write_bulk(garmin_data_p->port,
 						   garmin_data_p->inbuffer,
author maintainer
#935 lore raw

PATCH 934/990 USB: serial: sierra: validate URB length in instat callback

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tristan Madani <[email protected]>

commit a3d43b39032cc5565a5693a10c581844342372cd upstream.

sierra_instat_callback() reads request fields and one byte past the usb_ctrlrequest header without first checking that urb->actual_length is large enough. A short USB interrupt transfer could cause an out-of-bounds read.

Add two length checks matching the pattern already present in the option driver (option_instat_callback): one for the request header before accessing bRequestType, and one for the line-state data byte inside the serial-state notification handler. Use dev_err() since failing these checks causes the interrupt URB not to be resubmitted.

Fixes 033a3fb980b041 ("USB: Sierra Wireless driver update")
[ johan: use sizeof(*req_pkt) consistently ]
---
 drivers/usb/serial/sierra.c |   18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
drivers/usb/serial/sierra.c +15 -3
@@ -575,12 +575,24 @@ static void sierra_instat_callback(struc
 				__func__);
 			return;
 		}
+		if (urb->actual_length < sizeof(*req_pkt)) {
+			dev_err(&port->dev, "%s: short transfer\n",
+				__func__);
+			return;
+		}
 		if ((req_pkt->bRequestType == 0xA1) &&
 				(req_pkt->bRequest == 0x20)) {
 			int old_dcd_state;
-			unsigned char signals = *((unsigned char *)
-					urb->transfer_buffer +
-					sizeof(struct usb_ctrlrequest));
+			unsigned char signals;
+
+			if (urb->actual_length < sizeof(*req_pkt) + 1) {
+				dev_err(&port->dev,
+					"%s: short interrupt transfer\n",
+					__func__);
+				return;
+			}
+			signals = *((unsigned char *)urb->transfer_buffer +
+					sizeof(*req_pkt));
 
 			dev_dbg(&port->dev, "%s: signal x%x\n", __func__,
 				signals);
author maintainer
#936 lore raw

PATCH 935/990 USB: serial: upd78f0730: fix NULL-deref on hangup

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit 0e0b1fcfb80c0490bda7f7eb633ebb5e431c2e16 upstream.

The port tty pointer is cleared on hangup before deasserting the modem control signals and should not be used in the dtr_rts() callback.

Factor out a new upd78f0730_port_tiocmset() helper that can be used in upd78f0730_dtr_rts() to avoid dereferencing a NULL-pointer on hangup (e.g. on disconnect).

This issue was flagged by an LLM.

Fixes ea534e0b4047 ("USB: serial: add uPD78F0730 USB to Serial Adaptor Driver")
Cc Maksim Salau <[email protected]>
---
 drivers/usb/serial/upd78f0730.c |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/usb/serial/upd78f0730.c +9 -4
@@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tt
 	return res;
 }
 
-static int upd78f0730_tiocmset(struct tty_struct *tty,
+static int upd78f0730_port_tiocmset(struct usb_serial_port *port,
 			unsigned int set, unsigned int clear)
 {
-	struct usb_serial_port *port = tty->driver_data;
 	struct upd78f0730_port_private *private;
 	struct upd78f0730_set_dtr_rts request;
 	struct device *dev = &port->dev;
@@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tt
 	return res;
 }
 
+static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
+{
+	struct usb_serial_port *port = tty->driver_data;
+
+	return upd78f0730_port_tiocmset(port, set, clear);
+}
+
 static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state)
 {
 	struct upd78f0730_port_private *private;
@@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct t
 
 static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on)
 {
-	struct tty_struct *tty = port->port.tty;
 	unsigned int set = 0;
 	unsigned int clear = 0;
 
@@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct us
 	else
 		clear = TIOCM_DTR | TIOCM_RTS;
 
-	upd78f0730_tiocmset(tty, set, clear);
+	upd78f0730_port_tiocmset(port, set, clear);
 }
 
 static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty)
author maintainer
#937 lore raw

PATCH 936/990 USB: serial: io_edgeport: fix NULL-deref on early status

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit ae22e9b6412e5dc99e1cf8bd13c6176d44c7d42e upstream.

The driver submits the interrupt-in URB during probe or on first port open, which on completion may submit the bulk-in URB before all ports have been opened and their waitqueues have been initialised.

If a (malicious) device sends a status message for a port that has not yet been opened this may lead to a NULL-pointer dereference in the bulk-in completion handler when attempting to wakeup blocked tasks.

Move waitqueue initialisation from open() to port_probe() to address this.

---
 drivers/usb/serial/io_edgeport.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/usb/serial/io_edgeport.c +5 -5
@@ -877,11 +877,6 @@ static int edge_open(struct tty_struct *
 		}
 	}
 
-	/* initialize our wait queues */
-	init_waitqueue_head(&edge_port->wait_open);
-	init_waitqueue_head(&edge_port->wait_chase);
-	init_waitqueue_head(&edge_port->wait_command);
-
 	/* initialize our port settings */
 	edge_port->txCredits = 0;	/* Can't send any data yet */
 	/* Must always set this bit to enable ints! */
@@ -2965,6 +2960,11 @@ static int edge_port_probe(struct usb_se
 		return -ENOMEM;
 
 	spin_lock_init(&edge_port->ep_lock);
+
+	init_waitqueue_head(&edge_port->wait_open);
+	init_waitqueue_head(&edge_port->wait_chase);
+	init_waitqueue_head(&edge_port->wait_command);
+
 	edge_port->port = port;
 
 	usb_set_serial_port_data(port, edge_port);
author maintainer
#938 lore raw

PATCH 937/990 USB: serial: io_edgeport: fix potential close() use-after-free

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit 839ff5fa30995c40cd5fba15fd976ad63416738a upstream.

Add the missing open check on write() and locking when updating the port status during close() to prevent a racing interrupt completion handler from trying to submit more data for the port while its write URB and FIFO are being deallocated.

This issue was flagged by Sashiko when reviewing a related fix.

---
 drivers/usb/serial/io_edgeport.c |    8 ++++++++
 1 file changed, 8 insertions(+)
drivers/usb/serial/io_edgeport.c +8 -0
@@ -1085,7 +1085,9 @@ static void edge_close(struct usb_serial
 
 	/* port->close = true; */
 	edge_port->closePending = false;
+	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->open = false;
+	spin_unlock_irq(&edge_port->ep_lock);
 	edge_port->openPending = false;
 
 	usb_kill_urb(edge_port->write_urb);
@@ -1127,6 +1129,12 @@ static int edge_write(struct tty_struct
 
 	spin_lock_irqsave(&edge_port->ep_lock, flags);
 
+	/* avoid accessing freed fifo if tty_wakeup() races with close() */
+	if (!edge_port->open) {
+		spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+		return 0;
+	}
+
 	/* calculate number of bytes to put in fifo */
 	copySize = min_t(unsigned int, count,
 				(edge_port->txCredits - fifo->count));
author maintainer
#939 lore raw

PATCH 938/990 USB: serial: io_edgeport: fix potential NULL-deref at open

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit a0403880a0a638f189e5187068244d9fd5bc8d4d upstream.

Do not mark the port as open until after the write FIFO has been allocated and initialised to prevent a racing interrupt completion from attempting to send stale data and dereference the FIFO buffer pointer.

Note that the open flag defaults to false and is cleared on close() so there is no need to reinitialise it on every open().

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/usb/serial/io_edgeport.c +5 -5
@@ -885,9 +885,7 @@ static int edge_open(struct tty_struct *
 
 	/* send a open port command */
 	edge_port->openPending = true;
-	edge_port->open        = false;
 	response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0);
-
 	if (response < 0) {
 		dev_err(dev, "%s - error sending open port command\n", __func__);
 		edge_port->openPending = false;
@@ -897,8 +895,7 @@ static int edge_open(struct tty_struct *
 	/* now wait for the port to be completely opened */
 	wait_event_timeout(edge_port->wait_open, !edge_port->openPending,
 								OPEN_TIMEOUT);
-
-	if (!edge_port->open) {
+	if (edge_port->openPending) {
 		/* open timed out */
 		dev_dbg(dev, "%s - open timeout\n", __func__);
 		edge_port->openPending = false;
@@ -926,6 +923,10 @@ static int edge_open(struct tty_struct *
 		return -ENOMEM;
 	}
 
+	spin_lock_irq(&edge_port->ep_lock);
+	edge_port->open = true;
+	spin_unlock_irq(&edge_port->ep_lock);
+
 	dev_dbg(dev, "%s - Initialize TX fifo to %d bytes\n",
 		__func__, edge_port->maxTxCredits);
 
@@ -1818,7 +1819,6 @@ static void process_rcvd_status(struct e
 
 		/* we have completed the open */
 		edge_port->openPending = false;
-		edge_port->open = true;
 		wake_up(&edge_port->wait_open);
 		return;
 	}
author maintainer
#940 lore raw

PATCH 939/990 USB: serial: io_edgeport: move initial termios update to open()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit febadc65a4ef8d08a12e76d6ec50834d72cc0e59 upstream.

Explicitly update the terminal settings on open() instead of doing so from the interrupt completion handler when receiving an open command response, which in theory can be received after a failed open attempt.

Note that this will be used to fix a FIFO corruption issue and also allows for switching to synchronous commands.

---
 drivers/usb/serial/io_edgeport.c |   64 ++++++---------------------------------
 1 file changed, 10 insertions(+), 54 deletions(-)
drivers/usb/serial/io_edgeport.c +10 -54
@@ -281,8 +281,7 @@ static void handle_new_lsr(struct edgepo
 static int  send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command,
 				__u8 param);
 static int  calc_baud_rate_divisor(struct device *dev, int baud_rate, int *divisor);
-static void change_port_settings(struct tty_struct *tty,
-				struct edgeport_port *edge_port,
+static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port,
 				const struct ktermios *old_termios);
 static int  send_cmd_write_uart_register(struct edgeport_port *edge_port,
 				__u8 regNum, __u8 regValue);
@@ -923,6 +922,9 @@ static int edge_open(struct tty_struct *
 		return -ENOMEM;
 	}
 
+	if (tty)
+		edge_set_termios(tty, port, NULL);
+
 	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->open = true;
 	spin_unlock_irq(&edge_port->ep_lock);
@@ -1444,30 +1446,6 @@ static void edge_unthrottle(struct tty_s
 
 
 /*****************************************************************************
- * SerialSetTermios
- *	this function is called by the tty driver when it wants to change
- * the termios structure
- *****************************************************************************/
-static void edge_set_termios(struct tty_struct *tty,
-			     struct usb_serial_port *port,
-			     const struct ktermios *old_termios)
-{
-	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
-
-	if (edge_port == NULL)
-		return;
-
-	if (!edge_port->open) {
-		dev_dbg(&port->dev, "%s - port not opened\n", __func__);
-		return;
-	}
-
-	/* change the port settings to the new ones specified */
-	change_port_settings(tty, edge_port, old_termios);
-}
-
-
-/*****************************************************************************
  * get_lsr_info - get line status register info
  *
  * Purpose: Let user call ioctl() to get info when the UART physically
@@ -1756,7 +1734,6 @@ static void process_rcvd_status(struct e
 {
 	struct usb_serial_port *port;
 	struct edgeport_port *edge_port;
-	struct tty_struct *tty;
 	struct device *dev;
 	__u8 code = edge_serial->rxStatusCode;
 
@@ -1808,15 +1785,6 @@ static void process_rcvd_status(struct e
 			__func__, edge_serial->rxPort, byte2, edge_port->txCredits);
 		handle_new_msr(edge_port, byte2);
 
-		/* send the current line settings to the port so we are
-		   in sync with any further termios calls */
-		tty = tty_port_tty_get(&edge_port->port->port);
-		if (tty) {
-			change_port_settings(tty,
-				edge_port, &tty->termios);
-			tty_kref_put(tty);
-		}
-
 		/* we have completed the open */
 		edge_port->openPending = false;
 		wake_up(&edge_port->wait_open);
@@ -2328,18 +2296,12 @@ static int send_cmd_write_uart_register(
 }
 
 
-/*****************************************************************************
- * change_port_settings
- *	This routine is called to set the UART on the device to match the
- *	specified new settings.
- *****************************************************************************/
-
-static void change_port_settings(struct tty_struct *tty,
-	struct edgeport_port *edge_port, const struct ktermios *old_termios)
+static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port,
+		const struct ktermios *old_termios)
 {
-	struct device *dev = &edge_port->port->dev;
-	struct edgeport_serial *edge_serial =
-			usb_get_serial_data(edge_port->port->serial);
+	struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial);
+	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
+	struct device *dev = &port->dev;
 	int baud;
 	unsigned cflag;
 	__u8 mask = 0xff;
@@ -2350,12 +2312,6 @@ static void change_port_settings(struct
 	__u8 txFlow;
 	int status;
 
-	if (!edge_port->open &&
-	    !edge_port->openPending) {
-		dev_dbg(dev, "%s - port not opened\n", __func__);
-		return;
-	}
-
 	cflag = tty->termios.c_cflag;
 
 	switch (cflag & CSIZE) {
@@ -2489,7 +2445,7 @@ static void change_port_settings(struct
 
 	dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud);
 	status = send_cmd_write_baud_rate(edge_port, baud);
-	if (status == -1) {
+	if (status == -1 && old_termios) {
 		/* Speed change was not possible - put back the old speed */
 		baud = tty_termios_baud_rate(old_termios);
 		tty_encode_baud_rate(tty, baud, baud);
author maintainer
#941 lore raw

PATCH 940/990 USB: serial: io_edgeport: fix potential fifo corruption

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit 270f76c3b88c9cc3d6ca58c5c0c0f34c2373b27c upstream.

The device buffer size is determined during open() and the driver allocates a TX FIFO of corresponding size.

Add the missing sanity check to prevent memory corruption in case a malicious device sends a second open response with a different buffer size.

This issue was flagged by Sashiko when reviewing a related fix.

---
 drivers/usb/serial/io_edgeport.c |   15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/usb/serial/io_edgeport.c +14 -1
@@ -877,13 +877,17 @@ static int edge_open(struct tty_struct *
 	}
 
 	/* initialize our port settings */
+	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->txCredits = 0;	/* Can't send any data yet */
+	edge_port->maxTxCredits = 0;
+	edge_port->openPending = true;
+	spin_unlock_irq(&edge_port->ep_lock);
+
 	/* Must always set this bit to enable ints! */
 	edge_port->shadowMCR = MCR_MASTER_IE;
 	edge_port->chaseResponsePending = false;
 
 	/* send a open port command */
-	edge_port->openPending = true;
 	response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0);
 	if (response < 0) {
 		dev_err(dev, "%s - error sending open port command\n", __func__);
@@ -1736,6 +1740,7 @@ static void process_rcvd_status(struct e
 	struct edgeport_port *edge_port;
 	struct device *dev;
 	__u8 code = edge_serial->rxStatusCode;
+	unsigned long flags;
 
 	/* switch the port pointer to the one being currently talked about */
 	if (edge_serial->rxPort >= edge_serial->serial->num_ports)
@@ -1779,6 +1784,12 @@ static void process_rcvd_status(struct e
 	}
 
 	if (code == IOSP_STATUS_OPEN_RSP) {
+		spin_lock_irqsave(&edge_port->ep_lock, flags);
+		/* reject stray open responses to avoid FIFO corruption */
+		if (!edge_port->openPending) {
+			spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+			return;
+		}
 		edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3);
 		edge_port->maxTxCredits = edge_port->txCredits;
 		dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n",
@@ -1787,6 +1798,8 @@ static void process_rcvd_status(struct e
 
 		/* we have completed the open */
 		edge_port->openPending = false;
+		spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+
 		wake_up(&edge_port->wait_open);
 		return;
 	}
author maintainer
#942 lore raw

PATCH 941/990 USB: serial: io_edgeport: fix potential use-after-free on disconnect

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit 50613e6380db7a904ef15c60ed0c436baf308f0a upstream.

The driver submits command URBs asynchronously but fails to stop them on disconnect, something which could lead to a use-after-free when accessing driver data in the completion handler after a port has been unbound.

Add an URB anchor to track and kill outstanding command URBs on disconnect.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   19 ++++++-------------
 1 file changed, 6 insertions(+), 13 deletions(-)
drivers/usb/serial/io_edgeport.c +6 -13
@@ -225,6 +225,7 @@ struct edgeport_serial {
 	__u8			rxStatusParam;			/* the receive status parameter */
 	__s16			rxBytesRemaining;		/* the number of port bytes left to read */
 	struct usb_serial	*serial;			/* loop back to the owner of this object */
+	struct usb_anchor	cmd_anchor;
 };
 
 /* baud rate information */
@@ -261,9 +262,6 @@ static const struct divisor_table_entry
 	{   230400,	1},
 };
 
-/* Number of outstanding Command Write Urbs */
-static atomic_t CmdUrbs = ATOMIC_INIT(0);
-
 
 /* function prototypes */
 
@@ -776,11 +774,6 @@ static void edge_bulk_out_cmd_callback(s
 	struct device *dev = &urb->dev->dev;
 	int status = urb->status;
 
-	atomic_dec(&CmdUrbs);
-	dev_dbg(dev, "%s - FREE URB %p (outstanding %d)\n", __func__, urb,
-		atomic_read(&CmdUrbs));
-
-
 	/* clean up the transfer buffer */
 	kfree(urb->transfer_buffer);
 
@@ -2127,24 +2120,21 @@ static int write_cmd_usb(struct edgeport
 	if (!urb)
 		return -ENOMEM;
 
-	atomic_inc(&CmdUrbs);
-	dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n",
-		__func__, urb, atomic_read(&CmdUrbs));
-
 	usb_fill_bulk_urb(urb, edge_serial->serial->dev,
 			usb_sndbulkpipe(edge_serial->serial->dev,
 					edge_serial->bulk_out_endpoint),
 			buffer, length, edge_bulk_out_cmd_callback, edge_port);
 
 	edge_port->commandPending = true;
+	usb_anchor_urb(urb, &edge_serial->cmd_anchor);
 	status = usb_submit_urb(urb, GFP_ATOMIC);
 
 	if (status) {
 		/* something went wrong */
 		dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n",
 			__func__, status);
+		usb_unanchor_urb(urb);
 		usb_free_urb(urb);
-		atomic_dec(&CmdUrbs);
 		return status;
 	}
 
@@ -2696,6 +2686,7 @@ static int edge_startup(struct usb_seria
 
 	spin_lock_init(&edge_serial->es_lock);
 	edge_serial->serial = serial;
+	init_usb_anchor(&edge_serial->cmd_anchor);
 	usb_set_serial_data(serial, edge_serial);
 
 	/* get the name for the device from the device */
@@ -2900,6 +2891,8 @@ static void edge_disconnect(struct usb_s
 {
 	struct edgeport_serial *edge_serial = usb_get_serial_data(serial);
 
+	usb_kill_anchored_urbs(&edge_serial->cmd_anchor);
+
 	if (edge_serial->is_epic) {
 		usb_kill_urb(edge_serial->interrupt_read_urb);
 		usb_kill_urb(edge_serial->read_urb);
author maintainer
#943 lore raw

PATCH 942/990 USB: serial: io_edgeport: serialise MCR accesses

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johan Hovold <[email protected]>

commit 6e4629504d7e5a22dd26f3b262f0a0f80e3cad6a upstream.

Add a mutex to serialise modem control register updates to prevent concurrent tasks from interfering with each other.

Note that the register updates are currently asynchronous so a task may read back a value which has not yet taken effect.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   15 +++++++++++++++
 1 file changed, 15 insertions(+)
drivers/usb/serial/io_edgeport.c +15 -0
@@ -168,6 +168,7 @@ struct edgeport_port {
 	struct urb		*write_urb;		/* write URB for this port */
 	bool			write_in_progress;	/* 'true' while a write URB is outstanding */
 	spinlock_t		ep_lock;
+	struct mutex		mutex;
 
 	__u8			shadowLCR;		/* last LCR value received */
 	__u8			shadowMCR;		/* last MCR value received */
@@ -877,7 +878,10 @@ static int edge_open(struct tty_struct *
 	spin_unlock_irq(&edge_port->ep_lock);
 
 	/* Must always set this bit to enable ints! */
+	mutex_lock(&edge_port->mutex);
 	edge_port->shadowMCR = MCR_MASTER_IE;
+	mutex_unlock(&edge_port->mutex);
+
 	edge_port->chaseResponsePending = false;
 
 	/* send a open port command */
@@ -1398,9 +1402,11 @@ static void edge_throttle(struct tty_str
 
 	/* if we are implementing RTS/CTS, toggle that line */
 	if (C_CRTSCTS(tty)) {
+		mutex_lock(&edge_port->mutex);
 		edge_port->shadowMCR &= ~MCR_RTS;
 		status = send_cmd_write_uart_register(edge_port, MCR,
 							edge_port->shadowMCR);
+		mutex_unlock(&edge_port->mutex);
 		if (status != 0)
 			return;
 	}
@@ -1435,9 +1441,11 @@ static void edge_unthrottle(struct tty_s
 	}
 	/* if we are implementing RTS/CTS, toggle that line */
 	if (C_CRTSCTS(tty)) {
+		mutex_lock(&edge_port->mutex);
 		edge_port->shadowMCR |= MCR_RTS;
 		send_cmd_write_uart_register(edge_port, MCR,
 						edge_port->shadowMCR);
+		mutex_unlock(&edge_port->mutex);
 	}
 }
 
@@ -1478,6 +1486,7 @@ static int edge_tiocmset(struct tty_stru
 	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
 	unsigned int mcr;
 
+	mutex_lock(&edge_port->mutex);
 	mcr = edge_port->shadowMCR;
 	if (set & TIOCM_RTS)
 		mcr |= MCR_RTS;
@@ -1496,6 +1505,7 @@ static int edge_tiocmset(struct tty_stru
 	edge_port->shadowMCR = mcr;
 
 	send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
+	mutex_unlock(&edge_port->mutex);
 
 	return 0;
 }
@@ -1509,6 +1519,7 @@ static int edge_tiocmget(struct tty_stru
 	unsigned int mcr;
 
 	msr = edge_port->shadowMSR;
+	mutex_lock(&edge_port->mutex);
 	mcr = edge_port->shadowMCR;
 	result = ((mcr & MCR_DTR)	? TIOCM_DTR: 0)	  /* 0x002 */
 		  | ((mcr & MCR_RTS)	? TIOCM_RTS: 0)   /* 0x004 */
@@ -1516,6 +1527,7 @@ static int edge_tiocmget(struct tty_stru
 		  | ((msr & EDGEPORT_MSR_CD)	? TIOCM_CAR: 0)   /* 0x040 */
 		  | ((msr & EDGEPORT_MSR_RI)	? TIOCM_RI:  0)   /* 0x080 */
 		  | ((msr & EDGEPORT_MSR_DSR)	? TIOCM_DSR: 0);  /* 0x100 */
+	mutex_unlock(&edge_port->mutex);
 
 	return result;
 }
@@ -2430,12 +2442,14 @@ static void edge_set_termios(struct tty_
 		return;
 
 	/* set up the MCR register and send it to the EdgePort */
+	mutex_lock(&edge_port->mutex);
 	edge_port->shadowMCR = MCR_MASTER_IE;
 	if (cflag & CBAUD)
 		edge_port->shadowMCR |= (MCR_DTR | MCR_RTS);
 
 	status = send_cmd_write_uart_register(edge_port, MCR,
 						edge_port->shadowMCR);
+	mutex_unlock(&edge_port->mutex);
 	if (status != 0)
 		return;
 
@@ -2930,6 +2944,7 @@ static int edge_port_probe(struct usb_se
 		return -ENOMEM;
 
 	spin_lock_init(&edge_port->ep_lock);
+	mutex_init(&edge_port->mutex);
 
 	init_waitqueue_head(&edge_port->wait_open);
 	init_waitqueue_head(&edge_port->wait_chase);
author maintainer
#944 lore raw

PATCH 943/990 dt-bindings: iio: adc: Add syscon property for multi-SCU SoCs

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Billy Tsai <[email protected]>

commit 6ec0623a7c77bc2c383e9971d7b0c9df3ec988fb upstream.

The ADC's reference-voltage trimming data lives in a System Control Unit (SCU) register. SoCs with a single SCU instance let the driver locate it without any additional information, but SoCs such as AST2700 that expose more than one SCU node need an explicit phandle to disambiguate which one holds the trimming data.

Add an "aspeed,trim-syscon" phandle property, and require it for the AST2700 compatibles since they are the first multi-SCU SoCs supported by this driver.

---
 Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml |   17 ++++++++++
 1 file changed, 17 insertions(+)
Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml +17 -0
@@ -62,6 +62,11 @@ properties:
     description:
       Inform the driver that last channel will be used to sensor battery.
 
+  aspeed,trim-syscon:
+    $ref: /schemas/types.yaml#/definitions/phandle
+    description:
+      Phandle to the SCU holding the ADC's reference-voltage trimming data.
+
 required:
   - compatible
   - reg
@@ -69,6 +74,18 @@ required:
   - resets
   - "#io-channel-cells"
 
+allOf:
+  - if:
+      properties:
+        compatible:
+          contains:
+            enum:
+              - aspeed,ast2700-adc0
+              - aspeed,ast2700-adc1
+    then:
+      required:
+        - aspeed,trim-syscon
+
 additionalProperties: false
 
 examples:
author maintainer
#945 lore raw

PATCH 944/990 iio: accel: adxl313: add missing buffer selections in Kconfig

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Alexis Bouzigues <[email protected]>

commit 4e9f192f997dc56f309090233352d62edbea42ce upstream.

The FIFO support added to the ADXL313 core uses devm_iio_kfifo_buffer_setup() and iio_push_to_buffers(), but its Kconfig entry does not select the required buffer support. Enabling either frontend without IIO_BUFFER or IIO_KFIFO_BUF causes undefined references to devm_iio_kfifo_buffer_setup_ext() and iio_push_to_buffers().

Select IIO_BUFFER and IIO_KFIFO_BUF from the shared ADXL313 core symbol so both the I2C and SPI frontends have the required dependencies.

Fixes ff8093fa6ba4 ("iio: accel: adxl313: add buffered FIFO watermark with interrupt handling")
---
 drivers/iio/accel/Kconfig |    2 ++
 1 file changed, 2 insertions(+)
drivers/iio/accel/Kconfig +2 -0
@@ -32,6 +32,8 @@ config ADIS16209
 
 config ADXL313
 	tristate
+	select IIO_BUFFER
+	select IIO_KFIFO_BUF
 
 config ADXL313_I2C
 	tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver"
author maintainer
#946 lore raw

PATCH 945/990 iio: accel: kxsd9: Fix potential use-after-free on removal

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Guangshuo Li <[email protected]>

commit fd7334314f63a3a2a4927f209b2ca0e33d111840 upstream.

Unregistering an IIO device with an active triggered buffer detaches its poll function. Freeing the poll function first can therefore make iio_device_unregister() access freed memory.

Unregister the device before cleaning up the triggered buffer.

This issue was found by our static analysis tool under development.

Fixes 0427a106a98a ("iio: accel: kxsd9: Add triggered buffer handling")
---
 drivers/iio/accel/kxsd9.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/accel/kxsd9.c +1 -1
@@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *
 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
 	struct kxsd9_state *st = iio_priv(indio_dev);
 
-	iio_triggered_buffer_cleanup(indio_dev);
 	iio_device_unregister(indio_dev);
+	iio_triggered_buffer_cleanup(indio_dev);
 	pm_runtime_get_sync(dev);
 	pm_runtime_put_noidle(dev);
 	pm_runtime_disable(dev);
author maintainer
#947 lore raw

PATCH 946/990 iio: acpi: Accept comma separated values in ROTM strings

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yu-Hsiang Tseng <[email protected]>

commit dd53f1841ecfa2da152cbc31038a5f125b2b9e57 upstream.

The ROTM method of the MXC6655 accelerometer on the Higole F9B, an Alder Lake-N handheld (AMI BIOS F9D_16G_P800217, DMI strings are all "Default string"), separates the values with a comma and a space:

	Method (ROTM, 0, NotSerialized)
	{
	    Name (SBUF, Package (0x03)
	    {
	        "-1, 0, 0",
	        "0, 1, 0",
	        "0, 0, 1"
	    })
	    Return (SBUF)
	}

iio_read_acpi_mount_matrix() only accepts the space separated form used in Microsoft's example ("0 1 0"). It rejects this matrix and mxc4005 falls back to the identity matrix:

	mxc4005 i2c-MXC6655:00: Incorrect ACPI mount matrix string format
	mxc4005 i2c-MXC6655:00: mounting matrix not found: using identity...

With the X axis not inverted, iio-sensor-proxy reports left-up when the device is held right-up and vice versa, so the desktop turns the picture upside down whenever the handheld is held in landscape.

It is not the only BIOS written this way. The BOSC0200 on the AYANEO Air Plus uses commas in its ROMS method as well, with a space before one of them, and its ROMK method has "1, 0,0":

	Method (ROMS, 0, NotSerialized)
	{
	    Name (SBUF, Package (0x03)
	    {
	        "-1, 0, 0",
	        "0, -1 , 0",
	        "0, 0, -1"
	    })
	    Return (SBUF)
	}

The kernel's sscanf() does not support '%*[', so there is no clean way to take both separators in a single format string. That leaves either a second sscanf() call with a comma format, or normalizing the separator first. Do the latter: turn the commas into spaces before parsing, so the existing "%d %d %d" format, which already takes any amount of white space around the values, keeps working unchanged. The strings live in the buffer acpi_evaluate_object() allocated for us, so they can be modified in place.

With this change in_accel_mount_matrix on the Higole F9B reads "-1, 0, 0; 0, 1, 0; 0, 0, 1" and, with no udev hwdb override, the desktop rotates correctly in all four orientations. The AYANEO Air Plus was not tested; systemd's hwdb has an entry for it, which iio-sensor-proxy prefers over the kernel's matrix.

---
 drivers/iio/industrialio-acpi.c |    9 +++++++++
 1 file changed, 9 insertions(+)
drivers/iio/industrialio-acpi.c +9 -0
@@ -6,6 +6,7 @@
 #include <linux/export.h>
 #include <linux/iio/iio.h>
 #include <linux/sprintf.h>
+#include <linux/string.h>
 
 /**
  * iio_read_acpi_mount_matrix() - Read accelerometer mount matrix info from ACPI
@@ -63,6 +64,14 @@ bool iio_read_acpi_mount_matrix(struct d
 		}
 
 		str = elements[i].string.pointer;
+		/*
+		 * Microsoft's example separates the values with spaces, "0 1 0".
+		 * Some BIOSes use commas instead, with or without spaces around
+		 * them: "0, 1, 0", "0, -1 , 0", "1, 0,0". The string lives in
+		 * the buffer allocated for us above, so turn the commas into
+		 * spaces in place before parsing.
+		 */
+		strreplace(str, ',', ' ');
 		if (sscanf(str, "%d %d %d", &val[0], &val[1], &val[2]) != 3) {
 			dev_err(dev, "Incorrect ACPI mount matrix string format\n");
 			goto out_free_buffer;
author maintainer
#948 lore raw

PATCH 947/990 iio: afe: rescale: expose offset if rescaler or source has one

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Amer <[email protected]>

commit c293f0db308fe76a0a9b0f6674cd2dea149b03aa upstream.

A rescale channel advertises IIO_CHAN_INFO_OFFSET only when its own offset is non-zero. A child rescale therefore hides a source offset, and consumers apply raw * scale and drop it, even though rescale_read_raw() folds the source offset in.

Expose the attribute when either the rescaler or the source channel provides an offset.

Fixes a29c3283653b ("iio: afe: rescale: add offset support")
---
 drivers/iio/afe/iio-rescale.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/iio/afe/iio-rescale.c +2 -1
@@ -304,7 +304,8 @@ static int rescale_configure_channel(str
 	chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
 		BIT(IIO_CHAN_INFO_SCALE);
 
-	if (rescale->offset)
+	if (rescale->offset ||
+	    iio_channel_has_info(schan, IIO_CHAN_INFO_OFFSET))
 		chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OFFSET);
 
 	/*
author maintainer
#949 lore raw

PATCH 948/990 iio: atlas-ezo: Fix humidity channel read support

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Nikhil Gautam <[email protected]>

commit 0cb3fc8987038a26ac0f581bfa26b16daf6ca6a7 upstream.

The atlas_ezo_read_raw() function rejects channels that are not of type IIO_CONCENTRATION, preventing the relative humidity channel from reading raw and scale values.

Remove the early channel type check to allow both concentration and relative humidity channels to reach the mask-specific handling.

Fixes dc3ebfcaa51f ("iio: chemical: atlas-ezo-sensor: add humidity sensor support")
---
 drivers/iio/chemical/atlas-ezo-sensor.c |    3 ---
 1 file changed, 3 deletions(-)
drivers/iio/chemical/atlas-ezo-sensor.c +0 -3
@@ -117,9 +117,6 @@ static int atlas_ezo_read_raw(struct iio
 	struct atlas_ezo_data *data = iio_priv(indio_dev);
 	struct i2c_client *client = data->client;
 
-	if (chan->type != IIO_CONCENTRATION)
-		return -EINVAL;
-
 	switch (mask) {
 	case IIO_CHAN_INFO_RAW: {
 		int ret;
author maintainer
#950 lore raw

PATCH 949/990 iio: common: scmi_sensors: fix truncating 64-bit divisions

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Arnav Kapoor <[email protected]>

commit 043ececf147863fbd253687aa0b9edcac358a711 upstream.

do_div() divides a 64-bit dividend by a 32-bit divisor: the divisor is stored in a uint32_t on all architectures. The driver passes 64-bit divisors to it in several places, so they are silently truncated:

- scmi_iio_set_odr_val() divides by uHz, which exceeds 32 bits for sampling frequencies above ~4294 Hz.
- convert_ns_to_freq() divides by interval_ns, which exceeds 32 bits for update intervals of ~4.29 s and above. If its low 32 bits happen to be zero, this is a division by zero.
- scmi_iio_get_odr_val(), scmi_iio_convert_interval_to_ns(), scmi_iio_sensor_update_cb() and scmi_iio_get_raw_available() divide by int_pow(10, n), which returns u64 and exceeds 32 bits for n >= 10. The SCMI exponent fields allow values down to -16.

Truncation results in wrong sampling frequency, timestamp and raw_available values being reported to userspace.

Use div64_u64() and div64_u64_rem(), which take a 64-bit divisor.

---
 drivers/iio/common/scmi_sensors/scmi_iio.c |   27 +++++++++++++--------------
 1 file changed, 13 insertions(+), 14 deletions(-)
drivers/iio/common/scmi_sensors/scmi_iio.c +13 -14
@@ -14,6 +14,7 @@
 #include <linux/iio/sysfs.h>
 #include <linux/kernel.h>
 #include <linux/kthread.h>
+#include <linux/math64.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
 #include <linux/scmi_protocol.h>
@@ -71,8 +72,7 @@ static int scmi_iio_sensor_update_cb(str
 		tstamp_scale = sensor->sensor_info->tstamp_scale +
 			       const_ilog2(NSEC_PER_SEC) / const_ilog2(10);
 		if (tstamp_scale < 0) {
-			do_div(time, int_pow(10, abs(tstamp_scale)));
-			time_ns = time;
+			time_ns = div64_u64(time, int_pow(10, abs(tstamp_scale)));
 		} else {
 			time_ns = time * int_pow(10, tstamp_scale);
 		}
@@ -163,7 +163,7 @@ static int scmi_iio_set_odr_val(struct i
 	mult = scnprintf(buf, sizeof(buf), "%llu", sf) - 1;
 
 	sec = int_pow(10, mult) * MICROHZ_PER_HZ;
-	do_div(sec, uHz);
+	sec = div64_u64(sec, uHz);
 	if (sec == 0) {
 		dev_err(&iio_dev->dev,
 			"Trying to set invalid sensor update value for sensor %s",
@@ -238,13 +238,10 @@ static int scmi_iio_read_avail(struct ii
 
 static void convert_ns_to_freq(u64 interval_ns, u64 *hz, u64 *uhz)
 {
-	u64 rem, freq;
+	u64 rem;
 
-	freq = NSEC_PER_SEC;
-	rem = do_div(freq, interval_ns);
-	*hz = freq;
-	*uhz = rem * 1000000UL;
-	do_div(*uhz, interval_ns);
+	*hz = div64_u64_rem(HZ_PER_GHZ, interval_ns, &rem);
+	*uhz = div64_u64(rem * MICROHZ_PER_HZ, interval_ns);
 }
 
 static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2)
@@ -270,7 +267,8 @@ static int scmi_iio_get_odr_val(struct i
 	mult = SCMI_SENS_CFG_GET_UPDATE_EXP(sensor_config);
 	if (mult < 0) {
 		sensor_interval_mult = int_pow(10, abs(mult));
-		do_div(sensor_update_interval, sensor_interval_mult);
+		sensor_update_interval = div64_u64(sensor_update_interval,
+						   sensor_interval_mult);
 	} else {
 		sensor_interval_mult = int_pow(10, mult);
 		sensor_update_interval =
@@ -396,9 +394,9 @@ static ssize_t scmi_iio_get_raw_availabl
 		 */
 		exponent = exponent - scale;
 		if (exponent < 0) {
-			rem = do_div(resolution,
-				     int_pow(10, abs(exponent))
-				     );
+			resolution = div64_u64_rem(resolution,
+						   int_pow(10, abs(exponent)),
+						   &rem);
 			len = sysfs_emit(buf,
 					"[%lld %llu.%llu %lld]\n", min_range,
 					resolution, rem, max_range);
@@ -503,7 +501,8 @@ static u64 scmi_iio_convert_interval_to_
 	mult = SCMI_SENS_INTVL_GET_EXP(val);
 	if (mult < 0) {
 		sensor_interval_mult = int_pow(10, abs(mult));
-		do_div(sensor_update_interval, sensor_interval_mult);
+		sensor_update_interval = div64_u64(sensor_update_interval,
+						   sensor_interval_mult);
 	} else {
 		sensor_interval_mult = int_pow(10, mult);
 		sensor_update_interval =
author maintainer
#951 lore raw

PATCH 950/990 iio: dac: mcp4725: Update the cached DAC value only on success

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Baek Kyu, Kim <[email protected]>

commit 098a4c37dc8815ea941866179220394e4d182c67 upstream.

mcp4725_write_raw() updates dac_value even if mcp4725_set_value() rejects the requested value or reports an I2C transfer error. After writing 1000, a rejected write of 4096 returns -EINVAL without an I2C transfer, but out_voltage0_raw reports 4096. A later powerdown exit sends 00 00 instead of the 03 e8 frame for the last successful value. The EEPROM store path uses the same cache.

Return the setter error before updating dac_value. This keeps the last successful software value for readback, powerdown exit and EEPROM writes.

Fixes cf35ad61aca2 ("iio: add mcp4725 I2C DAC driver")
---
 drivers/iio/dac/mcp4725.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/iio/dac/mcp4725.c +2 -0
@@ -357,6 +357,8 @@ static int mcp4725_write_raw(struct iio_
 	switch (mask) {
 	case IIO_CHAN_INFO_RAW:
 		ret = mcp4725_set_value(indio_dev, val);
+		if (ret)
+			return ret;
 		data->dac_value = val;
 		break;
 	default:
author maintainer
#952 lore raw

PATCH 951/990 iio: gyro: bmg160: reject duplicate event disable

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jiale Yao <[email protected]>

commit d0c8bd5d18a492d64d05482f4b1700e14df7ff84 upstream.

The IIO core does not filter duplicate writes to the event enable attribute. bmg160_write_event_config() already ignores repeated enable requests, but a repeated disable request still calls bmg160_set_power_state(data, false), dropping a runtime PM reference that was not acquired for this request. This can underflow the runtime PM usage count and trigger a "Runtime PM usage count underflow" warning.

Return early when the requested state already matches ev_enable_state.

Fixes 22b46c45fb9b ("iio:gyro:bmg160 Gyro Sensor driver")
---
 drivers/iio/gyro/bmg160_core.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/gyro/bmg160_core.c +1 -1
@@ -761,7 +761,7 @@ static int bmg160_write_event_config(str
 	struct bmg160_data *data = iio_priv(indio_dev);
 	int ret;
 
-	if (state && data->ev_enable_state)
+	if (state == data->ev_enable_state)
 		return 0;
 
 	mutex_lock(&data->mutex);
author maintainer
#953 lore raw

PATCH 952/990 iio: hid-sensor: Fix scale for magnetic north heading

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Maximilian Czirr <[email protected]>

commit c72dcaeaabd60e164e7324f80ccb037e879eefdd upstream.

hid_sensor_format_scale() applies the HID unit exponent only when the usage and unit match an entry in unit_conversion[].

Rotation-from-north support uses HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, but that usage has no entry in the conversion table. As a result, the unit exponent is ignored and the heading can be exposed with a scale of 1 instead of the scale specified by the HID descriptor.

Add a unitless conversion entry so the HID unit exponent is applied to the magnetic north heading. A sensor reporting an exponent of -5 then correctly exposes a scale of 0.00001 instead of 1.

Fixes abea9c62c32f ("iio: hid-sensor-magn-3d: Add support for rotation from north")
---
 drivers/iio/common/hid-sensors/hid-sensor-attributes.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/iio/common/hid-sensors/hid-sensor-attributes.c +2 -0
@@ -38,6 +38,8 @@ static const struct {
 	{HID_USAGE_SENSOR_COMPASS_3D, 0, 0, 1000000},
 	{HID_USAGE_SENSOR_COMPASS_3D, HID_USAGE_SENSOR_UNITS_GAUSS, 1, 0},
 
+	{HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, 0, 1, 0},
+
 	{HID_USAGE_SENSOR_INCLINOMETER_3D, 0, 0, 17453293},
 	{HID_USAGE_SENSOR_INCLINOMETER_3D,
 		HID_USAGE_SENSOR_UNITS_DEGREES, 0, 17453293},
author maintainer
#954 lore raw

PATCH 953/990 iio: hid-sensors: fix fractional part for unit exponents -7 and -8

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Srinivas Pandruvada <[email protected]>

commit 79c8dffd84e9784ec05bea68dbe5e71f7ec9941a upstream.

split_micro_fraction() scales the remainder to micro units by multiplying it by 10^(6 - exp). The unit exponent of a HID field goes down to -8, so exp can be 7 or 8 here. Then the argument of int_pow() is negative, which the unsigned parameter turns into a huge power of
ten: 0 modulo 2^64. As a result, the fractional part of a value read from the hysteresis attributes is always reported as 0.

Divide by 10^(exp - 6) in these two cases. This matches the reverse conversion in convert_to_vtf_format().

Fixes 73c6768b710a ("iio: hid-sensors: Common attribute and trigger")
---
 drivers/iio/common/hid-sensors/hid-sensor-attributes.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/iio/common/hid-sensors/hid-sensor-attributes.c +6 -1
@@ -99,9 +99,14 @@ static void simple_div(int dividend, int
 static void split_micro_fraction(unsigned int no, int exp, int *val1, int *val2)
 {
 	int divisor = int_pow(10, exp);
+	unsigned int rem;
 
 	*val1 = no / divisor;
-	*val2 = no % divisor * int_pow(10, 6 - exp);
+	rem = no % divisor;
+	if (exp > 6)
+		*val2 = rem / (unsigned int)int_pow(10, exp - 6);
+	else
+		*val2 = rem * int_pow(10, 6 - exp);
 }
 
 /*
author maintainer
#955 lore raw

PATCH 954/990 iio: humidity: am2315: fix negative temperature decoding

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Vidhu Sarwal <[email protected]>

commit 0a570feeca37d85fbfd6b4f6e3d9f33e1461c634 upstream.

The AM2315/AM2320 report temperature as a sign-magnitude value, with bit 15 as the sign and bits 14-0 as the magnitude. am2315_read_data() stores the raw value directly in an s16, causing negative temperatures to be interpreted as two's complement. Both the read_raw and the triggered buffer paths are affected.

Decode the sign bit before storing the temperature value. Positive readings are unaffected.

Fixes 366a3270c1c5 ("iio: humidity: Add support for AM2315")
---
 drivers/iio/humidity/am2315.c |   12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/iio/humidity/am2315.c +10 -2
@@ -113,6 +113,7 @@ static int am2315_read_data(struct am231
 	 */
 	u8 rx_buf[8];
 	u16 crc;
+	u16 temp_raw;
 
 	/* First wake up the device. */
 	am2315_ping(data->client);
@@ -144,8 +145,15 @@ static int am2315_read_data(struct am231
 
 	sensor_data->hum_data = (rx_buf[AM2315_HUM_OFFSET] << 8) |
 				 rx_buf[AM2315_HUM_OFFSET + 1];
-	sensor_data->temp_data = (rx_buf[AM2315_TEMP_OFFSET] << 8) |
-				  rx_buf[AM2315_TEMP_OFFSET + 1];
+
+	/*
+	 * Temperature is sign-magnitude, not two's complement:
+	 * bit 15 is the sign, bits 14-0 are the magnitude (x0.1 degC).
+	 */
+	temp_raw = (rx_buf[AM2315_TEMP_OFFSET] << 8) |
+		   rx_buf[AM2315_TEMP_OFFSET + 1];
+	sensor_data->temp_data = (temp_raw & 0x8000) ?
+				  -(temp_raw & 0x7fff) : temp_raw;
 
 	return ret;
 
author maintainer
#956 lore raw

PATCH 955/990 iio: imu: inv_icm42600: fix parsing of all FIFO frames for odr change

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jean-Baptiste Maneyrol <[email protected]>

commit 4a141623442888458d147f4e61fe47411c0e4e17 upstream.

For getting all odr change events, we need to parse all FIFO frames in each iio device. Fix this correctly by sending effectively all frames to all iio devices.

Previously only batches of frames containing a matching sensor event were sent to the corresponding iio device.

Fixes f670d4d34773 ("iio: imu: inv_icm42600: fix odr change not caught in certain cases")
---
 drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c |   24 ++++++++-------------
 1 file changed, 10 insertions(+), 14 deletions(-)
drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c +10 -14
@@ -513,22 +513,20 @@ int inv_icm42600_buffer_fifo_parse(struc
 		ts = &gyro_st->ts;
 		inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_gyro,
 						st->timestamp.gyro);
-		ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro);
-		if (ret)
-			return ret;
 	}
 
+	ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro);
+	if (ret)
+		return ret;
+
 	/* handle accelerometer timestamp and FIFO data parsing */
 	if (st->fifo.nb.accel > 0) {
 		ts = &accel_st->ts;
 		inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_accel,
 						st->timestamp.accel);
-		ret = inv_icm42600_accel_parse_fifo(st->indio_accel);
-		if (ret)
-			return ret;
 	}
 
-	return 0;
+	return inv_icm42600_accel_parse_fifo(st->indio_accel);
 }
 
 int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st,
@@ -553,20 +551,18 @@ int inv_icm42600_buffer_hwfifo_flush(str
 	if (st->fifo.nb.gyro > 0) {
 		ts = &gyro_st->ts;
 		inv_sensors_timestamp_interrupt(ts, st->fifo.nb.gyro, gyro_ts);
-		ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro);
-		if (ret)
-			return ret;
 	}
 
+	ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro);
+	if (ret)
+		return ret;
+
 	if (st->fifo.nb.accel > 0) {
 		ts = &accel_st->ts;
 		inv_sensors_timestamp_interrupt(ts, st->fifo.nb.accel, accel_ts);
-		ret = inv_icm42600_accel_parse_fifo(st->indio_accel);
-		if (ret)
-			return ret;
 	}
 
-	return 0;
+	return inv_icm42600_accel_parse_fifo(st->indio_accel);
 }
 
 int inv_icm42600_buffer_init(struct inv_icm42600_state *st)
author maintainer
#957 lore raw

PATCH 956/990 iio: imu: inv_mpu6050: fix magnetometer scale of Y and Z axes

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Arnav Kapoor <[email protected]>

commit e5f7a6684a23d9b20184a81b4ebded3b3504ccdc upstream.

inv_mpu_magn_get_scale() returns st->magn_raw_to_gauss[chan->address], where magn_raw_to_gauss[] holds one coefficient per axis, computed in inv_magn_init() from the per-axis factory sensitivity adjustment values (ASAX, ASAY, ASAZ) of the AK8975/AK8963 magnetometer.

However INV_MPU9X50_MAGN_CHAN() never sets .address, so it is 0 for all three magnetometer channels. As a result the Y and Z channels report the scale computed from the X axis adjustment value, and userspace scales the Y and Z readings with the wrong per-axis calibration.

Set .address to the axis index (0 for X, 1 for Y, 2 for Z) in the channel macro, matching the order used to fill magn_raw_to_gauss[].

Fixes b1392de06184 ("iio: imu: inv_mpu6050: add MPU925x magnetometer support")
---
 drivers/iio/imu/inv_mpu6050/inv_mpu_core.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +2 -0
@@ -1574,6 +1574,8 @@ static const unsigned long inv_mpu_scan_
 		.type = IIO_MAGN,					\
 		.modified = 1,						\
 		.channel2 = _chan2,					\
+		/* index of the axis in magn_raw_to_gauss[] */		\
+		.address = (_chan2) - IIO_MOD_X,			\
 		.info_mask_separate = BIT(IIO_CHAN_INFO_SCALE) |	\
 				      BIT(IIO_CHAN_INFO_RAW),		\
 		.scan_index = _index,					\
author maintainer
#958 lore raw

PATCH 957/990 iio: imu: inv_mpu6050: fix swapped accel and gyro startup times

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Arnav Kapoor <[email protected]>

commit 3a5e2ca34cadd9d5993064884aa5b9c4f6d71dff upstream.

struct inv_mpu6050_hw declares startup_time as { accel, gyro }, but every entry of hw_info[] initializes it positionally as
{ *_GYRO_STARTUP_TIME, *_ACCEL_STARTUP_TIME }, so the two values are swapped for all chips.

inv_mpu6050_switch_engine() waits for startup_time.gyro after enabling the gyroscope, so it waits for the accelerometer startup time instead, e.g. 20 ms instead of 60 ms on MPU6050 and 20 ms instead of 100 ms on ICM20602, and the first gyroscope samples can be read before the sensor has settled. Enabling only the accelerometer waits longer than needed.

Use designated initializers, so each value is assigned to the member it is named after.

Fixes e46a36d92da0 ("Add startup time for each chip using inv_mpu6050 driver")
---
 drivers/iio/imu/inv_mpu6050/inv_mpu_core.c |   95 +++++++++++++++++++++++------
 1 file changed, 76 insertions(+), 19 deletions(-)
drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +76 -19
@@ -149,7 +149,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6050,
 		.fifo_size = 1024,
 		.temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE},
-		.startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6050_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6050_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU6500_WHOAMI_VALUE,
@@ -158,7 +161,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU6515_WHOAMI_VALUE,
@@ -167,7 +173,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU6880_WHOAMI_VALUE,
@@ -176,7 +185,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 4096,
 		.temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU6000_WHOAMI_VALUE,
@@ -185,7 +197,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6050,
 		.fifo_size = 1024,
 		.temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE},
-		.startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6050_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6050_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU9150_WHOAMI_VALUE,
@@ -194,7 +209,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6050,
 		.fifo_size = 1024,
 		.temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE},
-		.startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6050_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6050_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU9250_WHOAMI_VALUE,
@@ -203,7 +221,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_MPU9255_WHOAMI_VALUE,
@@ -212,7 +233,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20608_WHOAMI_VALUE,
@@ -221,7 +245,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20608D_WHOAMI_VALUE,
@@ -230,7 +257,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20609_WHOAMI_VALUE,
@@ -239,7 +269,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 4 * 1024,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20689_WHOAMI_VALUE,
@@ -248,7 +281,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 4 * 1024,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20600_WHOAMI_VALUE,
@@ -257,7 +293,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 1008,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_ICM20602_ACCEL_STARTUP_TIME,
+			.gyro = INV_ICM20602_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20602_WHOAMI_VALUE,
@@ -266,7 +305,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 1008,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_ICM20602_ACCEL_STARTUP_TIME,
+			.gyro = INV_ICM20602_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_ICM20690_WHOAMI_VALUE,
@@ -275,7 +317,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 1024,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_ICM20690_GYRO_STARTUP_TIME, INV_ICM20690_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_ICM20690_ACCEL_STARTUP_TIME,
+			.gyro = INV_ICM20690_GYRO_STARTUP_TIME,
+		},
 	},
 	{	.whoami = INV_IAM20380_WHOAMI_VALUE,
 		.name = "IAM20380",
@@ -283,7 +328,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_IAM20680_WHOAMI_VALUE,
@@ -292,7 +340,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 512,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_IAM20680HP_WHOAMI_VALUE,
@@ -301,7 +352,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 4 * 1024,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 	{
 		.whoami = INV_IAM20680HT_WHOAMI_VALUE,
@@ -310,7 +364,10 @@ static const struct inv_mpu6050_hw hw_in
 		.config = &chip_config_6500,
 		.fifo_size = 4 * 1024,
 		.temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE},
-		.startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME},
+		.startup_time = {
+			.accel = INV_MPU6500_ACCEL_STARTUP_TIME,
+			.gyro = INV_MPU6500_GYRO_STARTUP_TIME,
+		},
 	},
 };
 
author maintainer
#959 lore raw

PATCH 958/990 iio: imu: kmx61: reject duplicate event disable

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jiale Yao <[email protected]>

commit 9a60b35fe45801d45454e1efe90569c9cc6ea736 upstream.

The IIO core does not filter duplicate writes to the event enable attribute. kmx61_write_event_config() already ignores repeated enable requests, but a repeated disable request still calls kmx61_set_power_state(data, false, KMX61_ACC), dropping a runtime PM reference that was not acquired for this request. This can underflow the runtime PM usage count and trigger a "Runtime PM usage count underflow" warning.

Return early when the requested state already matches ev_enable_state.

Fixes fd3ae7a9f21c ("iio: imu: kmx61: Add support for any motion trigger")
---
 drivers/iio/imu/kmx61.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/imu/kmx61.c +1 -1
@@ -942,7 +942,7 @@ static int kmx61_write_event_config(stru
 	struct kmx61_data *data = kmx61_get_data(indio_dev);
 	int ret = 0;
 
-	if (state && data->ev_enable_state)
+	if (state == data->ev_enable_state)
 		return 0;
 
 	mutex_lock(&data->lock);
author maintainer
#960 lore raw

PATCH 959/990 iio: light: tsl2591: dont divide by zero

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jan Remes <[email protected]>

commit bd63c89aac5672f40cdc123a856493b628fc1abb upstream.

The TSL2591 has two raw light channels - CH0 and CH1. The algorithm for calculating illumination from the raw channels requires division by CH0 (which can be zero) and by "counts per lux" (CPL) value which is also zero for (gain = LOW, integration time <= 400 ms).

Furthermore, the algorithm assumes CH0 > CH1, which can be violated in almost complete darkness.

As a result, reading from 'in_illuminance_input' results in division-by-zero whenever CH0 is 0 (complete darkness) or whenever the parameters result in CPL being zero. This results in kernel oops on x86_64 and in reading the value as 0 on arm64.

Fix that by:
- reporting CH0 <= CH1 as zero (catches also CH0 = 0)
- updating the lux algorithm to only do the division at the end

Fixes 2335f0d7c790 ("iio: light: Added AMS tsl2591 driver implementation")
---
 drivers/iio/light/tsl2591.c |   32 ++++++++++++++++++++++----------
 1 file changed, 22 insertions(+), 10 deletions(-)
drivers/iio/light/tsl2591.c +22 -10
@@ -16,6 +16,7 @@
 #include <linux/interrupt.h>
 #include <linux/iopoll.h>
 #include <linux/kernel.h>
+#include <linux/math64.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
 #include <linux/pm_runtime.h>
@@ -425,6 +426,10 @@ static int tsl2591_wait_adc_complete(str
  * Scale values to get more representative value of lux i.e.
  * lux = ((C0DATA - C1DATA) * (1000 - ((C1DATA * 1000) / C0DATA))) / CPL
  *
+ * CPL is not computed on its own: at 1x gain it is below 1 for integration
+ * times under 500 ms, so the division by LUX DF is folded into the final
+ * division instead.
+ *
  * Channel 0 = IR + Visible
  * Channel 1 = IR only
  */
@@ -436,8 +441,10 @@ static int tsl2591_read_channel_data(str
 	struct tsl2591_als_settings *settings = &chip->als_settings;
 	struct i2c_client *client = chip->client;
 	u8 als_data[TSL2591_NUM_DATA_REGISTERS];
-	int counts_per_lux, int_time_fval, gain_multi, lux;
+	int int_time_fval, gain_multi;
 	u16 als_ch0, als_ch1;
+	u64 lux;
+	u32 rem;
 	int ret;
 
 	ret = tsl2591_wait_adc_complete(chip);
@@ -473,23 +480,28 @@ static int tsl2591_read_channel_data(str
 			return gain_multi;
 		}
 
-		int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time);
-		/* Calculate counts per lux value */
-		counts_per_lux = (int_time_fval * gain_multi) / TSL2591_LUX_COEFFICIENT;
+		/* No visible light, this also catches C0DATA == 0 */
+		if (als_ch0 <= als_ch1) {
+			*val = 0;
+			*val2 = 0;
+			break;
+		}
 
-		dev_dbg(&client->dev, "Counts Per Lux: %d\n", counts_per_lux);
+		int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time);
 
 		/* Calculate lux value */
-		lux = ((als_ch0 - als_ch1) *
-		       (1000 - ((als_ch1 * 1000) / als_ch0))) / counts_per_lux;
+		lux = (u64)(als_ch0 - als_ch1) *
+		      (1000 - ((als_ch1 * 1000) / als_ch0)) *
+		      TSL2591_LUX_COEFFICIENT;
+		lux = div_u64(lux, int_time_fval * gain_multi);
 
-		dev_dbg(&client->dev, "Raw lux calculation: %d\n", lux);
+		dev_dbg(&client->dev, "Raw lux calculation: %llu\n", lux);
 
 		/* Divide by 1000 to get real lux value before scaling */
-		*val = lux / 1000;
+		*val = div_u64_rem(lux, 1000, &rem);
 
 		/* Get the decimal part of lux reading */
-		*val2 = (lux - (*val * 1000)) * 1000;
+		*val2 = rem * 1000;
 
 		break;
 	default:
author maintainer
#961 lore raw

PATCH 960/990 iio: light: vcnl4035: Fix reversed ALS mode bit

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Alexander Sarmanow <[email protected]>

commit 6bcabc30b89f31e2925647d1ffa5a0e4b7919829 upstream.

According to the datasheet (table 2) the ALS_SD bit behaves the opposite way the current ALS mode defines are set, writing 0 powers the sensor and writing 1 shuts it down.

The current driver thinks the ALS is up while it's actually shut down and it's down when the systems powers it up.

Fixes 55707294c4eb ("iio: light: Add support for vishay vcnl4035")
---
 drivers/iio/light/vcnl4035.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/iio/light/vcnl4035.c +2 -2
@@ -44,8 +44,8 @@
 #define VCNL4035_DEV_ID_MASK		GENMASK(7, 0)
 
 /* Default values */
-#define VCNL4035_MODE_ALS_ENABLE	BIT(0)
-#define VCNL4035_MODE_ALS_DISABLE	0x00
+#define VCNL4035_MODE_ALS_ENABLE	0x00
+#define VCNL4035_MODE_ALS_DISABLE	BIT(0)
 #define VCNL4035_MODE_ALS_INT_ENABLE	BIT(1)
 #define VCNL4035_MODE_ALS_INT_DISABLE	0
 #define VCNL4035_DEV_ID_VAL		0x80
author maintainer
#962 lore raw

PATCH 961/990 iio: magnetometer: mmc35240: leave cache-only mode before the cache sync

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Shashank Mohan Jain <[email protected]>

commit 38e05cf38df705b7fa9e8ada931589fa96816f09 upstream.

mmc35240_resume() marks the register cache dirty and calls regcache_sync_region() while the regmap is still in cache-only mode. It calls regcache_cache_only(false) only after the sync. This ordering has been wrong since the resume support was added; it happened to work until regmap started rejecting a sync in cache-only mode.

Since commit afc8e3ee8307 ("regcache: Validate cache_only state in regcache_sync_region()") a sync in cache-only mode is refused with a WARN and -EINVAL. Every resume now gives

  WARNING: drivers/base/regmap/regcache.c:536 at regcache_sync_region+0x1a4/0x1c0
  ...
   mmc35240_resume+0x30/0x70
   dpm_run_callback+0x7d/0x1c0
   device_resume+0x175/0x270
  ...
  mmc35240 1-0030: Failed to restore control registers

and the control registers are not written. If the chip lost its state during suspend, it runs with the reset value of CTRL1 while the cache, and with it the sampling frequency attribute, still has the configured value. Writing the same frequency again does not repair this, because regmap_update_bits() finds no difference to the cache.

Leave cache-only mode first, then mark the cache dirty and sync it.

Reproduced in qemu with the driver bound to an i2c-stub device: set in_magn_sampling_frequency to 25 (CTRL1 = 0x02), clear CTRL0 and CTRL1 of the stub behind the driver's back to emulate the power loss, and run a suspend/resume cycle with "devices" in /sys/power/pm_test. Without this change CTRL1 is still 0x00 after resume and the warning is printed. With it, and also with the regcache commit reverted, CTRL1 is 0x02 again and there is no warning. Not tested on real hardware.

Fixes 553a776b7908 ("iio: magnetometer: mmc35240: Add PM sleep support")
---
 drivers/iio/magnetometer/mmc35240.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/iio/magnetometer/mmc35240.c +1 -2
@@ -533,14 +533,13 @@ static int mmc35240_resume(struct device
 	struct mmc35240_data *data = iio_priv(indio_dev);
 	int ret;
 
+	regcache_cache_only(data->regmap, false);
 	regcache_mark_dirty(data->regmap);
 	ret = regcache_sync_region(data->regmap, MMC35240_REG_CTRL0,
 				   MMC35240_REG_CTRL1);
 	if (ret < 0)
 		dev_err(dev, "Failed to restore control registers\n");
 
-	regcache_cache_only(data->regmap, false);
-
 	return 0;
 }
 
author maintainer
#963 lore raw

PATCH 962/990 iio: magnetometer: tlv493d: fix magnetic field scale

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Viral Patel <[email protected]>

commit ef5c183a863bb69bf019a2d2ae0e1bfdaebe6222 upstream.

The TLV493D-A1B6 datasheet specifies a magnetic resolution of 98 uT/LSB (0.098 mT/LSB). IIO reports magnetic field in Gauss (1 mT = 10 G), so the scale should be 0.98 G/LSB.

The driver currently reports 98/1000 = 0.098 G/LSB, which under-reports the magnetic field by a factor of 10. The comment also gives the resolution as 0.0098 mT (9.8 uT), mixing up units.

Correct the scale value and the comment.

Fixes 106511d280c7 ("iio: magnetometer: add support for Infineon TLV493D 3D Magentic sensor")
---
 drivers/iio/magnetometer/tlv493d.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/iio/magnetometer/tlv493d.c +3 -3
@@ -300,11 +300,11 @@ static int tlv493d_read_raw(struct iio_d
 		switch (chan->type) {
 		case IIO_MAGN:
 			/*
-			 * Magnetic field scale: 0.0098 mTesla (i.e. 9.8 µT)
-			 * Magnetic field in Gauss: mT * 10 = 0.098.
+			 * Magnetic field scale: 0.098 mTesla (i.e. 98 µT) per LSB.
+			 * In Gauss (1 mT = 10 G): 0.98 G per LSB.
 			 */
 			*val = 98;
-			*val2 = 1000;
+			*val2 = 100;
 			return IIO_VAL_FRACTIONAL;
 		case IIO_TEMP:
 			/*
author maintainer
#964 lore raw

PATCH 963/990 iio: proximity: sx9324: fix out-of-bounds read of scan period table

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Arnav Kapoor <[email protected]>

commit 7b5f54280f8e6ef07664f6705dd005feefbe87d1 upstream.

The scan period of the SX9324 is selected by the 5 bit wide SX9324_REG_GNRL_CTRL0_SCANPERIOD field, so it has 32 possible values. sx9324_scan_period_table[] however only has 16 entries, it was copied over from the SX9310 driver where the field is only 4 bits wide.

sx9324_wait_for_sample() indexes the table with the raw field value, so all the codes from 16 to 31 read past the end of the array. The default value of the register is SX9324_REG_GNRL_CTRL0_SCANPERIOD_100MS (0x16, i.e. 22), so the out-of-bounds read happens with the default configuration of the device. It is only avoided when the device has an interrupt line, as the wait is only done in the polling case.

The value read is then used as the duration of an msleep() call, so the sensor is polled with a completely random delay.

Fill the table with the scan periods of all 32 codes, which are the periods documented for the corresponding sx9324_samp_freq_table[] entries, and add a static assertion to keep both tables in sync.

Fixes 4c18a890dff8 ("iio:proximity:sx9324: Add SX9324 support")
---
 drivers/iio/proximity/sx9324.c |   13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
drivers/iio/proximity/sx9324.c +11 -2
@@ -280,11 +280,20 @@ static const struct {
 	{ 0, 250000 },  /* 11111: 4 s */
 };
 
+/*
+ * The scan period of the SX9324 is selected by the 5-bit wide
+ * SX9324_REG_GNRL_CTRL0_SCANPERIOD field. The values below are the scan
+ * periods in ms of the corresponding sx9324_samp_freq_table[] entries.
+ */
 static const unsigned int sx9324_scan_period_table[] = {
-	2,   15,  30,  45,   60,   90,	 120,  200,
-	400, 600, 800, 1000, 2000, 3000, 4000, 5000,
+	1, 2, 4, 6, 8, 10, 14, 18,			/* 0x00 - 0x07 */
+	22, 26, 30, 34, 38, 42, 46, 50,			/* 0x08 - 0x0f */
+	56, 62, 68, 74, 80, 90, 100, 200,		/* 0x10 - 0x17 */
+	300, 400, 600, 800, 1000, 2000, 3000, 4000,	/* 0x18 - 0x1f */
 };
 
+static_assert(ARRAY_SIZE(sx9324_scan_period_table) == ARRAY_SIZE(sx9324_samp_freq_table));
+
 static const struct regmap_range sx9324_writable_reg_ranges[] = {
 	/*
 	 * To set COMPSTAT for compensation, even if datasheet says register is
author maintainer
#965 lore raw

PATCH 964/990 iio: proximity: sx9500: ignore event config writes that dont change state

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Arnav Kapoor <[email protected]>

commit b8ed9165906597b69a46fabf39ab41690721ebe8 upstream.

sx9500_write_event_config() adjusts the channel and close/far user counts on every write, even when the event is already in the requested state. Writing 0 to a disabled event and then 1 leaves the counts at 0, so the channel and its interrupts stay off while the event reads as enabled. As channel_users[] is shared with raw reads, those can then wait forever for a conversion. Writing 1 twice and then 0 has the opposite effect.

Return early when the state doesn't change, as
sx_common_write_event_config() does.

Fixes 4193c0f1d863 ("iio: driver for Semtech SX9500 proximity solution")
---
 drivers/iio/proximity/sx9500.c |    6 ++++++
 1 file changed, 6 insertions(+)
drivers/iio/proximity/sx9500.c +6 -0
@@ -548,6 +548,12 @@ static int sx9500_write_event_config(str
 
 	mutex_lock(&data->mutex);
 
+	/* The user counts must only change when the state does. */
+	if (data->event_enabled[chan->channel] == state) {
+		ret = 0;
+		goto out_unlock;
+	}
+
 	if (state) {
 		ret = sx9500_inc_chan_users(data, chan->channel);
 		if (ret < 0)
author maintainer
#966 lore raw

PATCH 965/990 iio: temperature: mlx90614: Fix dual channel probe condition check

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Salah Triki <[email protected]>

commit 4d4e75b3074bc29525c963a81c19471528f29a45 upstream.

In mlx90614_probe_num_ir_sensors(), the check on chip_info->dual_channel is inverted.

Currently, if dual_channel is true (MLX90614), the function returns 0 immediately without checking op_eeprom_config1. This forces all MLX90614 devices to be registered as single sensor (num_channels = 2), making the second object temperature channel inaccessible.

Conversely, if dual_channel is false (MLX90615), the function skips the early return and performs an unnecessary SMBus read on EEPROM CONFIG1 even though MLX90615 does not support dual channel operation.

Fix this by negating the condition so that single-channel chips return early with 0, while dual-channel capable chips (MLX90614) proceed to read the EEPROM configuration register to detect whether 1 or 2 object channels are present.

Fixes 3d5ead238bc8 ("iio: mlx90614: Factor our register IO and constants into model specific descriptor")
---
 drivers/iio/temperature/mlx90614.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/temperature/mlx90614.c +1 -1
@@ -569,7 +569,7 @@ static int mlx90614_probe_num_ir_sensors
 	const struct mlx_chip_info *chip_info = data->chip_info;
 	s32 ret;
 
-	if (chip_info->dual_channel)
+	if (!chip_info->dual_channel)
 		return 0;
 
 	ret = i2c_smbus_read_word_data(client, chip_info->op_eeprom_config1);
author maintainer
#967 lore raw

PATCH 966/990 iio: trigger: free the trigger ID after device_del()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Changyul Lee <[email protected]>

commit d32bf759801e6df23038dc834622a122ec76a4dd upstream.

iio_trigger_unregister() returns the trigger ID to iio_trigger_ida before device_del() removes the "trigger<N>" device. A trigger registered in between can get the same ID, and its device_add() fails:

sysfs: cannot create duplicate filename '/bus/iio/devices/trigger0'

For example, adding a sysfs trigger while an hrtimer trigger is being removed through configfs, or the other way around, hits this because the two paths do not share a lock.

Free the ID after device_del(), as the error path of iio_trigger_register() already does, and drop the "Possible issue in here" comment.

Fixes 1637db44413e ("Staging: IIO: Trigger support added to core.")
---
 drivers/iio/industrialio-trigger.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/iio/industrialio-trigger.c +1 -2
@@ -105,9 +105,8 @@ void iio_trigger_unregister(struct iio_t
 	scoped_guard(mutex, &iio_trigger_list_lock)
 		list_del(&trig_info->list);
 
-	ida_free(&iio_trigger_ida, trig_info->id);
-	/* Possible issue in here */
 	device_del(&trig_info->dev);
+	ida_free(&iio_trigger_ida, trig_info->id);
 }
 EXPORT_SYMBOL(iio_trigger_unregister);
 
author maintainer
#968 lore raw

PATCH 967/990 iio: trigger: Return an error when the trigger has no free irq

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Karl Mehltretter <[email protected]>

commit dff701806ab6252f6a0fccba880c47cd09602625 upstream.

iio_trigger_attach_poll_func() prints an error when all CONFIG_IIO_CONSUMERS_PER_TRIGGER irqs of the trigger are in use, but returns 0. The buffer of the extra consumer is enabled without a poll function.

Disabling that buffer calls clear_bit() with a negative bit number and drops a module reference for the second time. On arm and arm64 the clear_bit() goes about 512 MB past the pool bitmap. That is an oops if the address is not mapped, and a bit cleared in unrelated memory if it is.

Return the error from iio_trigger_get_irq().

Fixes 995438233579 ("iio: Fix error handling in iio_trigger_attach_poll_func")
---
 drivers/iio/industrialio-trigger.c |    1 +
 1 file changed, 1 insertion(+)
drivers/iio/industrialio-trigger.c +1 -0
@@ -292,6 +292,7 @@ int iio_trigger_attach_poll_func(struct
 	if (pf->irq < 0) {
 		pr_err("Could not find an available irq for trigger %s, CONFIG_IIO_CONSUMERS_PER_TRIGGER=%d limit might be exceeded\n",
 			trig->name, CONFIG_IIO_CONSUMERS_PER_TRIGGER);
+		ret = pf->irq;
 		goto out_put_module;
 	}
 
author maintainer
#969 lore raw

PATCH 968/990 fou: reserve headroom before pushing the encap header

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Theodor Arsenij Larionov Trichkine <[email protected]>

commit bcb42672751a8786dce871a35bde363b041cb2f7 upstream.

ip_tunnel_xmit() and ip_md_tunnel_xmit() push the encap header before reserving headroom. A packet redirected into the tunnel (tc mirred, nft fwd/dup) keeps the headroom of its original device, so fou_build_udp() panics:

kernel BUG at net/core/skbuff.c:214!

  Call Trace:
   skb_push+0xcc/0xf0
   fou_build_udp+0x2f/0x380
   gue_build_header+0xfa/0x150
   ip_tunnel_xmit+0x87f/0x21c0

With a mirred mirror, the push overwrites the original packet instead. Reachable with CAP_NET_ADMIN in a user namespace.

Reserve the headroom in fou_build_header() and gue_build_header(); GUE sizes and builds the header from one copy of the encap fields. The skb head may move, so reload inner_iph after ip_tunnel_encap() and read tnl_params, which points into the head for GRE with header_ops, before the call. sit's ipip6_tunnel_xmit() holds no head pointer across it.

Fixes 56328486539d ("net: Changes to ip_tunnel to support foo-over-udp encapsulation")
Fixes ac931d4cdec3 ("ipip,ip_tunnel,sit: Add FOU support for externally controlled ipip devices")
---
 net/ipv4/fou_core.c  |   19 +++++++++++++++----
 net/ipv4/ip_tunnel.c |    6 ++++--
 2 files changed, 19 insertions(+), 6 deletions(-)
net/ipv4/fou_core.c +15 -4
@@ -1074,6 +1074,9 @@ static int fou_build_header(struct sk_bu
 	__be16 sport;
 	int err;
 
+	if (skb_cow_head(skb, fou_encap_hlen(e)))
+		return -ENOMEM;
+
 	err = __fou_build_header(skb, e, protocol, &sport, type);
 	if (err)
 		return err;
@@ -1086,16 +1089,24 @@ static int fou_build_header(struct sk_bu
 static int gue_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e,
 			    u8 *protocol, struct flowi4 *fl4)
 {
-	int type = e->flags & TUNNEL_ENCAP_FLAG_CSUM ? SKB_GSO_UDP_TUNNEL_CSUM :
-						       SKB_GSO_UDP_TUNNEL;
+	struct ip_tunnel_encap encap = {
+		.flags = READ_ONCE(e->flags),
+		.sport = READ_ONCE(e->sport),
+		.dport = READ_ONCE(e->dport),
+	};
+	int type = encap.flags & TUNNEL_ENCAP_FLAG_CSUM ?
+		   SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL;
 	__be16 sport;
 	int err;
 
-	err = __gue_build_header(skb, e, protocol, &sport, type);
+	if (skb_cow_head(skb, gue_encap_hlen(&encap)))
+		return -ENOMEM;
+
+	err = __gue_build_header(skb, &encap, protocol, &sport, type);
 	if (err)
 		return err;
 
-	fou_build_udp(skb, e, fl4, protocol, sport);
+	fou_build_udp(skb, &encap, fl4, protocol, sport);
 
 	return 0;
 }
net/ipv4/ip_tunnel.c +4 -2
@@ -604,6 +604,7 @@ void ip_md_tunnel_xmit(struct sk_buff *s
 
 	if (ip_tunnel_encap(skb, &tun_info->encap, &proto, &fl4) < 0)
 		goto tx_error;
+	inner_iph = (const struct iphdr *)skb_inner_network_header(skb);
 
 	use_cache = ip_tunnel_dst_cache_usable(skb, tun_info);
 	if (use_cache)
@@ -746,6 +747,8 @@ void ip_tunnel_xmit(struct sk_buff *skb,
 	}
 
 	tos = tnl_params->tos;
+	df = tnl_params->frag_off;
+	ttl = tnl_params->ttl;
 	if (tos & 0x1) {
 		tos &= ~0x1;
 		if (payload_protocol == htons(ETH_P_IP)) {
@@ -764,6 +767,7 @@ void ip_tunnel_xmit(struct sk_buff *skb,
 
 	if (ip_tunnel_encap(skb, &tunnel->encap, &protocol, &fl4) < 0)
 		goto tx_error;
+	inner_iph = (const struct iphdr *)skb_inner_network_header(skb);
 
 	if (connected && md) {
 		use_cache = ip_tunnel_dst_cache_usable(skb, tun_info);
@@ -796,7 +800,6 @@ void ip_tunnel_xmit(struct sk_buff *skb,
 		goto tx_error;
 	}
 
-	df = tnl_params->frag_off;
 	if (payload_protocol == htons(ETH_P_IP) && !tunnel->ignore_df)
 		df |= (inner_iph->frag_off & htons(IP_DF));
 
@@ -816,7 +819,6 @@ void ip_tunnel_xmit(struct sk_buff *skb,
 	}
 
 	tos = ip_tunnel_ecn_encap(tos, inner_iph, skb);
-	ttl = tnl_params->ttl;
 	if (ttl == 0) {
 		if (payload_protocol == htons(ETH_P_IP))
 			ttl = inner_iph->ttl;
author maintainer
#970 lore raw

PATCH 969/990 blk-mq: take quiesce_lock when removing a queue from the tag set

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mani Tofigh <[email protected]>

commit 495f22c5a99ac38e527294cdc4f3972718b9bee0 upstream.

Unquiescing a tag set can run the hw queues of a queue whose hctxs were already freed. blk_mq_unquiesce_tagset() walks the tag set's queues under quiesce_lock and rcu_read_lock(). Commit 71ec3c7d6db8 ("blk-mq:
quiesce a queue that joins a quiesced tag set") added quiesce_lock to the walks and to adding a queue, but blk_mq_del_queue_tag_set() still removes a queue without it. The hctxs are then freed right away since RCU only keeps the request_queue itself alive:

Task A (controller reset) Task B (namespace removal)
blk_mq_unquiesce_tagset()

    /* finds q */
                                       blk_mq_del_queue_tag_set(q)
                                       blk_mq_release(q)
                                         /* frees the hctxs */
    blk_mq_run_hw_queues(q)
      /* reads freed hctxs */

The window is short. On PREEMPT_RT quiesce_lock is a sleeping lock and the walk can be preempted inside it, which is how it's hit here:

  [  399.851277] BUG: KASAN: slab-use-after-free in blk_mq_run_hw_queues+0x4bd/0x550
  [  399.851328] Read of size 8 at addr ff11000003014148 by task kworker/u9:2/116
  [  399.851352] CPU: 1 UID: 0 PID: 116 Comm: kworker/u9:2 Not tainted 7.3.0-16299-g81cb9aa43246 #1 PREEMPT_RT
  [  399.851425] Workqueue: nvme-reset-wq nvme_loop_reset_ctrl_work
  [  399.851441] Call Trace:
  [  399.851457]  <TASK>
  [  399.851551]  blk_mq_run_hw_queues+0x4bd/0x550
  [  399.851564]  blk_mq_unquiesce_tagset+0x128/0x210
  [  399.851576]  nvme_loop_reset_ctrl_work+0x78/0x4c0
  [  399.851600]  process_one_work+0x92b/0x16d0
  [  399.851660]  worker_thread+0x4e6/0xd60
  [  399.851707]  kthread+0x300/0x3e0
  [  399.851727]  ret_from_fork+0x4f0/0x6f0
  [  399.851776]  ret_from_fork_asm+0x1a/0x30
  [  399.851793]  </TASK>
  ...
  [  399.851988] Freed by task 111:
  [  399.852040]  kfree+0x1b3/0x4b0
  [  399.852050]  blk_mq_release+0x400/0x550
  [  399.852060]  blk_put_queue+0x94/0x120
  [  399.852068]  disk_release+0x1bd/0x3f0
  [  399.852102]  nvme_free_ns+0x39/0x270
  [  399.852113]  nvme_remove_nsid_range+0x2d1/0x4a0
  [  399.852123]  nvme_scan_ns_list+0x2cc/0x390
  [  399.852134]  nvme_scan_work+0x421/0x9f0
  ...

With BLK_CGROUP the disk's root blkg holds the queue until a grace period later, which hides this for NVMe namespaces. It's still open without BLK_CGROUP, and from reading the code also for queues freed without a disk (e.g., SCSI device queues on a UFS host).

Take quiesce_lock around the list_del_rcu() as well so that the walk either finishes with a queue before it leaves the list or never sees it, and say so in the comment of quiesce_lock. With the fix, KASAN doesn't report the use-after-free anymore.

This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it about once every 20 minutes on a PREEMPT_RT kernel.

---
 block/blk-mq.c         |    3 +++
 include/linux/blk-mq.h |    3 ++-
 2 files changed, 5 insertions(+), 1 deletion(-)
block/blk-mq.c +3 -0
@@ -4348,7 +4348,10 @@ static void blk_mq_del_queue_tag_set(str
 
 	lockdep_assert_held(&set->tag_list_lock);
 
+	/* blk_mq_unquiesce_tagset() runs the hctxs, which are not RCU freed */
+	spin_lock(&set->quiesce_lock);
 	list_del_rcu(&q->tag_set_list);
+	spin_unlock(&set->quiesce_lock);
 	if (list_is_singular(&set->tag_list)) {
 		/* just transitioned to unshared */
 		set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
include/linux/blk-mq.h +2 -1
@@ -522,7 +522,8 @@ enum hctx_type {
  * @tag_list:	   List of the request queues that use this tag set. See also
  *		   request_queue.tag_set_list.
  * @quiesce_lock:  Serializes blk_mq_[un]quiesce_tagset() against each other
- *		   and against a request queue being added to @tag_list.
+ *		   and against a request queue being added to or removed from
+ *		   @tag_list.
  * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without
  *		   blk_mq_unquiesce_tagset().
  * @srcu:	   Use as lock when type of the request queue is blocking
author maintainer
#971 lore raw

PATCH 970/990 gpio: mpsse: reject bulk-in endpoints smaller than 3 bytes

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hyunjung Ko <[email protected]>

commit f94f85f82e042c89a1e64ed3ff1d591a2bccfa7b upstream.

mpsse_read() reads min(len + 2, wMaxPacketSize) bytes and then copies len_actual - 2 bytes to the caller. A device that declares a bulk-in endpoint with wMaxPacketSize 1 completes the read with len_actual 1, so the copy length becomes -1 and memcpy() runs far past the one byte buffer on the caller's stack and past bulk_in_buf:

memcpy: detected buffer overflow: 18446744073709551615 byte write of buffer size 1

  WARNING: lib/string_helpers.c:1036 at __fortify_report+0x6e/0xc0
  Call Trace:
   __fortify_panic+0xd/0x10
   gpio_mpsse_get_multiple+0x767/0x780
   gpio_mpsse_gpio_get+0xa2/0xf0
   gpiod_get_raw_value_commit+0xf8/0x1f0
   gpiod_get_value_cansleep+0x1e/0xa0
   value_show+0x42/0x90

Reproduced with dummy_hcd and raw-gadget. A read needs room for the two status bytes plus at least one data byte, so refuse to bind otherwise.

---
 drivers/gpio/gpio-mpsse.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/gpio/gpio-mpsse.c +4 -0
@@ -677,6 +677,10 @@ static int gpio_mpsse_probe(struct usb_i
 	if (err)
 		return err;
 
+	/* Every read carries two status bytes ahead of the data */
+	if (usb_endpoint_maxp(priv->bulk_in) < 3)
+		return -EINVAL;
+
 	priv->bulk_in_buf = devm_kmalloc(dev, usb_endpoint_maxp(priv->bulk_in),
 					 GFP_KERNEL);
 	if (!priv->bulk_in_buf)
author maintainer
#972 lore raw

PATCH 971/990 accel/ivpu: Defer recovery until probe completes

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Karol Wachowski <[email protected]>

commit dc61b19db1f77deb4c15bb71e64f46071447837c upstream.

An error IRQ that fires after ivpu_boot() enables interrupts queues recovery_work during probe. If probe then fails, the device is torn down while the work runs, and the work faults on the unmapped BARs:

  BUG: unable to handle page fault for address: ffffcfc6680200f4
  Workqueue: events_unbound ivpu_pm_recovery_work [intel_vpu]
  RIP: 0010:ivpu_hw_ip_ipc_rx_addr_get+0xc/0xb0 [intel_vpu]
  Call Trace:
   ivpu_wait_for_ready+0x155/0x220 [intel_vpu]
   ivpu_boot+0x9e/0x270 [intel_vpu]
   ivpu_resume+0xa4/0xd0 [intel_vpu]
   ivpu_pm_reset_complete+0x2c/0x90 [intel_vpu]
   ivpu_pm_recovery_work+0xf6/0x140 [intel_vpu]

If probe succeeds, the recovery runs concurrently with the rest of probe, and its pm_runtime_disable() discards the initial autosuspend request, leaving the NPU active until first use. Any recovery that starts while the NPU is idle loses the pending autosuspend the same way.

Keep recovery_work disabled from ivpu_pm_init() until ivpu_pm_enable(). A trigger during probe still runs diagnostics and masks interrupts, and ivpu_pm_enable() runs the deferred recovery before the initial autosuspend request. A trigger racing with ivpu_pm_enable() can cause a second, harmless recovery. Request autosuspend at the end of ivpu_pm_reset_complete() so the NPU suspends again after every reset.

---
 drivers/accel/ivpu/ivpu_pm.c |    9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/accel/ivpu/ivpu_pm.c +8 -1
@@ -148,8 +148,8 @@ static void ivpu_pm_reset_complete(struc
 	up_write(&vdev->pm->reset_lock);
 	atomic_set(&vdev->pm->reset_pending, 0);
 
-	pm_runtime_mark_last_busy(vdev->drm.dev);
 	pm_runtime_enable(vdev->drm.dev);
+	pm_request_autosuspend(vdev->drm.dev);
 }
 
 static void ivpu_pm_recovery_work(struct work_struct *work)
@@ -403,6 +403,7 @@ void ivpu_pm_init(struct ivpu_device *vd
 	atomic_set(&pm->reset_counter, 0);
 
 	INIT_WORK(&pm->recovery_work, ivpu_pm_recovery_work);
+	disable_work(&pm->recovery_work);
 	INIT_DELAYED_WORK(&pm->job_timeout_work, ivpu_job_timeout_work);
 
 	if (ivpu_disable_recovery)
@@ -427,6 +428,12 @@ void ivpu_pm_enable(struct ivpu_device *
 {
 	struct device *dev = vdev->drm.dev;
 
+	enable_work(&vdev->pm->recovery_work);
+	if (atomic_read(&vdev->pm->reset_pending)) {
+		queue_work(system_dfl_wq, &vdev->pm->recovery_work);
+		flush_work(&vdev->pm->recovery_work);
+	}
+
 	pm_runtime_allow(dev);
 	pm_runtime_mark_last_busy(dev);
 	pm_runtime_put_autosuspend(dev);
author maintainer
#973 lore raw

PATCH 972/990 sctp: fix skb_over_panic when adding addresses with a pending delete of another family

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Henry Martin <[email protected]>

commit ce09d8c13a15fe881d0a04c91979dcdf45ed9543 upstream.

sctp_make_asconf_update_ip() accounts for a pending DEL_IP parameter by reusing the length of the address being added. The write-back side instead serializes the pending address itself, with its own address family. If the pending delete is IPv6 (20-byte parameter) while the added addresses are IPv4 (8-byte), the chunk is allocated 12 bytes short and sctp_addto_chunk() writes past the end of the skb. E.g. on mainline (05441d697f7f):

    skbuff: skb_over_panic: text:ffffffff84859c77 len:392 put:20
        tail:0x188 end:0x180 dev:<NULL>
    kernel BUG at net/core/skbuff.c:215!
    CPU: 0 UID: 1000 PID: 379 Comm: poc_sctp
    Call Trace:
     skb_panic
     skb_put
     sctp_addto_chunk
     sctp_make_asconf_update_ip
     sctp_send_asconf_add_ip
     sctp_setsockopt_bindx
     __x64_sys_setsockopt

Requires addip enabled on the endpoint (net.sctp.addip_enable=1).

Account for the pending delete with its own address family, as the write-back side already does.

This issue was discovered by an LLM code scanner.

---
 net/sctp/sm_make_chunk.c |   28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
net/sctp/sm_make_chunk.c +16 -12
@@ -2867,7 +2867,6 @@ struct sctp_chunk *sctp_make_asconf_upda
 	int addr_param_len = 0;
 	union sctp_addr *addr;
 	int totallen = 0, i;
-	int del_pickup = 0;
 	struct sctp_af *af;
 	void *addr_buf;
 
@@ -2882,16 +2881,21 @@ struct sctp_chunk *sctp_make_asconf_upda
 		totallen += addr_param_len;
 
 		addr_buf += af->sockaddr_len;
-		if (asoc->asconf_addr_del_pending && !del_pickup) {
-			/* reuse the parameter length from the same scope one */
-			totallen += paramlen;
-			totallen += addr_param_len;
-			del_pickup = 1;
-
-			pr_debug("%s: picked same-scope del_pending addr, "
-				 "totallen for all addresses is %d\n",
-				 __func__, totallen);
-		}
+	}
+
+	if (asoc->asconf_addr_del_pending) {
+		/* The DEL_IP parameter is serialized from the pending address
+		 * itself below; account for its own address family, which may
+		 * differ from the added ones.
+		 */
+		addr = asoc->asconf_addr_del_pending;
+		af = sctp_get_af_specific(addr->v4.sin_family);
+		totallen += paramlen;
+		totallen += af->to_addr_param(addr, &addr_param);
+
+		pr_debug("%s: picked del_pending addr, "
+			 "totallen for all addresses is %d\n",
+			 __func__, totallen);
 	}
 
 	/* Create an asconf chunk with the required length. */
@@ -2914,7 +2918,7 @@ struct sctp_chunk *sctp_make_asconf_upda
 
 		addr_buf += af->sockaddr_len;
 	}
-	if (flags == SCTP_PARAM_ADD_IP && del_pickup) {
+	if (flags == SCTP_PARAM_ADD_IP && asoc->asconf_addr_del_pending) {
 		addr = asoc->asconf_addr_del_pending;
 		af = sctp_get_af_specific(addr->v4.sin_family);
 		addr_param_len = af->to_addr_param(addr, &addr_param);
author maintainer
#974 lore raw

PATCH 973/990 nvme: fix deadlock on nvme_subsystems_lock in nvme_init_subsystem()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mani Tofigh <[email protected]>

commit ba1213be15c613a1c03db69ea6480ca140a6ca00 upstream.

Connecting a controller to a new subsystem deadlocks when sysfs_create_link() fails in nvme_init_subsystem(), e.g., on an allocation failure. The error path drops the last subsystem reference with nvme_subsystems_lock held and nvme_destroy_subsystem() takes the same lock again:

nvme nvme0: failed to create sysfs link from subsystem.
============================================
WARNING: possible recursive locking detected
...
nvmesubsys/95 is trying to acquire lock:
(nvme_subsystems_lock){+.+.}-{4:4}, at: nvme_destroy_subsystem+0x1b/0x1e0

but task is already holding lock:
(nvme_subsystems_lock){+.+.}-{4:4}, at: nvme_init_identify+0x81e/0x34b0
...

  Call Trace:
   __mutex_lock+0x1a2/0x26e0
   nvme_destroy_subsystem+0x1b/0x1e0
   nvme_init_identify.cold+0x3bc/0x56f
   nvme_init_ctrl_finish+0x1bc/0x7a0
   nvme_loop_configure_admin_queue+0x205/0x2b0
   nvme_loop_create_ctrl+0x480/0xd10
   nvmf_dev_write+0x365/0x650
   vfs_write+0x1e3/0x1250
   ksys_write+0xfa/0x200
   do_syscall_64+0xfb/0x590
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
  ...
  INFO: task nvmesubsys:95 blocked for more than 20 seconds.
  INFO: task nvmesubsys:95 is blocked on a mutex likely owned by task nvmesubsys:95.

Every later controller setup or removal then waits for the lock too. The nvme_validate_cntlid() error path for an existing subsystem does the same put, and deadlocks the same way if the other references go away in between.

Drop the lock before the put. For a new subsystem, take it off the list first so another controller can't find it in between. With the fix, the connect fails and the next connect works.

This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within about 30s.

Fixes 32fd90c40768 ("nvme: change locking for the per-subsystem controller list")
---
 drivers/nvme/host/core.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/nvme/host/core.c +4 -0
@@ -3317,7 +3317,11 @@ static int nvme_init_subsystem(struct nv
 	return 0;
 
 out_put_subsystem:
+	if (!found)
+		list_del_init(&subsys->entry);
+	mutex_unlock(&nvme_subsystems_lock);
 	nvme_put_subsystem(subsys);
+	return ret;
 out_unlock:
 	mutex_unlock(&nvme_subsystems_lock);
 	return ret;
author maintainer
#975 lore raw

PATCH 974/990 tcp: fix NULL pointer dereference when restarting a Fast Open listener

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hyunwoo Kim <[email protected]>

commit aa40afa831ebfe45e40a23721711059f2ac584d4 upstream.

When a valid RST is received for a Fast Open child accepted before the three-way handshake completes, reqsk_fastopen_remove() adds the request_sock to the listener's RST list if the listener is in TCP_LISTEN.

An application can call shutdown(SHUT_RD) on a listener socket. inet_csk_listen_stop() checks rskq_rst_head without holding fastopenq.lock. If rskq_rst_head is NULL, it does not acquire the lock and therefore does not synchronize with an insertion by reqsk_fastopen_remove() after that function has passed the TCP_LISTEN check.

The more likely outcome of this race, even without a subsequent listen(), is a leak. If reqsk_fastopen_remove() inserts a request_sock after inet_csk_listen_stop() observes an empty list and returns, the request_sock is stranded in rskq_rst_head and keeps a reference on the listener. The socket is already in TCP_CLOSE, so a subsequent close() does not call inet_csk_listen_stop() again.

If listen() is called again on the same socket before the delayed list insertion, the insertion can overlap the queue initialization in reqsk_queue_alloc(). If it occurs after rskq_rst_head is set to NULL but before rskq_rst_tail is set to NULL, rskq_rst_head points to the request_sock while rskq_rst_tail is NULL.

When a valid RST is later received for another accepted Fast Open child, rskq_rst_head is not NULL, so reqsk_fastopen_remove() attempts to write the request_sock pointer to rskq_rst_tail->dl_next while rskq_rst_tail is NULL. KASAN reports:

  BUG: KASAN: null-ptr-deref in reqsk_fastopen_remove+0x147/0x210
  Write of size 8 at addr 0000000000000088 by task swapper/3/0
  ...
  Call Trace:
   <IRQ>
   ...
   reqsk_fastopen_remove+0x147/0x210
   tcp_check_req+0xa70/0x1060
   ...
   tcp_rcv_state_process+0x1cb/0x2ae0
   ...
   tcp_v4_do_rcv+0x1fe/0x740
   tcp_v4_rcv+0x1744/0x2070
   ...
   ip_protocol_deliver_rcu+0x5c/0x280
   ip_local_deliver_finish+0x171/0x330
   ip_local_deliver+0x107/0x370
   ...
   </IRQ>

To widen the race window, the issue was reproduced after adding mdelay(3000) immediately after reqsk_fastopen_remove() checks that the listener is in TCP_LISTEN and immediately after reqsk_queue_alloc() sets rskq_rst_head to NULL.

Make inet_csk_listen_stop() acquire fastopenq.lock regardless of the value of rskq_rst_head and detach the list while holding the lock. With this synchronization, reqsk_fastopen_remove() either inserts the request_sock before inet_csk_listen_stop() acquires the lock, in which case inet_csk_listen_stop() reclaims it, or sees that the listener is not in TCP_LISTEN and does not insert anything.

---
 net/ipv4/inet_connection_sock.c |   20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)
net/ipv4/inet_connection_sock.c +9 -11
@@ -1549,17 +1549,15 @@ skip_child_forget:
 		if (!has_current_bpf_ctx())
 			cond_resched();
 	}
-	if (queue->fastopenq.rskq_rst_head) {
-		/* Free all the reqs queued in rskq_rst_head. */
-		spin_lock_bh(&queue->fastopenq.lock);
-		req = queue->fastopenq.rskq_rst_head;
-		queue->fastopenq.rskq_rst_head = NULL;
-		spin_unlock_bh(&queue->fastopenq.lock);
-		while (req != NULL) {
-			next = req->dl_next;
-			reqsk_put(req);
-			req = next;
-		}
+	/* Free all the reqs queued in rskq_rst_head. */
+	spin_lock_bh(&queue->fastopenq.lock);
+	req = queue->fastopenq.rskq_rst_head;
+	queue->fastopenq.rskq_rst_head = NULL;
+	spin_unlock_bh(&queue->fastopenq.lock);
+	while (req != NULL) {
+		next = req->dl_next;
+		reqsk_put(req);
+		req = next;
 	}
 	WARN_ON_ONCE(sk->sk_ack_backlog);
 }
author maintainer
#976 lore raw

PATCH 975/990 powerpc/watchdog: disable watchdog when watchdog_thresh=0

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Luiz Capitulino (Red Hat) <[email protected]>

commit d513ec3c907b067d4a32b14ec6f73c3e041cb136 upstream.

On powerpc, trying to disable the hardlockup detector with:

 # echo 0 > /proc/sys/kernel/watchdog_thresh

causes an immediate and endless hardlockup detection, eventually leading to an unusable system (splat example below). This happens because watchdog_calc_timeouts() sets wd_timer_period_ms, wd_panic_timeout_tb and wd_smp_panic_timeout_tb to zero, but start_watchdog() still starts the timer (with expiry=0) in this code path:

proc_watchdog_thresh()
proc_watchdog_update()

    __lockup_detector_reconfigure()
      watchdog_hardlockup_start()
        start_watchdog_on_cpu()
          start_watchdog()
            hrtimer_start() /* wd_timer_period_ms=0 */

However, according to Documentation/admin-guide/sysctl/kernel.rst, setting watchdog_thresh=0 should disable both the soft and hard lockup detectors.

This condition is already checked in __lockup_detector_reconfigure() for the soft lockup detector and the arch-independent hardlockup detector, what's missing is powerpc performing the same check in start_watchdog().

[  278.110085] watchdog: CPU 0 detected hard LOCKUP on other CPUs 1
[  278.110086] watchdog: CPU 1 became unstuck TB:33050716089564575
[  278.110097] CPU: 1 UID: 0 PID: 0 Comm: swapper/1 Kdump: loaded Tainted: G            E       7.4.0-rc1 #1 PREEMPT(full)
[  278.110103] watchdog: CPU 0 TB:33050716089564185, last SMP heartbeat TB:33050716089563885 (0ms ago)
[  278.110109] Tainted: [E]=UNSIGNED_MODULE
[  278.110126] Hardware name: IBM,8375-42A POWER9 (architected) 0x4e0202 0xf000005 of:IBM,FW940.00 (VL940_027) hv:phyp pSeries
[  278.110136] NIP:  c0000000001bd518 LR: c0000000014dedf8 CTR: 0000000000000000
[  278.110145] REGS: c000000004b17a80 TRAP: 0900   Tainted: G            E        (7.4.0-rc1)
[  278.110155] MSR:  800000000280b033 <SF,VEC,VSX,EE,FP,ME,IR,DR,RI,LE>  CR: 22000224  XER: 20040004
[  278.110189] CFAR: 0000000000000000 IRQMASK: 0

GPR00: 0000000000000000 c000000004b17d20 c000000001c38100 0000000000000000
GPR04: 000000000000ffff 0000000000000000 0000000000000000 0000000000000000
GPR08: 0000000000000000 0000000000000080 0000000000000080 ffffffffffffffff
GPR12: 0000000000000000 c000000017fff300 0000000000000000 000000002ef3d820
GPR16: 0000000000000000 0000000000000000 0000000000000000 0000000000000000
GPR20: 0000000000000000 0000000000000000 0000000000000000 0000000000000001
GPR24: 0000000000000001 00000040c0a6075e 0000000000000000 0000000000000001
GPR28: c0000001fdb5b140 0000000000000001 c000000002291968 c000000002291970

[  278.110306] NIP [c0000000001bd518] plpar_hcall_norets_notrace+0x18/0x2c
[  278.110319] LR [c0000000014dedf8] check_and_cede_processor+0x48/0x60
[  278.110333] Call Trace:
[  278.110338] [c000000004b17d20] [c000000004b17dd0] 0xc000000004b17dd0 (unreliable)
[  278.110354] [c000000004b17d80] [c0000000014df020] shared_cede_loop+0x70/0x170
[  278.110367] [c000000004b17dc0] [c0000000014de460] cpuidle_enter_state+0x2f0/0x748
[  278.110381] [c000000004b17e70] [c000000000fe43b8] cpuidle_enter+0x48/0x70
[  278.110397] [c000000004b17eb0] [c0000000002cdcf8] call_cpuidle+0x48/0x90
[  278.110409] [c000000004b17ed0] [c0000000002d6300] cpuidle_idle_call+0x160/0x2d0
[  278.110422] [c000000004b17f20] [c0000000002d6578] do_idle+0x108/0x1f0
[  278.110434] [c000000004b17f60] [c0000000002d6938] cpu_startup_entry+0x48/0x50
[  278.110446] [c000000004b17f90] [c0000000000615c0] start_secondary+0x290/0x2a0
[  278.110459] [c000000004b17fe0] [c00000000000e258] start_secondary_prolog+0x10/0x14
---
 arch/powerpc/kernel/watchdog.c |    3 +++
 1 file changed, 3 insertions(+)
arch/powerpc/kernel/watchdog.c +3 -0
@@ -482,6 +482,9 @@ static void start_watchdog(void *arg)
 	if (!(watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED))
 		return;
 
+	if (!watchdog_thresh)
+		return;
+
 	if (!cpumask_test_cpu(cpu, &watchdog_cpumask))
 		return;
 
author maintainer
#977 lore raw

PATCH 976/990 9p: fix memory leak in v9fs_init_fs_context error path

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sasha Levin <[email protected]>

commit 0fd76f1be20d19ac593138ceec502cb044c909bd upstream.

Move the assignments of fc->ops and fc->fs_private to right after the kzalloc, before any fallible operations. Previously these were assigned at the end of the function, after the kstrdup calls for uname and aname. If either kstrdup failed, the error path would set fc->need_free but leave fc->ops NULL, so put_fs_context() would never call v9fs_free_fc() to free the allocated context and any already-duplicated strings.

Fixes 1f3e4142c0eb ("9p: convert to the new mount API")
Assisted-by Claude:claude-opus-4-6

Message-ID: <[email protected]>

---
 fs/9p/vfs_super.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/9p/vfs_super.c +3 -3
@@ -312,6 +312,9 @@ static int v9fs_init_fs_context(struct f
 	if (!ctx)
 		return -ENOMEM;
 
+	fc->ops = &v9fs_context_ops;
+	fc->fs_private = ctx;
+
 	/* initialize core options */
 	ctx->session_opts.afid = ~0;
 	ctx->session_opts.cache = CACHE_NONE;
@@ -346,9 +349,6 @@ static int v9fs_init_fs_context(struct f
 	ctx->rdma_opts.timeout = P9_RDMA_TIMEOUT;
 	ctx->rdma_opts.privport = false;
 
-	fc->ops = &v9fs_context_ops;
-	fc->fs_private = ctx;
-
 	return 0;
 error:
 	fc->need_free = 1;
author maintainer
#978 lore raw

PATCH 977/990 9p: fix access mode flags being ORed instead of replaced

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Pierre Barre <[email protected]>

commit da2346a48a5a1fed86c3fe3d73c0b60e7b3027c9 upstream.

Since commit 1f3e4142c0eb ("9p: convert to the new mount API"), v9fs_apply_options() applies parsed mount flags with |= onto flags already set by v9fs_session_init(). For 9P2000.L, session_init sets V9FS_ACCESS_CLIENT as the default, so when the user mounts with "access=user", both bits end up set. Access mode checks compare against exact values, so having both bits set matches neither mode.

This causes v9fs_fid_lookup() to fall through to the default switch case, using INVALID_UID (nobody/65534) instead of current_fsuid() for all fid lookups. Root is then unable to chown or perform other privileged operations.

Fix by clearing the access mask before applying the user's choice.

Fixes 1f3e4142c0eb ("9p: convert to the new mount API")

Message-ID: <[email protected]>

---
 fs/9p/v9fs.c |    4 ++++
 1 file changed, 4 insertions(+)
fs/9p/v9fs.c +4 -0
@@ -408,7 +408,11 @@ static void v9fs_apply_options(struct v9
 	/*
 	 * Note that we must |= flags here as session_init already
 	 * set basic flags. This adds in flags from parsed options.
+	 * Default access flags must be cleared if session options
+	 * changes them to avoid mangling the setting.
 	 */
+	if (ctx->session_opts.flags & V9FS_ACCESS_MASK)
+		v9ses->flags &= ~V9FS_ACCESS_MASK;
 	v9ses->flags |= ctx->session_opts.flags;
 #ifdef CONFIG_9P_FSCACHE
 	v9ses->cachetag = ctx->session_opts.cachetag;
author maintainer
#979 lore raw

PATCH 978/990 9p: fix privport option setting wrong RDMA field

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stefano Garzarella <[email protected]>

commit 7fb9bd3659051ff74a29387de0023bb8300e4aa7 upstream.

While reviewing a patch adding vsock transport to 9p, I noticed that since commit 1f3e4142c0eb ("9p: convert to the new mount API"), the Opt_privport case incorrectly sets rdma_opts->port instead of rdma_opts->privport, so mounting with the privport option overwrites the RDMA port number instead of enabling privileged port usage.

Fixes 1f3e4142c0eb ("9p: convert to the new mount API")

Message-ID: <[email protected]>

---
 fs/9p/v9fs.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/9p/v9fs.c +1 -1
@@ -384,7 +384,7 @@ int v9fs_parse_param(struct fs_context *
 		break;
 	case Opt_privport:
 		fd_opts->privport = true;
-		rdma_opts->port = true;
+		rdma_opts->privport = true;
 		break;
 	}
 
author maintainer
#980 lore raw

PATCH 979/990 9p: free the session after a grace period

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit bcec7fc2e224088daf94448d663b02e0d0b9c717 upstream.

v9fs_vfs_get_link_dotl() reads ->cache from the v9fs_session_info in sb->s_fs_info to decide whether the symlink target sits in the page cache. It does that before it looks at the dentry, so it also does it in rcu pathwalk mode. Without loose or metadata caching the dentries have no ->d_revalidate() that would make the walk leave rcu mode before it gets there.

v9fs_kill_super() frees the session and clears sb->s_fs_info without waiting for a grace period. Right now a pathwalk can't still be in v9fs_vfs_get_link_dotl() at that point, but only by accident. umount(2) waits for a grace period in namespace_unlock() before it drops the mount. And a mount whose last reference goes away elsewhere, like the chdir out of a lazily unmounted directory, still gets a grace period from bdi_unregister(). v9fs_fill_super() sets up a private bdi, so generic_shutdown_super() unregisters it from kill_anon_super() and bdi_remove_from_list() waits in synchronize_rcu_expedited() before v9fs_kill_super() frees the session. That grace period protects the rcu readers of bdi_list in the writeback code. It has nothing to do with pathwalk.

Don't rely on it. Keep sb->s_fs_info and free the session after a grace period.

---
 fs/9p/v9fs.h      |    1 +
 fs/9p/vfs_super.c |    4 ++--
 2 files changed, 3 insertions(+), 2 deletions(-)
fs/9p/v9fs.h +1 -0
@@ -147,6 +147,7 @@ struct v9fs_session_info {
 	struct list_head slist; /* list of sessions registered with v9fs */
 	struct rw_semaphore rename_sem;
 	long session_lock_timeout; /* retry interval for blocking locks */
+	struct rcu_head rcu;	/* v9fs_vfs_get_link_dotl() reads ->cache in rcu pathwalk */
 };
 
 #define NDENTRY_TIMEOUT_NEVER (-1U)
fs/9p/vfs_super.c +2 -2
@@ -173,8 +173,8 @@ static void v9fs_kill_super(struct super
 
 	v9fs_session_cancel(v9ses);
 	v9fs_session_close(v9ses);
-	kfree(v9ses);
-	s->s_fs_info = NULL;
+	/* v9fs_vfs_get_link_dotl() may still read ->cache in rcu pathwalk */
+	kfree_rcu(v9ses, rcu);
 	p9_debug(P9_DEBUG_VFS, "exiting kill_super\n");
 }
 
author maintainer
#981 lore raw

PATCH 980/990 perf: Fix null pointer access in is_include_guest_event()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Vinay Belgaumkar <[email protected]>

commit 88aed0422f39b22406f35f1e758cea25e7bbcfb5 upstream.

A typical module unload occurring event when there is an active perf connection leads to freeing of the pmu pointer. The call log is something like:
..
__pmu_detach_event
pmu_detach_event
pmu_detach_events
perf_pmu_unregister
..

__pmu_detach_event() sets event->pmu to null. When the perf connection finally is closed, the following stack trace is observed:

 Oops: general protection fault, kernel NULL pointer dereference
 ...
 RIP: 0010:_free_event+0x3e/0x370
 ...
 Call Trace:
 ...
 perf_event_release_kernel+0x260/0x2d0
 perf_release+0x12/0x20

A call to mediated_pmu_unaccount_event() inside _free_event() is the root cause of this crash. Adding a check inside is_include_guest_event() ensures we don't accidentally access a null pmu ptr. In addition to this, we will now call mediated_pmu_unaccount_event() before clearing the pmu ptr so that nr_include_guest_events counts are maintained correctly.

Fixes eff95e170275 ("perf: Add APIs to create/release mediated guest vPMUs")
Assisted-by Claude:Claude-Sonnet-5
---
 kernel/events/core.c |    4 ++++
 1 file changed, 4 insertions(+)
kernel/events/core.c +4 -0
@@ -6229,6 +6229,9 @@ static DEFINE_MUTEX(perf_mediated_pmu_mu
 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */
 static inline bool is_include_guest_event(struct perf_event *event)
 {
+	if (!event->pmu)
+		return false;
+
 	if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) &&
 	    !event->attr.exclude_guest)
 		return true;
@@ -12789,6 +12792,7 @@ static void __pmu_detach_event(struct pm
 	exclusive_event_destroy(event);
 	module_put(pmu->module);
 
+	mediated_pmu_unaccount_event(event);
 	event->pmu = NULL; /* force fault instead of UAF */
 }
 
author maintainer
#982 lore raw

PATCH 981/990 wifi: ath12k: fix EHT TX MCS limitation due to wrong 20 MHz-only parsing

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Baochen Qiang <[email protected]>

commit 60fb2cf51e77bb1c0261160b4be44209d68956b1 upstream.

When connecting to an AP configured for EHT 20 MHz with a full EHT MCS/NSS map (supporting MCS 0-13)

Supported EHT-MCS and NSS Set

    EHT-MCS Map (BW <= 80MHz): 0x444444
        .... .... .... .... .... 0100 = Rx Max Nss That Supports EHT-MCS 0-9: 4
        .... .... .... .... 0100 .... = Tx Max Nss That Supports EHT-MCS 0-9: 4
        .... .... .... 0100 .... .... = Rx Max Nss That Supports EHT-MCS 10-11: 4
        .... .... 0100 .... .... .... = Tx Max Nss That Supports EHT-MCS 10-11: 4
        .... 0100 .... .... .... .... = Rx Max Nss That Supports EHT-MCS 12-13: 4
        0100 .... .... .... .... .... = Tx Max Nss That Supports EHT-MCS 12-13: 4

TX throughput is observed to be significantly lower than expected. Investigation shows that TX rates are limited to EHT MCS 11, even though the AP advertises support for EHT MCS 12/13.

The root cause is an incorrect parsing of the Supported EHT-MCS and NSS Set element in ath12k_peer_assoc_h_eht().

IEEE Std 802.11be-2024 Figure 9-1074as describes the format for 20 MHz-Only Non-AP STAs.

IEEE Std 802.11be-2024 Figure 9-1074at describes the format for all other AP and non-AP STAs.

Currently the first format is parsed when the peer advertises no wider HE channel width support, without considering whether it is an AP or a non-AP STA. This is incorrect: the peer AP's capabilities must be parsed using Figure 9-1074at even when it operates on 20 MHz only. Parsing it as Figure 9-1074as causes rx_tx_mcs13_max_nss to be interpreted as zero, which is then passed to firmware, leading firmware to assume the peer does not support MCS 13 and to limit TX rates at MCS 11.

Fix this by parsing the Figure 9-1074as format only when the peer is a 20 MHz-Only non-AP STA, i.e. when the local interface operates as AP or mesh point.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c5-00302-QCAHMTSWPL_V1.0_V2.0_SILICONZ-1.115823.3

---
 drivers/net/wireless/ath/ath12k/mac.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/net/wireless/ath/ath12k/mac.c +6 -2
@@ -3356,7 +3356,9 @@ static void ath12k_peer_assoc_h_eht(stru
 		arg->peer_eht_mcs_count++;
 		fallthrough;
 	default:
-		if (!(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
+		if ((vif->type == NL80211_IFTYPE_AP ||
+		     vif->type == NL80211_IFTYPE_MESH_POINT) &&
+		    !(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
 		      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) {
 			bw_20 = &eht_cap->eht_mcs_nss_supp.only_20mhz;
 
@@ -3385,7 +3387,9 @@ static void ath12k_peer_assoc_h_eht(stru
 	arg->punct_bitmap = ~arvif->punct_bitmap;
 	arg->eht_disable_mcs15 = link_conf->eht_disable_mcs15;
 
-	if (!(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
+	if ((vif->type == NL80211_IFTYPE_AP ||
+	     vif->type == NL80211_IFTYPE_MESH_POINT) &&
+	    !(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
 	      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) {
 		if (bw_20->rx_tx_mcs13_max_nss)
 			max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs13_max_nss,
author maintainer
#983 lore raw

PATCH 982/990 drm/xe/xe_survivability: Remove unused index

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Riana Tauro <[email protected]>

commit fb084e4183e1d79ead103265cafc4b6bc0ecba03 upstream.

Remove unused index variable and fix for loop.

---
 drivers/gpu/drm/xe/xe_survivability_mode.c |   15 ++++-----------
 1 file changed, 4 insertions(+), 11 deletions(-)
drivers/gpu/drm/xe/xe_survivability_mode.c +4 -11
@@ -120,11 +120,6 @@ xe_survivability_attribute *dev_attr_to_
 	return container_of(attr, struct xe_survivability_attribute, attr);
 }
 
-static u32 aux_history_offset(u32 reg_value)
-{
-	return REG_FIELD_GET(AUXINFO_HISTORY_OFFSET, reg_value);
-}
-
 static void set_survivability_info(struct xe_mmio *mmio, u32  *info, int id)
 {
 	info[id] = xe_mmio_read32(mmio, PCODE_SCRATCH(id));
@@ -136,7 +131,6 @@ static void populate_survivability_info(
 	u32 *info = survivability->info;
 	struct xe_mmio *mmio;
 	u32 id = 0, reg_value;
-	int index;
 
 	mmio = xe_root_tile_mmio(xe);
 	set_survivability_info(mmio, info, CAPABILITY_INFO);
@@ -149,13 +143,12 @@ static void populate_survivability_info(
 			set_survivability_info(mmio, info, POSTCODE_TRACE_OVERFLOW);
 	}
 
+	/* Traverse the linked list of aux info registers */
 	if (reg_value & AUXINFO_SUPPORT) {
-		id = REG_FIELD_GET(AUXINFO_REG_OFFSET, reg_value);
-
-		for (index = 0; id >= AUX_INFO0 && id < MAX_SCRATCH_REG; index++) {
+		for (id = REG_FIELD_GET(AUXINFO_REG_OFFSET, reg_value);
+		     id >= AUX_INFO0 && id < MAX_SCRATCH_REG;
+		     id =  REG_FIELD_GET(AUXINFO_HISTORY_OFFSET, info[id]))
 			set_survivability_info(mmio, info, id);
-			id = aux_history_offset(info[id]);
-		}
 	}
 }
 
author maintainer
#984 lore raw

PATCH 983/990 drm/xe: Dont disable GuCRC in suspend path

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Vinay Belgaumkar <[email protected]>

commit b458597544c20c31cef9d907696e8b9652b0894e upstream.

GuCRC should not be disabled in xe_guc_stop_prepare() as C6 is a prerequisite for s0ix and s2idle. This is a regression caused by the patch below.

---
 drivers/gpu/drm/xe/xe_gt.c  |    2 ++
 drivers/gpu/drm/xe/xe_guc.c |    1 -
 2 files changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/drm/xe/xe_gt.c +2 -0
@@ -40,6 +40,7 @@
 #include "xe_gt_topology.h"
 #include "xe_guc_exec_queue_types.h"
 #include "xe_guc_pc.h"
+#include "xe_guc_rc.h"
 #include "xe_guc_submit.h"
 #include "xe_hw_fence.h"
 #include "xe_hw_engine_class_sysfs.h"
@@ -889,6 +890,7 @@ static int gt_reset(struct xe_gt *gt)
 	if (IS_SRIOV_PF(gt_to_xe(gt)))
 		xe_gt_sriov_pf_stop_prepare(gt);
 
+	xe_guc_rc_disable(&gt->uc.guc);
 	xe_uc_stop_prepare(&gt->uc);
 	xe_gt_pagefault_reset(gt);
 
drivers/gpu/drm/xe/xe_guc.c +0 -1
@@ -1616,7 +1616,6 @@ void xe_guc_stop_prepare(struct xe_guc *
 	if (!IS_SRIOV_VF(guc_to_xe(guc))) {
 		int err;
 
-		xe_guc_rc_disable(guc);
 		err = xe_guc_pc_stop(&guc->pc);
 		xe_gt_WARN(guc_to_gt(guc), err, "Failed to stop GuC PC: %pe\n",
 			   ERR_PTR(err));
author maintainer
#985 lore raw

PATCH 984/990 net: bridge: vlan: fix bugs caused by switchdev deletion errors

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Nikolay Aleksandrov <[email protected]>

commit 2842ce397dd09882530b42f7fdb0c855767eb24e upstream.

Allowing switchdev to prevent vlan deletion and error out in __vlan_del could cause multiple different issues - inconsistent state, memory leaks when flushing, NULL pointer dereference on bridge error when flushing. It doesn't make sense to allow it to stop __vlan_del, so log the error and continue with software vlan deletion. This is also consistent with 8021q behaviour.

Fixes bf361ad38165 ("net: bridge: check __vlan_vid_del for error")
Fixes 5454f5c28eca ("net: bridge: vlan: check for errors from __vlan_del in __vlan_flush")
Fixes 2594e9064a57 ("bridge: vlan: add per-vlan struct and move to rhashtables")
Fixes 9c86ce2c1ae3 ("net: bridge: Notify about bridge VLANs")
---
 net/bridge/br_vlan.c |   31 ++++++++++++++-----------------
 1 file changed, 14 insertions(+), 17 deletions(-)
net/bridge/br_vlan.c +14 -17
@@ -387,12 +387,12 @@ out_filt:
 	goto out;
 }
 
-static int __vlan_del(struct net_bridge_vlan *v)
+static void __vlan_del(struct net_bridge_vlan *v)
 {
 	struct net_bridge_vlan *masterv = v;
 	struct net_bridge_vlan_group *vg;
 	struct net_bridge_port *p = NULL;
-	int err = 0;
+	int err;
 
 	if (br_vlan_is_master(v)) {
 		vg = br_vlan_group(v->br);
@@ -406,12 +406,16 @@ static int __vlan_del(struct net_bridge_
 	if (p) {
 		err = __vlan_vid_del(p->dev, p->br, v);
 		if (err)
-			goto out;
+			br_warn(p->br,
+				"port %u(%s) failed to delete vlan %u from switchdev: %pe\n",
+				(unsigned int)p->port_no, p->dev->name,
+				v->vid, ERR_PTR(err));
 	} else {
 		err = br_switchdev_port_vlan_del(v->br->dev, v->vid);
 		if (err && err != -EOPNOTSUPP)
-			goto out;
-		err = 0;
+			br_warn(v->br,
+				"failed to delete bridge vlan %u from switchdev: %pe\n",
+				v->vid, ERR_PTR(err));
 	}
 
 	if (br_vlan_should_use(v)) {
@@ -431,8 +435,6 @@ static int __vlan_del(struct net_bridge_
 	}
 
 	br_vlan_put_master(masterv);
-out:
-	return err;
 }
 
 static void __vlan_group_free(struct net_bridge_vlan_group *vg)
@@ -449,7 +451,6 @@ static void __vlan_flush(const struct ne
 {
 	struct net_bridge_vlan *vlan, *tmp;
 	u16 v_start = 0, v_end = 0;
-	int err;
 
 	__vlan_delete_pvid(vg, vg->pvid);
 	list_for_each_entry_safe(vlan, tmp, &vg->vlan_list, vlist) {
@@ -463,13 +464,7 @@ static void __vlan_flush(const struct ne
 		}
 		v_end = vlan->vid;
 
-		err = __vlan_del(vlan);
-		if (err) {
-			br_err(br,
-			       "port %u(%s) failed to delete vlan %d: %pe\n",
-			       (unsigned int) p->port_no, p->dev->name,
-			       vlan->vid, ERR_PTR(err));
-		}
+		__vlan_del(vlan);
 	}
 
 	/* notify about the last/whole vlan range */
@@ -837,8 +832,9 @@ int br_vlan_delete(struct net_bridge *br
 	br_fdb_delete_by_port(br, NULL, vid, 0);
 
 	vlan_tunnel_info_del(vg, v);
+	__vlan_del(v);
 
-	return __vlan_del(v);
+	return 0;
 }
 
 void br_vlan_flush(struct net_bridge *br)
@@ -1368,8 +1364,9 @@ int nbp_vlan_delete(struct net_bridge_po
 		return -ENOENT;
 	br_fdb_find_delete_local(port->br, port, port->dev->dev_addr, vid);
 	br_fdb_delete_by_port(port->br, port, vid, 0);
+	__vlan_del(v);
 
-	return __vlan_del(v);
+	return 0;
 }
 
 void nbp_vlan_flush(struct net_bridge_port *port)
author maintainer
#986 lore raw

PATCH 985/990 xfrm: hold net_device reference under RCU in bundle creation

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>

commit 9fa903b24b1f46b4ff5443bcd4aca23e5c57f9c1 upstream.

xfrm_bundle_create() and xfrm_create_dummy_bundle() read dst->dev into a local pointer without taking a device reference, then pass it to xfrm_fill_dst(). A concurrent RTM_DELLINK replaces dst->dev via dst_dev_put() and frees the old net_device, causing a use-after-free when xfrm6_fill_dst() later dereferences the stale dev pointer.

  BUG: KASAN: slab-use-after-free in xfrm6_fill_dst+0x82c/0x860
  (net/ipv6/xfrm6_policy.c:86 netdev_hold())
  Read of size 8 at addr ffff8880142fe588 by task exploit/153
  Call Trace:
   xfrm6_fill_dst+0x82c/0x860
   xfrm_resolve_and_create_bundle+0x21d4/0x2bd0
   xfrm_lookup_with_ifid+0x485/0x1640
   ip6_dst_lookup_flow+0x19b/0x1e0
   udpv6_sendmsg+0x1443/0x2dd0

Fix this by reading dst->dev via dst_dev_rcu() and keeping the RCU read-side critical section active until xfrm_fill_dst() has taken the required device references.

Fixes 25ee3286dcbc ("[IPSEC]: Merge common code into xfrm_bundle_create")
Fixes a0073fe18e71 ("xfrm: Add a state resolution packet queue")
Assisted-by GitHub-Copilot:claude-opus-4.6
---
 net/xfrm/xfrm_policy.c |   20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
net/xfrm/xfrm_policy.c +15 -5
@@ -2777,9 +2777,12 @@ static struct dst_entry *xfrm_bundle_cre
 	xdst0->path = dst;
 
 	err = -ENODEV;
-	dev = dst->dev;
-	if (!dev)
+	rcu_read_lock();
+	dev = dst_dev_rcu(dst);
+	if (!dev) {
+		rcu_read_unlock();
 		goto free_dst;
+	}
 
 	xfrm_init_path(xdst0, dst, nfheader_len);
 	xfrm_init_pmtu(bundle, nx);
@@ -2787,8 +2790,10 @@ static struct dst_entry *xfrm_bundle_cre
 	for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
 	     xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
 		err = xfrm_fill_dst(xdst_prev, dev, fl);
-		if (err)
+		if (err) {
+			rcu_read_unlock();
 			goto free_dst;
+		}
 
 		xdst_prev->u.dst.header_len = header_len;
 		xdst_prev->u.dst.trailer_len = trailer_len;
@@ -2796,6 +2801,7 @@ static struct dst_entry *xfrm_bundle_cre
 		trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
 	}
 
+	rcu_read_unlock();
 	return &xdst0->u.dst;
 
 put_states:
@@ -3065,11 +3071,15 @@ static struct xfrm_dst *xfrm_create_dumm
 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
 
 	err = -ENODEV;
-	dev = dst->dev;
-	if (!dev)
+	rcu_read_lock();
+	dev = dst_dev_rcu(dst);
+	if (!dev) {
+		rcu_read_unlock();
 		goto free_dst;
+	}
 
 	err = xfrm_fill_dst(xdst, dev, fl);
+	rcu_read_unlock();
 	if (err)
 		goto free_dst;
 
author maintainer
#987 lore raw

PATCH 986/990 net: ipv6: keep room for the mac header in dst_dev_overhead()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yuya Kusakabe <[email protected]>

commit 87cd6b717e4069dca34e0866e57eaeb44d3b173e upstream.

The seg6, ioam6 and rpl lwtunnels size their skb_cow_head() request as the length they are about to push plus dst_dev_overhead(), then push the new headers and rebuild the mac header below them with skb_mac_header_rebuild(). That rebuild needs skb->mac_len of headroom, but dst_dev_overhead() leaves LL_RESERVED_SPACE() of the egress device, 16 bytes for plain Ethernet.

Where the mac header is longer than that, as it is on ingress through a VLAN device with reorder_hdr off, the rebuild runs out of room:
skb_set_mac_header(skb, -skb->mac_len) computes a negative offset, stores it unchecked in the u16 skb->mac_header, and the memmove that follows writes skb->mac_len bytes about 64 KB past skb->head. Forwarding plain ping6 traffic through such a device reproduces it on all five seg6 encapsulation modes and on the rpl and ioam6 inline paths; skb->mac_header comes back as 65534 on a 704-byte head.

Return the larger of the two. The helper already returns skb->mac_len when it has no dst, so this only makes the other branch agree, and it covers every caller rather than each call site in turn.

Fixes 40475b63761a ("net: ipv6: seg6_iptunnel: mitigate 2-realloc issue")
Fixes dce525185bc9 ("net: ipv6: ioam6_iptunnel: mitigate 2-realloc issue")
Fixes 985ec6f5e623 ("net: ipv6: rpl_iptunnel: mitigate 2-realloc issue")
---
 include/net/dst.h |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/net/dst.h +2 -1
@@ -455,7 +455,8 @@ static inline unsigned int dst_dev_overh
 					    struct sk_buff *skb)
 {
 	if (likely(dst))
-		return LL_RESERVED_SPACE(dst->dev);
+		return max_t(unsigned int, skb->mac_len,
+			     LL_RESERVED_SPACE(dst->dev));
 
 	return skb->mac_len;
 }
author maintainer
#988 lore raw

PATCH 987/990 seg6: ensure packet data is writable before modifying SRH and IPv6 DA

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Mayer <[email protected]>

commit 8ae3f4067ba4ae3a15581392f6dac422e3d3def0 upstream.

advance_nextseg() modifies the SRH Segments Left field and the IPv6 destination address without ensuring the packet data is writable. seg6_next_csid_advance_arg() has the same problem when it advances the NEXT-C-SID argument in the destination address.

The skb may be cloned, for example by an AF_PACKET socket receiving on the ingress device. advance_nextseg() and seg6_next_csid_advance_arg() then write into the packet data shared with the clone. A read from that socket can return the modified packet instead of the received one. The simplified path below shows this for advance_nextseg():

__netif_receive_skb_one_core
__netif_receive_skb_core
deliver_skb [orig: users=2, cloned=0]
packet_rcv
skb_clone clone queued to the AF_PACKET socket
consume_skb(orig) [orig: users=1, cloned=1]
ipv6_rcv
ip6_rcv_core skb_share_check: no-op [orig: users=1]
[...]
input_action_end_core
advance_nextseg writes into the data shared with the clone

Call skb_ensure_writable() in advance_nextseg() and in seg6_next_csid_advance_arg() before they modify the packet data. skb_ensure_writable() may reallocate skb->head, which invalidates the pointers into the packet data taken before the call. advance_nextseg() now returns a valid SRH pointer, or NULL if skb_ensure_writable() fails.
seg6_next_csid_advance_arg() takes the pointer to the destination address from the skb after skb_ensure_writable().
On failure, the callers drop the packet with SKB_DROP_REASON_NOMEM.

Fixes 140f04c33bbc ("ipv6: sr: implement several seg6local actions")
Fixes 848f3c0d4769 ("seg6: add NEXT-C-SID support for SRv6 End behavior")
---
 net/ipv6/seg6_local.c |  140 +++++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 117 insertions(+), 23 deletions(-)
net/ipv6/seg6_local.c +117 -23
@@ -292,13 +292,43 @@ static bool decap_and_validate(struct sk
 	return true;
 }
 
-static void advance_nextseg(struct ipv6_sr_hdr *srh, struct in6_addr *daddr)
+/* advance the SRH to the next segment and set the IPv6 DA accordingly.
+ * skb pointers may change: after this call, the caller must evaluate again
+ * any pointer into the packet data.
+ *
+ * This function returns:
+ *  - the SRH on success;
+ *  - NULL when the skb cannot be made writable. In this case, the function
+ *    sets the drop reason to SKB_DROP_REASON_NOMEM.
+ */
+static struct ipv6_sr_hdr *advance_nextseg(struct sk_buff *skb,
+					   struct ipv6_sr_hdr *srh,
+					   enum skb_drop_reason *reason)
 {
 	struct in6_addr *addr;
+	int srhoff;
+	int wlen;
+
+	srhoff = (unsigned char *)srh - skb->data;
+	/* we write only the Segment Left field and the IPv6 DA. The segment
+	 * list is only read, and seg6_get_srh() already pulled it into the
+	 * linear area.
+	 */
+	wlen = srhoff + sizeof(*srh);
+
+	if (unlikely(skb_ensure_writable(skb, wlen))) {
+		*reason = SKB_DROP_REASON_NOMEM;
+		return NULL;
+	}
+
+	/* skb_ensure_writable() may change skb pointers; evaluate srh again */
+	srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
 
 	srh->segments_left--;
 	addr = srh->segments + srh->segments_left;
-	*daddr = *addr;
+	ipv6_hdr(skb)->daddr = *addr;
+
+	return srh;
 }
 
 static int
@@ -396,12 +426,26 @@ static bool seg6_next_csid_is_arg_zero(c
 	return true;
 }
 
-/* assume that DA.Argument length > 0 */
-static void seg6_next_csid_advance_arg(struct in6_addr *addr,
-				       const struct seg6_flavors_info *finfo)
+/* assume that DA.Argument length > 0.
+ * skb pointers may change: after this call, the caller must evaluate again
+ * any pointer into the packet data.
+ *
+ * This function returns:
+ *  - SKB_NOT_DROPPED_YET on success;
+ *  - SKB_DROP_REASON_NOMEM when the skb cannot be made writable.
+ */
+static enum skb_drop_reason
+seg6_next_csid_advance_arg(struct sk_buff *skb,
+			   const struct seg6_flavors_info *finfo)
 {
 	__u8 fnc_octects = seg6_flv_lcnode_func_octects(finfo);
 	__u8 blk_octects = seg6_flv_lcblock_octects(finfo);
+	struct in6_addr *addr;
+
+	if (unlikely(skb_ensure_writable(skb, sizeof(struct ipv6hdr))))
+		return SKB_DROP_REASON_NOMEM;
+
+	addr = &ipv6_hdr(skb)->daddr;
 
 	/* advance DA.Argument */
 	memmove(&addr->s6_addr[blk_octects],
@@ -409,6 +453,8 @@ static void seg6_next_csid_advance_arg(s
 		16 - blk_octects - fnc_octects);
 
 	memset(&addr->s6_addr[16 - fnc_octects], 0x00, fnc_octects);
+
+	return SKB_NOT_DROPPED_YET;
 }
 
 static int input_action_end_finish(struct sk_buff *skb,
@@ -422,31 +468,42 @@ static int input_action_end_finish(struc
 static int input_action_end_core(struct sk_buff *skb,
 				 struct seg6_local_lwt *slwt)
 {
+	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
 	struct ipv6_sr_hdr *srh;
+	int err = -EINVAL;
 
 	srh = get_and_validate_srh(skb);
 	if (!srh)
 		goto drop;
 
-	advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+	srh = advance_nextseg(skb, srh, &reason);
+	if (!srh) {
+		err = -ENOMEM;
+		goto drop;
+	}
 
 	return input_action_end_finish(skb, slwt);
 
 drop:
-	kfree_skb(skb);
-	return -EINVAL;
+	kfree_skb_reason(skb, reason);
+	return err;
 }
 
 static int end_next_csid_core(struct sk_buff *skb, struct seg6_local_lwt *slwt)
 {
 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
 	struct in6_addr *daddr = &ipv6_hdr(skb)->daddr;
+	enum skb_drop_reason reason;
 
 	if (seg6_next_csid_is_arg_zero(daddr, finfo))
 		return input_action_end_core(skb, slwt);
 
 	/* update DA */
-	seg6_next_csid_advance_arg(daddr, finfo);
+	reason = seg6_next_csid_advance_arg(skb, finfo);
+	if (reason) {
+		kfree_skb_reason(skb, reason);
+		return -ENOMEM;
+	}
 
 	return input_action_end_finish(skb, slwt);
 }
@@ -462,19 +519,25 @@ static int input_action_end_x_finish(str
 static int input_action_end_x_core(struct sk_buff *skb,
 				   struct seg6_local_lwt *slwt)
 {
+	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
 	struct ipv6_sr_hdr *srh;
+	int err = -EINVAL;
 
 	srh = get_and_validate_srh(skb);
 	if (!srh)
 		goto drop;
 
-	advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+	srh = advance_nextseg(skb, srh, &reason);
+	if (!srh) {
+		err = -ENOMEM;
+		goto drop;
+	}
 
 	return input_action_end_x_finish(skb, slwt);
 
 drop:
-	kfree_skb(skb);
-	return -EINVAL;
+	kfree_skb_reason(skb, reason);
+	return err;
 }
 
 static int end_x_next_csid_core(struct sk_buff *skb,
@@ -482,12 +545,17 @@ static int end_x_next_csid_core(struct s
 {
 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
 	struct in6_addr *daddr = &ipv6_hdr(skb)->daddr;
+	enum skb_drop_reason reason;
 
 	if (seg6_next_csid_is_arg_zero(daddr, finfo))
 		return input_action_end_x_core(skb, slwt);
 
 	/* update DA */
-	seg6_next_csid_advance_arg(daddr, finfo);
+	reason = seg6_next_csid_advance_arg(skb, finfo);
+	if (reason) {
+		kfree_skb_reason(skb, reason);
+		return -ENOMEM;
+	}
 
 	return input_action_end_x_finish(skb, slwt);
 }
@@ -774,10 +842,12 @@ pull:
  */
 static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt)
 {
+	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
 	enum seg6_local_flv_action action;
 	enum seg6_local_pktinfo pinfo;
 	struct ipv6_sr_hdr *srh;
+	int err = -EINVAL;
 	__u32 flvmask;
 	int srhoff;
 
@@ -801,10 +871,18 @@ static int end_flv8986_core(struct sk_bu
 	switch (action) {
 	case SEG6_LOCAL_FLV_ACT_END:
 		/* process the packet as the "standard" End behavior */
-		advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+		srh = advance_nextseg(skb, srh, &reason);
+		if (!srh) {
+			err = -ENOMEM;
+			goto drop;
+		}
 		break;
 	case SEG6_LOCAL_FLV_ACT_PSP:
-		advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+		srh = advance_nextseg(skb, srh, &reason);
+		if (!srh) {
+			err = -ENOMEM;
+			goto drop;
+		}
 
 		if (unlikely(!seg6_pop_srh(skb, srhoff)))
 			goto drop;
@@ -821,8 +899,8 @@ static int end_flv8986_core(struct sk_bu
 	return input_action_end_finish(skb, slwt);
 
 drop:
-	kfree_skb(skb);
-	return -EINVAL;
+	kfree_skb_reason(skb, reason);
+	return err;
 }
 
 /* regular endpoint function */
@@ -861,21 +939,27 @@ static int input_action_end_x(struct sk_
 
 static int input_action_end_t(struct sk_buff *skb, struct seg6_local_lwt *slwt)
 {
+	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
 	struct ipv6_sr_hdr *srh;
+	int err = -EINVAL;
 
 	srh = get_and_validate_srh(skb);
 	if (!srh)
 		goto drop;
 
-	advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+	srh = advance_nextseg(skb, srh, &reason);
+	if (!srh) {
+		err = -ENOMEM;
+		goto drop;
+	}
 
 	seg6_lookup_nexthop(skb, NULL, slwt->table);
 
 	return dst_input(skb);
 
 drop:
-	kfree_skb(skb);
-	return -EINVAL;
+	kfree_skb_reason(skb, reason);
+	return err;
 }
 
 /* decapsulate and forward inner L2 frame on specified interface */
@@ -1450,6 +1534,7 @@ drop:
 static int input_action_end_b6_encap(struct sk_buff *skb,
 				     struct seg6_local_lwt *slwt)
 {
+	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
 	struct ipv6_sr_hdr *srh;
 	int err = -EINVAL;
 
@@ -1457,7 +1542,11 @@ static int input_action_end_b6_encap(str
 	if (!srh)
 		goto drop;
 
-	advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+	srh = advance_nextseg(skb, srh, &reason);
+	if (!srh) {
+		err = -ENOMEM;
+		goto drop;
+	}
 
 	skb_reset_inner_headers(skb);
 	skb->encapsulation = 1;
@@ -1473,7 +1562,7 @@ static int input_action_end_b6_encap(str
 	return dst_input(skb);
 
 drop:
-	kfree_skb(skb);
+	kfree_skb_reason(skb, reason);
 	return err;
 }
 
@@ -1509,6 +1598,7 @@ static int input_action_end_bpf(struct s
 				struct seg6_local_lwt *slwt)
 {
 	struct seg6_bpf_srh_state *srh_state;
+	enum skb_drop_reason reason;
 	struct ipv6_sr_hdr *srh;
 	int ret;
 
@@ -1517,7 +1607,11 @@ static int input_action_end_bpf(struct s
 		kfree_skb(skb);
 		return -EINVAL;
 	}
-	advance_nextseg(srh, &ipv6_hdr(skb)->daddr);
+	srh = advance_nextseg(skb, srh, &reason);
+	if (!srh) {
+		kfree_skb_reason(skb, reason);
+		return -ENOMEM;
+	}
 
 	/* The access to the per-CPU buffer srh_state is protected by running
 	 * always in softirq context (with disabled BH). On PREEMPT_RT the
author maintainer
#989 lore raw

PATCH 988/990 tcp: Set unhashed_state in inet_twsk_hashdance_schedule().

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kuniyuki Iwashima <[email protected]>

commit 404381b4f1053a271a85679cc76a543b10ae043e upstream.

inet_unhash() sets inet_csk(sk)->unhashed_state only when the socket is hashed because tcp_set_state(sk, TCP_CLOSE) could be called multiple times, e.g. tcp_abort() calls it directly and tcp_done_with_error().

However, inet_twsk_hashdance_schedule() also unhashes a socket when replacing it with twsk, allowing the socket to bypass checks for inet_csk(sk)->unhashed_state.

Let's update inet_csk(sk)->unhashed_state there as well.

---
 net/ipv4/inet_timewait_sock.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/ipv4/inet_timewait_sock.c +4 -2
@@ -111,11 +111,13 @@ void inet_twsk_hashdance_schedule(struct
 				  struct inet_hashinfo *hashinfo,
 				  int timeo)
 {
-	const struct inet_sock *inet = inet_sk(sk);
-	const struct inet_connection_sock *icsk = inet_csk(sk);
 	struct inet_ehash_bucket *ehead = inet_ehash_bucket(hashinfo, sk->sk_hash);
+	struct inet_connection_sock *icsk = inet_csk(sk);
 	spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
 	struct inet_bind_hashbucket *bhead, *bhead2;
+	const struct inet_sock *inet = inet_sk(sk);
+
+	icsk->unhashed_state = sk->sk_state;
 
 	/* Step 1: Put TW into bind hash. Original socket stays there too.
 	   Note, that any socket with inet->num != 0 MUST be bound in
author maintainer
#990 lore raw

PATCH 989/990 mtd: core: avoid double-free of OTP NVMEM device

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Karl Mehltretter <[email protected]>

commit 26300879cd8e4612dce66bb8f6ff7cd35fcf3e59 upstream.

If factory OTP setup fails after the user OTP NVMEM device has been registered, mtd_otp_nvmem_add() unregisters the user device but leaves mtd->otp_user_nvmem set. On an error, the caller unregisters it again. For -EOPNOTSUPP, registration continues and normal teardown unregisters it again.

Clear mtd->otp_user_nvmem after unregistering it.

Fixes e0489f6e221f ("mtd: core: fix error path for nvmem provider")
Fixes fe0b8213c012 ("mtd: core: Don't fail mtd_otp_nvmem_add() if OTP is unsupported")
Assisted-by Codex:gpt-5.6-sol
---
 drivers/mtd/mtdcore.c |    1 +
 1 file changed, 1 insertion(+)
drivers/mtd/mtdcore.c +1 -0
@@ -1082,6 +1082,7 @@ static int mtd_otp_nvmem_add(struct mtd_
 
 err:
 	nvmem_unregister(mtd->otp_user_nvmem);
+	mtd->otp_user_nvmem = NULL;
 	/* Don't report error if OTP is not supported. */
 	if (err == -EOPNOTSUPP)
 		return 0;
author maintainer
#991 lore raw

PATCH 990/990 greybus: raw: fix use-after-free if write is called after disconnect

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Damien Riégel <[email protected]>

commit 84265cbd96b97058ef67e3f8be3933667a000835 upstream.

If a user writes to the chardev after disconnect has been called, the kernel panics with the following trace (with CONFIG_INIT_ON_FREE_DEFAULT_ON=y):

        BUG: kernel NULL pointer dereference, address: 0000000000000218
         ...
        Call Trace:
         <TASK>
         gb_operation_create_common+0x61/0x180
         gb_operation_create_flags+0x28/0xa0
         gb_operation_sync_timeout+0x6f/0x100
         raw_write+0x7b/0xc7 [gb_raw]
         vfs_write+0xcf/0x420
         ? task_mm_cid_work+0x136/0x220
         ksys_write+0x63/0xe0
         do_syscall_64+0xa4/0x290
         entry_SYSCALL_64_after_hwframe+0x77/0x7f

Disconnect calls gb_connection_destroy, which ends up freeing the connection object. When gb_operation_sync is called in the write file operations, its gets a freed connection as parameter and the kernel panics.

The gb_connection_destroy cannot be moved out of the disconnect function, as the Greybus subsystem expect all connections belonging to a bundle to be destroyed when disconnect returns.

To prevent this bug, use a rw lock to synchronize access between write and disconnect. This guarantees that the write function doesn't try to use a disconnected connection.

---
 drivers/staging/greybus/raw.c |   23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
drivers/staging/greybus/raw.c +21 -2
@@ -21,6 +21,8 @@ struct gb_raw {
 	struct list_head list;
 	int list_data;
 	struct mutex list_lock;
+	struct rw_semaphore disconnect_lock;
+	bool disconnected;
 	struct cdev cdev;
 	struct device dev;
 };
@@ -200,6 +202,7 @@ static int gb_raw_probe(struct gb_bundle
 
 	INIT_LIST_HEAD(&raw->list);
 	mutex_init(&raw->list_lock);
+	init_rwsem(&raw->disconnect_lock);
 
 	raw->connection = connection;
 	greybus_set_drvdata(bundle, raw);
@@ -235,6 +238,11 @@ static void gb_raw_disconnect(struct gb_
 	struct raw_data *temp;
 
 	cdev_device_del(&raw->cdev, &raw->dev);
+
+	down_write(&raw->disconnect_lock);
+	raw->disconnected = true;
+	up_write(&raw->disconnect_lock);
+
 	gb_connection_disable(connection);
 	gb_connection_destroy(connection);
 
@@ -277,11 +285,22 @@ static ssize_t raw_write(struct file *fi
 	if (count > MAX_PACKET_SIZE)
 		return -E2BIG;
 
+	down_read(&raw->disconnect_lock);
+
+	if (raw->disconnected) {
+		retval = -ENODEV;
+		goto exit;
+	}
+
 	retval = gb_raw_send(raw, count, buf);
 	if (retval)
-		return retval;
+		goto exit;
 
-	return count;
+	retval = count;
+exit:
+	up_read(&raw->disconnect_lock);
+
+	return retval;
 }
 
 static ssize_t raw_read(struct file *file, char __user *buf, size_t count,
#992 lore raw
In reply to Greg Kroah-Hartman
Quoted 5 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.18.66 release. There are 990 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Quoted 8 lines

Responses should be made by Fri, 27 Nov 2026 14:36:57 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.18.66-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.18.y
and the diffstat can be found below.

Similar build failure as for 6.12.120-rc1:

  LD [M]  drivers/gpu/drm/amd/amdgpu/amdgpu.o
  AR      drivers/gpu/built-in.a
  AR      drivers/built-in.a

make[1]: *** [/usr/src/linux-stable-rc/Makefile:2051: .] Error 2
make: *** [Makefile:248: __sub-make] Error 2

Reverting 4d1bfec69f617f91af00b5cb9b86cae8850049ab fixes the build.

Signature · 1 line
Brett Sheffield (he/him)
author maintainer
#993 lore raw
Quoted 17 lines · Brett A C Sheffield
Quoted 5 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.18.66 release. There are 990 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Quoted 8 lines

Responses should be made by Fri, 27 Nov 2026 14:36:57 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.18.66-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.18.y
and the diffstat can be found below.

Similar build failure as for 6.12.120-rc1:

Quoted 7 lines
  LD [M]  drivers/gpu/drm/amd/amdgpu/amdgpu.o
  AR      drivers/gpu/built-in.a
  AR      drivers/built-in.a

make[1]: *** [/usr/src/linux-stable-rc/Makefile:2051: .] Error 2
make: *** [Makefile:248: __sub-make] Error 2

Reverting 4d1bfec69f617f91af00b5cb9b86cae8850049ab fixes the build.

Again, can you show the real error?

#994 lore raw
Quoted 24 lines · Greg Kroah-Hartman
Quoted 23 lines · Brett A C Sheffield
Quoted 5 lines · Greg Kroah-Hartman

This is the start of the stable review cycle for the 6.18.66 release. There are 990 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

Quoted 8 lines

Responses should be made by Fri, 27 Nov 2026 14:36:57 +0000. Anything received after that time might be too late.

The whole patch series can be found in one patch at:

	https://www.kernel.org/pub/linux/kernel/v6.x/stable-review/patch-6.18.66-rc1.gz

or in the git tree and branch at:
git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable-rc.git linux-6.18.y
and the diffstat can be found below.

Similar build failure as for 6.12.120-rc1:

  LD [M]  drivers/gpu/drm/amd/amdgpu/amdgpu.o
  AR      drivers/gpu/built-in.a
  AR      drivers/built-in.a

make[1]: *** [/usr/src/linux-stable-rc/Makefile:2051: .] Error 2
make: *** [Makefile:248: __sub-make] Error 2

Quoted 3 lines
Quoted 1 line

Reverting 4d1bfec69f617f91af00b5cb9b86cae8850049ab fixes the build.

Again, can you show the real error?

fs/nfs/nfs4proc.c: In function ‘nfs4_proc_unlck’:
fs/nfs/nfs4proc.c:7331:24: error: variable ‘cbnl’ has initializer but incomplete type

 7331 |                 struct cb_notify_lock_args cbnl = { .cbnl_valid = false };
      |                        ^~~~~~~~~~~~~~~~~~~

fs/nfs/nfs4proc.c:7331:54: error: ‘struct cb_notify_lock_args’ has no member named ‘cbnl_valid’
7331 | struct cb_notify_lock_args cbnl = { .cbnl_valid = false };
| ^~~~~~~~~~
fs/nfs/nfs4proc.c:7331:67: error: excess elements in struct initializer [-Werror]
7331 | struct cb_notify_lock_args cbnl = { .cbnl_valid = false };
| ^~~~~
fs/nfs/nfs4proc.c:7331:67: note: (near initialization for ‘cbnl’)
fs/nfs/nfs4proc.c:7331:44: error: storage size of ‘cbnl’ isn’t known
7331 | struct cb_notify_lock_args cbnl = { .cbnl_valid = false };
| ^~~~
fs/nfs/nfs4proc.c:7335:33: error: ‘struct nfs_client’ has no member named ‘cl_lock_waitq’; did you mean ‘cl_rpcwaitq’?

 7335 |                 __wake_up(&clp->cl_lock_waitq, TASK_NORMAL, 0, &cbnl);
      |                                 ^~~~~~~~~~~~~
      |                                 cl_rpcwaitq
fs/nfs/nfs4proc.c:7331:44: error: unused variable ‘cbnl’ [-Werror=unused-variable]
 7331 |                 struct cb_notify_lock_args cbnl = { .cbnl_valid = false };
      |
Signature · 1 line
Brett Sheffield (he/him)