Skip to contentSkip to conversation

HID: intel-thc-hid: intel-ipts: support THC IPTS ports

PATCH Superseded Emfox Zhou 2 participants 8 messages Nov 18

Subsystems (3)

v7 of 9 Superseded Latest is v9 →

lore
Share & tools
lore

Emfox Zhou

author
#0 lore raw

v7 cover HID: intel-thc-hid: intel-ipts: support THC IPTS ports

The THC ports on Tiger Lake, Lakefield, Alder Lake and Raptor Lake run in IPTS mode: plain SPI with a private framing instead of HIDSPI, which is all intel-thc-hid handles today. This adds a backend for them next to intel-quickspi and intel-quicki2c, on top of the same core.

It is based on v7.4-rc3 with two core fix series applied, both still under review:

https://lore.kernel.org/r/[email protected]
https://lore.kernel.org/r/[email protected]

One gives the DMA engines a lifetime, the other keeps a PRD table from overrunning after a reset, and the recovery path here relies on both. They overlap in intel-thc-dma.c: apply the first, then the second.

Register, DMA and interrupt work goes through the exported intel-thc API, except in four places where the core has no call for it: the reset, port-supported and quiesce-state bits of THC_M_PRT_CONTROL are accessed directly. Nothing outside the new directory changes except Kconfig and Makefile.

The hardware facts - port IDs, configuration block layout, frame codes and header sizes - come from the ithc driver linux-surface ships, at
https://github.com/quo/ithc-linux 6d53c9c (dual licensed GPL-2.0 / BSD-2-Clause); no code is taken from it. The layout, the frame format and the ordering between quiesce, interrupt configuration and the DMA engines are the parts most likely to need scrutiny; each is argued in the commit message that relies on it. All of it was confirmed on a Surface Pro 8 with a 045e:0c37 controller.

The first four patches each leave a state that builds and loads: port bring-up, DMA and interrupts, HID registration, system sleep. The fifth documents the frame format and the IPTS handshake.

Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v7:

- A reset no longer races the threaded handler: the port is masked, synchronize_irq() waits for a run already inside, and only then is the engine reset. A run that acknowledged the end of a frame the reset had just re-armed the engine for would lose the interrupt announcing it again. The two flags are cleared in an order that cannot turn away a run which found the reset finished.

- A request that cannot complete is refused instead of sent: one issued from inside the threaded handler, which is the thread that has to deliver its completion, and one issued while a reset is queued or running, where the write would wait out its timeout holding the bus lock the reset needs. The descriptor path retries both a reset's refusal and a write that lost its completion to one, since a descriptor request carries nothing a late answer could spoil.

- The waits happen outside the lock, which now covers only the write. The handler calls into the HID core on its way to a report, so a request issued there would wait for a lock its own thread holds. A queued reset leaves the line open for the same reason, and reports an overrun once instead of once per frame.

- The feature gate is released by the caller that takes the answer, not by the frame that brings it, and the check and the copy happen under one lock hold. Only a timeout shuts the channel: an answer dropped by a reset was never left out there.

- The port is masked before the interrupt handler is registered, so an enable left by firmware cannot make the shared level line assert with nothing to acknowledge it. Teardown keeps the line open until the write already inside thc_dma_write() gets its completion, and waits for the handler once more after the buffers are gone.

- Smaller ones: a descriptor larger than HID_MAX_DESCRIPTOR_SIZE is rejected before it reaches hid_parse_report(); the SPI timing comment says fastest, not slowest; the DEVRST comment says which way the bit goes; the two comments that disagreed about masking are one.

- The documentation names the two steps that precede the first configuration read, gives the bit positions it had only described in words, points at ipts.h for the offsets it restates, and says what system sleep does to the hidraw node.

Emfox Zhou (5):
HID: intel-thc-hid: intel-ipts: bring up the port
HID: intel-thc-hid: intel-ipts: receive reports
HID: intel-thc-hid: intel-ipts: add the HID device
HID: intel-thc-hid: intel-ipts: handle system sleep
HID: intel-thc-hid: intel-ipts: document the IPTS mode

 Documentation/hid/intel-thc-hid.rst           | 109 +-
 drivers/hid/intel-thc-hid/Kconfig             |  14 +
 drivers/hid/intel-thc-hid/Makefile            |   4 +
 drivers/hid/intel-thc-hid/intel-ipts/ipts.c   | 975 ++++++++++++++++++
 drivers/hid/intel-thc-hid/intel-ipts/ipts.h   | 200 ++++
 .../hid/intel-thc-hid/intel-ipts/pci-ipts.c   | 193 ++++
 6 files changed, 1494 insertions(+), 1 deletion(-)
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/ipts.c
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/ipts.h
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

author
#1 lore raw

PATCH v7 1/5 HID: intel-thc-hid: intel-ipts: bring up the port

Ports on Tiger Lake, Lakefield, Alder Lake and Raptor Lake can run in IPTS mode: instead of HIDSPI the port drives the touch controller over plain SPI, and the controller answers with a 64 byte configuration block at address zero that carries the vendor and product IDs, the buffer sizes and the SPI timing it expects.

Add a port driver that does that much: select the SPI port, release the controller from reset, read the configuration block over the existing PIO path, apply the timing the controller asked for and enable the touch engine. Removal puts it back into reset.

Three things are not obvious from the register names:

- The bulk data window is at 0x1000, not at zero, and has to be set before the DMA engines run: they write there, and left unset they write into the configuration block, where the controller drops the frames without reporting an error.

- Quiescing gates the whole data path, not only the interrupt. The port stays quiesced while the block is read and the timing applied, and is released only once that is done.

- The edge detect bit belongs to the interrupt setup, but is set
here: the first configuration read is unreliable without it.

Meteor Lake and newer IDs are deliberately absent: those ports are already claimed by the HIDSPI driver.

---
 drivers/hid/intel-thc-hid/Kconfig             |  14 +
 drivers/hid/intel-thc-hid/Makefile            |   4 +
 drivers/hid/intel-thc-hid/intel-ipts/ipts.c   | 240 ++++++++++++++++++
 drivers/hid/intel-thc-hid/intel-ipts/ipts.h   | 119 +++++++++
 .../hid/intel-thc-hid/intel-ipts/pci-ipts.c   | 125 +++++++++
 5 files changed, 502 insertions(+)
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/ipts.c
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/ipts.h
 create mode 100644 drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c
drivers/hid/intel-thc-hid/Kconfig +14 -0
index 9d74e53b8..3df645f34 100644
@@ -40,4 +40,18 @@ config INTEL_QUICKI2C
 
 	  Say Y/M here if you want to support Intel QuickI2C. If unsure, say N.
 
+config INTEL_IPTS
+	tristate "Intel Touch Host Controller IPTS mode"
+	depends on INTEL_THC_HID
+	help
+	  Support for THC ports in IPTS mode. Instead of HIDSPI these ports
+	  drive the touch controller over plain SPI and carry its reports in a
+	  private framing. This driver brings such a port up, reads the
+	  controller's configuration block and exposes the reports as a HID
+	  device, so that a decoder in user space can turn them into input
+	  events.
+
+	  Say Y/M here if you have an Intel touch controller that runs in IPTS
+	  mode. If unsure, say N.
+
 endmenu
drivers/hid/intel-thc-hid/Makefile +4 -0
index f1182253b..049009592 100644
@@ -20,4 +20,8 @@ intel-quicki2c-objs += intel-quicki2c/pci-quicki2c.o
 intel-quicki2c-objs += intel-quicki2c/quicki2c-hid.o
 intel-quicki2c-objs += intel-quicki2c/quicki2c-protocol.o
 
+obj-$(CONFIG_INTEL_IPTS) += intel-ipts.o
+intel-ipts-objs += intel-ipts/pci-ipts.o
+intel-ipts-objs += intel-ipts/ipts.o
+
 ccflags-y += -I $(src)/intel-thc
drivers/hid/intel-thc-hid/intel-ipts/ipts.c new file +240 -0

240 lines not on this page · raw message

drivers/hid/intel-thc-hid/intel-ipts/ipts.h new file +119 -0

119 lines not on this page · raw message

drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c new file +125 -0

125 lines not on this page · raw message

author
#2 lore raw

PATCH v7 2/5 HID: intel-thc-hid: intel-ipts: receive reports

In reply to Emfox Zhou

Configure the receive and transmit DMA engines, take the port interrupt and decode the frames that arrive.

Interrupt remapping rejects the MSI requests these ports send: the requester ID in them is 01:05.0, neither the port's own function nor a valid DMA alias for it, so only the legacy interrupt pin works once remapping is on. MSI is the fallback for a platform that does not route that pin. The pin is shared with other functions on the PCH, and such a line only takes handlers that agree on oneshot, so the request asks for it only if a sharer uses it. The hardirq masks the port itself, so a foreign interrupt costs at most a few register reads in the thread, and is reported as not handled.

Transfer errors are recovered from a work item and not from the threaded
handler: thc_rxdma_reset() takes the bus lock, and the core's write path holds that lock while it waits for the very completion the handler delivers. The port is masked as soon as the reset is queued, and the threaded handler stops touching the status registers once the reset runs:
acknowledging a frame it is not going to read would lose the interrupt that announces it again. The thread masks the port on entry as well, because a sharer can queue a second run through IRQTF_RUNTHREAD with no hardirq of ours in between.

Every frame carries a code and a length in front of the payload. The receive side decodes that header and logs each frame.

Three details of the bring-up are worth spelling out:

- The interrupt configuration has to be applied before the DMA engines are started: it programs the device interrupt type field to the invalid value, and starting the receive engine then replaces that field with the type it expects. The other order would leave the invalid value in place.

- An event that arrives while the thread runs leaves nothing behind but its status bit, so the handler drains the status registers instead of trusting a single delivery: a write completion taken for granted this way makes the next transfer wait for a completion that never comes, and the port stays unusable until it is reset.

- Bulk transfers have no address phase, so the SPI opcode is zero. The opcodes the HIDSPI path uses make this controller ignore the frames altogether.

The frame size the controller reports is bounded by the receive ring, one page per PRD entry: a port that asks for a larger buffer is refused with an explicit error instead of failing in sgl_alloc().

The reset covers the host side only and leaves the PRD table descriptors the controller rewrites in place: taking a frame puts its entry back, but a frame that is not read keeps the length the controller wrote, and the next frame that does not fit ends in a PRD overrun. intel-quickspi and intel-quicki2c recover through the same call and have the same gap. Restoring those descriptors is the core's job, not this driver's, and a separate change to intel-thc does it.

---
 drivers/hid/intel-thc-hid/intel-ipts/ipts.c   | 317 ++++++++++++++++++
 drivers/hid/intel-thc-hid/intel-ipts/ipts.h   |  25 ++
 .../hid/intel-thc-hid/intel-ipts/pci-ipts.c   |  40 +++
 3 files changed, 382 insertions(+)
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +317 -0
index 2d14e5278..17f6f664e 100644
@@ -5,8 +5,13 @@
 
 #include <linux/delay.h>
 #include <linux/math.h>
+#include <linux/interrupt.h>
+#include <linux/minmax.h>
 #include <linux/regmap.h>
+#include <linux/sizes.h>
 #include <linux/string.h>
+#include <linux/unaligned.h>
+#include <linux/workqueue.h>
 
 #include "intel-thc-hw.h"
 #include "ipts.h"
@@ -17,9 +22,19 @@
 /* Slowest clock the core can program, used until the controller is read. */
 #define THC_IPTS_BOOT_SPI_HZ		THC_IPTS_SPI_MIN_HZ
 
+/* One page per PRD entry; a larger frame cannot be received. */
+#define THC_IPTS_RX_MAX			(PRD_ENTRIES_NUM * SZ_4K)
+
 /* Time the controller needs after reset before it answers on the bus. */
 #define THC_IPTS_BOOT_MS		100
 
+/*
+ * The core stops at the first error cause and reports the rest as a mask, so
+ * reading until it finds nothing can take a pass per cause plus one that
+ * confirms the status is drained.
+ */
+#define THC_IPTS_IRQ_PASSES		(THC_UNKNOWN_INT + 1)
+
 static int thc_ipts_read_cfg(struct thc_ipts *idev)
 {
 	int ret, try;
@@ -129,6 +144,281 @@ static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable)
 				 &touch);
 }
 
+static void thc_ipts_handle_frame(struct thc_ipts *idev, size_t len)
+{
+	size_t capacity = idev->max_rx - THC_IPTS_RX_HDR_SIZE;
+	u32 code, size;
+
+	if (len < THC_IPTS_RX_HDR_SIZE)
+		return;
+
+	code = get_unaligned_le32(idev->rx_frame);
+	/* The header may claim more than what actually arrived. */
+	size = min_t(u32, get_unaligned_le32(idev->rx_frame + 4),
+		     capacity);
+	size = min_t(u32, size, len - THC_IPTS_RX_HDR_SIZE);
+
+	dev_dbg(idev->dev, "frame code %u, %u bytes\n", code, size);
+}
+
+static void thc_ipts_dma_stop(struct thc_ipts *idev)
+{
+	if (!idev->dma_ready)
+		return;
+
+	WRITE_ONCE(idev->dma_ready, false);
+	thc_dma_unconfigure(idev->thc);
+	thc_dma_release(idev->thc);
+}
+
+static int thc_ipts_resize(struct thc_ipts *idev, u8 **buf, size_t *have,
+			   size_t want)
+{
+	u8 *p;
+
+	if (*have >= want)
+		return 0;
+
+	p = devm_krealloc(idev->dev, *buf, want, GFP_KERNEL);
+	if (!p)
+		return -ENOMEM;
+
+	*buf = p;
+	*have = want;
+
+	return 0;
+}
+
+static int thc_ipts_dma_start(struct thc_ipts *idev)
+{
+	int ret;
+
+	/*
+	 * The receive ring has one page per PRD entry and the core refuses a
+	 * frame that needs more: bound it here, or the port fails with a bare
+	 * allocation error from sgl_alloc().
+	 */
+	if (idev->max_rx > THC_IPTS_RX_MAX) {
+		dev_err(idev->dev, "receive buffer of %zu bytes is too large\n",
+			idev->max_rx);
+		return -ENODEV;
+	}
+
+	/*
+	 * A resume can report larger limits than the probe did, and the
+	 * engines would then write past the end. Follow them on every start;
+	 * the receive buffer is rounded up because the core rounds to a page.
+	 */
+	ret = thc_ipts_resize(idev, &idev->rx_frame, &idev->buf_rx,
+			      round_up(idev->max_rx, SZ_4K));
+	if (ret)
+		return ret;
+
+	ret = thc_dma_set_max_packet_sizes(idev->thc, 0, idev->max_rx,
+					   idev->max_tx, 0);
+	if (ret)
+		return ret;
+
+	ret = thc_dma_allocate(idev->thc);
+	if (ret)
+		return ret;
+
+	ret = thc_dma_configure(idev->thc);
+	if (ret) {
+		thc_dma_release(idev->thc);
+		return ret;
+	}
+
+	WRITE_ONCE(idev->dma_ready, true);
+
+	return 0;
+}
+
+irqreturn_t thc_ipts_hardirq(int irq, void *data)
+{
+	struct thc_ipts *idev = data;
+
+	/* Nothing of ours is pending: the cause belongs to a sharer. */
+	if (!READ_ONCE(idev->dma_ready))
+		return IRQ_NONE;
+
+	/* Level triggered and shared: mask first, or it stays asserted. */
+	thc_interrupt_enable(idev->thc, false);
+
+	/*
+	 * A reset or a teardown in flight still gets the thread: the status it
+	 * drains is where a pending transmit completion is delivered, and a
+	 * write waiting for that one holds the bus lock the reset needs.
+	 */
+	return IRQ_WAKE_THREAD;
+}
+
+static int thc_ipts_read_frames(struct thc_ipts *idev)
+{
+	for (;;) {
+		int finished = 0;
+		size_t len = 0;
+
+		if (thc_rxdma_read(idev->thc, THC_RXDMA2, idev->rx_frame,
+				   &len, &finished)) {
+			dev_warn_once(idev->dev,
+				      "cannot read a frame from the engine\n");
+			return -EIO;
+		}
+
+		if (!len)
+			break;
+
+		thc_ipts_handle_frame(idev, len);
+		if (finished)
+			break;
+	}
+
+	return 0;
+}
+
+/*
+ * Refuse new requests and queue the reset. The line stays open: a write that
+ * is already waiting for its completion needs this interrupt, and the work
+ * item takes the port once that write is done.
+ */
+static void thc_ipts_request_recover(struct thc_ipts *idev)
+{
+	if (READ_ONCE(idev->recover_pending))
+		return;
+
+	WRITE_ONCE(idev->recover_pending, true);
+	schedule_work(&idev->recover_work);
+}
+
+/*
+ * From a work item: the reset waits for the bus lock a pending write holds
+ * until the threaded handler delivers its completion.
+ */
+void thc_ipts_recover(struct work_struct *work)
+{
+	struct thc_ipts *idev = container_of(work, struct thc_ipts,
+					     recover_work);
+
+	/*
+	 * From here the status registers belong to the reset: the threaded
+	 * handler must not acknowledge a frame it is not going to read, or the
+	 * interrupt that would announce it again never comes. The flag alone
+	 * is only a snapshot to a run that is already inside, so the mask and
+	 * the wait below are what keeps that run out.
+	 */
+	WRITE_ONCE(idev->recovering, true);
+	thc_interrupt_enable(idev->thc, false);
+	synchronize_irq(idev->irq);
+
+	if (thc_rxdma_reset(idev->thc)) {
+		/* Nothing left: keep the port masked until it restarts. */
+		dev_err(idev->dev, "cannot reset the receive engine\n");
+		return;
+	}
+
+	/* The reset drops whatever the engines had queued. A run of the
+	 * handler that sees ->recovering clear must not be turned away by
+	 * ->recover_pending afterwards, so that one is cleared first.
+	 */
+	WRITE_ONCE(idev->recover_seq, READ_ONCE(idev->recover_seq) + 1);
+	WRITE_ONCE(idev->recover_pending, false);
+	WRITE_ONCE(idev->recovering, false);
+	if (!READ_ONCE(idev->stopping))
+		thc_interrupt_enable(idev->thc, true);
+}
+
+irqreturn_t thc_ipts_thread(int irq, void *data)
+{
+	struct thc_ipts *idev = data;
+	irqreturn_t ret = IRQ_NONE;
+	bool need_recover = false;
+	bool reported = false;
+	int pass;
+
+	/* Reports are handed to the HID core from here, and a driver callback
+	 * that sends a request would wait for a completion this very thread
+	 * delivers: thc_ipts_send() refuses those.
+	 */
+	WRITE_ONCE(idev->in_thread, true);
+
+	/* A sharer can queue a second run of this thread with no hardirq of
+	 * ours in between: mask again, the write is idempotent.
+	 */
+	thc_interrupt_enable(idev->thc, false);
+
+	/* The port stays masked, so a cause that arrives meanwhile leaves only
+	 * its status bit: read until the core reports none.
+	 */
+	for (pass = 0; pass < THC_IPTS_IRQ_PASSES; pass++) {
+		int mask;
+
+		/*
+		 * The reset owns the status registers while it runs: a frame
+		 * acknowledged here but not read is never announced again.
+		 */
+		if (READ_ONCE(idev->recovering)) {
+			/* Nothing acknowledged, but the line is still ours. */
+			ret = IRQ_HANDLED;
+			break;
+		}
+
+		mask = thc_interrupt_handler(idev->thc);
+
+		if (mask == BIT(THC_UNKNOWN_INT))
+			break;
+
+		ret = IRQ_HANDLED;
+		if (mask & (BIT(THC_FATAL_ERR_INT) | BIT(THC_TXN_ERR_INT))) {
+			/* An overrun raises this for every frame until the
+			 * reset takes the port: report the first one only.
+			 */
+			if (!reported) {
+				dev_err(idev->dev,
+					"transfer error, resetting the engine\n");
+				reported = true;
+			}
+			/* The teardown has its own reset to wait for. */
+			if (!READ_ONCE(idev->stopping))
+				need_recover = true;
+			/* The core stops at the first cause: a Tx completion
+			 * behind the error would time out under the bus lock.
+			 */
+			continue;
+		}
+
+		/* A reset is queued or running, or the port is going away: the
+		 * ring is not ours to read, only its status was.
+		 */
+		if (need_recover || READ_ONCE(idev->recover_pending) ||
+		    READ_ONCE(idev->recovering) ||
+		    READ_ONCE(idev->stopping))
+			continue;
+
+		if (mask & BIT(THC_RXDMA2_INT) && thc_ipts_read_frames(idev))
+			need_recover = true;
+	}
+
+	/* The work item resets the engine and unmasks again; a frame read
+	 * meanwhile would corrupt the ring.
+	 */
+	if (need_recover) {
+		thc_ipts_request_recover(idev);
+		return IRQ_HANDLED;
+	}
+
+	/* A reset unmasks when it is done. A teardown masks on its own, so the
+	 * line stays open here: a write already on the wire needs the
+	 * completion this handler delivers.
+	 */
+	if (!READ_ONCE(idev->recovering))
+		thc_interrupt_enable(idev->thc, true);
+
+	WRITE_ONCE(idev->in_thread, false);
+
+	return ret;
+}
+
 /**
  * thc_ipts_port_start - bring one port up
  * @idev: port to start
@@ -138,6 +428,9 @@ int thc_ipts_port_start(struct thc_ipts *idev)
 	u32 ctrl, hz, mode;
 	int ret;
 
+	WRITE_ONCE(idev->stopping, false);
+	WRITE_ONCE(idev->recovering, false);
+
 	ret = thc_ipts_quiesce(idev, true);
 	if (ret)
 		return ret;
@@ -220,6 +513,15 @@ int thc_ipts_port_start(struct thc_ipts *idev)
 		return ret;
 	idev->running = true;
 
+	/* Sets the type field to invalid; RXDMA2 start writes the real one. */
+	thc_interrupt_config(idev->thc);
+
+	ret = thc_ipts_dma_start(idev);
+	if (ret)
+		return ret;
+
+	thc_interrupt_enable(idev->thc, true);
+
 	return 0;
 }
 
@@ -229,6 +531,19 @@ int thc_ipts_port_start(struct thc_ipts *idev)
  */
 void thc_ipts_port_stop(struct thc_ipts *idev)
 {
+	/*
+	 * Mask the line, then wait for a handler that may be holding a
+	 * frame for the HID device which is about to go away.
+	 */
+	WRITE_ONCE(idev->stopping, true);
+	thc_interrupt_enable(idev->thc, false);
+	synchronize_irq(idev->irq);
+	cancel_work_sync(&idev->recover_work);
+
+	/* A handler that read ->stopping early may have unmasked. */
+	thc_interrupt_enable(idev->thc, false);
+
+	/* Stop the controller before the buffers it writes into go away. */
 	if (idev->running)
 		thc_ipts_touch_set(idev, false);
 
@@ -237,4 +552,6 @@ void thc_ipts_port_stop(struct thc_ipts *idev)
 	regmap_write_bits(idev->thc->thc_regmap, THC_M_PRT_CONTROL_OFFSET,
 			  THC_M_PRT_CONTROL_DEVRST, 0);
 	thc_ipts_quiesce(idev, true);
+
+	thc_ipts_dma_stop(idev);
 }
drivers/hid/intel-thc-hid/intel-ipts/ipts.h +25 -0
index b4ce633fc..e05be4b1c 100644
@@ -8,6 +8,7 @@
 #include <linux/device.h>
 #include <linux/interrupt.h>
 #include <linux/types.h>
+#include <linux/wait.h>
 
 #include "intel-thc-dev.h"
 
@@ -95,24 +96,48 @@ static_assert(offsetof(struct thc_ipts_cfg, vendor) == 0x1c);
  * struct thc_ipts - state of one THC port in IPTS mode
  * @dev: device used for resources and logging
  * @thc: shared THC core context
+ * @irq: interrupt line of the port
  * @cfg: configuration block last read from the controller
  * @vendor: vendor ID the controller reports for its HID device
  * @product: product ID the controller reports for its HID device
  * @max_rx: largest frame the controller may send, in bytes
  * @max_tx: largest frame the driver may send, in bytes
+ * @buf_rx: allocated size of @rx_frame
+ * @rx_frame: buffer for one received frame, including its header
+ * @recover_work: resets the receive engine after a transfer error
  * @running: the controller answered and is out of reset
+ * @dma_ready: DMA engines are configured and may be used
+ * @recover_pending: a reset is wanted, refuse new requests
+ * @recovering: a reset is queued or running, ignore the interrupt
+ * @recover_seq: number of resets that ran, to tell a dropped answer apart
+ * @stopping: the port is being torn down, ignore the interrupt
+ * @in_thread: the threaded handler is running, so no write can complete
  */
 struct thc_ipts {
 	struct device		*dev;
 	struct thc_device	*thc;
+	int			irq;
 	struct thc_ipts_cfg	cfg;
 	u16			vendor;
 	u16			product;
 	size_t			max_rx;
 	size_t			max_tx;
+	size_t			buf_rx;
+	u8			*rx_frame;
+	struct work_struct	recover_work;
 	bool			running;
+	bool			dma_ready;
+	bool			recover_pending;
+	bool			recovering;
+	unsigned int		recover_seq;
+	bool			stopping;
+	bool			in_thread;
 };
 
+irqreturn_t thc_ipts_hardirq(int irq, void *data);
+irqreturn_t thc_ipts_thread(int irq, void *data);
+void thc_ipts_recover(struct work_struct *work);
+
 int thc_ipts_port_start(struct thc_ipts *idev);
 void thc_ipts_port_stop(struct thc_ipts *idev);
 
drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c +40 -0
index 48046cd12..1670d116a 100644
@@ -46,6 +46,7 @@ static int thc_ipts_probe(struct pci_dev *pci, const struct pci_device_id *id)
 
 	idev->dev = &pci->dev;
 	pci_set_drvdata(pci, idev);
+	INIT_WORK(&idev->recover_work, thc_ipts_recover);
 
 	ret = pcim_enable_device(pci);
 	if (ret) {
@@ -77,9 +78,43 @@ static int thc_ipts_probe(struct pci_dev *pci, const struct pci_device_id *id)
 	if (IS_ERR(idev->thc))
 		return PTR_ERR(idev->thc);
 
+	/*
+	 * Firmware may leave the global enable set, and the line is shared and
+	 * level triggered: mask it until a handler is in place.
+	 */
+	thc_interrupt_enable(idev->thc, false);
+
+	/*
+	 * Interrupt remapping rejects the MSI these ports ask for, so take the
+	 * shared legacy pin; MSI is for a platform that routes no pin.
+	 */
+	ret = pci_alloc_irq_vectors(pci, 1, 1, PCI_IRQ_INTX);
+	if (ret < 0) {
+		dev_warn(idev->dev, "no interrupt pin, falling back to MSI\n");
+		ret = pci_alloc_irq_vectors(pci, 1, 1,
+					    PCI_IRQ_MSI | PCI_IRQ_MSIX);
+	}
+	if (ret < 0) {
+		dev_err(idev->dev, "no interrupt vector, error %d\n", ret);
+		return ret;
+	}
+
+	idev->irq = pci_irq_vector(pci, 0);
+
+	/* Oneshot only if a sharer has it: the hardirq masks the port. */
+	ret = devm_request_threaded_irq(idev->dev, idev->irq, thc_ipts_hardirq,
+					thc_ipts_thread,
+					IRQF_SHARED | IRQF_COND_ONESHOT,
+					KBUILD_MODNAME, idev);
+	if (ret) {
+		dev_err(idev->dev, "cannot get the interrupt, error %d\n", ret);
+		return ret;
+	}
+
 	ret = thc_ipts_port_start(idev);
 	if (ret) {
 		thc_ipts_port_stop(idev);
+		devm_free_irq(idev->dev, idev->irq, idev);
 		return ret;
 	}
 
@@ -97,6 +132,11 @@ static void thc_ipts_remove(struct pci_dev *pci)
 	struct thc_ipts *idev = pci_get_drvdata(pci);
 
 	thc_ipts_port_stop(idev);
+
+	/* The handler has to go before the vector it is bound to is freed;
+	 * the vectors themselves belong to pcim_enable_device().
+	 */
+	devm_free_irq(idev->dev, idev->irq, idev);
 	pci_clear_master(pci);
 }
 
#3 lore raw

Re: [PATCH v7 2/5] HID: intel-thc-hid: intel-ipts: receive reports

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] HID: intel-thc-hid: intel-ipts: IRQ unmasking races in stop and recover - [Medium] HID…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] HID: intel-thc-hid: intel-ipts: IRQ unmasking races in stop and recover
- [Medium] HID: intel-thc-hid: intel-ipts: invalid wait context in thc_ipts_hardirq()
--

commit 993aaa08c813c3f151cc4b084284f9a37d80893f
Author: Emfox Zhou <[email protected]>

HID: intel-thc-hid: intel-ipts: receive reports

This commit configures the THC DMA engines for IPTS, requests the port interrupt, and adds frame reception and error recovery handling.

Quoted 4 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +0 -0
index 2d14e5278f986..17f6f664e95b5 100644

[ ... ]

Quoted 3 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +0 -0
@@ -129,6 +144,281 @@ static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable)
 				 &touch);
 }

[ ... ]

Quoted 9 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +9 -0
+static void thc_ipts_dma_stop(struct thc_ipts *idev)
+{
+	if (!idev->dma_ready)
+		return;
+
+	WRITE_ONCE(idev->dma_ready, false);
+	thc_dma_unconfigure(idev->thc);
+	thc_dma_release(idev->thc);
+}

[ ... ]

Quoted 8 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +8 -0
+irqreturn_t thc_ipts_hardirq(int irq, void *data)
+{
+	struct thc_ipts *idev = data;
+
+	/* Nothing of ours is pending: the cause belongs to a sharer. */
+	if (!READ_ONCE(idev->dma_ready))
+		return IRQ_NONE;
+

drivers/hid/intel-thc-hid/intel-ipts/ipts.c static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable) · line 254

Quoted 10 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +10 -0
+	/* Level triggered and shared: mask first, or it stays asserted. */
+	thc_interrupt_enable(idev->thc, false);
+
+	/*
+	 * A reset or a teardown in flight still gets the thread: the status it
+	 * drains is where a pending transmit completion is delivered, and a
+	 * write waiting for that one holds the bus lock the reset needs.
+	 */
+	return IRQ_WAKE_THREAD;
+}

[Severity: Medium]
Does calling thc_interrupt_enable() from thc_ipts_hardirq() trigger a lockdep invalid wait context warning when the shared legacy INTx line runs in oneshot mode?

thc_ipts_probe() allocates a legacy PCI_IRQ_INTX vector and requests the interrupt with IRQF_SHARED | IRQF_COND_ONESHOT. When a sharer on the line uses IRQF_ONESHOT, __setup_irq() sets IRQF_ONESHOT on this action as well, and __handle_irq_event_percpu() runs thc_ipts_hardirq() in LD_WAIT_SPIN context without calling lockdep_hardirq_threaded().

thc_interrupt_enable() then calls regmap_write_bits() on idev->thc->thc_regmap, which is configured with .fast_io = true and no .use_raw_spinlock:

drivers/hid/intel-thc-hid/intel-thc/intel-thc-dev.c:

static const struct regmap_config thc_regmap_cfg = {
	...
	.fast_io = true,
};

Acquiring that non-raw spinlock_t from hardirq context violates CONFIG_PROVE_RAW_LOCK_NESTING.

[ ... ]

Quoted 21 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +21 -0
+void thc_ipts_recover(struct work_struct *work)
+{
+	struct thc_ipts *idev = container_of(work, struct thc_ipts,
+					     recover_work);
+
+	/*
+	 * From here the status registers belong to the reset: the threaded
+	 * handler must not acknowledge a frame it is not going to read, or the
+	 * interrupt that would announce it again never comes. The flag alone
+	 * is only a snapshot to a run that is already inside, so the mask and
+	 * the wait below are what keeps that run out.
+	 */
+	WRITE_ONCE(idev->recovering, true);
+	thc_interrupt_enable(idev->thc, false);
+	synchronize_irq(idev->irq);
+
+	if (thc_rxdma_reset(idev->thc)) {
+		/* Nothing left: keep the port masked until it restarts. */
+		dev_err(idev->dev, "cannot reset the receive engine\n");
+		return;
+	}

[ ... ]

Quoted 2 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +2 -0
+irqreturn_t thc_ipts_thread(int irq, void *data)
+{

[ ... ]

Quoted 11 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +11 -0
+	/* A reset unmasks when it is done. A teardown masks on its own, so the
+	 * line stays open here: a write already on the wire needs the
+	 * completion this handler delivers.
+	 */
+	if (!READ_ONCE(idev->recovering))
+		thc_interrupt_enable(idev->thc, true);
+
+	WRITE_ONCE(idev->in_thread, false);
+
+	return ret;
+}

[ ... ]

Quoted 21 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +13 -0
@@ -229,6 +531,19 @@ int thc_ipts_port_start(struct thc_ipts *idev)
  */
 void thc_ipts_port_stop(struct thc_ipts *idev)
 {
+	/*
+	 * Mask the line, then wait for a handler that may be holding a
+	 * frame for the HID device which is about to go away.
+	 */
+	WRITE_ONCE(idev->stopping, true);
+	thc_interrupt_enable(idev->thc, false);
+	synchronize_irq(idev->irq);
+	cancel_work_sync(&idev->recover_work);
+
+	/* A handler that read ->stopping early may have unmasked. */
+	thc_interrupt_enable(idev->thc, false);
+
+	/* Stop the controller before the buffers it writes into go away. */
 	if (idev->running)
 		thc_ipts_touch_set(idev, false);
 

drivers/hid/intel-thc-hid/intel-ipts/ipts.c void thc_ipts_port_stop(struct thc_ipts *idev) · line 557

Quoted 6 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +2 -0
@@ -237,4 +552,6 @@ void thc_ipts_port_stop(struct thc_ipts *idev)
 	regmap_write_bits(idev->thc->thc_regmap, THC_M_PRT_CONTROL_OFFSET,
 			  THC_M_PRT_CONTROL_DEVRST, 0);
 	thc_ipts_quiesce(idev, true);
+
+	thc_ipts_dma_stop(idev);
 }

[Severity: Medium]
Can a shared interrupt or an in-flight thc_ipts_thread() re-enable the port interrupt and race with thc_ipts_port_stop() and thc_ipts_recover()?

Because the IRQ is registered with IRQF_SHARED, any interrupt from another device on the line causes thc_ipts_hardirq() to return IRQ_WAKE_THREAD as long as idev->dma_ready is true. In thc_ipts_port_stop(), idev->dma_ready remains true until thc_ipts_dma_stop(), and thc_ipts_thread() does not check idev->stopping before re-enabling interrupts:

CPU0 CPU1
thc_ipts_port_stop()
WRITE_ONCE(idev->stopping, true)
synchronize_irq(idev->irq)
thc_interrupt_enable(..., false)

                                      <shared IRQ>
                                      thc_ipts_hardirq()
                                        if (!READ_ONCE(idev->dma_ready))
                                        return IRQ_WAKE_THREAD
  thc_ipts_touch_set(idev, false)
  ...
  thc_ipts_dma_stop()
    WRITE_ONCE(idev->dma_ready, false)
    thc_dma_unconfigure(idev->thc)
    thc_dma_release(idev->thc)
                                      thc_ipts_thread()
                                        thc_interrupt_handler(idev->thc)
                                        if (!READ_ONCE(idev->recovering))
                                          thc_interrupt_enable(..., true)
                                            <-- runs during DMA teardown
                                                and leaves IRQ unmasked

Even with commit "HID: intel-thc-hid: intel-ipts: add the HID device" adding synchronize_irq() and thc_interrupt_enable(idev->thc, false) after thc_ipts_dma_stop(), thc_dma_unconfigure() and thc_dma_release() still run before synchronize_irq() waits for a woken thc_ipts_thread(), and the port interrupt is briefly unmasked during shutdown.

A similar race exists in thc_ipts_recover(): if thc_ipts_thread() checks !READ_ONCE(idev->recovering) just before thc_ipts_recover() sets idev->recovering and masks the port, the thread can call thc_interrupt_enable(idev->thc, true) before synchronize_irq() returns. Because thc_ipts_recover() does not mask again after synchronize_irq(), thc_rxdma_reset() runs with the port interrupt unmasked (and leaves it unmasked if thc_rxdma_reset() fails).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#4 lore raw

PATCH v7 3/5 HID: intel-thc-hid: intel-ipts: add the HID device

In reply to Emfox Zhou

Register a HID device and let it own the handshake: the report descriptor is not read once at probe and kept, it is asked for over the transport whenever the HID core parses the device, and feature reports are fetched the same way. Both need a lock that keeps one frame on the wire at a time, a wait queue the answer is delivered on, and buffers for the answers. The descriptor is asked for up to six times, 300 ms each; a request that finds the port masked by a reset waits for that reset instead of spending a try.

A feature answer arrives as a frame of its own and carries only the report ID back, which does not tell it from the answer to the next request for the same report: nothing on the wire says which request a frame answers. So the request is sent once, and a timeout shuts the channel until the port is started again, the only point where controller and device are known to agree. A reset is counted: an answer it dropped returns -EIO and leaves the channel open, because that frame was never left out there. Resetting the engine instead would drop a late answer, and the reset does not restore the PRD table, so a frame left unread would make the next one overrun.

The state is updated under a lock, so accepting an answer and consuming it are one step; it is a mutex, because the answer is copied in the threaded handler and can be as large as a receive frame. The waits happen outside
it: the thread that delivers an answer calls into the HID core on its way and would otherwise wait for a lock the waiter holds. A second feature request while one is outstanding is refused rather than queued, for that reason and because its answer could not be told from the first one's.

Requests are refused while a recovery is in flight: the port is masked, so a write would wait out its one second timeout holding the bus lock the reset needs. Teardown refuses new requests, then waits for one already inside thc_dma_write(), which needs the interrupt the mask takes away; the mask follows that wait, and the line is waited on once more after the buffers are gone. The transmit lock is not held across synchronize_irq():
the threaded handler can issue a request of its own from a HID callback.

Input reports go straight to the input layer and the raw stream is available through hidraw, where decoding belongs: the reports carry a heatmap, and turning it into contacts needs floating point arithmetic the kernel cannot do. The controller starts streaming once user space asks for it, through a set feature request on report 5.

---
 drivers/hid/intel-thc-hid/intel-ipts/ipts.c   | 458 +++++++++++++++++-
 drivers/hid/intel-thc-hid/intel-ipts/ipts.h   |  56 +++
 .../hid/intel-thc-hid/intel-ipts/pci-ipts.c   |   3 +
 3 files changed, 497 insertions(+), 20 deletions(-)
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +438 -20
index 17f6f664e..347a70571 100644
@@ -3,8 +3,10 @@
  * Transport for THC ports in IPTS mode: plain SPI with a private framing.
  */
 
+#include <linux/cleanup.h>
 #include <linux/delay.h>
 #include <linux/math.h>
+#include <linux/hid.h>
 #include <linux/interrupt.h>
 #include <linux/minmax.h>
 #include <linux/regmap.h>
@@ -144,8 +146,86 @@ static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable)
 				 &touch);
 }
 
+/*
+ * Frames are built in @idev->tx_frame, so the lock is taken here rather than
+ * by the callers: none of them may hold it across a wait.
+ */
+static int thc_ipts_send(struct thc_ipts *idev, u32 code, const void *data,
+			 size_t len)
+{
+	size_t padded = round_up(len, 4);
+	u8 *frame = idev->tx_frame;
+
+	/* The completion of a write is delivered by the threaded handler, so
+	 * one issued from there would wait out its timeout: refuse it instead,
+	 * and let the caller retry from its own context.
+	 */
+	if (READ_ONCE(idev->in_thread))
+		return -EBUSY;
+
+	guard(mutex)(&idev->tx_lock);
+
+	if (READ_ONCE(idev->stopping))
+		return -ESHUTDOWN;
+	/* A reset is queued or running: the write would only time out. */
+	if (READ_ONCE(idev->recover_pending) || READ_ONCE(idev->recovering))
+		return -EAGAIN;
+	/* No engine to write into: waiting for a reset would not help. */
+	if (!READ_ONCE(idev->dma_ready))
+		return -ENODEV;
+	if (THC_IPTS_TX_HDR_SIZE + padded > idev->max_tx)
+		return -EMSGSIZE;
+
+	put_unaligned_le32(code, frame);
+	put_unaligned_le32((u32)len, frame + 4);
+	memset(frame + THC_IPTS_TX_HDR_SIZE, 0, padded);
+	if (len && data)
+		memcpy(frame + THC_IPTS_TX_HDR_SIZE, data, len);
+
+	return thc_dma_write(idev->thc, frame, THC_IPTS_TX_HDR_SIZE + padded);
+}
+
+static void thc_ipts_descriptor(struct thc_ipts *idev, const u8 *data,
+				size_t len)
+{
+	/* One answer per request: a late reply must not overwrite it. */
+	if (len <= THC_IPTS_DESC_PREAMBLE || READ_ONCE(idev->have_desc))
+		return;
+
+	len = min(len - THC_IPTS_DESC_PREAMBLE, idev->max_rx);
+	memcpy(idev->desc, data + THC_IPTS_DESC_PREAMBLE, len);
+	idev->desc_len = len;
+	/* The bytes and the length have to land before the flag is seen. */
+	smp_store_release(&idev->have_desc, true);
+	wake_up(&idev->wq);
+}
+
+static void thc_ipts_feature(struct thc_ipts *idev, const u8 *data,
+			     size_t len)
+{
+	if (!len)
+		return;
+
+	/* Only a frame that arrives while a request is waiting is taken. */
+	mutex_lock(&idev->feature_lock);
+	if (!idev->feature_pending ||
+	    (idev->feature_id && data[0] != idev->feature_id)) {
+		mutex_unlock(&idev->feature_lock);
+		return;
+	}
+
+	len = min(len, idev->max_rx);
+	memcpy(idev->feature, data, len);
+	idev->feature_len = len;
+	WRITE_ONCE(idev->feature_done, true);
+	mutex_unlock(&idev->feature_lock);
+
+	wake_up(&idev->wq);
+}
+
 static void thc_ipts_handle_frame(struct thc_ipts *idev, size_t len)
 {
+	const u8 *payload = idev->rx_frame + THC_IPTS_RX_HDR_SIZE;
 	size_t capacity = idev->max_rx - THC_IPTS_RX_HDR_SIZE;
 	u32 code, size;
 
@@ -154,11 +234,31 @@ static void thc_ipts_handle_frame(struct thc_ipts *idev, size_t len)
 
 	code = get_unaligned_le32(idev->rx_frame);
 	/* The header may claim more than what actually arrived. */
-	size = min_t(u32, get_unaligned_le32(idev->rx_frame + 4),
-		     capacity);
+	size = min_t(u32, get_unaligned_le32(idev->rx_frame + 4), capacity);
 	size = min_t(u32, size, len - THC_IPTS_RX_HDR_SIZE);
 
-	dev_dbg(idev->dev, "frame code %u, %u bytes\n", code, size);
+	switch (code) {
+	case THC_IPTS_RX_INPUT: {
+		struct hid_device *hdev = READ_ONCE(idev->hid);
+
+		if (hdev)
+			hid_safe_input_report(hdev, HID_INPUT_REPORT,
+					      (u8 *)payload, capacity, size, 1);
+		break;
+	}
+	case THC_IPTS_RX_DESC:
+		thc_ipts_descriptor(idev, payload, size);
+		break;
+	case THC_IPTS_RX_FEATURE:
+		thc_ipts_feature(idev, payload, size);
+		break;
+	case THC_IPTS_RX_RESET:
+		dev_warn(idev->dev, "controller asked for a reset\n");
+		break;
+	default:
+		dev_dbg(idev->dev, "frame code %u, %u bytes\n", code, size);
+		break;
+	}
 }
 
 static void thc_ipts_dma_stop(struct thc_ipts *idev)
@@ -211,9 +311,19 @@ static int thc_ipts_dma_start(struct thc_ipts *idev)
 	 */
 	ret = thc_ipts_resize(idev, &idev->rx_frame, &idev->buf_rx,
 			      round_up(idev->max_rx, SZ_4K));
+	if (!ret)
+		ret = thc_ipts_resize(idev, &idev->tx_frame, &idev->buf_tx,
+				      round_up(idev->max_tx, 4));
+	if (!ret)
+		ret = thc_ipts_resize(idev, &idev->desc, &idev->buf_desc,
+				      idev->max_rx);
+	if (!ret)
+		ret = thc_ipts_resize(idev, &idev->feature, &idev->buf_feat,
+				      idev->max_rx);
 	if (ret)
 		return ret;
 
+	/* Only RXDMA2 (in) and TXDMA (out) are used; the other two stay 0. */
 	ret = thc_dma_set_max_packet_sizes(idev->thc, 0, idev->max_rx,
 					   idev->max_tx, 0);
 	if (ret)
@@ -289,6 +399,8 @@ static void thc_ipts_request_recover(struct thc_ipts *idev)
 
 	WRITE_ONCE(idev->recover_pending, true);
 	schedule_work(&idev->recover_work);
+	/* A request waiting for the port looks at that flag. */
+	wake_up(&idev->wq);
 }
 
 /*
@@ -300,6 +412,14 @@ void thc_ipts_recover(struct work_struct *work)
 	struct thc_ipts *idev = container_of(work, struct thc_ipts,
 					     recover_work);
 
+	/*
+	 * A write that is already on the wire holds this lock and needs the
+	 * interrupt that the mask below takes away: let it finish first, or it
+	 * times out over the bus lock the reset is waiting for.
+	 */
+	mutex_lock(&idev->tx_lock);
+	mutex_unlock(&idev->tx_lock);
+
 	/*
 	 * From here the status registers belong to the reset: the threaded
 	 * handler must not acknowledge a frame it is not going to read, or the
@@ -314,6 +434,8 @@ void thc_ipts_recover(struct work_struct *work)
 	if (thc_rxdma_reset(idev->thc)) {
 		/* Nothing left: keep the port masked until it restarts. */
 		dev_err(idev->dev, "cannot reset the receive engine\n");
+		/* It stays masked, so the waiters learn it from the flags. */
+		wake_up(&idev->wq);
 		return;
 	}
 
@@ -324,6 +446,10 @@ void thc_ipts_recover(struct work_struct *work)
 	WRITE_ONCE(idev->recover_seq, READ_ONCE(idev->recover_seq) + 1);
 	WRITE_ONCE(idev->recover_pending, false);
 	WRITE_ONCE(idev->recovering, false);
+
+	/* A request waiting out the reset is looking at that flag. */
+	wake_up(&idev->wq);
+
 	if (!READ_ONCE(idev->stopping))
 		thc_interrupt_enable(idev->thc, true);
 }
@@ -370,10 +496,10 @@ irqreturn_t thc_ipts_thread(int irq, void *data)
 
 		ret = IRQ_HANDLED;
 		if (mask & (BIT(THC_FATAL_ERR_INT) | BIT(THC_TXN_ERR_INT))) {
-			/* An overrun raises this for every frame until the
-			 * reset takes the port: report the first one only.
+			/* An overrun raises this until the reset takes the
+			 * port: report the first one only.
 			 */
-			if (!reported) {
+			if (!reported && !READ_ONCE(idev->recover_pending)) {
 				dev_err(idev->dev,
 					"transfer error, resetting the engine\n");
 				reported = true;
@@ -399,17 +525,19 @@ irqreturn_t thc_ipts_thread(int irq, void *data)
 			need_recover = true;
 	}
 
-	/* The work item resets the engine and unmasks again; a frame read
-	 * meanwhile would corrupt the ring.
+	/*
+	 * The work item resets the engine in its own time; a frame read
+	 * meanwhile would corrupt the ring, so only queue the reset.
 	 */
-	if (need_recover) {
+	if (need_recover)
 		thc_ipts_request_recover(idev);
-		return IRQ_HANDLED;
-	}
 
-	/* A reset unmasks when it is done. A teardown masks on its own, so the
-	 * line stays open here: a write already on the wire needs the
-	 * completion this handler delivers.
+	/*
+	 * A reset unmasks when it is done, and a teardown masks on its own.
+	 * Leaving the line open here is what a write already on the wire
+	 * needs: this handler is where its completion is delivered, and
+	 * masking it away would make that write time out over the bus lock
+	 * the reset is waiting for.
 	 */
 	if (!READ_ONCE(idev->recovering))
 		thc_interrupt_enable(idev->thc, true);
@@ -419,6 +547,274 @@ irqreturn_t thc_ipts_thread(int irq, void *data)
 	return ret;
 }
 
+/* No reset is queued or running, and the port is not going away. */
+static bool thc_ipts_idle(const struct thc_ipts *idev)
+{
+	return !READ_ONCE(idev->recover_pending) &&
+	       !READ_ONCE(idev->recovering) &&
+	       !READ_ONCE(idev->stopping);
+}
+
+static int thc_ipts_hid_parse(struct hid_device *hdev)
+{
+	struct thc_ipts *idev = hdev->driver_data;
+	unsigned long timeout = msecs_to_jiffies(THC_IPTS_REQ_TIMEOUT_MS);
+	u64 zero = 0;
+	unsigned int retries = 0;
+	int ret;
+	int try = 0;
+
+	/* A descriptor from a previous start is not this one's. */
+	WRITE_ONCE(idev->have_desc, false);
+
+	while (try < THC_IPTS_REQ_TRIES) {
+		/* An answer that landed after a wait expired is taken here. */
+		if (smp_load_acquire(&idev->have_desc))
+			break;
+
+		/* The controller ignores the eight byte argument. */
+		ret = thc_ipts_send(idev, THC_IPTS_TX_GET_DESC, &zero,
+				    sizeof(zero));
+		/*
+		 * -EAGAIN is our own reset refusing the request. -ETIMEDOUT is
+		 * a write that was already on the wire when one started: its
+		 * completion went away with the mask. Both are worth another
+		 * try, a descriptor request carries nothing a late answer could
+		 * spoil.
+		 */
+		if (ret == -EAGAIN || ret == -ETIMEDOUT) {
+			if (++retries > THC_IPTS_REQ_TRIES ||
+			    !wait_event_timeout(idev->wq,
+						thc_ipts_idle(idev), timeout))
+				break;
+			continue;
+		}
+		if (ret)
+			return ret;
+
+		try++;
+		wait_event_timeout(idev->wq, READ_ONCE(idev->have_desc),
+				   timeout);
+	}
+
+	/* Pairs with the release in thc_ipts_descriptor(). */
+	if (smp_load_acquire(&idev->have_desc) && idev->desc_len > 0) {
+		/* The receive buffer holds more than a descriptor may be. */
+		if (idev->desc_len > HID_MAX_DESCRIPTOR_SIZE) {
+			dev_err(idev->dev,
+				"report descriptor of %zu bytes is too large\n",
+				idev->desc_len);
+			return -EINVAL;
+		}
+
+		return hid_parse_report(hdev, idev->desc, idev->desc_len);
+	}
+
+	dev_err(idev->dev, "controller did not return a report descriptor\n");
+
+	return -ETIMEDOUT;
+}
+
+/* A feature report comes back as a frame of its own: the request waits. */
+static int thc_ipts_get_feature(struct thc_ipts *idev, unsigned char reportnum,
+				u8 *buf, size_t len)
+{
+	unsigned long timeout = msecs_to_jiffies(THC_IPTS_REQ_TIMEOUT_MS);
+	unsigned int seq;
+	int ret;
+
+	/*
+	 * One request at a time, and the wait below happens without a lock: a
+	 * request issued from a HID callback in the handler thread would be
+	 * waiting for an answer only that very thread can deliver. The gate is
+	 * released by whoever takes the answer, not by the frame that brings
+	 * it, or a second request could be answered into this one's buffer.
+	 */
+	mutex_lock(&idev->feature_lock);
+
+	/* The frame carries only the report ID, so a late answer cannot be
+	 * told from the next one's: after a timeout the channel stays shut.
+	 */
+	if (idev->feature_off) {
+		mutex_unlock(&idev->feature_lock);
+		return -EIO;
+	}
+	if (idev->feature_pending) {
+		mutex_unlock(&idev->feature_lock);
+		return -EBUSY;
+	}
+
+	WRITE_ONCE(idev->feature_done, false);
+	idev->feature_id = reportnum;
+	idev->feature_pending = true;
+	mutex_unlock(&idev->feature_lock);
+
+	seq = READ_ONCE(idev->recover_seq);
+
+	/* A refusal happens before anything is written, so the channel stays
+	 * open for it; a timeout is a different matter, see below.
+	 */
+	ret = thc_ipts_send(idev, THC_IPTS_TX_GET_FEATURE, &reportnum, 1);
+	if (ret) {
+		mutex_lock(&idev->feature_lock);
+		idev->feature_pending = false;
+
+		/* The start bit was written before the wait, so the frame may
+		 * well be on the wire: its answer cannot be told from the next
+		 * request's one.
+		 */
+		if (ret == -ETIMEDOUT)
+			WRITE_ONCE(idev->feature_off, true);
+		mutex_unlock(&idev->feature_lock);
+
+		if (ret == -ETIMEDOUT)
+			dev_err(idev->dev, "feature report %u not acknowledged\n",
+				reportnum);
+
+		return ret;
+	}
+
+	wait_event_timeout(idev->wq, READ_ONCE(idev->feature_done) ||
+			   READ_ONCE(idev->recover_pending) ||
+			   READ_ONCE(idev->recovering) ||
+			   READ_ONCE(idev->stopping), timeout);
+
+	mutex_lock(&idev->feature_lock);
+	/* An answer that landed while the wait was expiring counts too. */
+	if (!idev->feature_done) {
+		/* A reset discards what the engines had queued, so an answer
+		 * that was on its way is gone and cannot be waited for.
+		 */
+		if (READ_ONCE(idev->recover_seq) != seq ||
+		    READ_ONCE(idev->recover_pending) ||
+		    READ_ONCE(idev->recovering) ||
+		    READ_ONCE(idev->stopping))
+			ret = -EIO;
+		else
+			ret = -ETIMEDOUT;
+
+		idev->feature_pending = false;
+		/* Only a timeout leaves a frame out there: after a reset the
+		 * answer was dropped and the channel is still in step.
+		 */
+		if (ret == -ETIMEDOUT)
+			WRITE_ONCE(idev->feature_off, true);
+		mutex_unlock(&idev->feature_lock);
+
+		if (ret == -ETIMEDOUT)
+			dev_err(idev->dev, "no feature report %u\n", reportnum);
+
+		return ret;
+	}
+
+	/* The payload is the report as user space writes it: ID first. */
+	len = min(len, idev->feature_len);
+	if (len)
+		memcpy(buf, idev->feature, len);
+	idev->feature_pending = false;
+	mutex_unlock(&idev->feature_lock);
+
+	return len ?: -EPROTO;
+}
+
+static int thc_ipts_hid_raw_request(struct hid_device *hdev,
+				    unsigned char reportnum, __u8 *buf,
+				    size_t len, unsigned char rtype,
+				    int reqtype)
+{
+	struct thc_ipts *idev = hdev->driver_data;
+	u32 code;
+	int ret;
+
+	if (!buf || !len)
+		return -EINVAL;
+
+	if (reqtype == HID_REQ_GET_REPORT && rtype == HID_FEATURE_REPORT)
+		return thc_ipts_get_feature(idev, reportnum, buf, len);
+
+	if (reqtype != HID_REQ_SET_REPORT ||
+	    (rtype != HID_OUTPUT_REPORT && rtype != HID_FEATURE_REPORT))
+		return -EOPNOTSUPP;
+
+	code = rtype == HID_OUTPUT_REPORT ? THC_IPTS_TX_OUTPUT :
+					    THC_IPTS_TX_SET_FEATURE;
+
+	ret = thc_ipts_send(idev, code, buf, len);
+	if (ret)
+		return ret;
+
+	/* raw_request returns the byte count, which hidraw forwards. */
+	return (int)len;
+}
+
+/* The HID core calls these unconditionally; nothing to do in this mode. */
+static int thc_ipts_hid_start(struct hid_device *hdev)
+{
+	return 0;
+}
+
+static void thc_ipts_hid_stop(struct hid_device *hdev)
+{
+}
+
+static int thc_ipts_hid_open(struct hid_device *hdev)
+{
+	return 0;
+}
+
+static void thc_ipts_hid_close(struct hid_device *hdev)
+{
+}
+
+static const struct hid_ll_driver thc_ipts_ll_driver = {
+	.start		= thc_ipts_hid_start,
+	.stop		= thc_ipts_hid_stop,
+	.open		= thc_ipts_hid_open,
+	.close		= thc_ipts_hid_close,
+	.parse		= thc_ipts_hid_parse,
+	.raw_request	= thc_ipts_hid_raw_request,
+};
+
+static void thc_ipts_hid_remove(struct thc_ipts *idev)
+{
+	if (!READ_ONCE(idev->hid))
+		return;
+
+	hid_destroy_device(idev->hid);
+	WRITE_ONCE(idev->hid, NULL);
+}
+
+static int thc_ipts_hid_add(struct thc_ipts *idev)
+{
+	struct hid_device *hdev;
+	int ret;
+
+	hdev = hid_allocate_device();
+	if (IS_ERR(hdev))
+		return PTR_ERR(hdev);
+
+	hdev->ll_driver = &thc_ipts_ll_driver;
+	hdev->bus = BUS_PCI;
+	hdev->vendor = idev->vendor;
+	hdev->product = idev->product;
+	hdev->version = le32_to_cpu(idev->cfg.revision) & 0xffff;
+	hdev->dev.parent = idev->dev;
+	hdev->driver_data = idev;
+	snprintf(hdev->name, sizeof(hdev->name), "intel-ipts %04X:%04X",
+		 idev->vendor, idev->product);
+	strscpy(hdev->phys, dev_name(idev->dev), sizeof(hdev->phys));
+
+	ret = hid_add_device(hdev);
+	if (ret) {
+		hid_destroy_device(hdev);
+		return ret;
+	}
+
+	WRITE_ONCE(idev->hid, hdev);
+
+	return 0;
+}
+
 /**
  * thc_ipts_port_start - bring one port up
  * @idev: port to start
@@ -429,7 +825,9 @@ int thc_ipts_port_start(struct thc_ipts *idev)
 	int ret;
 
 	WRITE_ONCE(idev->stopping, false);
+	WRITE_ONCE(idev->recover_pending, false);
 	WRITE_ONCE(idev->recovering, false);
+	WRITE_ONCE(idev->feature_off, false);
 
 	ret = thc_ipts_quiesce(idev, true);
 	if (ret)
@@ -522,7 +920,7 @@ int thc_ipts_port_start(struct thc_ipts *idev)
 
 	thc_interrupt_enable(idev->thc, true);
 
-	return 0;
+	return thc_ipts_hid_add(idev);
 }
 
 /**
@@ -531,11 +929,17 @@ int thc_ipts_port_start(struct thc_ipts *idev)
  */
 void thc_ipts_port_stop(struct thc_ipts *idev)
 {
-	/*
-	 * Mask the line, then wait for a handler that may be holding a
-	 * frame for the HID device which is about to go away.
+	/* Refuse new requests first, then wait for one that is already inside
+	 * thc_dma_write(): the completion it waits for comes through the
+	 * handler this teardown is about to mask. The lock is not held across
+	 * synchronize_irq(), because the threaded handler can issue a request
+	 * of its own from a HID callback.
 	 */
 	WRITE_ONCE(idev->stopping, true);
+	wake_up(&idev->wq);
+	mutex_lock(&idev->tx_lock);
+	mutex_unlock(&idev->tx_lock);
+
 	thc_interrupt_enable(idev->thc, false);
 	synchronize_irq(idev->irq);
 	cancel_work_sync(&idev->recover_work);
@@ -543,7 +947,7 @@ void thc_ipts_port_stop(struct thc_ipts *idev)
 	/* A handler that read ->stopping early may have unmasked. */
 	thc_interrupt_enable(idev->thc, false);
 
-	/* Stop the controller before the buffers it writes into go away. */
+	/* Stop the controller before its buffers go away. */
 	if (idev->running)
 		thc_ipts_touch_set(idev, false);
 
@@ -551,7 +955,21 @@ void thc_ipts_port_stop(struct thc_ipts *idev)
 	/* Forced: the bit may read as clear and still need the command. */
 	regmap_write_bits(idev->thc->thc_regmap, THC_M_PRT_CONTROL_OFFSET,
 			  THC_M_PRT_CONTROL_DEVRST, 0);
-	thc_ipts_quiesce(idev, true);
 
+	/* The buffers are not devm-managed, so releasing them is the only way
+	 * back: do it even when the engine did not acknowledge the stop, and
+	 * let thc_dma_unconfigure() clear the start bits on its way out.
+	 */
+	if (thc_ipts_quiesce(idev, true))
+		dev_warn(idev->dev, "engine did not stop, releasing anyway\n");
 	thc_ipts_dma_stop(idev);
+
+	/* ->dma_ready goes away with the buffers, and a handler woken before
+	 * that still looks at the ring: wait for it once more, then mask what
+	 * it may have left open.
+	 */
+	synchronize_irq(idev->irq);
+	thc_interrupt_enable(idev->thc, false);
+
+	thc_ipts_hid_remove(idev);
 }
drivers/hid/intel-thc-hid/intel-ipts/ipts.h +56 -0

89 lines not on this page · raw message

drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c +3 -0
index 1670d116a..5aa0ad6fb 100644
@@ -45,6 +45,9 @@ static int thc_ipts_probe(struct pci_dev *pci, const struct pci_device_id *id)
 		return -ENOMEM;
 
 	idev->dev = &pci->dev;
+	mutex_init(&idev->tx_lock);
+	mutex_init(&idev->feature_lock);
+	init_waitqueue_head(&idev->wq);
 	pci_set_drvdata(pci, idev);
 	INIT_WORK(&idev->recover_work, thc_ipts_recover);
 
#5 lore raw

Re: [PATCH v7 3/5] HID: intel-thc-hid: intel-ipts: add the HID device

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] HID: intel-thc-hid: device-wide in_thread in thc_ipts_send() causes -EBUSY - [Medium] HID…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] HID: intel-thc-hid: device-wide in_thread in thc_ipts_send() causes -EBUSY
- [Medium] HID: intel-thc-hid: early recover_seq read in thc_ipts_get_feature()
- [Medium] HID: intel-thc-hid: IRQ unmask race in thc_ipts_thread() on reset and stop
--

commit 6e11ece02bde2a13fad79dc0bf400dc9dc7577a0
Author: Emfox Zhou <[email protected]>

HID: intel-thc-hid: intel-ipts: add the HID device

This commit registers a HID device for the Intel IPTS transport and implements report descriptor parsing, input report forwarding, and raw feature and output report requests over THC DMA.

Quoted 4 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +0 -0
index 17f6f664e95b5..347a705719e6e 100644

[ ... ]

Quoted 10 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +6 -0
@@ -144,8 +146,86 @@ static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable)
 				 &touch);
 }
 
+/*
+ * Frames are built in @idev->tx_frame, so the lock is taken here rather than
+ * by the callers: none of them may hold it across a wait.
+ */
+static int thc_ipts_send(struct thc_ipts *idev, u32 code, const void *data,
+			 size_t len)

drivers/hid/intel-thc-hid/intel-ipts/ipts.c static int thc_ipts_touch_set(struct thc_ipts *idev, bool enable) · line 164

Quoted 10 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +10 -0
+{
+	size_t padded = round_up(len, 4);
+	u8 *frame = idev->tx_frame;
+
+	/* The completion of a write is delivered by the threaded handler, so
+	 * one issued from there would wait out its timeout: refuse it instead,
+	 * and let the caller retry from its own context.
+	 */
+	if (READ_ONCE(idev->in_thread))
+		return -EBUSY;

[Severity: High]
Does checking the device-wide idev->in_thread flag reject normal process-context callers on other CPUs whenever thc_ipts_thread() is running?

thc_ipts_thread() sets idev->in_thread for its entire execution, including when woken by a shared INTx interrupt or while delivering touch input reports. In thc_ipts_port_start(), interrupts are enabled while idev->dma_ready is true before calling thc_ipts_hid_add() -> hid_add_device() -> thc_ipts_hid_parse():

CPU0 CPU1
thc_ipts_port_start()
thc_interrupt_enable(..., true)

                                  thc_ipts_thread()
                                    WRITE_ONCE(idev->in_thread, true)
  thc_ipts_hid_add()
    ...
      thc_ipts_hid_parse()
        thc_ipts_send()
          if (READ_ONCE(idev->in_thread))
            return -EBUSY;  <-- aborts hid_add_device() and probe

Because thc_ipts_hid_parse() only retries -EAGAIN and -ETIMEDOUT, -EBUSY immediately fails HID registration and driver probe, and at runtime hidraw feature and output requests fail with -EBUSY whenever they overlap with incoming touch frames.

[ ... ]

Quoted 18 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +4 -7
@@ -399,17 +525,19 @@ irqreturn_t thc_ipts_thread(int irq, void *data)
 			need_recover = true;
 	}
 
-	/* The work item resets the engine and unmasks again; a frame read
-	 * meanwhile would corrupt the ring.
+	/*
+	 * The work item resets the engine in its own time; a frame read
+	 * meanwhile would corrupt the ring, so only queue the reset.
 	 */
-	if (need_recover) {
+	if (need_recover)
 		thc_ipts_request_recover(idev);
-		return IRQ_HANDLED;
-	}
 
-	/* A reset unmasks when it is done. A teardown masks on its own, so the
-	 * line stays open here: a write already on the wire needs the

drivers/hid/intel-thc-hid/intel-ipts/ipts.c irqreturn_t thc_ipts_thread(int irq, void *data) · line 543

Quoted 10 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +6 -1
-	 * completion this handler delivers.
+	/*
+	 * A reset unmasks when it is done, and a teardown masks on its own.
+	 * Leaving the line open here is what a write already on the wire
+	 * needs: this handler is where its completion is delivered, and
+	 * masking it away would make that write time out over the bus lock
+	 * the reset is waiting for.
 	 */
 	if (!READ_ONCE(idev->recovering))
 		thc_interrupt_enable(idev->thc, true);

[Severity: Medium]
Can thc_ipts_thread() unmask interrupts while thc_ipts_recover() or thc_ipts_port_stop() expects the port to stay masked?

In the recovery path, thc_ipts_recover() does not mask interrupts again after synchronize_irq(), so a handler that checked idev->recovering just before it was set leaves interrupts enabled across thc_rxdma_reset() and after a reset failure:

CPU0 (thc_ipts_thread) CPU1 (thc_ipts_recover)
if (!READ_ONCE(idev->recovering))

                                  WRITE_ONCE(idev->recovering, true)
                                  thc_interrupt_enable(idev->thc, false)
  thc_interrupt_enable(..., true)
                                  synchronize_irq(idev->irq)
                                  thc_rxdma_reset(idev->thc)  <-- IRQ unmasked

Inaddition, thc_ipts_thread() does not check idev->stopping before calling thc_interrupt_enable(idev->thc, true), so any shared interrupt that wakes the thread in thc_ipts_port_stop() before thc_ipts_dma_stop() clears idev->dma_ready will re-enable device interrupts during teardown.

[ ... ]

Quoted 1 line
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +0 -0
@@ -419,6 +547,274 @@ irqreturn_t thc_ipts_thread(int irq, void *data)

[ ... ]

Quoted 4 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +4 -0
+/* A feature report comes back as a frame of its own: the request waits. */
+static int thc_ipts_get_feature(struct thc_ipts *idev, unsigned char reportnum,
+				u8 *buf, size_t len)
+{

[ ... ]

Quoted 6 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +6 -0
+	seq = READ_ONCE(idev->recover_seq);
+
+	/* A refusal happens before anything is written, so the channel stays
+	 * open for it; a timeout is a different matter, see below.
+	 */
+	ret = thc_ipts_send(idev, THC_IPTS_TX_GET_FEATURE, &reportnum, 1);

[ ... ]

Quoted 15 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +15 -0
+	wait_event_timeout(idev->wq, READ_ONCE(idev->feature_done) ||
+			   READ_ONCE(idev->recover_pending) ||
+			   READ_ONCE(idev->recovering) ||
+			   READ_ONCE(idev->stopping), timeout);
+
+	mutex_lock(&idev->feature_lock);
+	/* An answer that landed while the wait was expiring counts too. */
+	if (!idev->feature_done) {
+		/* A reset discards what the engines had queued, so an answer
+		 * that was on its way is gone and cannot be waited for.
+		 */
+		if (READ_ONCE(idev->recover_seq) != seq ||
+		    READ_ONCE(idev->recover_pending) ||
+		    READ_ONCE(idev->recovering) ||
+		    READ_ONCE(idev->stopping))

drivers/hid/intel-thc-hid/intel-ipts/ipts.c irqreturn_t thc_ipts_thread(int irq, void *data) · line 701

Quoted 10 lines
drivers/hid/intel-thc-hid/intel-ipts/ipts.c +10 -0
+			ret = -EIO;
+		else
+			ret = -ETIMEDOUT;
+
+		idev->feature_pending = false;
+		/* Only a timeout leaves a frame out there: after a reset the
+		 * answer was dropped and the channel is still in step.
+		 */
+		if (ret == -ETIMEDOUT)
+			WRITE_ONCE(idev->feature_off, true);

[Severity: Medium]
Can sampling idev->recover_seq before thc_ipts_send() leave idev->feature_off false after a feature request times out on the wire?

CPU0 (thc_ipts_get_feature) CPU1 (thc_ipts_recover)
seq = READ_ONCE(idev->recover_seq)

                                  WRITE_ONCE(idev->recover_seq, ... + 1)
                                  WRITE_ONCE(idev->recover_pending, false)
                                  WRITE_ONCE(idev->recovering, false)

thc_ipts_send()
guard(mutex)(&idev->tx_lock)
thc_dma_write() <-- sent after reset
wait_event_timeout() <-- times out
if (READ_ONCE(idev->recover_seq) != seq ...)
ret = -EIO; <-- feature_off not set

Because thc_ipts_recover() finishes before thc_ipts_send() checks idev->recover_pending and idev->recovering under idev->tx_lock, the request is transmitted after the reset, but a subsequent timeout sees idev->recover_seq != seq and leaves the feature channel open while an unanswered request is still in flight.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author
#6 lore raw

PATCH v7 4/5 HID: intel-thc-hid: intel-ipts: handle system sleep

In reply to Emfox Zhou

System sleep takes the port down and builds it up again rather than keeping the HID device across it: the controller forgets the streaming mode user space asked it for, and hidraw offers no way to tell user space to ask again. A new HID device is what comes back, so the hidraw node and the input device are destroyed on the way down and reappear under a new minor; a daemon holding them open sees that and repeats the request.

Nothing here arms a wakeup source, so the port does not have to stay alive across sleep: DEFINE_SIMPLE_DEV_PM_OPS() installs the same pair for freeze and restore, and a controller that lost power in hibernation comes back through the full bring-up.

---
 .../hid/intel-thc-hid/intel-ipts/pci-ipts.c   | 25 +++++++++++++++++++
 1 file changed, 25 insertions(+)
drivers/hid/intel-thc-hid/intel-ipts/pci-ipts.c +25 -0
index 5aa0ad6fb..b2d9be4ee 100644
@@ -143,6 +143,30 @@ static void thc_ipts_remove(struct pci_dev *pci)
 	pci_clear_master(pci);
 }
 
+static int thc_ipts_suspend(struct device *dev)
+{
+	struct thc_ipts *idev = dev_get_drvdata(dev);
+
+	thc_ipts_port_stop(idev);
+
+	return 0;
+}
+
+static int thc_ipts_resume(struct device *dev)
+{
+	struct thc_ipts *idev = dev_get_drvdata(dev);
+	int ret;
+
+	ret = thc_ipts_port_start(idev);
+	if (ret)
+		thc_ipts_port_stop(idev);
+
+	return ret;
+}
+
+static DEFINE_SIMPLE_DEV_PM_OPS(thc_ipts_pm_ops, thc_ipts_suspend,
+				thc_ipts_resume);
+
 static void thc_ipts_shutdown(struct pci_dev *pci)
 {
 	struct thc_ipts *idev = pci_get_drvdata(pci);
@@ -157,6 +181,7 @@ static struct pci_driver thc_ipts_driver = {
 	.probe		= thc_ipts_probe,
 	.remove		= thc_ipts_remove,
 	.shutdown	= thc_ipts_shutdown,
+	.driver.pm	= pm_sleep_ptr(&thc_ipts_pm_ops),
 	/* Bring-up waits for the controller, up to a few seconds. */
 	.driver.probe_type = PROBE_PREFER_ASYNCHRONOUS,
 };
author
#7 lore raw

PATCH v7 5/5 HID: intel-thc-hid: intel-ipts: document the IPTS mode

In reply to Emfox Zhou

The THC documentation only covers HIDSPI and HIDI2C. Ports from before Meteor Lake run in a third mode, and the intel-ipts driver is written against behaviour that is not described anywhere in tree.

Record what the driver depends on: the layout of the configuration block, the frame codes and header sizes, the bulk data window, and the order in which quiesce, interrupt configuration and the DMA engines have to be set up.

---
 Documentation/hid/intel-thc-hid.rst | 109 +++++++++++++++++++++++++++-
 1 file changed, 108 insertions(+), 1 deletion(-)
Documentation/hid/intel-thc-hid.rst +108 -1
index 8b378c57b..e6bdf30b6 100644
@@ -590,7 +590,114 @@ To debug THC, event tracing mechanism is used. To enable debug logs::
   echo 1 > /sys/kernel/debug/tracing/events/intel_thc/enable
   cat /sys/kernel/debug/tracing/trace
 
-7. Reference
+7. IPTS Mode
+============
+
+THC also supports IPTS mode, the private Intel Precise Touch and Stylus
+protocol. The port drives the touch controller over plain SPI and moves the
+data through the same DMA engines, but the framing is private and the
+parameters come from the controller itself instead of ACPI. The
+``intel-ipts`` module handles ports in that mode, which is what Tiger Lake,
+Lakefield, Alder Lake and Raptor Lake hardware use.
+
+This section describes how the driver uses those ports. It is not a
+specification: everything below comes from observing the controller and is
+limited to what this driver relies on.
+
+7.1 Configuration Block
+-----------------------
+
+At SPI address 0 the controller exposes a 64 byte block. The driver reads it
+over the PIO path after releasing the controller from reset, and retries
+until the tag ``$TIC`` (``0x43495424``) appears, because the block is only
+partially filled while the controller is still starting.
+
+Two steps come before that read: the DMA engines are unconfigured first, so
+engines the firmware left armed do not keep writing through the PRD base it
+had mapped, and the interrupt trigger is switched to edge, without which the
+first read is unreliable.
+
+Fields the driver uses:
+
+======  ==========================================================
+Offset  Meaning
+======  ==========================================================
+0x00    pending interrupt causes
+0x08    buffer sizes, ``(size / 64) - 1``; Rx bits 13:0, Tx 23:14
+0x0c    touch engine control: enable BIT(0), HID reports BIT(2),
+        power state GENMASK(5, 3)
+0x14    controller tag, ``$TIC``
+0x18    SPI timing: clock divisor GENMASK(3, 1), divide-by-8 and
+        dual/quad bits
+0x1c    vendor and product ID reported to HID
+0x20    product revision
+0x24    firmware version word
+======  ==========================================================
+
+The driver enables the touch engine with reports and full power, and clears
+it again when the port is shut down.
+
+The offsets above, the frame codes and the header sizes below are compiled
+into ``ipts.h``; a ``static_assert()`` on every offset makes a mismatch a
+build failure rather than a quiet misread.
+
+7.2 Frames
+----------
+
+Both directions carry a code and a length in front of the payload. Frames
+from the controller use a 64 byte header, frames to it an 8 byte header, and
+only the latter has the payload padded to a four byte boundary.
+
+==== ========================== =======================
+Code Received from controller   Sent to controller
+==== ========================== =======================
+3    input report               set feature
+4    feature report             get feature
+5    report descriptor          output report
+7    reset request              get report descriptor
+==== ========================== =======================
+
+A report descriptor comes back with eight bytes of preamble that the driver
+skips.
+
+7.3 Data Window
+---------------
+
+Bulk transfers go through address ``0x1000`` of the controller, not through
+address 0. The DMA engines have to be pointed there explicitly, otherwise
+they write into the configuration block and the controller drops the frames
+without reporting an error. The input header address is zero: that is where
+the controller writes the interrupt cause word, at the start of the
+configuration block.
+
+7.4 Enabling and Flow Control
+-----------------------------
+
+The port has to be released from quiesce before the driver enables the
+touch engine: quiescing holds back the device interrupt and the data path,
+not the configuration access, which is why the block above is read while the
+port is still quiesced. The interrupt configuration programs the interrupt
+type field in the device to the invalid value, and starting the receive
+engine then replaces that field with the type it expects, so the two have to
+happen in that order.
+
+The controller starts streaming once user space asks for it, through a set
+feature request on report 5. The driver does not do that on its own; the
+daemon that opens hidraw sends it.
+
+7.5 What Is Left to User Space
+------------------------------
+
+The reports carry heatmap data, and turning that into contacts is a
+substantial image-processing job that already exists in user space. The
+driver therefore stops at the HID layer: the report descriptor comes from
+the controller and is not written by the driver, the report stream is
+available through hidraw, and ``iptsd`` decodes it into input events.
+
+System sleep tears the port down and brings it back, so the hidraw node is
+destroyed and re-created: a daemon has to reopen it after resume.
+
+8. Reference
 ============
 - HIDSPI: https://download.microsoft.com/download/c/a/0/ca07aef3-3e10-4022-b1e9-c98cea99465d/HidSpiProtocolSpec.pdf
 - HIDI2C: https://download.microsoft.com/download/7/d/d/7dd44bb7-2a7a-4505-ac1c-7227d3d96d5b/hid-over-i2c-protocol-spec-v1-0.docx