← Documents Documentation/hid/intel-thc-hid.rst GitHub 원문 ↗

Linux 6.18.37 · HID

Intel Touch Host Controller (THC)

Intel THC의 QuickSPI·QuickI2C protocol, PIO·DMA·PRD memory model과 HID report 흐름을 설명합니다.

Source pathDocumentation/hid/intel-thc-hid.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

intel-thc-hid.rst:1-596

Intel Touch Host Controller는 PCH의 SPI·I2C touch host adapter로, hardware sequencer와 PIO·DMA를 이용해 Touch IC의 HID report를 system memory와 Linux HID core에 연결합니다.

이 문서는 controller block, Panther Lake input 보호, opcode, 네 DMA channel, 128-bit PRD descriptor와 QuickSPI·QuickI2C의 reset·input·output flow를 register와 pointer 수준에서 설명합니다.

문서 범위
항목
SourceDocumentation/hid/intel-thc-hid.rst
분량596 source lines
BusEnhanced SPI · I2C
TransferPIO · RxDMA1 · RxDMA2 · SWDMA · TxDMA
MemoryPRD table · circular buffer · SGL

Source와 주요 구현 요소입니다.

THC 전체 흐름
ACPI와 PCI resource로 THC·Touch IC 초기화PIO로 device descriptor와 packet size 획득PRD table과 DMA channel 구성Touch interrupt에서 sequencer가 packet readRxDMA가 circular buffer에 frame 저장QuickSPI/QuickI2C driver가 HID core에 report 전달

Touch 감지에서 HID input까지의 경로입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 =================================
4 Intel Touch Host Controller (THC)
5 =================================
6
7 Touch Host Controller is the name of the IP block in PCH that interface with Touch Devices (ex:
8 touchscreen, touchpad etc.). It is comprised of 3 key functional blocks:
9
10 - A natively half-duplex Quad I/O capable SPI master
11 - Low latency I2C interface to support HIDI2C compliant devices
12 - A HW sequencer with RW DMA capability to system memory
13
14 It has a single root space IOSF Primary interface that supports transactions to/from touch devices.
15 Host driver configures and controls the touch devices over THC interface. THC provides high
16 bandwidth DMA services to the touch driver and transfers the HID report to host system main memory.
17
18 Hardware sequencer within the THC is responsible for transferring (via DMA) data from touch devices
19 into system memory. A ring buffer is used to avoid data loss due to asynchronous nature of data
20 consumption (by host) in relation to data production (by touch device via DMA).
21
22 Unlike other common SPI/I2C controllers, THC handles the HID device data interrupt and reset
23 signals directly.
24
25 1. Overview
26 ===========
27
28 1.1 THC software/hardware stack
29 -------------------------------
30
31 Below diagram illustrates the high-level architecture of THC software/hardware stack, which is fully
32 capable of supporting HIDSPI/HIDI2C protocol in Linux OS.
33
34 ::
35
36 ----------------------------------------------
37 | +-----------------------------------+ |
38 | | Input Device | |
39 | +-----------------------------------+ |
40 | +-----------------------------------+ |
41 | | HID Multi-touch Driver | |
42 | +-----------------------------------+ |
43 | +-----------------------------------+ |
44 | | HID Core | |
45 | +-----------------------------------+ |
46 | +-----------------------------------+ |
47 | | THC QuickSPI/QuickI2C Driver | |
48 | +-----------------------------------+ |
49 | +-----------------------------------+ |
50 | | THC Hardware Driver | |
51 | +-----------------------------------+ |
52 | +----------------+ +----------------+ |
53 | SW | PCI Bus Driver | | ACPI Resource | |
54 | +----------------+ +----------------+ |
55 ----------------------------------------------
56 ----------------------------------------------
57 | +-----------------------------------+ |
58 | HW | PCI Bus | |
59 | +-----------------------------------+ |
60 | +-----------------------------------+ |
61 | | THC Controller | |
62 | +-----------------------------------+ |
63 | +-----------------------------------+ |
64 | | Touch IC | |
65 | +-----------------------------------+ |
66 ----------------------------------------------
67
68 Touch IC (TIC), also as known as the Touch devices (touchscreen or touchpad). The discrete analog
69 components that sense and transfer either discrete touch data or heatmap data in the form of HID
70 reports over the SPI/I2C bus to the THC Controller on the host.
71
72 THC Host Controller, which is a PCI device HBA (host bus adapter), integrated into the PCH, that
73 serves as a bridge between the Touch ICs and the host.
74
75 THC Hardware Driver, provides THC hardware operation APIs for above QuickSPI/QuickI2C driver, it
76 accesses THC MMIO registers to configure and control THC hardware.
77
78 THC QuickSPI/QuickI2C driver, also as known as HIDSPI/HIDI2C driver, is registered as a HID
79 low-level driver that manages the THC Controller and implements HIDSPI/HIDI2C protocol.
80
81
82 1.2 THC hardware diagram
83 ------------------------
84 Below diagram shows THC hardware components::
85
86 ---------------------------------
87 | THC Controller |
88 | +---------------------------+ |
89 | | PCI Config Space | |
90 | +---------------------------+ |
91 | +---------------------------+ |
92 | + MMIO Registers | |
93 | +---------------------------+ |
94 +---------------+ | +------------+ +------------+ |
95 | System Memory +---+--+ DMA | | PIO | |
96 +---------------+ | +------------+ +------------+ |
97 | +---------------------------+ |
98 | | HW Sequencer | |
99 | +---------------------------+ |
100 | +------------+ +------------+ |
101 | | SPI/I2C | | GPIO | |
102 | | Controller | | Controller | |
103 | +------------+ +------------+ |
104 ---------------------------------
105
106 As THC is exposed as a PCI devices, so it has standard PCI config space registers for PCI
107 enumeration and configuration.
108
109 MMIO Registers, which provide registers access for driver to configure and control THC hardware,
110 the registers include several categories: Interrupt status and control, DMA configure,
111 PIO (Programmed I/O, defined in section 3.2) status and control, SPI bus configure, I2C subIP
112 status and control, reset status and control...
113
114 THC provides two ways for driver to communicate with external Touch ICs: PIO and DMA.
115 PIO can let driver manually write/read data to/from Touch ICs, instead, THC DMA can
116 automatically write/read data without driver involved.
117
118 HW Sequencer includes THC major logic, it gets instruction from MMIO registers to control
119 SPI bus and I2C bus to finish a bus data transaction, it also can automatically handle
120 Touch ICs interrupt and start DMA receive/send data from/to Touch ICs according to interrupt
121 type. That means THC HW Sequencer understands HIDSPI/HIDI2C transfer protocol, and handle
122 the communication without driver involved, what driver needs to do is just configure the THC
123 properly, and prepare the formatted data packet or handle received data packet.
124
125 As THC supports HIDSPI/HIDI2C protocols, it has SPI controller and I2C subIP in it to expose
126 SPI bus and I2C bus. THC also integrates a GPIO controller to provide interrupt line support
127 and reset line support.
128
129 2. THC Hardware Interface
130 =========================
131
132 2.1 Host Interface
133 ------------------
134
135 THC is exposed as "PCI Digitizer device" to the host. The PCI product and device IDs are
136 changed from different generations of processors. So the source code which enumerates drivers
137 needs to update from generation to generation.
138
139
140 2.2 Device Interface
141 --------------------
142
143 THC supports two types of bus for Touch IC connection: Enhanced SPI bus and I2C bus.
144
145 2.2.1 SPI Port
146 ~~~~~~~~~~~~~~
147
148 When PORT_TYPE = 00b in MMIO registers, THC uses SPI interfaces to communicate with external
149 Touch IC. THC enhanced SPI Bus supports different SPI modes: standard Single IO mode,
150 Dual IO mode and Quad IO mode.
151
152 In Single IO mode, THC drives MOSI line to send data to Touch ICs, and receives data from Touch
153 ICs data from MISO line. In Dual IO mode, THC drivers MOSI and MISO both for data sending, and
154 also receives the data on both line. In Quad IO mode, there are other two lines (IO2 and IO3)
155 are added, THC drives MOSI (IO0), MISO (IO1), IO2 and IO3 at the same time for data sending, and
156 also receives the data on those 4 lines. Driver needs to configure THC in different mode by
157 setting different opcode.
158
159 Beside IO mode, driver also needs to configure SPI bus speed. THC supports up to 42MHz SPI clock
160 on Intel Lunar Lake platform.
161
162 For THC sending data to Touch IC, the data flow on SPI bus::
163
164 | --------------------THC sends---------------------------------|
165 <8Bits OPCode><24Bits Slave Address><Data><Data><Data>...........
166
167 For THC receiving data from Touch IC, the data flow on SPI bus::
168
169 | ---------THC Sends---------------||-----Touch IC sends--------|
170 <8Bits OPCode><24Bits Slave Address><Data><Data><Data>...........
171
172 2.2.2 I2C Port
173 ~~~~~~~~~~~~~~
174
175 THC also integrates I2C controller in it, it's called I2C SubSystem. When PORT_TYPE = 01, THC
176 is configured to I2C mode. Comparing to SPI mode which can be configured through MMIO registers
177 directly, THC needs to use PIO read (by setting SubIP read opcode) to I2C subIP APB registers'
178 value and use PIO write (by setting SubIP write opcode) to do a write operation.
179
180 2.2.3 GPIO interface
181 ~~~~~~~~~~~~~~~~~~~~
182
183 THC also includes two GPIO pins, one for interrupt and the other for device reset control.
184
185 Interrupt line can be configured to either level triggered or edge triggered by setting MMIO
186 Control register.
187
188 Reset line is controlled by BIOS (or EFI) through ACPI _RST method, driver needs to call this
189 device ACPI _RST method to reset touch IC during initialization.
190
191 2.3 Max input size control
192 --------------------------
193
194 This is a new feature introduced in Panther Lake platform, THC hardware allows driver to set
195 a max input size for RxDMA. After this max size gets set and enabled, for every input report
196 packet reading, THC hardware sequencer will first read incoming input packet size, then compare
197 input packet size with the given max size:
198
199 - if input packet size <= max size, THC continues using input packet size to finish the reading
200 - if input packet size > max size, there is potential input data crash risk during
201 transferring, THC will use max size instead of input packet size for reading
202
203 This feature is used to avoid data corruption which will cause RxDMA buffer overrun issue for
204 I2C bus, and enhance whole system stability.
205
206 2.4 Interrupt delay
207 -------------------
208
209 Because of MCU performance limitation, some touch devices cannot de-assert interrupt pin
210 immediately after input data is transferred, which cause an interrupt toggle delay. But THC
211 always detects next interrupt immediately after last input interrupt is handled. In this
212 case, the delayed interrupt de-assertion will be recognized as a new interrupt signal by THC,
213 and causes THC to start an input report reading spuriously.
214
215 In order to avoid this situation, THC introduced interrupt delay new feature in Panther Lake
216 platform, where THC allows driver to set an interrupt delay. After this feature is enabled,
217 THC will delay this given time for next interrupt detection.
218
219 3. High level concept
220 =====================
221
222 3.1 Opcode
223 ----------
224
225 Opcode (operation code) is used to tell THC or Touch IC what the operation will be, such as PIO
226 read or PIO write.
227
228 When THC is configured to SPI mode, opcodes are used for determining the read/write IO mode.
229 There are some OPCode examples for SPI IO mode:
230
231 ======= ==============================
232 opcode Corresponding SPI command
233 ======= ==============================
234 0x0B Read Single I/O
235 0x02 Write Single I/O
236 0xBB Read Dual I/O
237 0xB2 Write Dual I/O
238 0xEB Read Quad I/O
239 0xE2 Write Quad I/O
240 ======= ==============================
241
242 In general, different touch IC has different OPCode definition. According to HIDSPI
243 protocol whitepaper, those OPCodes are defined in device ACPI table, and driver needs to
244 query those information through OS ACPI APIs during driver initialization, then configures
245 THC MMIO OPCode registers with correct setting.
246
247 When THC is working in I2C mode, opcodes are used to tell THC what's the next PIO type:
248 I2C SubIP APB register read, I2C SubIP APB register write, I2C touch IC device read,
249 I2C touch IC device write, I2C touch IC device write followed by read.
250
251 Here are the THC pre-defined opcodes for I2C mode:
252
253 ======= =================================================== ===========
254 opcode Corresponding I2C command Address
255 ======= =================================================== ===========
256 0x12 Read I2C SubIP APB internal registers 0h - FFh
257 0x13 Write I2C SubIP APB internal registers 0h - FFh
258 0x14 Read external Touch IC through I2C bus N/A
259 0x18 Write external Touch IC through I2C bus N/A
260 0x1C Write then read external Touch IC through I2C bus N/A
261 ======= =================================================== ===========
262
263 3.2 PIO
264 -------
265
266 THC provides a programmed I/O (PIO) access interface for the driver to access the touch IC's
267 configuration registers, or access I2C subIP's configuration registers. To use PIO to perform
268 I/O operations, driver should pre-program PIO control registers and PIO data registers and kick
269 off the sequencing cycle. THC uses different PIO opcodes to distinguish different PIO
270 operations (PIO read/write/write followed by read).
271
272 If there is a Sequencing Cycle In Progress and an attempt is made to program any of the control,
273 address, or data register the cycle is blocked and a sequence error will be encountered.
274
275 A status bit indicates when the cycle has completed allowing the driver to know when read results
276 can be checked and/or when to initiate a new command. If enabled, the cycle done assertion can
277 interrupt driver with an interrupt.
278
279 Because THC only has 16 FIFO registers for PIO, so all the data transfer through PIO shouldn't
280 exceed 64 bytes.
281
282 As DMA needs max packet size for transferring configuration, and the max packet size information
283 always in HID device descriptor which needs THC driver to read it out from HID Device (Touch IC).
284 So PIO typical use case is, before DMA initialization, write RESET command (PIO write), read
285 RESET response (PIO read or PIO write followed by read), write Power ON command (PIO write), read
286 device descriptor (PIO read).
287
288 For how to issue a PIO operation, here is the steps which driver needs follow:
289
290 - Program read/write data size in THC_SS_BC.
291 - Program I/O target address in THC_SW_SEQ_DATA0_ADDR.
292 - If write, program the write data in THC_SW_SEQ_DATA0..THC_SW_SEQ_DATAn.
293 - Program the PIO opcode in THC_SS_CMD.
294 - Set TSSGO = 1 to start the PIO write sequence.
295 - If THC_SS_CD_IE = 1, SW will receives a MSI when the PIO is completed.
296 - If read, read out the data in THC_SW_SEQ_DATA0..THC_SW_SEQ_DATAn.
297
298 3.3 DMA
299 -------
300
301 THC has 4 DMA channels: Read DMA1, Read DMA2, Write DMA and Software DMA.
302
303 3.3.1 Read DMA Channel
304 ~~~~~~~~~~~~~~~~~~~~~~
305
306 THC has two Read DMA engines: 1st RxDMA (RxDMA1) and 2nd RxDMA (RxDMA2). RxDMA1 is reserved for
307 raw data mode. RxDMA2 is used for HID data mode and it is the RxDMA engine currently driver uses
308 for HID input report data retrieval.
309
310 RxDMA's typical use case is auto receiving the data from Touch IC. Once RxDMA is enabled by
311 software, THC will start auto-handling receiving logic.
312
313 For SPI mode, THC RxDMA sequence is: when Touch IC triggers a interrupt to THC, THC reads out
314 report header to identify what's the report type, and what's the report length, according to
315 above information, THC reads out report body to internal FIFO and start RxDMA coping the data
316 to system memory. After that, THC update interrupt cause register with report type, and update
317 RxDMA PRD table read pointer, then trigger a MSI interrupt to notify driver RxDMA finishing
318 data receiving.
319
320 For I2C mode, THC RxDMA's behavior is a little bit different, because of HIDI2C protocol difference
321 with HIDSPI protocol, RxDMA only be used to receive input report. The sequence is, when Touch IC
322 triggers a interrupt to THC, THC first reads out 2 bytes from input report address to determine the
323 packet length, then use this packet length to start a DMA reading from input report address for
324 input report data. After that, THC update RxDMA PRD table read pointer, then trigger a MSI interrupt
325 to notify driver input report data is ready in system memory.
326
327 All above sequence is hardware automatically handled, all driver needs to do is configure RxDMA and
328 waiting for interrupt ready then read out the data from system memory.
329
330 3.3.2 Software DMA channel
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~
332
333 THC supports a software triggered RxDMA mode to read the touch data from touch IC. This SW RxDMA
334 is the 3rd THC RxDMA engine with the similar functionalities as the existing two RxDMAs, the only
335 difference is this SW RxDMA is triggered by software, and RxDMA2 is triggered by external Touch IC
336 interrupt. It gives a flexibility to software driver to use RxDMA read Touch IC data in any time.
337
338 Before software starts a SW RxDMA, it shall stop the 1st and 2nd RxDMA, clear PRD read/write pointer
339 and quiesce the device interrupt (THC_DEVINT_QUIESCE_HW_STS = 1), other operations are the same with
340 RxDMA.
341
342 3.3.3 Write DMA Channel
343 ~~~~~~~~~~~~~~~~~~~~~~~
344
345 THC has one write DMA engine, which can be used for sending data to Touch IC automatically.
346 According to HIDSPI and HIDI2C protocol, every time only one command can be sent to touch IC, and
347 before last command is completely handled, next command cannot be sent, THC write DMA engine only
348 supports single PRD table.
349
350 What driver needs to do is, preparing PRD table and DMA buffer, then copy data to DMA buffer and
351 update PRD table with buffer address and buffer length, then start write DMA. THC will
352 automatically send the data to touch IC, and trigger a DMA completion interrupt once transferring
353 is done.
354
355 3.4 PRD
356 -------
357
358 Physical Region Descriptor (PRD) provides the memory mapping description for THC DMAs.
359
360 3.4.1 PRD table and entry
361 ~~~~~~~~~~~~~~~~~~~~~~~~~
362
363 In order to improve physical DMA memory usage, modern drivers trend to allocate a virtually
364 contiguous, but physically fragmented buffer of memory for each data buffer. Linux OS also
365 provide SGL (scatter gather list) APIs to support this usage.
366
367 THC uses PRD table (physical region descriptor) to support the corresponding OS kernel
368 SGL that describes the virtual to physical buffer mapping.
369
370 ::
371
372 ------------------------ -------------- --------------
373 | PRD table base address +----+ PRD table #1 +-----+ PRD Entry #1 |
374 ------------------------ -------------- --------------
375 --------------
376 | PRD Entry #2 |
377 --------------
378 --------------
379 | PRD Entry #n |
380 --------------
381
382 The read DMA engine supports multiple PRD tables held within a circular buffer that allow the THC
383 to support multiple data buffers from the Touch IC. This allows host SW to arm the Read DMA engine
384 with multiple buffers, allowing the Touch IC to send multiple data frames to the THC without SW
385 interaction. This capability is required when the CPU processes touch frames slower than the
386 Touch IC can send them.
387
388 To simplify the design, SW assumes worst-case memory fragmentation. Therefore,each PRD table shall
389 contain the same number of PRD entries, allowing for a global register (per Touch IC) to hold the
390 number of PRD-entries per PRD table.
391
392 SW allocates up to 128 PRD tables per Read DMA engine as specified in the THC_M_PRT_RPRD_CNTRL.PCD
393 register field. The number of PRD tables should equal the number of data buffers.
394
395 Max OS memory fragmentation will be at a 4KB boundary, thus to address 1MB of virtually contiguous
396 memory 256 PRD entries are required for a single PRD Table. SW writes the number of PRD entries
397 for each PRD table in the THC_M_PRT_RPRD_CNTRL.PTEC register field. The PRD entry's length must be
398 multiple of 4KB except for the last entry in a PRD table.
399
400 SW allocates all the data buffers and PRD tables only once at host initialization.
401
402 3.4.2 PRD Write pointer and read pointer
403 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404
405 As PRD tables are organized as a Circular Buffer (CB), a read pointer and a write pointer for a CB
406 are needed.
407
408 DMA HW consumes the PRD tables in the CB, one PRD entry at a time until the EOP bit is found set
409 in a PRD entry. At this point HW increments the PRD read pointer. Thus, the read pointer points
410 to the PRD which the DMA engine is currently processing. This pointer rolls over once the circular
411 buffer's depth has been traversed with bit[7] the Rollover bit. E.g. if the DMA CB depth is equal
412 to 4 entries (0011b), then the read pointers will follow this pattern (HW is required to honor
413 this behavior): 00h 01h 02h 03h 80h 81h 82h 83h 00h 01h ...
414
415 The write pointer is updated by SW. The write pointer points to location in the DMA CB, where the
416 next PRD table is going to be stored. SW needs to ensure that this pointer rolls over once the
417 circular buffer's depth has been traversed with Bit[7] as the rollover bit. E.g. if the DMA CB
418 depth is equal to 5 entries (0100b), then the write pointers will follow this pattern (SW is
419 required to honor this behavior): 00h 01h 02h 03h 04h 80h 81h 82h 83h 84h 00h 01h ..
420
421 3.4.3 PRD descriptor structure
422 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
423
424 Intel THC uses PRD entry descriptor for every PRD entry. Every PRD entry descriptor occupies
425 128 bits memories:
426
427 =================== ======== ===============================================
428 struct field bit(s) description
429 =================== ======== ===============================================
430 dest_addr 53..0 destination memory address, as every entry
431 is 4KB, ignore lowest 10 bits of address.
432 reserved1 54..62 reserved
433 int_on_completion 63 completion interrupt enable bit, if this bit
434 set it means THC will trigger a completion
435 interrupt. This bit is set by SW driver.
436 len 87..64 how many bytes of data in this entry.
437 end_of_prd 88 end of PRD table bit, if this bit is set,
438 it means this entry is last entry in this PRD
439 table. This bit is set by SW driver.
440 hw_status 90..89 HW status bits
441 reserved2 127..91 reserved
442 =================== ======== ===============================================
443
444 And one PRD table can include up to 256 PRD entries, as every entries is 4K bytes, so every
445 PRD table can describe 1M bytes memory.
446
447 .. code-block:: c
448
449 struct thc_prd_table {
450 struct thc_prd_entry entries[PRD_ENTRIES_NUM];
451 };
452
453 In general, every PRD table means one HID touch data packet. Every DMA engine can support
454 up to 128 PRD tables (except write DMA, write DMA only has one PRD table). SW driver is responsible
455 to get max packet length from touch IC, and use this max packet length to create PRD entries for
456 each PRD table.
457
458 4. HIDSPI support (QuickSPI)
459 ============================
460
461 Intel THC is total compatible with HIDSPI protocol, THC HW sequenser can accelerate HIDSPI
462 protocol transferring.
463
464 4.1 Reset Flow
465 --------------
466
467 - Call ACPI _RST method to reset Touch IC device.
468 - Read the reset response from TIC through PIO read.
469 - Issue a command to retrieve device descriptor from Touch IC through PIO write.
470 - Read the device descriptor from Touch IC through PIO read.
471 - If the device descriptor is valid, allocate DMA buffers and configure all DMA channels.
472 - Issue a command to retrieve report descriptor from Touch IC through DMA.
473
474 4.2 Input Report Data Flow
475 --------------------------
476
477 Basic Flow:
478
479 - Touch IC interrupts the THC Controller using an in-band THC interrupt.
480 - THC Sequencer reads the input report header by transmitting read approval as a signal
481 to the Touch IC to prepare for host to read from the device.
482 - THC Sequencer executes a Input Report Body Read operation corresponding to the value
483 reflected in “Input Report Length” field of the Input Report Header.
484 - THC DMA engine begins fetching data from the THC Sequencer and writes to host memory
485 at PRD entry 0 for the current CB PRD table entry. This process continues until the
486 THC Sequencer signals all data has been read or the THC DMA Read Engine reaches the
487 end of it's last PRD entry (or both).
488 - The THC Sequencer checks for the “Last Fragment Flag” bit in the Input Report Header.
489 If it is clear, the THC Sequencer enters an idle state.
490 - If the “Last Fragment Flag” bit is enabled the THC Sequencer enters End-of-Frame Processing.
491
492 THC Sequencer End of Frame Processing:
493
494 - THC DMA engine increments the read pointer of the Read PRD CB, sets EOF interrupt status
495 in RxDMA2 register (THC_M_PRT_READ_DMA_INT_STS_2).
496 - If THC EOF interrupt is enabled by the driver in the control register (THC_M_PRT_READ_DMA_CNTRL_2),
497 generates interrupt to software.
498
499 Sequence of steps to read data from RX DMA buffer:
500
501 - THC QuickSPI driver checks CB write Ptr and CB read Ptr to identify if any data frame in DMA
502 circular buffers.
503 - THC QuickSPI driver gets first unprocessed PRD table.
504 - THC QuickSPI driver scans all PRD entries in this PRD table to calculate the total frame size.
505 - THC QuickSPI driver copies all frame data out.
506 - THC QuickSPI driver checks the data type according to input report body, and calls related
507 callbacks to process the data.
508 - THC QuickSPI driver updates write Ptr.
509
510 4.3 Output Report Data Flow
511 ---------------------------
512
513 Generic Output Report Flow:
514
515 - HID core calls raw_request callback with a request to THC QuickSPI driver.
516 - THC QuickSPI Driver converts request provided data into the output report packet and copies it
517 to THC's write DMA buffer.
518 - Start TxDMA to complete the write operation.
519
520 5. HIDI2C support (QuickI2C)
521 ============================
522
523 5.1 Reset Flow
524 --------------
525
526 - Read device descriptor from Touch IC device through PIO write followed by read.
527 - If the device descriptor is valid, allocate DMA buffers and configure all DMA channels.
528 - Use PIO or TxDMA to write a SET_POWER request to TIC's command register, and check if the
529 write operation is successfully completed.
530 - Use PIO or TxDMA to write a RESET request to TIC's command register. If the write operation
531 is successfully completed, wait for reset response from TIC.
532 - Use SWDMA to read report descriptor through TIC's report descriptor register.
533
534 5.2 Input Report Data Flow
535 --------------------------
536
537 Basic Flow:
538
539 - Touch IC asserts the interrupt indicating that it has an interrupt to send to HOST.
540 THC Sequencer issues a READ request over the I2C bus. The HIDI2C device returns the
541 first 2 bytes from the HIDI2C device which contains the length of the received data.
542 - THC Sequencer continues the Read operation as per the size of data indicated in the
543 length field.
544 - THC DMA engine begins fetching data from the THC Sequencer and writes to host memory
545 at PRD entry 0 for the current CB PRD table entry. THC writes 2Bytes for length field
546 plus the remaining data to RxDMA buffer. This process continues until the THC Sequencer
547 signals all data has been read or the THC DMA Read Engine reaches the end of it's last
548 PRD entry (or both).
549 - THC Sequencer enters End-of-Input Report Processing.
550 - If the device has no more input reports to send to the host, it de-asserts the interrupt
551 line. For any additional input reports, device keeps the interrupt line asserted and
552 steps 1 through 4 in the flow are repeated.
553
554 THC Sequencer End of Input Report Processing:
555
556 - THC DMA engine increments the read pointer of the Read PRD CB, sets EOF interrupt status
557 in RxDMA 2 register (THC_M_PRT_READ_DMA_INT_STS_2).
558 - If THC EOF interrupt is enabled by the driver in the control register
559 (THC_M_PRT_READ_DMA_CNTRL_2), generates interrupt to software.
560
561 Sequence of steps to read data from RX DMA buffer:
562
563 - THC QuickI2C driver checks CB write Ptr and CB read Ptr to identify if any data frame in DMA
564 circular buffers.
565 - THC QuickI2C driver gets first unprocessed PRD table.
566 - THC QuickI2C driver scans all PRD entries in this PRD table to calculate the total frame size.
567 - THC QuickI2C driver copies all frame data out.
568 - THC QuickI2C driver call hid_input_report to send the input report content to HID core, which
569 includes Report ID + Report Data Content (remove the length field from the original report
570 data).
571 - THC QuickI2C driver updates write Ptr.
572
573 5.3 Output Report Data Flow
574 ---------------------------
575
576 Generic Output Report Flow:
577
578 - HID core call THC QuickI2C raw_request callback.
579 - THC QuickI2C uses PIO or TXDMA to write a SET_REPORT request to TIC's command register. Report
580 type in SET_REPORT should be set to Output.
581 - THC QuickI2C programs TxDMA buffer with TX Data to be written to TIC's data register. The first
582 2 bytes should indicate the length of the report followed by the report contents including
583 Report ID.
584
585 6. THC Debugging
586 ================
587
588 To debug THC, event tracing mechanism is used. To enable debug logs::
589
590 echo 1 > /sys/kernel/debug/tracing/events/intel_thc/enable
591 cat /sys/kernel/debug/tracing/trace
592
593 7. Reference
594 ============
595 - HIDSPI: https://download.microsoft.com/download/c/a/0/ca07aef3-3e10-4022-b1e9-c98cea99465d/HidSpiProtocolSpec.pdf
596 - HIDI2C: https://download.microsoft.com/download/7/d/d/7dd44bb7-2a7a-4505-ac1c-7227d3d96d5b/hid-over-i2c-protocol-spec-v1-0.docx
597

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

THC 기능 블록과 software/hardware stack

1-81

Touch Host Controller(THC)는 touchscreen, touchpad 같은 Touch Device와 연결되는 PCH 내부 IP block의 이름입니다. 세 핵심 기능 블록은 native half-duplex Quad I/O 지원 SPI master, HIDI2C 호환 device를 위한 low-latency I2C interface, system memory에 읽고 쓰는 DMA 기능을 갖춘 hardware sequencer입니다.

THC에는 touch device와 오가는 transaction을 지원하는 하나의 root-space IOSF Primary interface가 있습니다. Host driver는 THC interface를 통해 touch device를 설정하고 제어합니다. THC는 touch driver에 고대역폭 DMA 서비스를 제공하며 HID report를 host system main memory로 옮깁니다.

THC 안의 hardware sequencer는 DMA를 이용해 touch device의 data를 system memory로 전송합니다. Touch device의 비동기 data 생산 속도와 host의 소비 속도가 다르기 때문에 ring buffer를 사용하여 data 손실을 막습니다. 일반 SPI/I2C controller와 달리 THC는 HID device data interrupt와 reset signal도 직접 처리합니다.

Linux의 THC stack은 HIDSPI와 HIDI2C protocol을 모두 지원합니다. Software 쪽은 Input Device, HID Multi-touch Driver, HID Core, THC QuickSPI/QuickI2C Driver, THC Hardware Driver, PCI Bus Driver와 ACPI Resource로 이어집니다. Hardware 쪽은 PCI Bus, THC Controller, Touch IC 순서입니다.

Touch IC(TIC)는 touchscreen 또는 touchpad 같은 Touch Device입니다. Discrete analog component가 touch를 감지하고, discrete touch data 또는 heatmap data를 HID report 형식으로 SPI/I2C bus를 거쳐 host의 THC Controller에 전달합니다.

THC Host Controller는 PCH에 통합된 PCI device HBA(host bus adapter)이며 Touch IC와 host 사이의 bridge입니다. THC Hardware Driver는 QuickSPI/QuickI2C driver에 hardware operation API를 제공하고 THC MMIO register에 접근하여 hardware를 설정·제어합니다.

THC QuickSPI/QuickI2C driver는 HIDSPI/HIDI2C driver라고도 합니다. HID low-level driver로 등록되어 THC Controller를 관리하고 HIDSPI/HIDI2C protocol을 구현합니다.

THC stack 계층
영역계층역할
Linux inputInput Device · HID Multi-touch DriverTouch event를 input subsystem에 제공
HIDHID CoreHID device·report 공통 처리
ProtocolTHC QuickSPI/QuickI2C DriverHIDSPI·HIDI2C 구현과 low-level HID operation
Hardware APITHC Hardware DriverMMIO register와 DMA·PIO 제어
EnumerationPCI Bus Driver · ACPI ResourceController 발견과 platform resource 제공
HardwarePCI Bus · THC Controller · Touch ICHost bridge와 실제 touch sensing

원문의 software/hardware block diagram을 위에서 아래로 정리했습니다.

Touch report 전달 경로
Touch IC가 discrete 또는 heatmap touch data 생성SPI/I2C bus로 THC Controller에 HID report 전달Hardware sequencer가 DMA로 system memory에 기록QuickSPI/QuickI2C driver가 protocol packet 처리HID Core와 HID Multi-touch Driver가 report 해석Input Device를 통해 userspace에 event 제공

Touch IC의 감지 결과가 Linux input event가 되는 경로입니다.

.. SPDX-License-Identifier: GPL-2.0

=================================
Intel Touch Host Controller (THC)
=================================

Touch Host Controller is the name of the IP block in PCH that interface with Touch Devices (ex:
touchscreen, touchpad etc.). It is comprised of 3 key functional blocks:

- A natively half-duplex Quad I/O capable SPI master
- Low latency I2C interface to support HIDI2C compliant devices
- A HW sequencer with RW DMA capability to system memory

It has a single root space IOSF Primary interface that supports transactions to/from touch devices.
Host driver configures and controls the touch devices over THC interface. THC provides high
bandwidth DMA services to the touch driver and transfers the HID report to host system main memory.

Hardware sequencer within the THC is responsible for transferring (via DMA) data from touch devices
into system memory. A ring buffer is used to avoid data loss due to asynchronous nature of data
consumption (by host) in relation to data production (by touch device via DMA).

Unlike other common SPI/I2C controllers, THC handles the HID device data interrupt and reset
signals directly.

1. Overview
===========

1.1 THC software/hardware stack
-------------------------------

Below diagram illustrates the high-level architecture of THC software/hardware stack, which is fully
capable of supporting HIDSPI/HIDI2C protocol in Linux OS.

::

  ----------------------------------------------
 |      +-----------------------------------+   |
 |      |           Input Device            |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |       HID Multi-touch Driver      |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |             HID Core              |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |    THC QuickSPI/QuickI2C Driver   |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |      THC Hardware Driver          |   |
 |      +-----------------------------------+   |
 |      +----------------+ +----------------+   |
 |  SW  | PCI Bus Driver | | ACPI Resource  |   |
 |      +----------------+ +----------------+   |
  ----------------------------------------------
  ----------------------------------------------
 |      +-----------------------------------+   |
 |  HW  |              PCI Bus              |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |           THC Controller          |   |
 |      +-----------------------------------+   |
 |      +-----------------------------------+   |
 |      |              Touch IC             |   |
 |      +-----------------------------------+   |
  ----------------------------------------------

Touch IC (TIC), also as known as the Touch devices (touchscreen or touchpad). The discrete analog
components that sense and transfer either discrete touch data or heatmap data in the form of HID
reports over the SPI/I2C bus to the THC Controller on the host.

THC Host Controller, which is a PCI device HBA (host bus adapter), integrated into the PCH, that
serves as a bridge between the Touch ICs and the host.

THC Hardware Driver, provides THC hardware operation APIs for above QuickSPI/QuickI2C driver, it
accesses THC MMIO registers to configure and control THC hardware.

THC QuickSPI/QuickI2C driver, also as known as HIDSPI/HIDI2C driver, is registered as a HID
low-level driver that manages the THC Controller and implements HIDSPI/HIDI2C protocol.

THC hardware 구성과 host interface

82-140

THC Controller는 PCI Config Space, MMIO Register, DMA, PIO, HW Sequencer, SPI/I2C Controller와 GPIO Controller로 구성됩니다. DMA는 system memory에 연결되고, SPI/I2C와 GPIO는 외부 Touch IC 쪽 bus와 signal을 담당합니다.

THC는 PCI device로 노출되므로 PCI enumeration과 configuration을 위한 표준 PCI config-space register를 가집니다.

MMIO register는 driver가 THC hardware를 설정하고 제어하는 interface입니다. Register 범주는 interrupt status/control, DMA configuration, 3.2절의 PIO status/control, SPI bus configuration, I2C subIP status/control, reset status/control 등을 포함합니다.

Driver가 외부 Touch IC와 통신하는 방법은 PIO와 DMA 두 가지입니다. PIO에서는 driver가 Touch IC에 data를 직접 쓰고 읽습니다. DMA에서는 driver가 개별 전송에 관여하지 않아도 THC가 자동으로 data를 읽고 씁니다.

HW Sequencer에는 THC의 핵심 logic이 들어 있습니다. MMIO register의 instruction을 받아 SPI 또는 I2C bus transaction을 끝내고, Touch IC interrupt를 자동 처리하며 interrupt type에 따라 DMA receive/send를 시작할 수 있습니다. 즉 sequencer가 HIDSPI/HIDI2C transfer protocol을 이해하므로 driver는 THC를 올바르게 설정하고 형식에 맞춘 packet을 준비하거나 수신 packet을 처리하면 됩니다.

HIDSPI와 HIDI2C를 지원하기 위해 THC에는 SPI controller와 I2C subIP가 들어 있습니다. GPIO controller도 통합되어 interrupt line과 reset line을 제공합니다.

Host에는 THC가 `PCI Digitizer device`로 노출됩니다. PCI product ID와 device ID는 processor generation에 따라 바뀌므로 driver enumeration source code도 세대별로 갱신해야 합니다.

THC controller block
BlockInterface책임
PCI Config SpacePCI BusEnumeration과 standard configuration
MMIO RegistersHost driverInterrupt·DMA·PIO·bus·reset 제어
DMASystem MemoryTouch packet 자동 read/write
PIODriver sequenceConfiguration register 수동 access
HW SequencerMMIO instructionHIDSPI/HIDI2C transaction 자동화
SPI/I2C ControllerTouch busTouch IC data transfer
GPIO ControllerInterrupt · reset lineDevice signal 직접 처리

원문의 hardware diagram을 기능별로 정리했습니다.

Hardware transaction
PCI로 THC Controller enumerateDriver가 MMIO register와 ACPI resource 구성HW Sequencer에 bus transaction instruction 제공SPI/I2C controller가 Touch IC와 통신PIO 또는 DMA로 payload 이동Interrupt status를 갱신하고 driver에 완료 통지

Driver 설정 이후 sequencer가 data transfer를 수행합니다.

1.2 THC hardware diagram
------------------------
Below diagram shows THC hardware components::

                      ---------------------------------
                     |          THC Controller         |
                     |  +---------------------------+  |
                     |  |     PCI Config Space      |  |
                     |  +---------------------------+  |
                     |  +---------------------------+  |
                     |  +       MMIO Registers      |  |
                     |  +---------------------------+  |
 +---------------+   |  +------------+ +------------+  |
 | System Memory +---+--+      DMA   | |   PIO      |  |
 +---------------+   |  +------------+ +------------+  |
                     |  +---------------------------+  |
                     |  |       HW Sequencer        |  |
                     |  +---------------------------+  |
                     |  +------------+ +------------+  |
                     |  |  SPI/I2C   | |    GPIO    |  |
                     |  | Controller | | Controller |  |
                     |  +------------+ +------------+  |
                      ---------------------------------

As THC is exposed as a PCI devices, so it has standard PCI config space registers for PCI
enumeration and configuration.

MMIO Registers, which provide registers access for driver to configure and control THC hardware,
the registers include several categories: Interrupt status and control, DMA configure,
PIO (Programmed I/O, defined in section 3.2) status and control, SPI bus configure, I2C subIP
status and control, reset status and control...

THC provides two ways for driver to communicate with external Touch ICs: PIO and DMA.
PIO can let driver manually write/read data to/from Touch ICs, instead, THC DMA can
automatically write/read data without driver involved.

HW Sequencer includes THC major logic, it gets instruction from MMIO registers to control
SPI bus and I2C bus to finish a bus data transaction, it also can automatically handle
Touch ICs interrupt and start DMA receive/send data from/to Touch ICs according to interrupt
type. That means THC HW Sequencer understands HIDSPI/HIDI2C transfer protocol, and handle
the communication without driver involved, what driver needs to do is just configure the THC
properly, and prepare the formatted data packet or handle received data packet.

As THC supports HIDSPI/HIDI2C protocols, it has SPI controller and I2C subIP in it to expose
SPI bus and I2C bus. THC also integrates a GPIO controller to provide interrupt line support
and reset line support.

2. THC Hardware Interface
=========================

2.1 Host Interface
------------------

THC is exposed as "PCI Digitizer device" to the host. The PCI product and device IDs are
changed from different generations of processors. So the source code which enumerates drivers
needs to update from generation to generation.


2.2 Device Interface

SPI·I2C·GPIO와 Panther Lake 보호 기능

141-218

THC는 Touch IC 연결에 Enhanced SPI bus와 I2C bus 두 종류를 지원합니다.

MMIO register의 `PORT_TYPE = 00b`이면 SPI interface를 사용합니다. Enhanced SPI bus는 standard Single I/O, Dual I/O, Quad I/O mode를 지원합니다. Single mode는 MOSI로 송신하고 MISO로 수신합니다. Dual mode는 MOSI와 MISO를 모두 송수신에 쓰며, Quad mode는 IO2와 IO3를 추가하여 MOSI(IO0), MISO(IO1), IO2, IO3 네 line을 함께 사용합니다. Driver는 opcode를 달리 설정해 mode를 선택합니다.

I/O mode 외에도 SPI bus speed를 설정해야 합니다. Intel Lunar Lake platform에서 THC는 최대 42MHz SPI clock을 지원합니다.

THC가 Touch IC로 보낼 때 SPI frame은 8-bit OPCode, 24-bit Slave Address, 연속 Data로 구성됩니다. 받을 때는 THC가 먼저 8-bit OPCode와 24-bit Slave Address를 보내고, 이어지는 Data 구간은 Touch IC가 전송합니다.

THC 내부 I2C controller는 I2C SubSystem이라고 합니다. `PORT_TYPE = 01`이면 I2C mode입니다. SPI는 MMIO register로 직접 설정할 수 있지만 I2C subIP APB register는 SubIP read opcode를 설정한 PIO read로 읽고, SubIP write opcode를 설정한 PIO write로 써야 합니다.

THC에는 GPIO pin 두 개가 있으며 하나는 interrupt, 다른 하나는 device reset control용입니다. Interrupt line은 MMIO Control register에서 level-triggered 또는 edge-triggered로 설정합니다. Reset line은 BIOS 또는 EFI가 ACPI `_RST` method로 제어하므로 driver는 initialization 중 device의 ACPI `_RST`를 호출해 Touch IC를 reset해야 합니다.

Panther Lake에서 도입된 max input size 기능은 driver가 RxDMA의 최대 입력 크기를 정하게 합니다. 매 input report를 읽기 전에 hardware sequencer가 packet size를 읽어 설정된 max size와 비교합니다. Packet size가 max 이하이면 실제 size로 읽고, 더 크면 transfer 중 data corruption 위험이 있으므로 max size만 읽습니다. 이 기능은 I2C bus에서 RxDMA buffer overrun으로 이어지는 data corruption을 막고 system 안정성을 높입니다.

일부 Touch Device는 MCU 성능 제한 때문에 input data 전송 직후 interrupt pin을 즉시 de-assert하지 못합니다. THC는 이전 interrupt 처리가 끝나자마자 다음 interrupt를 감지하므로 늦게 내려간 signal을 새 interrupt로 오인해 input report를 불필요하게 읽을 수 있습니다. Panther Lake의 interrupt-delay 기능을 활성화하면 driver가 정한 시간만큼 다음 interrupt detection을 늦춰 이 문제를 피합니다.

Touch IC interface mode
ModePORT_TYPEData path주요 설정
SPI Single I/O00bMOSI 송신 · MISO 수신Single opcode · bus speed
SPI Dual I/O00bMOSI와 MISO 동시 사용Dual opcode · bus speed
SPI Quad I/O00bIO0·IO1·IO2·IO3Quad opcode · 최대 42MHz on Lunar Lake
I2C SubSystem01I2C busPIO로 subIP APB register access
GPION/AInterrupt · resetMMIO trigger mode · ACPI _RST

Port와 data line, 설정 방법의 차이입니다.

보호된 input 시작
이전 report 처리 뒤 설정된 interrupt delay 대기새 Touch IC interrupt 감지Incoming packet size 먼저 읽기Packet size와 RxDMA max input size 비교작거나 같으면 실제 size로 transfer크면 max size로 제한하여 buffer overrun 방지

Panther Lake의 size와 interrupt-delay 검사를 함께 적용합니다.

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

THC supports two types of bus for Touch IC connection: Enhanced SPI bus and I2C bus.

2.2.1 SPI Port
~~~~~~~~~~~~~~

When PORT_TYPE = 00b in MMIO registers, THC uses SPI interfaces to communicate with external
Touch IC. THC enhanced SPI Bus supports different SPI modes: standard Single IO mode,
Dual IO mode and Quad IO mode.

In Single IO mode, THC drives MOSI line to send data to Touch ICs, and receives data from Touch
ICs data from MISO line. In Dual IO mode, THC drivers MOSI and MISO both for data sending, and
also receives the data on both line. In Quad IO mode, there are other two lines (IO2 and IO3)
are added, THC drives MOSI (IO0), MISO (IO1), IO2 and IO3 at the same time for data sending, and
also receives the data on those 4 lines. Driver needs to configure THC in different mode by
setting different opcode.

Beside IO mode, driver also needs to configure SPI bus speed. THC supports up to 42MHz SPI clock
on Intel Lunar Lake platform.

For THC sending data to Touch IC, the data flow on SPI bus::

 | --------------------THC sends---------------------------------|
 <8Bits OPCode><24Bits Slave Address><Data><Data><Data>...........

For THC receiving data from Touch IC, the data flow on SPI bus::

 | ---------THC Sends---------------||-----Touch IC sends--------|
 <8Bits OPCode><24Bits Slave Address><Data><Data><Data>...........

2.2.2 I2C Port
~~~~~~~~~~~~~~

THC also integrates I2C controller in it, it's called I2C SubSystem. When PORT_TYPE = 01, THC
is configured to I2C mode. Comparing to SPI mode which can be configured through MMIO registers
directly, THC needs to use PIO read (by setting SubIP read opcode) to I2C subIP APB registers'
value and use PIO write (by setting SubIP write opcode) to do a write operation.

2.2.3 GPIO interface
~~~~~~~~~~~~~~~~~~~~

THC also includes two GPIO pins, one for interrupt and the other for device reset control.

Interrupt line can be configured to either level triggered or edge triggered by setting MMIO
Control register.

Reset line is controlled by BIOS (or EFI) through ACPI _RST method, driver needs to call this
device ACPI _RST method to reset touch IC during initialization.

2.3 Max input size control
--------------------------

This is a new feature introduced in Panther Lake platform, THC hardware allows driver to set
a max input size for RxDMA. After this max size gets set and enabled, for every input report
packet reading, THC hardware sequencer will first read incoming input packet size, then compare
input packet size with the given max size:

- if input packet size <= max size, THC continues using input packet size to finish the reading
- if input packet size > max size, there is potential input data crash risk during
  transferring, THC will use max size instead of input packet size for reading

This feature is used to avoid data corruption which will cause RxDMA buffer overrun issue for
I2C bus, and enhance whole system stability.

2.4 Interrupt delay
-------------------

Because of MCU performance limitation, some touch devices cannot de-assert interrupt pin
immediately after input data is transferred, which cause an interrupt toggle delay. But THC
always detects next interrupt immediately after last input interrupt is handled. In this
case, the delayed interrupt de-assertion will be recognized as a new interrupt signal by THC,
and causes THC to start an input report reading spuriously.

In order to avoid this situation, THC introduced interrupt delay new feature in Panther Lake
platform, where THC allows driver to set an interrupt delay. After this feature is enabled,
THC will delay this given time for next interrupt detection.

SPI와 I2C opcode

219-262

Opcode(operation code)는 PIO read 또는 PIO write처럼 다음 operation이 무엇인지 THC나 Touch IC에 알립니다.

SPI mode에서 opcode는 read/write 방향과 I/O mode를 결정합니다. 예제 opcode는 `0x0B` Read Single I/O, `0x02` Write Single I/O, `0xBB` Read Dual I/O, `0xB2` Write Dual I/O, `0xEB` Read Quad I/O, `0xE2` Write Quad I/O입니다.

일반적으로 Touch IC마다 opcode 정의가 다릅니다. HIDSPI protocol whitepaper에 따라 이 opcode는 device ACPI table에 정의됩니다. Driver는 initialization 중 OS ACPI API로 정보를 조회하고 올바른 값으로 THC MMIO opcode register를 설정해야 합니다.

I2C mode에서 opcode는 다음 PIO type을 지정합니다. I2C SubIP APB register read/write, I2C Touch IC device read/write, 또는 Touch IC device write followed by read입니다.

THC가 미리 정의한 I2C opcode는 `0x12` SubIP APB internal register read, `0x13` internal register write, `0x14` external Touch IC read, `0x18` external Touch IC write, `0x1C` external Touch IC write then read입니다. Internal register address 범위는 `0h - FFh`이고 외부 device command의 address 열은 N/A입니다.

THC opcode
BusOpcodeCommand
SPI0x0B / 0x02Read / Write Single I/O
SPI0xBB / 0xB2Read / Write Dual I/O
SPI0xEB / 0xE2Read / Write Quad I/O
I2C0x12 / 0x13Read / Write I2C SubIP APB internal register
I2C0x14 / 0x18Read / Write external Touch IC
I2C0x1CWrite then read external Touch IC

SPI opcode는 device별 ACPI 정보이고 I2C opcode는 THC가 미리 정의합니다.

Opcode 구성
PORT_TYPE으로 SPI 또는 I2C mode 확인SPI이면 device ACPI table의 opcode 조회Single·Dual·Quad와 read/write 조합 선택I2C이면 pre-defined PIO command 선택THC MMIO opcode register에 값 설정Sequencer가 지정 operation 수행

Bus mode에 따라 opcode의 출처와 의미가 달라집니다.

3. High level concept
=====================

3.1 Opcode
----------

Opcode (operation code) is used to tell THC or Touch IC what the operation will be, such as PIO
read or PIO write.

When THC is configured to SPI mode, opcodes are used for determining the read/write IO mode.
There are some OPCode examples for SPI IO mode:

=======   ==============================
opcode    Corresponding SPI command
=======   ==============================
0x0B      Read Single I/O
0x02      Write Single I/O
0xBB      Read Dual I/O
0xB2      Write Dual I/O
0xEB      Read Quad I/O
0xE2      Write Quad I/O
=======   ==============================

In general, different touch IC has different OPCode definition. According to HIDSPI
protocol whitepaper, those OPCodes are defined in device ACPI table, and driver needs to
query those information through OS ACPI APIs during driver initialization, then configures
THC MMIO OPCode registers with correct setting.

When THC is working in I2C mode, opcodes are used to tell THC what's the next PIO type:
I2C SubIP APB register read, I2C SubIP APB register write, I2C touch IC device read,
I2C touch IC device write, I2C touch IC device write followed by read.

Here are the THC pre-defined opcodes for I2C mode:

=======   ===================================================   ===========
opcode    Corresponding I2C command                             Address
=======   ===================================================   ===========
0x12      Read I2C SubIP APB internal registers                 0h - FFh
0x13      Write I2C SubIP APB internal registers                0h - FFh
0x14      Read external Touch IC through I2C bus                N/A
0x18      Write external Touch IC through I2C bus               N/A
0x1C      Write then read external Touch IC through I2C bus     N/A
=======   ===================================================   ===========

PIO access와 초기화 sequence

263-297

THC의 programmed I/O(PIO) interface는 driver가 Touch IC configuration register 또는 I2C subIP configuration register에 접근하게 합니다. Driver는 PIO control register와 data register를 미리 program한 뒤 sequencing cycle을 시작합니다. PIO read, write, write followed by read는 서로 다른 opcode로 구분합니다.

Sequencing Cycle이 진행 중일 때 control, address 또는 data register를 program하려 하면 cycle이 차단되고 sequence error가 발생합니다.

Status bit는 cycle 완료를 알려 주어 driver가 read result를 확인하거나 새 command를 시작할 시점을 판단하게 합니다. Cycle-done interrupt를 enable하면 완료 assertion이 interrupt로 driver에 전달됩니다.

THC에는 PIO용 FIFO register가 16개뿐이므로 PIO data transfer는 64 bytes를 넘으면 안 됩니다.

DMA configuration에는 max packet size가 필요하고, 이 정보는 Touch IC에서 읽어야 하는 HID device descriptor에 들어 있습니다. 따라서 DMA 초기화 전 PIO의 일반적인 용도는 RESET command 쓰기, RESET response 읽기 또는 write-followed-by-read, Power ON command 쓰기, device descriptor 읽기입니다.

PIO operation은 `THC_SS_BC`에 read/write size를, `THC_SW_SEQ_DATA0_ADDR`에 target address를 설정하는 것으로 시작합니다. Write라면 `THC_SW_SEQ_DATA0..THC_SW_SEQ_DATAn`에 data를 넣고 `THC_SS_CMD`에 opcode를 씁니다. `TSSGO = 1`로 sequence를 시작합니다. `THC_SS_CD_IE = 1`이면 완료 시 software가 MSI를 받습니다. Read operation이면 완료 뒤 같은 DATA register들에서 결과를 읽습니다.

PIO programming register
순서Register·field동작
1THC_SS_BCRead/write data size 설정
2THC_SW_SEQ_DATA0_ADDRI/O target address 설정
3THC_SW_SEQ_DATA0..DATAnWrite payload 입력
4THC_SS_CMDPIO opcode 설정
5TSSGO = 1PIO sequence 시작
6THC_SS_CD_IE = 1완료 MSI 선택
7THC_SW_SEQ_DATA0..DATAnRead result 회수

PIO cycle을 시작하는 데 필요한 register와 값입니다.

DMA 이전 PIO 초기화
진행 중인 sequencing cycle이 없는지 확인PIO write로 RESET command 전송PIO read 또는 write-followed-by-read로 response 수신PIO write로 Power ON command 전송PIO read로 HID device descriptor 획득Max packet size를 이용해 DMA 구성

Descriptor에서 max packet size를 얻기 전의 대표 흐름입니다.

3.2 PIO
-------

THC provides a programmed I/O (PIO) access interface for the driver to access the touch IC's
configuration registers, or access I2C subIP's configuration registers. To use PIO to perform
I/O operations, driver should pre-program PIO control registers and PIO data registers and kick
off the sequencing cycle. THC uses different PIO opcodes to distinguish different PIO
operations (PIO read/write/write followed by read).

If there is a Sequencing Cycle In Progress and an attempt is made to program any of the control,
address, or data register the cycle is blocked and a sequence error will be encountered.

A status bit indicates when the cycle has completed allowing the driver to know when read results
can be checked and/or when to initiate a new command. If enabled, the cycle done assertion can
interrupt driver with an interrupt.

Because THC only has 16 FIFO registers for PIO, so all the data transfer through PIO shouldn't
exceed 64 bytes.

As DMA needs max packet size for transferring configuration, and the max packet size information
always in HID device descriptor which needs THC driver to read it out from HID Device (Touch IC).
So PIO typical use case is, before DMA initialization, write RESET command (PIO write), read
RESET response (PIO read or PIO write followed by read), write Power ON command (PIO write), read
device descriptor (PIO read).

For how to issue a PIO operation, here is the steps which driver needs follow:

- Program read/write data size in THC_SS_BC.
- Program I/O target address in THC_SW_SEQ_DATA0_ADDR.
- If write, program the write data in THC_SW_SEQ_DATA0..THC_SW_SEQ_DATAn.
- Program the PIO opcode in THC_SS_CMD.
- Set TSSGO = 1 to start the PIO write sequence.
- If THC_SS_CD_IE = 1, SW will receives a MSI when the PIO is completed.
- If read, read out the data in THC_SW_SEQ_DATA0..THC_SW_SEQ_DATAn.

Read·software·write DMA channel

298-354

THC에는 Read DMA1, Read DMA2, Write DMA, Software DMA의 네 DMA channel이 있습니다.

두 Read DMA engine 중 첫 번째 RxDMA(RxDMA1)는 raw data mode용이고, 두 번째 RxDMA(RxDMA2)는 HID data mode용입니다. 현재 driver가 HID input report를 가져올 때 사용하는 engine은 RxDMA2입니다. Software가 RxDMA를 enable하면 THC가 수신 logic을 자동 처리합니다.

SPI mode에서 Touch IC interrupt가 발생하면 THC는 report header를 읽어 report type과 length를 알아냅니다. 이 정보로 report body를 internal FIFO에 읽고 RxDMA가 system memory로 복사합니다. 이후 interrupt-cause register를 report type으로 갱신하고 RxDMA PRD table read pointer를 전진시킨 뒤 MSI로 수신 완료를 driver에 알립니다.

I2C mode는 HIDI2C protocol 차이 때문에 RxDMA가 input report 수신에만 쓰입니다. Interrupt가 오면 THC가 input-report address의 첫 2 bytes를 읽어 packet length를 결정하고, 그 길이만큼 같은 address에서 DMA read를 수행합니다. 이어 PRD read pointer를 갱신하고 MSI로 system memory에 input report가 준비됐음을 알립니다.

두 sequence 모두 hardware가 자동 처리합니다. Driver는 RxDMA를 설정하고 ready interrupt를 기다린 뒤 system memory의 data를 읽으면 됩니다.

Software-triggered RxDMA는 세 번째 RxDMA engine입니다. 기존 두 RxDMA와 기능은 비슷하지만 외부 Touch IC interrupt로 시작되는 RxDMA2와 달리 software가 시작하므로 driver가 원하는 시점에 DMA로 Touch IC data를 읽을 수 있습니다. 시작 전에는 RxDMA1·RxDMA2를 정지하고 PRD read/write pointer를 지우며 `THC_DEVINT_QUIESCE_HW_STS = 1`로 device interrupt를 quiesce해야 합니다. 나머지 operation은 RxDMA와 같습니다.

Write DMA engine은 하나이며 Touch IC에 data를 자동 전송합니다. HIDSPI와 HIDI2C는 한 번에 command 하나만 허용하고 이전 command가 완전히 처리되기 전에는 다음 command를 보낼 수 없으므로 write DMA는 PRD table 하나만 지원합니다.

Driver는 PRD table과 DMA buffer를 준비하고 data를 buffer에 복사한 뒤 buffer address와 length로 PRD table을 갱신하여 write DMA를 시작합니다. THC가 Touch IC에 data를 자동 전송하고 완료되면 DMA completion interrupt를 발생시킵니다.

THC DMA channel
ChannelTrigger용도
RxDMA1Touch IC / hardwareRaw data mode
RxDMA2Touch IC interruptHID input report 수신
Software DMASoftware원하는 시점의 Touch IC read
Write DMASoftware startTouch IC command·report 송신, single PRD table

Trigger와 protocol 용도를 구분했습니다.

RxDMA input 수신
Touch IC가 interrupt 발생SPI는 report header, I2C는 첫 2-byte length 읽기Sequencer가 body read size 결정RxDMA가 internal path에서 system memory로 복사PRD read pointer 갱신MSI로 driver에 data-ready 통지

SPI와 I2C의 header 차이 뒤 공통 DMA 완료 경로가 이어집니다.

3.3 DMA
-------

THC has 4 DMA channels: Read DMA1, Read DMA2, Write DMA and Software DMA.

3.3.1 Read DMA Channel
~~~~~~~~~~~~~~~~~~~~~~

THC has two Read DMA engines: 1st RxDMA (RxDMA1) and 2nd RxDMA (RxDMA2). RxDMA1 is reserved for
raw data mode. RxDMA2 is used for HID data mode and it is the RxDMA engine currently driver uses
for HID input report data retrieval.

RxDMA's typical use case is auto receiving the data from Touch IC. Once RxDMA is enabled by
software, THC will start auto-handling receiving logic.

For SPI mode, THC RxDMA sequence is: when Touch IC triggers a interrupt to THC, THC reads out
report header to identify what's the report type, and what's the report length, according to
above information, THC reads out report body to internal FIFO and start RxDMA coping the data
to system memory. After that, THC update interrupt cause register with report type, and update
RxDMA PRD table read pointer, then trigger a MSI interrupt to notify driver RxDMA finishing
data receiving.

For I2C mode, THC RxDMA's behavior is a little bit different, because of HIDI2C protocol difference
with HIDSPI protocol, RxDMA only be used to receive input report. The sequence is, when Touch IC
triggers a interrupt to THC, THC first reads out 2 bytes from input report address to determine the
packet length, then use this packet length to start a DMA reading from input report address for
input report data. After that, THC update RxDMA PRD table read pointer, then trigger a MSI interrupt
to notify driver input report data is ready in system memory.

All above sequence is hardware automatically handled, all driver needs to do is configure RxDMA and
waiting for interrupt ready then read out the data from system memory.

3.3.2 Software DMA channel
~~~~~~~~~~~~~~~~~~~~~~~~~~

THC supports a software triggered RxDMA mode to read the touch data from touch IC. This SW RxDMA
is the 3rd THC RxDMA engine with the similar functionalities as the existing two RxDMAs, the only
difference is this SW RxDMA is triggered by software, and RxDMA2 is triggered by external Touch IC
interrupt. It gives a flexibility to software driver to use RxDMA read Touch IC data in any time.

Before software starts a SW RxDMA, it shall stop the 1st and 2nd RxDMA, clear PRD read/write pointer
and quiesce the device interrupt (THC_DEVINT_QUIESCE_HW_STS = 1), other operations are the same with
RxDMA.

3.3.3 Write DMA Channel
~~~~~~~~~~~~~~~~~~~~~~~

THC has one write DMA engine, which can be used for sending data to Touch IC automatically.
According to HIDSPI and HIDI2C protocol, every time only one command can be sent to touch IC, and
before last command is completely handled, next command cannot be sent, THC write DMA engine only
supports single PRD table.

What driver needs to do is, preparing PRD table and DMA buffer, then copy data to DMA buffer and
update PRD table with buffer address and buffer length, then start write DMA. THC will
automatically send the data to touch IC, and trigger a DMA completion interrupt once transferring
is done.

PRD table, scatter-gather와 circular pointer

355-420

Physical Region Descriptor(PRD)는 THC DMA를 위한 memory mapping description을 제공합니다.

현대 driver는 physical DMA memory를 효율적으로 쓰기 위해 data buffer마다 virtual하게는 연속이지만 physical하게는 여러 조각인 memory를 할당하는 경향이 있습니다. Linux는 이를 위한 SGL(scatter gather list) API를 제공합니다. THC는 OS kernel SGL의 virtual-to-physical mapping을 PRD table로 표현합니다.

PRD table base address는 여러 PRD table을 가리키고, 각 table은 PRD Entry #1부터 #n까지를 포함합니다.

Read DMA engine은 circular buffer 안의 여러 PRD table을 지원합니다. Host software가 여러 data buffer로 engine을 미리 arm할 수 있어 CPU가 touch frame을 처리하는 속도보다 Touch IC의 송신 속도가 빠른 경우에도 software 개입 없이 여러 frame을 받을 수 있습니다.

설계를 단순화하려고 software는 최악의 memory fragmentation을 가정합니다. 모든 PRD table은 같은 수의 PRD entry를 가져야 하므로 Touch IC별 global register 하나가 table당 entry 수를 보관할 수 있습니다.

Software는 `THC_M_PRT_RPRD_CNTRL.PCD` field에 지정된 대로 Read DMA engine마다 최대 128개 PRD table을 할당합니다. Table 수는 data buffer 수와 같아야 합니다. OS memory의 최대 fragmentation boundary가 4KB이므로 virtual 1MB를 표현하려면 table 하나에 PRD entry 256개가 필요합니다. Table당 entry 수는 `THC_M_PRT_RPRD_CNTRL.PTEC`에 쓰고, 마지막 entry를 제외한 entry length는 4KB의 배수여야 합니다. Data buffer와 PRD table은 host initialization 때 한 번만 할당합니다.

PRD table이 circular buffer(CB)로 구성되므로 read pointer와 write pointer가 필요합니다. DMA hardware는 EOP bit가 설정된 entry를 만날 때까지 entry를 하나씩 소비한 뒤 PRD read pointer를 증가시킵니다. Read pointer는 현재 DMA engine이 처리하는 PRD를 가리키며 CB depth를 돌면 bit 7을 rollover bit로 사용합니다. Depth 4이면 `00h 01h 02h 03h 80h 81h 82h 83h 00h...` 순서입니다.

Write pointer는 software가 갱신하며 다음 PRD table을 저장할 CB 위치를 가리킵니다. Software도 depth를 다 돌면 bit 7을 rollover bit로 처리해야 합니다. Depth 5이면 `00h 01h 02h 03h 04h 80h 81h 82h 83h 84h 00h...` 순서입니다.

PRD 규모와 제약
항목의미
Read DMA PRD tables최대 128Data buffer 수와 동일
PRD entries per table최대 2564KB 조각으로 1MB 표현
Entry length4KB 배수마지막 entry는 예외
PCDTHC_M_PRT_RPRD_CNTRL.PCDPRD table 수·depth 관련 field
PTECTHC_M_PRT_RPRD_CNTRL.PTECTable당 PRD entry 수
Rolloverbit 7Circular pointer의 wrap 세대 구분

Circular buffer와 scatter-gather mapping의 핵심 수치입니다.

PRD circular buffer 소비
Host initialization에서 data buffer와 PRD table 할당SGL의 physical fragment를 PRD entry로 기록Software가 다음 table 위치까지 write pointer 갱신DMA hardware가 entry를 순서대로 소비EOP entry에서 frame 완료 후 read pointer 증가CB depth 끝에서 bit 7을 바꾸어 rollover

Hardware read pointer와 software write pointer가 독립적으로 움직입니다.

3.4 PRD
-------

Physical Region Descriptor (PRD) provides the memory mapping description for THC DMAs.

3.4.1 PRD table and entry
~~~~~~~~~~~~~~~~~~~~~~~~~

In order to improve physical DMA memory usage, modern drivers trend to allocate a virtually
contiguous, but physically fragmented buffer of memory for each data buffer. Linux OS also
provide SGL (scatter gather list) APIs to support this usage.

THC uses PRD table (physical region descriptor) to support the corresponding OS kernel
SGL that describes the virtual to physical buffer mapping.

::

  ------------------------      --------------       --------------
 | PRD table base address +----+ PRD table #1 +-----+ PRD Entry #1 |
  ------------------------      --------------       --------------
                                                     --------------
                                                    | PRD Entry #2 |
                                                     --------------
                                                     --------------
                                                    | PRD Entry #n |
                                                     --------------

The read DMA engine supports multiple PRD tables held within a circular buffer that allow the THC
to support multiple data buffers from the Touch IC. This allows host SW to arm the Read DMA engine
with multiple buffers, allowing the Touch IC to send multiple data frames to the THC without SW
interaction. This capability is required when the CPU processes touch frames slower than the
Touch IC can send them.

To simplify the design, SW assumes worst-case memory fragmentation. Therefore,each PRD table shall
contain the same number of PRD entries, allowing for a global register (per Touch IC) to hold the
number of PRD-entries per PRD table.

SW allocates up to 128 PRD tables per Read DMA engine as specified in the THC_M_PRT_RPRD_CNTRL.PCD
register field. The number of PRD tables should equal the number of data buffers.

Max OS memory fragmentation will be at a 4KB boundary, thus to address 1MB of virtually contiguous
memory 256 PRD entries are required for a single PRD Table. SW writes the number of PRD entries
for each PRD table in the THC_M_PRT_RPRD_CNTRL.PTEC register field. The PRD entry's length must be
multiple of 4KB except for the last entry in a PRD table.

SW allocates all the data buffers and PRD tables only once at host initialization.

3.4.2 PRD Write pointer and read pointer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As PRD tables are organized as a Circular Buffer (CB), a read pointer and a write pointer for a CB
are needed.

DMA HW consumes the PRD tables in the CB, one PRD entry at a time until the EOP bit is found set
in a PRD entry. At this point HW increments the PRD read pointer. Thus, the read pointer points
to the PRD which the DMA engine is currently processing. This pointer rolls over once the circular
buffer's depth has been traversed with bit[7] the Rollover bit. E.g. if the DMA CB depth is equal
to 4 entries (0011b), then the read pointers will follow this pattern (HW is required to honor
this behavior): 00h 01h 02h 03h 80h 81h 82h 83h 00h 01h ...

The write pointer is updated by SW. The write pointer points to location in the DMA CB, where the
next PRD table is going to be stored. SW needs to ensure that this pointer rolls over once the
circular buffer's depth has been traversed with Bit[7] as the rollover bit. E.g. if the DMA CB
depth is equal to 5 entries (0100b), then the write pointers will follow this pattern (SW is
required to honor this behavior): 00h 01h 02h 03h 04h 80h 81h 82h 83h 84h 00h 01h ..

128-bit PRD descriptor 구조

421-457

Intel THC는 모든 PRD entry에 PRD entry descriptor를 사용하며 descriptor 하나는 128 bits입니다.

`dest_addr`는 bit 53..0의 destination memory address입니다. 원문은 각 entry가 4KB이므로 address의 lowest 10 bits를 무시한다고 설명합니다. Bit 54..62는 `reserved1`입니다.

Bit 63의 `int_on_completion`은 completion interrupt enable bit이며 software driver가 설정합니다. Bit 87..64의 `len`은 entry에 든 data byte 수입니다. Bit 88의 `end_of_prd`는 PRD table의 마지막 entry임을 나타내며 software driver가 설정합니다. Bit 90..89는 `hw_status`, bit 127..91은 `reserved2`입니다.

PRD table 하나에는 최대 256 entry가 들어가고 각 entry가 4KB를 표현하므로 table 하나가 1MB memory를 기술할 수 있습니다. C 구조체 `struct thc_prd_table`은 `struct thc_prd_entry entries[PRD_ENTRIES_NUM]` 배열을 포함합니다.

일반적으로 PRD table 하나는 HID touch data packet 하나를 뜻합니다. DMA engine마다 최대 128개 table을 지원하지만 write DMA는 table 하나만 가집니다. Software driver는 Touch IC에서 max packet length를 얻어 그 크기에 맞게 각 table의 PRD entry를 만들어야 합니다.

PRD entry descriptor
FieldBits설명
dest_addr53..0Destination memory address
reserved162..54Reserved
int_on_completion63Software가 설정하는 completion interrupt enable
len87..64Entry의 data byte 수
end_of_prd88Software가 설정하는 table 마지막 entry 표시
hw_status90..89Hardware status
reserved2127..91Reserved

128-bit descriptor의 field layout을 보존했습니다.

Packet용 PRD table 생성
Touch IC descriptor에서 max packet length 읽기필요한 4KB physical fragment 수 계산각 fragment의 dest_addr와 len 기록필요하면 int_on_completion 설정마지막 entry에 end_of_prd 설정PRD table을 해당 DMA engine circular buffer에 배치

Touch IC의 최대 packet 길이로 table을 준비합니다.

3.4.3 PRD descriptor structure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Intel THC uses PRD entry descriptor for every PRD entry. Every PRD entry descriptor occupies
128 bits memories:

===================   ========   ===============================================
struct field          bit(s)     description
===================   ========   ===============================================
dest_addr             53..0      destination memory address, as every entry
                                 is 4KB, ignore lowest 10 bits of address.
reserved1             54..62     reserved
int_on_completion     63         completion interrupt enable bit, if this bit
                                 set it means THC will trigger a completion
                                 interrupt. This bit is set by SW driver.
len                   87..64     how many bytes of data in this entry.
end_of_prd            88         end of PRD table bit, if this bit is set,
                                 it means this entry is last entry in this PRD
                                 table. This bit is set by SW driver.
hw_status             90..89     HW status bits
reserved2             127..91    reserved
===================   ========   ===============================================

And one PRD table can include up to 256 PRD entries, as every entries is 4K bytes, so every
PRD table can describe 1M bytes memory.

.. code-block:: c

   struct thc_prd_table {
        struct thc_prd_entry entries[PRD_ENTRIES_NUM];
   };

In general, every PRD table means one HID touch data packet. Every DMA engine can support
up to 128 PRD tables (except write DMA, write DMA only has one PRD table). SW driver is responsible
to get max packet length from touch IC, and use this max packet length to create PRD entries for
each PRD table.

HIDSPI QuickSPI reset·input·output flow

458-519

Intel THC는 HIDSPI protocol과 완전히 호환되며 THC HW sequencer가 HIDSPI transfer를 가속합니다.

Reset flow는 ACPI `_RST` method로 Touch IC를 reset하고 PIO read로 TIC reset response를 받는 것으로 시작합니다. PIO write로 device descriptor 요청 command를 보내고 PIO read로 descriptor를 가져옵니다. Descriptor가 유효하면 DMA buffer를 할당하고 모든 DMA channel을 설정한 뒤 DMA로 report descriptor 요청 command를 보냅니다.

Input report의 기본 흐름에서 Touch IC는 in-band THC interrupt로 Controller를 깨웁니다. Sequencer는 read approval을 전송하면서 input report header를 읽어 Touch IC가 host read를 준비하도록 합니다. Header의 `Input Report Length` 값에 맞춰 Input Report Body Read를 수행합니다.

DMA engine은 sequencer의 data를 가져와 현재 CB PRD table의 PRD entry 0부터 host memory에 씁니다. Sequencer가 모든 data를 읽었다고 알리거나 DMA Read Engine이 마지막 PRD entry 끝에 도달할 때까지, 또는 두 조건이 모두 충족될 때까지 계속합니다.

Sequencer는 Input Report Header의 `Last Fragment Flag`를 확인합니다. Flag가 clear이면 idle state에 들어가고, enable이면 End-of-Frame Processing에 들어갑니다.

End-of-Frame에서 DMA engine은 Read PRD CB의 read pointer를 증가시키고 RxDMA2 register `THC_M_PRT_READ_DMA_INT_STS_2`에 EOF interrupt status를 설정합니다. Driver가 `THC_M_PRT_READ_DMA_CNTRL_2`에서 EOF interrupt를 enable했다면 software interrupt를 발생시킵니다.

QuickSPI driver는 CB write pointer와 read pointer를 비교해 DMA circular buffer에 frame이 있는지 확인합니다. 첫 unprocessed PRD table을 가져와 모든 entry를 scan하여 전체 frame size를 계산하고 data를 복사합니다. Input report body의 data type을 확인해 관련 callback을 호출한 뒤 write pointer를 갱신합니다.

Output report에서는 HID core가 `raw_request` callback으로 QuickSPI driver에 요청합니다. Driver는 data를 output-report packet으로 변환해 THC write DMA buffer에 복사하고 TxDMA를 시작하여 write를 완료합니다.

QuickSPI 단계
FlowOperationTransport
ResetACPI _RST · reset responseACPI + PIO read
DescriptorDevice descriptor request/readPIO write + PIO read
Report descriptorDescriptor 유효 뒤 요청DMA
Input header/bodyRead approval · Input Report LengthSequencer + RxDMA2
EOFPRD pointer 증가 · EOF statusTHC_M_PRT_READ_DMA_INT_STS_2
Outputraw_request · packet 변환Write DMA / TxDMA

Reset과 input·output의 핵심 operation입니다.

QuickSPI input report
Touch IC가 in-band THC interrupt 발생Sequencer가 read approval과 header read 수행Input Report Length만큼 body readRxDMA2가 PRD entry를 따라 host memory에 기록Last Fragment Flag에 따라 idle 또는 EOF 처리QuickSPI driver가 frame size 계산·data 복사Data type별 callback 호출 후 CB write pointer 갱신

Interrupt에서 HID callback까지의 전체 경로입니다.

4. HIDSPI support (QuickSPI)
============================

Intel THC is total compatible with HIDSPI protocol, THC HW sequenser can accelerate HIDSPI
protocol transferring.

4.1 Reset Flow
--------------

- Call ACPI _RST method to reset Touch IC device.
- Read the reset response from TIC through PIO read.
- Issue a command to retrieve device descriptor from Touch IC through PIO write.
- Read the device descriptor from Touch IC through PIO read.
- If the device descriptor is valid, allocate DMA buffers and configure all DMA channels.
- Issue a command to retrieve report descriptor from Touch IC through DMA.

4.2 Input Report Data Flow
--------------------------

Basic Flow:

- Touch IC interrupts the THC Controller using an in-band THC interrupt.
- THC Sequencer reads the input report header by transmitting read approval as a signal
  to the Touch IC to prepare for host to read from the device.
- THC Sequencer executes a Input Report Body Read operation corresponding to the value
  reflected in “Input Report Length” field of the Input Report Header.
- THC DMA engine begins fetching data from the THC Sequencer and writes to host memory
  at PRD entry 0 for the current CB PRD table entry. This process continues until the
  THC Sequencer signals all data has been read or the THC DMA Read Engine reaches the
  end of it's last PRD entry (or both).
- The THC Sequencer checks for the “Last Fragment Flag” bit in the Input Report Header.
  If it is clear, the THC Sequencer enters an idle state.
- If the “Last Fragment Flag” bit is enabled the THC Sequencer enters End-of-Frame Processing.

THC Sequencer End of Frame Processing:

- THC DMA engine increments the read pointer of the Read PRD CB, sets EOF interrupt status
  in RxDMA2 register (THC_M_PRT_READ_DMA_INT_STS_2).
- If THC EOF interrupt is enabled by the driver in the control register (THC_M_PRT_READ_DMA_CNTRL_2),
  generates interrupt to software.

Sequence of steps to read data from RX DMA buffer:

- THC QuickSPI driver checks CB write Ptr and CB read Ptr to identify if any data frame in DMA
  circular buffers.
- THC QuickSPI driver gets first unprocessed PRD table.
- THC QuickSPI driver scans all PRD entries in this PRD table to calculate the total frame size.
- THC QuickSPI driver copies all frame data out.
- THC QuickSPI driver checks the data type according to input report body, and calls related
  callbacks to process the data.
- THC QuickSPI driver updates write Ptr.

4.3 Output Report Data Flow
---------------------------

Generic Output Report Flow:

- HID core calls raw_request callback with a request to THC QuickSPI driver.
- THC QuickSPI Driver converts request provided data into the output report packet and copies it
  to THC's write DMA buffer.
- Start TxDMA to complete the write operation.

HIDI2C QuickI2C reset·input·output flow

520-584

QuickI2C reset flow는 PIO write-followed-by-read로 Touch IC의 device descriptor를 읽는 것으로 시작합니다. Descriptor가 유효하면 DMA buffer를 할당하고 모든 DMA channel을 설정합니다.

PIO 또는 TxDMA로 TIC command register에 `SET_POWER` request를 쓰고 성공 여부를 확인합니다. 같은 방식으로 `RESET` request를 쓰며 성공하면 TIC reset response를 기다립니다. Report descriptor는 SWDMA를 사용해 TIC report-descriptor register에서 읽습니다.

Input report에서는 Touch IC가 host에 보낼 interrupt가 있음을 나타내는 interrupt line을 assert합니다. THC Sequencer가 I2C READ request를 보내면 HIDI2C device가 수신 data 길이가 든 첫 2 bytes를 반환합니다. Sequencer는 length field가 나타낸 크기만큼 read를 계속합니다.

THC DMA engine은 sequencer에서 data를 가져와 현재 CB PRD table의 entry 0부터 host memory에 기록합니다. RxDMA buffer에는 2-byte length field와 나머지 data를 함께 씁니다. Sequencer가 모든 data를 읽었거나 DMA Read Engine이 마지막 PRD entry 끝에 도달할 때까지 계속한 뒤 End-of-Input Report Processing에 들어갑니다.

Device에 추가 input report가 없으면 interrupt line을 de-assert합니다. 더 있으면 line을 assert한 채로 유지하고 앞의 read 절차를 반복합니다.

End-of-Input Report에서 DMA engine은 Read PRD CB read pointer를 증가시키고 RxDMA2 register `THC_M_PRT_READ_DMA_INT_STS_2`에 EOF status를 설정합니다. `THC_M_PRT_READ_DMA_CNTRL_2`에서 EOF interrupt가 enable되어 있으면 software interrupt를 발생시킵니다.

QuickI2C driver는 CB write/read pointer를 비교하고 첫 unprocessed PRD table을 가져옵니다. Entry를 모두 scan해 frame size를 계산하고 data를 복사합니다. 원본 data의 length field는 제거하고 `Report ID + Report Data Content`를 `hid_input_report`로 HID core에 보낸 뒤 write pointer를 갱신합니다.

Output report에서는 HID core가 QuickI2C `raw_request` callback을 호출합니다. Driver는 PIO 또는 TXDMA로 TIC command register에 `SET_REPORT` request를 쓰며 report type을 Output으로 설정합니다. TIC data register에 쓸 TX data를 TxDMA buffer에 구성할 때 첫 2 bytes는 report length이고, 뒤에는 Report ID를 포함한 report content가 옵니다.

QuickI2C packet 처리
FlowCommand·data처리
ResetSET_POWER · RESETPIO 또는 TxDMA, reset response 대기
Report descriptorTIC report descriptor registerSWDMA read
Input prefix첫 2 bytesInput report length
Input bodyLength + remaining dataRxDMA buffer에 기록
HID 전달Report ID + Report Data ContentLength field 제거 후 hid_input_report
OutputSET_REPORT type=Output2-byte length + Report ID + content

HIDI2C의 2-byte length field가 input과 output 모두에 관여합니다.

QuickI2C input report
Touch IC가 interrupt line assertSequencer가 I2C READ로 2-byte length 획득Length만큼 remaining data readRxDMA가 length와 data를 PRD buffer에 기록EOF status와 선택적 software interrupt 발생Driver가 length field를 제거하고 hid_input_report 호출추가 report가 있으면 interrupt를 유지하고 반복

Assert된 interrupt가 유지되면 여러 report를 연속 처리합니다.

5. HIDI2C support (QuickI2C)
============================

5.1 Reset Flow
--------------

- Read device descriptor from Touch IC device through PIO write followed by read.
- If the device descriptor is valid, allocate DMA buffers and configure all DMA channels.
- Use PIO or TxDMA to write a SET_POWER request to TIC's command register, and check if the
  write operation is successfully completed.
- Use PIO or TxDMA to write a RESET request to TIC's command register. If the write operation
  is successfully completed, wait for reset response from TIC.
- Use SWDMA to read report descriptor through TIC's report descriptor register.

5.2 Input Report Data Flow
--------------------------

Basic Flow:

- Touch IC asserts the interrupt indicating that it has an interrupt to send to HOST.
  THC Sequencer issues a READ request over the I2C bus. The HIDI2C device returns the
  first 2 bytes from the HIDI2C device which contains the length of the received data.
- THC Sequencer continues the Read operation as per the size of data indicated in the
  length field.
- THC DMA engine begins fetching data from the THC Sequencer and writes to host memory
  at PRD entry 0 for the current CB PRD table entry. THC writes 2Bytes for length field
  plus the remaining data to RxDMA buffer. This process continues until the THC Sequencer
  signals all data has been read or the THC DMA Read Engine reaches the end of it's last
  PRD entry (or both).
- THC Sequencer enters End-of-Input Report Processing.
- If the device has no more input reports to send to the host, it de-asserts the interrupt
  line. For any additional input reports, device keeps the interrupt line asserted and
  steps 1 through 4 in the flow are repeated.

THC Sequencer End of Input Report Processing:

- THC DMA engine increments the read pointer of the Read PRD CB, sets EOF interrupt status
  in RxDMA 2 register (THC_M_PRT_READ_DMA_INT_STS_2).
- If THC EOF interrupt is enabled by the driver in the control register
  (THC_M_PRT_READ_DMA_CNTRL_2), generates interrupt to software.

Sequence of steps to read data from RX DMA buffer:

- THC QuickI2C driver checks CB write Ptr and CB read Ptr to identify if any data frame in DMA
  circular buffers.
- THC QuickI2C driver gets first unprocessed PRD table.
- THC QuickI2C driver scans all PRD entries in this PRD table to calculate the total frame size.
- THC QuickI2C driver copies all frame data out.
- THC QuickI2C driver call hid_input_report to send the input report content to HID core, which
  includes Report ID + Report Data Content (remove the length field from the original report
  data).
- THC QuickI2C driver updates write Ptr.

5.3 Output Report Data Flow
---------------------------

Generic Output Report Flow:

- HID core call THC QuickI2C raw_request callback.
- THC QuickI2C uses PIO or TXDMA to write a SET_REPORT request to TIC's command register. Report
  type in SET_REPORT should be set to Output.
- THC QuickI2C programs TxDMA buffer with TX Data to be written to TIC's data register. The first
  2 bytes should indicate the length of the report followed by the report contents including
  Report ID.

THC tracing과 protocol reference

585-596

THC debugging에는 event tracing mechanism을 사용합니다. `echo 1 > /sys/kernel/debug/tracing/events/intel_thc/enable`로 event를 활성화하고 `cat /sys/kernel/debug/tracing/trace`로 trace buffer를 읽습니다.

참고 protocol은 Microsoft의 HIDSPI specification `HidSpiProtocolSpec.pdf`와 HID over I2C protocol specification v1.0 문서입니다. 원문에는 두 download URL이 그대로 제공됩니다.

THC debug·reference
항목
Trace enable/sys/kernel/debug/tracing/events/intel_thc/enable
Trace output/sys/kernel/debug/tracing/trace
HIDSPIHidSpiProtocolSpec.pdf
HIDI2Chid-over-i2c-protocol-spec-v1-0.docx

Tracing node와 protocol 문서를 구분했습니다.

THC event trace
intel_thc event enable node에 1 기록QuickSPI 또는 QuickI2C 문제 재현Kernel tracing buffer 읽기PIO·DMA·interrupt event 순서 분석필요하면 HIDSPI/HIDI2C specification 대조

문제를 재현하기 전에 trace event를 활성화합니다.

6. THC Debugging
================

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
============
- 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