From 7b88f21dac8dfa7f9b943efbac5a0ee0e025bdc2 Mon Sep 17 00:00:00 2001 From: ferrreo Date: Mon, 24 Apr 2023 12:43:21 +0100 Subject: [PATCH] Linux 6.3 release --- main.sh | 6 +- patches/0001-Add-legion-laptop-v0.1.patch | 942 +- patches/0001-cachy-all.patch | 11850 +++++++++++++++- patches/0002-eevdf.patch | 233 +- patches/0003-bore.patch | 424 - patches/surface/0001-surface3-oemb.patch | 101 + patches/surface/0002-mwifiex.patch | 400 + patches/surface/0003-ath10k.patch | 121 + patches/surface/0004-ipts.patch | 2988 ++++ patches/surface/0005-ithc.patch | 1433 ++ patches/surface/0006-surface-sam.patch | 2065 +++ .../surface/0007-surface-sam-over-hid.patch | 335 + patches/surface/0008-surface-button.patch | 149 + patches/surface/0009-surface-typecover.patch | 574 + patches/surface/0010-surface-shutdown.patch | 97 + patches/surface/0011-surface-gpe.patch | 51 + patches/surface/0012-cameras.patch | 2943 ++++ patches/surface/0013-amd-gpio.patch | 109 + patches/surface/0014-rtc.patch | 109 + scripts/patch.sh | 4 +- scripts/source.sh | 6 +- 21 files changed, 23564 insertions(+), 1376 deletions(-) delete mode 100644 patches/0003-bore.patch create mode 100644 patches/surface/0001-surface3-oemb.patch create mode 100644 patches/surface/0002-mwifiex.patch create mode 100644 patches/surface/0003-ath10k.patch create mode 100644 patches/surface/0004-ipts.patch create mode 100644 patches/surface/0005-ithc.patch create mode 100644 patches/surface/0006-surface-sam.patch create mode 100644 patches/surface/0007-surface-sam-over-hid.patch create mode 100644 patches/surface/0008-surface-button.patch create mode 100644 patches/surface/0009-surface-typecover.patch create mode 100644 patches/surface/0010-surface-shutdown.patch create mode 100644 patches/surface/0011-surface-gpe.patch create mode 100644 patches/surface/0012-cameras.patch create mode 100644 patches/surface/0013-amd-gpio.patch create mode 100644 patches/surface/0014-rtc.patch diff --git a/main.sh b/main.sh index baba420..a96c2a0 100755 --- a/main.sh +++ b/main.sh @@ -2,6 +2,6 @@ . ./scripts/source.sh . ../scripts/patch.sh -. ../scripts/config.sh -. ../scripts/build.sh -. ../scripts/output.sh +# . ../scripts/config.sh +# . ../scripts/build.sh +# . ../scripts/output.sh diff --git a/patches/0001-Add-legion-laptop-v0.1.patch b/patches/0001-Add-legion-laptop-v0.1.patch index fe165a1..c0a5478 100644 --- a/patches/0001-Add-legion-laptop-v0.1.patch +++ b/patches/0001-Add-legion-laptop-v0.1.patch @@ -1,14 +1,14 @@ -From cc665be20697f44218f895e596fec00025965d5b Mon Sep 17 00:00:00 2001 +From 5a8cfba07126140f91bd48af08c56757b05baa1a Mon Sep 17 00:00:00 2001 From: John Martens -Date: Fri, 27 Jan 2023 10:54:22 +0000 +Date: Sun, 2 Apr 2023 16:39:30 +0000 Subject: [PATCH] Add legion-laptop v0.1 Add extra support for Lenovo Legion laptops. --- drivers/platform/x86/Kconfig | 10 + drivers/platform/x86/Makefile | 1 + - drivers/platform/x86/legion-laptop.c | 3029 ++++++++++++++++++++++++++ - 3 files changed, 3040 insertions(+) + drivers/platform/x86/legion-laptop.c | 2783 ++++++++++++++++++++++++++ + 3 files changed, 2794 insertions(+) create mode 100644 drivers/platform/x86/legion-laptop.c diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig @@ -18,7 +18,7 @@ index f5312f51d..74e24e5ab 100644 @@ -683,6 +683,16 @@ config THINKPAD_LMI To compile this driver as a module, choose M here: the module will be called think-lmi. - + +config LEGION_LAPTOP + tristate "Lenovo Legion Laptop Extras" + depends on ACPI @@ -30,7 +30,7 @@ index f5312f51d..74e24e5ab 100644 + hotkey, fan control, and power mode. + source "drivers/platform/x86/intel/Kconfig" - + config MSI_LAPTOP diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile index 5a428caa6..cfd07f9f3 100644 @@ -41,15 +41,15 @@ index 5a428caa6..cfd07f9f3 100644 obj-$(CONFIG_THINKPAD_ACPI) += thinkpad_acpi.o obj-$(CONFIG_THINKPAD_LMI) += think-lmi.o +obj-$(CONFIG_LEGION_LAPTOP) += legion-laptop.o - + # Intel obj-y += intel/ diff --git a/drivers/platform/x86/legion-laptop.c b/drivers/platform/x86/legion-laptop.c new file mode 100644 -index 000000000..6edfeffcc +index 000000000..d1268d239 --- /dev/null +++ b/drivers/platform/x86/legion-laptop.c -@@ -0,0 +1,3029 @@ +@@ -0,0 +1,2783 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * legion-laptop.c - Extra Lenovo Legion laptop support, in @@ -141,8 +141,6 @@ index 000000000..6edfeffcc + ec_readonly, + "Only read from embedded controller but do not write or change settings."); + -+//TODO: remove this, kernel modules do not have versions -+#define MODULEVERSION "0.1" +#define LEGIONFEATURES \ + "fancurve powermode platformprofile platformprofilenotify minifancurve" + @@ -179,117 +177,67 @@ index 000000000..6edfeffcc + */ +// TODO: same order as in initialization +struct ec_register_offsets { -+ u16 ECINDAR0; -+ u16 ECINDAR1; -+ u16 ECINDAR2; -+ u16 ECINDAR3; -+ u16 ECINDDR; -+ u16 GPDRA; -+ u16 GPCRA0; -+ u16 GPCRA1; -+ u16 GPCRA2; -+ u16 GPCRA3; -+ u16 GPCRA4; -+ u16 GPCRA5; -+ u16 GPCRA6; -+ u16 GPCRA7; -+ u16 GPOTA; -+ u16 GPDMRA; -+ u16 DCR0; -+ u16 DCR1; -+ u16 DCR2; -+ u16 DCR3; -+ u16 DCR4; -+ u16 DCR5; -+ u16 DCR6; -+ u16 DCR7; -+ u16 CTR2; ++ // Super I/O Configuration Registers ++ // 7.15 General Control (GCTRL) ++ // General Control (GCTRL) ++ // (see EC Interface Registers and 6.2 Plug and Play Configuration (PNPCFG)) in datasheet ++ // note: these are in two places saved ++ // in EC Interface Registers and in super io configuraion registers ++ // Chip ID + u16 ECHIPID1; + u16 ECHIPID2; ++ // Chip Version + u16 ECHIPVER; + u16 ECDEBUG; -+ u16 EADDR; -+ u16 EDAT; -+ u16 ECNT; -+ u16 ESTS; -+ u16 FW_VER; -+ u16 FAN_CUR_POINT; -+ u16 FAN_POINTS_SIZE; -+ u16 FAN1_BASE; -+ u16 FAN2_BASE; -+ u16 FAN_ACC_BASE; -+ u16 FAN_DEC_BASE; -+ u16 CPU_TEMP; -+ u16 CPU_TEMP_HYST; -+ u16 GPU_TEMP; -+ u16 GPU_TEMP_HYST; -+ u16 VRM_TEMP; -+ u16 VRM_TEMP_HYST; -+ u16 CPU_TEMP_EN; -+ u16 GPU_TEMP_EN; -+ u16 VRM_TEMP_EN; -+ u16 FAN1_ACC_TIMER; -+ u16 FAN2_ACC_TIMER; -+ u16 FAN1_CUR_ACC; -+ u16 FAN1_CUR_DEC; -+ u16 FAN2_CUR_ACC; -+ u16 FAN2_CUR_DEC; -+ u16 FAN1_RPM_LSB; -+ u16 FAN1_RPM_MSB; -+ u16 FAN2_RPM_LSB; -+ u16 FAN2_RPM_MSB; + -+ u16 F1TLRR; -+ u16 F1TMRR; -+ u16 F2TLRR; -+ u16 F2TMRR; -+ u16 CTR1; -+ u16 CTR3; -+ u16 FAN1CNF; -+ u16 FAN2CNF; -+ -+ // altnerive regsisters -+ // TODO: decide on one version -+ u16 FAN1_TARGET_RPM; -+ u16 FAN2_TARGET_RPM; -+ u16 ALT_CPU_TEMP; -+ u16 ALT_GPU_TEMP; -+ u16 ALT_POWERMODE; -+ -+ u16 ALT_FAN1_RPM; -+ u16 ALT_FAN2_RPM; -+ u16 ALT_CPU_TEMP2; -+ u16 ALT_GPU_TEMP2; -+ u16 ALT_IC_TEMP2; -+ -+ u16 MINIFANCURVE_ON_COOL; -+ u16 LOCKFANCONTROLLER; -+ u16 MAXIMUMFANSPEED; -+}; -+ -+enum ECRAM_ACCESS { ECRAM_ACCESS_PORTIO, ECRAM_ACCESS_MEMORYIO }; -+ -+enum CONTROL_METHOD { -+ // control EC by readin/writing to EC memory -+ CONTROL_METHOD_ECRAM, -+ // control EC only by ACPI calls -+ CONTROL_METHOD_ACPI ++ // Lenovo Custom OEM extension ++ // Firmware of ITE can be extended by ++ // custom program using its own "variables" ++ // These are the offsets to these "variables" ++ u16 EXT_FAN_CUR_POINT; ++ u16 EXT_FAN_POINTS_SIZE; ++ u16 EXT_FAN1_BASE; ++ u16 EXT_FAN2_BASE; ++ u16 EXT_FAN_ACC_BASE; ++ u16 EXT_FAN_DEC_BASE; ++ u16 EXT_CPU_TEMP; ++ u16 EXT_CPU_TEMP_HYST; ++ u16 EXT_GPU_TEMP; ++ u16 EXT_GPU_TEMP_HYST; ++ u16 EXT_VRM_TEMP; ++ u16 EXT_VRM_TEMP_HYST; ++ u16 EXT_FAN1_RPM_LSB; ++ u16 EXT_FAN1_RPM_MSB; ++ u16 EXT_FAN2_RPM_LSB; ++ u16 EXT_FAN2_RPM_MSB; ++ u16 EXT_FAN1_TARGET_RPM; ++ u16 EXT_FAN2_TARGET_RPM; ++ u16 EXT_POWERMODE; ++ u16 EXT_MINIFANCURVE_ON_COOL; ++ // values ++ // 0x04: enable mini fan curve if very long on cool level ++ // - this might be due to potential temp failure ++ // - or just because really so cool ++ // 0xA0: disable it ++ u16 EXT_LOCKFANCONTROLLER; ++ u16 EXT_MAXIMUMFANSPEED; ++ u16 EXT_WHITE_KEYBOARD_BACKLIGHT; ++ u16 EXT_IC_TEMP_INPUT; ++ u16 EXT_CPU_TEMP_INPUT; ++ u16 EXT_GPU_TEMP_INPUT; +}; + +struct model_config { + const struct ec_register_offsets *registers; + bool check_embedded_controller_id; + u16 embedded_controller_id; -+ // how should the EC be acesses? -+ enum CONTROL_METHOD access_method; + -+ // if EC is accessed by RAM, how sould it be access -+ enum ECRAM_ACCESS ecram_access_method; -+ -+ // if EC is accessed by memory mapped, what is its address -+ phys_addr_t memoryio_physical_start; ++ // first addr in EC we access/scan + phys_addr_t memoryio_physical_ec_start; + size_t memoryio_size; ++ ++ // TODO: maybe use bitfield ++ bool has_minifancurve; +}; + +/* =================================== */ @@ -300,188 +248,77 @@ index 000000000..6edfeffcc +// - all default names and register addresses are supported by datasheet +// - register addresses for custom firmware by SmokelesssCPU +static const struct ec_register_offsets ec_register_offsets_v0 = { -+ // 6.3 Shared Memory Flash Interface Bridge (SMFI) -+ // "The SMFI provides an HLPC interface between the host bus a -+ // and the M bus. The flash is mapped into the -+ // host memory address space for host accesses. The flash is also -+ // mapped into the EC memory address space for EC accesses" -+ .ECINDAR0 = 0x103B, -+ .ECINDAR1 = 0x103C, -+ .ECINDAR2 = 0x103D, -+ .ECINDAR3 = 0x103E, -+ .ECINDDR = 0x103F, -+ -+ // 7.5 General Purpose I/O Port (GPIO) -+ // I/O pins controlled by registers. -+ .GPDRA = 0x1601, -+ // port data, i.e. data to output to pins -+ // or data read from pins -+ .GPCRA0 = 0x1610, -+ // control register for each pin, -+ // set as input, output, ... -+ .GPCRA1 = 0x1611, -+ .GPCRA2 = 0x1612, -+ .GPCRA3 = 0x1613, -+ .GPCRA4 = 0x1614, -+ .GPCRA5 = 0x1615, -+ .GPCRA6 = 0x1616, -+ .GPCRA7 = 0x1617, -+ .GPOTA = 0x1671, -+ .GPDMRA = 0x1661, -+ -+ // Super I/O Configuration Registers -+ // 7.15 General Control (GCTRL) -+ // General Control (GCTRL) -+ // (see EC Interface Registers and 6.2 Plug and Play Configuration (PNPCFG)) in datasheet -+ // note: these are in two places saved -+ // in EC Interface Registers and in super io configuraion registers -+ // Chip ID -+ .ECHIPID1 = 0x2000, // 0x20 -+ .ECHIPID2 = 0x2001, // 0x21 -+ // Chip Version -+ .ECHIPVER = 0x2002, // 0x22 -+ .ECDEBUG = 0x2003, //0x23 SIOCTRL (super io control) -+ -+ // External GPIO Controller (EGPC) -+ // 7.16 External GPIO Controller (EGPC) -+ // Communication with an external GPIO chip -+ // (IT8301) -+ // Address -+ .EADDR = 0x2100, -+ // Data -+ .EDAT = 0x2101, -+ // Control -+ .ECNT = 0x2102, -+ // Status -+ .ESTS = 0x2103, -+ -+ // FAN/PWM control by ITE -+ // 7.11 PWM -+ // - lower powered ITEs just come with PWM -+ // control -+ // - higher powered ITEs, e.g. ITE8511, come -+ // from ITE with a fan control software -+ // in ROM with 3 (or 4) fan curve points -+ // called SmartAuto Fan Control -+ // - in Lenovo Legion Laptop the SmartAuto -+ // is not used, but the fan is controlled -+ // by a custom program flashed on the ITE -+ // chip -+ -+ // duty cycle of each PWM output -+ .DCR0 = 0x1802, -+ .DCR1 = 0x1803, -+ .DCR2 = 0x1804, -+ .DCR3 = 0x1805, -+ .DCR4 = 0x1806, -+ .DCR5 = 0x1807, -+ .DCR6 = 0x1808, -+ .DCR7 = 0x1809, -+ // FAN1 tachometer (least, most signficant byte) -+ .F1TLRR = 0x181E, -+ .F1TMRR = 0x181F, -+ // FAN1 tachometer (least, most signficant byte) -+ .F2TLRR = 0x1820, -+ .F2TLRR = 0x1821, -+ // cycle time, i.e. clock prescaler for PWM signal -+ .CTR1 = 0x1842, -+ .CTR2 = 0x1842, -+ .CTR3 = 0x1842, -+ -+ // bits 7-6 (higest bit) -+ // 00: SmartAuto mode 0 (temperature controlled) -+ // 01: SmartAuto mode 1 (temperaute replaced by a register value) -+ // 10: manual mode -+ // bits: 4-2 -+ // PWM output channel used for ouput (0-7 by 3 bits) -+ .FAN1CNF = 0x1810, -+ // spin up time (duty cycle = 100% for this time when fan stopped) -+ // 00: 0 -+ // 01: 250ms -+ // 10: 500ms -+ // 11: 1000ms -+ .FAN2CNF = 0x1811, -+ -+ // Lenovo Custom OEM extension -+ // Firmware of ITE can be extended by -+ // custom program using its own "variables" -+ // These are the offsets to these "variables" -+ .FW_VER = 0xC2C7, -+ .FAN_CUR_POINT = 0xC534, -+ .FAN_POINTS_SIZE = 0xC535, -+ .FAN1_BASE = 0xC540, -+ .FAN2_BASE = 0xC550, -+ .FAN_ACC_BASE = 0xC560, -+ .FAN_DEC_BASE = 0xC570, -+ .CPU_TEMP = 0xC580, -+ .CPU_TEMP_HYST = 0xC590, -+ .GPU_TEMP = 0xC5A0, -+ .GPU_TEMP_HYST = 0xC5B0, -+ .VRM_TEMP = 0xC5C0, -+ .VRM_TEMP_HYST = 0xC5D0, -+ .CPU_TEMP_EN = 0xC631, -+ .GPU_TEMP_EN = 0xC632, -+ .VRM_TEMP_EN = 0xC633, -+ .FAN1_ACC_TIMER = 0xC3DA, -+ .FAN2_ACC_TIMER = 0xC3DB, -+ .FAN1_CUR_ACC = 0xC3DC, -+ .FAN1_CUR_DEC = 0xC3DD, -+ .FAN2_CUR_ACC = 0xC3DE, -+ .FAN2_CUR_DEC = 0xC3DF, -+ .FAN1_RPM_LSB = 0xC5E0, -+ .FAN1_RPM_MSB = 0xC5E1, -+ .FAN2_RPM_LSB = 0xC5E2, -+ .FAN2_RPM_MSB = 0xC5E3, -+ -+ // values -+ // 0x04: enable mini fan curve if very long on cool level -+ // - this might be due to potential temp failure -+ // - or just because really so cool -+ // 0xA0: disable it -+ .MINIFANCURVE_ON_COOL = 0xC536, -+ -+ .LOCKFANCONTROLLER = 0xc4AB, -+ -+ .ALT_CPU_TEMP = 0xc538, -+ .ALT_GPU_TEMP = 0xc539, -+ .ALT_POWERMODE = 0xc420, -+ -+ .FAN1_TARGET_RPM = 0xc600, -+ .FAN2_TARGET_RPM = 0xc601, -+ .ALT_FAN1_RPM = 0xC406, -+ .ALT_FAN2_RPM = 0xC4FE, -+ -+ .ALT_CPU_TEMP2 = 0xC5E6, -+ .ALT_GPU_TEMP2 = 0xC5E7, -+ .ALT_IC_TEMP2 = 0xC5E8, -+ -+ //enabled: 0x40 -+ //disabled: 0x00 -+ .MAXIMUMFANSPEED = 0xBD ++ .ECHIPID1 = 0x2000, ++ .ECHIPID2 = 0x2001, ++ .ECHIPVER = 0x2002, ++ .ECDEBUG = 0x2003, ++ .EXT_FAN_CUR_POINT = 0xC534, ++ .EXT_FAN_POINTS_SIZE = 0xC535, ++ .EXT_FAN1_BASE = 0xC540, ++ .EXT_FAN2_BASE = 0xC550, ++ .EXT_FAN_ACC_BASE = 0xC560, ++ .EXT_FAN_DEC_BASE = 0xC570, ++ .EXT_CPU_TEMP = 0xC580, ++ .EXT_CPU_TEMP_HYST = 0xC590, ++ .EXT_GPU_TEMP = 0xC5A0, ++ .EXT_GPU_TEMP_HYST = 0xC5B0, ++ .EXT_VRM_TEMP = 0xC5C0, ++ .EXT_VRM_TEMP_HYST = 0xC5D0, ++ .EXT_FAN1_RPM_LSB = 0xC5E0, ++ .EXT_FAN1_RPM_MSB = 0xC5E1, ++ .EXT_FAN2_RPM_LSB = 0xC5E2, ++ .EXT_FAN2_RPM_MSB = 0xC5E3, ++ .EXT_MINIFANCURVE_ON_COOL = 0xC536, ++ .EXT_LOCKFANCONTROLLER = 0xc4AB, ++ .EXT_CPU_TEMP_INPUT = 0xc538, ++ .EXT_GPU_TEMP_INPUT = 0xc539, ++ .EXT_IC_TEMP_INPUT = 0xC5E8, ++ .EXT_POWERMODE = 0xc420, ++ .EXT_FAN1_TARGET_RPM = 0xc600, ++ .EXT_FAN2_TARGET_RPM = 0xc601, ++ .EXT_MAXIMUMFANSPEED = 0xBD, ++ .EXT_WHITE_KEYBOARD_BACKLIGHT = (0x3B + 0xC400) +}; + +static const struct model_config model_v0 = { + .registers = &ec_register_offsets_v0, + .check_embedded_controller_id = true, + .embedded_controller_id = 0x8227, -+ .access_method = CONTROL_METHOD_ECRAM, -+ .ecram_access_method = ECRAM_ACCESS_PORTIO, -+ .memoryio_physical_start = 0xFE00D400, + .memoryio_physical_ec_start = 0xC400, -+ .memoryio_size = 0x300 ++ .memoryio_size = 0x300, ++ .has_minifancurve = true ++}; ++ ++static const struct model_config model_kfcn = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = true, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, ++ .memoryio_size = 0x300, ++ .has_minifancurve = false +}; + +static const struct model_config model_hacn = { + .registers = &ec_register_offsets_v0, + .check_embedded_controller_id = false, + .embedded_controller_id = 0x8227, -+ .access_method = CONTROL_METHOD_ECRAM, -+ .ecram_access_method = ECRAM_ACCESS_MEMORYIO, -+ .memoryio_physical_start = 0xFE00D400, + .memoryio_physical_ec_start = 0xC400, -+ .memoryio_size = 0x300 ++ .memoryio_size = 0x300, ++ .has_minifancurve = false +}; + ++ ++static const struct model_config model_k9cn = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = false, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, // or replace 0xC400 by 0x0400 ? ++ .memoryio_size = 0x300, ++ .has_minifancurve = false ++}; ++ ++ ++ +static const struct dmi_system_id denylist[] = { {} }; + +static const struct dmi_system_id optimistic_allowlist[] = { @@ -567,7 +404,7 @@ index 000000000..6edfeffcc + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_BIOS_VERSION, "KFCN"), + }, -+ .driver_data = (void *)&model_v0 ++ .driver_data = (void *)&model_kfcn + }, + { + // modelyear: 2021 @@ -578,22 +415,70 @@ index 000000000..6edfeffcc + }, + .driver_data = (void *)&model_hacn + }, -+ {} -+}; -+ -+static const struct dmi_system_id explicit_allowlist[] = { + { -+ .ident = "GKCN58WW", ++ // modelyear: 2021 ++ .ident = "G9CN", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), -+ DMI_MATCH(DMI_BIOS_VERSION, "GKCN58WW"), ++ DMI_MATCH(DMI_BIOS_VERSION, "G9CN"), + }, + .driver_data = (void *)&model_v0 + }, ++ { ++ // modelyear: 2022 ++ .ident = "K9CN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "K9CN"), ++ }, ++ .driver_data = (void *)&model_k9cn ++ }, + {} +}; + +/* ================================= */ ++/* ACPI access */ ++/* ================================= */ ++ ++// function from ideapad-laptop.c ++static int eval_int(acpi_handle handle, const char *name, unsigned long *res) ++{ ++ unsigned long long result; ++ acpi_status status; ++ ++ status = acpi_evaluate_integer(handle, (char *)name, NULL, &result); ++ if (ACPI_FAILURE(status)) ++ return -EIO; ++ ++ *res = result; ++ ++ return 0; ++} ++ ++// function from ideapad-laptop.c ++static int exec_simple_method(acpi_handle handle, const char *name, ++ unsigned long arg) ++{ ++ acpi_status status = ++ acpi_execute_simple_method(handle, (char *)name, arg); ++ ++ return ACPI_FAILURE(status) ? -EIO : 0; ++} ++ ++// function from ideapad-laptop.c ++static int exec_sbmc(acpi_handle handle, unsigned long arg) ++{ ++ // \_SB.PCI0.LPC0.EC0.VPC0.SBMC ++ return exec_simple_method(handle, "SBMC", arg); ++} ++ ++static int eval_qcho(acpi_handle handle, unsigned long *res) ++{ ++ // \_SB.PCI0.LPC0.EC0.QCHO ++ return eval_int(handle, "QCHO", res); ++} ++ ++/* ================================= */ +/* EC RAM Access with port-mapped IO */ +/* ================================= */ + @@ -656,21 +541,6 @@ index 000000000..6edfeffcc + release_region(ECRAM_PORTIO_START_PORT, ECRAM_PORTIO_PORTS_SIZE); +} + -+//ssize_t ecram_portio_read_low(struct ecram_portio *ec_portio, u8 offset, u8 *value){ -+// mutex_lock(&ec_portio->io_port_mutex); -+// outb(0x66, 0x80); -+// outb(offset, ECRAM_PORTIO_DATA_PORT); -+// *value = inb(ECRAM_PORTIO_DATA_PORT); -+// mutex_unlock(&ec_portio->io_port_mutex); -+//} -+//ssize_t ecram_portio_write_low(struct ecram_portio *ec_portio, u8 offset, u8 value){ -+// mutex_lock(&ec_portio->io_port_mutex); -+// outb(0x66, ECRAM_PORTIO_ADDR_PORT); -+// outb(offset, ECRAM_PORTIO_DATA_PORT); -+// outb(value, ECRAM_PORTIO_DATA_PORT); -+// mutex_unlock(&ec_portio->io_port_mutex); -+//} -+ +/* Read a byte from the EC RAM. + * + * Return status because of commong signature for alle @@ -732,132 +602,27 @@ index 000000000..6edfeffcc +} + +/* =================================== */ -+/* EC RAM Access with memory mapped IO */ -+/* =================================== */ -+ -+struct ecram_memoryio { -+ // TODO: start of remapped memory in EC RAM is assumed to be 0 -+ // u16 ecram_start; -+ -+ // physical address of remapped IO, depends on model and firmware -+ phys_addr_t physical_start; -+ // start adress of region in ec memory -+ phys_addr_t physical_ec_start; -+ // virtual address of remapped IO -+ u8 *virtual_start; -+ // size of remapped access -+ size_t size; -+}; -+ -+/** -+ * physical_start : corresponds to EC RAM 0 inside EC -+ * size: size of remapped region -+ * -+ * strong exception safety -+ */ -+ssize_t ecram_memoryio_init(struct ecram_memoryio *ec_memoryio, -+ phys_addr_t physical_start, phys_addr_t physical_ec_start, size_t size) -+{ -+ void *virtual_start = ioremap(physical_start, size); -+ -+ if (!IS_ERR_OR_NULL(virtual_start)) { -+ ec_memoryio->virtual_start = virtual_start; -+ ec_memoryio->physical_start = physical_start; -+ ec_memoryio->physical_ec_start = physical_ec_start; -+ ec_memoryio->size = size; -+ pr_info("Succeffuly mapped embedded controller: 0x%llx (in RAM)/0x%llx (in EC) to virtual 0x%p\n", -+ ec_memoryio->physical_start, -+ ec_memoryio->physical_ec_start, -+ ec_memoryio->virtual_start); -+ } else { -+ pr_info("Error mapping embedded controller memory at 0x%llx\n", -+ physical_start); -+ return -ENOMEM; -+ } -+ return 0; -+} -+ -+void ecram_memoryio_exit(struct ecram_memoryio *ec_memoryio) -+{ -+ if (ec_memoryio->virtual_start != NULL) { -+ pr_info("Unmapping embedded controller memory at 0x%llx (in RAM)/0x%llx (in EC) at virtual 0x%p\n", -+ ec_memoryio->physical_start, -+ ec_memoryio->physical_ec_start, -+ ec_memoryio->virtual_start); -+ iounmap(ec_memoryio->virtual_start); -+ ec_memoryio->virtual_start = NULL; -+ } -+} -+ -+/* Read a byte from the EC RAM. -+ * -+ * Return status because of commong signature for alle -+ * methods to access EC RAM. -+ */ -+ssize_t ecram_memoryio_read(const struct ecram_memoryio *ec_memoryio, -+ u16 ec_offset, u8 *value) -+{ -+ if (ec_offset < ec_memoryio->physical_ec_start) { -+ pr_info("Unexpected read at offset %d into EC RAM\n", -+ ec_offset); -+ return -1; -+ } -+ *value = *(ec_memoryio->virtual_start + (ec_offset - ec_memoryio->physical_ec_start)); -+ return 0; -+} -+ -+/* Write a byte to the EC RAM. -+ * -+ * Return status because of commong signature for alle -+ * methods to access EC RAM. -+ */ -+ssize_t ecram_memoryio_write(const struct ecram_memoryio *ec_memoryio, -+ u16 ec_offset, u8 value) -+{ -+ if (ec_offset < ec_memoryio->physical_ec_start) { -+ pr_info("Unexpected write at offset %d into EC RAM\n", -+ ec_offset); -+ return -1; -+ } -+ *(ec_memoryio->virtual_start + (ec_offset - ec_memoryio->physical_ec_start)) = value; -+ return 0; -+} -+ -+/* =================================== */ +/* EC RAM Access */ +/* =================================== */ + +struct ecram { -+ struct ecram_memoryio memoryio; + struct ecram_portio portio; -+ enum ECRAM_ACCESS access_method; +}; + -+ssize_t ecram_init(struct ecram *ecram, enum ECRAM_ACCESS access_method, -+ phys_addr_t memoryio_physical_start, phys_addr_t memoryio_ec_physical_start, size_t region_size) ++ssize_t ecram_init(struct ecram *ecram, phys_addr_t memoryio_ec_physical_start, ++ size_t region_size) +{ + ssize_t err; + -+ err = ecram_memoryio_init(&ecram->memoryio, memoryio_physical_start, -+ memoryio_ec_physical_start, region_size); -+ if (err) { -+ pr_info("Failed ecram_memoryio_init\n"); -+ goto err_ecram_memoryio_init; -+ } + err = ecram_portio_init(&ecram->portio); + if (err) { + pr_info("Failed ecram_portio_init\n"); + goto err_ecram_portio_init; + } + -+ ecram->access_method = access_method; -+ + return 0; + +err_ecram_portio_init: -+ ecram_memoryio_exit(&ecram->memoryio); -+err_ecram_memoryio_init: -+ + return err; +} + @@ -865,7 +630,6 @@ index 000000000..6edfeffcc +{ + pr_info("Unloading legion ecram\n"); + ecram_portio_exit(&ecram->portio); -+ ecram_memoryio_exit(&ecram->memoryio); + pr_info("Unloading legion ecram done\n"); +} + @@ -877,17 +641,7 @@ index 000000000..6edfeffcc + u8 value; + int err; + -+ switch (ecram->access_method) { -+ case ECRAM_ACCESS_MEMORYIO: -+ err = ecram_memoryio_read(&ecram->memoryio, ecram_offset, -+ &value); -+ break; -+ case ECRAM_ACCESS_PORTIO: -+ err = ecram_portio_read(&ecram->portio, ecram_offset, &value); -+ break; -+ default: -+ break; -+ } ++ err = ecram_portio_read(&ecram->portio, ecram_offset, &value); + if (err) + pr_info("Error reading EC RAM at 0x%x\n", ecram_offset); + return value; @@ -902,18 +656,7 @@ index 000000000..6edfeffcc + ecram_offset); + return; + } -+ -+ switch (ecram->access_method) { -+ case ECRAM_ACCESS_MEMORYIO: -+ err = ecram_memoryio_write(&ecram->memoryio, ecram_offset, -+ value); -+ break; -+ case ECRAM_ACCESS_PORTIO: -+ err = ecram_portio_write(&ecram->portio, ecram_offset, value); -+ break; -+ default: -+ break; -+ } ++ err = ecram_portio_write(&ecram->portio, ecram_offset, value); + if (err) + pr_info("Error writing EC RAM at 0x%x\n", ecram_offset); +} @@ -967,26 +710,25 @@ index 000000000..6edfeffcc + struct sensor_values *values) +{ + values->fan1_target_rpm = -+ 100 * ecram_read(ecram, model->registers->FAN1_TARGET_RPM); ++ 100 * ecram_read(ecram, model->registers->EXT_FAN1_TARGET_RPM); + values->fan2_target_rpm = -+ 100 * ecram_read(ecram, model->registers->FAN2_TARGET_RPM); -+ // TODO: what source toc choose? -+ // values->fan1_rpm = 100*ecram_read(ecram, model->registers->ALT_FAN1_RPM); -+ // values->fan2_rpm = 100*ecram_read(ecram, model->registers->ALT_FAN2_RPM); ++ 100 * ecram_read(ecram, model->registers->EXT_FAN2_TARGET_RPM); + + values->fan1_rpm = -+ ecram_read(ecram, model->registers->FAN1_RPM_LSB) + -+ (((int)ecram_read(ecram, model->registers->FAN1_RPM_MSB)) << 8); ++ ecram_read(ecram, model->registers->EXT_FAN1_RPM_LSB) + ++ (((int)ecram_read(ecram, model->registers->EXT_FAN1_RPM_MSB)) ++ << 8); + values->fan2_rpm = -+ ecram_read(ecram, model->registers->FAN2_RPM_LSB) + -+ (((int)ecram_read(ecram, model->registers->FAN2_RPM_MSB)) << 8); ++ ecram_read(ecram, model->registers->EXT_FAN2_RPM_LSB) + ++ (((int)ecram_read(ecram, model->registers->EXT_FAN2_RPM_MSB)) ++ << 8); + + values->cpu_temp_celsius = -+ ecram_read(ecram, model->registers->ALT_CPU_TEMP); ++ ecram_read(ecram, model->registers->EXT_CPU_TEMP_INPUT); + values->gpu_temp_celsius = -+ ecram_read(ecram, model->registers->ALT_GPU_TEMP); ++ ecram_read(ecram, model->registers->EXT_GPU_TEMP_INPUT); + values->ic_temp_celsius = -+ ecram_read(ecram, model->registers->ALT_IC_TEMP2); ++ ecram_read(ecram, model->registers->EXT_IC_TEMP_INPUT); + + values->cpu_temp_celsius = ecram_read(ecram, 0xC5E6); + values->gpu_temp_celsius = ecram_read(ecram, 0xC5E7); @@ -1001,7 +743,7 @@ index 000000000..6edfeffcc + +int read_powermode(struct ecram *ecram, const struct model_config *model) +{ -+ return ecram_read(ecram, model->registers->ALT_POWERMODE); ++ return ecram_read(ecram, model->registers->EXT_POWERMODE); +} + +ssize_t write_powermode(struct ecram *ecram, const struct model_config *model, @@ -1011,7 +753,7 @@ index 000000000..6edfeffcc + pr_info("Unexpected power mode value ignored: %d\n", value); + return -ENOMEM; + } -+ ecram_write(ecram, model->registers->ALT_POWERMODE, value); ++ ecram_write(ecram, model->registers->EXT_POWERMODE, value); + return 0; +} + @@ -1037,14 +779,14 @@ index 000000000..6edfeffcc +{ + u8 val = state ? lockfancontroller_ON : lockfancontroller_OFF; + -+ ecram_write(ecram, model->registers->LOCKFANCONTROLLER, val); ++ ecram_write(ecram, model->registers->EXT_LOCKFANCONTROLLER, val); + return 0; +} + +int read_lockfancontroller(struct ecram *ecram, + const struct model_config *model, bool *state) +{ -+ int value = ecram_read(ecram, model->registers->LOCKFANCONTROLLER); ++ int value = ecram_read(ecram, model->registers->EXT_LOCKFANCONTROLLER); + + switch (value) { + case lockfancontroller_ON: @@ -1067,7 +809,7 @@ index 000000000..6edfeffcc +int read_maximumfanspeed(struct ecram *ecram, const struct model_config *model, + bool *state) +{ -+ int value = ecram_read(ecram, model->registers->MAXIMUMFANSPEED); ++ int value = ecram_read(ecram, model->registers->EXT_MAXIMUMFANSPEED); + + switch (value) { + case MAXIMUMFANSPEED_ON: @@ -1089,7 +831,7 @@ index 000000000..6edfeffcc +{ + u8 val = state ? MAXIMUMFANSPEED_ON : MAXIMUMFANSPEED_OFF; + -+ ecram_write(ecram, model->registers->MAXIMUMFANSPEED, val); ++ ecram_write(ecram, model->registers->EXT_MAXIMUMFANSPEED, val); + return 0; +} + @@ -1099,7 +841,8 @@ index 000000000..6edfeffcc +int read_minifancurve(struct ecram *ecram, const struct model_config *model, + bool *state) +{ -+ int value = ecram_read(ecram, model->registers->MINIFANCURVE_ON_COOL); ++ int value = ++ ecram_read(ecram, model->registers->EXT_MINIFANCURVE_ON_COOL); + + switch (value) { + case MINIFANCUVE_ON_COOL_ON: @@ -1121,10 +864,70 @@ index 000000000..6edfeffcc +{ + u8 val = state ? MINIFANCUVE_ON_COOL_ON : MINIFANCUVE_ON_COOL_OFF; + -+ ecram_write(ecram, model->registers->MINIFANCURVE_ON_COOL, val); ++ ecram_write(ecram, model->registers->EXT_MINIFANCURVE_ON_COOL, val); + return 0; +} + ++#define KEYBOARD_BACKLIGHT_OFF 18 ++#define KEYBOARD_BACKLIGHT_ON1 21 ++#define KEYBOARD_BACKLIGHT_ON2 23 ++ ++int read_keyboard_backlight(struct ecram *ecram, ++ const struct model_config *model, int *state) ++{ ++ int value = ecram_read(ecram, ++ model->registers->EXT_WHITE_KEYBOARD_BACKLIGHT); ++ ++ //switch (value) { ++ //case MINIFANCUVE_ON_COOL_ON: ++ // *state = true; ++ // break; ++ //case MINIFANCUVE_ON_COOL_OFF: ++ // *state = false; ++ // break; ++ //default: ++ // pr_info("Unexpected value in MINIFANCURVE register:%d\n", ++ // value); ++ // return -1; ++ //} ++ *state = value; ++ return 0; ++} ++ ++int write_keyboard_backlight(struct ecram *ecram, ++ const struct model_config *model, int state) ++{ ++ u8 val = state > 0 ? KEYBOARD_BACKLIGHT_ON1 : KEYBOARD_BACKLIGHT_OFF; ++ ++ ecram_write(ecram, model->registers->EXT_WHITE_KEYBOARD_BACKLIGHT, val); ++ return 0; ++} ++ ++#define FCT_RAPID_CHARGE_ON 0x07 ++#define FCT_RAPID_CHARGE_OFF 0x08 ++#define RAPID_CHARGE_ON 0x0 ++#define RAPID_CHARGE_OFF 0x1 ++ ++int read_rapidcharge(acpi_handle acpihandle, int *state) ++{ ++ unsigned long result; ++ int err; ++ ++ err = eval_qcho(acpihandle, &result); ++ if (err) ++ return err; ++ ++ *state = result; ++ return 0; ++} ++ ++int write_rapidcharge(acpi_handle acpihandle, bool state) ++{ ++ unsigned long fct_nr = state > 0 ? FCT_RAPID_CHARGE_ON : ++ FCT_RAPID_CHARGE_OFF; ++ return exec_sbmc(acpihandle, fct_nr); ++} ++ +/* ============================= */ +/* Data model for fan curve */ +/* ============================ */ @@ -1317,38 +1120,6 @@ index 000000000..6edfeffcc + return valid; +} + -+//TODO: remove this if meaning of hyst in fan curve is clear! -+// -+//bool fancurve_set_cpu_deltahyst(struct fancurve* fancurve, int point_id, int hyst_value) -+//{ -+// int max_temp = fancurve->points[point_id].cpu_max_temp_celsius; -+// bool valid = hyst_value < max_temp; -+// if(valid){ -+// fancurve->points[point_id].cpu_min_temp_celsius = max_temp - hyst_value; -+// } -+// return valid; -+//} -+ -+//bool fancurve_set_gpu_deltahyst(struct fancurve* fancurve, int point_id, int hyst_value) -+//{ -+// int max_temp = fancurve->points[point_id].gpu_max_temp_celsius; -+// bool valid = hyst_value < max_temp; -+// if(valid){ -+// fancurve->points[point_id].gpu_min_temp_celsius = max_temp - hyst_value; -+// } -+// return valid; -+//} -+ -+//bool fancurve_set_ic_deltahyst(struct fancurve* fancurve, int point_id, int hyst_value) -+//{ -+// int max_temp = fancurve->points[point_id].ic_max_temp_celsius; -+// bool valid = hyst_value < max_temp; -+// if(valid){ -+// fancurve->points[point_id].ic_min_temp_celsius = max_temp - hyst_value; -+// } -+// return valid; -+//} -+ +bool fancurve_set_size(struct fancurve *fancurve, int size, bool init_values) +{ + bool valid = size >= 1 && size <= MAXFANCURVESIZE; @@ -1358,7 +1129,6 @@ index 000000000..6edfeffcc + if (init_values && size < fancurve->size) { + // fancurve size is decreased, but last etnry alwasy needs 127 temperatures + // Note: size >=1 -+ // TODO: remove this comment + fancurve->points[size - 1].cpu_max_temp_celsius = 127; + fancurve->points[size - 1].ic_max_temp_celsius = 127; + fancurve->points[size - 1].gpu_max_temp_celsius = 127; @@ -1392,35 +1162,36 @@ index 000000000..6edfeffcc + struct fancurve_point *point = &fancurve->points[i]; + + point->rpm1_raw = -+ ecram_read(ecram, model->registers->FAN1_BASE + i); ++ ecram_read(ecram, model->registers->EXT_FAN1_BASE + i); + point->rpm2_raw = -+ ecram_read(ecram, model->registers->FAN2_BASE + i); ++ ecram_read(ecram, model->registers->EXT_FAN2_BASE + i); + -+ point->accel = -+ ecram_read(ecram, model->registers->FAN_ACC_BASE + i); -+ point->decel = -+ ecram_read(ecram, model->registers->FAN_DEC_BASE + i); ++ point->accel = ecram_read( ++ ecram, model->registers->EXT_FAN_ACC_BASE + i); ++ point->decel = ecram_read( ++ ecram, model->registers->EXT_FAN_DEC_BASE + i); + point->cpu_max_temp_celsius = -+ ecram_read(ecram, model->registers->CPU_TEMP + i); -+ point->cpu_min_temp_celsius = -+ ecram_read(ecram, model->registers->CPU_TEMP_HYST + i); ++ ecram_read(ecram, model->registers->EXT_CPU_TEMP + i); ++ point->cpu_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_CPU_TEMP_HYST + i); + point->gpu_max_temp_celsius = -+ ecram_read(ecram, model->registers->GPU_TEMP + i); -+ point->gpu_min_temp_celsius = -+ ecram_read(ecram, model->registers->GPU_TEMP_HYST + i); ++ ecram_read(ecram, model->registers->EXT_GPU_TEMP + i); ++ point->gpu_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_GPU_TEMP_HYST + i); + point->ic_max_temp_celsius = -+ ecram_read(ecram, model->registers->VRM_TEMP + i); -+ point->ic_min_temp_celsius = -+ ecram_read(ecram, model->registers->VRM_TEMP_HYST + i); ++ ecram_read(ecram, model->registers->EXT_VRM_TEMP + i); ++ point->ic_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_VRM_TEMP_HYST + i); + } + + // Do not trust that hardware; It might suddendly report + // a larger size, so clamp it. -+ fancurve->size = ecram_read(ecram, model->registers->FAN_POINTS_SIZE); ++ fancurve->size = ++ ecram_read(ecram, model->registers->EXT_FAN_POINTS_SIZE); + fancurve->size = + min(fancurve->size, (typeof(fancurve->size))(MAXFANCURVESIZE)); + fancurve->current_point_i = -+ ecram_read(ecram, model->registers->FAN_CUR_POINT); ++ ecram_read(ecram, model->registers->EXT_FAN_CUR_POINT); + fancurve->current_point_i = + min(fancurve->current_point_i, fancurve->size); + return 0; @@ -1440,39 +1211,39 @@ index 000000000..6edfeffcc + i < fancurve->size ? &fancurve->points[i] : + &fancurve_point_zero; + -+ ecram_write(ecram, model->registers->FAN1_BASE + i, ++ ecram_write(ecram, model->registers->EXT_FAN1_BASE + i, + point->rpm1_raw); -+ ecram_write(ecram, model->registers->FAN2_BASE + i, ++ ecram_write(ecram, model->registers->EXT_FAN2_BASE + i, + point->rpm2_raw); + -+ ecram_write(ecram, model->registers->FAN_ACC_BASE + i, ++ ecram_write(ecram, model->registers->EXT_FAN_ACC_BASE + i, + point->accel); -+ ecram_write(ecram, model->registers->FAN_DEC_BASE + i, ++ ecram_write(ecram, model->registers->EXT_FAN_DEC_BASE + i, + point->decel); + -+ ecram_write(ecram, model->registers->CPU_TEMP + i, ++ ecram_write(ecram, model->registers->EXT_CPU_TEMP + i, + point->cpu_max_temp_celsius); -+ ecram_write(ecram, model->registers->CPU_TEMP_HYST + i, ++ ecram_write(ecram, model->registers->EXT_CPU_TEMP_HYST + i, + point->cpu_min_temp_celsius); -+ ecram_write(ecram, model->registers->GPU_TEMP + i, ++ ecram_write(ecram, model->registers->EXT_GPU_TEMP + i, + point->gpu_max_temp_celsius); -+ ecram_write(ecram, model->registers->GPU_TEMP_HYST + i, ++ ecram_write(ecram, model->registers->EXT_GPU_TEMP_HYST + i, + point->gpu_min_temp_celsius); -+ ecram_write(ecram, model->registers->VRM_TEMP + i, ++ ecram_write(ecram, model->registers->EXT_VRM_TEMP + i, + point->ic_max_temp_celsius); -+ ecram_write(ecram, model->registers->VRM_TEMP_HYST + i, ++ ecram_write(ecram, model->registers->EXT_VRM_TEMP_HYST + i, + point->ic_min_temp_celsius); + } + + if (write_size) { -+ ecram_write(ecram, model->registers->FAN_POINTS_SIZE, ++ ecram_write(ecram, model->registers->EXT_FAN_POINTS_SIZE, + fancurve->size); + } + + // Reset current fan level to 0, so algorithm in EC + // selects fan curve point again and resetting hysterisis + // effects -+ ecram_write(ecram, model->registers->FAN_CUR_POINT, 0); ++ ecram_write(ecram, model->registers->EXT_FAN_CUR_POINT, 0); + + // Reset internal fan levels + ecram_write(ecram, 0xC634, 0); // CPU @@ -1482,35 +1253,6 @@ index 000000000..6edfeffcc + return 0; +} + -+//TODO: still needed? -+//static ssize_t fancurve_print(const struct fancurve* fancurve, char *buf) -+//{ -+// ssize_t output_char_count = 0; -+// size_t i; -+// for (i = 0; i < fancurve->size; ++i) { -+// const struct fancurve_point * point = &fancurve->points[i]; -+// int res = sprintf(buf, "%d %d %d %d %d %d %d %d %d %d\n", -+// point->rpm1_raw*100, point->rpm2_raw*100, -+// point->accel, point->decel, -+// point->cpu_min_temp_celsius, -+// point->cpu_max_temp_celsius, -+// point->gpu_min_temp_celsius, -+// point->gpu_max_temp_celsius, -+// point->ic_min_temp_celsius, -+// point->ic_max_temp_celsius); -+// if (res > 0) { -+// output_char_count += res; -+// } else { -+// pr_debug( -+// "Error writing to buffer for output of fanCurveStructure\n"); -+// return 0; -+// } -+// // go forward in buffer to append next print output -+// buf += res; -+// } -+// return output_char_count; -+//} -+ +static ssize_t fancurve_print_seqfile(const struct fancurve *fancurve, + struct seq_file *s) +{ @@ -1565,9 +1307,6 @@ index 000000000..6edfeffcc + struct device *hwmon_dev; + struct platform_profile_handler platform_profile_handler; + -+ // EC enables mini fancurve if long enough on low temp -+ bool has_minifancurve_on_cool; -+ + // TODO: remove? + bool loaded; +}; @@ -1620,7 +1359,9 @@ index 000000000..6edfeffcc + size_t offset; + + for (offset = 0; offset < priv->conf->memoryio_size; ++offset) { -+ char value = ecram_read(&priv->ecram, priv->conf->memoryio_physical_ec_start + offset); ++ char value = ecram_read(&priv->ecram, ++ priv->conf->memoryio_physical_ec_start + ++ offset); + + seq_write(s, &value, 1); + } @@ -1640,12 +1381,12 @@ index 000000000..6edfeffcc + seq_printf(s, "EC Chip ID: %x\n", read_ec_id(&priv->ecram, priv->conf)); + seq_printf(s, "EC Chip Version: %x\n", + read_ec_version(&priv->ecram, priv->conf)); -+ // TODO: remove this -+ seq_printf(s, "legion_laptop version: %s\n", MODULEVERSION); + seq_printf(s, "legion_laptop features: %s\n", LEGIONFEATURES); + seq_printf(s, "legion_laptop ec_readonly: %d\n", ec_readonly); + read_fancurve(&priv->ecram, priv->conf, &priv->fancurve); + ++ seq_printf(s, "minifancurve feature enabled: %d\n", ++ priv->conf->has_minifancurve); + err = read_minifancurve(&priv->ecram, priv->conf, &is_minifancurve); + seq_printf(s, "minifancurve on cool: %s\n", + err ? "error" : (is_minifancurve ? "true" : "false")); @@ -1666,10 +1407,6 @@ index 000000000..6edfeffcc + seq_puts(s, "Current fan curve in hardware (embedded controller):\n"); + fancurve_print_seqfile(&priv->fancurve, s); + seq_puts(s, "=====================\n"); -+ -+ // TODO: decide what to do with it, still needed? -+ // seq_puts(s, "Configured fan curve.\n"); -+ // fancurve_print_seqfile(&priv->fancurve_configured, s); + return 0; +} + @@ -1698,8 +1435,7 @@ index 000000000..6edfeffcc +static void legion_debugfs_exit(struct legion_private *priv) +{ + pr_info("Unloading legion dubugfs\n"); -+ // TODO: remove this note -+ // Note: does nothing if null ++ // The following is does nothing if pointer is NULL + debugfs_remove_recursive(priv->debugfs_dir); + priv->debugfs_dir = NULL; + pr_info("Unloading legion dubugfs done\n"); @@ -1787,8 +1523,40 @@ index 000000000..6edfeffcc + +static DEVICE_ATTR_RW(lockfancontroller); + ++static ssize_t keyboard_backlight_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ int state; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ read_keyboard_backlight(&priv->ecram, priv->conf, &state); ++ return sysfs_emit(buf, "%d\n", state); ++} ++ ++static ssize_t keyboard_backlight_store(struct device *dev, ++ struct device_attribute *attr, ++ const char *buf, size_t count) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int state; ++ int err; ++ ++ err = kstrtouint(buf, 0, &state); ++ if (err) ++ return err; ++ ++ err = write_keyboard_backlight(&priv->ecram, priv->conf, state); ++ if (err) ++ return -EINVAL; ++ ++ return count; ++} ++ ++static DEVICE_ATTR_RW(keyboard_backlight); ++ +static struct attribute *legion_sysfs_attributes[] = { -+ &dev_attr_powermode.attr, &dev_attr_lockfancontroller.attr, NULL ++ &dev_attr_powermode.attr, &dev_attr_lockfancontroller.attr, ++ &dev_attr_keyboard_backlight.attr, NULL +}; + +static const struct attribute_group legion_attribute_group = { @@ -2276,13 +2044,9 @@ index 000000000..6edfeffcc + switch (fancurve_attr_id) { + case FANCURVE_ATTR_PWM1: + valid = fancurve_set_rpm1(&fancurve, point_id, value); -+ // TODO: remove -+ //valid = valid && fancurve_set_rpm2(&fancurve, point_id, value); + break; + case FANCURVE_ATTR_PWM2: + valid = fancurve_set_rpm2(&fancurve, point_id, value); -+ // TODO: remove -+ //valid = valid && fancurve_set_rpm2(&fancurve, point_id, value); + break; + case FANCURVE_ATTR_CPU_TEMP: + valid = fancurve_set_cpu_temp_max(&fancurve, point_id, value); @@ -2777,14 +2541,27 @@ index 000000000..6edfeffcc + &sensor_dev_attr_pwm1_mode.dev_attr.attr, NULL +}; + ++static umode_t legion_is_visible(struct kobject *kobj, struct attribute *attr, ++ int idx) ++{ ++ bool supported = true; ++ struct device *dev = kobj_to_dev(kobj); ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ if (attr == &sensor_dev_attr_minifancurve.dev_attr.attr) ++ supported = priv->conf->has_minifancurve; ++ ++ return supported ? attr->mode : 0; ++} ++ +static const struct attribute_group legion_hwmon_sensor_group = { + .attrs = sensor_hwmon_attributes, -+ .is_visible = NULL // use modes from attributes ++ .is_visible = NULL +}; + +static const struct attribute_group legion_hwmon_fancurve_group = { + .attrs = fancurve_hwmon_attributes, -+ .is_visible = NULL // use modes from attributes ++ .is_visible = legion_is_visible, +}; + +static const struct attribute_group *legion_hwmon_groups[] = { @@ -2800,7 +2577,7 @@ index 000000000..6edfeffcc + // TODO: Use devm_hwmon_device_register_with_groups ? + // some laptop drivers use this, some + struct device *hwmon_dev = hwmon_device_register_with_groups( -+ &priv->platform_device->dev, "legion_hwmon", NULL, ++ &priv->platform_device->dev, "legion_hwmon", priv, + legion_hwmon_groups); + if (IS_ERR_OR_NULL(hwmon_dev)) { + pr_err("hwmon_device_register failed!\n"); @@ -2836,8 +2613,12 @@ index 000000000..6edfeffcc + bool do_load_by_list = false; + bool do_load = false; + //struct legion_private *priv = dev_get_drvdata(&pdev->dev); -+ dev_info(&pdev->dev, "legion_laptop platform driver %s probing\n", -+ MODULEVERSION); ++ dev_info(&pdev->dev, "legion_laptop platform driver probing\n"); ++ ++ dev_info(&pdev->dev, "Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", ++ dmi_get_system_info(DMI_SYS_VENDOR), ++ dmi_get_system_info(DMI_PRODUCT_NAME), ++ dmi_get_system_info(DMI_BIOS_VERSION)); + + // TODO: allocate? + priv = &_priv; @@ -2891,9 +2672,7 @@ index 000000000..6edfeffcc + + priv->conf = dmi_sys->driver_data; + -+ err = ecram_init(&priv->ecram, priv->conf->ecram_access_method, -+ priv->conf->memoryio_physical_start, -+ priv->conf->memoryio_physical_ec_start, ++ err = ecram_init(&priv->ecram, priv->conf->memoryio_physical_ec_start, + priv->conf->memoryio_size); + if (err) { + dev_info(&pdev->dev, @@ -2970,8 +2749,7 @@ index 000000000..6edfeffcc +int legion_remove(struct platform_device *pdev) +{ + struct legion_private *priv = dev_get_drvdata(&pdev->dev); -+ // TODO: remove this -+ pr_info("Unloading legion\n"); ++ + mutex_lock(&legion_shared_mutex); + priv->loaded = false; + mutex_unlock(&legion_shared_mutex); @@ -3035,49 +2813,25 @@ index 000000000..6edfeffcc +int __init legion_init(void) +{ + int err; -+ // TODO: remove version -+ pr_info("legion_laptop %s starts loading\n", MODULEVERSION); -+ -+ // TODO: remove this, make a comment -+ if (!(MAXFANCURVESIZE <= 10)) { -+ pr_debug("Fan curve size too large\n"); -+ err = -ENOMEM; -+ goto error_assert; -+ } -+ -+ // TODO: remove this -+ pr_info("Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", -+ dmi_get_system_info(DMI_SYS_VENDOR), -+ dmi_get_system_info(DMI_PRODUCT_NAME), -+ dmi_get_system_info(DMI_BIOS_VERSION)); + ++ pr_info("legion_laptop starts loading\n"); + err = platform_driver_register(&legion_driver); + if (err) { + pr_info("legion_laptop: platform_driver_register failed\n"); -+ goto error_platform_driver; ++ return err; + } + -+ // TODO: remove version -+ // pr_info("legion_laptop %s loading done\n", MODULEVERSION); -+ + return 0; -+ -+error_platform_driver: -+error_assert: -+ return err; +} + +module_init(legion_init); + +void __exit legion_exit(void) +{ -+ // TODO: remove this -+ pr_info("legion_laptop %s starts unloading\n", MODULEVERSION); + platform_driver_unregister(&legion_driver); -+ // TODO: remove this -+ pr_info("legion_laptop %s unloaded\n", MODULEVERSION); ++ pr_info("legion_laptop exit\n"); +} + +module_exit(legion_exit); --- -2.39.1 +-- +2.40.0 diff --git a/patches/0001-cachy-all.patch b/patches/0001-cachy-all.patch index ffe879d..7a25c73 100644 --- a/patches/0001-cachy-all.patch +++ b/patches/0001-cachy-all.patch @@ -1,7 +1,7 @@ -From c2fc7486fbb316ab576a741ae264255a4cc4de44 Mon Sep 17 00:00:00 2001 +From 699468c6193ea5f7294fa33720c1333793a7ffa6 Mon Sep 17 00:00:00 2001 From: Peter Jung Date: Mon, 6 Mar 2023 18:43:03 +0100 -Subject: [PATCH 01/10] bbr2 +Subject: [PATCH 01/12] bbr2 Signed-off-by: Peter Jung --- @@ -3283,21 +3283,30 @@ index cb79127f45c3..70e4de876a7f 100644 -- 2.40.0 -From 8f60626e149f4437570d56968a2cab10a822fcd4 Mon Sep 17 00:00:00 2001 +From 6ff5f7407177949cb2fb7082e4928f2a015c1ff0 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:21:39 +0200 -Subject: [PATCH 02/10] bfq +Date: Mon, 17 Apr 2023 18:21:50 +0200 +Subject: [PATCH 02/12] bfq Signed-off-by: Peter Jung --- - block/bfq-iosched.c | 6 ++++++ - 1 file changed, 6 insertions(+) + block/bfq-iosched.c | 8 ++++++++ + 1 file changed, 8 insertions(+) diff --git a/block/bfq-iosched.c b/block/bfq-iosched.c -index d9ed3108c17a..f32b177a36e5 100644 +index d9ed3108c17a..66146bbcd4af 100644 --- a/block/bfq-iosched.c +++ b/block/bfq-iosched.c -@@ -7617,6 +7617,7 @@ MODULE_ALIAS("bfq-iosched"); +@@ -649,6 +649,8 @@ static bool bfqq_request_over_limit(struct bfq_queue *bfqq, int limit) + sched_data->service_tree[i].wsum; + } + } ++ if (!wsum) ++ continue; + limit = DIV_ROUND_CLOSEST(limit * entity->weight, wsum); + if (entity->allocated >= limit) { + bfq_log_bfqq(bfqq->bfqd, bfqq, +@@ -7617,6 +7619,7 @@ MODULE_ALIAS("bfq-iosched"); static int __init bfq_init(void) { int ret; @@ -3305,7 +3314,7 @@ index d9ed3108c17a..f32b177a36e5 100644 #ifdef CONFIG_BFQ_GROUP_IOSCHED ret = blkcg_policy_register(&blkcg_policy_bfq); -@@ -7648,6 +7649,11 @@ static int __init bfq_init(void) +@@ -7648,6 +7651,11 @@ static int __init bfq_init(void) if (ret) goto slab_kill; @@ -3320,71 +3329,73 @@ index d9ed3108c17a..f32b177a36e5 100644 -- 2.40.0 -From 7a2801ac4761f911a6b2e7a8532b9fedc5382bc5 Mon Sep 17 00:00:00 2001 +From 62e4dbb0e66501638a4adf0d840b067d3b95bb93 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:21:58 +0200 -Subject: [PATCH 03/10] cachy +Date: Sat, 22 Apr 2023 11:43:07 +0200 +Subject: [PATCH 03/12] cachy Signed-off-by: Peter Jung --- - .gitignore | 1 + - .../admin-guide/kernel-parameters.txt | 9 + - Documentation/dontdiff | 1 + - Makefile | 8 +- - arch/arc/configs/axs101_defconfig | 1 + - arch/arc/configs/axs103_defconfig | 1 + - arch/arc/configs/axs103_smp_defconfig | 1 + - arch/arc/configs/haps_hs_defconfig | 1 + - arch/arc/configs/haps_hs_smp_defconfig | 1 + - arch/arc/configs/hsdk_defconfig | 1 + - arch/arc/configs/nsim_700_defconfig | 1 + - arch/arc/configs/nsimosci_defconfig | 1 + - arch/arc/configs/nsimosci_hs_defconfig | 1 + - arch/arc/configs/nsimosci_hs_smp_defconfig | 1 + - arch/arc/configs/tb10x_defconfig | 1 + - arch/arc/configs/vdk_hs38_defconfig | 1 + - arch/arc/configs/vdk_hs38_smp_defconfig | 1 + - arch/x86/Kconfig.cpu | 416 ++++++++++- - arch/x86/Makefile | 45 +- - arch/x86/Makefile.postlink | 41 ++ - arch/x86/boot/compressed/.gitignore | 1 - - arch/x86/boot/compressed/Makefile | 10 +- - arch/x86/include/asm/vermagic.h | 72 ++ - drivers/Makefile | 15 +- - drivers/i2c/busses/Kconfig | 9 + - drivers/i2c/busses/Makefile | 1 + - drivers/i2c/busses/i2c-nct6775.c | 647 ++++++++++++++++++ - drivers/i2c/busses/i2c-piix4.c | 4 +- - drivers/md/dm-crypt.c | 5 + - drivers/pci/quirks.c | 101 +++ - drivers/platform/x86/Kconfig | 14 + - drivers/platform/x86/Makefile | 3 + - drivers/platform/x86/steamdeck.c | 523 ++++++++++++++ - include/linux/pagemap.h | 2 +- - include/linux/user_namespace.h | 4 + - include/net/netns/ipv4.h | 1 + - include/trace/events/tcp.h | 7 + - init/Kconfig | 39 ++ - kernel/Kconfig.hz | 24 + - kernel/fork.c | 14 + - kernel/module/Kconfig | 25 + - kernel/sched/fair.c | 20 +- - kernel/sysctl.c | 12 + - kernel/user_namespace.c | 7 + - mm/Kconfig | 2 +- - mm/compaction.c | 4 + - mm/page-writeback.c | 8 + - mm/swap.c | 5 + - mm/vmpressure.c | 4 + - mm/vmscan.c | 8 + - net/ipv4/sysctl_net_ipv4.c | 7 + - net/ipv4/tcp_input.c | 36 + - net/ipv4/tcp_ipv4.c | 2 + - scripts/Makefile.lib | 13 +- - scripts/Makefile.modinst | 7 +- - 55 files changed, 2144 insertions(+), 46 deletions(-) + .gitignore | 1 + + .../admin-guide/kernel-parameters.txt | 9 + + Documentation/dontdiff | 1 + + Makefile | 8 +- + arch/arc/configs/axs101_defconfig | 1 + + arch/arc/configs/axs103_defconfig | 1 + + arch/arc/configs/axs103_smp_defconfig | 1 + + arch/arc/configs/haps_hs_defconfig | 1 + + arch/arc/configs/haps_hs_smp_defconfig | 1 + + arch/arc/configs/hsdk_defconfig | 1 + + arch/arc/configs/nsim_700_defconfig | 1 + + arch/arc/configs/nsimosci_defconfig | 1 + + arch/arc/configs/nsimosci_hs_defconfig | 1 + + arch/arc/configs/nsimosci_hs_smp_defconfig | 1 + + arch/arc/configs/tb10x_defconfig | 1 + + arch/arc/configs/vdk_hs38_defconfig | 1 + + arch/arc/configs/vdk_hs38_smp_defconfig | 1 + + arch/x86/Kconfig.cpu | 416 ++- + arch/x86/Makefile | 45 +- + arch/x86/Makefile.postlink | 41 + + arch/x86/boot/compressed/.gitignore | 1 - + arch/x86/boot/compressed/Makefile | 10 +- + arch/x86/include/asm/vermagic.h | 72 + + drivers/Makefile | 15 +- + drivers/i2c/busses/Kconfig | 9 + + drivers/i2c/busses/Makefile | 1 + + drivers/i2c/busses/i2c-nct6775.c | 647 ++++ + drivers/i2c/busses/i2c-piix4.c | 4 +- + drivers/md/dm-crypt.c | 5 + + drivers/pci/quirks.c | 101 + + drivers/platform/x86/Kconfig | 24 + + drivers/platform/x86/Makefile | 4 + + drivers/platform/x86/legion-laptop.c | 2783 +++++++++++++++++ + drivers/platform/x86/steamdeck.c | 523 ++++ + include/linux/pagemap.h | 2 +- + include/linux/user_namespace.h | 4 + + include/net/netns/ipv4.h | 1 + + include/trace/events/tcp.h | 7 + + init/Kconfig | 39 + + kernel/Kconfig.hz | 24 + + kernel/fork.c | 14 + + kernel/module/Kconfig | 25 + + kernel/sched/fair.c | 20 +- + kernel/sysctl.c | 12 + + kernel/user_namespace.c | 7 + + mm/Kconfig | 2 +- + mm/compaction.c | 4 + + mm/page-writeback.c | 8 + + mm/swap.c | 5 + + mm/vmpressure.c | 4 + + mm/vmscan.c | 8 + + net/ipv4/sysctl_net_ipv4.c | 7 + + net/ipv4/tcp_input.c | 36 + + net/ipv4/tcp_ipv4.c | 2 + + scripts/Makefile.lib | 13 +- + scripts/Makefile.modinst | 7 +- + 56 files changed, 4938 insertions(+), 46 deletions(-) create mode 100644 arch/x86/Makefile.postlink create mode 100644 drivers/i2c/busses/i2c-nct6775.c + create mode 100644 drivers/platform/x86/legion-laptop.c create mode 100644 drivers/platform/x86/steamdeck.c diff --git a/.gitignore b/.gitignore @@ -3400,7 +3411,7 @@ index 70ec6037fa7a..9bafd3c6bb5f 100644 /vmlinux-gdb.py /vmlinuz diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt -index 6221a1d057dd..4f6761a93715 100644 +index 7016cb12dc4e..736233f95d59 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -4190,6 +4190,15 @@ @@ -3432,7 +3443,7 @@ index 3c399f132e2d..a62ad01e6d11 100644 vmlinuz voffset.h diff --git a/Makefile b/Makefile -index 5aeea3d98fc0..c6249845f6a1 100644 +index f5543eef4f82..44c927047211 100644 --- a/Makefile +++ b/Makefile @@ -818,6 +818,9 @@ KBUILD_CFLAGS += $(call cc-disable-warning, address-of-packed-member) @@ -5244,10 +5255,27 @@ index 44cab813bf95..25edf55de985 100644 }; diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig -index 4a01b315e0a9..e9ddf76b8b57 100644 +index 4a01b315e0a9..e4a6c31a80df 100644 --- a/drivers/platform/x86/Kconfig +++ b/drivers/platform/x86/Kconfig -@@ -1099,6 +1099,20 @@ config WINMATE_FM07_KEYS +@@ -641,6 +641,16 @@ config THINKPAD_LMI + To compile this driver as a module, choose M here: the module will + be called think-lmi. + ++config LEGION_LAPTOP ++ tristate "Lenovo Legion Laptop Extras" ++ depends on ACPI ++ depends on ACPI_WMI || ACPI_WMI = n ++ depends on HWMON || HWMON = n ++ select ACPI_PLATFORM_PROFILE ++ help ++ This is a driver for Lenovo Legion laptops and contains drivers for ++ hotkey, fan control, and power mode. ++ + source "drivers/platform/x86/intel/Kconfig" + + config MSI_LAPTOP +@@ -1099,6 +1109,20 @@ config WINMATE_FM07_KEYS buttons below the display. This module adds an input device that delivers key events when these buttons are pressed. @@ -5269,16 +5297,2813 @@ index 4a01b315e0a9..e9ddf76b8b57 100644 config P2SB diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile -index 1d3d1b02541b..75b30a3face9 100644 +index 1d3d1b02541b..fde9a683103e 100644 --- a/drivers/platform/x86/Makefile +++ b/drivers/platform/x86/Makefile -@@ -134,3 +134,6 @@ obj-$(CONFIG_SIEMENS_SIMATIC_IPC) += simatic-ipc.o +@@ -66,6 +66,7 @@ obj-$(CONFIG_IDEAPAD_LAPTOP) += ideapad-laptop.o + obj-$(CONFIG_SENSORS_HDAPS) += hdaps.o + obj-$(CONFIG_THINKPAD_ACPI) += thinkpad_acpi.o + obj-$(CONFIG_THINKPAD_LMI) += think-lmi.o ++obj-$(CONFIG_LEGION_LAPTOP) += legion-laptop.o + + # Intel + obj-y += intel/ +@@ -134,3 +135,6 @@ obj-$(CONFIG_SIEMENS_SIMATIC_IPC) += simatic-ipc.o # Winmate obj-$(CONFIG_WINMATE_FM07_KEYS) += winmate-fm07-keys.o + +# Steam Deck +obj-$(CONFIG_STEAMDECK) += steamdeck.o +diff --git a/drivers/platform/x86/legion-laptop.c b/drivers/platform/x86/legion-laptop.c +new file mode 100644 +index 000000000000..d1268d239cc5 +--- /dev/null ++++ b/drivers/platform/x86/legion-laptop.c +@@ -0,0 +1,2783 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * legion-laptop.c - Extra Lenovo Legion laptop support, in ++ * particular for fan curve control and power mode. ++ * ++ * Copyright (C) 2022 johnfan ++ * ++ * ++ * This driver might work on other Lenovo Legion models. If you ++ * want to try it you can pass force=1 as argument ++ * to the module which will force it to load even when the DMI ++ * data doesn't match the model AND FIRMWARE. ++ * ++ * Support for other hardware of this model is already partially ++ * provided by the module ideapd-laptop. ++ * ++ * The development page for this driver is located at ++ * https://github.com/johnfanv2/LenovoLegionLinux ++ * ++ * This driver exports the files: ++ * - /sys/kernel/debug/legion/fancurve (ro) ++ * The fan curve in the form stored in the firmware in an ++ * human readable table. ++ * ++ * - /sys/module/legion_laptop/drivers/platform\:legion/PNP0C09\:00/powermode (rw) ++ * 0: balanced mode (white) ++ * 1: performance mode (red) ++ * 2: quiet mode (blue) ++ * ?: custom mode (pink) ++ * ++ * NOTE: Writing to this will load the default fan curve from ++ * the firmware for this mode, so the fan curve might ++ * have to be reconfigured if needed. ++ * ++ * It implements the usual hwmon interface to monitor fan speed and temmperature ++ * and allows to set the fan curve inside the firware. ++ * ++ * - /sys/class/hwmon/X/fan1_input or /sys/class/hwmon/X/fan2_input (ro) ++ * Current fan speed of fan1/fan2. ++ * - /sys/class/hwmon/X/temp1_input (ro) ++ * - /sys/class/hwmon/X/temp2_input (ro) ++ * - /sys/class/hwmon/X/temp3_input (ro) ++ * Temperature (Celsius) of CPU, GPU, and IC used for fan control. ++ * - /sys/class/hwmon/X/pwmY_auto_pointZ_pwm (rw) ++ * PWM (0-255) of the fan at the Y-level in the fan curve ++ * - /sys/class/hwmon/X/pwmY_auto_pointZ_temp (rw) ++ * upper temperature of tempZ (CPU, GPU, or IC) at the Y-level in the fan curve ++ * - /sys/class/hwmon/X/pwmY_auto_pointZ_temp_hyst (rw) ++ * hysteris (CPU, GPU, or IC) at the Y-level in the fan curve. The lower ++ * temperatue of the level is the upper temperature minus the hysteris ++ * ++ * ++ * Credits for reverse engineering the firmware to: ++ * - David Woodhouse: heavily inspired by lenovo_laptop.c ++ * - Luke Cama: Windows version "LegionFanControl" ++ * - SmokelessCPU: reverse engineering of custom registers in EC ++ * and commincation method with EC via ports ++ * - 0x1F9F1: additional reverse engineering for complete fan curve ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++MODULE_LICENSE("GPL"); ++MODULE_AUTHOR("johnfan"); ++MODULE_DESCRIPTION("Lenovo Legion laptop extras"); ++ ++static bool force; ++module_param(force, bool, 0440); ++MODULE_PARM_DESC( ++ force, ++ "Force loading this module even if model or BIOS does not match."); ++ ++static bool ec_readonly; ++module_param(ec_readonly, bool, 0440); ++MODULE_PARM_DESC( ++ ec_readonly, ++ "Only read from embedded controller but do not write or change settings."); ++ ++#define LEGIONFEATURES \ ++ "fancurve powermode platformprofile platformprofilenotify minifancurve" ++ ++//Size of fancurve stored in embedded controller ++#define MAXFANCURVESIZE 10 ++ ++#define LEGION_DRVR_SHORTNAME "legion" ++#define LEGION_HWMON_NAME LEGION_DRVR_SHORTNAME "_hwmon" ++ ++/* =============================== */ ++/* Embedded Controller Description */ ++/* =============================== */ ++ ++/* The configuration and registers to access the embedded controller ++ * depending on different the version of the software on the ++ * embedded controller or and the BIOS/UEFI firmware. ++ * ++ * To control fan curve in the embedded controller (EC) one has to ++ * write to its "RAM". There are different possibilities: ++ * - EC RAM is memory mapped (write to it with ioremap) ++ * - access EC RAM via ported mapped IO (outb/inb) ++ * - access EC RAM via ACPI methods. It is only possible to write ++ * to part of it (first 0xFF bytes?) ++ * ++ * In later models the firmware directly exposes ACPI methods to ++ * set the fan curve direclty, without writing to EC RAM. This ++ * is done inside the ACPI method. ++ */ ++ ++/** ++ * Offsets for interseting values inside the EC RAM (0 = start of ++ * EC RAM. These might change depending on the software inside of ++ * the EC, which can be updated by a BIOS update from Lenovo. ++ */ ++// TODO: same order as in initialization ++struct ec_register_offsets { ++ // Super I/O Configuration Registers ++ // 7.15 General Control (GCTRL) ++ // General Control (GCTRL) ++ // (see EC Interface Registers and 6.2 Plug and Play Configuration (PNPCFG)) in datasheet ++ // note: these are in two places saved ++ // in EC Interface Registers and in super io configuraion registers ++ // Chip ID ++ u16 ECHIPID1; ++ u16 ECHIPID2; ++ // Chip Version ++ u16 ECHIPVER; ++ u16 ECDEBUG; ++ ++ // Lenovo Custom OEM extension ++ // Firmware of ITE can be extended by ++ // custom program using its own "variables" ++ // These are the offsets to these "variables" ++ u16 EXT_FAN_CUR_POINT; ++ u16 EXT_FAN_POINTS_SIZE; ++ u16 EXT_FAN1_BASE; ++ u16 EXT_FAN2_BASE; ++ u16 EXT_FAN_ACC_BASE; ++ u16 EXT_FAN_DEC_BASE; ++ u16 EXT_CPU_TEMP; ++ u16 EXT_CPU_TEMP_HYST; ++ u16 EXT_GPU_TEMP; ++ u16 EXT_GPU_TEMP_HYST; ++ u16 EXT_VRM_TEMP; ++ u16 EXT_VRM_TEMP_HYST; ++ u16 EXT_FAN1_RPM_LSB; ++ u16 EXT_FAN1_RPM_MSB; ++ u16 EXT_FAN2_RPM_LSB; ++ u16 EXT_FAN2_RPM_MSB; ++ u16 EXT_FAN1_TARGET_RPM; ++ u16 EXT_FAN2_TARGET_RPM; ++ u16 EXT_POWERMODE; ++ u16 EXT_MINIFANCURVE_ON_COOL; ++ // values ++ // 0x04: enable mini fan curve if very long on cool level ++ // - this might be due to potential temp failure ++ // - or just because really so cool ++ // 0xA0: disable it ++ u16 EXT_LOCKFANCONTROLLER; ++ u16 EXT_MAXIMUMFANSPEED; ++ u16 EXT_WHITE_KEYBOARD_BACKLIGHT; ++ u16 EXT_IC_TEMP_INPUT; ++ u16 EXT_CPU_TEMP_INPUT; ++ u16 EXT_GPU_TEMP_INPUT; ++}; ++ ++struct model_config { ++ const struct ec_register_offsets *registers; ++ bool check_embedded_controller_id; ++ u16 embedded_controller_id; ++ ++ // first addr in EC we access/scan ++ phys_addr_t memoryio_physical_ec_start; ++ size_t memoryio_size; ++ ++ // TODO: maybe use bitfield ++ bool has_minifancurve; ++}; ++ ++/* =================================== */ ++/* Coinfiguration for different models */ ++/* =================================== */ ++ ++// Idea by SmokelesssCPU (modified) ++// - all default names and register addresses are supported by datasheet ++// - register addresses for custom firmware by SmokelesssCPU ++static const struct ec_register_offsets ec_register_offsets_v0 = { ++ .ECHIPID1 = 0x2000, ++ .ECHIPID2 = 0x2001, ++ .ECHIPVER = 0x2002, ++ .ECDEBUG = 0x2003, ++ .EXT_FAN_CUR_POINT = 0xC534, ++ .EXT_FAN_POINTS_SIZE = 0xC535, ++ .EXT_FAN1_BASE = 0xC540, ++ .EXT_FAN2_BASE = 0xC550, ++ .EXT_FAN_ACC_BASE = 0xC560, ++ .EXT_FAN_DEC_BASE = 0xC570, ++ .EXT_CPU_TEMP = 0xC580, ++ .EXT_CPU_TEMP_HYST = 0xC590, ++ .EXT_GPU_TEMP = 0xC5A0, ++ .EXT_GPU_TEMP_HYST = 0xC5B0, ++ .EXT_VRM_TEMP = 0xC5C0, ++ .EXT_VRM_TEMP_HYST = 0xC5D0, ++ .EXT_FAN1_RPM_LSB = 0xC5E0, ++ .EXT_FAN1_RPM_MSB = 0xC5E1, ++ .EXT_FAN2_RPM_LSB = 0xC5E2, ++ .EXT_FAN2_RPM_MSB = 0xC5E3, ++ .EXT_MINIFANCURVE_ON_COOL = 0xC536, ++ .EXT_LOCKFANCONTROLLER = 0xc4AB, ++ .EXT_CPU_TEMP_INPUT = 0xc538, ++ .EXT_GPU_TEMP_INPUT = 0xc539, ++ .EXT_IC_TEMP_INPUT = 0xC5E8, ++ .EXT_POWERMODE = 0xc420, ++ .EXT_FAN1_TARGET_RPM = 0xc600, ++ .EXT_FAN2_TARGET_RPM = 0xc601, ++ .EXT_MAXIMUMFANSPEED = 0xBD, ++ .EXT_WHITE_KEYBOARD_BACKLIGHT = (0x3B + 0xC400) ++}; ++ ++static const struct model_config model_v0 = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = true, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, ++ .memoryio_size = 0x300, ++ .has_minifancurve = true ++}; ++ ++static const struct model_config model_kfcn = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = true, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, ++ .memoryio_size = 0x300, ++ .has_minifancurve = false ++}; ++ ++static const struct model_config model_hacn = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = false, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, ++ .memoryio_size = 0x300, ++ .has_minifancurve = false ++}; ++ ++ ++static const struct model_config model_k9cn = { ++ .registers = &ec_register_offsets_v0, ++ .check_embedded_controller_id = false, ++ .embedded_controller_id = 0x8227, ++ .memoryio_physical_ec_start = 0xC400, // or replace 0xC400 by 0x0400 ? ++ .memoryio_size = 0x300, ++ .has_minifancurve = false ++}; ++ ++ ++ ++static const struct dmi_system_id denylist[] = { {} }; ++ ++static const struct dmi_system_id optimistic_allowlist[] = { ++ { ++ // modelyear: 2021 ++ // generation: 6 ++ // name: Legion 5, Legion 5 pro, Legion 7 ++ // Family: Legion 5 15ACH6H, ... ++ .ident = "GKCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "GKCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2020 ++ .ident = "EUCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "EUCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2020 ++ .ident = "EFCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "EFCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2020 ++ .ident = "FSCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "FSCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2021 ++ .ident = "HHCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "HHCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2022 ++ .ident = "H1CN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "H1CN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2022 ++ .ident = "J2CN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "J2CN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2022 ++ .ident = "JUCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "JUCN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2022 ++ .ident = "KFCN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "KFCN"), ++ }, ++ .driver_data = (void *)&model_kfcn ++ }, ++ { ++ // modelyear: 2021 ++ .ident = "HACN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "HACN"), ++ }, ++ .driver_data = (void *)&model_hacn ++ }, ++ { ++ // modelyear: 2021 ++ .ident = "G9CN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "G9CN"), ++ }, ++ .driver_data = (void *)&model_v0 ++ }, ++ { ++ // modelyear: 2022 ++ .ident = "K9CN", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), ++ DMI_MATCH(DMI_BIOS_VERSION, "K9CN"), ++ }, ++ .driver_data = (void *)&model_k9cn ++ }, ++ {} ++}; ++ ++/* ================================= */ ++/* ACPI access */ ++/* ================================= */ ++ ++// function from ideapad-laptop.c ++static int eval_int(acpi_handle handle, const char *name, unsigned long *res) ++{ ++ unsigned long long result; ++ acpi_status status; ++ ++ status = acpi_evaluate_integer(handle, (char *)name, NULL, &result); ++ if (ACPI_FAILURE(status)) ++ return -EIO; ++ ++ *res = result; ++ ++ return 0; ++} ++ ++// function from ideapad-laptop.c ++static int exec_simple_method(acpi_handle handle, const char *name, ++ unsigned long arg) ++{ ++ acpi_status status = ++ acpi_execute_simple_method(handle, (char *)name, arg); ++ ++ return ACPI_FAILURE(status) ? -EIO : 0; ++} ++ ++// function from ideapad-laptop.c ++static int exec_sbmc(acpi_handle handle, unsigned long arg) ++{ ++ // \_SB.PCI0.LPC0.EC0.VPC0.SBMC ++ return exec_simple_method(handle, "SBMC", arg); ++} ++ ++static int eval_qcho(acpi_handle handle, unsigned long *res) ++{ ++ // \_SB.PCI0.LPC0.EC0.QCHO ++ return eval_int(handle, "QCHO", res); ++} ++ ++/* ================================= */ ++/* EC RAM Access with port-mapped IO */ ++/* ================================= */ ++ ++/* ++ * See datasheet of e.g. IT8502E/F/G, e.g. ++ * 6.2 Plug and Play Configuration (PNPCFG) ++ * ++ * Depending on configured BARDSEL register ++ * the ports ++ * ECRAM_PORTIO_ADDR_PORT and ++ * ECRAM_PORTIO_DATA_PORT ++ * are configured. ++ * ++ * By performing IO on these ports one can ++ * read/write to registers in the EC. ++ * ++ * "To access a register of PNPCFG, write target index to ++ * address port and access this PNPCFG register via ++ * data port" [datasheet, 6.2 Plug and Play Configuration] ++ */ ++ ++// IO ports used to write to communicate with embedded controller ++// Start of used ports ++#define ECRAM_PORTIO_START_PORT 0x4E ++// Number of used ports ++#define ECRAM_PORTIO_PORTS_SIZE 2 ++// Port used to specify address in EC RAM to read/write ++// 0x4E/0x4F is the usual port for IO super controler ++// 0x2E/0x2F also common (ITE can also be configure to use these) ++#define ECRAM_PORTIO_ADDR_PORT 0x4E ++// Port to send/receive the value to write/read ++#define ECRAM_PORTIO_DATA_PORT 0x4F ++// Name used to request ports ++#define ECRAM_PORTIO_NAME "legion" ++ ++struct ecram_portio { ++ /* protects read/write to EC RAM performed ++ * as a certain sequence of outb, inb ++ * commands on the IO ports. There can ++ * be at most one. ++ */ ++ struct mutex io_port_mutex; ++}; ++ ++ssize_t ecram_portio_init(struct ecram_portio *ec_portio) ++{ ++ if (!request_region(ECRAM_PORTIO_START_PORT, ECRAM_PORTIO_PORTS_SIZE, ++ ECRAM_PORTIO_NAME)) { ++ pr_info("Cannot init ecram_portio the %x ports starting at %x\n", ++ ECRAM_PORTIO_PORTS_SIZE, ECRAM_PORTIO_START_PORT); ++ return -ENODEV; ++ } ++ //pr_info("Reserved %x ports starting at %x\n", ECRAM_PORTIO_PORTS_SIZE, ECRAM_PORTIO_START_PORT); ++ mutex_init(&ec_portio->io_port_mutex); ++ return 0; ++} ++ ++void ecram_portio_exit(struct ecram_portio *ec_portio) ++{ ++ release_region(ECRAM_PORTIO_START_PORT, ECRAM_PORTIO_PORTS_SIZE); ++} ++ ++/* Read a byte from the EC RAM. ++ * ++ * Return status because of commong signature for alle ++ * methods to access EC RAM. ++ */ ++ssize_t ecram_portio_read(struct ecram_portio *ec_portio, u16 offset, u8 *value) ++{ ++ mutex_lock(&ec_portio->io_port_mutex); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x11, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ // TODO: no explicit cast between types seems to be sometimes ++ // done and sometimes not ++ outb((u8)((offset >> 8) & 0xFF), ECRAM_PORTIO_DATA_PORT); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x10, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ outb((u8)(offset & 0xFF), ECRAM_PORTIO_DATA_PORT); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x12, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ *value = inb(ECRAM_PORTIO_DATA_PORT); ++ ++ mutex_unlock(&ec_portio->io_port_mutex); ++ return 0; ++} ++ ++/* Write a byte to the EC RAM. ++ * ++ * Return status because of commong signature for alle ++ * methods to access EC RAM. ++ */ ++ssize_t ecram_portio_write(struct ecram_portio *ec_portio, u16 offset, u8 value) ++{ ++ mutex_lock(&ec_portio->io_port_mutex); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x11, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ // TODO: no explicit cast between types seems to be sometimes ++ // done and sometimes not ++ outb((u8)((offset >> 8) & 0xFF), ECRAM_PORTIO_DATA_PORT); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x10, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ outb((u8)(offset & 0xFF), ECRAM_PORTIO_DATA_PORT); ++ ++ outb(0x2E, ECRAM_PORTIO_ADDR_PORT); ++ outb(0x12, ECRAM_PORTIO_DATA_PORT); ++ outb(0x2F, ECRAM_PORTIO_ADDR_PORT); ++ outb(value, ECRAM_PORTIO_DATA_PORT); ++ ++ mutex_unlock(&ec_portio->io_port_mutex); ++ return 0; ++} ++ ++/* =================================== */ ++/* EC RAM Access */ ++/* =================================== */ ++ ++struct ecram { ++ struct ecram_portio portio; ++}; ++ ++ssize_t ecram_init(struct ecram *ecram, phys_addr_t memoryio_ec_physical_start, ++ size_t region_size) ++{ ++ ssize_t err; ++ ++ err = ecram_portio_init(&ecram->portio); ++ if (err) { ++ pr_info("Failed ecram_portio_init\n"); ++ goto err_ecram_portio_init; ++ } ++ ++ return 0; ++ ++err_ecram_portio_init: ++ return err; ++} ++ ++void ecram_exit(struct ecram *ecram) ++{ ++ pr_info("Unloading legion ecram\n"); ++ ecram_portio_exit(&ecram->portio); ++ pr_info("Unloading legion ecram done\n"); ++} ++ ++/** ++ * ecram_offset address on the EC ++ */ ++static u8 ecram_read(struct ecram *ecram, u16 ecram_offset) ++{ ++ u8 value; ++ int err; ++ ++ err = ecram_portio_read(&ecram->portio, ecram_offset, &value); ++ if (err) ++ pr_info("Error reading EC RAM at 0x%x\n", ecram_offset); ++ return value; ++} ++ ++static void ecram_write(struct ecram *ecram, u16 ecram_offset, u8 value) ++{ ++ int err; ++ ++ if (ec_readonly) { ++ pr_info("Skipping writing EC RAM at 0x%x because readonly.\n", ++ ecram_offset); ++ return; ++ } ++ err = ecram_portio_write(&ecram->portio, ecram_offset, value); ++ if (err) ++ pr_info("Error writing EC RAM at 0x%x\n", ecram_offset); ++} ++ ++/* =============================== */ ++/* Reads from EC */ ++/* =============================== */ ++ ++u16 read_ec_id(struct ecram *ecram, const struct model_config *model) ++{ ++ u8 id1 = ecram_read(ecram, model->registers->ECHIPID1); ++ u8 id2 = ecram_read(ecram, model->registers->ECHIPID2); ++ ++ return (id1 << 8) + id2; ++} ++ ++u16 read_ec_version(struct ecram *ecram, const struct model_config *model) ++{ ++ u8 vers = ecram_read(ecram, model->registers->ECHIPVER); ++ u8 debug = ecram_read(ecram, model->registers->ECDEBUG); ++ ++ return (vers << 8) + debug; ++} ++ ++/* ============================= */ ++/* Data model for sensor values */ ++/* ============================ */ ++ ++struct sensor_values { ++ u16 fan1_rpm; // current speed in rpm of fan 1 ++ u16 fan2_rpm; // current speed in rpm of fan2 ++ u16 fan1_target_rpm; // target speed in rpm of fan 1 ++ u16 fan2_target_rpm; // target speed in rpm of fan 2 ++ u8 cpu_temp_celsius; // cpu temperature in celcius ++ u8 gpu_temp_celsius; // gpu temperature in celcius ++ u8 ic_temp_celsius; // ic temperature in celcius ++}; ++ ++enum SENSOR_ATTR { ++ SENSOR_CPU_TEMP_ID = 1, ++ SENSOR_GPU_TEMP_ID = 2, ++ SENSOR_IC_TEMP_ID = 3, ++ SENSOR_FAN1_RPM_ID = 4, ++ SENSOR_FAN2_RPM_ID = 5, ++ SENSOR_FAN1_TARGET_RPM_ID = 6, ++ SENSOR_FAN2_TARGET_RPM_ID = 7 ++}; ++ ++static int read_sensor_values(struct ecram *ecram, ++ const struct model_config *model, ++ struct sensor_values *values) ++{ ++ values->fan1_target_rpm = ++ 100 * ecram_read(ecram, model->registers->EXT_FAN1_TARGET_RPM); ++ values->fan2_target_rpm = ++ 100 * ecram_read(ecram, model->registers->EXT_FAN2_TARGET_RPM); ++ ++ values->fan1_rpm = ++ ecram_read(ecram, model->registers->EXT_FAN1_RPM_LSB) + ++ (((int)ecram_read(ecram, model->registers->EXT_FAN1_RPM_MSB)) ++ << 8); ++ values->fan2_rpm = ++ ecram_read(ecram, model->registers->EXT_FAN2_RPM_LSB) + ++ (((int)ecram_read(ecram, model->registers->EXT_FAN2_RPM_MSB)) ++ << 8); ++ ++ values->cpu_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_CPU_TEMP_INPUT); ++ values->gpu_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_GPU_TEMP_INPUT); ++ values->ic_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_IC_TEMP_INPUT); ++ ++ values->cpu_temp_celsius = ecram_read(ecram, 0xC5E6); ++ values->gpu_temp_celsius = ecram_read(ecram, 0xC5E7); ++ values->ic_temp_celsius = ecram_read(ecram, 0xC5E8); ++ ++ return 0; ++} ++ ++/* =============================== */ ++/* Behaviour changing functions */ ++/* =============================== */ ++ ++int read_powermode(struct ecram *ecram, const struct model_config *model) ++{ ++ return ecram_read(ecram, model->registers->EXT_POWERMODE); ++} ++ ++ssize_t write_powermode(struct ecram *ecram, const struct model_config *model, ++ u8 value) ++{ ++ if (!(value >= 0 && value <= 2)) { ++ pr_info("Unexpected power mode value ignored: %d\n", value); ++ return -ENOMEM; ++ } ++ ecram_write(ecram, model->registers->EXT_POWERMODE, value); ++ return 0; ++} ++ ++/** ++ * Shortly toggle powermode to a different mode ++ * and switch back, e.g. to reset fan curve. ++ */ ++void toggle_powermode(struct ecram *ecram, const struct model_config *model) ++{ ++ int old_powermode = read_powermode(ecram, model); ++ int next_powermode = old_powermode == 0 ? 1 : 0; ++ ++ write_powermode(ecram, model, next_powermode); ++ mdelay(1500); ++ write_powermode(ecram, model, old_powermode); ++} ++ ++#define lockfancontroller_ON 8 ++#define lockfancontroller_OFF 0 ++ ++ssize_t write_lockfancontroller(struct ecram *ecram, ++ const struct model_config *model, bool state) ++{ ++ u8 val = state ? lockfancontroller_ON : lockfancontroller_OFF; ++ ++ ecram_write(ecram, model->registers->EXT_LOCKFANCONTROLLER, val); ++ return 0; ++} ++ ++int read_lockfancontroller(struct ecram *ecram, ++ const struct model_config *model, bool *state) ++{ ++ int value = ecram_read(ecram, model->registers->EXT_LOCKFANCONTROLLER); ++ ++ switch (value) { ++ case lockfancontroller_ON: ++ *state = true; ++ break; ++ case lockfancontroller_OFF: ++ *state = false; ++ break; ++ default: ++ pr_info("Unexpected value in lockfanspeed register:%d\n", ++ value); ++ return -1; ++ } ++ return 0; ++} ++ ++#define MAXIMUMFANSPEED_ON 0x40 ++#define MAXIMUMFANSPEED_OFF 0x00 ++ ++int read_maximumfanspeed(struct ecram *ecram, const struct model_config *model, ++ bool *state) ++{ ++ int value = ecram_read(ecram, model->registers->EXT_MAXIMUMFANSPEED); ++ ++ switch (value) { ++ case MAXIMUMFANSPEED_ON: ++ *state = true; ++ break; ++ case MAXIMUMFANSPEED_OFF: ++ *state = false; ++ break; ++ default: ++ pr_info("Unexpected value in maximumfanspeed register:%d\n", ++ value); ++ return -1; ++ } ++ return 0; ++} ++ ++ssize_t write_maximumfanspeed(struct ecram *ecram, ++ const struct model_config *model, bool state) ++{ ++ u8 val = state ? MAXIMUMFANSPEED_ON : MAXIMUMFANSPEED_OFF; ++ ++ ecram_write(ecram, model->registers->EXT_MAXIMUMFANSPEED, val); ++ return 0; ++} ++ ++#define MINIFANCUVE_ON_COOL_ON 0x04 ++#define MINIFANCUVE_ON_COOL_OFF 0xA0 ++ ++int read_minifancurve(struct ecram *ecram, const struct model_config *model, ++ bool *state) ++{ ++ int value = ++ ecram_read(ecram, model->registers->EXT_MINIFANCURVE_ON_COOL); ++ ++ switch (value) { ++ case MINIFANCUVE_ON_COOL_ON: ++ *state = true; ++ break; ++ case MINIFANCUVE_ON_COOL_OFF: ++ *state = false; ++ break; ++ default: ++ pr_info("Unexpected value in MINIFANCURVE register:%d\n", ++ value); ++ return -1; ++ } ++ return 0; ++} ++ ++ssize_t write_minifancurve(struct ecram *ecram, ++ const struct model_config *model, bool state) ++{ ++ u8 val = state ? MINIFANCUVE_ON_COOL_ON : MINIFANCUVE_ON_COOL_OFF; ++ ++ ecram_write(ecram, model->registers->EXT_MINIFANCURVE_ON_COOL, val); ++ return 0; ++} ++ ++#define KEYBOARD_BACKLIGHT_OFF 18 ++#define KEYBOARD_BACKLIGHT_ON1 21 ++#define KEYBOARD_BACKLIGHT_ON2 23 ++ ++int read_keyboard_backlight(struct ecram *ecram, ++ const struct model_config *model, int *state) ++{ ++ int value = ecram_read(ecram, ++ model->registers->EXT_WHITE_KEYBOARD_BACKLIGHT); ++ ++ //switch (value) { ++ //case MINIFANCUVE_ON_COOL_ON: ++ // *state = true; ++ // break; ++ //case MINIFANCUVE_ON_COOL_OFF: ++ // *state = false; ++ // break; ++ //default: ++ // pr_info("Unexpected value in MINIFANCURVE register:%d\n", ++ // value); ++ // return -1; ++ //} ++ *state = value; ++ return 0; ++} ++ ++int write_keyboard_backlight(struct ecram *ecram, ++ const struct model_config *model, int state) ++{ ++ u8 val = state > 0 ? KEYBOARD_BACKLIGHT_ON1 : KEYBOARD_BACKLIGHT_OFF; ++ ++ ecram_write(ecram, model->registers->EXT_WHITE_KEYBOARD_BACKLIGHT, val); ++ return 0; ++} ++ ++#define FCT_RAPID_CHARGE_ON 0x07 ++#define FCT_RAPID_CHARGE_OFF 0x08 ++#define RAPID_CHARGE_ON 0x0 ++#define RAPID_CHARGE_OFF 0x1 ++ ++int read_rapidcharge(acpi_handle acpihandle, int *state) ++{ ++ unsigned long result; ++ int err; ++ ++ err = eval_qcho(acpihandle, &result); ++ if (err) ++ return err; ++ ++ *state = result; ++ return 0; ++} ++ ++int write_rapidcharge(acpi_handle acpihandle, bool state) ++{ ++ unsigned long fct_nr = state > 0 ? FCT_RAPID_CHARGE_ON : ++ FCT_RAPID_CHARGE_OFF; ++ return exec_sbmc(acpihandle, fct_nr); ++} ++ ++/* ============================= */ ++/* Data model for fan curve */ ++/* ============================ */ ++ ++struct fancurve_point { ++ // rpm1 devided by 100 ++ u8 rpm1_raw; ++ // rpm2 devided by 100 ++ u8 rpm2_raw; ++ // >=2 , <=5 (lower is faster); must be increasing by level ++ u8 accel; ++ // >=2 , <=5 (lower is faster); must be increasing by level ++ u8 decel; ++ ++ // min must be lower or equal than max ++ // last level max must be 127 ++ // <=127 cpu max temp for this level; must be increasing by level ++ u8 cpu_max_temp_celsius; ++ // <=127 cpu min temp for this level; must be increasing by level ++ u8 cpu_min_temp_celsius; ++ // <=127 gpu min temp for this level; must be increasing by level ++ u8 gpu_max_temp_celsius; ++ // <=127 gpu max temp for this level; must be increasing by level ++ u8 gpu_min_temp_celsius; ++ // <=127 ic max temp for this level; must be increasing by level ++ u8 ic_max_temp_celsius; ++ // <=127 ic max temp for this level; must be increasing by level ++ u8 ic_min_temp_celsius; ++}; ++ ++enum FANCURVE_ATTR { ++ FANCURVE_ATTR_PWM1 = 1, ++ FANCURVE_ATTR_PWM2 = 2, ++ FANCURVE_ATTR_CPU_TEMP = 3, ++ FANCURVE_ATTR_CPU_HYST = 4, ++ FANCURVE_ATTR_GPU_TEMP = 5, ++ FANCURVE_ATTR_GPU_HYST = 6, ++ FANCURVE_ATTR_IC_TEMP = 7, ++ FANCURVE_ATTR_IC_HYST = 8, ++ FANCURVE_ATTR_ACCEL = 9, ++ FANCURVE_ATTR_DECEL = 10, ++ FANCURVE_SIZE = 11, ++ FANCURVE_MINIFANCURVE_ON_COOL = 12 ++}; ++ ++// used for clearing table entries ++static const struct fancurve_point fancurve_point_zero = { 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0 }; ++ ++struct fancurve { ++ struct fancurve_point points[MAXFANCURVESIZE]; ++ // number of points used; must be <= MAXFANCURVESIZE ++ size_t size; ++ // the point that at which fans are run currently ++ size_t current_point_i; ++}; ++ ++// calculate derived values ++ ++int fancurve_get_cpu_deltahyst(struct fancurve_point *point) ++{ ++ return ((int)point->cpu_max_temp_celsius) - ++ ((int)point->cpu_min_temp_celsius); ++} ++ ++int fancurve_get_gpu_deltahyst(struct fancurve_point *point) ++{ ++ return ((int)point->gpu_max_temp_celsius) - ++ ((int)point->gpu_min_temp_celsius); ++} ++ ++int fancurve_get_ic_deltahyst(struct fancurve_point *point) ++{ ++ return ((int)point->ic_max_temp_celsius) - ++ ((int)point->ic_min_temp_celsius); ++} ++ ++// validation functions ++ ++bool fancurve_is_valid_min_temp(int min_temp) ++{ ++ return min_temp >= 0 && min_temp <= 127; ++} ++ ++bool fancurve_is_valid_max_temp(int max_temp) ++{ ++ return max_temp >= 0 && max_temp <= 127; ++} ++ ++// setters with validation ++// - make hwmon implementation easier ++// - keep fancurve valid, otherwise EC will not properly control fan ++ ++bool fancurve_set_rpm1(struct fancurve *fancurve, int point_id, int rpm) ++{ ++ bool valid = point_id == 0 ? rpm == 0 : (rpm >= 0 && rpm <= 4500); ++ ++ if (valid) ++ fancurve->points[point_id].rpm1_raw = rpm / 100; ++ return valid; ++} ++ ++bool fancurve_set_rpm2(struct fancurve *fancurve, int point_id, int rpm) ++{ ++ bool valid = point_id == 0 ? rpm == 0 : (rpm >= 0 && rpm <= 4500); ++ ++ if (valid) ++ fancurve->points[point_id].rpm2_raw = rpm / 100; ++ return valid; ++} ++ ++// TODO: remove { ... } from single line if body ++ ++bool fancurve_set_accel(struct fancurve *fancurve, int point_id, int accel) ++{ ++ bool valid = accel >= 2 && accel <= 5; ++ ++ if (valid) ++ fancurve->points[point_id].accel = accel; ++ return valid; ++} ++ ++bool fancurve_set_decel(struct fancurve *fancurve, int point_id, int decel) ++{ ++ bool valid = decel >= 2 && decel <= 5; ++ ++ if (valid) ++ fancurve->points[point_id].decel = decel; ++ return valid; ++} ++ ++bool fancurve_set_cpu_temp_max(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].cpu_max_temp_celsius = value; ++ ++ return valid; ++} ++ ++bool fancurve_set_gpu_temp_max(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].gpu_max_temp_celsius = value; ++ return valid; ++} ++ ++bool fancurve_set_ic_temp_max(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].ic_max_temp_celsius = value; ++ return valid; ++} ++ ++bool fancurve_set_cpu_temp_min(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].cpu_min_temp_celsius = value; ++ return valid; ++} ++ ++bool fancurve_set_gpu_temp_min(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].gpu_min_temp_celsius = value; ++ return valid; ++} ++ ++bool fancurve_set_ic_temp_min(struct fancurve *fancurve, int point_id, ++ int value) ++{ ++ bool valid = fancurve_is_valid_max_temp(value); ++ ++ if (valid) ++ fancurve->points[point_id].ic_min_temp_celsius = value; ++ return valid; ++} ++ ++bool fancurve_set_size(struct fancurve *fancurve, int size, bool init_values) ++{ ++ bool valid = size >= 1 && size <= MAXFANCURVESIZE; ++ ++ if (!valid) ++ return false; ++ if (init_values && size < fancurve->size) { ++ // fancurve size is decreased, but last etnry alwasy needs 127 temperatures ++ // Note: size >=1 ++ fancurve->points[size - 1].cpu_max_temp_celsius = 127; ++ fancurve->points[size - 1].ic_max_temp_celsius = 127; ++ fancurve->points[size - 1].gpu_max_temp_celsius = 127; ++ } ++ if (init_values && size > fancurve->size) { ++ // fancurve increased, so new entries need valid values ++ int i; ++ int last = fancurve->size > 0 ? fancurve->size - 1 : 0; ++ ++ for (i = fancurve->size; i < size; ++i) ++ fancurve->points[i] = fancurve->points[last]; ++ } ++ return true; ++} ++ ++/* Read the fan curve from the EC. ++ * ++ * In newer models (>=2022) there is an ACPI/WMI to read fan curve as ++ * a whole. So read/write fan table as a whole to use ++ * same interface for both cases. ++ * ++ * It reads all points from EC memory, even if stored fancurve is smaller, so ++ * it can contain 0 entries. ++ */ ++static int read_fancurve(struct ecram *ecram, const struct model_config *model, ++ struct fancurve *fancurve) ++{ ++ size_t i = 0; ++ ++ for (i = 0; i < MAXFANCURVESIZE; ++i) { ++ struct fancurve_point *point = &fancurve->points[i]; ++ ++ point->rpm1_raw = ++ ecram_read(ecram, model->registers->EXT_FAN1_BASE + i); ++ point->rpm2_raw = ++ ecram_read(ecram, model->registers->EXT_FAN2_BASE + i); ++ ++ point->accel = ecram_read( ++ ecram, model->registers->EXT_FAN_ACC_BASE + i); ++ point->decel = ecram_read( ++ ecram, model->registers->EXT_FAN_DEC_BASE + i); ++ point->cpu_max_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_CPU_TEMP + i); ++ point->cpu_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_CPU_TEMP_HYST + i); ++ point->gpu_max_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_GPU_TEMP + i); ++ point->gpu_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_GPU_TEMP_HYST + i); ++ point->ic_max_temp_celsius = ++ ecram_read(ecram, model->registers->EXT_VRM_TEMP + i); ++ point->ic_min_temp_celsius = ecram_read( ++ ecram, model->registers->EXT_VRM_TEMP_HYST + i); ++ } ++ ++ // Do not trust that hardware; It might suddendly report ++ // a larger size, so clamp it. ++ fancurve->size = ++ ecram_read(ecram, model->registers->EXT_FAN_POINTS_SIZE); ++ fancurve->size = ++ min(fancurve->size, (typeof(fancurve->size))(MAXFANCURVESIZE)); ++ fancurve->current_point_i = ++ ecram_read(ecram, model->registers->EXT_FAN_CUR_POINT); ++ fancurve->current_point_i = ++ min(fancurve->current_point_i, fancurve->size); ++ return 0; ++} ++ ++static int write_fancurve(struct ecram *ecram, const struct model_config *model, ++ const struct fancurve *fancurve, bool write_size) ++{ ++ size_t i; ++ // Reset fan update counters (try to avoid any race conditions) ++ ecram_write(ecram, 0xC5FE, 0); ++ ecram_write(ecram, 0xC5FF, 0); ++ for (i = 0; i < MAXFANCURVESIZE; ++i) { ++ // Entries for points larger than fancurve size should be cleared ++ // to 0 ++ const struct fancurve_point *point = ++ i < fancurve->size ? &fancurve->points[i] : ++ &fancurve_point_zero; ++ ++ ecram_write(ecram, model->registers->EXT_FAN1_BASE + i, ++ point->rpm1_raw); ++ ecram_write(ecram, model->registers->EXT_FAN2_BASE + i, ++ point->rpm2_raw); ++ ++ ecram_write(ecram, model->registers->EXT_FAN_ACC_BASE + i, ++ point->accel); ++ ecram_write(ecram, model->registers->EXT_FAN_DEC_BASE + i, ++ point->decel); ++ ++ ecram_write(ecram, model->registers->EXT_CPU_TEMP + i, ++ point->cpu_max_temp_celsius); ++ ecram_write(ecram, model->registers->EXT_CPU_TEMP_HYST + i, ++ point->cpu_min_temp_celsius); ++ ecram_write(ecram, model->registers->EXT_GPU_TEMP + i, ++ point->gpu_max_temp_celsius); ++ ecram_write(ecram, model->registers->EXT_GPU_TEMP_HYST + i, ++ point->gpu_min_temp_celsius); ++ ecram_write(ecram, model->registers->EXT_VRM_TEMP + i, ++ point->ic_max_temp_celsius); ++ ecram_write(ecram, model->registers->EXT_VRM_TEMP_HYST + i, ++ point->ic_min_temp_celsius); ++ } ++ ++ if (write_size) { ++ ecram_write(ecram, model->registers->EXT_FAN_POINTS_SIZE, ++ fancurve->size); ++ } ++ ++ // Reset current fan level to 0, so algorithm in EC ++ // selects fan curve point again and resetting hysterisis ++ // effects ++ ecram_write(ecram, model->registers->EXT_FAN_CUR_POINT, 0); ++ ++ // Reset internal fan levels ++ ecram_write(ecram, 0xC634, 0); // CPU ++ ecram_write(ecram, 0xC635, 0); // GPU ++ ecram_write(ecram, 0xC636, 0); // SENSOR ++ ++ return 0; ++} ++ ++static ssize_t fancurve_print_seqfile(const struct fancurve *fancurve, ++ struct seq_file *s) ++{ ++ int i; ++ ++ seq_printf( ++ s, ++ "rpm1|rpm2|acceleration|deceleration|cpu_min_temp|cpu_max_temp|gpu_min_temp|gpu_max_temp|ic_min_temp|ic_max_temp\n"); ++ for (i = 0; i < fancurve->size; ++i) { ++ const struct fancurve_point *point = &fancurve->points[i]; ++ ++ seq_printf( ++ s, "%d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\n", ++ point->rpm1_raw * 100, point->rpm2_raw * 100, ++ point->accel, point->decel, point->cpu_min_temp_celsius, ++ point->cpu_max_temp_celsius, ++ point->gpu_min_temp_celsius, ++ point->gpu_max_temp_celsius, point->ic_min_temp_celsius, ++ point->ic_max_temp_celsius); ++ } ++ return 0; ++} ++ ++/* ============================= */ ++/* Global and shared data between */ ++/* all calls to this module */ ++/* ============================ */ ++// Implemented like ideapad-laptop.c but currenlty still ++// wihtout dynamic memory allocation (instaed global _priv) ++ ++struct legion_private { ++ struct platform_device *platform_device; ++ // TODO: remove or keep? init? ++ // struct acpi_device *adev; ++ ++ // Method to access ECRAM ++ struct ecram ecram; ++ // Configuration with registers an ECRAM access method ++ const struct model_config *conf; ++ ++ // TODO: maybe refactor an keep only local to each function ++ // last known fan curve ++ struct fancurve fancurve; ++ // configured fan curve from user space ++ struct fancurve fancurve_configured; ++ ++ // update lock, when partial values of fancurve are changed ++ struct mutex fancurve_mutex; ++ ++ //interfaces ++ struct dentry *debugfs_dir; ++ struct device *hwmon_dev; ++ struct platform_profile_handler platform_profile_handler; ++ ++ // TODO: remove? ++ bool loaded; ++}; ++ ++// shared between different drivers: WMI, platform and proteced by mutex ++static struct legion_private *legion_shared; ++static struct legion_private _priv; ++static DEFINE_MUTEX(legion_shared_mutex); ++ ++static int legion_shared_init(struct legion_private *priv) ++{ ++ int ret; ++ ++ mutex_lock(&legion_shared_mutex); ++ ++ if (!legion_shared) { ++ legion_shared = priv; ++ mutex_init(&legion_shared->fancurve_mutex); ++ ret = 0; ++ } else { ++ pr_warn("Found multiple platform devices\n"); ++ ret = -EINVAL; ++ } ++ ++ priv->loaded = true; ++ mutex_unlock(&legion_shared_mutex); ++ ++ return ret; ++} ++ ++static void legion_shared_exit(struct legion_private *priv) ++{ ++ pr_info("Unloading legion shared\n"); ++ mutex_lock(&legion_shared_mutex); ++ ++ if (legion_shared == priv) ++ legion_shared = NULL; ++ ++ mutex_unlock(&legion_shared_mutex); ++ pr_info("Unloading legion shared done\n"); ++} ++ ++/* ============================= */ ++/* debugfs interface */ ++/* ============================ */ ++ ++static int debugfs_ecmemory_show(struct seq_file *s, void *unused) ++{ ++ struct legion_private *priv = s->private; ++ size_t offset; ++ ++ for (offset = 0; offset < priv->conf->memoryio_size; ++offset) { ++ char value = ecram_read(&priv->ecram, ++ priv->conf->memoryio_physical_ec_start + ++ offset); ++ ++ seq_write(s, &value, 1); ++ } ++ return 0; ++} ++ ++DEFINE_SHOW_ATTRIBUTE(debugfs_ecmemory); ++ ++static int debugfs_fancurve_show(struct seq_file *s, void *unused) ++{ ++ struct legion_private *priv = s->private; ++ bool is_minifancurve; ++ bool is_lockfancontroller; ++ bool is_maximumfanspeed; ++ int err; ++ ++ seq_printf(s, "EC Chip ID: %x\n", read_ec_id(&priv->ecram, priv->conf)); ++ seq_printf(s, "EC Chip Version: %x\n", ++ read_ec_version(&priv->ecram, priv->conf)); ++ seq_printf(s, "legion_laptop features: %s\n", LEGIONFEATURES); ++ seq_printf(s, "legion_laptop ec_readonly: %d\n", ec_readonly); ++ read_fancurve(&priv->ecram, priv->conf, &priv->fancurve); ++ ++ seq_printf(s, "minifancurve feature enabled: %d\n", ++ priv->conf->has_minifancurve); ++ err = read_minifancurve(&priv->ecram, priv->conf, &is_minifancurve); ++ seq_printf(s, "minifancurve on cool: %s\n", ++ err ? "error" : (is_minifancurve ? "true" : "false")); ++ err = read_lockfancontroller(&priv->ecram, priv->conf, ++ &is_lockfancontroller); ++ seq_printf(s, "lock fan controller: %s\n", ++ err ? "error" : (is_lockfancontroller ? "true" : "false")); ++ err = read_maximumfanspeed(&priv->ecram, priv->conf, ++ &is_maximumfanspeed); ++ seq_printf(s, "enable maximumfanspeed: %s\n", ++ err ? "error" : (is_maximumfanspeed ? "true" : "false")); ++ seq_printf(s, "enable maximumfanspeed status: %d\n", err); ++ ++ seq_printf(s, "fan curve current point id: %ld\n", ++ priv->fancurve.current_point_i); ++ seq_printf(s, "fan curve points size: %ld\n", priv->fancurve.size); ++ ++ seq_puts(s, "Current fan curve in hardware (embedded controller):\n"); ++ fancurve_print_seqfile(&priv->fancurve, s); ++ seq_puts(s, "=====================\n"); ++ return 0; ++} ++ ++DEFINE_SHOW_ATTRIBUTE(debugfs_fancurve); ++ ++static void legion_debugfs_init(struct legion_private *priv) ++{ ++ struct dentry *dir; ++ ++ // TODO: remove this note ++ // Note: as other kernel modules, do not catch errors here ++ // because if kernel is build without debugfs this ++ // will return an error but module still has to ++ // work, just without debugfs ++ // TODO: what permissions; some modules do 400 ++ // other do 444 ++ dir = debugfs_create_dir(LEGION_DRVR_SHORTNAME, NULL); ++ debugfs_create_file("fancurve", 0444, dir, priv, ++ &debugfs_fancurve_fops); ++ debugfs_create_file("ecmemory", 0444, dir, priv, ++ &debugfs_ecmemory_fops); ++ ++ priv->debugfs_dir = dir; ++} ++ ++static void legion_debugfs_exit(struct legion_private *priv) ++{ ++ pr_info("Unloading legion dubugfs\n"); ++ // The following is does nothing if pointer is NULL ++ debugfs_remove_recursive(priv->debugfs_dir); ++ priv->debugfs_dir = NULL; ++ pr_info("Unloading legion dubugfs done\n"); ++} ++ ++/* ============================= */ ++/* sysfs interface */ ++/* ============================ */ ++ ++static ssize_t powermode_show(struct device *dev, struct device_attribute *attr, ++ char *buf) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int power_mode = read_powermode(&priv->ecram, priv->conf); ++ ++ return sysfs_emit(buf, "%d\n", power_mode); ++} ++ ++static ssize_t powermode_store(struct device *dev, ++ struct device_attribute *attr, const char *buf, ++ size_t count) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int powermode; ++ int err; ++ ++ err = kstrtouint(buf, 0, &powermode); ++ if (err) ++ return err; ++ ++ err = write_powermode(&priv->ecram, priv->conf, powermode); ++ if (err) ++ return -EINVAL; ++ ++ // TODO: better? ++ // we have to wait a bit before change is done in hardware and ++ // readback done after notifying returns correct value, otherwise ++ // the notified reader will read old value ++ msleep(500); ++ platform_profile_notify(); ++ ++ return count; ++} ++ ++static DEVICE_ATTR_RW(powermode); ++ ++static ssize_t lockfancontroller_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ bool is_lockfancontroller; ++ int err; ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = read_lockfancontroller(&priv->ecram, priv->conf, ++ &is_lockfancontroller); ++ mutex_unlock(&priv->fancurve_mutex); ++ if (err) ++ return -EINVAL; ++ ++ return sysfs_emit(buf, "%d\n", is_lockfancontroller); ++} ++ ++static ssize_t lockfancontroller_store(struct device *dev, ++ struct device_attribute *attr, ++ const char *buf, size_t count) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ bool is_lockfancontroller; ++ int err; ++ ++ err = kstrtobool(buf, &is_lockfancontroller); ++ if (err) ++ return err; ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = write_lockfancontroller(&priv->ecram, priv->conf, ++ is_lockfancontroller); ++ mutex_unlock(&priv->fancurve_mutex); ++ if (err) ++ return -EINVAL; ++ ++ return count; ++} ++ ++static DEVICE_ATTR_RW(lockfancontroller); ++ ++static ssize_t keyboard_backlight_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ int state; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ read_keyboard_backlight(&priv->ecram, priv->conf, &state); ++ return sysfs_emit(buf, "%d\n", state); ++} ++ ++static ssize_t keyboard_backlight_store(struct device *dev, ++ struct device_attribute *attr, ++ const char *buf, size_t count) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int state; ++ int err; ++ ++ err = kstrtouint(buf, 0, &state); ++ if (err) ++ return err; ++ ++ err = write_keyboard_backlight(&priv->ecram, priv->conf, state); ++ if (err) ++ return -EINVAL; ++ ++ return count; ++} ++ ++static DEVICE_ATTR_RW(keyboard_backlight); ++ ++static struct attribute *legion_sysfs_attributes[] = { ++ &dev_attr_powermode.attr, &dev_attr_lockfancontroller.attr, ++ &dev_attr_keyboard_backlight.attr, NULL ++}; ++ ++static const struct attribute_group legion_attribute_group = { ++ .attrs = legion_sysfs_attributes ++}; ++ ++static int legion_sysfs_init(struct legion_private *priv) ++{ ++ return device_add_group(&priv->platform_device->dev, ++ &legion_attribute_group); ++} ++ ++static void legion_sysfs_exit(struct legion_private *priv) ++{ ++ pr_info("Unloading legion sysfs\n"); ++ device_remove_group(&priv->platform_device->dev, ++ &legion_attribute_group); ++ pr_info("Unloading legion sysfs done\n"); ++} ++ ++/* ============================= */ ++/* WMI + ACPI */ ++/* ============================ */ ++// heavily based on ideapad_laptop.c ++ ++// TODO: proper names if meaning of all events is clear ++enum LEGION_WMI_EVENT { ++ LEGION_WMI_EVENT_GAMEZONE = 1, ++ LEGION_EVENT_A, ++ LEGION_EVENT_B, ++ LEGION_EVENT_C, ++ LEGION_EVENT_D, ++ LEGION_EVENT_E, ++ LEGION_EVENT_F, ++ LEGION_EVENT_G ++}; ++ ++struct legion_wmi_private { ++ enum LEGION_WMI_EVENT event; ++}; ++ ++//static void legion_wmi_notify2(u32 value, void *context) ++// { ++// pr_info("WMI notify\n" ); ++// } ++ ++static void legion_wmi_notify(struct wmi_device *wdev, union acpi_object *data) ++{ ++ struct legion_wmi_private *wpriv; ++ struct legion_private *priv; ++ ++ mutex_lock(&legion_shared_mutex); ++ priv = legion_shared; ++ if ((!priv) && (priv->loaded)) { ++ pr_info("Received WMI event while not initialized!\n"); ++ goto unlock; ++ } ++ ++ wpriv = dev_get_drvdata(&wdev->dev); ++ switch (wpriv->event) { ++ case LEGION_EVENT_A: ++ pr_info("Fan event: legion type: %d; acpi type: %d (%d=integer)", ++ wpriv->event, data->type, ACPI_TYPE_INTEGER); ++ // TODO: here it is too early (first unlock mutext, then wait a bit) ++ //platform_profile_notify(); ++ break; ++ default: ++ pr_info("Event: legion type: %d; acpi type: %d (%d=integer)", ++ wpriv->event, data->type, ACPI_TYPE_INTEGER); ++ break; ++ } ++ ++unlock: ++ mutex_unlock(&legion_shared_mutex); ++ // todo; fix that! ++ // problem: we get a event just before the powermode change (from the key?), ++ // so if we notify to early, it will read the old power mode/platform profile ++ msleep(500); ++ platform_profile_notify(); ++} ++ ++static int legion_wmi_probe(struct wmi_device *wdev, const void *context) ++{ ++ struct legion_wmi_private *wpriv; ++ ++ wpriv = devm_kzalloc(&wdev->dev, sizeof(*wpriv), GFP_KERNEL); ++ if (!wpriv) ++ return -ENOMEM; ++ ++ *wpriv = *(const struct legion_wmi_private *)context; ++ ++ dev_set_drvdata(&wdev->dev, wpriv); ++ dev_info(&wdev->dev, "Register after probing for WMI.\n"); ++ return 0; ++} ++ ++static const struct legion_wmi_private legion_wmi_context_gamezone = { ++ .event = LEGION_WMI_EVENT_GAMEZONE ++}; ++static const struct legion_wmi_private legion_wmi_context_a = { ++ .event = LEGION_EVENT_A ++}; ++static const struct legion_wmi_private legion_wmi_context_b = { ++ .event = LEGION_EVENT_B ++}; ++static const struct legion_wmi_private legion_wmi_context_c = { ++ .event = LEGION_EVENT_C ++}; ++static const struct legion_wmi_private legion_wmi_context_d = { ++ .event = LEGION_EVENT_D ++}; ++static const struct legion_wmi_private legion_wmi_context_e = { ++ .event = LEGION_EVENT_E ++}; ++static const struct legion_wmi_private legion_wmi_context_f = { ++ .event = LEGION_EVENT_F ++}; ++ ++// check if really a method ++#define LEGION_WMI_GAMEZONE_GUID "887B54E3-DDDC-4B2C-8B88-68A26A8835D0" ++ ++#define LEGION_WMI_GUID_FAN_EVENT "D320289E-8FEA-41E0-86F9-611D83151B5F" ++#define LEGION_WMI_GUID_FAN2_EVENT "bc72a435-e8c1-4275-b3e2-d8b8074aba59" ++#define LEGION_WMI_GUID_GAMEZONE_KEY_EVENT \ ++ "10afc6d9-ea8b-4590-a2e7-1cd3c84bb4b1" ++#define LEGION_WMI_GUID_GAMEZONE_GPU_EVENT \ ++ "bfd42481-aee3-4502-a107-afb68425c5f8" ++#define LEGION_WMI_GUID_GAMEZONE_OC_EVENT "d062906b-12d4-4510-999d-4831ee80e985" ++#define LEGION_WMI_GUID_GAMEZONE_TEMP_EVENT \ ++ "bfd42481-aee3-4501-a107-afb68425c5f8" ++//#define LEGION_WMI_GUID_GAMEZONE_DATA_EVENT "887b54e3-dddc-4b2c-8b88-68a26a8835d0" ++ ++static const struct wmi_device_id legion_wmi_ids[] = { ++ { LEGION_WMI_GAMEZONE_GUID, &legion_wmi_context_gamezone }, ++ { LEGION_WMI_GUID_FAN_EVENT, &legion_wmi_context_a }, ++ { LEGION_WMI_GUID_FAN2_EVENT, &legion_wmi_context_b }, ++ { LEGION_WMI_GUID_GAMEZONE_KEY_EVENT, &legion_wmi_context_c }, ++ { LEGION_WMI_GUID_GAMEZONE_GPU_EVENT, &legion_wmi_context_d }, ++ { LEGION_WMI_GUID_GAMEZONE_OC_EVENT, &legion_wmi_context_e }, ++ { LEGION_WMI_GUID_GAMEZONE_TEMP_EVENT, &legion_wmi_context_f }, ++ { "8FC0DE0C-B4E4-43FD-B0F3-8871711C1294", ++ &legion_wmi_context_gamezone }, /* Legion 5 */ ++ {}, ++}; ++MODULE_DEVICE_TABLE(wmi, legion_wmi_ids); ++ ++static struct wmi_driver legion_wmi_driver = { ++ .driver = { ++ .name = "legion_wmi", ++ }, ++ .id_table = legion_wmi_ids, ++ .probe = legion_wmi_probe, ++ .notify = legion_wmi_notify, ++}; ++ ++//acpi_status status = wmi_install_notify_handler(LEGION_WMI_GAMEZONE_GUID, ++// legion_wmi_notify2, NULL); ++//if (ACPI_FAILURE(status)) { ++// return -ENODEV; ++//} ++//return 0; ++ ++static int legion_wmi_init(void) ++{ ++ return wmi_driver_register(&legion_wmi_driver); ++} ++ ++static void legion_wmi_exit(void) ++{ ++ // TODO: remove this ++ pr_info("Unloading legion WMI\n"); ++ ++ //wmi_remove_notify_handler(LEGION_WMI_GAMEZONE_GUID); ++ wmi_driver_unregister(&legion_wmi_driver); ++ pr_info("Unloading legion WMI done\n"); ++} ++ ++/* ============================= */ ++/* Platform profile */ ++/* ============================ */ ++ ++enum LEGION_POWERMODE { ++ LEGION_POWERMODE_BALANCED = 0, ++ LEGION_POWERMODE_PERFORMANCE = 1, ++ LEGION_POWERMODE_QUIET = 2, ++}; ++ ++static int legion_platform_profile_get(struct platform_profile_handler *pprof, ++ enum platform_profile_option *profile) ++{ ++ int powermode; ++ struct legion_private *priv; ++ ++ priv = container_of(pprof, struct legion_private, ++ platform_profile_handler); ++ powermode = read_powermode(&priv->ecram, priv->conf); ++ ++ switch (powermode) { ++ case LEGION_POWERMODE_BALANCED: ++ *profile = PLATFORM_PROFILE_BALANCED; ++ break; ++ case LEGION_POWERMODE_PERFORMANCE: ++ *profile = PLATFORM_PROFILE_PERFORMANCE; ++ break; ++ case LEGION_POWERMODE_QUIET: ++ *profile = PLATFORM_PROFILE_QUIET; ++ break; ++ default: ++ return -EINVAL; ++ } ++ return 0; ++} ++ ++static int legion_platform_profile_set(struct platform_profile_handler *pprof, ++ enum platform_profile_option profile) ++{ ++ int powermode; ++ struct legion_private *priv; ++ ++ priv = container_of(pprof, struct legion_private, ++ platform_profile_handler); ++ ++ switch (profile) { ++ case PLATFORM_PROFILE_BALANCED: ++ powermode = LEGION_POWERMODE_BALANCED; ++ break; ++ case PLATFORM_PROFILE_PERFORMANCE: ++ powermode = LEGION_POWERMODE_PERFORMANCE; ++ break; ++ case PLATFORM_PROFILE_QUIET: ++ powermode = LEGION_POWERMODE_QUIET; ++ break; ++ default: ++ return -EOPNOTSUPP; ++ } ++ ++ return write_powermode(&priv->ecram, priv->conf, powermode); ++} ++ ++static int legion_platform_profile_init(struct legion_private *priv) ++{ ++ int err; ++ ++ priv->platform_profile_handler.profile_get = ++ legion_platform_profile_get; ++ priv->platform_profile_handler.profile_set = ++ legion_platform_profile_set; ++ ++ set_bit(PLATFORM_PROFILE_QUIET, priv->platform_profile_handler.choices); ++ set_bit(PLATFORM_PROFILE_BALANCED, ++ priv->platform_profile_handler.choices); ++ set_bit(PLATFORM_PROFILE_PERFORMANCE, ++ priv->platform_profile_handler.choices); ++ ++ err = platform_profile_register(&priv->platform_profile_handler); ++ if (err) ++ return err; ++ ++ return 0; ++} ++ ++static void legion_platform_profile_exit(struct legion_private *priv) ++{ ++ pr_info("Unloading legion platform profile\n"); ++ platform_profile_remove(); ++ pr_info("Unloading legion platform profile done\n"); ++} ++ ++/* ============================= */ ++/* hwom interface */ ++/* ============================ */ ++ ++// hw-mon interface ++ ++// todo: register_group or register_info? ++ ++// TODO: use one common function (like here) or one function per attribute? ++static ssize_t sensor_label_show(struct device *dev, ++ struct device_attribute *attr, char *buf) ++{ ++ int sensor_id = (to_sensor_dev_attr(attr))->index; ++ const char *label; ++ ++ switch (sensor_id) { ++ case SENSOR_CPU_TEMP_ID: ++ label = "CPU Temperature\n"; ++ break; ++ case SENSOR_GPU_TEMP_ID: ++ label = "GPU Temperature\n"; ++ break; ++ case SENSOR_IC_TEMP_ID: ++ label = "IC Temperature\n"; ++ break; ++ case SENSOR_FAN1_RPM_ID: ++ label = "Fan 1\n"; ++ break; ++ case SENSOR_FAN2_RPM_ID: ++ label = "Fan 2\n"; ++ break; ++ case SENSOR_FAN1_TARGET_RPM_ID: ++ label = "Fan 1 Target\n"; ++ break; ++ case SENSOR_FAN2_TARGET_RPM_ID: ++ label = "Fan 2 Target\n"; ++ break; ++ default: ++ return -EOPNOTSUPP; ++ } ++ ++ return sprintf(buf, label); ++} ++ ++// TODO: use one common function (like here) or one function per attribute? ++static ssize_t sensor_show(struct device *dev, struct device_attribute *devattr, ++ char *buf) ++{ ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int sensor_id = (to_sensor_dev_attr(devattr))->index; ++ struct sensor_values values; ++ int outval; ++ ++ read_sensor_values(&priv->ecram, priv->conf, &values); ++ ++ switch (sensor_id) { ++ case SENSOR_CPU_TEMP_ID: ++ outval = 1000 * values.cpu_temp_celsius; ++ break; ++ case SENSOR_GPU_TEMP_ID: ++ outval = 1000 * values.gpu_temp_celsius; ++ break; ++ case SENSOR_IC_TEMP_ID: ++ outval = 1000 * values.ic_temp_celsius; ++ break; ++ case SENSOR_FAN1_RPM_ID: ++ outval = values.fan1_rpm; ++ break; ++ case SENSOR_FAN2_RPM_ID: ++ outval = values.fan2_rpm; ++ break; ++ case SENSOR_FAN1_TARGET_RPM_ID: ++ outval = values.fan1_target_rpm; ++ break; ++ case SENSOR_FAN2_TARGET_RPM_ID: ++ outval = values.fan2_target_rpm; ++ break; ++ default: ++ pr_info("Error reading sensor value with id %d\n", sensor_id); ++ return -EOPNOTSUPP; ++ } ++ ++ return sprintf(buf, "%d\n", outval); ++} ++ ++static SENSOR_DEVICE_ATTR_RO(temp1_input, sensor, SENSOR_CPU_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(temp1_label, sensor_label, SENSOR_CPU_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(temp2_input, sensor, SENSOR_GPU_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(temp2_label, sensor_label, SENSOR_GPU_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(temp3_input, sensor, SENSOR_IC_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(temp3_label, sensor_label, SENSOR_IC_TEMP_ID); ++static SENSOR_DEVICE_ATTR_RO(fan1_input, sensor, SENSOR_FAN1_RPM_ID); ++static SENSOR_DEVICE_ATTR_RO(fan1_label, sensor_label, SENSOR_FAN1_RPM_ID); ++static SENSOR_DEVICE_ATTR_RO(fan2_input, sensor, SENSOR_FAN2_RPM_ID); ++static SENSOR_DEVICE_ATTR_RO(fan2_label, sensor_label, SENSOR_FAN2_RPM_ID); ++static SENSOR_DEVICE_ATTR_RO(fan1_target, sensor, SENSOR_FAN1_TARGET_RPM_ID); ++static SENSOR_DEVICE_ATTR_RO(fan2_target, sensor, SENSOR_FAN2_TARGET_RPM_ID); ++ ++static struct attribute *sensor_hwmon_attributes[] = { ++ &sensor_dev_attr_temp1_input.dev_attr.attr, ++ &sensor_dev_attr_temp1_label.dev_attr.attr, ++ &sensor_dev_attr_temp2_input.dev_attr.attr, ++ &sensor_dev_attr_temp2_label.dev_attr.attr, ++ &sensor_dev_attr_temp3_input.dev_attr.attr, ++ &sensor_dev_attr_temp3_label.dev_attr.attr, ++ &sensor_dev_attr_fan1_input.dev_attr.attr, ++ &sensor_dev_attr_fan1_label.dev_attr.attr, ++ &sensor_dev_attr_fan2_input.dev_attr.attr, ++ &sensor_dev_attr_fan2_label.dev_attr.attr, ++ &sensor_dev_attr_fan1_target.dev_attr.attr, ++ &sensor_dev_attr_fan2_target.dev_attr.attr, ++ NULL ++}; ++ ++static ssize_t autopoint_show(struct device *dev, ++ struct device_attribute *devattr, char *buf) ++{ ++ struct fancurve fancurve; ++ int err; ++ int value; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int fancurve_attr_id = to_sensor_dev_attr_2(devattr)->nr; ++ int point_id = to_sensor_dev_attr_2(devattr)->index; ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = read_fancurve(&priv->ecram, priv->conf, &fancurve); ++ mutex_unlock(&priv->fancurve_mutex); ++ ++ if (err) { ++ pr_info("Reading fancurve failed\n"); ++ return -EOPNOTSUPP; ++ } ++ if (!(point_id >= 0 && point_id < MAXFANCURVESIZE)) { ++ pr_info("Reading fancurve failed due to wrong point id: %d\n", ++ point_id); ++ return -EOPNOTSUPP; ++ } ++ ++ switch (fancurve_attr_id) { ++ case FANCURVE_ATTR_PWM1: ++ value = fancurve.points[point_id].rpm1_raw * 100; ++ break; ++ case FANCURVE_ATTR_PWM2: ++ value = fancurve.points[point_id].rpm2_raw * 100; ++ break; ++ case FANCURVE_ATTR_CPU_TEMP: ++ value = fancurve.points[point_id].cpu_max_temp_celsius; ++ break; ++ case FANCURVE_ATTR_CPU_HYST: ++ value = fancurve.points[point_id].cpu_min_temp_celsius; ++ break; ++ case FANCURVE_ATTR_GPU_TEMP: ++ value = fancurve.points[point_id].gpu_max_temp_celsius; ++ break; ++ case FANCURVE_ATTR_GPU_HYST: ++ value = fancurve.points[point_id].gpu_min_temp_celsius; ++ break; ++ case FANCURVE_ATTR_IC_TEMP: ++ value = fancurve.points[point_id].ic_max_temp_celsius; ++ break; ++ case FANCURVE_ATTR_IC_HYST: ++ value = fancurve.points[point_id].ic_min_temp_celsius; ++ break; ++ case FANCURVE_ATTR_ACCEL: ++ value = fancurve.points[point_id].accel; ++ break; ++ case FANCURVE_ATTR_DECEL: ++ value = fancurve.points[point_id].decel; ++ break; ++ case FANCURVE_SIZE: ++ value = fancurve.size; ++ break; ++ default: ++ pr_info("Reading fancurve failed due to wrong attribute id: %d\n", ++ fancurve_attr_id); ++ return -EOPNOTSUPP; ++ } ++ ++ return sprintf(buf, "%d\n", value); ++} ++ ++static ssize_t autopoint_store(struct device *dev, ++ struct device_attribute *devattr, ++ const char *buf, size_t count) ++{ ++ struct fancurve fancurve; ++ int err; ++ int value; ++ bool valid; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ int fancurve_attr_id = to_sensor_dev_attr_2(devattr)->nr; ++ int point_id = to_sensor_dev_attr_2(devattr)->index; ++ ++ if (!(point_id >= 0 && point_id < MAXFANCURVESIZE)) { ++ pr_info("Reading fancurve failed due to wrong point id: %d\n", ++ point_id); ++ err = -EOPNOTSUPP; ++ goto error; ++ } ++ ++ err = kstrtoint(buf, 0, &value); ++ if (err) { ++ pr_info("Parse for hwmon store is not succesful: error:%d; point_id: %d; fancurve_attr_id: %d\\n", ++ err, point_id, fancurve_attr_id); ++ goto error; ++ } ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = read_fancurve(&priv->ecram, priv->conf, &fancurve); ++ ++ if (err) { ++ pr_info("Reading fancurve failed\n"); ++ err = -EOPNOTSUPP; ++ goto error_mutex; ++ } ++ ++ switch (fancurve_attr_id) { ++ case FANCURVE_ATTR_PWM1: ++ valid = fancurve_set_rpm1(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_PWM2: ++ valid = fancurve_set_rpm2(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_CPU_TEMP: ++ valid = fancurve_set_cpu_temp_max(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_CPU_HYST: ++ valid = fancurve_set_cpu_temp_min(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_GPU_TEMP: ++ valid = fancurve_set_gpu_temp_max(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_GPU_HYST: ++ valid = fancurve_set_gpu_temp_min(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_IC_TEMP: ++ valid = fancurve_set_ic_temp_max(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_IC_HYST: ++ valid = fancurve_set_ic_temp_min(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_ACCEL: ++ valid = fancurve_set_accel(&fancurve, point_id, value); ++ break; ++ case FANCURVE_ATTR_DECEL: ++ valid = fancurve_set_decel(&fancurve, point_id, value); ++ break; ++ case FANCURVE_SIZE: ++ valid = fancurve_set_size(&fancurve, value, true); ++ break; ++ default: ++ pr_info("Writing fancurve failed due to wrong attribute id: %d\n", ++ fancurve_attr_id); ++ err = -EOPNOTSUPP; ++ goto error_mutex; ++ } ++ ++ if (!valid) { ++ pr_info("Ignoring invalid fancurve value %d for attribute %d at point %d\n", ++ value, fancurve_attr_id, point_id); ++ err = -EOPNOTSUPP; ++ goto error_mutex; ++ } ++ ++ err = write_fancurve(&priv->ecram, priv->conf, &fancurve, false); ++ if (err) { ++ pr_info("Writing fancurve failed for accessing hwmon at point_id: %d\n", ++ point_id); ++ err = -EOPNOTSUPP; ++ goto error_mutex; ++ } ++ ++ mutex_unlock(&priv->fancurve_mutex); ++ return count; ++ ++error_mutex: ++ mutex_unlock(&priv->fancurve_mutex); ++error: ++ return count; ++} ++ ++// rpm1 ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point1_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point2_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point3_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point4_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point5_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point6_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point7_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point8_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point9_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point10_pwm, autopoint, ++ FANCURVE_ATTR_PWM1, 9); ++// rpm2 ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point1_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point2_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point3_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point4_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point5_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point6_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point7_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point8_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point9_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point10_pwm, autopoint, ++ FANCURVE_ATTR_PWM2, 9); ++// CPU temp ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point1_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point2_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point3_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point4_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point5_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point6_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point7_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point8_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point9_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point10_temp, autopoint, ++ FANCURVE_ATTR_CPU_TEMP, 9); ++// CPU temp hyst ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point1_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point2_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point3_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point4_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point5_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point6_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point7_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point8_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point9_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point10_temp_hyst, autopoint, ++ FANCURVE_ATTR_CPU_HYST, 9); ++// GPU temp ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point1_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point2_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point3_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point4_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point5_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point6_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point7_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point8_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point9_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point10_temp, autopoint, ++ FANCURVE_ATTR_GPU_TEMP, 9); ++// GPU temp hyst ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point1_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point2_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point3_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point4_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point5_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point6_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point7_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point8_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point9_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm2_auto_point10_temp_hyst, autopoint, ++ FANCURVE_ATTR_GPU_HYST, 9); ++// IC temp ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point1_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point2_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point3_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point4_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point5_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point6_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point7_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point8_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point9_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point10_temp, autopoint, ++ FANCURVE_ATTR_IC_TEMP, 9); ++// IC temp hyst ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point1_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point2_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point3_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point4_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point5_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point6_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point7_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point8_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point9_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm3_auto_point10_temp_hyst, autopoint, ++ FANCURVE_ATTR_IC_HYST, 9); ++// accel ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point1_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point2_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point3_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point4_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point5_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point6_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point7_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point8_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point9_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point10_accel, autopoint, ++ FANCURVE_ATTR_ACCEL, 9); ++// decel ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point1_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 0); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point2_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 1); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point3_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 2); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point4_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 3); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point5_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 4); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point6_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 5); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point7_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 6); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point8_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 7); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point9_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 8); ++static SENSOR_DEVICE_ATTR_2_RW(pwm1_auto_point10_decel, autopoint, ++ FANCURVE_ATTR_DECEL, 9); ++//size ++static SENSOR_DEVICE_ATTR_2_RW(auto_points_size, autopoint, FANCURVE_SIZE, 0); ++ ++static ssize_t minifancurve_show(struct device *dev, ++ struct device_attribute *devattr, char *buf) ++{ ++ bool value; ++ int err; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = read_minifancurve(&priv->ecram, priv->conf, &value); ++ if (err) { ++ err = -1; ++ pr_info("Reading minifancurve not succesful\n"); ++ goto error_unlock; ++ } ++ mutex_unlock(&priv->fancurve_mutex); ++ return sprintf(buf, "%d\n", value); ++ ++error_unlock: ++ mutex_unlock(&priv->fancurve_mutex); ++ return -1; ++} ++ ++static ssize_t minifancurve_store(struct device *dev, ++ struct device_attribute *devattr, ++ const char *buf, size_t count) ++{ ++ int value; ++ int err; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ err = kstrtoint(buf, 0, &value); ++ if (err) { ++ err = -1; ++ pr_info("Parse for hwmon store is not succesful: error:%d\n", ++ err); ++ goto error; ++ } ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = write_minifancurve(&priv->ecram, priv->conf, value); ++ if (err) { ++ err = -1; ++ pr_info("Writing minifancurve not succesful\n"); ++ goto error_unlock; ++ } ++ mutex_unlock(&priv->fancurve_mutex); ++ return count; ++ ++error_unlock: ++ mutex_unlock(&priv->fancurve_mutex); ++error: ++ return err; ++} ++ ++static SENSOR_DEVICE_ATTR_RW(minifancurve, minifancurve, 0); ++ ++static ssize_t pwm1_mode_show(struct device *dev, ++ struct device_attribute *devattr, char *buf) ++{ ++ bool value; ++ int err; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = read_maximumfanspeed(&priv->ecram, priv->conf, &value); ++ if (err) { ++ err = -1; ++ pr_info("Reading pwm1_mode/maximumfanspeed not succesful\n"); ++ goto error_unlock; ++ } ++ mutex_unlock(&priv->fancurve_mutex); ++ return sprintf(buf, "%d\n", value ? 0 : 2); ++ ++error_unlock: ++ mutex_unlock(&priv->fancurve_mutex); ++ return -1; ++} ++ ++static ssize_t pwm1_mode_store(struct device *dev, ++ struct device_attribute *devattr, ++ const char *buf, size_t count) ++{ ++ int value; ++ int is_maximumfanspeed; ++ int err; ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ err = kstrtoint(buf, 0, &value); ++ if (err) { ++ err = -1; ++ pr_info("Parse for hwmon store is not succesful: error:%d\n", ++ err); ++ goto error; ++ } ++ is_maximumfanspeed = value == 0; ++ ++ mutex_lock(&priv->fancurve_mutex); ++ err = write_maximumfanspeed(&priv->ecram, priv->conf, ++ is_maximumfanspeed); ++ if (err) { ++ err = -1; ++ pr_info("Writing pwm1_mode/maximumfanspeed not succesful\n"); ++ goto error_unlock; ++ } ++ mutex_unlock(&priv->fancurve_mutex); ++ return count; ++ ++error_unlock: ++ mutex_unlock(&priv->fancurve_mutex); ++error: ++ return err; ++} ++ ++static SENSOR_DEVICE_ATTR_RW(pwm1_mode, pwm1_mode, 0); ++ ++static struct attribute *fancurve_hwmon_attributes[] = { ++ &sensor_dev_attr_pwm1_auto_point1_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point2_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point3_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point4_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point5_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point6_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point7_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point8_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point9_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point10_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point1_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point2_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point3_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point4_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point5_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point6_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point7_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point8_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point9_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point10_pwm.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point1_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point2_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point3_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point4_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point5_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point6_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point7_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point8_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point9_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point10_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point1_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point2_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point3_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point4_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point5_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point6_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point7_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point8_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point9_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point10_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point1_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point2_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point3_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point4_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point5_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point6_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point7_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point8_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point9_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point10_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point1_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point2_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point3_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point4_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point5_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point6_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point7_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point8_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point9_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm2_auto_point10_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point1_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point2_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point3_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point4_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point5_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point6_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point7_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point8_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point9_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point10_temp.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point1_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point2_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point3_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point4_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point5_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point6_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point7_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point8_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point9_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm3_auto_point10_temp_hyst.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point1_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point2_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point3_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point4_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point5_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point6_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point7_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point8_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point9_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point10_accel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point1_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point2_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point3_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point4_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point5_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point6_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point7_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point8_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point9_decel.dev_attr.attr, ++ &sensor_dev_attr_pwm1_auto_point10_decel.dev_attr.attr, ++ // ++ &sensor_dev_attr_auto_points_size.dev_attr.attr, ++ &sensor_dev_attr_minifancurve.dev_attr.attr, ++ &sensor_dev_attr_pwm1_mode.dev_attr.attr, NULL ++}; ++ ++static umode_t legion_is_visible(struct kobject *kobj, struct attribute *attr, ++ int idx) ++{ ++ bool supported = true; ++ struct device *dev = kobj_to_dev(kobj); ++ struct legion_private *priv = dev_get_drvdata(dev); ++ ++ if (attr == &sensor_dev_attr_minifancurve.dev_attr.attr) ++ supported = priv->conf->has_minifancurve; ++ ++ return supported ? attr->mode : 0; ++} ++ ++static const struct attribute_group legion_hwmon_sensor_group = { ++ .attrs = sensor_hwmon_attributes, ++ .is_visible = NULL ++}; ++ ++static const struct attribute_group legion_hwmon_fancurve_group = { ++ .attrs = fancurve_hwmon_attributes, ++ .is_visible = legion_is_visible, ++}; ++ ++static const struct attribute_group *legion_hwmon_groups[] = { ++ &legion_hwmon_sensor_group, &legion_hwmon_fancurve_group, NULL ++}; ++ ++ssize_t legion_hwmon_init(struct legion_private *priv) ++{ ++ //TODO: use hwmon_device_register_with_groups or ++ // hwmon_device_register_with_info (latter means all hwmon functions have to be ++ // changed) ++ // some laptop driver do it in one way, some in the other ++ // TODO: Use devm_hwmon_device_register_with_groups ? ++ // some laptop drivers use this, some ++ struct device *hwmon_dev = hwmon_device_register_with_groups( ++ &priv->platform_device->dev, "legion_hwmon", priv, ++ legion_hwmon_groups); ++ if (IS_ERR_OR_NULL(hwmon_dev)) { ++ pr_err("hwmon_device_register failed!\n"); ++ return PTR_ERR(hwmon_dev); ++ } ++ dev_set_drvdata(hwmon_dev, priv); ++ priv->hwmon_dev = hwmon_dev; ++ return 0; ++} ++ ++void legion_hwmon_exit(struct legion_private *priv) ++{ ++ pr_info("Unloading legion hwon\n"); ++ if (priv->hwmon_dev) { ++ hwmon_device_unregister(priv->hwmon_dev); ++ priv->hwmon_dev = NULL; ++ } ++ pr_info("Unloading legion hwon done\n"); ++} ++ ++/* ============================= */ ++/* Platform driver */ ++/* ============================ */ ++ ++int legion_add(struct platform_device *pdev) ++{ ++ struct legion_private *priv; ++ const struct dmi_system_id *dmi_sys; ++ int err; ++ u16 ec_read_id; ++ bool is_denied = true; ++ bool is_allowed = false; ++ bool do_load_by_list = false; ++ bool do_load = false; ++ //struct legion_private *priv = dev_get_drvdata(&pdev->dev); ++ dev_info(&pdev->dev, "legion_laptop platform driver probing\n"); ++ ++ dev_info(&pdev->dev, "Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", ++ dmi_get_system_info(DMI_SYS_VENDOR), ++ dmi_get_system_info(DMI_PRODUCT_NAME), ++ dmi_get_system_info(DMI_BIOS_VERSION)); ++ ++ // TODO: allocate? ++ priv = &_priv; ++ priv->platform_device = pdev; ++ err = legion_shared_init(priv); ++ if (err) { ++ dev_info(&pdev->dev, "legion_laptop is forced to load.\n"); ++ goto err_legion_shared_init; ++ } ++ dev_set_drvdata(&pdev->dev, priv); ++ ++ // TODO: remove ++ pr_info("Read identifying information: DMI_SYS_VENDOR: %s; DMI_PRODUCT_NAME: %s; DMI_BIOS_VERSION:%s\n", ++ dmi_get_system_info(DMI_SYS_VENDOR), ++ dmi_get_system_info(DMI_PRODUCT_NAME), ++ dmi_get_system_info(DMI_BIOS_VERSION)); ++ ++ dmi_sys = dmi_first_match(optimistic_allowlist); ++ is_allowed = dmi_sys != NULL; ++ is_denied = dmi_check_system(denylist); ++ do_load_by_list = is_allowed && !is_denied; ++ do_load = do_load_by_list || force; ++ ++ dev_info( ++ &pdev->dev, ++ "is_denied: %d; is_allowed: %d; do_load_by_list: %d; do_load: %d\n", ++ is_denied, is_allowed, do_load_by_list, do_load); ++ ++ if (!(do_load)) { ++ dev_info( ++ &pdev->dev, ++ "Module not useable for this laptop because it is not in allowlist. Notify maintainer if you want to add your device or force load with param force.\n"); ++ err = -ENOMEM; ++ goto err_model_mismtach; ++ } ++ ++ if (force) ++ dev_info(&pdev->dev, "legion_laptop is forced to load.\n"); ++ ++ if (!do_load_by_list && do_load) { ++ dev_info( ++ &pdev->dev, ++ "legion_laptop is forced to load and would otherwise be not loaded\n"); ++ } ++ ++ // if forced and no module found, use config for first model ++ if (dmi_sys == NULL) ++ dmi_sys = &optimistic_allowlist[0]; ++ dev_info(&pdev->dev, "Using configuration for system: %s\n", ++ dmi_sys->ident); ++ ++ priv->conf = dmi_sys->driver_data; ++ ++ err = ecram_init(&priv->ecram, priv->conf->memoryio_physical_ec_start, ++ priv->conf->memoryio_size); ++ if (err) { ++ dev_info(&pdev->dev, ++ "Could not init access to embedded controller\n"); ++ goto err_ecram_init; ++ } ++ ++ ec_read_id = read_ec_id(&priv->ecram, priv->conf); ++ dev_info(&pdev->dev, "Read embedded controller ID 0x%x\n", ec_read_id); ++ if (priv->conf->check_embedded_controller_id && ++ !(ec_read_id == priv->conf->embedded_controller_id)) { ++ err = -ENOMEM; ++ dev_info(&pdev->dev, "Expected EC chip id 0x%x but read 0x%x\n", ++ priv->conf->embedded_controller_id, ec_read_id); ++ goto err_ecram_id; ++ } ++ if (!priv->conf->check_embedded_controller_id) { ++ dev_info(&pdev->dev, ++ "Skipped checking embedded controller id\n"); ++ } ++ ++ dev_info(&pdev->dev, "Creating debugfs inteface\n"); ++ legion_debugfs_init(priv); ++ ++ pr_info("Creating sysfs inteface\n"); ++ err = legion_sysfs_init(priv); ++ if (err) { ++ dev_info(&pdev->dev, "Creating sysfs interface failed\n"); ++ goto err_sysfs_init; ++ } ++ ++ pr_info("Creating hwmon interface"); ++ err = legion_hwmon_init(priv); ++ if (err) ++ goto err_hwmon_init; ++ ++ pr_info("Creating platform profile support\n"); ++ err = legion_platform_profile_init(priv); ++ if (err) { ++ dev_info(&pdev->dev, "Creating platform profile failed\n"); ++ goto err_platform_profile; ++ } ++ ++ pr_info("Init WMI driver support\n"); ++ err = legion_wmi_init(); ++ if (err) { ++ dev_info(&pdev->dev, "Init WMI driver failed\n"); ++ goto err_wmi; ++ } ++ ++ dev_info(&pdev->dev, "legion_laptop loaded for this device\n"); ++ return 0; ++ ++ // TODO: remove eventually ++ legion_wmi_exit(); ++err_wmi: ++ legion_platform_profile_exit(priv); ++err_platform_profile: ++ legion_hwmon_exit(priv); ++err_hwmon_init: ++ legion_sysfs_exit(priv); ++err_sysfs_init: ++ legion_debugfs_exit(priv); ++err_ecram_id: ++ ecram_exit(&priv->ecram); ++err_ecram_init: ++ legion_shared_exit(priv); ++err_legion_shared_init: ++err_model_mismtach: ++ dev_info(&pdev->dev, "legion_laptop not loaded for this device\n"); ++ return err; ++} ++ ++int legion_remove(struct platform_device *pdev) ++{ ++ struct legion_private *priv = dev_get_drvdata(&pdev->dev); ++ ++ mutex_lock(&legion_shared_mutex); ++ priv->loaded = false; ++ mutex_unlock(&legion_shared_mutex); ++ ++ // first unregister wmi, so toggling powermode does not ++ // generate events anymore that even might be delayed ++ legion_wmi_exit(); ++ legion_platform_profile_exit(priv); ++ ++ // toggle power mode to load default setting from embedded controller ++ // again ++ toggle_powermode(&priv->ecram, priv->conf); ++ ++ legion_hwmon_exit(priv); ++ legion_sysfs_exit(priv); ++ legion_debugfs_exit(priv); ++ ecram_exit(&priv->ecram); ++ legion_shared_exit(priv); ++ ++ pr_info("Legion platform unloaded\n"); ++ return 0; ++} ++ ++int legion_resume(struct platform_device *pdev) ++{ ++ //struct legion_private *priv = dev_get_drvdata(&pdev->dev); ++ dev_info(&pdev->dev, "Resumed in legion-laptop\n"); ++ ++ return 0; ++} ++ ++#ifdef CONFIG_PM_SLEEP ++static int legion_pm_resume(struct device *dev) ++{ ++ //struct legion_private *priv = dev_get_drvdata(dev); ++ dev_info(dev, "Resumed PM in legion-laptop\n"); ++ ++ return 0; ++} ++#endif ++static SIMPLE_DEV_PM_OPS(legion_pm, NULL, legion_pm_resume); ++ ++// same as ideapad ++static const struct acpi_device_id legion_device_ids[] = { ++ { "PNP0C09", 0 }, // todo: change to "VPC2004" ++ { "", 0 }, ++}; ++MODULE_DEVICE_TABLE(acpi, legion_device_ids); ++ ++static struct platform_driver legion_driver = { ++ .probe = legion_add, ++ .remove = legion_remove, ++ .resume = legion_resume, ++ .driver = { ++ .name = "legion", ++ .pm = &legion_pm, ++ .acpi_match_table = ACPI_PTR(legion_device_ids), ++ }, ++}; ++ ++int __init legion_init(void) ++{ ++ int err; ++ ++ pr_info("legion_laptop starts loading\n"); ++ err = platform_driver_register(&legion_driver); ++ if (err) { ++ pr_info("legion_laptop: platform_driver_register failed\n"); ++ return err; ++ } ++ ++ return 0; ++} ++ ++module_init(legion_init); ++ ++void __exit legion_exit(void) ++{ ++ platform_driver_unregister(&legion_driver); ++ pr_info("legion_laptop exit\n"); ++} ++ ++module_exit(legion_exit); diff --git a/drivers/platform/x86/steamdeck.c b/drivers/platform/x86/steamdeck.c new file mode 100644 index 000000000000..77a6677ec19e @@ -5874,7 +8699,7 @@ index 901b440238d5..7026df84a0f6 100644 TP_PROTO(const struct sock *sk, const struct request_sock *req), diff --git a/init/Kconfig b/init/Kconfig -index 1fb5f313d18f..9b298860cfed 100644 +index c88bb30a8b0b..908d045dbe10 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -123,6 +123,10 @@ config THREAD_INFO_IN_TASK @@ -5908,7 +8733,7 @@ index 1fb5f313d18f..9b298860cfed 100644 config DEFAULT_INIT string "Default init path" default "" -@@ -1253,6 +1270,22 @@ config USER_NS +@@ -1249,6 +1266,22 @@ config USER_NS If unsure, say N. @@ -5931,7 +8756,7 @@ index 1fb5f313d18f..9b298860cfed 100644 config PID_NS bool "PID Namespaces" default y -@@ -1433,6 +1466,12 @@ config CC_OPTIMIZE_FOR_PERFORMANCE +@@ -1429,6 +1462,12 @@ config CC_OPTIMIZE_FOR_PERFORMANCE with the "-O2" compiler flag for best performance and most helpful compile-time warnings. @@ -5987,7 +8812,7 @@ index 38ef6d06888e..0f78364efd4f 100644 config SCHED_HRTICK diff --git a/kernel/fork.c b/kernel/fork.c -index 0c92f224c68c..49c173e367d2 100644 +index ea332319dffe..349945168239 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -98,6 +98,10 @@ @@ -6001,7 +8826,7 @@ index 0c92f224c68c..49c173e367d2 100644 #include #include #include -@@ -2031,6 +2035,10 @@ static __latent_entropy struct task_struct *copy_process( +@@ -2032,6 +2036,10 @@ static __latent_entropy struct task_struct *copy_process( if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS)) return ERR_PTR(-EINVAL); @@ -6012,7 +8837,7 @@ index 0c92f224c68c..49c173e367d2 100644 /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. -@@ -3181,6 +3189,12 @@ int ksys_unshare(unsigned long unshare_flags) +@@ -3182,6 +3190,12 @@ int ksys_unshare(unsigned long unshare_flags) if (unshare_flags & CLONE_NEWNS) unshare_flags |= CLONE_FS; @@ -6062,7 +8887,7 @@ index 424b3bc58f3f..ecf2798c5ccf 100644 bool "Support in-kernel module decompression" depends on MODULE_COMPRESS_GZIP || MODULE_COMPRESS_XZ || MODULE_COMPRESS_ZSTD diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index 6986ea31c984..dcdd8422de72 100644 +index 5f6587d94c1d..96c66b50ee48 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -69,9 +69,13 @@ @@ -6227,7 +9052,7 @@ index 516b1aa247e8..78fb31d27ed7 100644 EXPORT_SYMBOL_GPL(dirty_writeback_interval); diff --git a/mm/swap.c b/mm/swap.c -index 57cb01b042f6..3a7bec75480f 100644 +index 423199ee8478..adef27bd3f8b 100644 --- a/mm/swap.c +++ b/mm/swap.c @@ -1090,6 +1090,10 @@ void folio_batch_remove_exceptionals(struct folio_batch *fbatch) @@ -6292,10 +9117,10 @@ index 9c1c5e8b24b8..71a7f4517e5a 100644 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) { diff --git a/net/ipv4/sysctl_net_ipv4.c b/net/ipv4/sysctl_net_ipv4.c -index 0d0cc4ef2b85..544104f9f4b3 100644 +index 40fe70fc2015..3028e27897d9 100644 --- a/net/ipv4/sysctl_net_ipv4.c +++ b/net/ipv4/sysctl_net_ipv4.c -@@ -1467,6 +1467,13 @@ static struct ctl_table ipv4_net_table[] = { +@@ -1470,6 +1470,13 @@ static struct ctl_table ipv4_net_table[] = { .extra1 = SYSCTL_ZERO, .extra2 = &tcp_plb_max_cong_thresh, }, @@ -6371,7 +9196,7 @@ index 754e0212c951..b6d7faeb737a 100644 * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. diff --git a/net/ipv4/tcp_ipv4.c b/net/ipv4/tcp_ipv4.c -index ea370afa70ed..b869b6c1b226 100644 +index b9d55277cb85..5e577877158b 100644 --- a/net/ipv4/tcp_ipv4.c +++ b/net/ipv4/tcp_ipv4.c @@ -3275,6 +3275,8 @@ static int __net_init tcp_sk_init(struct net *net) @@ -6434,10 +9259,10 @@ index ab0c5bd1a60f..f4989f706d7f 100644 -- 2.40.0 -From 9b77615274a43646ad38d250d0c63be888c15bda Mon Sep 17 00:00:00 2001 +From fea8ca6edfbcecc63ceb49bc5f163632addaf0b5 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:22:15 +0200 -Subject: [PATCH 04/10] fixes +Date: Sat, 22 Apr 2023 11:43:21 +0200 +Subject: [PATCH 04/12] fixes Signed-off-by: Peter Jung --- @@ -6446,24 +9271,58 @@ Signed-off-by: Peter Jung Documentation/admin-guide/mm/ksm.rst | 7 + Documentation/leds/index.rst | 1 + Documentation/leds/ledtrig-blkdev.rst | 158 +++ + Documentation/x86/topology.rst | 26 + + arch/x86/include/asm/cacheinfo.h | 1 + + arch/x86/kernel/cpu/amd.c | 1 + + arch/x86/kernel/cpu/cacheinfo.c | 36 + + arch/x86/kernel/cpu/hygon.c | 1 + + arch/x86/net/bpf_jit_comp.c | 5 +- drivers/bluetooth/btusb.c | 2 +- + .../drm/amd/display/dc/bios/bios_parser2.c | 7 +- + .../drm/amd/display/dc/dcn20/dcn20_resource.c | 2 +- + .../drm/amd/display/dc/dcn21/dcn21_resource.c | 2 +- + .../gpu/drm/amd/pm/swsmu/smu11/navi10_ppt.c | 3 +- drivers/leds/trigger/Kconfig | 9 + drivers/leds/trigger/Makefile | 1 + drivers/leds/trigger/ledtrig-blkdev.c | 1221 +++++++++++++++++ fs/eventpoll.c | 188 ++- fs/proc/base.c | 1 + + include/linux/atomic/atomic-arch-fallback.h | 208 ++- + include/linux/atomic/atomic-instrumented.h | 68 +- + include/linux/atomic/atomic-long.h | 38 +- include/linux/mm_types.h | 7 +- include/linux/pageblock-flags.h | 2 +- + include/linux/rcuref.h | 155 +++ + include/linux/types.h | 6 + + include/net/dst.h | 30 +- + include/net/ip6_fib.h | 3 - + include/net/ip6_route.h | 2 +- + include/net/route.h | 3 - + include/net/sock.h | 2 +- kernel/kheaders.c | 10 +- kernel/padata.c | 4 +- + lib/Makefile | 2 +- + lib/rcuref.c | 281 ++++ mm/ksm.c | 185 ++- + net/bridge/br_nf_core.c | 2 +- + net/core/dst.c | 26 +- + net/core/rtnetlink.c | 2 +- + net/ipv4/route.c | 20 +- + net/ipv4/xfrm4_policy.c | 4 +- + net/ipv6/route.c | 32 +- + net/ipv6/xfrm6_policy.c | 4 +- + net/netfilter/ipvs/ip_vs_xmit.c | 4 +- scripts/Makefile.vmlinux_o | 2 +- + scripts/atomic/atomics.tbl | 2 +- + scripts/atomic/fallbacks/add_negative | 11 +- sound/pci/hda/cs35l41_hda.c | 2 +- .../selftests/mm/ksm_functional_tests.c | 96 +- - 19 files changed, 1862 insertions(+), 122 deletions(-) + 51 files changed, 2751 insertions(+), 222 deletions(-) create mode 100644 Documentation/ABI/testing/sysfs-class-led-trigger-blkdev create mode 100644 Documentation/leds/ledtrig-blkdev.rst create mode 100644 drivers/leds/trigger/ledtrig-blkdev.c + create mode 100644 include/linux/rcuref.h + create mode 100644 lib/rcuref.c diff --git a/Documentation/ABI/stable/sysfs-block b/Documentation/ABI/stable/sysfs-block index 282de3680367..ac1dd2fbd855 100644 @@ -6764,6 +9623,164 @@ index 000000000000..9ff5b99de451 +* The ``blkdev`` LED trigger supports many-to-many device/LED associations. + A device can be associated with multiple LEDs, and an LED can be associated + with multiple devices. +diff --git a/Documentation/x86/topology.rst b/Documentation/x86/topology.rst +index 7f58010ea86a..9de14f3f7783 100644 +--- a/Documentation/x86/topology.rst ++++ b/Documentation/x86/topology.rst +@@ -33,6 +33,7 @@ historical nature and should be cleaned up. + The topology of a system is described in the units of: + + - packages ++ - cluster + - cores + - threads + +@@ -90,6 +91,22 @@ Package-related topology information in the kernel: + Cache. In general, it is a number identifying an LLC uniquely on the + system. + ++Clusters ++======== ++A cluster consists of threads of one or more cores sharing the same L2 cache. ++ ++Cluster-related topology information in the kernel: ++ ++ - cluster_id: ++ ++ A per-CPU variable containing: ++ ++ - Upper bits extracted from the APIC ID. CPUs which have the same value ++ in these bits share an L2 and have the same cluster_id. ++ ++ CPUs for which cluster information is unavailable will show 65535 ++ (BAD_APICID) as the cluster_id. ++ + Cores + ===== + A core consists of 1 or more threads. It does not matter whether the threads +@@ -125,6 +142,11 @@ Thread-related topology information in the kernel: + + The number of online threads is also printed in /proc/cpuinfo "siblings." + ++ - topology_cluster_cpumask(): ++ ++ The cpumask contains all online threads in the cluster to which a thread ++ belongs. ++ + - topology_sibling_cpumask(): + + The cpumask contains all online threads in the core to which a thread +@@ -138,6 +160,10 @@ Thread-related topology information in the kernel: + + The physical package ID to which a thread belongs. + ++ - topology_cluster_id(); ++ ++ The ID of the cluster to which a thread belongs. ++ + - topology_core_id(); + + The ID of the core to which a thread belongs. It is also printed in /proc/cpuinfo +diff --git a/arch/x86/include/asm/cacheinfo.h b/arch/x86/include/asm/cacheinfo.h +index ce9685fc78d8..2034cd556c07 100644 +--- a/arch/x86/include/asm/cacheinfo.h ++++ b/arch/x86/include/asm/cacheinfo.h +@@ -7,6 +7,7 @@ extern unsigned int memory_caching_control; + #define CACHE_MTRR 0x01 + #define CACHE_PAT 0x02 + ++void cacheinfo_topoext_init_l2c_id(struct cpuinfo_x86 *c, int cpu); + void cacheinfo_amd_init_llc_id(struct cpuinfo_x86 *c, int cpu); + void cacheinfo_hygon_init_llc_id(struct cpuinfo_x86 *c, int cpu); + +diff --git a/arch/x86/kernel/cpu/amd.c b/arch/x86/kernel/cpu/amd.c +index 95cdd08c4cbb..d6594727f924 100644 +--- a/arch/x86/kernel/cpu/amd.c ++++ b/arch/x86/kernel/cpu/amd.c +@@ -358,6 +358,7 @@ static void amd_get_topology(struct cpuinfo_x86 *c) + if (!err) + c->x86_coreid_bits = get_count_order(c->x86_max_cores); + ++ cacheinfo_topoext_init_l2c_id(c, cpu); + cacheinfo_amd_init_llc_id(c, cpu); + + } else if (cpu_has(c, X86_FEATURE_NODEID_MSR)) { +diff --git a/arch/x86/kernel/cpu/cacheinfo.c b/arch/x86/kernel/cpu/cacheinfo.c +index 4063e8991211..947a1f27278c 100644 +--- a/arch/x86/kernel/cpu/cacheinfo.c ++++ b/arch/x86/kernel/cpu/cacheinfo.c +@@ -659,6 +659,42 @@ static int find_num_cache_leaves(struct cpuinfo_x86 *c) + return i; + } + ++void cacheinfo_topoext_init_l2c_id(struct cpuinfo_x86 *c, int cpu) ++{ ++ u32 eax, ebx, ecx, edx, num_sharing_cache; ++ int i = 0, bits; ++ ++ /* Check if L2 cache identifiers exists. */ ++ if (!cpuid_ecx(0x80000006)) ++ return; ++ ++ while (true) { ++ u32 level; ++ ++ cpuid_count(0x8000001d, i, &eax, &ebx, &ecx, &edx); ++ if (!eax) ++ return; ++ ++ /* ++ * Check if the current leaf is for L2 cache using ++ * eax[7:5] used to describe the cache level. ++ */ ++ level = (eax >> 5) & 0x7; ++ if (level == 2) ++ break; ++ ++ ++i; ++ } ++ ++ /* ++ * L2 ID is calculated from the number of threads ++ * sharing the L2 cache. ++ */ ++ num_sharing_cache = ((eax >> 14) & 0xfff) + 1; ++ bits = get_count_order(num_sharing_cache); ++ per_cpu(cpu_l2c_id, cpu) = c->apicid >> bits; ++} ++ + void cacheinfo_amd_init_llc_id(struct cpuinfo_x86 *c, int cpu) + { + /* +diff --git a/arch/x86/kernel/cpu/hygon.c b/arch/x86/kernel/cpu/hygon.c +index 5a2962c492d3..cb0025b4a2fd 100644 +--- a/arch/x86/kernel/cpu/hygon.c ++++ b/arch/x86/kernel/cpu/hygon.c +@@ -89,6 +89,7 @@ static void hygon_get_topology(struct cpuinfo_x86 *c) + /* Socket ID is ApicId[6] for these processors. */ + c->phys_proc_id = c->apicid >> APICID_SOCKET_ID_BIT; + ++ cacheinfo_topoext_init_l2c_id(c, cpu); + cacheinfo_hygon_init_llc_id(c, cpu); + } else if (cpu_has(c, X86_FEATURE_NODEID_MSR)) { + u64 value; +diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c +index 1056bbf55b17..212bfd1517ec 100644 +--- a/arch/x86/net/bpf_jit_comp.c ++++ b/arch/x86/net/bpf_jit_comp.c +@@ -343,9 +343,10 @@ static int emit_call(u8 **pprog, void *func, void *ip) + + static int emit_rsb_call(u8 **pprog, void *func, void *ip) + { ++ void *adjusted_ip; + OPTIMIZER_HIDE_VAR(func); +- x86_call_depth_emit_accounting(pprog, func); +- return emit_patch(pprog, func, ip, 0xE8); ++ adjusted_ip = (u8 *)ip + x86_call_depth_emit_accounting(pprog, func); ++ return emit_patch(pprog, func, adjusted_ip, 0xE8); + } + + static int emit_jump(u8 **pprog, void *func, void *ip) diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c index 5c536151ef83..5a80379253a7 100644 --- a/drivers/bluetooth/btusb.c @@ -6777,6 +9794,64 @@ index 5c536151ef83..5a80379253a7 100644 gpiod_set_value_cansleep(reset_gpio, 1); return; +diff --git a/drivers/gpu/drm/amd/display/dc/bios/bios_parser2.c b/drivers/gpu/drm/amd/display/dc/bios/bios_parser2.c +index e381de2429fa..ae3783a7d7f4 100644 +--- a/drivers/gpu/drm/amd/display/dc/bios/bios_parser2.c ++++ b/drivers/gpu/drm/amd/display/dc/bios/bios_parser2.c +@@ -515,11 +515,8 @@ static enum bp_result get_gpio_i2c_info( + info->i2c_slave_address = record->i2c_slave_addr; + + /* TODO: check how to get register offset for en, Y, etc. */ +- info->gpio_info.clk_a_register_index = +- le16_to_cpu( +- header->gpio_pin[table_index].data_a_reg_index); +- info->gpio_info.clk_a_shift = +- header->gpio_pin[table_index].gpio_bitshift; ++ info->gpio_info.clk_a_register_index = le16_to_cpu(pin->data_a_reg_index); ++ info->gpio_info.clk_a_shift = pin->gpio_bitshift; + + return BP_RESULT_OK; + } +diff --git a/drivers/gpu/drm/amd/display/dc/dcn20/dcn20_resource.c b/drivers/gpu/drm/amd/display/dc/dcn20/dcn20_resource.c +index 3af24ef9cb2d..51838bef7fb0 100644 +--- a/drivers/gpu/drm/amd/display/dc/dcn20/dcn20_resource.c ++++ b/drivers/gpu/drm/amd/display/dc/dcn20/dcn20_resource.c +@@ -714,7 +714,7 @@ static const struct dc_debug_options debug_defaults_drv = { + .timing_trace = false, + .clock_trace = true, + .disable_pplib_clock_request = true, +- .pipe_split_policy = MPC_SPLIT_AVOID_MULT_DISP, ++ .pipe_split_policy = MPC_SPLIT_DYNAMIC, + .force_single_disp_pipe_split = false, + .disable_dcc = DCC_ENABLE, + .vsr_support = true, +diff --git a/drivers/gpu/drm/amd/display/dc/dcn21/dcn21_resource.c b/drivers/gpu/drm/amd/display/dc/dcn21/dcn21_resource.c +index 8f9244fe5c86..c10ff621cb1d 100644 +--- a/drivers/gpu/drm/amd/display/dc/dcn21/dcn21_resource.c ++++ b/drivers/gpu/drm/amd/display/dc/dcn21/dcn21_resource.c +@@ -642,7 +642,7 @@ static const struct dc_debug_options debug_defaults_drv = { + .clock_trace = true, + .disable_pplib_clock_request = true, + .min_disp_clk_khz = 100000, +- .pipe_split_policy = MPC_SPLIT_AVOID_MULT_DISP, ++ .pipe_split_policy = MPC_SPLIT_DYNAMIC, + .force_single_disp_pipe_split = false, + .disable_dcc = DCC_ENABLE, + .vsr_support = true, +diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu11/navi10_ppt.c b/drivers/gpu/drm/amd/pm/swsmu/smu11/navi10_ppt.c +index 95da6dd1cc65..c4000518dc56 100644 +--- a/drivers/gpu/drm/amd/pm/swsmu/smu11/navi10_ppt.c ++++ b/drivers/gpu/drm/amd/pm/swsmu/smu11/navi10_ppt.c +@@ -304,7 +304,8 @@ navi10_get_allowed_feature_mask(struct smu_context *smu, + | FEATURE_MASK(FEATURE_GFX_SS_BIT) + | FEATURE_MASK(FEATURE_APCC_DFLL_BIT) + | FEATURE_MASK(FEATURE_FW_CTF_BIT) +- | FEATURE_MASK(FEATURE_OUT_OF_BAND_MONITOR_BIT); ++ | FEATURE_MASK(FEATURE_OUT_OF_BAND_MONITOR_BIT) ++ | FEATURE_MASK(FEATURE_TEMP_DEPENDENT_VMIN_BIT); + + if (adev->pm.pp_feature & PP_SCLK_DPM_MASK) + *(uint64_t *)feature_mask |= FEATURE_MASK(FEATURE_DPM_GFXCLK_BIT); diff --git a/drivers/leds/trigger/Kconfig b/drivers/leds/trigger/Kconfig index dc6816d36d06..bda249068182 100644 --- a/drivers/leds/trigger/Kconfig @@ -8398,6 +11473,417 @@ index 5e0e0ccd47aa..07463ad4a70a 100644 mmput(mm); } +diff --git a/include/linux/atomic/atomic-arch-fallback.h b/include/linux/atomic/atomic-arch-fallback.h +index 77bc5522e61c..4226379a232d 100644 +--- a/include/linux/atomic/atomic-arch-fallback.h ++++ b/include/linux/atomic/atomic-arch-fallback.h +@@ -1208,15 +1208,21 @@ arch_atomic_inc_and_test(atomic_t *v) + #define arch_atomic_inc_and_test arch_atomic_inc_and_test + #endif + ++#ifndef arch_atomic_add_negative_relaxed ++#ifdef arch_atomic_add_negative ++#define arch_atomic_add_negative_acquire arch_atomic_add_negative ++#define arch_atomic_add_negative_release arch_atomic_add_negative ++#define arch_atomic_add_negative_relaxed arch_atomic_add_negative ++#endif /* arch_atomic_add_negative */ ++ + #ifndef arch_atomic_add_negative + /** +- * arch_atomic_add_negative - add and test if negative ++ * arch_atomic_add_negative - Add and test if negative + * @i: integer value to add + * @v: pointer of type atomic_t + * +- * Atomically adds @i to @v and returns true +- * if the result is negative, or false when +- * result is greater than or equal to zero. ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. + */ + static __always_inline bool + arch_atomic_add_negative(int i, atomic_t *v) +@@ -1226,6 +1232,95 @@ arch_atomic_add_negative(int i, atomic_t *v) + #define arch_atomic_add_negative arch_atomic_add_negative + #endif + ++#ifndef arch_atomic_add_negative_acquire ++/** ++ * arch_atomic_add_negative_acquire - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic_add_negative_acquire(int i, atomic_t *v) ++{ ++ return arch_atomic_add_return_acquire(i, v) < 0; ++} ++#define arch_atomic_add_negative_acquire arch_atomic_add_negative_acquire ++#endif ++ ++#ifndef arch_atomic_add_negative_release ++/** ++ * arch_atomic_add_negative_release - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic_add_negative_release(int i, atomic_t *v) ++{ ++ return arch_atomic_add_return_release(i, v) < 0; ++} ++#define arch_atomic_add_negative_release arch_atomic_add_negative_release ++#endif ++ ++#ifndef arch_atomic_add_negative_relaxed ++/** ++ * arch_atomic_add_negative_relaxed - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic_add_negative_relaxed(int i, atomic_t *v) ++{ ++ return arch_atomic_add_return_relaxed(i, v) < 0; ++} ++#define arch_atomic_add_negative_relaxed arch_atomic_add_negative_relaxed ++#endif ++ ++#else /* arch_atomic_add_negative_relaxed */ ++ ++#ifndef arch_atomic_add_negative_acquire ++static __always_inline bool ++arch_atomic_add_negative_acquire(int i, atomic_t *v) ++{ ++ bool ret = arch_atomic_add_negative_relaxed(i, v); ++ __atomic_acquire_fence(); ++ return ret; ++} ++#define arch_atomic_add_negative_acquire arch_atomic_add_negative_acquire ++#endif ++ ++#ifndef arch_atomic_add_negative_release ++static __always_inline bool ++arch_atomic_add_negative_release(int i, atomic_t *v) ++{ ++ __atomic_release_fence(); ++ return arch_atomic_add_negative_relaxed(i, v); ++} ++#define arch_atomic_add_negative_release arch_atomic_add_negative_release ++#endif ++ ++#ifndef arch_atomic_add_negative ++static __always_inline bool ++arch_atomic_add_negative(int i, atomic_t *v) ++{ ++ bool ret; ++ __atomic_pre_full_fence(); ++ ret = arch_atomic_add_negative_relaxed(i, v); ++ __atomic_post_full_fence(); ++ return ret; ++} ++#define arch_atomic_add_negative arch_atomic_add_negative ++#endif ++ ++#endif /* arch_atomic_add_negative_relaxed */ ++ + #ifndef arch_atomic_fetch_add_unless + /** + * arch_atomic_fetch_add_unless - add unless the number is already a given value +@@ -2329,15 +2424,21 @@ arch_atomic64_inc_and_test(atomic64_t *v) + #define arch_atomic64_inc_and_test arch_atomic64_inc_and_test + #endif + ++#ifndef arch_atomic64_add_negative_relaxed ++#ifdef arch_atomic64_add_negative ++#define arch_atomic64_add_negative_acquire arch_atomic64_add_negative ++#define arch_atomic64_add_negative_release arch_atomic64_add_negative ++#define arch_atomic64_add_negative_relaxed arch_atomic64_add_negative ++#endif /* arch_atomic64_add_negative */ ++ + #ifndef arch_atomic64_add_negative + /** +- * arch_atomic64_add_negative - add and test if negative ++ * arch_atomic64_add_negative - Add and test if negative + * @i: integer value to add + * @v: pointer of type atomic64_t + * +- * Atomically adds @i to @v and returns true +- * if the result is negative, or false when +- * result is greater than or equal to zero. ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. + */ + static __always_inline bool + arch_atomic64_add_negative(s64 i, atomic64_t *v) +@@ -2347,6 +2448,95 @@ arch_atomic64_add_negative(s64 i, atomic64_t *v) + #define arch_atomic64_add_negative arch_atomic64_add_negative + #endif + ++#ifndef arch_atomic64_add_negative_acquire ++/** ++ * arch_atomic64_add_negative_acquire - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic64_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic64_add_negative_acquire(s64 i, atomic64_t *v) ++{ ++ return arch_atomic64_add_return_acquire(i, v) < 0; ++} ++#define arch_atomic64_add_negative_acquire arch_atomic64_add_negative_acquire ++#endif ++ ++#ifndef arch_atomic64_add_negative_release ++/** ++ * arch_atomic64_add_negative_release - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic64_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic64_add_negative_release(s64 i, atomic64_t *v) ++{ ++ return arch_atomic64_add_return_release(i, v) < 0; ++} ++#define arch_atomic64_add_negative_release arch_atomic64_add_negative_release ++#endif ++ ++#ifndef arch_atomic64_add_negative_relaxed ++/** ++ * arch_atomic64_add_negative_relaxed - Add and test if negative ++ * @i: integer value to add ++ * @v: pointer of type atomic64_t ++ * ++ * Atomically adds @i to @v and returns true if the result is negative, ++ * or false when the result is greater than or equal to zero. ++ */ ++static __always_inline bool ++arch_atomic64_add_negative_relaxed(s64 i, atomic64_t *v) ++{ ++ return arch_atomic64_add_return_relaxed(i, v) < 0; ++} ++#define arch_atomic64_add_negative_relaxed arch_atomic64_add_negative_relaxed ++#endif ++ ++#else /* arch_atomic64_add_negative_relaxed */ ++ ++#ifndef arch_atomic64_add_negative_acquire ++static __always_inline bool ++arch_atomic64_add_negative_acquire(s64 i, atomic64_t *v) ++{ ++ bool ret = arch_atomic64_add_negative_relaxed(i, v); ++ __atomic_acquire_fence(); ++ return ret; ++} ++#define arch_atomic64_add_negative_acquire arch_atomic64_add_negative_acquire ++#endif ++ ++#ifndef arch_atomic64_add_negative_release ++static __always_inline bool ++arch_atomic64_add_negative_release(s64 i, atomic64_t *v) ++{ ++ __atomic_release_fence(); ++ return arch_atomic64_add_negative_relaxed(i, v); ++} ++#define arch_atomic64_add_negative_release arch_atomic64_add_negative_release ++#endif ++ ++#ifndef arch_atomic64_add_negative ++static __always_inline bool ++arch_atomic64_add_negative(s64 i, atomic64_t *v) ++{ ++ bool ret; ++ __atomic_pre_full_fence(); ++ ret = arch_atomic64_add_negative_relaxed(i, v); ++ __atomic_post_full_fence(); ++ return ret; ++} ++#define arch_atomic64_add_negative arch_atomic64_add_negative ++#endif ++ ++#endif /* arch_atomic64_add_negative_relaxed */ ++ + #ifndef arch_atomic64_fetch_add_unless + /** + * arch_atomic64_fetch_add_unless - add unless the number is already a given value +@@ -2456,4 +2646,4 @@ arch_atomic64_dec_if_positive(atomic64_t *v) + #endif + + #endif /* _LINUX_ATOMIC_FALLBACK_H */ +-// b5e87bdd5ede61470c29f7a7e4de781af3770f09 ++// 00071fffa021cec66f6290d706d69c91df87bade +diff --git a/include/linux/atomic/atomic-instrumented.h b/include/linux/atomic/atomic-instrumented.h +index 7a139ec030b0..0496816738ca 100644 +--- a/include/linux/atomic/atomic-instrumented.h ++++ b/include/linux/atomic/atomic-instrumented.h +@@ -592,6 +592,28 @@ atomic_add_negative(int i, atomic_t *v) + return arch_atomic_add_negative(i, v); + } + ++static __always_inline bool ++atomic_add_negative_acquire(int i, atomic_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_add_negative_acquire(i, v); ++} ++ ++static __always_inline bool ++atomic_add_negative_release(int i, atomic_t *v) ++{ ++ kcsan_release(); ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_add_negative_release(i, v); ++} ++ ++static __always_inline bool ++atomic_add_negative_relaxed(int i, atomic_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_add_negative_relaxed(i, v); ++} ++ + static __always_inline int + atomic_fetch_add_unless(atomic_t *v, int a, int u) + { +@@ -1211,6 +1233,28 @@ atomic64_add_negative(s64 i, atomic64_t *v) + return arch_atomic64_add_negative(i, v); + } + ++static __always_inline bool ++atomic64_add_negative_acquire(s64 i, atomic64_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic64_add_negative_acquire(i, v); ++} ++ ++static __always_inline bool ++atomic64_add_negative_release(s64 i, atomic64_t *v) ++{ ++ kcsan_release(); ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic64_add_negative_release(i, v); ++} ++ ++static __always_inline bool ++atomic64_add_negative_relaxed(s64 i, atomic64_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic64_add_negative_relaxed(i, v); ++} ++ + static __always_inline s64 + atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u) + { +@@ -1830,6 +1874,28 @@ atomic_long_add_negative(long i, atomic_long_t *v) + return arch_atomic_long_add_negative(i, v); + } + ++static __always_inline bool ++atomic_long_add_negative_acquire(long i, atomic_long_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_long_add_negative_acquire(i, v); ++} ++ ++static __always_inline bool ++atomic_long_add_negative_release(long i, atomic_long_t *v) ++{ ++ kcsan_release(); ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_long_add_negative_release(i, v); ++} ++ ++static __always_inline bool ++atomic_long_add_negative_relaxed(long i, atomic_long_t *v) ++{ ++ instrument_atomic_read_write(v, sizeof(*v)); ++ return arch_atomic_long_add_negative_relaxed(i, v); ++} ++ + static __always_inline long + atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u) + { +@@ -2083,4 +2149,4 @@ atomic_long_dec_if_positive(atomic_long_t *v) + }) + + #endif /* _LINUX_ATOMIC_INSTRUMENTED_H */ +-// 764f741eb77a7ad565dc8d99ce2837d5542e8aee ++// 1b485de9cbaa4900de59e14ee2084357eaeb1c3a +diff --git a/include/linux/atomic/atomic-long.h b/include/linux/atomic/atomic-long.h +index 800b8c35992d..2fc51ba66beb 100644 +--- a/include/linux/atomic/atomic-long.h ++++ b/include/linux/atomic/atomic-long.h +@@ -479,6 +479,24 @@ arch_atomic_long_add_negative(long i, atomic_long_t *v) + return arch_atomic64_add_negative(i, v); + } + ++static __always_inline bool ++arch_atomic_long_add_negative_acquire(long i, atomic_long_t *v) ++{ ++ return arch_atomic64_add_negative_acquire(i, v); ++} ++ ++static __always_inline bool ++arch_atomic_long_add_negative_release(long i, atomic_long_t *v) ++{ ++ return arch_atomic64_add_negative_release(i, v); ++} ++ ++static __always_inline bool ++arch_atomic_long_add_negative_relaxed(long i, atomic_long_t *v) ++{ ++ return arch_atomic64_add_negative_relaxed(i, v); ++} ++ + static __always_inline long + arch_atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u) + { +@@ -973,6 +991,24 @@ arch_atomic_long_add_negative(long i, atomic_long_t *v) + return arch_atomic_add_negative(i, v); + } + ++static __always_inline bool ++arch_atomic_long_add_negative_acquire(long i, atomic_long_t *v) ++{ ++ return arch_atomic_add_negative_acquire(i, v); ++} ++ ++static __always_inline bool ++arch_atomic_long_add_negative_release(long i, atomic_long_t *v) ++{ ++ return arch_atomic_add_negative_release(i, v); ++} ++ ++static __always_inline bool ++arch_atomic_long_add_negative_relaxed(long i, atomic_long_t *v) ++{ ++ return arch_atomic_add_negative_relaxed(i, v); ++} ++ + static __always_inline long + arch_atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u) + { +@@ -1011,4 +1047,4 @@ arch_atomic_long_dec_if_positive(atomic_long_t *v) + + #endif /* CONFIG_64BIT */ + #endif /* _LINUX_ATOMIC_LONG_H */ +-// e8f0e08ff072b74d180eabe2ad001282b38c2c88 ++// a194c07d7d2f4b0e178d3c118c919775d5d65f50 diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h index a57e6ae78e65..22b2ac82bffd 100644 --- a/include/linux/mm_types.h @@ -8436,6 +11922,314 @@ index 5f1ae07d724b..97cda629c9e9 100644 #endif /* CONFIG_HUGETLB_PAGE */ +diff --git a/include/linux/rcuref.h b/include/linux/rcuref.h +new file mode 100644 +index 000000000000..2c8bfd0f1b6b +--- /dev/null ++++ b/include/linux/rcuref.h +@@ -0,0 +1,155 @@ ++/* SPDX-License-Identifier: GPL-2.0-only */ ++#ifndef _LINUX_RCUREF_H ++#define _LINUX_RCUREF_H ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define RCUREF_ONEREF 0x00000000U ++#define RCUREF_MAXREF 0x7FFFFFFFU ++#define RCUREF_SATURATED 0xA0000000U ++#define RCUREF_RELEASED 0xC0000000U ++#define RCUREF_DEAD 0xE0000000U ++#define RCUREF_NOREF 0xFFFFFFFFU ++ ++/** ++ * rcuref_init - Initialize a rcuref reference count with the given reference count ++ * @ref: Pointer to the reference count ++ * @cnt: The initial reference count typically '1' ++ */ ++static inline void rcuref_init(rcuref_t *ref, unsigned int cnt) ++{ ++ atomic_set(&ref->refcnt, cnt - 1); ++} ++ ++/** ++ * rcuref_read - Read the number of held reference counts of a rcuref ++ * @ref: Pointer to the reference count ++ * ++ * Return: The number of held references (0 ... N) ++ */ ++static inline unsigned int rcuref_read(rcuref_t *ref) ++{ ++ unsigned int c = atomic_read(&ref->refcnt); ++ ++ /* Return 0 if within the DEAD zone. */ ++ return c >= RCUREF_RELEASED ? 0 : c + 1; ++} ++ ++extern __must_check bool rcuref_get_slowpath(rcuref_t *ref); ++ ++/** ++ * rcuref_get - Acquire one reference on a rcuref reference count ++ * @ref: Pointer to the reference count ++ * ++ * Similar to atomic_inc_not_zero() but saturates at RCUREF_MAXREF. ++ * ++ * Provides no memory ordering, it is assumed the caller has guaranteed the ++ * object memory to be stable (RCU, etc.). It does provide a control dependency ++ * and thereby orders future stores. See documentation in lib/rcuref.c ++ * ++ * Return: ++ * False if the attempt to acquire a reference failed. This happens ++ * when the last reference has been put already ++ * ++ * True if a reference was successfully acquired ++ */ ++static inline __must_check bool rcuref_get(rcuref_t *ref) ++{ ++ /* ++ * Unconditionally increase the reference count. The saturation and ++ * dead zones provide enough tolerance for this. ++ */ ++ if (likely(!atomic_add_negative_relaxed(1, &ref->refcnt))) ++ return true; ++ ++ /* Handle the cases inside the saturation and dead zones */ ++ return rcuref_get_slowpath(ref); ++} ++ ++extern __must_check bool rcuref_put_slowpath(rcuref_t *ref); ++ ++/* ++ * Internal helper. Do not invoke directly. ++ */ ++static __always_inline __must_check bool __rcuref_put(rcuref_t *ref) ++{ ++ RCU_LOCKDEP_WARN(!rcu_read_lock_held() && preemptible(), ++ "suspicious rcuref_put_rcusafe() usage"); ++ /* ++ * Unconditionally decrease the reference count. The saturation and ++ * dead zones provide enough tolerance for this. ++ */ ++ if (likely(!atomic_add_negative_release(-1, &ref->refcnt))) ++ return false; ++ ++ /* ++ * Handle the last reference drop and cases inside the saturation ++ * and dead zones. ++ */ ++ return rcuref_put_slowpath(ref); ++} ++ ++/** ++ * rcuref_put_rcusafe -- Release one reference for a rcuref reference count RCU safe ++ * @ref: Pointer to the reference count ++ * ++ * Provides release memory ordering, such that prior loads and stores are done ++ * before, and provides an acquire ordering on success such that free() ++ * must come after. ++ * ++ * Can be invoked from contexts, which guarantee that no grace period can ++ * happen which would free the object concurrently if the decrement drops ++ * the last reference and the slowpath races against a concurrent get() and ++ * put() pair. rcu_read_lock()'ed and atomic contexts qualify. ++ * ++ * Return: ++ * True if this was the last reference with no future references ++ * possible. This signals the caller that it can safely release the ++ * object which is protected by the reference counter. ++ * ++ * False if there are still active references or the put() raced ++ * with a concurrent get()/put() pair. Caller is not allowed to ++ * release the protected object. ++ */ ++static inline __must_check bool rcuref_put_rcusafe(rcuref_t *ref) ++{ ++ return __rcuref_put(ref); ++} ++ ++/** ++ * rcuref_put -- Release one reference for a rcuref reference count ++ * @ref: Pointer to the reference count ++ * ++ * Can be invoked from any context. ++ * ++ * Provides release memory ordering, such that prior loads and stores are done ++ * before, and provides an acquire ordering on success such that free() ++ * must come after. ++ * ++ * Return: ++ * ++ * True if this was the last reference with no future references ++ * possible. This signals the caller that it can safely schedule the ++ * object, which is protected by the reference counter, for ++ * deconstruction. ++ * ++ * False if there are still active references or the put() raced ++ * with a concurrent get()/put() pair. Caller is not allowed to ++ * deconstruct the protected object. ++ */ ++static inline __must_check bool rcuref_put(rcuref_t *ref) ++{ ++ bool released; ++ ++ preempt_disable(); ++ released = __rcuref_put(ref); ++ preempt_enable(); ++ return released; ++} ++ ++#endif +diff --git a/include/linux/types.h b/include/linux/types.h +index ea8cf60a8a79..688fb943556a 100644 +--- a/include/linux/types.h ++++ b/include/linux/types.h +@@ -175,6 +175,12 @@ typedef struct { + } atomic64_t; + #endif + ++typedef struct { ++ atomic_t refcnt; ++} rcuref_t; ++ ++#define RCUREF_INIT(i) { .refcnt = ATOMIC_INIT(i - 1) } ++ + struct list_head { + struct list_head *next, *prev; + }; +diff --git a/include/net/dst.h b/include/net/dst.h +index d67fda89cd0f..78884429deed 100644 +--- a/include/net/dst.h ++++ b/include/net/dst.h +@@ -16,6 +16,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -61,23 +62,36 @@ struct dst_entry { + unsigned short trailer_len; /* space to reserve at tail */ + + /* +- * __refcnt wants to be on a different cache line from ++ * __rcuref wants to be on a different cache line from + * input/output/ops or performance tanks badly + */ + #ifdef CONFIG_64BIT +- atomic_t __refcnt; /* 64-bit offset 64 */ ++ rcuref_t __rcuref; /* 64-bit offset 64 */ + #endif + int __use; + unsigned long lastuse; +- struct lwtunnel_state *lwtstate; + struct rcu_head rcu_head; + short error; + short __pad; + __u32 tclassid; + #ifndef CONFIG_64BIT +- atomic_t __refcnt; /* 32-bit offset 64 */ ++ struct lwtunnel_state *lwtstate; ++ rcuref_t __rcuref; /* 32-bit offset 64 */ + #endif + netdevice_tracker dev_tracker; ++ ++ /* ++ * Used by rtable and rt6_info. Moves lwtstate into the next cache ++ * line on 64bit so that lwtstate does not cause false sharing with ++ * __rcuref under contention of __rcuref. This also puts the ++ * frequently accessed members of rtable and rt6_info out of the ++ * __rcuref cache line. ++ */ ++ struct list_head rt_uncached; ++ struct uncached_list *rt_uncached_list; ++#ifdef CONFIG_64BIT ++ struct lwtunnel_state *lwtstate; ++#endif + }; + + struct dst_metrics { +@@ -225,10 +239,10 @@ static inline void dst_hold(struct dst_entry *dst) + { + /* + * If your kernel compilation stops here, please check +- * the placement of __refcnt in struct dst_entry ++ * the placement of __rcuref in struct dst_entry + */ +- BUILD_BUG_ON(offsetof(struct dst_entry, __refcnt) & 63); +- WARN_ON(atomic_inc_not_zero(&dst->__refcnt) == 0); ++ BUILD_BUG_ON(offsetof(struct dst_entry, __rcuref) & 63); ++ WARN_ON(!rcuref_get(&dst->__rcuref)); + } + + static inline void dst_use_noref(struct dst_entry *dst, unsigned long time) +@@ -292,7 +306,7 @@ static inline void skb_dst_copy(struct sk_buff *nskb, const struct sk_buff *oskb + */ + static inline bool dst_hold_safe(struct dst_entry *dst) + { +- return atomic_inc_not_zero(&dst->__refcnt); ++ return rcuref_get(&dst->__rcuref); + } + + /** +diff --git a/include/net/ip6_fib.h b/include/net/ip6_fib.h +index 6268963d9599..79570cb4ea9c 100644 +--- a/include/net/ip6_fib.h ++++ b/include/net/ip6_fib.h +@@ -217,9 +217,6 @@ struct rt6_info { + struct inet6_dev *rt6i_idev; + u32 rt6i_flags; + +- struct list_head rt6i_uncached; +- struct uncached_list *rt6i_uncached_list; +- + /* more non-fragment space at head required */ + unsigned short rt6i_nfheader_len; + }; +diff --git a/include/net/ip6_route.h b/include/net/ip6_route.h +index 81ee387a1fc4..3556595ce59a 100644 +--- a/include/net/ip6_route.h ++++ b/include/net/ip6_route.h +@@ -100,7 +100,7 @@ static inline struct dst_entry *ip6_route_output(struct net *net, + static inline void ip6_rt_put_flags(struct rt6_info *rt, int flags) + { + if (!(flags & RT6_LOOKUP_F_DST_NOREF) || +- !list_empty(&rt->rt6i_uncached)) ++ !list_empty(&rt->dst.rt_uncached)) + ip6_rt_put(rt); + } + +diff --git a/include/net/route.h b/include/net/route.h +index fe00b0a2e475..bcc367cf3aa2 100644 +--- a/include/net/route.h ++++ b/include/net/route.h +@@ -78,9 +78,6 @@ struct rtable { + /* Miscellaneous cached information */ + u32 rt_mtu_locked:1, + rt_pmtu:31; +- +- struct list_head rt_uncached; +- struct uncached_list *rt_uncached_list; + }; + + static inline bool rt_is_input_route(const struct rtable *rt) +diff --git a/include/net/sock.h b/include/net/sock.h +index 573f2bf7e0de..5edf0038867c 100644 +--- a/include/net/sock.h ++++ b/include/net/sock.h +@@ -2131,7 +2131,7 @@ sk_dst_get(struct sock *sk) + + rcu_read_lock(); + dst = rcu_dereference(sk->sk_dst_cache); +- if (dst && !atomic_inc_not_zero(&dst->__refcnt)) ++ if (dst && !rcuref_get(&dst->__rcuref)) + dst = NULL; + rcu_read_unlock(); + return dst; diff --git a/kernel/kheaders.c b/kernel/kheaders.c index 8f69772af77b..42163c9e94e5 100644 --- a/kernel/kheaders.c @@ -8492,6 +12286,306 @@ index e007b8a4b738..7c80301ab084 100644 { struct padata_work *pw = container_of(w, struct padata_work, pw_work); struct padata_mt_job_state *ps = pw->pw_data; +diff --git a/lib/Makefile b/lib/Makefile +index baf2821f7a00..31a3a257fd49 100644 +--- a/lib/Makefile ++++ b/lib/Makefile +@@ -47,7 +47,7 @@ obj-y += bcd.o sort.o parser.o debug_locks.o random32.o \ + list_sort.o uuid.o iov_iter.o clz_ctz.o \ + bsearch.o find_bit.o llist.o memweight.o kfifo.o \ + percpu-refcount.o rhashtable.o base64.o \ +- once.o refcount.o usercopy.o errseq.o bucket_locks.o \ ++ once.o refcount.o rcuref.o usercopy.o errseq.o bucket_locks.o \ + generic-radix-tree.o + obj-$(CONFIG_STRING_SELFTEST) += test_string.o + obj-y += string_helpers.o +diff --git a/lib/rcuref.c b/lib/rcuref.c +new file mode 100644 +index 000000000000..5ec00a4a64d1 +--- /dev/null ++++ b/lib/rcuref.c +@@ -0,0 +1,281 @@ ++// SPDX-License-Identifier: GPL-2.0-only ++ ++/* ++ * rcuref - A scalable reference count implementation for RCU managed objects ++ * ++ * rcuref is provided to replace open coded reference count implementations ++ * based on atomic_t. It protects explicitely RCU managed objects which can ++ * be visible even after the last reference has been dropped and the object ++ * is heading towards destruction. ++ * ++ * A common usage pattern is: ++ * ++ * get() ++ * rcu_read_lock(); ++ * p = get_ptr(); ++ * if (p && !atomic_inc_not_zero(&p->refcnt)) ++ * p = NULL; ++ * rcu_read_unlock(); ++ * return p; ++ * ++ * put() ++ * if (!atomic_dec_return(&->refcnt)) { ++ * remove_ptr(p); ++ * kfree_rcu((p, rcu); ++ * } ++ * ++ * atomic_inc_not_zero() is implemented with a try_cmpxchg() loop which has ++ * O(N^2) behaviour under contention with N concurrent operations. ++ * ++ * rcuref uses atomic_add_negative_relaxed() for the fast path, which scales ++ * better under contention. ++ * ++ * Why not refcount? ++ * ================= ++ * ++ * In principle it should be possible to make refcount use the rcuref ++ * scheme, but the destruction race described below cannot be prevented ++ * unless the protected object is RCU managed. ++ * ++ * Theory of operation ++ * =================== ++ * ++ * rcuref uses an unsigned integer reference counter. As long as the ++ * counter value is greater than or equal to RCUREF_ONEREF and not larger ++ * than RCUREF_MAXREF the reference is alive: ++ * ++ * ONEREF MAXREF SATURATED RELEASED DEAD NOREF ++ * 0 0x7FFFFFFF 0x8000000 0xA0000000 0xBFFFFFFF 0xC0000000 0xE0000000 0xFFFFFFFF ++ * <---valid --------> <-------saturation zone-------> <-----dead zone-----> ++ * ++ * The get() and put() operations do unconditional increments and ++ * decrements. The result is checked after the operation. This optimizes ++ * for the fast path. ++ * ++ * If the reference count is saturated or dead, then the increments and ++ * decrements are not harmful as the reference count still stays in the ++ * respective zones and is always set back to STATURATED resp. DEAD. The ++ * zones have room for 2^28 racing operations in each direction, which ++ * makes it practically impossible to escape the zones. ++ * ++ * Once the last reference is dropped the reference count becomes ++ * RCUREF_NOREF which forces rcuref_put() into the slowpath operation. The ++ * slowpath then tries to set the reference count from RCUREF_NOREF to ++ * RCUREF_DEAD via a cmpxchg(). This opens a small window where a ++ * concurrent rcuref_get() can acquire the reference count and bring it ++ * back to RCUREF_ONEREF or even drop the reference again and mark it DEAD. ++ * ++ * If the cmpxchg() succeeds then a concurrent rcuref_get() will result in ++ * DEAD + 1, which is inside the dead zone. If that happens the reference ++ * count is put back to DEAD. ++ * ++ * The actual race is possible due to the unconditional increment and ++ * decrements in rcuref_get() and rcuref_put(): ++ * ++ * T1 T2 ++ * get() put() ++ * if (atomic_add_negative(-1, &ref->refcnt)) ++ * succeeds-> atomic_cmpxchg(&ref->refcnt, NOREF, DEAD); ++ * ++ * atomic_add_negative(1, &ref->refcnt); <- Elevates refcount to DEAD + 1 ++ * ++ * As the result of T1's add is negative, the get() goes into the slow path ++ * and observes refcnt being in the dead zone which makes the operation fail. ++ * ++ * Possible critical states: ++ * ++ * Context Counter References Operation ++ * T1 0 1 init() ++ * T2 1 2 get() ++ * T1 0 1 put() ++ * T2 -1 0 put() tries to mark dead ++ * T1 0 1 get() ++ * T2 0 1 put() mark dead fails ++ * T1 -1 0 put() tries to mark dead ++ * T1 DEAD 0 put() mark dead succeeds ++ * T2 DEAD+1 0 get() fails and puts it back to DEAD ++ * ++ * Of course there are more complex scenarios, but the above illustrates ++ * the working principle. The rest is left to the imagination of the ++ * reader. ++ * ++ * Deconstruction race ++ * =================== ++ * ++ * The release operation must be protected by prohibiting a grace period in ++ * order to prevent a possible use after free: ++ * ++ * T1 T2 ++ * put() get() ++ * // ref->refcnt = ONEREF ++ * if (!atomic_add_negative(-1, &ref->refcnt)) ++ * return false; <- Not taken ++ * ++ * // ref->refcnt == NOREF ++ * --> preemption ++ * // Elevates ref->refcnt to ONEREF ++ * if (!atomic_add_negative(1, &ref->refcnt)) ++ * return true; <- taken ++ * ++ * if (put(&p->ref)) { <-- Succeeds ++ * remove_pointer(p); ++ * kfree_rcu(p, rcu); ++ * } ++ * ++ * RCU grace period ends, object is freed ++ * ++ * atomic_cmpxchg(&ref->refcnt, NOREF, DEAD); <- UAF ++ * ++ * This is prevented by disabling preemption around the put() operation as ++ * that's in most kernel configurations cheaper than a rcu_read_lock() / ++ * rcu_read_unlock() pair and in many cases even a NOOP. In any case it ++ * prevents the grace period which keeps the object alive until all put() ++ * operations complete. ++ * ++ * Saturation protection ++ * ===================== ++ * ++ * The reference count has a saturation limit RCUREF_MAXREF (INT_MAX). ++ * Once this is exceedded the reference count becomes stale by setting it ++ * to RCUREF_SATURATED, which will cause a memory leak, but it prevents ++ * wrap arounds which obviously cause worse problems than a memory ++ * leak. When saturation is reached a warning is emitted. ++ * ++ * Race conditions ++ * =============== ++ * ++ * All reference count increment/decrement operations are unconditional and ++ * only verified after the fact. This optimizes for the good case and takes ++ * the occasional race vs. a dead or already saturated refcount into ++ * account. The saturation and dead zones are large enough to accomodate ++ * for that. ++ * ++ * Memory ordering ++ * =============== ++ * ++ * Memory ordering rules are slightly relaxed wrt regular atomic_t functions ++ * and provide only what is strictly required for refcounts. ++ * ++ * The increments are fully relaxed; these will not provide ordering. The ++ * rationale is that whatever is used to obtain the object to increase the ++ * reference count on will provide the ordering. For locked data ++ * structures, its the lock acquire, for RCU/lockless data structures its ++ * the dependent load. ++ * ++ * rcuref_get() provides a control dependency ordering future stores which ++ * ensures that the object is not modified when acquiring a reference ++ * fails. ++ * ++ * rcuref_put() provides release order, i.e. all prior loads and stores ++ * will be issued before. It also provides a control dependency ordering ++ * against the subsequent destruction of the object. ++ * ++ * If rcuref_put() successfully dropped the last reference and marked the ++ * object DEAD it also provides acquire ordering. ++ */ ++ ++#include ++#include ++ ++/** ++ * rcuref_get_slowpath - Slowpath of rcuref_get() ++ * @ref: Pointer to the reference count ++ * ++ * Invoked when the reference count is outside of the valid zone. ++ * ++ * Return: ++ * False if the reference count was already marked dead ++ * ++ * True if the reference count is saturated, which prevents the ++ * object from being deconstructed ever. ++ */ ++bool rcuref_get_slowpath(rcuref_t *ref) ++{ ++ unsigned int cnt = atomic_read(&ref->refcnt); ++ ++ /* ++ * If the reference count was already marked dead, undo the ++ * increment so it stays in the middle of the dead zone and return ++ * fail. ++ */ ++ if (cnt >= RCUREF_RELEASED) { ++ atomic_set(&ref->refcnt, RCUREF_DEAD); ++ return false; ++ } ++ ++ /* ++ * If it was saturated, warn and mark it so. In case the increment ++ * was already on a saturated value restore the saturation ++ * marker. This keeps it in the middle of the saturation zone and ++ * prevents the reference count from overflowing. This leaks the ++ * object memory, but prevents the obvious reference count overflow ++ * damage. ++ */ ++ if (WARN_ONCE(cnt > RCUREF_MAXREF, "rcuref saturated - leaking memory")) ++ atomic_set(&ref->refcnt, RCUREF_SATURATED); ++ return true; ++} ++EXPORT_SYMBOL_GPL(rcuref_get_slowpath); ++ ++/** ++ * rcuref_put_slowpath - Slowpath of __rcuref_put() ++ * @ref: Pointer to the reference count ++ * ++ * Invoked when the reference count is outside of the valid zone. ++ * ++ * Return: ++ * True if this was the last reference with no future references ++ * possible. This signals the caller that it can safely schedule the ++ * object, which is protected by the reference counter, for ++ * deconstruction. ++ * ++ * False if there are still active references or the put() raced ++ * with a concurrent get()/put() pair. Caller is not allowed to ++ * deconstruct the protected object. ++ */ ++bool rcuref_put_slowpath(rcuref_t *ref) ++{ ++ unsigned int cnt = atomic_read(&ref->refcnt); ++ ++ /* Did this drop the last reference? */ ++ if (likely(cnt == RCUREF_NOREF)) { ++ /* ++ * Carefully try to set the reference count to RCUREF_DEAD. ++ * ++ * This can fail if a concurrent get() operation has ++ * elevated it again or the corresponding put() even marked ++ * it dead already. Both are valid situations and do not ++ * require a retry. If this fails the caller is not ++ * allowed to deconstruct the object. ++ */ ++ if (atomic_cmpxchg_release(&ref->refcnt, RCUREF_NOREF, RCUREF_DEAD) != RCUREF_NOREF) ++ return false; ++ ++ /* ++ * The caller can safely schedule the object for ++ * deconstruction. Provide acquire ordering. ++ */ ++ smp_acquire__after_ctrl_dep(); ++ return true; ++ } ++ ++ /* ++ * If the reference count was already in the dead zone, then this ++ * put() operation is imbalanced. Warn, put the reference count back to ++ * DEAD and tell the caller to not deconstruct the object. ++ */ ++ if (WARN_ONCE(cnt >= RCUREF_RELEASED, "rcuref - imbalanced put()")) { ++ atomic_set(&ref->refcnt, RCUREF_DEAD); ++ return false; ++ } ++ ++ /* ++ * This is a put() operation on a saturated refcount. Restore the ++ * mean saturation value and tell the caller to not deconstruct the ++ * object. ++ */ ++ if (cnt > RCUREF_MAXREF) ++ atomic_set(&ref->refcnt, RCUREF_SATURATED); ++ return false; ++} ++EXPORT_SYMBOL_GPL(rcuref_put_slowpath); diff --git a/mm/ksm.c b/mm/ksm.c index 2b8d30068cbb..82029f1d454b 100644 --- a/mm/ksm.c @@ -8835,6 +12929,349 @@ index 2b8d30068cbb..82029f1d454b 100644 &full_scans_attr.attr, #ifdef CONFIG_NUMA &merge_across_nodes_attr.attr, +diff --git a/net/bridge/br_nf_core.c b/net/bridge/br_nf_core.c +index 8c69f0c95a8e..98aea5485aae 100644 +--- a/net/bridge/br_nf_core.c ++++ b/net/bridge/br_nf_core.c +@@ -73,7 +73,7 @@ void br_netfilter_rtable_init(struct net_bridge *br) + { + struct rtable *rt = &br->fake_rtable; + +- atomic_set(&rt->dst.__refcnt, 1); ++ rcuref_init(&rt->dst.__rcuref, 1); + rt->dst.dev = br->dev; + dst_init_metrics(&rt->dst, br_dst_default_metrics, true); + rt->dst.flags = DST_NOXFRM | DST_FAKE_RTABLE; +diff --git a/net/core/dst.c b/net/core/dst.c +index 31c08a3386d3..3247e84045ca 100644 +--- a/net/core/dst.c ++++ b/net/core/dst.c +@@ -66,7 +66,7 @@ void dst_init(struct dst_entry *dst, struct dst_ops *ops, + dst->tclassid = 0; + #endif + dst->lwtstate = NULL; +- atomic_set(&dst->__refcnt, initial_ref); ++ rcuref_init(&dst->__rcuref, initial_ref); + dst->__use = 0; + dst->lastuse = jiffies; + dst->flags = flags; +@@ -162,31 +162,15 @@ EXPORT_SYMBOL(dst_dev_put); + + void dst_release(struct dst_entry *dst) + { +- if (dst) { +- int newrefcnt; +- +- newrefcnt = atomic_dec_return(&dst->__refcnt); +- if (WARN_ONCE(newrefcnt < 0, "dst_release underflow")) +- net_warn_ratelimited("%s: dst:%p refcnt:%d\n", +- __func__, dst, newrefcnt); +- if (!newrefcnt) +- call_rcu_hurry(&dst->rcu_head, dst_destroy_rcu); +- } ++ if (dst && rcuref_put(&dst->__rcuref)) ++ call_rcu_hurry(&dst->rcu_head, dst_destroy_rcu); + } + EXPORT_SYMBOL(dst_release); + + void dst_release_immediate(struct dst_entry *dst) + { +- if (dst) { +- int newrefcnt; +- +- newrefcnt = atomic_dec_return(&dst->__refcnt); +- if (WARN_ONCE(newrefcnt < 0, "dst_release_immediate underflow")) +- net_warn_ratelimited("%s: dst:%p refcnt:%d\n", +- __func__, dst, newrefcnt); +- if (!newrefcnt) +- dst_destroy(dst); +- } ++ if (dst && rcuref_put(&dst->__rcuref)) ++ dst_destroy(dst); + } + EXPORT_SYMBOL(dst_release_immediate); + +diff --git a/net/core/rtnetlink.c b/net/core/rtnetlink.c +index 6e44e92ebdf5..a6380dd47e7f 100644 +--- a/net/core/rtnetlink.c ++++ b/net/core/rtnetlink.c +@@ -840,7 +840,7 @@ int rtnl_put_cacheinfo(struct sk_buff *skb, struct dst_entry *dst, u32 id, + if (dst) { + ci.rta_lastuse = jiffies_delta_to_clock_t(jiffies - dst->lastuse); + ci.rta_used = dst->__use; +- ci.rta_clntref = atomic_read(&dst->__refcnt); ++ ci.rta_clntref = rcuref_read(&dst->__rcuref); + } + if (expires) { + unsigned long clock; +diff --git a/net/ipv4/route.c b/net/ipv4/route.c +index de6e3515ab4f..0f0cb629e0ad 100644 +--- a/net/ipv4/route.c ++++ b/net/ipv4/route.c +@@ -1508,20 +1508,20 @@ void rt_add_uncached_list(struct rtable *rt) + { + struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list); + +- rt->rt_uncached_list = ul; ++ rt->dst.rt_uncached_list = ul; + + spin_lock_bh(&ul->lock); +- list_add_tail(&rt->rt_uncached, &ul->head); ++ list_add_tail(&rt->dst.rt_uncached, &ul->head); + spin_unlock_bh(&ul->lock); + } + + void rt_del_uncached_list(struct rtable *rt) + { +- if (!list_empty(&rt->rt_uncached)) { +- struct uncached_list *ul = rt->rt_uncached_list; ++ if (!list_empty(&rt->dst.rt_uncached)) { ++ struct uncached_list *ul = rt->dst.rt_uncached_list; + + spin_lock_bh(&ul->lock); +- list_del_init(&rt->rt_uncached); ++ list_del_init(&rt->dst.rt_uncached); + spin_unlock_bh(&ul->lock); + } + } +@@ -1546,13 +1546,13 @@ void rt_flush_dev(struct net_device *dev) + continue; + + spin_lock_bh(&ul->lock); +- list_for_each_entry_safe(rt, safe, &ul->head, rt_uncached) { ++ list_for_each_entry_safe(rt, safe, &ul->head, dst.rt_uncached) { + if (rt->dst.dev != dev) + continue; + rt->dst.dev = blackhole_netdev; + netdev_ref_replace(dev, blackhole_netdev, + &rt->dst.dev_tracker, GFP_ATOMIC); +- list_move(&rt->rt_uncached, &ul->quarantine); ++ list_move(&rt->dst.rt_uncached, &ul->quarantine); + } + spin_unlock_bh(&ul->lock); + } +@@ -1644,7 +1644,7 @@ struct rtable *rt_dst_alloc(struct net_device *dev, + rt->rt_uses_gateway = 0; + rt->rt_gw_family = 0; + rt->rt_gw4 = 0; +- INIT_LIST_HEAD(&rt->rt_uncached); ++ INIT_LIST_HEAD(&rt->dst.rt_uncached); + + rt->dst.output = ip_output; + if (flags & RTCF_LOCAL) +@@ -1675,7 +1675,7 @@ struct rtable *rt_dst_clone(struct net_device *dev, struct rtable *rt) + new_rt->rt_gw4 = rt->rt_gw4; + else if (rt->rt_gw_family == AF_INET6) + new_rt->rt_gw6 = rt->rt_gw6; +- INIT_LIST_HEAD(&new_rt->rt_uncached); ++ INIT_LIST_HEAD(&new_rt->dst.rt_uncached); + + new_rt->dst.input = rt->dst.input; + new_rt->dst.output = rt->dst.output; +@@ -2859,7 +2859,7 @@ struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_or + else if (rt->rt_gw_family == AF_INET6) + rt->rt_gw6 = ort->rt_gw6; + +- INIT_LIST_HEAD(&rt->rt_uncached); ++ INIT_LIST_HEAD(&rt->dst.rt_uncached); + } + + dst_release(dst_orig); +diff --git a/net/ipv4/xfrm4_policy.c b/net/ipv4/xfrm4_policy.c +index 3d0dfa6cf9f9..47861c8b7340 100644 +--- a/net/ipv4/xfrm4_policy.c ++++ b/net/ipv4/xfrm4_policy.c +@@ -91,7 +91,7 @@ static int xfrm4_fill_dst(struct xfrm_dst *xdst, struct net_device *dev, + xdst->u.rt.rt_gw6 = rt->rt_gw6; + xdst->u.rt.rt_pmtu = rt->rt_pmtu; + xdst->u.rt.rt_mtu_locked = rt->rt_mtu_locked; +- INIT_LIST_HEAD(&xdst->u.rt.rt_uncached); ++ INIT_LIST_HEAD(&xdst->u.rt.dst.rt_uncached); + rt_add_uncached_list(&xdst->u.rt); + + return 0; +@@ -121,7 +121,7 @@ static void xfrm4_dst_destroy(struct dst_entry *dst) + struct xfrm_dst *xdst = (struct xfrm_dst *)dst; + + dst_destroy_metrics_generic(dst); +- if (xdst->u.rt.rt_uncached_list) ++ if (xdst->u.rt.dst.rt_uncached_list) + rt_del_uncached_list(&xdst->u.rt); + xfrm_dst_destroy(xdst); + } +diff --git a/net/ipv6/route.c b/net/ipv6/route.c +index 0fdb03df2287..b9d22a0a6c09 100644 +--- a/net/ipv6/route.c ++++ b/net/ipv6/route.c +@@ -139,20 +139,20 @@ void rt6_uncached_list_add(struct rt6_info *rt) + { + struct uncached_list *ul = raw_cpu_ptr(&rt6_uncached_list); + +- rt->rt6i_uncached_list = ul; ++ rt->dst.rt_uncached_list = ul; + + spin_lock_bh(&ul->lock); +- list_add_tail(&rt->rt6i_uncached, &ul->head); ++ list_add_tail(&rt->dst.rt_uncached, &ul->head); + spin_unlock_bh(&ul->lock); + } + + void rt6_uncached_list_del(struct rt6_info *rt) + { +- if (!list_empty(&rt->rt6i_uncached)) { +- struct uncached_list *ul = rt->rt6i_uncached_list; ++ if (!list_empty(&rt->dst.rt_uncached)) { ++ struct uncached_list *ul = rt->dst.rt_uncached_list; + + spin_lock_bh(&ul->lock); +- list_del_init(&rt->rt6i_uncached); ++ list_del_init(&rt->dst.rt_uncached); + spin_unlock_bh(&ul->lock); + } + } +@@ -169,7 +169,7 @@ static void rt6_uncached_list_flush_dev(struct net_device *dev) + continue; + + spin_lock_bh(&ul->lock); +- list_for_each_entry_safe(rt, safe, &ul->head, rt6i_uncached) { ++ list_for_each_entry_safe(rt, safe, &ul->head, dst.rt_uncached) { + struct inet6_dev *rt_idev = rt->rt6i_idev; + struct net_device *rt_dev = rt->dst.dev; + bool handled = false; +@@ -188,7 +188,7 @@ static void rt6_uncached_list_flush_dev(struct net_device *dev) + handled = true; + } + if (handled) +- list_move(&rt->rt6i_uncached, ++ list_move(&rt->dst.rt_uncached, + &ul->quarantine); + } + spin_unlock_bh(&ul->lock); +@@ -293,7 +293,7 @@ static const struct fib6_info fib6_null_entry_template = { + + static const struct rt6_info ip6_null_entry_template = { + .dst = { +- .__refcnt = ATOMIC_INIT(1), ++ .__rcuref = RCUREF_INIT(1), + .__use = 1, + .obsolete = DST_OBSOLETE_FORCE_CHK, + .error = -ENETUNREACH, +@@ -307,7 +307,7 @@ static const struct rt6_info ip6_null_entry_template = { + + static const struct rt6_info ip6_prohibit_entry_template = { + .dst = { +- .__refcnt = ATOMIC_INIT(1), ++ .__rcuref = RCUREF_INIT(1), + .__use = 1, + .obsolete = DST_OBSOLETE_FORCE_CHK, + .error = -EACCES, +@@ -319,7 +319,7 @@ static const struct rt6_info ip6_prohibit_entry_template = { + + static const struct rt6_info ip6_blk_hole_entry_template = { + .dst = { +- .__refcnt = ATOMIC_INIT(1), ++ .__rcuref = RCUREF_INIT(1), + .__use = 1, + .obsolete = DST_OBSOLETE_FORCE_CHK, + .error = -EINVAL, +@@ -334,7 +334,7 @@ static const struct rt6_info ip6_blk_hole_entry_template = { + static void rt6_info_init(struct rt6_info *rt) + { + memset_after(rt, 0, dst); +- INIT_LIST_HEAD(&rt->rt6i_uncached); ++ INIT_LIST_HEAD(&rt->dst.rt_uncached); + } + + /* allocate dst with ip6_dst_ops */ +@@ -2638,7 +2638,7 @@ struct dst_entry *ip6_route_output_flags(struct net *net, + dst = ip6_route_output_flags_noref(net, sk, fl6, flags); + rt6 = (struct rt6_info *)dst; + /* For dst cached in uncached_list, refcnt is already taken. */ +- if (list_empty(&rt6->rt6i_uncached) && !dst_hold_safe(dst)) { ++ if (list_empty(&rt6->dst.rt_uncached) && !dst_hold_safe(dst)) { + dst = &net->ipv6.ip6_null_entry->dst; + dst_hold(dst); + } +@@ -2748,7 +2748,7 @@ INDIRECT_CALLABLE_SCOPE struct dst_entry *ip6_dst_check(struct dst_entry *dst, + from = rcu_dereference(rt->from); + + if (from && (rt->rt6i_flags & RTF_PCPU || +- unlikely(!list_empty(&rt->rt6i_uncached)))) ++ unlikely(!list_empty(&rt->dst.rt_uncached)))) + dst_ret = rt6_dst_from_check(rt, from, cookie); + else + dst_ret = rt6_check(rt, from, cookie); +@@ -6477,7 +6477,7 @@ static int __net_init ip6_route_net_init(struct net *net) + net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops; + dst_init_metrics(&net->ipv6.ip6_null_entry->dst, + ip6_template_metrics, true); +- INIT_LIST_HEAD(&net->ipv6.ip6_null_entry->rt6i_uncached); ++ INIT_LIST_HEAD(&net->ipv6.ip6_null_entry->dst.rt_uncached); + + #ifdef CONFIG_IPV6_MULTIPLE_TABLES + net->ipv6.fib6_has_custom_rules = false; +@@ -6489,7 +6489,7 @@ static int __net_init ip6_route_net_init(struct net *net) + net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops; + dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst, + ip6_template_metrics, true); +- INIT_LIST_HEAD(&net->ipv6.ip6_prohibit_entry->rt6i_uncached); ++ INIT_LIST_HEAD(&net->ipv6.ip6_prohibit_entry->dst.rt_uncached); + + net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template, + sizeof(*net->ipv6.ip6_blk_hole_entry), +@@ -6499,7 +6499,7 @@ static int __net_init ip6_route_net_init(struct net *net) + net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops; + dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst, + ip6_template_metrics, true); +- INIT_LIST_HEAD(&net->ipv6.ip6_blk_hole_entry->rt6i_uncached); ++ INIT_LIST_HEAD(&net->ipv6.ip6_blk_hole_entry->dst.rt_uncached); + #ifdef CONFIG_IPV6_SUBTREES + net->ipv6.fib6_routes_require_src = 0; + #endif +diff --git a/net/ipv6/xfrm6_policy.c b/net/ipv6/xfrm6_policy.c +index ea435eba3053..2b493f8d0091 100644 +--- a/net/ipv6/xfrm6_policy.c ++++ b/net/ipv6/xfrm6_policy.c +@@ -89,7 +89,7 @@ static int xfrm6_fill_dst(struct xfrm_dst *xdst, struct net_device *dev, + xdst->u.rt6.rt6i_gateway = rt->rt6i_gateway; + xdst->u.rt6.rt6i_dst = rt->rt6i_dst; + xdst->u.rt6.rt6i_src = rt->rt6i_src; +- INIT_LIST_HEAD(&xdst->u.rt6.rt6i_uncached); ++ INIT_LIST_HEAD(&xdst->u.rt6.dst.rt_uncached); + rt6_uncached_list_add(&xdst->u.rt6); + + return 0; +@@ -121,7 +121,7 @@ static void xfrm6_dst_destroy(struct dst_entry *dst) + if (likely(xdst->u.rt6.rt6i_idev)) + in6_dev_put(xdst->u.rt6.rt6i_idev); + dst_destroy_metrics_generic(dst); +- if (xdst->u.rt6.rt6i_uncached_list) ++ if (xdst->u.rt6.dst.rt_uncached_list) + rt6_uncached_list_del(&xdst->u.rt6); + xfrm_dst_destroy(xdst); + } +diff --git a/net/netfilter/ipvs/ip_vs_xmit.c b/net/netfilter/ipvs/ip_vs_xmit.c +index 80448885c3d7..99c349c0d968 100644 +--- a/net/netfilter/ipvs/ip_vs_xmit.c ++++ b/net/netfilter/ipvs/ip_vs_xmit.c +@@ -339,7 +339,7 @@ __ip_vs_get_out_rt(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb, + spin_unlock_bh(&dest->dst_lock); + IP_VS_DBG(10, "new dst %pI4, src %pI4, refcnt=%d\n", + &dest->addr.ip, &dest_dst->dst_saddr.ip, +- atomic_read(&rt->dst.__refcnt)); ++ rcuref_read(&rt->dst.__rcuref)); + } + if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.ip; +@@ -507,7 +507,7 @@ __ip_vs_get_out_rt_v6(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb, + spin_unlock_bh(&dest->dst_lock); + IP_VS_DBG(10, "new dst %pI6, src %pI6, refcnt=%d\n", + &dest->addr.in6, &dest_dst->dst_saddr.in6, +- atomic_read(&rt->dst.__refcnt)); ++ rcuref_read(&rt->dst.__rcuref)); + } + if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.in6; diff --git a/scripts/Makefile.vmlinux_o b/scripts/Makefile.vmlinux_o index 0edfdb40364b..ae52d3b3f063 100644 --- a/scripts/Makefile.vmlinux_o @@ -8848,6 +13285,45 @@ index 0edfdb40364b..ae52d3b3f063 100644 targets := .tmp_initcalls.lds +diff --git a/scripts/atomic/atomics.tbl b/scripts/atomic/atomics.tbl +index fbee2f6190d9..85ca8d9b5c27 100644 +--- a/scripts/atomic/atomics.tbl ++++ b/scripts/atomic/atomics.tbl +@@ -33,7 +33,7 @@ try_cmpxchg B v p:old i:new + sub_and_test b i v + dec_and_test b v + inc_and_test b v +-add_negative b i v ++add_negative B i v + add_unless fb v i:a i:u + inc_not_zero b v + inc_unless_negative b v +diff --git a/scripts/atomic/fallbacks/add_negative b/scripts/atomic/fallbacks/add_negative +index 15caa2eb2371..e5980abf5904 100755 +--- a/scripts/atomic/fallbacks/add_negative ++++ b/scripts/atomic/fallbacks/add_negative +@@ -1,16 +1,15 @@ + cat < -Date: Mon, 6 Mar 2023 18:45:25 +0100 -Subject: [PATCH 05/10] Implement amd-pstate guided driver +Date: Mon, 17 Apr 2023 18:32:06 +0200 +Subject: [PATCH 05/12] Implement amd-pstate guided driver Signed-off-by: Peter Jung --- .../admin-guide/kernel-parameters.txt | 40 ++-- Documentation/admin-guide/pm/amd-pstate.rst | 31 ++- - drivers/acpi/cppc_acpi.c | 121 +++++++++++- - drivers/cpufreq/amd-pstate.c | 177 +++++++++++++----- - include/acpi/cppc_acpi.h | 11 ++ + drivers/acpi/cppc_acpi.c | 121 ++++++++++- + drivers/cpufreq/amd-pstate.c | 199 ++++++++++++------ + include/acpi/cppc_acpi.h | 11 + include/linux/amd-pstate.h | 2 + - 6 files changed, 302 insertions(+), 80 deletions(-) + 6 files changed, 312 insertions(+), 92 deletions(-) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt -index 4f6761a93715..bf2a402af231 100644 +index 736233f95d59..cb4d7e74c71a 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -339,6 +339,29 @@ @@ -9065,7 +13541,7 @@ index 4f6761a93715..bf2a402af231 100644 amijoy.map= [HW,JOY] Amiga joystick support Map of devices attached to JOY0DAT and JOY1DAT Format: , -@@ -7068,20 +7091,3 @@ +@@ -7074,20 +7097,3 @@ xmon commands. off xmon is disabled. @@ -9312,10 +13788,18 @@ index c51d3ccb4cca..02a4bfb54967 100644 /* Update only if there are pending write commands */ if (pcc_ss_data->pending_pcc_write_cmd) diff --git a/drivers/cpufreq/amd-pstate.c b/drivers/cpufreq/amd-pstate.c -index 73c7643b2697..7955cfc91c31 100644 +index 8dd46fad151e..5a3d4aa0f45a 100644 --- a/drivers/cpufreq/amd-pstate.c +++ b/drivers/cpufreq/amd-pstate.c -@@ -106,6 +106,8 @@ static unsigned int epp_values[] = { +@@ -63,7 +63,6 @@ static struct cpufreq_driver *current_pstate_driver; + static struct cpufreq_driver amd_pstate_driver; + static struct cpufreq_driver amd_pstate_epp_driver; + static int cppc_state = AMD_PSTATE_DISABLE; +-struct kobject *amd_pstate_kobj; + + /* + * AMD Energy Preference Performance (EPP) +@@ -106,6 +105,8 @@ static unsigned int epp_values[] = { [EPP_INDEX_POWERSAVE] = AMD_CPPC_EPP_POWERSAVE, }; @@ -9324,7 +13808,7 @@ index 73c7643b2697..7955cfc91c31 100644 static inline int get_mode_idx_from_str(const char *str, size_t size) { int i; -@@ -308,7 +310,22 @@ static int cppc_init_perf(struct amd_cpudata *cpudata) +@@ -308,7 +309,22 @@ static int cppc_init_perf(struct amd_cpudata *cpudata) cppc_perf.lowest_nonlinear_perf); WRITE_ONCE(cpudata->lowest_perf, cppc_perf.lowest_perf); @@ -9348,7 +13832,7 @@ index 73c7643b2697..7955cfc91c31 100644 } DEFINE_STATIC_CALL(amd_pstate_init_perf, pstate_init_perf); -@@ -385,12 +402,18 @@ static inline bool amd_pstate_sample(struct amd_cpudata *cpudata) +@@ -385,12 +401,18 @@ static inline bool amd_pstate_sample(struct amd_cpudata *cpudata) } static void amd_pstate_update(struct amd_cpudata *cpudata, u32 min_perf, @@ -9368,7 +13852,7 @@ index 73c7643b2697..7955cfc91c31 100644 value &= ~AMD_CPPC_MIN_PERF(~0L); value |= AMD_CPPC_MIN_PERF(min_perf); -@@ -445,7 +468,7 @@ static int amd_pstate_target(struct cpufreq_policy *policy, +@@ -445,7 +467,7 @@ static int amd_pstate_target(struct cpufreq_policy *policy, cpufreq_freq_transition_begin(policy, &freqs); amd_pstate_update(cpudata, min_perf, des_perf, @@ -9377,7 +13861,7 @@ index 73c7643b2697..7955cfc91c31 100644 cpufreq_freq_transition_end(policy, &freqs, false); return 0; -@@ -479,7 +502,8 @@ static void amd_pstate_adjust_perf(unsigned int cpu, +@@ -479,7 +501,8 @@ static void amd_pstate_adjust_perf(unsigned int cpu, if (max_perf < min_perf) max_perf = min_perf; @@ -9387,7 +13871,7 @@ index 73c7643b2697..7955cfc91c31 100644 cpufreq_cpu_put(policy); } -@@ -816,6 +840,98 @@ static ssize_t show_energy_performance_preference( +@@ -816,6 +839,98 @@ static ssize_t show_energy_performance_preference( return sysfs_emit(buf, "%s\n", energy_perf_strings[preference]); } @@ -9456,7 +13940,7 @@ index 73c7643b2697..7955cfc91c31 100644 + return 0; +} + -+cppc_mode_transition_fn mode_state_machine[AMD_PSTATE_MAX][AMD_PSTATE_MAX] = { ++static cppc_mode_transition_fn mode_state_machine[AMD_PSTATE_MAX][AMD_PSTATE_MAX] = { + [AMD_PSTATE_DISABLE] = { + [AMD_PSTATE_DISABLE] = NULL, + [AMD_PSTATE_PASSIVE] = amd_pstate_register_driver, @@ -9486,7 +13970,7 @@ index 73c7643b2697..7955cfc91c31 100644 static ssize_t amd_pstate_show_status(char *buf) { if (!current_pstate_driver) -@@ -824,57 +940,22 @@ static ssize_t amd_pstate_show_status(char *buf) +@@ -824,55 +939,22 @@ static ssize_t amd_pstate_show_status(char *buf) return sysfs_emit(buf, "%s\n", amd_pstate_mode_string[cppc_state]); } @@ -9503,27 +13987,27 @@ index 73c7643b2697..7955cfc91c31 100644 - if (size > 7 || size < 6) + if (size > strlen("passive") || size < strlen("active")) return -EINVAL; -- mode_idx = get_mode_idx_from_str(buf, size); ++ + mode_idx = get_mode_idx_from_str(buf, size); - switch(mode_idx) { - case AMD_PSTATE_DISABLE: -- if (!current_pstate_driver) -- return -EINVAL; -- if (cppc_state == AMD_PSTATE_ACTIVE) -- return -EBUSY; -- cpufreq_unregister_driver(current_pstate_driver); -- amd_pstate_driver_cleanup(); +- if (current_pstate_driver) { +- cpufreq_unregister_driver(current_pstate_driver); +- amd_pstate_driver_cleanup(); +- } - break; - case AMD_PSTATE_PASSIVE: - if (current_pstate_driver) { - if (current_pstate_driver == &amd_pstate_driver) - return 0; - cpufreq_unregister_driver(current_pstate_driver); -- cppc_state = AMD_PSTATE_PASSIVE; -- current_pstate_driver = &amd_pstate_driver; - } -+ mode_idx = get_mode_idx_from_str(buf, size); ++ if (mode_idx < 0 || mode_idx >= AMD_PSTATE_MAX) ++ return -EINVAL; +- current_pstate_driver = &amd_pstate_driver; +- cppc_state = AMD_PSTATE_PASSIVE; - ret = cpufreq_register_driver(current_pstate_driver); - break; - case AMD_PSTATE_ACTIVE: @@ -9531,27 +14015,41 @@ index 73c7643b2697..7955cfc91c31 100644 - if (current_pstate_driver == &amd_pstate_epp_driver) - return 0; - cpufreq_unregister_driver(current_pstate_driver); -- current_pstate_driver = &amd_pstate_epp_driver; -- cppc_state = AMD_PSTATE_ACTIVE; - } -+ if (mode_idx < 0 || mode_idx >= AMD_PSTATE_MAX) -+ return -EINVAL; ++ if (mode_state_machine[cppc_state][mode_idx]) ++ return mode_state_machine[cppc_state][mode_idx](mode_idx); +- current_pstate_driver = &amd_pstate_epp_driver; +- cppc_state = AMD_PSTATE_ACTIVE; - ret = cpufreq_register_driver(current_pstate_driver); - break; - default: - ret = -EINVAL; - break; - } -+ if (mode_state_machine[cppc_state][mode_idx]) -+ return mode_state_machine[cppc_state][mode_idx](mode_idx); - +- - return ret; + return 0; } static ssize_t show_status(struct kobject *kobj, -@@ -1279,7 +1360,7 @@ static int __init amd_pstate_init(void) +@@ -930,6 +1012,7 @@ static struct attribute *pstate_global_attributes[] = { + }; + + static const struct attribute_group amd_pstate_global_attr_group = { ++ .name = "amd_pstate", + .attrs = pstate_global_attributes, + }; + +@@ -1251,6 +1334,7 @@ static struct cpufreq_driver amd_pstate_epp_driver = { + + static int __init amd_pstate_init(void) + { ++ struct device *dev_root; + int ret; + + if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD) +@@ -1277,7 +1361,7 @@ static int __init amd_pstate_init(void) /* capability check */ if (boot_cpu_has(X86_FEATURE_CPPC)) { pr_debug("AMD CPPC MSR based functionality is supported\n"); @@ -9560,7 +14058,40 @@ index 73c7643b2697..7955cfc91c31 100644 current_pstate_driver->adjust_perf = amd_pstate_adjust_perf; } else { pr_debug("AMD CPPC shared memory based functionality is supported\n"); -@@ -1341,7 +1422,7 @@ static int __init amd_pstate_param(char *str) +@@ -1297,24 +1381,19 @@ static int __init amd_pstate_init(void) + if (ret) + pr_err("failed to register with return %d\n", ret); + +- amd_pstate_kobj = kobject_create_and_add("amd_pstate", &cpu_subsys.dev_root->kobj); +- if (!amd_pstate_kobj) { +- ret = -EINVAL; +- pr_err("global sysfs registration failed.\n"); +- goto kobject_free; +- } +- +- ret = sysfs_create_group(amd_pstate_kobj, &amd_pstate_global_attr_group); +- if (ret) { +- pr_err("sysfs attribute export failed with error %d.\n", ret); +- goto global_attr_free; ++ dev_root = bus_get_dev_root(&cpu_subsys); ++ if (dev_root) { ++ ret = sysfs_create_group(&dev_root->kobj, &amd_pstate_global_attr_group); ++ put_device(dev_root); ++ if (ret) { ++ pr_err("sysfs attribute export failed with error %d.\n", ret); ++ goto global_attr_free; ++ } + } + + return ret; + + global_attr_free: +- kobject_put(amd_pstate_kobj); +-kobject_free: + cpufreq_unregister_driver(current_pstate_driver); + return ret; + } +@@ -1339,7 +1418,7 @@ static int __init amd_pstate_param(char *str) if (cppc_state == AMD_PSTATE_ACTIVE) current_pstate_driver = &amd_pstate_epp_driver; @@ -9628,10 +14159,10 @@ index f5f22418e64b..c10ebf8c42e6 100644 -- 2.40.0 -From 3c01171fc23cece3cf05ed3380e25fa10cd3393d Mon Sep 17 00:00:00 2001 +From 084a88d4285810ecceb5d51050b8bfeab4040146 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:22:26 +0200 -Subject: [PATCH 06/10] ksm +Date: Mon, 17 Apr 2023 18:28:52 +0200 +Subject: [PATCH 06/12] ksm Signed-off-by: Peter Jung --- @@ -10128,19 +14659,20 @@ index 340125d08c03..36e756355f04 100644 -- 2.40.0 -From d349cbde64499039351b1bb146999948a1319b71 Mon Sep 17 00:00:00 2001 +From 47cb984518eba210942d062aed420d30b0879b2b Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:24:33 +0200 -Subject: [PATCH 07/10] maple-lru +Date: Mon, 24 Apr 2023 12:49:39 +0200 +Subject: [PATCH 07/12] maple-lru Signed-off-by: Peter Jung --- - Documentation/mm/multigen_lru.rst | 44 +++++++++++++++++++++++--- - include/linux/mmzone.h | 2 +- - lib/maple_tree.c | 51 ++++++------------------------- - mm/vmscan.c | 24 ++++++--------- - tools/testing/radix-tree/maple.c | 24 +++++++++++++++ - 5 files changed, 84 insertions(+), 61 deletions(-) + Documentation/mm/multigen_lru.rst | 44 ++++++++-- + include/linux/mmzone.h | 10 +-- + lib/maple_tree.c | 78 ++++++----------- + lib/test_maple_tree.c | 27 ++++-- + mm/vmscan.c | 136 +++++++++++------------------- + tools/testing/radix-tree/maple.c | 24 ++++++ + 6 files changed, 163 insertions(+), 156 deletions(-) diff --git a/Documentation/mm/multigen_lru.rst b/Documentation/mm/multigen_lru.rst index 5f1f6ecbb79b..52ed5092022f 100644 @@ -10226,10 +14758,31 @@ index 5f1f6ecbb79b..52ed5092022f 100644 The aging and the eviction form a producer-consumer model; specifically, the latter drives the former by the sliding window over diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h -index 9fb1b03b83b2..bf8786d45b31 100644 +index 9fb1b03b83b2..cabe7f51ea66 100644 --- a/include/linux/mmzone.h +++ b/include/linux/mmzone.h -@@ -1369,7 +1369,7 @@ typedef struct pglist_data { +@@ -453,18 +453,14 @@ enum { + struct lru_gen_mm_state { + /* set to max_seq after each iteration */ + unsigned long seq; +- /* where the current iteration continues (inclusive) */ ++ /* where the current iteration continues after */ + struct list_head *head; +- /* where the last iteration ended (exclusive) */ ++ /* where the last iteration ended before */ + struct list_head *tail; +- /* to wait for the last page table walker to finish */ +- struct wait_queue_head wait; + /* Bloom filters flip after each iteration */ + unsigned long *filters[NR_BLOOM_FILTERS]; + /* the mm stats for debugging */ + unsigned long stats[NR_HIST_GENS][NR_MM_STATS]; +- /* the number of concurrent page table walkers */ +- int nr_walkers; + }; + + struct lru_gen_mm_walk { +@@ -1369,7 +1365,7 @@ typedef struct pglist_data { #ifdef CONFIG_LRU_GEN /* kswap mm walk data */ @@ -10239,41 +14792,10 @@ index 9fb1b03b83b2..bf8786d45b31 100644 struct lru_gen_memcg memcg_lru; #endif diff --git a/lib/maple_tree.c b/lib/maple_tree.c -index db60edb55f2f..4df6a0ce1c1b 100644 +index 1281a40d5735..110a36479dce 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c -@@ -1303,26 +1303,18 @@ static inline void mas_alloc_nodes(struct ma_state *mas, gfp_t gfp) - node = mas->alloc; - node->request_count = 0; - while (requested) { -- max_req = MAPLE_ALLOC_SLOTS; -- if (node->node_count) { -- unsigned int offset = node->node_count; -- -- slots = (void **)&node->slot[offset]; -- max_req -= offset; -- } else { -- slots = (void **)&node->slot; -- } -- -+ max_req = MAPLE_ALLOC_SLOTS - node->node_count; -+ slots = (void **)&node->slot[node->node_count]; - max_req = min(requested, max_req); - count = mt_alloc_bulk(gfp, max_req, slots); - if (!count) - goto nomem_bulk; - -+ if (node->node_count == 0) -+ node->slot[0]->node_count = 0; - node->node_count += count; - allocated += count; - node = node->slot[0]; -- node->node_count = 0; -- node->request_count = 0; - requested -= count; - } - mas->alloc->total = allocated; -@@ -2317,9 +2309,7 @@ static inline struct maple_enode *mte_node_or_none(struct maple_enode *enode) +@@ -2312,9 +2312,7 @@ static inline struct maple_enode *mte_node_or_none(struct maple_enode *enode) static inline void mas_wr_node_walk(struct ma_wr_state *wr_mas) { struct ma_state *mas = wr_mas->mas; @@ -10284,7 +14806,7 @@ index db60edb55f2f..4df6a0ce1c1b 100644 if (unlikely(ma_is_dense(wr_mas->type))) { wr_mas->r_max = wr_mas->r_min = mas->index; -@@ -2332,34 +2322,12 @@ static inline void mas_wr_node_walk(struct ma_wr_state *wr_mas) +@@ -2327,34 +2325,12 @@ static inline void mas_wr_node_walk(struct ma_wr_state *wr_mas) count = wr_mas->node_end = ma_data_end(wr_mas->node, wr_mas->type, wr_mas->pivots, mas->max); offset = mas->offset; @@ -10299,7 +14821,7 @@ index db60edb55f2f..4df6a0ce1c1b 100644 - - if (unlikely(!max && offset)) - goto max; - +- - min = max + 1; - while (++offset < count) { - max = wr_mas->pivots[offset]; @@ -10307,12 +14829,12 @@ index db60edb55f2f..4df6a0ce1c1b 100644 - goto done; - else if (unlikely(!max)) - break; -+ while (offset < count && mas->index > wr_mas->pivots[offset]) -+ offset++; - min = max + 1; - } -- ++ while (offset < count && mas->index > wr_mas->pivots[offset]) ++ offset++; + -max: - max = mas->max; -done: @@ -10323,7 +14845,84 @@ index db60edb55f2f..4df6a0ce1c1b 100644 wr_mas->offset_end = mas->offset = offset; } -@@ -5819,6 +5787,7 @@ int mas_preallocate(struct ma_state *mas, gfp_t gfp) +@@ -3282,7 +3258,7 @@ static inline void mas_destroy_rebalance(struct ma_state *mas, unsigned char end + + if (tmp < max_p) + memset(pivs + tmp, 0, +- sizeof(unsigned long *) * (max_p - tmp)); ++ sizeof(unsigned long) * (max_p - tmp)); + + if (tmp < mt_slots[mt]) + memset(slots + tmp, 0, sizeof(void *) * (max_s - tmp)); +@@ -5274,25 +5250,28 @@ static inline void mas_fill_gap(struct ma_state *mas, void *entry, + * @size: The size of the gap + * @fwd: Searching forward or back + */ +-static inline void mas_sparse_area(struct ma_state *mas, unsigned long min, ++static inline int mas_sparse_area(struct ma_state *mas, unsigned long min, + unsigned long max, unsigned long size, bool fwd) + { +- unsigned long start = 0; +- +- if (!unlikely(mas_is_none(mas))) +- start++; ++ if (!unlikely(mas_is_none(mas)) && min == 0) { ++ min++; ++ /* ++ * At this time, min is increased, we need to recheck whether ++ * the size is satisfied. ++ */ ++ if (min > max || max - min + 1 < size) ++ return -EBUSY; ++ } + /* mas_is_ptr */ + +- if (start < min) +- start = min; +- + if (fwd) { +- mas->index = start; +- mas->last = start + size - 1; +- return; ++ mas->index = min; ++ mas->last = min + size - 1; ++ } else { ++ mas->last = max; ++ mas->index = max - size + 1; + } +- +- mas->index = max; ++ return 0; + } + + /* +@@ -5321,10 +5300,8 @@ int mas_empty_area(struct ma_state *mas, unsigned long min, + return -EBUSY; + + /* Empty set */ +- if (mas_is_none(mas) || mas_is_ptr(mas)) { +- mas_sparse_area(mas, min, max, size, true); +- return 0; +- } ++ if (mas_is_none(mas) || mas_is_ptr(mas)) ++ return mas_sparse_area(mas, min, max, size, true); + + /* The start of the window can only be within these values */ + mas->index = min; +@@ -5380,10 +5357,8 @@ int mas_empty_area_rev(struct ma_state *mas, unsigned long min, + } + + /* Empty set. */ +- if (mas_is_none(mas) || mas_is_ptr(mas)) { +- mas_sparse_area(mas, min, max, size, false); +- return 0; +- } ++ if (mas_is_none(mas) || mas_is_ptr(mas)) ++ return mas_sparse_area(mas, min, max, size, false); + + /* The start of the window can only be within these values. */ + mas->index = min; +@@ -5815,6 +5790,7 @@ int mas_preallocate(struct ma_state *mas, gfp_t gfp) mas_reset(mas); return ret; } @@ -10331,11 +14930,219 @@ index db60edb55f2f..4df6a0ce1c1b 100644 /* * mas_destroy() - destroy a maple state. +diff --git a/lib/test_maple_tree.c b/lib/test_maple_tree.c +index f1db333270e9..4d85d04b26f8 100644 +--- a/lib/test_maple_tree.c ++++ b/lib/test_maple_tree.c +@@ -102,7 +102,7 @@ static noinline void check_mtree_alloc_rrange(struct maple_tree *mt, + unsigned long result = expected + 1; + int ret; + +- ret = mtree_alloc_rrange(mt, &result, ptr, size, start, end - 1, ++ ret = mtree_alloc_rrange(mt, &result, ptr, size, start, end, + GFP_KERNEL); + MT_BUG_ON(mt, ret != eret); + if (ret) +@@ -680,7 +680,7 @@ static noinline void check_alloc_rev_range(struct maple_tree *mt) + 0, /* Return value success. */ + + 0x0, /* Min */ +- 0x565234AF1 << 12, /* Max */ ++ 0x565234AF0 << 12, /* Max */ + 0x3000, /* Size */ + 0x565234AEE << 12, /* max - 3. */ + 0, /* Return value success. */ +@@ -692,14 +692,14 @@ static noinline void check_alloc_rev_range(struct maple_tree *mt) + 0, /* Return value success. */ + + 0x0, /* Min */ +- 0x7F36D510A << 12, /* Max */ ++ 0x7F36D5109 << 12, /* Max */ + 0x4000, /* Size */ + 0x7F36D5106 << 12, /* First rev hole of size 0x4000 */ + 0, /* Return value success. */ + + /* Ascend test. */ + 0x0, +- 34148798629 << 12, ++ 34148798628 << 12, + 19 << 12, + 34148797418 << 12, + 0x0, +@@ -711,6 +711,12 @@ static noinline void check_alloc_rev_range(struct maple_tree *mt) + 0x0, + -EBUSY, + ++ /* Single space test. */ ++ 34148798725 << 12, ++ 34148798725 << 12, ++ 1 << 12, ++ 34148798725 << 12, ++ 0, + }; + + int i, range_count = ARRAY_SIZE(range); +@@ -759,9 +765,9 @@ static noinline void check_alloc_rev_range(struct maple_tree *mt) + mas_unlock(&mas); + for (i = 0; i < req_range_count; i += 5) { + #if DEBUG_REV_RANGE +- pr_debug("\tReverse request between %lu-%lu size %lu, should get %lu\n", +- req_range[i] >> 12, +- (req_range[i + 1] >> 12) - 1, ++ pr_debug("\tReverse request %d between %lu-%lu size %lu, should get %lu\n", ++ i, req_range[i] >> 12, ++ (req_range[i + 1] >> 12), + req_range[i+2] >> 12, + req_range[i+3] >> 12); + #endif +@@ -880,6 +886,13 @@ static noinline void check_alloc_range(struct maple_tree *mt) + 4503599618982063UL << 12, /* Size */ + 34359052178 << 12, /* Expected location */ + -EBUSY, /* Return failure. */ ++ ++ /* Test a single entry */ ++ 34148798648 << 12, /* Min */ ++ 34148798648 << 12, /* Max */ ++ 4096, /* Size of 1 */ ++ 34148798648 << 12, /* Location is the same as min/max */ ++ 0, /* Success */ + }; + int i, range_count = ARRAY_SIZE(range); + int req_range_count = ARRAY_SIZE(req_range); diff --git a/mm/vmscan.c b/mm/vmscan.c -index 71a7f4517e5a..8dadd1772661 100644 +index 71a7f4517e5a..ae60ddff831a 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c -@@ -3608,7 +3608,7 @@ static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq) +@@ -3398,18 +3398,13 @@ void lru_gen_del_mm(struct mm_struct *mm) + for_each_node(nid) { + struct lruvec *lruvec = get_lruvec(memcg, nid); + +- /* where the last iteration ended (exclusive) */ ++ /* where the current iteration continues after */ ++ if (lruvec->mm_state.head == &mm->lru_gen.list) ++ lruvec->mm_state.head = lruvec->mm_state.head->prev; ++ ++ /* where the last iteration ended before */ + if (lruvec->mm_state.tail == &mm->lru_gen.list) + lruvec->mm_state.tail = lruvec->mm_state.tail->next; +- +- /* where the current iteration continues (inclusive) */ +- if (lruvec->mm_state.head != &mm->lru_gen.list) +- continue; +- +- lruvec->mm_state.head = lruvec->mm_state.head->next; +- /* the deletion ends the current iteration */ +- if (lruvec->mm_state.head == &mm_list->fifo) +- WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1); + } + + list_del_init(&mm->lru_gen.list); +@@ -3505,68 +3500,54 @@ static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, + struct mm_struct **iter) + { + bool first = false; +- bool last = true; ++ bool last = false; + struct mm_struct *mm = NULL; + struct mem_cgroup *memcg = lruvec_memcg(lruvec); + struct lru_gen_mm_list *mm_list = get_mm_list(memcg); + struct lru_gen_mm_state *mm_state = &lruvec->mm_state; + + /* +- * There are four interesting cases for this page table walker: +- * 1. It tries to start a new iteration of mm_list with a stale max_seq; +- * there is nothing left to do. +- * 2. It's the first of the current generation, and it needs to reset +- * the Bloom filter for the next generation. +- * 3. It reaches the end of mm_list, and it needs to increment +- * mm_state->seq; the iteration is done. +- * 4. It's the last of the current generation, and it needs to reset the +- * mm stats counters for the next generation. ++ * mm_state->seq is incremented after each iteration of mm_list. There ++ * are three interesting cases for this page table walker: ++ * 1. It tries to start a new iteration with a stale max_seq: there is ++ * nothing left to do. ++ * 2. It started the next iteration: it needs to reset the Bloom filter ++ * so that a fresh set of PTE tables can be recorded. ++ * 3. It ended the current iteration: it needs to reset the mm stats ++ * counters and tell its caller to increment max_seq. + */ + spin_lock(&mm_list->lock); + + VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq); +- VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq); +- VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers); + +- if (walk->max_seq <= mm_state->seq) { +- if (!*iter) +- last = false; ++ if (walk->max_seq <= mm_state->seq) + goto done; +- } + +- if (!mm_state->nr_walkers) { +- VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo); ++ if (!mm_state->head) ++ mm_state->head = &mm_list->fifo; + +- mm_state->head = mm_list->fifo.next; ++ if (mm_state->head == &mm_list->fifo) + first = true; +- } +- +- while (!mm && mm_state->head != &mm_list->fifo) { +- mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list); + ++ do { + mm_state->head = mm_state->head->next; ++ if (mm_state->head == &mm_list->fifo) { ++ WRITE_ONCE(mm_state->seq, mm_state->seq + 1); ++ last = true; ++ break; ++ } + + /* force scan for those added after the last iteration */ +- if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) { +- mm_state->tail = mm_state->head; ++ if (!mm_state->tail || mm_state->tail == mm_state->head) { ++ mm_state->tail = mm_state->head->next; + walk->force_scan = true; + } + ++ mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list); + if (should_skip_mm(mm, walk)) + mm = NULL; +- } +- +- if (mm_state->head == &mm_list->fifo) +- WRITE_ONCE(mm_state->seq, mm_state->seq + 1); ++ } while (!mm); + done: +- if (*iter && !mm) +- mm_state->nr_walkers--; +- if (!*iter && mm) +- mm_state->nr_walkers++; +- +- if (mm_state->nr_walkers) +- last = false; +- + if (*iter || last) + reset_mm_stats(lruvec, walk, last); + +@@ -3594,9 +3575,9 @@ static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq) + + VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq); + +- if (max_seq > mm_state->seq && !mm_state->nr_walkers) { +- VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo); +- ++ if (max_seq > mm_state->seq) { ++ mm_state->head = NULL; ++ mm_state->tail = NULL; + WRITE_ONCE(mm_state->seq, mm_state->seq + 1); + reset_mm_stats(lruvec, NULL, true); + success = true; +@@ -3608,7 +3589,7 @@ static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq) } /****************************************************************************** @@ -10344,7 +15151,62 @@ index 71a7f4517e5a..8dadd1772661 100644 ******************************************************************************/ /* -@@ -5671,14 +5671,14 @@ static void lru_gen_change_state(bool enabled) +@@ -4196,10 +4177,6 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end, + + walk_pmd_range(&val, addr, next, args); + +- /* a racy check to curtail the waiting time */ +- if (wq_has_sleeper(&walk->lruvec->mm_state.wait)) +- return 1; +- + if (need_resched() || walk->batched >= MAX_LRU_BATCH) { + end = (addr | ~PUD_MASK) + 1; + goto done; +@@ -4232,8 +4209,14 @@ static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_ + walk->next_addr = FIRST_USER_ADDRESS; + + do { ++ DEFINE_MAX_SEQ(lruvec); ++ + err = -EBUSY; + ++ /* another thread might have called inc_max_seq() */ ++ if (walk->max_seq != max_seq) ++ break; ++ + /* folio_update_gen() requires stable folio_memcg() */ + if (!mem_cgroup_trylock_pages(memcg)) + break; +@@ -4466,25 +4449,12 @@ static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq, + success = iterate_mm_list(lruvec, walk, &mm); + if (mm) + walk_mm(lruvec, mm, walk); +- +- cond_resched(); + } while (mm); + done: +- if (!success) { +- if (sc->priority <= DEF_PRIORITY - 2) +- wait_event_killable(lruvec->mm_state.wait, +- max_seq < READ_ONCE(lrugen->max_seq)); +- return false; +- } +- +- VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq)); ++ if (success) ++ inc_max_seq(lruvec, can_swap, force_scan); + +- inc_max_seq(lruvec, can_swap, force_scan); +- /* either this sees any waiters or they will see updated max_seq */ +- if (wq_has_sleeper(&lruvec->mm_state.wait)) +- wake_up_all(&lruvec->mm_state.wait); +- +- return true; ++ return success; + } + + /****************************************************************************** +@@ -5671,14 +5641,14 @@ static void lru_gen_change_state(bool enabled) * sysfs interface ******************************************************************************/ @@ -10363,7 +15225,7 @@ index 71a7f4517e5a..8dadd1772661 100644 { unsigned int msecs; -@@ -5690,11 +5690,9 @@ static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, +@@ -5690,11 +5660,9 @@ static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, return len; } @@ -10377,7 +15239,7 @@ index 71a7f4517e5a..8dadd1772661 100644 { unsigned int caps = 0; -@@ -5711,7 +5709,7 @@ static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, c +@@ -5711,7 +5679,7 @@ static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, c } /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ @@ -10386,7 +15248,7 @@ index 71a7f4517e5a..8dadd1772661 100644 const char *buf, size_t len) { int i; -@@ -5738,9 +5736,7 @@ static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr, +@@ -5738,9 +5706,7 @@ static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr, return len; } @@ -10397,7 +15259,7 @@ index 71a7f4517e5a..8dadd1772661 100644 static struct attribute *lru_gen_attrs[] = { &lru_gen_min_ttl_attr.attr, -@@ -5748,7 +5744,7 @@ static struct attribute *lru_gen_attrs[] = { +@@ -5748,7 +5714,7 @@ static struct attribute *lru_gen_attrs[] = { NULL }; @@ -10406,6 +15268,22 @@ index 71a7f4517e5a..8dadd1772661 100644 .name = "lru_gen", .attrs = lru_gen_attrs, }; +@@ -6130,7 +6096,6 @@ void lru_gen_init_lruvec(struct lruvec *lruvec) + INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]); + + lruvec->mm_state.seq = MIN_NR_GENS; +- init_waitqueue_head(&lruvec->mm_state.wait); + } + + #ifdef CONFIG_MEMCG +@@ -6163,7 +6128,6 @@ void lru_gen_exit_memcg(struct mem_cgroup *memcg) + for_each_node(nid) { + struct lruvec *lruvec = get_lruvec(memcg, nid); + +- VM_WARN_ON_ONCE(lruvec->mm_state.nr_walkers); + VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0, + sizeof(lruvec->lrugen.nr_pages))); + diff --git a/tools/testing/radix-tree/maple.c b/tools/testing/radix-tree/maple.c index 4c89ff333f6f..9286d3baa12d 100644 --- a/tools/testing/radix-tree/maple.c @@ -10451,10 +15329,10 @@ index 4c89ff333f6f..9286d3baa12d 100644 -- 2.40.0 -From c9249daec15495e2d4e2a0519e75421784e31ddc Mon Sep 17 00:00:00 2001 +From f95bdd28880e60795bc28ad055c0ba90a634ad44 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:25:25 +0200 -Subject: [PATCH 08/10] Per-VMA locks +Date: Mon, 24 Apr 2023 12:50:36 +0200 +Subject: [PATCH 08/12] Per-VMA locks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @@ -10643,40 +15521,41 @@ Suren Baghdasaryan (23): Signed-off-by: Peter Jung --- - Documentation/admin-guide/mm/userfaultfd.rst | 17 +++ + Documentation/admin-guide/mm/userfaultfd.rst | 17 ++ arch/arm64/Kconfig | 1 + - arch/arm64/mm/fault.c | 36 +++++ - arch/powerpc/mm/fault.c | 37 +++++ + arch/arm64/mm/fault.c | 36 ++++ + arch/powerpc/mm/fault.c | 37 ++++ arch/powerpc/platforms/powernv/Kconfig | 1 + arch/powerpc/platforms/pseries/Kconfig | 1 + arch/s390/Kconfig | 1 + arch/s390/mm/fault.c | 24 +++ arch/x86/Kconfig | 1 + - arch/x86/mm/fault.c | 36 +++++ + arch/x86/mm/fault.c | 36 ++++ fs/userfaultfd.c | 16 ++ - include/linux/mm.h | 127 +++++++++++++++- + include/linux/mm.h | 127 ++++++++++++- include/linux/mm_inline.h | 6 + - include/linux/mm_types.h | 30 +++- - include/linux/mmap_lock.h | 37 +++-- + include/linux/mm_types.h | 30 ++- + include/linux/mmap_lock.h | 37 ++-- include/linux/userfaultfd_k.h | 23 +++ include/linux/vm_event_item.h | 6 + include/linux/vmstat.h | 6 + include/uapi/linux/userfaultfd.h | 10 +- - kernel/fork.c | 96 ++++++++++-- + kernel/fork.c | 96 ++++++++-- mm/Kconfig | 12 ++ mm/Kconfig.debug | 6 + + mm/filemap.c | 6 + mm/hugetlb.c | 4 + mm/init-mm.c | 3 + mm/internal.h | 2 +- mm/khugepaged.c | 10 +- - mm/memory.c | 146 ++++++++++++++++--- - mm/mmap.c | 48 ++++-- - mm/mprotect.c | 51 +++++-- + mm/memory.c | 187 +++++++++++++++---- + mm/mmap.c | 48 +++-- + mm/mprotect.c | 51 ++++- mm/mremap.c | 1 + - mm/rmap.c | 31 ++-- + mm/rmap.c | 31 +-- mm/vmstat.c | 6 + - tools/testing/selftests/mm/userfaultfd.c | 45 +++++- - 33 files changed, 783 insertions(+), 94 deletions(-) + tools/testing/selftests/mm/userfaultfd.c | 45 ++++- + 34 files changed, 811 insertions(+), 113 deletions(-) diff --git a/Documentation/admin-guide/mm/userfaultfd.rst b/Documentation/admin-guide/mm/userfaultfd.rst index 7dc823b56ca4..bd2226299583 100644 @@ -10979,7 +15858,7 @@ index a498ae1fbe66..e4399983c50c 100644 return; diff --git a/fs/userfaultfd.c b/fs/userfaultfd.c -index 44d1ee429eb0..881e9c82b9d1 100644 +index 40f9e1a2ebdd..7cecde5026dd 100644 --- a/fs/userfaultfd.c +++ b/fs/userfaultfd.c @@ -108,6 +108,21 @@ static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx) @@ -11004,7 +15883,7 @@ index 44d1ee429eb0..881e9c82b9d1 100644 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma, vm_flags_t flags) { -@@ -1971,6 +1986,7 @@ static int userfaultfd_api(struct userfaultfd_ctx *ctx, +@@ -1973,6 +1988,7 @@ static int userfaultfd_api(struct userfaultfd_ctx *ctx, #endif #ifndef CONFIG_PTE_MARKER_UFFD_WP uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM; @@ -11477,7 +16356,7 @@ index 005e5e306266..90c958952bfc 100644 __u64 ioctls; diff --git a/kernel/fork.c b/kernel/fork.c -index 49c173e367d2..346ce90d1f33 100644 +index 349945168239..ebd353730887 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -455,13 +455,49 @@ static struct kmem_cache *vm_area_cachep; @@ -11608,7 +16487,7 @@ index 49c173e367d2..346ce90d1f33 100644 mm_pgtables_bytes_init(mm); mm->map_count = 0; mm->locked_vm = 0; -@@ -3073,6 +3140,9 @@ void __init proc_caches_init(void) +@@ -3074,6 +3141,9 @@ void __init proc_caches_init(void) NULL); vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT); @@ -11655,6 +16534,30 @@ index c3547a373c9c..4965a7333a3f 100644 + default y + help + Statistics for per-vma locks. +diff --git a/mm/filemap.c b/mm/filemap.c +index 2723104cc06a..7d898f26755b 100644 +--- a/mm/filemap.c ++++ b/mm/filemap.c +@@ -1706,6 +1706,8 @@ static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait) + * mmap_lock has been released (mmap_read_unlock(), unless flags had both + * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in + * which case mmap_lock is still held. ++ * If flags had FAULT_FLAG_VMA_LOCK set, meaning the operation is performed ++ * with VMA lock only, the VMA lock is still held. + * + * If neither ALLOW_RETRY nor KILLABLE are set, will always return true + * with the folio locked and the mmap_lock unperturbed. +@@ -1713,6 +1715,10 @@ static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait) + bool __folio_lock_or_retry(struct folio *folio, struct mm_struct *mm, + unsigned int flags) + { ++ /* Can't do this if not holding mmap_lock */ ++ if (flags & FAULT_FLAG_VMA_LOCK) ++ return false; ++ + if (fault_flag_allow_retry_first(flags)) { + /* + * CAUTION! In this case, mmap_lock is not released diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 245038a9fe4e..4d860b53a14a 100644 --- a/mm/hugetlb.c @@ -11698,10 +16601,10 @@ index 7920a8b7982e..0c455d6e4e3e 100644 struct zap_details; diff --git a/mm/khugepaged.c b/mm/khugepaged.c -index 92e6f56a932d..042007f0bfa1 100644 +index 0ec69b96b497..624acc3f116a 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c -@@ -1049,6 +1049,7 @@ static int collapse_huge_page(struct mm_struct *mm, unsigned long address, +@@ -1053,6 +1053,7 @@ static int collapse_huge_page(struct mm_struct *mm, unsigned long address, if (result != SCAN_SUCCEED) goto out_up_write; @@ -11709,7 +16612,7 @@ index 92e6f56a932d..042007f0bfa1 100644 anon_vma_lock_write(vma->anon_vma); mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address, -@@ -1172,7 +1173,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, +@@ -1176,7 +1177,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, * enabled swap entries. Please see * comment below for pte_uffd_wp(). */ @@ -11718,7 +16621,7 @@ index 92e6f56a932d..042007f0bfa1 100644 result = SCAN_PTE_UFFD_WP; goto out_unmap; } -@@ -1512,6 +1513,9 @@ int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, +@@ -1516,6 +1517,9 @@ int collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, goto drop_hpage; } @@ -11728,7 +16631,7 @@ index 92e6f56a932d..042007f0bfa1 100644 /* * We need to lock the mapping so that from here on, only GUP-fast and * hardware page walks can access the parts of the page tables that -@@ -1689,6 +1693,10 @@ static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff, +@@ -1693,6 +1697,10 @@ static int retract_page_tables(struct address_space *mapping, pgoff_t pgoff, result = SCAN_PTE_MAPPED_HUGEPAGE; if ((cc->is_khugepaged || is_target) && mmap_write_trylock(mm)) { @@ -11740,7 +16643,7 @@ index 92e6f56a932d..042007f0bfa1 100644 * Re-check whether we have an ->anon_vma, because * collapse_and_free_pmd() requires that either no diff --git a/mm/memory.c b/mm/memory.c -index 01a23ad48a04..e7ffdadb684d 100644 +index 01a23ad48a04..9deb0d0f3f7f 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -104,6 +104,20 @@ EXPORT_SYMBOL(mem_map); @@ -11856,19 +16759,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 } static vm_fault_t handle_pte_marker(struct vm_fault *vmf) -@@ -3698,6 +3734,11 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) - if (!pte_unmap_same(vmf)) - goto out; - -+ if (vmf->flags & FAULT_FLAG_VMA_LOCK) { -+ ret = VM_FAULT_RETRY; -+ goto out; -+ } -+ - entry = pte_to_swp_entry(vmf->orig_pte); - if (unlikely(non_swap_entry(entry))) { - if (is_migration_entry(entry)) { -@@ -4012,6 +4053,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) +@@ -4012,6 +4048,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) */ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) { @@ -11876,7 +16767,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 struct vm_area_struct *vma = vmf->vma; struct folio *folio; vm_fault_t ret = 0; -@@ -4045,7 +4087,7 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) +@@ -4045,7 +4082,7 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) vma->vm_page_prot)); vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, &vmf->ptl); @@ -11885,7 +16776,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 update_mmu_tlb(vma, vmf->address, vmf->pte); goto unlock; } -@@ -4085,7 +4127,7 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) +@@ -4085,7 +4122,7 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address, &vmf->ptl); @@ -11894,7 +16785,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 update_mmu_tlb(vma, vmf->address, vmf->pte); goto release; } -@@ -4105,6 +4147,8 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) +@@ -4105,6 +4142,8 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) folio_add_new_anon_rmap(folio, vma, vmf->address); folio_add_lru_vma(folio, vma); setpte: @@ -11903,7 +16794,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry); /* No need to invalidate - it was non-present before */ -@@ -4272,7 +4316,7 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) +@@ -4272,7 +4311,7 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page) void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr) { struct vm_area_struct *vma = vmf->vma; @@ -11912,7 +16803,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 bool write = vmf->flags & FAULT_FLAG_WRITE; bool prefault = vmf->address != addr; pte_t entry; -@@ -4503,6 +4547,8 @@ static vm_fault_t do_read_fault(struct vm_fault *vmf) +@@ -4503,6 +4542,8 @@ static vm_fault_t do_read_fault(struct vm_fault *vmf) return ret; } @@ -11921,7 +16812,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 ret = __do_fault(vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) return ret; -@@ -4519,6 +4565,9 @@ static vm_fault_t do_cow_fault(struct vm_fault *vmf) +@@ -4519,6 +4560,9 @@ static vm_fault_t do_cow_fault(struct vm_fault *vmf) struct vm_area_struct *vma = vmf->vma; vm_fault_t ret; @@ -11931,7 +16822,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 if (unlikely(anon_vma_prepare(vma))) return VM_FAULT_OOM; -@@ -4558,6 +4607,9 @@ static vm_fault_t do_shared_fault(struct vm_fault *vmf) +@@ -4558,6 +4602,9 @@ static vm_fault_t do_shared_fault(struct vm_fault *vmf) struct vm_area_struct *vma = vmf->vma; vm_fault_t ret, tmp; @@ -11941,7 +16832,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 ret = __do_fault(vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) return ret; -@@ -4916,12 +4968,8 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) +@@ -4916,12 +4963,8 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) } } @@ -11956,7 +16847,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 if (!pte_present(vmf->orig_pte)) return do_swap_page(vmf); -@@ -4929,6 +4977,9 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) +@@ -4929,6 +4972,9 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma)) return do_numa_page(vmf); @@ -11966,7 +16857,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd); spin_lock(vmf->ptl); entry = vmf->orig_pte; -@@ -4965,10 +5016,10 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) +@@ -4965,10 +5011,10 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf) } /* @@ -11981,7 +16872,88 @@ index 01a23ad48a04..e7ffdadb684d 100644 */ static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma, unsigned long address, unsigned int flags) -@@ -5230,6 +5281,63 @@ vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, +@@ -5080,24 +5126,31 @@ static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma, + * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should + * still be in per-arch page fault handlers at the entry of page fault. + */ +-static inline void mm_account_fault(struct pt_regs *regs, ++static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs, + unsigned long address, unsigned int flags, + vm_fault_t ret) + { + bool major; + ++ /* Incomplete faults will be accounted upon completion. */ ++ if (ret & VM_FAULT_RETRY) ++ return; ++ + /* +- * We don't do accounting for some specific faults: +- * +- * - Unsuccessful faults (e.g. when the address wasn't valid). That +- * includes arch_vma_access_permitted() failing before reaching here. +- * So this is not a "this many hardware page faults" counter. We +- * should use the hw profiling for that. +- * +- * - Incomplete faults (VM_FAULT_RETRY). They will only be counted +- * once they're completed. ++ * To preserve the behavior of older kernels, PGFAULT counters record ++ * both successful and failed faults, as opposed to perf counters, ++ * which ignore failed cases. ++ */ ++ count_vm_event(PGFAULT); ++ count_memcg_event_mm(mm, PGFAULT); ++ ++ /* ++ * Do not account for unsuccessful faults (e.g. when the address wasn't ++ * valid). That includes arch_vma_access_permitted() failing before ++ * reaching here. So this is not a "this many hardware page faults" ++ * counter. We should use the hw profiling for that. + */ +- if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY)) ++ if (ret & VM_FAULT_ERROR) + return; + + /* +@@ -5180,21 +5233,22 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, + vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, + unsigned int flags, struct pt_regs *regs) + { ++ /* If the fault handler drops the mmap_lock, vma may be freed */ ++ struct mm_struct *mm = vma->vm_mm; + vm_fault_t ret; + + __set_current_state(TASK_RUNNING); + +- count_vm_event(PGFAULT); +- count_memcg_event_mm(vma->vm_mm, PGFAULT); +- + ret = sanitize_fault_flags(vma, &flags); + if (ret) +- return ret; ++ goto out; + + if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE, + flags & FAULT_FLAG_INSTRUCTION, +- flags & FAULT_FLAG_REMOTE)) +- return VM_FAULT_SIGSEGV; ++ flags & FAULT_FLAG_REMOTE)) { ++ ret = VM_FAULT_SIGSEGV; ++ goto out; ++ } + + /* + * Enable the memcg OOM handling for faults triggered in user +@@ -5223,13 +5277,70 @@ vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address, + if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) + mem_cgroup_oom_synchronize(false); + } +- +- mm_account_fault(regs, address, flags, ret); ++out: ++ mm_account_fault(mm, regs, address, flags, ret); + + return ret; } EXPORT_SYMBOL_GPL(handle_mm_fault); @@ -12046,7 +17018,7 @@ index 01a23ad48a04..e7ffdadb684d 100644 /* * Allocate p4d page table. diff --git a/mm/mmap.c b/mm/mmap.c -index ff68a67a2a7c..a2bc2d9432b8 100644 +index d5475fbf5729..cbac45aa39ae 100644 --- a/mm/mmap.c +++ b/mm/mmap.c @@ -133,7 +133,7 @@ void unlink_file_vma(struct vm_area_struct *vma) @@ -12132,7 +17104,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 if (vma_start < vma->vm_start || vma_end > vma->vm_end) vma_expanded = true; -@@ -2119,7 +2132,7 @@ static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas) +@@ -2157,7 +2170,7 @@ static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas) if (vma->vm_flags & VM_ACCOUNT) nr_accounted += nrpages; vm_stat_account(mm, vma->vm_flags, -nrpages); @@ -12141,7 +17113,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 } vm_unacct_memory(nr_accounted); validate_mm(mm); -@@ -2142,7 +2155,8 @@ static void unmap_region(struct mm_struct *mm, struct maple_tree *mt, +@@ -2180,7 +2193,8 @@ static void unmap_region(struct mm_struct *mm, struct maple_tree *mt, update_hiwater_rss(mm); unmap_vmas(&tlb, mt, vma, start, end, mm_wr_locked); free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS, @@ -12151,7 +17123,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 tlb_finish_mmu(&tlb); } -@@ -2198,10 +2212,10 @@ int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, +@@ -2236,10 +2250,10 @@ int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, if (new->vm_ops && new->vm_ops->open) new->vm_ops->open(new); @@ -12163,7 +17135,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 if (new_below) { vma->vm_start = addr; -@@ -2245,10 +2259,12 @@ int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, +@@ -2283,10 +2297,12 @@ int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma, static inline int munmap_sidetree(struct vm_area_struct *vma, struct ma_state *mas_detach) { @@ -12176,7 +17148,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 if (vma->vm_flags & VM_LOCKED) vma->vm_mm->locked_vm -= vma_pages(vma); -@@ -2904,9 +2920,9 @@ static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma, +@@ -2942,9 +2958,9 @@ static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma, if (vma_iter_prealloc(vmi)) goto unacct_fail; @@ -12187,7 +17159,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 vma->vm_end = addr + len; vm_flags_set(vma, VM_SOFTDIRTY); vma_iter_store(vmi, vma); -@@ -3039,7 +3055,7 @@ void exit_mmap(struct mm_struct *mm) +@@ -3077,7 +3093,7 @@ void exit_mmap(struct mm_struct *mm) mmap_write_lock(mm); mt_clear_in_rcu(&mm->mm_mt); free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS, @@ -12196,7 +17168,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 tlb_finish_mmu(&tlb); /* -@@ -3050,7 +3066,7 @@ void exit_mmap(struct mm_struct *mm) +@@ -3088,7 +3104,7 @@ void exit_mmap(struct mm_struct *mm) do { if (vma->vm_flags & VM_ACCOUNT) nr_accounted += vma_pages(vma); @@ -12205,7 +17177,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 count++; cond_resched(); } while ((vma = mas_find(&mas, ULONG_MAX)) != NULL); -@@ -3173,6 +3189,7 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap, +@@ -3211,6 +3227,7 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap, get_file(new_vma->vm_file); if (new_vma->vm_ops && new_vma->vm_ops->open) new_vma->vm_ops->open(new_vma); @@ -12213,7 +17185,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 if (vma_link(mm, new_vma)) goto out_vma_link; *need_rmap_locks = false; -@@ -3467,6 +3484,7 @@ static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping) +@@ -3505,6 +3522,7 @@ static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping) * of mm/rmap.c: * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for * hugetlb mapping); @@ -12221,7 +17193,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 * - all i_mmap_rwsem locks; * - all anon_vma->rwseml * -@@ -3489,6 +3507,13 @@ int mm_take_all_locks(struct mm_struct *mm) +@@ -3527,6 +3545,13 @@ int mm_take_all_locks(struct mm_struct *mm) mutex_lock(&mm_all_locks_mutex); @@ -12235,7 +17207,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 mas_for_each(&mas, vma, ULONG_MAX) { if (signal_pending(current)) goto out_unlock; -@@ -3578,6 +3603,7 @@ void mm_drop_all_locks(struct mm_struct *mm) +@@ -3616,6 +3641,7 @@ void mm_drop_all_locks(struct mm_struct *mm) if (vma->vm_file && vma->vm_file->f_mapping) vm_unlock_mapping(vma->vm_file->f_mapping); } @@ -12244,7 +17216,7 @@ index ff68a67a2a7c..a2bc2d9432b8 100644 mutex_unlock(&mm_all_locks_mutex); } diff --git a/mm/mprotect.c b/mm/mprotect.c -index 13e84d8c0797..b9da9a5f87fe 100644 +index 36351a00c0e8..204194155863 100644 --- a/mm/mprotect.c +++ b/mm/mprotect.c @@ -276,7 +276,15 @@ static long change_pte_range(struct mmu_gather *tlb, @@ -12487,10 +17459,10 @@ index 7f22844ed704..e030d63c031a 100644 -- 2.40.0 -From d0f327c32c39cafbdeefac5fd65a0087a603e76f Mon Sep 17 00:00:00 2001 +From 9d501d43ebbad46d54beaa5e0bb64cc27d9d3551 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:25:55 +0200 -Subject: [PATCH 09/10] sched +Date: Sat, 22 Apr 2023 11:46:01 +0200 +Subject: [PATCH 09/12] sched Signed-off-by: Peter Jung --- @@ -12498,14 +17470,17 @@ Signed-off-by: Peter Jung arch/x86/kernel/smpboot.c | 4 +- include/linux/sched.h | 3 + include/linux/sched/sd_flags.h | 5 +- + kernel/sched/clock.c | 3 + kernel/sched/core.c | 4 +- + kernel/sched/deadline.c | 1 + kernel/sched/debug.c | 1 + kernel/sched/fair.c | 265 ++++++++++++++++++++------------- kernel/sched/features.h | 1 + kernel/sched/pelt.c | 60 ++++++++ kernel/sched/pelt.h | 42 +++++- + kernel/sched/rt.c | 4 + kernel/sched/sched.h | 23 ++- - 11 files changed, 294 insertions(+), 137 deletions(-) + 14 files changed, 302 insertions(+), 137 deletions(-) diff --git a/arch/x86/kernel/itmt.c b/arch/x86/kernel/itmt.c index 9ff480e94511..6510883c5e81 100644 @@ -12603,6 +17578,20 @@ index 57bde66d95f7..fad77b5172e2 100644 /* * Prefer to place tasks in a sibling domain +diff --git a/kernel/sched/clock.c b/kernel/sched/clock.c +index 5732fa75ebab..b5cc2b53464d 100644 +--- a/kernel/sched/clock.c ++++ b/kernel/sched/clock.c +@@ -300,6 +300,9 @@ noinstr u64 local_clock(void) + if (static_branch_likely(&__sched_clock_stable)) + return sched_clock() + __sched_clock_offset; + ++ if (!static_branch_likely(&sched_clock_running)) ++ return sched_clock(); ++ + preempt_disable_notrace(); + clock = sched_clock_local(this_scd()); + preempt_enable_notrace(); diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 0d18c3969f90..17bb9637f314 100644 --- a/kernel/sched/core.c @@ -12625,6 +17614,18 @@ index 0d18c3969f90..17bb9637f314 100644 INIT_LIST_HEAD(&p->se.group_node); #ifdef CONFIG_FAIR_GROUP_SCHED +diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c +index 71b24371a6f7..ac8010f6f3a2 100644 +--- a/kernel/sched/deadline.c ++++ b/kernel/sched/deadline.c +@@ -2246,6 +2246,7 @@ static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq) + !cpumask_test_cpu(later_rq->cpu, &task->cpus_mask) || + task_on_cpu(rq, task) || + !dl_task(task) || ++ is_migration_disabled(task) || + !task_on_rq_queued(task))) { + double_unlock_balance(rq, later_rq); + later_rq = NULL; diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c index 1637b65ba07a..8d64fba16cfe 100644 --- a/kernel/sched/debug.c @@ -12638,7 +17639,7 @@ index 1637b65ba07a..8d64fba16cfe 100644 P(se.avg.load_sum); P(se.avg.runnable_sum); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index dcdd8422de72..115be8a965f2 100644 +index 96c66b50ee48..0f92281fbed9 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -1082,6 +1082,23 @@ update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) @@ -12964,7 +17965,7 @@ index dcdd8422de72..115be8a965f2 100644 if (env->sd->flags & SD_NUMA) -@@ -10387,7 +10421,10 @@ static struct sched_group *find_busiest_group(struct lb_env *env) +@@ -10397,7 +10431,10 @@ static struct sched_group *find_busiest_group(struct lb_env *env) goto out_balanced; } @@ -12976,7 +17977,7 @@ index dcdd8422de72..115be8a965f2 100644 if (sds.prefer_sibling && local->group_type == group_has_spare && busiest->sum_nr_running > local->sum_nr_running + 1) goto force_balance; -@@ -10489,8 +10526,15 @@ static struct rq *find_busiest_queue(struct lb_env *env, +@@ -10499,8 +10536,15 @@ static struct rq *find_busiest_queue(struct lb_env *env, nr_running == 1) continue; @@ -12993,7 +17994,7 @@ index dcdd8422de72..115be8a965f2 100644 sched_asym_prefer(i, env->dst_cpu) && nr_running == 1) continue; -@@ -10579,12 +10623,19 @@ static inline bool +@@ -10589,12 +10633,19 @@ static inline bool asym_active_balance(struct lb_env *env) { /* @@ -13017,7 +18018,7 @@ index dcdd8422de72..115be8a965f2 100644 } static inline bool -@@ -11318,9 +11369,13 @@ static void nohz_balancer_kick(struct rq *rq) +@@ -11328,9 +11379,13 @@ static void nohz_balancer_kick(struct rq *rq) * When ASYM_PACKING; see if there's a more preferred CPU * currently idle; in which case, kick the ILB to move tasks * around. @@ -13198,6 +18199,26 @@ index 3a0e0dc28721..9b35b5072bae 100644 static inline void update_idle_rq_clock_pelt(struct rq *rq) { } +diff --git a/kernel/sched/rt.c b/kernel/sched/rt.c +index 0a11f44adee5..4f5796dd26a5 100644 +--- a/kernel/sched/rt.c ++++ b/kernel/sched/rt.c +@@ -2000,11 +2000,15 @@ static struct rq *find_lock_lowest_rq(struct task_struct *task, struct rq *rq) + * the mean time, task could have + * migrated already or had its affinity changed. + * Also make sure that it wasn't scheduled on its rq. ++ * It is possible the task was scheduled, set ++ * "migrate_disabled" and then got preempted, so we must ++ * check the task migration disable flag here too. + */ + if (unlikely(task_rq(task) != rq || + !cpumask_test_cpu(lowest_rq->cpu, &task->cpus_mask) || + task_on_cpu(rq, task) || + !rt_task(task) || ++ is_migration_disabled(task) || + !task_on_rq_queued(task))) { + + double_unlock_balance(rq, lowest_rq); diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 3e8df6d31c1e..7331d436ebc4 100644 --- a/kernel/sched/sched.h @@ -13256,10 +18277,6313 @@ index 3e8df6d31c1e..7331d436ebc4 100644 -- 2.40.0 -From 6c867f735d5efe4f7df3cc9cf96dc0928914c438 Mon Sep 17 00:00:00 2001 +From 08f22b408defdf8a20d03f43c3432ba21547095b Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:26:12 +0200 -Subject: [PATCH 10/10] zstd +Date: Sat, 22 Apr 2023 11:46:19 +0200 +Subject: [PATCH 10/12] Surface + +Signed-off-by: Peter Jung +--- + arch/x86/kernel/acpi/boot.c | 24 + + drivers/acpi/acpi_tad.c | 35 +- + drivers/bluetooth/btusb.c | 15 + + drivers/hid/Kconfig | 4 + + drivers/hid/Makefile | 3 + + drivers/hid/hid-multitouch.c | 196 ++++++- + drivers/hid/ipts/Kconfig | 14 + + drivers/hid/ipts/Makefile | 14 + + drivers/hid/ipts/cmd.c | 62 ++ + drivers/hid/ipts/cmd.h | 61 ++ + drivers/hid/ipts/context.h | 51 ++ + drivers/hid/ipts/control.c | 495 ++++++++++++++++ + drivers/hid/ipts/control.h | 127 +++++ + drivers/hid/ipts/desc.h | 81 +++ + drivers/hid/ipts/hid.c | 348 ++++++++++++ + drivers/hid/ipts/hid.h | 22 + + drivers/hid/ipts/main.c | 127 +++++ + drivers/hid/ipts/mei.c | 189 +++++++ + drivers/hid/ipts/mei.h | 67 +++ + drivers/hid/ipts/receiver.c | 249 ++++++++ + drivers/hid/ipts/receiver.h | 17 + + drivers/hid/ipts/resources.c | 108 ++++ + drivers/hid/ipts/resources.h | 39 ++ + drivers/hid/ipts/spec-data.h | 100 ++++ + drivers/hid/ipts/spec-device.h | 285 ++++++++++ + drivers/hid/ipts/spec-hid.h | 35 ++ + drivers/hid/ipts/thread.c | 85 +++ + drivers/hid/ipts/thread.h | 60 ++ + drivers/hid/ithc/Kbuild | 6 + + drivers/hid/ithc/Kconfig | 12 + + drivers/hid/ithc/ithc-debug.c | 96 ++++ + drivers/hid/ithc/ithc-dma.c | 258 +++++++++ + drivers/hid/ithc/ithc-dma.h | 67 +++ + drivers/hid/ithc/ithc-main.c | 534 ++++++++++++++++++ + drivers/hid/ithc/ithc-regs.c | 64 +++ + drivers/hid/ithc/ithc-regs.h | 186 ++++++ + drivers/hid/ithc/ithc.h | 60 ++ + drivers/i2c/i2c-core-acpi.c | 35 ++ + drivers/input/misc/soc_button_array.c | 33 +- + drivers/iommu/intel/iommu.c | 24 + + drivers/iommu/intel/irq_remapping.c | 16 + + drivers/misc/mei/hw-me-regs.h | 1 + + drivers/misc/mei/pci-me.c | 1 + + drivers/net/wireless/ath/ath10k/core.c | 58 ++ + drivers/net/wireless/marvell/mwifiex/pcie.c | 19 + + .../wireless/marvell/mwifiex/pcie_quirks.c | 37 +- + .../wireless/marvell/mwifiex/pcie_quirks.h | 2 + + drivers/pci/pci-driver.c | 3 + + drivers/pci/quirks.c | 36 ++ + drivers/platform/surface/Kconfig | 7 + + drivers/platform/surface/Makefile | 1 + + drivers/platform/surface/surface3-wmi.c | 7 + + drivers/platform/surface/surface_gpe.c | 17 + + .../surface/surfacebook1_dgpu_switch.c | 162 ++++++ + drivers/platform/surface/surfacepro3_button.c | 30 +- + drivers/usb/core/quirks.c | 3 + + include/linux/pci.h | 1 + + sound/soc/codecs/rt5645.c | 9 + + .../intel/common/soc-acpi-intel-cht-match.c | 8 + + 59 files changed, 4636 insertions(+), 70 deletions(-) + create mode 100644 drivers/hid/ipts/Kconfig + create mode 100644 drivers/hid/ipts/Makefile + create mode 100644 drivers/hid/ipts/cmd.c + create mode 100644 drivers/hid/ipts/cmd.h + create mode 100644 drivers/hid/ipts/context.h + create mode 100644 drivers/hid/ipts/control.c + create mode 100644 drivers/hid/ipts/control.h + create mode 100644 drivers/hid/ipts/desc.h + create mode 100644 drivers/hid/ipts/hid.c + create mode 100644 drivers/hid/ipts/hid.h + create mode 100644 drivers/hid/ipts/main.c + create mode 100644 drivers/hid/ipts/mei.c + create mode 100644 drivers/hid/ipts/mei.h + create mode 100644 drivers/hid/ipts/receiver.c + create mode 100644 drivers/hid/ipts/receiver.h + create mode 100644 drivers/hid/ipts/resources.c + create mode 100644 drivers/hid/ipts/resources.h + create mode 100644 drivers/hid/ipts/spec-data.h + create mode 100644 drivers/hid/ipts/spec-device.h + create mode 100644 drivers/hid/ipts/spec-hid.h + create mode 100644 drivers/hid/ipts/thread.c + create mode 100644 drivers/hid/ipts/thread.h + create mode 100644 drivers/hid/ithc/Kbuild + create mode 100644 drivers/hid/ithc/Kconfig + create mode 100644 drivers/hid/ithc/ithc-debug.c + create mode 100644 drivers/hid/ithc/ithc-dma.c + create mode 100644 drivers/hid/ithc/ithc-dma.h + create mode 100644 drivers/hid/ithc/ithc-main.c + create mode 100644 drivers/hid/ithc/ithc-regs.c + create mode 100644 drivers/hid/ithc/ithc-regs.h + create mode 100644 drivers/hid/ithc/ithc.h + create mode 100644 drivers/platform/surface/surfacebook1_dgpu_switch.c + +diff --git a/arch/x86/kernel/acpi/boot.c b/arch/x86/kernel/acpi/boot.c +index 0dac4ab5b55b..623d94a9cb86 100644 +--- a/arch/x86/kernel/acpi/boot.c ++++ b/arch/x86/kernel/acpi/boot.c +@@ -22,6 +22,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -1252,6 +1253,24 @@ static void __init mp_config_acpi_legacy_irqs(void) + } + } + ++static const struct dmi_system_id surface_quirk[] __initconst = { ++ { ++ .ident = "Microsoft Surface Laptop 4 (AMD 15\")", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_4_1952:1953") ++ }, ++ }, ++ { ++ .ident = "Microsoft Surface Laptop 4 (AMD 13\")", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_4_1958:1959") ++ }, ++ }, ++ {} ++}; ++ + /* + * Parse IOAPIC related entries in MADT + * returns 0 on success, < 0 on error +@@ -1307,6 +1326,11 @@ static int __init acpi_parse_madt_ioapic_entries(void) + acpi_sci_ioapic_setup(acpi_gbl_FADT.sci_interrupt, 0, 0, + acpi_gbl_FADT.sci_interrupt); + ++ if (dmi_check_system(surface_quirk)) { ++ pr_warn("Surface hack: Override irq 7\n"); ++ mp_override_legacy_irq(7, 3, 3, 7); ++ } ++ + /* Fill in identity legacy mappings where no override */ + mp_config_acpi_legacy_irqs(); + +diff --git a/drivers/acpi/acpi_tad.c b/drivers/acpi/acpi_tad.c +index e9b8e8305e23..944276934e7e 100644 +--- a/drivers/acpi/acpi_tad.c ++++ b/drivers/acpi/acpi_tad.c +@@ -432,6 +432,14 @@ static ssize_t caps_show(struct device *dev, struct device_attribute *attr, + + static DEVICE_ATTR_RO(caps); + ++static struct attribute *acpi_tad_attrs[] = { ++ &dev_attr_caps.attr, ++ NULL, ++}; ++static const struct attribute_group acpi_tad_attr_group = { ++ .attrs = acpi_tad_attrs, ++}; ++ + static ssize_t ac_alarm_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) + { +@@ -480,15 +488,14 @@ static ssize_t ac_status_show(struct device *dev, struct device_attribute *attr, + + static DEVICE_ATTR_RW(ac_status); + +-static struct attribute *acpi_tad_attrs[] = { +- &dev_attr_caps.attr, ++static struct attribute *acpi_tad_ac_attrs[] = { + &dev_attr_ac_alarm.attr, + &dev_attr_ac_policy.attr, + &dev_attr_ac_status.attr, + NULL, + }; +-static const struct attribute_group acpi_tad_attr_group = { +- .attrs = acpi_tad_attrs, ++static const struct attribute_group acpi_tad_ac_attr_group = { ++ .attrs = acpi_tad_ac_attrs, + }; + + static ssize_t dc_alarm_store(struct device *dev, struct device_attribute *attr, +@@ -563,13 +570,18 @@ static int acpi_tad_remove(struct platform_device *pdev) + + pm_runtime_get_sync(dev); + ++ if (dd->capabilities & ACPI_TAD_AC_WAKE) ++ sysfs_remove_group(&dev->kobj, &acpi_tad_ac_attr_group); ++ + if (dd->capabilities & ACPI_TAD_DC_WAKE) + sysfs_remove_group(&dev->kobj, &acpi_tad_dc_attr_group); + + sysfs_remove_group(&dev->kobj, &acpi_tad_attr_group); + +- acpi_tad_disable_timer(dev, ACPI_TAD_AC_TIMER); +- acpi_tad_clear_status(dev, ACPI_TAD_AC_TIMER); ++ if (dd->capabilities & ACPI_TAD_AC_WAKE) { ++ acpi_tad_disable_timer(dev, ACPI_TAD_AC_TIMER); ++ acpi_tad_clear_status(dev, ACPI_TAD_AC_TIMER); ++ } + if (dd->capabilities & ACPI_TAD_DC_WAKE) { + acpi_tad_disable_timer(dev, ACPI_TAD_DC_TIMER); + acpi_tad_clear_status(dev, ACPI_TAD_DC_TIMER); +@@ -604,11 +616,6 @@ static int acpi_tad_probe(struct platform_device *pdev) + return -ENODEV; + } + +- if (!acpi_has_method(handle, "_PRW")) { +- dev_info(dev, "Missing _PRW\n"); +- return -ENODEV; +- } +- + dd = devm_kzalloc(dev, sizeof(*dd), GFP_KERNEL); + if (!dd) + return -ENOMEM; +@@ -637,6 +644,12 @@ static int acpi_tad_probe(struct platform_device *pdev) + if (ret) + goto fail; + ++ if (caps & ACPI_TAD_AC_WAKE) { ++ ret = sysfs_create_group(&dev->kobj, &acpi_tad_ac_attr_group); ++ if (ret) ++ goto fail; ++ } ++ + if (caps & ACPI_TAD_DC_WAKE) { + ret = sysfs_create_group(&dev->kobj, &acpi_tad_dc_attr_group); + if (ret) +diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c +index 5a80379253a7..5651b4bfe72c 100644 +--- a/drivers/bluetooth/btusb.c ++++ b/drivers/bluetooth/btusb.c +@@ -65,6 +65,7 @@ static struct usb_driver btusb_driver; + #define BTUSB_INTEL_BROKEN_INITIAL_NCMD BIT(25) + #define BTUSB_INTEL_NO_WBS_SUPPORT BIT(26) + #define BTUSB_ACTIONS_SEMI BIT(27) ++#define BTUSB_LOWER_LESCAN_INTERVAL BIT(28) + + static const struct usb_device_id btusb_table[] = { + /* Generic Bluetooth USB device */ +@@ -468,6 +469,7 @@ static const struct usb_device_id blacklist_table[] = { + { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL }, ++ { USB_DEVICE(0x1286, 0x204c), .driver_info = BTUSB_LOWER_LESCAN_INTERVAL }, + + /* Intel Bluetooth devices */ + { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_COMBINED }, +@@ -4033,6 +4035,19 @@ static int btusb_probe(struct usb_interface *intf, + if (id->driver_info & BTUSB_MARVELL) + hdev->set_bdaddr = btusb_set_bdaddr_marvell; + ++ /* The Marvell 88W8897 combined wifi and bluetooth card is known for ++ * very bad bt+wifi coexisting performance. ++ * ++ * Decrease the passive BT Low Energy scan interval a bit ++ * (0x0190 * 0.625 msec = 250 msec) and make the scan window shorter ++ * (0x000a * 0,625 msec = 6.25 msec). This allows for significantly ++ * higher wifi throughput while passively scanning for BT LE devices. ++ */ ++ if (id->driver_info & BTUSB_LOWER_LESCAN_INTERVAL) { ++ hdev->le_scan_interval = 0x0190; ++ hdev->le_scan_window = 0x000a; ++ } ++ + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) && + (id->driver_info & BTUSB_MEDIATEK)) { + hdev->setup = btusb_mtk_setup; +diff --git a/drivers/hid/Kconfig b/drivers/hid/Kconfig +index 4ce012f83253..aebb62488cf1 100644 +--- a/drivers/hid/Kconfig ++++ b/drivers/hid/Kconfig +@@ -1300,6 +1300,10 @@ config HID_KUNIT_TEST + + If in doubt, say "N". + ++source "drivers/hid/ipts/Kconfig" ++ ++source "drivers/hid/ithc/Kconfig" ++ + endmenu + + source "drivers/hid/bpf/Kconfig" +diff --git a/drivers/hid/Makefile b/drivers/hid/Makefile +index 5d37cacbde33..a3ff62e922f1 100644 +--- a/drivers/hid/Makefile ++++ b/drivers/hid/Makefile +@@ -167,3 +167,6 @@ obj-$(INTEL_ISH_FIRMWARE_DOWNLOADER) += intel-ish-hid/ + obj-$(CONFIG_AMD_SFH_HID) += amd-sfh-hid/ + + obj-$(CONFIG_SURFACE_HID_CORE) += surface-hid/ ++ ++obj-$(CONFIG_HID_IPTS) += ipts/ ++obj-$(CONFIG_HID_ITHC) += ithc/ +diff --git a/drivers/hid/hid-multitouch.c b/drivers/hid/hid-multitouch.c +index e31be0cb8b85..508a250ff4bf 100644 +--- a/drivers/hid/hid-multitouch.c ++++ b/drivers/hid/hid-multitouch.c +@@ -34,7 +34,10 @@ + #include + #include + #include ++#include + #include ++#include ++#include + #include + #include + #include +@@ -47,6 +50,7 @@ MODULE_DESCRIPTION("HID multitouch panels"); + MODULE_LICENSE("GPL"); + + #include "hid-ids.h" ++#include "usbhid/usbhid.h" + + /* quirks to control the device */ + #define MT_QUIRK_NOT_SEEN_MEANS_UP BIT(0) +@@ -72,12 +76,18 @@ MODULE_LICENSE("GPL"); + #define MT_QUIRK_FORCE_MULTI_INPUT BIT(20) + #define MT_QUIRK_DISABLE_WAKEUP BIT(21) + #define MT_QUIRK_ORIENTATION_INVERT BIT(22) ++#define MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT BIT(23) ++#define MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH BIT(24) + + #define MT_INPUTMODE_TOUCHSCREEN 0x02 + #define MT_INPUTMODE_TOUCHPAD 0x03 + + #define MT_BUTTONTYPE_CLICKPAD 0 + ++#define MS_TYPE_COVER_FEATURE_REPORT_USAGE 0xff050086 ++#define MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE 0xff050072 ++#define MS_TYPE_COVER_APPLICATION 0xff050050 ++ + enum latency_mode { + HID_LATENCY_NORMAL = 0, + HID_LATENCY_HIGH = 1, +@@ -169,6 +179,8 @@ struct mt_device { + + struct list_head applications; + struct list_head reports; ++ ++ struct notifier_block pm_notifier; + }; + + static void mt_post_parse_default_settings(struct mt_device *td, +@@ -213,6 +225,7 @@ static void mt_post_parse(struct mt_device *td, struct mt_application *app); + #define MT_CLS_GOOGLE 0x0111 + #define MT_CLS_RAZER_BLADE_STEALTH 0x0112 + #define MT_CLS_SMART_TECH 0x0113 ++#define MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER 0x0114 + + #define MT_DEFAULT_MAXCONTACT 10 + #define MT_MAX_MAXCONTACT 250 +@@ -397,6 +410,17 @@ static const struct mt_class mt_classes[] = { + MT_QUIRK_CONTACT_CNT_ACCURATE | + MT_QUIRK_SEPARATE_APP_REPORT, + }, ++ { .name = MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER, ++ .quirks = MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT | ++ MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH | ++ MT_QUIRK_ALWAYS_VALID | ++ MT_QUIRK_IGNORE_DUPLICATES | ++ MT_QUIRK_HOVERING | ++ MT_QUIRK_CONTACT_CNT_ACCURATE | ++ MT_QUIRK_STICKY_FINGERS | ++ MT_QUIRK_WIN8_PTP_BUTTONS, ++ .export_all_inputs = true ++ }, + { } + }; + +@@ -1370,6 +1394,9 @@ static int mt_input_mapping(struct hid_device *hdev, struct hid_input *hi, + field->application != HID_CP_CONSUMER_CONTROL && + field->application != HID_GD_WIRELESS_RADIO_CTLS && + field->application != HID_GD_SYSTEM_MULTIAXIS && ++ !(field->application == MS_TYPE_COVER_APPLICATION && ++ application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) && + !(field->application == HID_VD_ASUS_CUSTOM_MEDIA_KEYS && + application->quirks & MT_QUIRK_ASUS_CUSTOM_UP)) + return -1; +@@ -1397,6 +1424,21 @@ static int mt_input_mapping(struct hid_device *hdev, struct hid_input *hi, + return 1; + } + ++ /* ++ * The Microsoft Surface Pro Typecover has a non-standard HID ++ * tablet mode switch on a vendor specific usage page with vendor ++ * specific usage. ++ */ ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ usage->type = EV_SW; ++ usage->code = SW_TABLET_MODE; ++ *max = SW_MAX; ++ *bit = hi->input->swbit; ++ return 1; ++ } ++ + if (rdata->is_mt_collection) + return mt_touch_input_mapping(hdev, hi, field, usage, bit, max, + application); +@@ -1418,6 +1460,7 @@ static int mt_input_mapped(struct hid_device *hdev, struct hid_input *hi, + { + struct mt_device *td = hid_get_drvdata(hdev); + struct mt_report_data *rdata; ++ struct input_dev *input; + + rdata = mt_find_report_data(td, field->report); + if (rdata && rdata->is_mt_collection) { +@@ -1425,6 +1468,19 @@ static int mt_input_mapped(struct hid_device *hdev, struct hid_input *hi, + return -1; + } + ++ /* ++ * We own an input device which acts as a tablet mode switch for ++ * the Surface Pro Typecover. ++ */ ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ rdata->application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ input = hi->input; ++ input_set_capability(input, EV_SW, SW_TABLET_MODE); ++ input_report_switch(input, SW_TABLET_MODE, 0); ++ return -1; ++ } ++ + /* let hid-core decide for the others */ + return 0; + } +@@ -1434,11 +1490,21 @@ static int mt_event(struct hid_device *hid, struct hid_field *field, + { + struct mt_device *td = hid_get_drvdata(hid); + struct mt_report_data *rdata; ++ struct input_dev *input; + + rdata = mt_find_report_data(td, field->report); + if (rdata && rdata->is_mt_collection) + return mt_touch_event(hid, field, usage, value); + ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ rdata->application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ input = field->hidinput->input; ++ input_report_switch(input, SW_TABLET_MODE, (value & 0xFF) != 0x22); ++ input_sync(input); ++ return 1; ++ } ++ + return 0; + } + +@@ -1591,6 +1657,42 @@ static void mt_post_parse(struct mt_device *td, struct mt_application *app) + app->quirks &= ~MT_QUIRK_CONTACT_CNT_ACCURATE; + } + ++static int get_type_cover_field(struct hid_report_enum *rep_enum, ++ struct hid_field **field, int usage) ++{ ++ struct hid_report *rep; ++ struct hid_field *cur_field; ++ int i, j; ++ ++ list_for_each_entry(rep, &rep_enum->report_list, list) { ++ for (i = 0; i < rep->maxfield; i++) { ++ cur_field = rep->field[i]; ++ if (cur_field->application != MS_TYPE_COVER_APPLICATION) ++ continue; ++ for (j = 0; j < cur_field->maxusage; j++) { ++ if (cur_field->usage[j].hid == usage) { ++ *field = cur_field; ++ return true; ++ } ++ } ++ } ++ } ++ return false; ++} ++ ++static void request_type_cover_tablet_mode_switch(struct hid_device *hdev) ++{ ++ struct hid_field *field; ++ ++ if (get_type_cover_field(&hdev->report_enum[HID_INPUT_REPORT], ++ &field, ++ MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE)) { ++ hid_hw_request(hdev, field->report, HID_REQ_GET_REPORT); ++ } else { ++ hid_err(hdev, "couldn't find tablet mode field\n"); ++ } ++} ++ + static int mt_input_configured(struct hid_device *hdev, struct hid_input *hi) + { + struct mt_device *td = hid_get_drvdata(hdev); +@@ -1640,6 +1742,13 @@ static int mt_input_configured(struct hid_device *hdev, struct hid_input *hi) + /* force BTN_STYLUS to allow tablet matching in udev */ + __set_bit(BTN_STYLUS, hi->input->keybit); + break; ++ case MS_TYPE_COVER_APPLICATION: ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) { ++ suffix = "Tablet Mode Switch"; ++ request_type_cover_tablet_mode_switch(hdev); ++ break; ++ } ++ fallthrough; + default: + suffix = "UNKNOWN"; + break; +@@ -1728,6 +1837,46 @@ static void mt_expired_timeout(struct timer_list *t) + clear_bit_unlock(MT_IO_FLAGS_RUNNING, &td->mt_io_flags); + } + ++static void update_keyboard_backlight(struct hid_device *hdev, bool enabled) ++{ ++ struct usb_device *udev = hid_to_usb_dev(hdev); ++ struct hid_field *field = NULL; ++ ++ /* Wake up the device in case it's already suspended */ ++ pm_runtime_get_sync(&udev->dev); ++ ++ if (!get_type_cover_field(&hdev->report_enum[HID_FEATURE_REPORT], ++ &field, ++ MS_TYPE_COVER_FEATURE_REPORT_USAGE)) { ++ hid_err(hdev, "couldn't find backlight field\n"); ++ goto out; ++ } ++ ++ field->value[field->index] = enabled ? 0x01ff00ff : 0x00ff00ff; ++ hid_hw_request(hdev, field->report, HID_REQ_SET_REPORT); ++ ++out: ++ pm_runtime_put_sync(&udev->dev); ++} ++ ++static int mt_pm_notifier(struct notifier_block *notifier, ++ unsigned long pm_event, ++ void *unused) ++{ ++ struct mt_device *td = ++ container_of(notifier, struct mt_device, pm_notifier); ++ struct hid_device *hdev = td->hdev; ++ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT) { ++ if (pm_event == PM_SUSPEND_PREPARE) ++ update_keyboard_backlight(hdev, 0); ++ else if (pm_event == PM_POST_SUSPEND) ++ update_keyboard_backlight(hdev, 1); ++ } ++ ++ return NOTIFY_DONE; ++} ++ + static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + { + int ret, i; +@@ -1751,6 +1900,9 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + td->inputmode_value = MT_INPUTMODE_TOUCHSCREEN; + hid_set_drvdata(hdev, td); + ++ td->pm_notifier.notifier_call = mt_pm_notifier; ++ register_pm_notifier(&td->pm_notifier); ++ + INIT_LIST_HEAD(&td->applications); + INIT_LIST_HEAD(&td->reports); + +@@ -1789,15 +1941,19 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + timer_setup(&td->release_timer, mt_expired_timeout, 0); + + ret = hid_parse(hdev); +- if (ret != 0) ++ if (ret != 0) { ++ unregister_pm_notifier(&td->pm_notifier); + return ret; ++ } + + if (mtclass->quirks & MT_QUIRK_FIX_CONST_CONTACT_ID) + mt_fix_const_fields(hdev, HID_DG_CONTACTID); + + ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); +- if (ret) ++ if (ret) { ++ unregister_pm_notifier(&td->pm_notifier); + return ret; ++ } + + ret = sysfs_create_group(&hdev->dev.kobj, &mt_attribute_group); + if (ret) +@@ -1826,13 +1982,24 @@ static int mt_suspend(struct hid_device *hdev, pm_message_t state) + + static int mt_reset_resume(struct hid_device *hdev) + { ++ struct mt_device *td = hid_get_drvdata(hdev); ++ + mt_release_contacts(hdev); + mt_set_modes(hdev, HID_LATENCY_NORMAL, true, true); ++ ++ /* Request an update on the typecover folding state on resume ++ * after reset. ++ */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) ++ request_type_cover_tablet_mode_switch(hdev); ++ + return 0; + } + + static int mt_resume(struct hid_device *hdev) + { ++ struct mt_device *td = hid_get_drvdata(hdev); ++ + /* Some Elan legacy devices require SET_IDLE to be set on resume. + * It should be safe to send it to other devices too. + * Tested on 3M, Stantum, Cypress, Zytronic, eGalax, and Elan panels. */ +@@ -1841,6 +2008,10 @@ static int mt_resume(struct hid_device *hdev) + + mt_set_modes(hdev, HID_LATENCY_NORMAL, true, true); + ++ /* Request an update on the typecover folding state on resume. */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) ++ request_type_cover_tablet_mode_switch(hdev); ++ + return 0; + } + #endif +@@ -1848,7 +2019,23 @@ static int mt_resume(struct hid_device *hdev) + static void mt_remove(struct hid_device *hdev) + { + struct mt_device *td = hid_get_drvdata(hdev); ++ struct hid_field *field; ++ struct input_dev *input; + ++ /* Reset tablet mode switch on disconnect. */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) { ++ if (get_type_cover_field(&hdev->report_enum[HID_INPUT_REPORT], ++ &field, ++ MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE)) { ++ input = field->hidinput->input; ++ input_report_switch(input, SW_TABLET_MODE, 0); ++ input_sync(input); ++ } else { ++ hid_err(hdev, "couldn't find tablet mode field\n"); ++ } ++ } ++ ++ unregister_pm_notifier(&td->pm_notifier); + del_timer_sync(&td->release_timer); + + sysfs_remove_group(&hdev->dev.kobj, &mt_attribute_group); +@@ -2226,6 +2413,11 @@ static const struct hid_device_id mt_devices[] = { + MT_USB_DEVICE(USB_VENDOR_ID_XIROKU, + USB_DEVICE_ID_XIROKU_CSR2) }, + ++ /* Microsoft Surface type cover */ ++ { .driver_data = MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER, ++ HID_DEVICE(HID_BUS_ANY, HID_GROUP_ANY, ++ USB_VENDOR_ID_MICROSOFT, 0x09c0) }, ++ + /* Google MT devices */ + { .driver_data = MT_CLS_GOOGLE, + HID_DEVICE(HID_BUS_ANY, HID_GROUP_ANY, USB_VENDOR_ID_GOOGLE, +diff --git a/drivers/hid/ipts/Kconfig b/drivers/hid/ipts/Kconfig +new file mode 100644 +index 000000000000..297401bd388d +--- /dev/null ++++ b/drivers/hid/ipts/Kconfig +@@ -0,0 +1,14 @@ ++# SPDX-License-Identifier: GPL-2.0-or-later ++ ++config HID_IPTS ++ tristate "Intel Precise Touch & Stylus" ++ depends on INTEL_MEI ++ depends on HID ++ help ++ Say Y here if your system has a touchscreen using Intels ++ Precise Touch & Stylus (IPTS) technology. ++ ++ If unsure say N. ++ ++ To compile this driver as a module, choose M here: the ++ module will be called ipts. +diff --git a/drivers/hid/ipts/Makefile b/drivers/hid/ipts/Makefile +new file mode 100644 +index 000000000000..0fe655bccdc0 +--- /dev/null ++++ b/drivers/hid/ipts/Makefile +@@ -0,0 +1,14 @@ ++# SPDX-License-Identifier: GPL-2.0-or-later ++# ++# Makefile for the IPTS touchscreen driver ++# ++ ++obj-$(CONFIG_HID_IPTS) += ipts.o ++ipts-objs := cmd.o ++ipts-objs += control.o ++ipts-objs += hid.o ++ipts-objs += main.o ++ipts-objs += mei.o ++ipts-objs += receiver.o ++ipts-objs += resources.o ++ipts-objs += thread.o +diff --git a/drivers/hid/ipts/cmd.c b/drivers/hid/ipts/cmd.c +new file mode 100644 +index 000000000000..7fd69271ccd5 +--- /dev/null ++++ b/drivers/hid/ipts/cmd.c +@@ -0,0 +1,62 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "mei.h" ++#include "spec-device.h" ++ ++int ipts_cmd_recv_timeout(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp, u64 timeout) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!rsp) ++ return -EFAULT; ++ ++ /* ++ * In a response, the command code will have the most significant bit flipped to 1. ++ * If code is passed to ipts_mei_recv as is, no messages will be received. ++ */ ++ ret = ipts_mei_recv(&ipts->mei, code | IPTS_RSP_BIT, rsp, timeout); ++ if (ret < 0) ++ return ret; ++ ++ dev_dbg(ipts->dev, "Received 0x%02X with status 0x%02X\n", code, rsp->status); ++ ++ /* ++ * Some devices will always return this error. ++ * It is allowed to ignore it and to try continuing. ++ */ ++ if (rsp->status == IPTS_STATUS_COMPAT_CHECK_FAIL) ++ rsp->status = IPTS_STATUS_SUCCESS; ++ ++ return 0; ++} ++ ++int ipts_cmd_send(struct ipts_context *ipts, enum ipts_command_code code, void *data, size_t size) ++{ ++ struct ipts_command cmd = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.cmd = code; ++ ++ if (data && size > 0) ++ memcpy(cmd.payload, data, size); ++ ++ dev_dbg(ipts->dev, "Sending 0x%02X with %ld bytes payload\n", code, size); ++ return ipts_mei_send(&ipts->mei, &cmd, sizeof(cmd.cmd) + size); ++} +diff --git a/drivers/hid/ipts/cmd.h b/drivers/hid/ipts/cmd.h +new file mode 100644 +index 000000000000..924758ffee67 +--- /dev/null ++++ b/drivers/hid/ipts/cmd.h +@@ -0,0 +1,61 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CMD_H ++#define IPTS_CMD_H ++ ++#include ++ ++#include "context.h" ++#include "spec-device.h" ++ ++/* ++ * The default timeout for receiving responses ++ */ ++#define IPTS_CMD_DEFAULT_TIMEOUT 1000 ++ ++/* ++ * ipts_cmd_recv_timeout() - Receives a response to a command. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command / response. ++ * @rsp: The address that the received response will be copied to. ++ * @timeout: How many milliseconds the function will wait at most. ++ * ++ * A negative timeout means to wait forever. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++int ipts_cmd_recv_timeout(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp, u64 timeout); ++ ++/* ++ * ipts_cmd_recv() - Receives a response to a command. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command / response. ++ * @rsp: The address that the received response will be copied to. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++static inline int ipts_cmd_recv(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp) ++{ ++ return ipts_cmd_recv_timeout(ipts, code, rsp, IPTS_CMD_DEFAULT_TIMEOUT); ++} ++ ++/* ++ * ipts_cmd_send() - Executes a command on the device. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command to execute. ++ * @data: The payload containing parameters for the command. ++ * @size: The size of the payload. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_cmd_send(struct ipts_context *ipts, enum ipts_command_code code, void *data, size_t size); ++ ++#endif /* IPTS_CMD_H */ +diff --git a/drivers/hid/ipts/context.h b/drivers/hid/ipts/context.h +new file mode 100644 +index 000000000000..3450a95e66ee +--- /dev/null ++++ b/drivers/hid/ipts/context.h +@@ -0,0 +1,51 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CONTEXT_H ++#define IPTS_CONTEXT_H ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "mei.h" ++#include "resources.h" ++#include "spec-device.h" ++#include "thread.h" ++ ++struct ipts_context { ++ struct device *dev; ++ struct ipts_mei mei; ++ ++ enum ipts_mode mode; ++ ++ /* ++ * Prevents concurrent GET_FEATURE reports. ++ */ ++ struct mutex feature_lock; ++ struct completion feature_event; ++ ++ /* ++ * These are not inside of struct ipts_resources ++ * because they don't own the memory they point to. ++ */ ++ struct ipts_buffer feature_report; ++ struct ipts_buffer descriptor; ++ ++ struct hid_device *hid; ++ struct ipts_device_info info; ++ struct ipts_resources resources; ++ ++ struct ipts_thread receiver_loop; ++}; ++ ++#endif /* IPTS_CONTEXT_H */ +diff --git a/drivers/hid/ipts/control.c b/drivers/hid/ipts/control.c +new file mode 100644 +index 000000000000..2f61500b5119 +--- /dev/null ++++ b/drivers/hid/ipts/control.c +@@ -0,0 +1,495 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "control.h" ++#include "desc.h" ++#include "hid.h" ++#include "receiver.h" ++#include "resources.h" ++#include "spec-data.h" ++#include "spec-device.h" ++ ++static int ipts_control_get_device_info(struct ipts_context *ipts, struct ipts_device_info *info) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!info) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_GET_DEVICE_INFO, NULL, 0); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_GET_DEVICE_INFO, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ memcpy(info, rsp.payload, sizeof(*info)); ++ return 0; ++} ++ ++static int ipts_control_set_mode(struct ipts_context *ipts, enum ipts_mode mode) ++{ ++ int ret = 0; ++ struct ipts_set_mode cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.mode = mode; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_SET_MODE, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MODE: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_SET_MODE, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MODE: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "SET_MODE: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++static int ipts_control_set_mem_window(struct ipts_context *ipts, struct ipts_resources *res) ++{ ++ int ret = 0; ++ struct ipts_mem_window cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ cmd.data_addr_lower[i] = lower_32_bits(res->data[i].dma_address); ++ cmd.data_addr_upper[i] = upper_32_bits(res->data[i].dma_address); ++ cmd.feedback_addr_lower[i] = lower_32_bits(res->feedback[i].dma_address); ++ cmd.feedback_addr_upper[i] = upper_32_bits(res->feedback[i].dma_address); ++ } ++ ++ cmd.workqueue_addr_lower = lower_32_bits(res->workqueue.dma_address); ++ cmd.workqueue_addr_upper = upper_32_bits(res->workqueue.dma_address); ++ ++ cmd.doorbell_addr_lower = lower_32_bits(res->doorbell.dma_address); ++ cmd.doorbell_addr_upper = upper_32_bits(res->doorbell.dma_address); ++ ++ cmd.hid2me_addr_lower = lower_32_bits(res->hid2me.dma_address); ++ cmd.hid2me_addr_upper = upper_32_bits(res->hid2me.dma_address); ++ ++ cmd.workqueue_size = IPTS_WORKQUEUE_SIZE; ++ cmd.workqueue_item_size = IPTS_WORKQUEUE_ITEM_SIZE; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_SET_MEM_WINDOW, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_SET_MEM_WINDOW, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++static int ipts_control_get_descriptor(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_data_header *header = NULL; ++ struct ipts_get_descriptor cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->resources.descriptor.address) ++ return -EFAULT; ++ ++ memset(ipts->resources.descriptor.address, 0, ipts->resources.descriptor.size); ++ ++ cmd.addr_lower = lower_32_bits(ipts->resources.descriptor.dma_address); ++ cmd.addr_upper = upper_32_bits(ipts->resources.descriptor.dma_address); ++ cmd.magic = 8; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_GET_DESCRIPTOR, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_GET_DESCRIPTOR, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ header = (struct ipts_data_header *)ipts->resources.descriptor.address; ++ ++ if (header->type == IPTS_DATA_TYPE_DESCRIPTOR) { ++ ipts->descriptor.address = &header->data[8]; ++ ipts->descriptor.size = header->size - 8; ++ ++ return 0; ++ } ++ ++ return -ENODATA; ++} ++ ++int ipts_control_request_flush(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_quiesce_io cmd = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_QUIESCE_IO, &cmd, sizeof(cmd)); ++ if (ret) ++ dev_err(ipts->dev, "QUIESCE_IO: send failed: %d\n", ret); ++ ++ return ret; ++} ++ ++int ipts_control_wait_flush(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_QUIESCE_IO, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "QUIESCE_IO: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status == IPTS_STATUS_TIMEOUT) ++ return -EAGAIN; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "QUIESCE_IO: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_request_data(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_READY_FOR_DATA, NULL, 0); ++ if (ret) ++ dev_err(ipts->dev, "READY_FOR_DATA: send failed: %d\n", ret); ++ ++ return ret; ++} ++ ++int ipts_control_wait_data(struct ipts_context *ipts, bool shutdown) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!shutdown) ++ ret = ipts_cmd_recv_timeout(ipts, IPTS_CMD_READY_FOR_DATA, &rsp, 0); ++ else ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_READY_FOR_DATA, &rsp); ++ ++ if (ret) { ++ if (ret != -EAGAIN) ++ dev_err(ipts->dev, "READY_FOR_DATA: recv failed: %d\n", ret); ++ ++ return ret; ++ } ++ ++ /* ++ * During shutdown, it is possible that the sensor has already been disabled. ++ */ ++ if (rsp.status == IPTS_STATUS_SENSOR_DISABLED) ++ return 0; ++ ++ if (rsp.status == IPTS_STATUS_TIMEOUT) ++ return -EAGAIN; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "READY_FOR_DATA: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) ++{ ++ int ret = 0; ++ struct ipts_feedback cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.buffer = buffer; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_FEEDBACK, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "FEEDBACK: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_FEEDBACK, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "FEEDBACK: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ /* ++ * We don't know what feedback data looks like so we are sending zeros. ++ * See also ipts_control_refill_buffer. ++ */ ++ if (rsp.status == IPTS_STATUS_INVALID_PARAMS) ++ return 0; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "FEEDBACK: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_cmd_type cmd, ++ enum ipts_feedback_data_type type, void *data, size_t size) ++{ ++ struct ipts_feedback_header *header = NULL; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->resources.hid2me.address) ++ return -EFAULT; ++ ++ memset(ipts->resources.hid2me.address, 0, ipts->resources.hid2me.size); ++ header = (struct ipts_feedback_header *)ipts->resources.hid2me.address; ++ ++ header->cmd_type = cmd; ++ header->data_type = type; ++ header->size = size; ++ header->buffer = IPTS_HID2ME_BUFFER; ++ ++ if (size + sizeof(*header) > ipts->resources.hid2me.size) ++ return -EINVAL; ++ ++ if (data && size > 0) ++ memcpy(header->payload, data, size); ++ ++ return ipts_control_send_feedback(ipts, IPTS_HID2ME_BUFFER); ++} ++ ++static inline int ipts_control_reset_sensor(struct ipts_context *ipts) ++{ ++ return ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_SOFT_RESET, ++ IPTS_FEEDBACK_DATA_TYPE_VENDOR, NULL, 0); ++} ++ ++int ipts_control_start(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_device_info info = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "Starting IPTS\n"); ++ ++ ret = ipts_control_get_device_info(ipts, &info); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to get device info: %d\n", ret); ++ return ret; ++ } ++ ++ ipts->info = info; ++ ++ ret = ipts_resources_init(&ipts->resources, ipts->dev, info.data_size, info.feedback_size); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to allocate buffers: %d", ret); ++ return ret; ++ } ++ ++ dev_info(ipts->dev, "IPTS EDS Version: %d\n", info.intf_eds); ++ ++ /* ++ * Handle newer devices ++ */ ++ if (info.intf_eds > 1) { ++ /* ++ * Fetching the descriptor will only work on newer devices. ++ * For older devices, a fallback descriptor will be used. ++ */ ++ ret = ipts_control_get_descriptor(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to fetch HID descriptor: %d\n", ret); ++ return ret; ++ } ++ ++ /* ++ * Newer devices can be directly initialized in doorbell mode. ++ */ ++ ipts->mode = IPTS_MODE_DOORBELL; ++ } ++ ++ ret = ipts_control_set_mode(ipts, ipts->mode); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to set mode: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_set_mem_window(ipts, &ipts->resources); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to set memory window: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_receiver_start(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to start receiver: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_request_data(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request data: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_hid_init(ipts, info); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to initialize HID device: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static int _ipts_control_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "Stopping IPTS\n"); ++ ++ ret = ipts_receiver_stop(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to stop receiver: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_reset_sensor(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to reset sensor: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_resources_free(&ipts->resources); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to free resources: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ ret = _ipts_control_stop(ipts); ++ if (ret) ++ return ret; ++ ++ ret = ipts_hid_free(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to free HID device: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_restart(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ ret = _ipts_control_stop(ipts); ++ if (ret) ++ return ret; ++ ++ /* ++ * Give the sensor some time to come back from resetting ++ */ ++ msleep(1000); ++ ++ ret = ipts_control_start(ipts); ++ if (ret) ++ return ret; ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/control.h b/drivers/hid/ipts/control.h +new file mode 100644 +index 000000000000..744bb92d682a +--- /dev/null ++++ b/drivers/hid/ipts/control.h +@@ -0,0 +1,127 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CONTROL_H ++#define IPTS_CONTROL_H ++ ++#include ++ ++#include "context.h" ++#include "spec-data.h" ++#include "spec-device.h" ++ ++/* ++ * ipts_control_request_flush() - Stop the data flow. ++ * @ipts: The IPTS driver context. ++ * ++ * Runs the command to stop the data flow on the device. ++ * All outstanding data needs to be acknowledged using feedback before the command will return. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_request_flush(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_flush() - Wait until data flow has been stopped. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_wait_flush(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_flush() - Notify the device that the driver can receive new data. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_request_data(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_data() - Wait until new data is available. ++ * @ipts: The IPTS driver context. ++ * @block: Whether to block execution until data is available. ++ * ++ * In doorbell mode, this function will never return while the data flow is active. Instead, ++ * the doorbell will be incremented when new data is available. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no data is available. ++ */ ++int ipts_control_wait_data(struct ipts_context *ipts, bool block); ++ ++/* ++ * ipts_control_send_feedback() - Submits a feedback buffer to the device. ++ * @ipts: The IPTS driver context. ++ * @buffer: The ID of the buffer containing feedback data. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer); ++ ++/* ++ * ipts_control_hid2me_feedback() - Sends HID2ME feedback, a special type of feedback. ++ * @ipts: The IPTS driver context. ++ * @cmd: The command that will be run on the device. ++ * @type: The type of the payload that is sent to the device. ++ * @data: The payload of the feedback command. ++ * @size: The size of the payload. ++ * ++ * HID2ME feedback is a special type of feedback, because it allows interfacing with ++ * the HID API of the device at any moment, without requiring a buffer that has to ++ * be acknowledged. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_cmd_type cmd, ++ enum ipts_feedback_data_type type, void *data, size_t size); ++ ++/* ++ * ipts_control_refill_buffer() - Acknowledges that data in a buffer has been processed. ++ * @ipts: The IPTS driver context. ++ * @buffer: The buffer that has been processed and can be refilled. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++static inline int ipts_control_refill_buffer(struct ipts_context *ipts, u32 buffer) ++{ ++ /* ++ * IPTS expects structured data in the feedback buffer matching the buffer that will be ++ * refilled. We don't know what that data looks like, so we just keep the buffer empty. ++ * This results in an INVALID_PARAMS error, but the buffer gets refilled without an issue. ++ * Sending a minimal structure with the buffer ID fixes the error, but breaks refilling ++ * the buffers on some devices. ++ */ ++ ++ return ipts_control_send_feedback(ipts, buffer); ++} ++ ++/* ++ * ipts_control_start() - Initialized the device and starts the data flow. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_start(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_stop() - Stops the data flow and resets the device. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_stop(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_restart() - Stops the device and starts it again. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_restart(struct ipts_context *ipts); ++ ++#endif /* IPTS_CONTROL_H */ +diff --git a/drivers/hid/ipts/desc.h b/drivers/hid/ipts/desc.h +new file mode 100644 +index 000000000000..c058974a03a1 +--- /dev/null ++++ b/drivers/hid/ipts/desc.h +@@ -0,0 +1,81 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_DESC_H ++#define IPTS_DESC_H ++ ++#include ++ ++#define IPTS_HID_REPORT_SINGLETOUCH 64 ++#define IPTS_HID_REPORT_DATA 65 ++#define IPTS_HID_REPORT_SET_MODE 66 ++ ++#define IPTS_HID_REPORT_DATA_SIZE 7485 ++ ++/* ++ * HID descriptor for singletouch data. ++ * This descriptor should be present on all IPTS devices. ++ */ ++static const u8 ipts_singletouch_descriptor[] = { ++ 0x05, 0x0D, /* Usage Page (Digitizer), */ ++ 0x09, 0x04, /* Usage (Touchscreen), */ ++ 0xA1, 0x01, /* Collection (Application), */ ++ 0x85, 0x40, /* Report ID (64), */ ++ 0x09, 0x42, /* Usage (Tip Switch), */ ++ 0x15, 0x00, /* Logical Minimum (0), */ ++ 0x25, 0x01, /* Logical Maximum (1), */ ++ 0x75, 0x01, /* Report Size (1), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x95, 0x07, /* Report Count (7), */ ++ 0x81, 0x03, /* Input (Constant, Variable), */ ++ 0x05, 0x01, /* Usage Page (Desktop), */ ++ 0x09, 0x30, /* Usage (X), */ ++ 0x75, 0x10, /* Report Size (16), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0xA4, /* Push, */ ++ 0x55, 0x0E, /* Unit Exponent (14), */ ++ 0x65, 0x11, /* Unit (Centimeter), */ ++ 0x46, 0x76, 0x0B, /* Physical Maximum (2934), */ ++ 0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x09, 0x31, /* Usage (Y), */ ++ 0x46, 0x74, 0x06, /* Physical Maximum (1652), */ ++ 0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0xB4, /* Pop, */ ++ 0xC0, /* End Collection */ ++}; ++ ++/* ++ * Fallback HID descriptor for older devices that do not have ++ * the ability to query their HID descriptor. ++ */ ++static const u8 ipts_fallback_descriptor[] = { ++ 0x05, 0x0D, /* Usage Page (Digitizer), */ ++ 0x09, 0x0F, /* Usage (Capacitive Hm Digitizer), */ ++ 0xA1, 0x01, /* Collection (Application), */ ++ 0x85, 0x41, /* Report ID (65), */ ++ 0x09, 0x56, /* Usage (Scan Time), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0x75, 0x10, /* Report Size (16), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x09, 0x61, /* Usage (Gesture Char Quality), */ ++ 0x75, 0x08, /* Report Size (8), */ ++ 0x96, 0x3D, 0x1D, /* Report Count (7485), */ ++ 0x81, 0x03, /* Input (Constant, Variable), */ ++ 0x85, 0x42, /* Report ID (66), */ ++ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ ++ 0x09, 0xC8, /* Usage (C8h), */ ++ 0x75, 0x08, /* Report Size (8), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0xB1, 0x02, /* Feature (Variable), */ ++ 0xC0, /* End Collection, */ ++}; ++ ++#endif /* IPTS_DESC_H */ +diff --git a/drivers/hid/ipts/hid.c b/drivers/hid/ipts/hid.c +new file mode 100644 +index 000000000000..6782394e8dde +--- /dev/null ++++ b/drivers/hid/ipts/hid.c +@@ -0,0 +1,348 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "control.h" ++#include "desc.h" ++#include "hid.h" ++#include "spec-data.h" ++#include "spec-device.h" ++#include "spec-hid.h" ++ ++static int ipts_hid_start(struct hid_device *hid) ++{ ++ return 0; ++} ++ ++static void ipts_hid_stop(struct hid_device *hid) ++{ ++} ++ ++static int ipts_hid_switch_mode(struct ipts_context *ipts, enum ipts_mode mode) ++{ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->mode == mode) ++ return 0; ++ ++ /* ++ * This is only allowed on older devices. ++ */ ++ if (ipts->info.intf_eds > 1) ++ return 0; ++ ++ ipts->mode = mode; ++ return ipts_control_restart(ipts); ++} ++ ++static int ipts_hid_parse(struct hid_device *hid) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ bool has_native_descriptor = false; ++ ++ u8 *buffer = NULL; ++ size_t size = 0; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ size = sizeof(ipts_singletouch_descriptor); ++ has_native_descriptor = ipts->descriptor.address && ipts->descriptor.size > 0; ++ ++ if (has_native_descriptor) ++ size += ipts->descriptor.size; ++ else ++ size += sizeof(ipts_fallback_descriptor); ++ ++ buffer = kzalloc(size, GFP_KERNEL); ++ if (!buffer) ++ return -ENOMEM; ++ ++ memcpy(buffer, ipts_singletouch_descriptor, sizeof(ipts_singletouch_descriptor)); ++ ++ if (has_native_descriptor) { ++ memcpy(&buffer[sizeof(ipts_singletouch_descriptor)], ipts->descriptor.address, ++ ipts->descriptor.size); ++ } else { ++ memcpy(&buffer[sizeof(ipts_singletouch_descriptor)], ipts_fallback_descriptor, ++ sizeof(ipts_fallback_descriptor)); ++ } ++ ++ ret = hid_parse_report(hid, buffer, size); ++ kfree(buffer); ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to parse HID descriptor: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static int ipts_hid_get_feature(struct ipts_context *ipts, unsigned char reportnum, __u8 *buf, ++ size_t size, enum ipts_feedback_data_type type) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ mutex_lock(&ipts->feature_lock); ++ ++ memset(buf, 0, size); ++ buf[0] = reportnum; ++ ++ memset(&ipts->feature_report, 0, sizeof(ipts->feature_report)); ++ reinit_completion(&ipts->feature_event); ++ ++ ret = ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, type, buf, size); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to send hid2me feedback: %d\n", ret); ++ goto out; ++ } ++ ++ ret = wait_for_completion_timeout(&ipts->feature_event, msecs_to_jiffies(5000)); ++ if (ret == 0) { ++ dev_warn(ipts->dev, "GET_FEATURES timed out!\n"); ++ ret = -EIO; ++ goto out; ++ } ++ ++ if (!ipts->feature_report.address) { ++ ret = -EFAULT; ++ goto out; ++ } ++ ++ if (ipts->feature_report.size > size) { ++ ret = -ETOOSMALL; ++ goto out; ++ } ++ ++ ret = ipts->feature_report.size; ++ memcpy(buf, ipts->feature_report.address, ipts->feature_report.size); ++ ++out: ++ mutex_unlock(&ipts->feature_lock); ++ return ret; ++} ++ ++static int ipts_hid_set_feature(struct ipts_context *ipts, unsigned char reportnum, __u8 *buf, ++ size_t size, enum ipts_feedback_data_type type) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ buf[0] = reportnum; ++ ++ ret = ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, type, buf, size); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send hid2me feedback: %d\n", ret); ++ ++ return ret; ++} ++ ++static int ipts_hid_raw_request(struct hid_device *hid, unsigned char reportnum, __u8 *buf, ++ size_t size, unsigned char rtype, int reqtype) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ enum ipts_feedback_data_type type = IPTS_FEEDBACK_DATA_TYPE_VENDOR; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES; ++ else ++ return -EIO; ++ ++ // Implemente mode switching report for older devices without native HID support ++ if (type == IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES && reportnum == IPTS_HID_REPORT_SET_MODE) { ++ ret = ipts_hid_switch_mode(ipts, buf[1]); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to switch modes: %d\n", ret); ++ return ret; ++ } ++ } ++ ++ if (reqtype == HID_REQ_GET_REPORT) ++ return ipts_hid_get_feature(ipts, reportnum, buf, size, type); ++ else ++ return ipts_hid_set_feature(ipts, reportnum, buf, size, type); ++} ++ ++static int ipts_hid_output_report(struct hid_device *hid, __u8 *data, size_t size) ++{ ++ struct ipts_context *ipts = NULL; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ return ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, ++ IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT, data, size); ++} ++ ++static struct hid_ll_driver ipts_hid_driver = { ++ .start = ipts_hid_start, ++ .stop = ipts_hid_stop, ++ .open = ipts_hid_start, ++ .close = ipts_hid_stop, ++ .parse = ipts_hid_parse, ++ .raw_request = ipts_hid_raw_request, ++ .output_report = ipts_hid_output_report, ++}; ++ ++int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) ++{ ++ int ret = 0; ++ u8 *temp = NULL; ++ struct ipts_hid_header *frame = NULL; ++ struct ipts_data_header *header = NULL; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->hid) ++ return -ENODEV; ++ ++ header = (struct ipts_data_header *)ipts->resources.data[buffer].address; ++ ++ if (!header) ++ return -EFAULT; ++ ++ if (header->size == 0) ++ return 0; ++ ++ if (header->type == IPTS_DATA_TYPE_HID) ++ return hid_input_report(ipts->hid, HID_INPUT_REPORT, header->data, header->size, 1); ++ ++ if (header->type == IPTS_DATA_TYPE_GET_FEATURES) { ++ ipts->feature_report.address = header->data; ++ ipts->feature_report.size = header->size; ++ ++ complete_all(&ipts->feature_event); ++ return 0; ++ } ++ ++ if (header->type != IPTS_DATA_TYPE_FRAME) ++ return 0; ++ ++ if (header->size + 3 + sizeof(struct ipts_hid_header) > IPTS_HID_REPORT_DATA_SIZE) ++ return -ERANGE; ++ ++ temp = kzalloc(IPTS_HID_REPORT_DATA_SIZE, GFP_KERNEL); ++ if (!temp) ++ return -ENOMEM; ++ ++ /* ++ * Synthesize a HID report matching the devices that natively send HID reports ++ */ ++ temp[0] = IPTS_HID_REPORT_DATA; ++ ++ frame = (struct ipts_hid_header *)&temp[3]; ++ frame->type = IPTS_HID_FRAME_TYPE_RAW; ++ frame->size = header->size + sizeof(*frame); ++ ++ memcpy(frame->data, header->data, header->size); ++ ++ ret = hid_input_report(ipts->hid, HID_INPUT_REPORT, temp, IPTS_HID_REPORT_DATA_SIZE, 1); ++ kfree(temp); ++ ++ return ret; ++} ++ ++int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->hid) ++ return 0; ++ ++ ipts->hid = hid_allocate_device(); ++ if (IS_ERR(ipts->hid)) { ++ int err = PTR_ERR(ipts->hid); ++ ++ dev_err(ipts->dev, "Failed to allocate HID device: %d\n", err); ++ return err; ++ } ++ ++ ipts->hid->driver_data = ipts; ++ ipts->hid->dev.parent = ipts->dev; ++ ipts->hid->ll_driver = &ipts_hid_driver; ++ ++ ipts->hid->vendor = info.vendor; ++ ipts->hid->product = info.product; ++ ipts->hid->group = HID_GROUP_MULTITOUCH; ++ ++ snprintf(ipts->hid->name, sizeof(ipts->hid->name), "IPTS %04X:%04X", info.vendor, ++ info.product); ++ ++ ret = hid_add_device(ipts->hid); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to add HID device: %d\n", ret); ++ ipts_hid_free(ipts); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_hid_free(struct ipts_context *ipts) ++{ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->hid) ++ return 0; ++ ++ hid_destroy_device(ipts->hid); ++ ipts->hid = NULL; ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/hid.h b/drivers/hid/ipts/hid.h +new file mode 100644 +index 000000000000..62bf3cd48608 +--- /dev/null ++++ b/drivers/hid/ipts/hid.h +@@ -0,0 +1,22 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_HID_H ++#define IPTS_HID_H ++ ++#include ++ ++#include "context.h" ++#include "spec-device.h" ++ ++int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer); ++ ++int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info); ++int ipts_hid_free(struct ipts_context *ipts); ++ ++#endif /* IPTS_HID_H */ +diff --git a/drivers/hid/ipts/main.c b/drivers/hid/ipts/main.c +new file mode 100644 +index 000000000000..0f20c6c08c38 +--- /dev/null ++++ b/drivers/hid/ipts/main.c +@@ -0,0 +1,127 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "control.h" ++#include "mei.h" ++#include "receiver.h" ++#include "spec-device.h" ++ ++/* ++ * The MEI client ID for IPTS functionality. ++ */ ++#define IPTS_ID UUID_LE(0x3e8d0870, 0x271a, 0x4208, 0x8e, 0xb5, 0x9a, 0xcb, 0x94, 0x02, 0xae, 0x04) ++ ++static int ipts_set_dma_mask(struct mei_cl_device *cldev) ++{ ++ if (!cldev) ++ return -EFAULT; ++ ++ if (!dma_coerce_mask_and_coherent(&cldev->dev, DMA_BIT_MASK(64))) ++ return 0; ++ ++ return dma_coerce_mask_and_coherent(&cldev->dev, DMA_BIT_MASK(32)); ++} ++ ++static int ipts_probe(struct mei_cl_device *cldev, const struct mei_cl_device_id *id) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) ++ return -EFAULT; ++ ++ ret = ipts_set_dma_mask(cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to set DMA mask for IPTS: %d\n", ret); ++ return ret; ++ } ++ ++ ret = mei_cldev_enable(cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to enable MEI device: %d\n", ret); ++ return ret; ++ } ++ ++ ipts = devm_kzalloc(&cldev->dev, sizeof(*ipts), GFP_KERNEL); ++ if (!ipts) { ++ mei_cldev_disable(cldev); ++ return -ENOMEM; ++ } ++ ++ ret = ipts_mei_init(&ipts->mei, cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to init MEI bus logic: %d\n", ret); ++ return ret; ++ } ++ ++ ipts->dev = &cldev->dev; ++ ipts->mode = IPTS_MODE_EVENT; ++ ++ mutex_init(&ipts->feature_lock); ++ init_completion(&ipts->feature_event); ++ ++ mei_cldev_set_drvdata(cldev, ipts); ++ ++ ret = ipts_control_start(ipts); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to start IPTS: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static void ipts_remove(struct mei_cl_device *cldev) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) { ++ pr_err("MEI device is NULL!"); ++ return; ++ } ++ ++ ipts = mei_cldev_get_drvdata(cldev); ++ ++ ret = ipts_control_stop(ipts); ++ if (ret) ++ dev_err(&cldev->dev, "Failed to stop IPTS: %d\n", ret); ++ ++ mei_cldev_disable(cldev); ++} ++ ++static struct mei_cl_device_id ipts_device_id_table[] = { ++ { .uuid = IPTS_ID, .version = MEI_CL_VERSION_ANY }, ++ {}, ++}; ++MODULE_DEVICE_TABLE(mei, ipts_device_id_table); ++ ++static struct mei_cl_driver ipts_driver = { ++ .id_table = ipts_device_id_table, ++ .name = "ipts", ++ .probe = ipts_probe, ++ .remove = ipts_remove, ++}; ++module_mei_cl_driver(ipts_driver); ++ ++MODULE_DESCRIPTION("IPTS touchscreen driver"); ++MODULE_AUTHOR("Dorian Stoll "); ++MODULE_LICENSE("GPL"); +diff --git a/drivers/hid/ipts/mei.c b/drivers/hid/ipts/mei.c +new file mode 100644 +index 000000000000..26666fd99b0c +--- /dev/null ++++ b/drivers/hid/ipts/mei.c +@@ -0,0 +1,189 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "mei.h" ++ ++static void locked_list_add(struct list_head *new, struct list_head *head, ++ struct rw_semaphore *lock) ++{ ++ down_write(lock); ++ list_add(new, head); ++ up_write(lock); ++} ++ ++static void locked_list_del(struct list_head *entry, struct rw_semaphore *lock) ++{ ++ down_write(lock); ++ list_del(entry); ++ up_write(lock); ++} ++ ++static void ipts_mei_incoming(struct mei_cl_device *cldev) ++{ ++ ssize_t ret = 0; ++ struct ipts_mei_message *entry = NULL; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) { ++ pr_err("MEI device is NULL!"); ++ return; ++ } ++ ++ ipts = mei_cldev_get_drvdata(cldev); ++ if (!ipts) { ++ pr_err("IPTS driver context is NULL!"); ++ return; ++ } ++ ++ entry = devm_kzalloc(ipts->dev, sizeof(*entry), GFP_KERNEL); ++ if (!entry) ++ return; ++ ++ INIT_LIST_HEAD(&entry->list); ++ ++ do { ++ ret = mei_cldev_recv(cldev, (u8 *)&entry->rsp, sizeof(entry->rsp)); ++ } while (ret == -EINTR); ++ ++ if (ret < 0) { ++ dev_err(ipts->dev, "Error while reading response: %ld\n", ret); ++ return; ++ } ++ ++ if (ret == 0) { ++ dev_err(ipts->dev, "Received empty response\n"); ++ return; ++ } ++ ++ locked_list_add(&entry->list, &ipts->mei.messages, &ipts->mei.message_lock); ++ wake_up_all(&ipts->mei.message_queue); ++} ++ ++static int ipts_mei_search(struct ipts_mei *mei, enum ipts_command_code code, ++ struct ipts_response *rsp) ++{ ++ struct ipts_mei_message *entry = NULL; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!rsp) ++ return -EFAULT; ++ ++ down_read(&mei->message_lock); ++ ++ /* ++ * Iterate over the list of received messages, and check if there is one ++ * matching the requested command code. ++ */ ++ list_for_each_entry(entry, &mei->messages, list) { ++ if (entry->rsp.cmd == code) ++ break; ++ } ++ ++ up_read(&mei->message_lock); ++ ++ /* ++ * If entry is not the list head, this means that the loop above has been stopped early, ++ * and that we found a matching element. We drop the message from the list and return it. ++ */ ++ if (!list_entry_is_head(entry, &mei->messages, list)) { ++ locked_list_del(&entry->list, &mei->message_lock); ++ ++ *rsp = entry->rsp; ++ devm_kfree(&mei->cldev->dev, entry); ++ ++ return 0; ++ } ++ ++ return -EAGAIN; ++} ++ ++int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts_response *rsp, ++ u64 timeout) ++{ ++ int ret = 0; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ /* ++ * A timeout of 0 means check and return immideately. ++ */ ++ if (timeout == 0) ++ return ipts_mei_search(mei, code, rsp); ++ ++ /* ++ * A timeout of less than 0 means to wait forever. ++ */ ++ if (timeout < 0) { ++ wait_event(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0); ++ return 0; ++ } ++ ++ ret = wait_event_timeout(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0, ++ msecs_to_jiffies(timeout)); ++ ++ if (ret > 0) ++ return 0; ++ ++ return -EAGAIN; ++} ++ ++int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length) ++{ ++ int ret = 0; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!mei->cldev) ++ return -EFAULT; ++ ++ if (!data) ++ return -EFAULT; ++ ++ do { ++ ret = mei_cldev_send(mei->cldev, (u8 *)data, length); ++ } while (ret == -EINTR); ++ ++ if (ret < 0) ++ return ret; ++ ++ return 0; ++} ++ ++int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev) ++{ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!cldev) ++ return -EFAULT; ++ ++ mei->cldev = cldev; ++ ++ INIT_LIST_HEAD(&mei->messages); ++ init_waitqueue_head(&mei->message_queue); ++ init_rwsem(&mei->message_lock); ++ ++ mei_cldev_register_rx_cb(cldev, ipts_mei_incoming); ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/mei.h b/drivers/hid/ipts/mei.h +new file mode 100644 +index 000000000000..eadacae54c40 +--- /dev/null ++++ b/drivers/hid/ipts/mei.h +@@ -0,0 +1,67 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_MEI_H ++#define IPTS_MEI_H ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include "spec-device.h" ++ ++struct ipts_mei_message { ++ struct list_head list; ++ struct ipts_response rsp; ++}; ++ ++struct ipts_mei { ++ struct mei_cl_device *cldev; ++ ++ struct list_head messages; ++ ++ wait_queue_head_t message_queue; ++ struct rw_semaphore message_lock; ++}; ++ ++/* ++ * ipts_mei_recv() - Receive data from a MEI device. ++ * @mei: The IPTS MEI device context. ++ * @code: The IPTS command code to look for. ++ * @rsp: The address that the received data will be copied to. ++ * @timeout: How many milliseconds the function will wait at most. ++ * ++ * A negative timeout means to wait forever. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts_response *rsp, ++ u64 timeout); ++ ++/* ++ * ipts_mei_send() - Send data to a MEI device. ++ * @ipts: The IPTS MEI device context. ++ * @data: The data to send. ++ * @size: The size of the data. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length); ++ ++/* ++ * ipts_mei_init() - Initialize the MEI device context. ++ * @mei: The MEI device context to initialize. ++ * @cldev: The MEI device the context will be bound to. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev); ++ ++#endif /* IPTS_MEI_H */ +diff --git a/drivers/hid/ipts/receiver.c b/drivers/hid/ipts/receiver.c +new file mode 100644 +index 000000000000..77234f9e0e17 +--- /dev/null ++++ b/drivers/hid/ipts/receiver.c +@@ -0,0 +1,249 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "control.h" ++#include "hid.h" ++#include "resources.h" ++#include "spec-device.h" ++#include "thread.h" ++ ++static void ipts_receiver_next_doorbell(struct ipts_context *ipts) ++{ ++ u32 *doorbell = (u32 *)ipts->resources.doorbell.address; ++ *doorbell = *doorbell + 1; ++} ++ ++static u32 ipts_receiver_current_doorbell(struct ipts_context *ipts) ++{ ++ u32 *doorbell = (u32 *)ipts->resources.doorbell.address; ++ return *doorbell; ++} ++ ++static void ipts_receiver_backoff(time64_t last, u32 n) ++{ ++ /* ++ * If the last change was less than n seconds ago, ++ * sleep for a shorter period so that new data can be ++ * processed quickly. If there was no change for more than ++ * n seconds, sleep longer to avoid wasting CPU cycles. ++ */ ++ if (last + n > ktime_get_seconds()) ++ msleep(20); ++ else ++ msleep(200); ++} ++ ++static int ipts_receiver_event_loop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ u32 buffer = 0; ++ ++ struct ipts_context *ipts = NULL; ++ time64_t last = ktime_get_seconds(); ++ ++ if (!thread) ++ return -EFAULT; ++ ++ ipts = thread->data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "IPTS running in event mode\n"); ++ ++ while (!ipts_thread_should_stop(thread)) { ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_control_wait_data(ipts, false); ++ if (ret == -EAGAIN) ++ break; ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ continue; ++ } ++ ++ buffer = ipts_receiver_current_doorbell(ipts) % IPTS_BUFFERS; ++ ipts_receiver_next_doorbell(ipts); ++ ++ ret = ipts_hid_input_data(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to process buffer: %d\n", ret); ++ ++ ret = ipts_control_refill_buffer(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send feedback: %d\n", ret); ++ ++ ret = ipts_control_request_data(ipts); ++ if (ret) ++ dev_err(ipts->dev, "Failed to request data: %d\n", ret); ++ ++ last = ktime_get_seconds(); ++ } ++ ++ ipts_receiver_backoff(last, 5); ++ } ++ ++ ret = ipts_control_request_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request flush: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_wait_data(ipts, true); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ ret = ipts_control_wait_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ return 0; ++} ++ ++static int ipts_receiver_doorbell_loop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ u32 buffer = 0; ++ ++ u32 doorbell = 0; ++ u32 lastdb = 0; ++ ++ struct ipts_context *ipts = NULL; ++ time64_t last = ktime_get_seconds(); ++ ++ if (!thread) ++ return -EFAULT; ++ ++ ipts = thread->data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "IPTS running in doorbell mode\n"); ++ ++ while (true) { ++ if (ipts_thread_should_stop(thread)) { ++ ret = ipts_control_request_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request flush: %d\n", ret); ++ return ret; ++ } ++ } ++ ++ doorbell = ipts_receiver_current_doorbell(ipts); ++ ++ /* ++ * After filling up one of the data buffers, IPTS will increment ++ * the doorbell. The value of the doorbell stands for the *next* ++ * buffer that IPTS is going to fill. ++ */ ++ while (lastdb != doorbell) { ++ buffer = lastdb % IPTS_BUFFERS; ++ ++ ret = ipts_hid_input_data(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to process buffer: %d\n", ret); ++ ++ ret = ipts_control_refill_buffer(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send feedback: %d\n", ret); ++ ++ last = ktime_get_seconds(); ++ lastdb++; ++ } ++ ++ if (ipts_thread_should_stop(thread)) ++ break; ++ ++ ipts_receiver_backoff(last, 5); ++ } ++ ++ ret = ipts_control_wait_data(ipts, true); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ ret = ipts_control_wait_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ return 0; ++} ++ ++int ipts_receiver_start(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->mode == IPTS_MODE_EVENT) { ++ ret = ipts_thread_start(&ipts->receiver_loop, ipts_receiver_event_loop, ipts, ++ "ipts_event"); ++ } else if (ipts->mode == IPTS_MODE_DOORBELL) { ++ ret = ipts_thread_start(&ipts->receiver_loop, ipts_receiver_doorbell_loop, ipts, ++ "ipts_doorbell"); ++ } else { ++ ret = -EINVAL; ++ } ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to start receiver loop: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_receiver_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_thread_stop(&ipts->receiver_loop); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to stop receiver loop: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/receiver.h b/drivers/hid/ipts/receiver.h +new file mode 100644 +index 000000000000..96070f34fbca +--- /dev/null ++++ b/drivers/hid/ipts/receiver.h +@@ -0,0 +1,17 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_RECEIVER_H ++#define IPTS_RECEIVER_H ++ ++#include "context.h" ++ ++int ipts_receiver_start(struct ipts_context *ipts); ++int ipts_receiver_stop(struct ipts_context *ipts); ++ ++#endif /* IPTS_RECEIVER_H */ +diff --git a/drivers/hid/ipts/resources.c b/drivers/hid/ipts/resources.c +new file mode 100644 +index 000000000000..80ba5885bb55 +--- /dev/null ++++ b/drivers/hid/ipts/resources.c +@@ -0,0 +1,108 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++ ++#include "resources.h" ++#include "spec-device.h" ++ ++static int ipts_resources_alloc_buffer(struct ipts_buffer *buffer, struct device *dev, size_t size) ++{ ++ if (!buffer) ++ return -EFAULT; ++ ++ if (buffer->address) ++ return 0; ++ ++ buffer->address = dma_alloc_coherent(dev, size, &buffer->dma_address, GFP_KERNEL); ++ ++ if (!buffer->address) ++ return -ENOMEM; ++ ++ buffer->size = size; ++ buffer->device = dev; ++ ++ return 0; ++} ++ ++static void ipts_resources_free_buffer(struct ipts_buffer *buffer) ++{ ++ if (!buffer->address) ++ return; ++ ++ dma_free_coherent(buffer->device, buffer->size, buffer->address, buffer->dma_address); ++ ++ buffer->address = NULL; ++ buffer->size = 0; ++ ++ buffer->dma_address = 0; ++ buffer->device = NULL; ++} ++ ++int ipts_resources_init(struct ipts_resources *res, struct device *dev, size_t ds, size_t fs) ++{ ++ int ret = 0; ++ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_resources_alloc_buffer(&res->data[i], dev, ds); ++ if (ret) ++ goto err; ++ } ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_resources_alloc_buffer(&res->feedback[i], dev, fs); ++ if (ret) ++ goto err; ++ } ++ ++ ret = ipts_resources_alloc_buffer(&res->doorbell, dev, sizeof(u32)); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->workqueue, dev, sizeof(u32)); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->hid2me, dev, fs); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->descriptor, dev, ds + 8); ++ if (ret) ++ goto err; ++ ++ return 0; ++ ++err: ++ ++ ipts_resources_free(res); ++ return ret; ++} ++ ++int ipts_resources_free(struct ipts_resources *res) ++{ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) ++ ipts_resources_free_buffer(&res->data[i]); ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) ++ ipts_resources_free_buffer(&res->feedback[i]); ++ ++ ipts_resources_free_buffer(&res->doorbell); ++ ipts_resources_free_buffer(&res->workqueue); ++ ipts_resources_free_buffer(&res->hid2me); ++ ipts_resources_free_buffer(&res->descriptor); ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/resources.h b/drivers/hid/ipts/resources.h +new file mode 100644 +index 000000000000..6cbb24a8a054 +--- /dev/null ++++ b/drivers/hid/ipts/resources.h +@@ -0,0 +1,39 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_RESOURCES_H ++#define IPTS_RESOURCES_H ++ ++#include ++#include ++ ++#include "spec-device.h" ++ ++struct ipts_buffer { ++ u8 *address; ++ size_t size; ++ ++ dma_addr_t dma_address; ++ struct device *device; ++}; ++ ++struct ipts_resources { ++ struct ipts_buffer data[IPTS_BUFFERS]; ++ struct ipts_buffer feedback[IPTS_BUFFERS]; ++ ++ struct ipts_buffer doorbell; ++ struct ipts_buffer workqueue; ++ struct ipts_buffer hid2me; ++ ++ struct ipts_buffer descriptor; ++}; ++ ++int ipts_resources_init(struct ipts_resources *res, struct device *dev, size_t ds, size_t fs); ++int ipts_resources_free(struct ipts_resources *res); ++ ++#endif /* IPTS_RESOURCES_H */ +diff --git a/drivers/hid/ipts/spec-data.h b/drivers/hid/ipts/spec-data.h +new file mode 100644 +index 000000000000..e8dd98895a7e +--- /dev/null ++++ b/drivers/hid/ipts/spec-data.h +@@ -0,0 +1,100 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_DATA_H ++#define IPTS_SPEC_DATA_H ++ ++#include ++#include ++ ++/** ++ * enum ipts_feedback_cmd_type - Commands that can be executed on the sensor through feedback. ++ */ ++enum ipts_feedback_cmd_type { ++ IPTS_FEEDBACK_CMD_TYPE_NONE = 0, ++ IPTS_FEEDBACK_CMD_TYPE_SOFT_RESET = 1, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_ARMED = 2, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_SENSING = 3, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_SLEEP = 4, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_DOZE = 5, ++ IPTS_FEEDBACK_CMD_TYPE_HARD_RESET = 6, ++}; ++ ++/** ++ * enum ipts_feedback_data_type - Defines what data a feedback buffer contains. ++ * @IPTS_FEEDBACK_DATA_TYPE_VENDOR: The buffer contains vendor specific feedback. ++ * @IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES: The buffer contains a HID set features report. ++ * @IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES: The buffer contains a HID get features report. ++ * @IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT: The buffer contains a HID output report. ++ * @IPTS_FEEDBACK_DATA_TYPE_STORE_DATA: The buffer contains calibration data for the sensor. ++ */ ++enum ipts_feedback_data_type { ++ IPTS_FEEDBACK_DATA_TYPE_VENDOR = 0, ++ IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES = 1, ++ IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES = 2, ++ IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT = 3, ++ IPTS_FEEDBACK_DATA_TYPE_STORE_DATA = 4, ++}; ++ ++/** ++ * struct ipts_feedback_header - Header that is prefixed to the data in a feedback buffer. ++ * @cmd_type: A command that should be executed on the sensor. ++ * @size: The size of the payload to be written. ++ * @buffer: The ID of the buffer that contains this feedback data. ++ * @protocol: The protocol version of the EDS. ++ * @data_type: The type of data that the buffer contains. ++ * @spi_offset: The offset at which to write the payload data to the sensor. ++ * @payload: Payload for the feedback command, or 0 if no payload is sent. ++ */ ++struct ipts_feedback_header { ++ enum ipts_feedback_cmd_type cmd_type; ++ u32 size; ++ u32 buffer; ++ u32 protocol; ++ enum ipts_feedback_data_type data_type; ++ u32 spi_offset; ++ u8 reserved[40]; ++ u8 payload[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_feedback_header) == 64); ++ ++/** ++ * enum ipts_data_type - Defines what type of data a buffer contains. ++ * @IPTS_DATA_TYPE_FRAME: Raw data frame. ++ * @IPTS_DATA_TYPE_ERROR: Error data. ++ * @IPTS_DATA_TYPE_VENDOR: Vendor specific data. ++ * @IPTS_DATA_TYPE_HID: A HID report. ++ * @IPTS_DATA_TYPE_GET_FEATURES: The response to a GET_FEATURES HID2ME command. ++ */ ++enum ipts_data_type { ++ IPTS_DATA_TYPE_FRAME = 0x00, ++ IPTS_DATA_TYPE_ERROR = 0x01, ++ IPTS_DATA_TYPE_VENDOR = 0x02, ++ IPTS_DATA_TYPE_HID = 0x03, ++ IPTS_DATA_TYPE_GET_FEATURES = 0x04, ++ IPTS_DATA_TYPE_DESCRIPTOR = 0x05, ++}; ++ ++/** ++ * struct ipts_data_header - Header that is prefixed to the data in a data buffer. ++ * @type: What data the buffer contains. ++ * @size: How much data the buffer contains. ++ * @buffer: Which buffer the data is in. ++ */ ++struct ipts_data_header { ++ enum ipts_data_type type; ++ u32 size; ++ u32 buffer; ++ u8 reserved[52]; ++ u8 data[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_data_header) == 64); ++ ++#endif /* IPTS_SPEC_DATA_H */ +diff --git a/drivers/hid/ipts/spec-device.h b/drivers/hid/ipts/spec-device.h +new file mode 100644 +index 000000000000..93f673d981f7 +--- /dev/null ++++ b/drivers/hid/ipts/spec-device.h +@@ -0,0 +1,285 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_DEVICE_H ++#define IPTS_SPEC_DEVICE_H ++ ++#include ++#include ++ ++/* ++ * The amount of buffers that IPTS can use for data transfer. ++ */ ++#define IPTS_BUFFERS 16 ++ ++/* ++ * The buffer ID that is used for HID2ME feedback ++ */ ++#define IPTS_HID2ME_BUFFER IPTS_BUFFERS ++ ++/** ++ * enum ipts_command - Commands that can be sent to the IPTS hardware. ++ * @IPTS_CMD_GET_DEVICE_INFO: Retrieves vendor information from the device. ++ * @IPTS_CMD_SET_MODE: Changes the mode that the device will operate in. ++ * @IPTS_CMD_SET_MEM_WINDOW: Configures memory buffers for passing data between device and driver. ++ * @IPTS_CMD_QUIESCE_IO: Stops the data flow from the device to the driver. ++ * @IPTS_CMD_READY_FOR_DATA: Informs the device that the driver is ready to receive data. ++ * @IPTS_CMD_FEEDBACK: Informs the device that a buffer was processed and can be refilled. ++ * @IPTS_CMD_CLEAR_MEM_WINDOW: Stops the data flow and clears the buffer addresses on the device. ++ * @IPTS_CMD_RESET_SENSOR: Resets the sensor to its default state. ++ * @IPTS_CMD_GET_DESCRIPTOR: Retrieves the HID descriptor of the device. ++ */ ++enum ipts_command_code { ++ IPTS_CMD_GET_DEVICE_INFO = 0x01, ++ IPTS_CMD_SET_MODE = 0x02, ++ IPTS_CMD_SET_MEM_WINDOW = 0x03, ++ IPTS_CMD_QUIESCE_IO = 0x04, ++ IPTS_CMD_READY_FOR_DATA = 0x05, ++ IPTS_CMD_FEEDBACK = 0x06, ++ IPTS_CMD_CLEAR_MEM_WINDOW = 0x07, ++ IPTS_CMD_RESET_SENSOR = 0x0B, ++ IPTS_CMD_GET_DESCRIPTOR = 0x0F, ++}; ++ ++/** ++ * enum ipts_status - Possible status codes returned by the IPTS device. ++ * @IPTS_STATUS_SUCCESS: Operation completed successfully. ++ * @IPTS_STATUS_INVALID_PARAMS: Command contained an invalid payload. ++ * @IPTS_STATUS_ACCESS_DENIED: ME could not validate a buffer address. ++ * @IPTS_STATUS_CMD_SIZE_ERROR: Command contains an invalid payload. ++ * @IPTS_STATUS_NOT_READY: Buffer addresses have not been set. ++ * @IPTS_STATUS_REQUEST_OUTSTANDING: There is an outstanding command of the same type. ++ * @IPTS_STATUS_NO_SENSOR_FOUND: No sensor could be found. ++ * @IPTS_STATUS_OUT_OF_MEMORY: Not enough free memory for requested operation. ++ * @IPTS_STATUS_INTERNAL_ERROR: An unexpected error occurred. ++ * @IPTS_STATUS_SENSOR_DISABLED: The sensor has been disabled and must be reinitialized. ++ * @IPTS_STATUS_COMPAT_CHECK_FAIL: Compatibility revision check between sensor and ME failed. ++ * The host can ignore this error and attempt to continue. ++ * @IPTS_STATUS_SENSOR_EXPECTED_RESET: The sensor went through a reset initiated by the driver. ++ * @IPTS_STATUS_SENSOR_UNEXPECTED_RESET: The sensor went through an unexpected reset. ++ * @IPTS_STATUS_RESET_FAILED: Requested sensor reset failed to complete. ++ * @IPTS_STATUS_TIMEOUT: The operation timed out. ++ * @IPTS_STATUS_TEST_MODE_FAIL: Test mode pattern did not match expected values. ++ * @IPTS_STATUS_SENSOR_FAIL_FATAL: The sensor reported an error during reset sequence. ++ * Further progress is not possible. ++ * @IPTS_STATUS_SENSOR_FAIL_NONFATAL: The sensor reported an error during reset sequence. ++ * The driver can attempt to continue. ++ * @IPTS_STATUS_INVALID_DEVICE_CAPS: The device reported invalid capabilities. ++ * @IPTS_STATUS_QUIESCE_IO_IN_PROGRESS: Command cannot be completed until Quiesce IO is done. ++ */ ++enum ipts_status { ++ IPTS_STATUS_SUCCESS = 0x00, ++ IPTS_STATUS_INVALID_PARAMS = 0x01, ++ IPTS_STATUS_ACCESS_DENIED = 0x02, ++ IPTS_STATUS_CMD_SIZE_ERROR = 0x03, ++ IPTS_STATUS_NOT_READY = 0x04, ++ IPTS_STATUS_REQUEST_OUTSTANDING = 0x05, ++ IPTS_STATUS_NO_SENSOR_FOUND = 0x06, ++ IPTS_STATUS_OUT_OF_MEMORY = 0x07, ++ IPTS_STATUS_INTERNAL_ERROR = 0x08, ++ IPTS_STATUS_SENSOR_DISABLED = 0x09, ++ IPTS_STATUS_COMPAT_CHECK_FAIL = 0x0A, ++ IPTS_STATUS_SENSOR_EXPECTED_RESET = 0x0B, ++ IPTS_STATUS_SENSOR_UNEXPECTED_RESET = 0x0C, ++ IPTS_STATUS_RESET_FAILED = 0x0D, ++ IPTS_STATUS_TIMEOUT = 0x0E, ++ IPTS_STATUS_TEST_MODE_FAIL = 0x0F, ++ IPTS_STATUS_SENSOR_FAIL_FATAL = 0x10, ++ IPTS_STATUS_SENSOR_FAIL_NONFATAL = 0x11, ++ IPTS_STATUS_INVALID_DEVICE_CAPS = 0x12, ++ IPTS_STATUS_QUIESCE_IO_IN_PROGRESS = 0x13, ++}; ++ ++/** ++ * struct ipts_command - Message that is sent to the device for calling a command. ++ * @cmd: The command that will be called. ++ * @payload: Payload containing parameters for the called command. ++ */ ++struct ipts_command { ++ enum ipts_command_code cmd; ++ u8 payload[320]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_command) == 324); ++ ++/** ++ * enum ipts_mode - Configures what data the device produces and how its sent. ++ * @IPTS_MODE_EVENT: The device will send an event once a buffer was filled. ++ * Older devices will return singletouch data in this mode. ++ * @IPTS_MODE_DOORBELL: The device will notify the driver by incrementing the doorbell value. ++ * Older devices will return multitouch data in this mode. ++ */ ++enum ipts_mode { ++ IPTS_MODE_EVENT = 0x00, ++ IPTS_MODE_DOORBELL = 0x01, ++}; ++ ++/** ++ * struct ipts_set_mode - Payload for the SET_MODE command. ++ * @mode: Changes the mode that IPTS will operate in. ++ */ ++struct ipts_set_mode { ++ enum ipts_mode mode; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_set_mode) == 16); ++ ++#define IPTS_WORKQUEUE_SIZE 8192 ++#define IPTS_WORKQUEUE_ITEM_SIZE 16 ++ ++/** ++ * struct ipts_mem_window - Payload for the SET_MEM_WINDOW command. ++ * @data_addr_lower: Lower 32 bits of the data buffer addresses. ++ * @data_addr_upper: Upper 32 bits of the data buffer addresses. ++ * @workqueue_addr_lower: Lower 32 bits of the workqueue buffer address. ++ * @workqueue_addr_upper: Upper 32 bits of the workqueue buffer address. ++ * @doorbell_addr_lower: Lower 32 bits of the doorbell buffer address. ++ * @doorbell_addr_upper: Upper 32 bits of the doorbell buffer address. ++ * @feedbackaddr_lower: Lower 32 bits of the feedback buffer addresses. ++ * @feedbackaddr_upper: Upper 32 bits of the feedback buffer addresses. ++ * @hid2me_addr_lower: Lower 32 bits of the hid2me buffer address. ++ * @hid2me_addr_upper: Upper 32 bits of the hid2me buffer address. ++ * @hid2me_size: Size of the hid2me feedback buffer. ++ * @workqueue_item_size: Magic value. Must be 16. ++ * @workqueue_size: Magic value. Must be 8192. ++ * ++ * The workqueue related items in this struct are required for using ++ * GuC submission with binary processing firmware. Since this driver does ++ * not use GuC submission and instead exports raw data to userspace, these ++ * items are not actually used, but they need to be allocated and passed ++ * to the device, otherwise initialization will fail. ++ */ ++struct ipts_mem_window { ++ u32 data_addr_lower[IPTS_BUFFERS]; ++ u32 data_addr_upper[IPTS_BUFFERS]; ++ u32 workqueue_addr_lower; ++ u32 workqueue_addr_upper; ++ u32 doorbell_addr_lower; ++ u32 doorbell_addr_upper; ++ u32 feedback_addr_lower[IPTS_BUFFERS]; ++ u32 feedback_addr_upper[IPTS_BUFFERS]; ++ u32 hid2me_addr_lower; ++ u32 hid2me_addr_upper; ++ u32 hid2me_size; ++ u8 reserved1; ++ u8 workqueue_item_size; ++ u16 workqueue_size; ++ u8 reserved[32]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_mem_window) == 320); ++ ++/** ++ * struct ipts_quiesce_io - Payload for the QUIESCE_IO command. ++ */ ++struct ipts_quiesce_io { ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_quiesce_io) == 12); ++ ++/** ++ * struct ipts_feedback - Payload for the FEEDBACK command. ++ * @buffer: The buffer that the device should refill. ++ */ ++struct ipts_feedback { ++ u32 buffer; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_feedback) == 16); ++ ++/** ++ * enum ipts_reset_type - Possible ways of resetting the device. ++ * @IPTS_RESET_TYPE_HARD: Perform hardware reset using GPIO pin. ++ * @IPTS_RESET_TYPE_SOFT: Perform software reset using SPI command. ++ */ ++enum ipts_reset_type { ++ IPTS_RESET_TYPE_HARD = 0x00, ++ IPTS_RESET_TYPE_SOFT = 0x01, ++}; ++ ++/** ++ * struct ipts_reset - Payload for the RESET_SENSOR command. ++ * @type: How the device should get reset. ++ */ ++struct ipts_reset_sensor { ++ enum ipts_reset_type type; ++ u8 reserved[4]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_reset_sensor) == 8); ++ ++/** ++ * struct ipts_get_descriptor - Payload for the GET_DESCRIPTOR command. ++ * @addr_lower: The lower 32 bits of the descriptor buffer address. ++ * @addr_upper: The upper 32 bits of the descriptor buffer address. ++ * @magic: A magic value. Must be 8. ++ */ ++struct ipts_get_descriptor { ++ u32 addr_lower; ++ u32 addr_upper; ++ u32 magic; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_get_descriptor) == 24); ++ ++/* ++ * The type of a response is indicated by a ++ * command code, with the most significant bit flipped to 1. ++ */ ++#define IPTS_RSP_BIT BIT(31) ++ ++/** ++ * struct ipts_response - Data returned from the device in response to a command. ++ * @cmd: The command that this response answers (IPTS_RSP_BIT will be 1). ++ * @status: The return code of the command. ++ * @payload: The data that was produced by the command. ++ */ ++struct ipts_response { ++ enum ipts_command_code cmd; ++ enum ipts_status status; ++ u8 payload[80]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_response) == 88); ++ ++/** ++ * struct ipts_device_info - Vendor information of the IPTS device. ++ * @vendor: Vendor ID of this device. ++ * @product: Product ID of this device. ++ * @hw_version: Hardware revision of this device. ++ * @fw_version: Firmware revision of this device. ++ * @data_size: Requested size for a data buffer. ++ * @feedback_size: Requested size for a feedback buffer. ++ * @mode: Mode that the device currently operates in. ++ * @max_contacts: Maximum amount of concurrent touches the sensor can process. ++ */ ++struct ipts_device_info { ++ u16 vendor; ++ u16 product; ++ u32 hw_version; ++ u32 fw_version; ++ u32 data_size; ++ u32 feedback_size; ++ enum ipts_mode mode; ++ u8 max_contacts; ++ u8 reserved1[3]; ++ u8 sensor_min_eds; ++ u8 sensor_maj_eds; ++ u8 me_min_eds; ++ u8 me_maj_eds; ++ u8 intf_eds; ++ u8 reserved2[11]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_device_info) == 44); ++ ++#endif /* IPTS_SPEC_DEVICE_H */ +diff --git a/drivers/hid/ipts/spec-hid.h b/drivers/hid/ipts/spec-hid.h +new file mode 100644 +index 000000000000..ea70f29ff00c +--- /dev/null ++++ b/drivers/hid/ipts/spec-hid.h +@@ -0,0 +1,35 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_HID_H ++#define IPTS_SPEC_HID_H ++ ++#include ++#include ++ ++/* ++ * Made-up type for passing raw IPTS data in a HID report. ++ */ ++#define IPTS_HID_FRAME_TYPE_RAW 0xEE ++ ++/** ++ * struct ipts_hid_frame - Header that is prefixed to raw IPTS data wrapped in a HID report. ++ * @size: Size of the data inside the report, including this header. ++ * @type: What type of data does this report contain. ++ */ ++struct ipts_hid_header { ++ u32 size; ++ u8 reserved1; ++ u8 type; ++ u8 reserved2; ++ u8 data[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_hid_header) == 7); ++ ++#endif /* IPTS_SPEC_HID_H */ +diff --git a/drivers/hid/ipts/thread.c b/drivers/hid/ipts/thread.c +new file mode 100644 +index 000000000000..8b46f775c107 +--- /dev/null ++++ b/drivers/hid/ipts/thread.c +@@ -0,0 +1,85 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include "thread.h" ++ ++bool ipts_thread_should_stop(struct ipts_thread *thread) ++{ ++ if (!thread) ++ return false; ++ ++ return READ_ONCE(thread->should_stop); ++} ++ ++static int ipts_thread_runner(void *data) ++{ ++ int ret = 0; ++ struct ipts_thread *thread = data; ++ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!thread->threadfn) ++ return -EFAULT; ++ ++ ret = thread->threadfn(thread); ++ complete_all(&thread->done); ++ ++ return ret; ++} ++ ++int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), ++ void *data, const char *name) ++{ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!threadfn) ++ return -EFAULT; ++ ++ init_completion(&thread->done); ++ ++ thread->data = data; ++ thread->should_stop = false; ++ thread->threadfn = threadfn; ++ ++ thread->thread = kthread_run(ipts_thread_runner, thread, name); ++ return PTR_ERR_OR_ZERO(thread->thread); ++} ++ ++int ipts_thread_stop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!thread->thread) ++ return 0; ++ ++ WRITE_ONCE(thread->should_stop, true); ++ ++ /* ++ * Make sure that the write has gone through before waiting. ++ */ ++ wmb(); ++ ++ wait_for_completion(&thread->done); ++ ret = kthread_stop(thread->thread); ++ ++ thread->thread = NULL; ++ thread->data = NULL; ++ thread->threadfn = NULL; ++ ++ return ret; ++} +diff --git a/drivers/hid/ipts/thread.h b/drivers/hid/ipts/thread.h +new file mode 100644 +index 000000000000..a314843599fc +--- /dev/null ++++ b/drivers/hid/ipts/thread.h +@@ -0,0 +1,60 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_THREAD_H ++#define IPTS_THREAD_H ++ ++#include ++#include ++#include ++ ++/* ++ * This wrapper over kthread is necessary, because calling kthread_stop makes it impossible ++ * to issue MEI commands from that thread while it shuts itself down. By using a custom ++ * boolean variable and a completion object, we can call kthread_stop only when the thread ++ * already finished all of its work and has returned. ++ */ ++struct ipts_thread { ++ struct task_struct *thread; ++ ++ bool should_stop; ++ struct completion done; ++ ++ void *data; ++ int (*threadfn)(struct ipts_thread *thread); ++}; ++ ++/* ++ * ipts_thread_should_stop() - Returns true if the thread is asked to terminate. ++ * @thread: The current thread. ++ * ++ * Returns: true if the thread should stop, false if not. ++ */ ++bool ipts_thread_should_stop(struct ipts_thread *thread); ++ ++/* ++ * ipts_thread_start() - Starts an IPTS thread. ++ * @thread: The thread to initialize and start. ++ * @threadfn: The function to execute. ++ * @data: An argument that will be passed to threadfn. ++ * @name: The name of the new thread. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), ++ void *data, const char name[]); ++ ++/* ++ * ipts_thread_stop() - Asks the thread to terminate and waits until it has finished. ++ * @thread: The thread that should stop. ++ * ++ * Returns: The return value of the thread function. ++ */ ++int ipts_thread_stop(struct ipts_thread *thread); ++ ++#endif /* IPTS_THREAD_H */ +diff --git a/drivers/hid/ithc/Kbuild b/drivers/hid/ithc/Kbuild +new file mode 100644 +index 000000000000..aea83f2ac07b +--- /dev/null ++++ b/drivers/hid/ithc/Kbuild +@@ -0,0 +1,6 @@ ++obj-$(CONFIG_HID_ITHC) := ithc.o ++ ++ithc-objs := ithc-main.o ithc-regs.o ithc-dma.o ithc-debug.o ++ ++ccflags-y := -std=gnu11 -Wno-declaration-after-statement ++ +diff --git a/drivers/hid/ithc/Kconfig b/drivers/hid/ithc/Kconfig +new file mode 100644 +index 000000000000..ede713023609 +--- /dev/null ++++ b/drivers/hid/ithc/Kconfig +@@ -0,0 +1,12 @@ ++config HID_ITHC ++ tristate "Intel Touch Host Controller" ++ depends on PCI ++ depends on HID ++ help ++ Say Y here if your system has a touchscreen using Intels ++ Touch Host Controller (ITHC / IPTS) technology. ++ ++ If unsure say N. ++ ++ To compile this driver as a module, choose M here: the ++ module will be called ithc. +diff --git a/drivers/hid/ithc/ithc-debug.c b/drivers/hid/ithc/ithc-debug.c +new file mode 100644 +index 000000000000..57bf125c45bd +--- /dev/null ++++ b/drivers/hid/ithc/ithc-debug.c +@@ -0,0 +1,96 @@ ++#include "ithc.h" ++ ++void ithc_log_regs(struct ithc *ithc) { ++ if (!ithc->prev_regs) return; ++ u32 __iomem *cur = (__iomem void*)ithc->regs; ++ u32 *prev = (void*)ithc->prev_regs; ++ for (int i = 1024; i < sizeof *ithc->regs / 4; i++) { ++ u32 x = readl(cur + i); ++ if (x != prev[i]) { ++ pci_info(ithc->pci, "reg %04x: %08x -> %08x\n", i * 4, prev[i], x); ++ prev[i] = x; ++ } ++ } ++} ++ ++static ssize_t ithc_debugfs_cmd_write(struct file *f, const char __user *buf, size_t len, loff_t *offset) { ++ struct ithc *ithc = file_inode(f)->i_private; ++ char cmd[256]; ++ if (!ithc || !ithc->pci) return -ENODEV; ++ if (!len) return -EINVAL; ++ if (len >= sizeof cmd) return -EINVAL; ++ if (copy_from_user(cmd, buf, len)) return -EFAULT; ++ cmd[len] = 0; ++ if (cmd[len-1] == '\n') cmd[len-1] = 0; ++ pci_info(ithc->pci, "debug command: %s\n", cmd); ++ u32 n = 0; ++ const char *s = cmd + 1; ++ u32 a[32]; ++ while (*s && *s != '\n') { ++ if (n >= ARRAY_SIZE(a)) return -EINVAL; ++ if (*s++ != ' ') return -EINVAL; ++ char *e; ++ a[n++] = simple_strtoul(s, &e, 0); ++ if (e == s) return -EINVAL; ++ s = e; ++ } ++ ithc_log_regs(ithc); ++ switch(cmd[0]) { ++ case 'x': // reset ++ ithc_reset(ithc); ++ break; ++ case 'w': // write register: offset mask value ++ if (n != 3 || (a[0] & 3)) return -EINVAL; ++ pci_info(ithc->pci, "debug write 0x%04x = 0x%08x (mask 0x%08x)\n", a[0], a[2], a[1]); ++ bitsl(((__iomem u32 *)ithc->regs) + a[0] / 4, a[1], a[2]); ++ break; ++ case 'r': // read register: offset ++ if (n != 1 || (a[0] & 3)) return -EINVAL; ++ pci_info(ithc->pci, "debug read 0x%04x = 0x%08x\n", a[0], readl(((__iomem u32 *)ithc->regs) + a[0] / 4)); ++ break; ++ case 's': // spi command: cmd offset len data... ++ // read config: s 4 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ++ // set touch cfg: s 6 12 4 XX ++ if (n < 3 || a[2] > (n - 3) * 4) return -EINVAL; ++ pci_info(ithc->pci, "debug spi command %u with %u bytes of data\n", a[0], a[2]); ++ if (!CHECK(ithc_spi_command, ithc, a[0], a[1], a[2], a + 3)) ++ for (u32 i = 0; i < (a[2] + 3) / 4; i++) pci_info(ithc->pci, "resp %u = 0x%08x\n", i, a[3+i]); ++ break; ++ case 'd': // dma command: cmd len data... ++ // get report descriptor: d 7 8 0 0 ++ // enable multitouch: d 3 2 0x0105 ++ if (n < 2 || a[1] > (n - 2) * 4) return -EINVAL; ++ pci_info(ithc->pci, "debug dma command %u with %u bytes of data\n", a[0], a[1]); ++ if (ithc_dma_tx(ithc, a[0], a[1], a + 2)) pci_err(ithc->pci, "dma tx failed\n"); ++ break; ++ default: ++ return -EINVAL; ++ } ++ ithc_log_regs(ithc); ++ return len; ++} ++ ++static const struct file_operations ithc_debugfops_cmd = { ++ .owner = THIS_MODULE, ++ .write = ithc_debugfs_cmd_write, ++}; ++ ++static void ithc_debugfs_devres_release(struct device *dev, void *res) { ++ struct dentry **dbgm = res; ++ if (*dbgm) debugfs_remove_recursive(*dbgm); ++} ++ ++int ithc_debug_init(struct ithc *ithc) { ++ struct dentry **dbgm = devres_alloc(ithc_debugfs_devres_release, sizeof *dbgm, GFP_KERNEL); ++ if (!dbgm) return -ENOMEM; ++ devres_add(&ithc->pci->dev, dbgm); ++ struct dentry *dbg = debugfs_create_dir(DEVNAME, NULL); ++ if (IS_ERR(dbg)) return PTR_ERR(dbg); ++ *dbgm = dbg; ++ ++ struct dentry *cmd = debugfs_create_file("cmd", 0220, dbg, ithc, &ithc_debugfops_cmd); ++ if (IS_ERR(cmd)) return PTR_ERR(cmd); ++ ++ return 0; ++} ++ +diff --git a/drivers/hid/ithc/ithc-dma.c b/drivers/hid/ithc/ithc-dma.c +new file mode 100644 +index 000000000000..7e89b3496918 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-dma.c +@@ -0,0 +1,258 @@ ++#include "ithc.h" ++ ++static int ithc_dma_prd_alloc(struct ithc *ithc, struct ithc_dma_prd_buffer *p, unsigned num_buffers, unsigned num_pages, enum dma_data_direction dir) { ++ p->num_pages = num_pages; ++ p->dir = dir; ++ p->size = round_up(num_buffers * num_pages * sizeof(struct ithc_phys_region_desc), PAGE_SIZE); ++ p->addr = dmam_alloc_coherent(&ithc->pci->dev, p->size, &p->dma_addr, GFP_KERNEL); ++ if (!p->addr) return -ENOMEM; ++ if (p->dma_addr & (PAGE_SIZE - 1)) return -EFAULT; ++ return 0; ++} ++ ++struct ithc_sg_table { ++ void *addr; ++ struct sg_table sgt; ++ enum dma_data_direction dir; ++}; ++static void ithc_dma_sgtable_free(struct sg_table *sgt) { ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_sg(sgt, sg, i) { ++ struct page *p = sg_page(sg); ++ if (p) __free_page(p); ++ } ++ sg_free_table(sgt); ++} ++static void ithc_dma_data_devres_release(struct device *dev, void *res) { ++ struct ithc_sg_table *sgt = res; ++ if (sgt->addr) vunmap(sgt->addr); ++ dma_unmap_sgtable(dev, &sgt->sgt, sgt->dir, 0); ++ ithc_dma_sgtable_free(&sgt->sgt); ++} ++ ++static int ithc_dma_data_alloc(struct ithc* ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b) { ++ // We don't use dma_alloc_coherent for data buffers, because they don't have to be contiguous (we can use one PRD per page) or coherent (they are unidirectional). ++ // Instead we use an sg_table of individually allocated pages (5.13 has dma_alloc_noncontiguous for this, but we'd like to support 5.10 for now). ++ struct page *pages[16]; ++ if (prds->num_pages == 0 || prds->num_pages > ARRAY_SIZE(pages)) return -EINVAL; ++ b->active_idx = -1; ++ struct ithc_sg_table *sgt = devres_alloc(ithc_dma_data_devres_release, sizeof *sgt, GFP_KERNEL); ++ if (!sgt) return -ENOMEM; ++ sgt->dir = prds->dir; ++ if (!sg_alloc_table(&sgt->sgt, prds->num_pages, GFP_KERNEL)) { ++ struct scatterlist *sg; ++ int i; ++ bool ok = true; ++ for_each_sgtable_sg(&sgt->sgt, sg, i) { ++ struct page *p = pages[i] = alloc_page(GFP_KERNEL | __GFP_ZERO); // don't need __GFP_DMA for PCI DMA ++ if (!p) { ok = false; break; } ++ sg_set_page(sg, p, PAGE_SIZE, 0); ++ } ++ if (ok && !dma_map_sgtable(&ithc->pci->dev, &sgt->sgt, prds->dir, 0)) { ++ devres_add(&ithc->pci->dev, sgt); ++ b->sgt = &sgt->sgt; ++ b->addr = sgt->addr = vmap(pages, prds->num_pages, 0, PAGE_KERNEL); ++ if (!b->addr) return -ENOMEM; ++ return 0; ++ } ++ ithc_dma_sgtable_free(&sgt->sgt); ++ } ++ devres_free(sgt); ++ return -ENOMEM; ++} ++ ++static int ithc_dma_data_buffer_put(struct ithc *ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b, unsigned idx) { ++ struct ithc_phys_region_desc *prd = prds->addr; ++ prd += idx * prds->num_pages; ++ if (b->active_idx >= 0) { pci_err(ithc->pci, "buffer already active\n"); return -EINVAL; } ++ b->active_idx = idx; ++ if (prds->dir == DMA_TO_DEVICE) { ++ if (b->data_size > PAGE_SIZE) return -EINVAL; ++ prd->addr = sg_dma_address(b->sgt->sgl) >> 10; ++ prd->size = b->data_size | PRD_FLAG_END; ++ flush_kernel_vmap_range(b->addr, b->data_size); ++ } else if (prds->dir == DMA_FROM_DEVICE) { ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_dma_sg(b->sgt, sg, i) { ++ prd->addr = sg_dma_address(sg) >> 10; ++ prd->size = sg_dma_len(sg); ++ prd++; ++ } ++ prd[-1].size |= PRD_FLAG_END; ++ } ++ dma_wmb(); // for the prds ++ dma_sync_sgtable_for_device(&ithc->pci->dev, b->sgt, prds->dir); ++ return 0; ++} ++ ++static int ithc_dma_data_buffer_get(struct ithc *ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b, unsigned idx) { ++ struct ithc_phys_region_desc *prd = prds->addr; ++ prd += idx * prds->num_pages; ++ if (b->active_idx != idx) { pci_err(ithc->pci, "wrong buffer index\n"); return -EINVAL; } ++ b->active_idx = -1; ++ if (prds->dir == DMA_FROM_DEVICE) { ++ dma_rmb(); // for the prds ++ b->data_size = 0; ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_dma_sg(b->sgt, sg, i) { ++ unsigned size = prd->size; ++ b->data_size += size & PRD_SIZE_MASK; ++ if (size & PRD_FLAG_END) break; ++ if ((size & PRD_SIZE_MASK) != sg_dma_len(sg)) { pci_err(ithc->pci, "truncated prd\n"); break; } ++ prd++; ++ } ++ invalidate_kernel_vmap_range(b->addr, b->data_size); ++ } ++ dma_sync_sgtable_for_cpu(&ithc->pci->dev, b->sgt, prds->dir); ++ return 0; ++} ++ ++int ithc_dma_rx_init(struct ithc *ithc, u8 channel, const char *devname) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ mutex_init(&rx->mutex); ++ u32 buf_size = DEVCFG_DMA_RX_SIZE(ithc->config.dma_buf_sizes); ++ unsigned num_pages = (buf_size + PAGE_SIZE - 1) / PAGE_SIZE; ++ pci_dbg(ithc->pci, "allocating rx buffers: num = %u, size = %u, pages = %u\n", NUM_RX_BUF, buf_size, num_pages); ++ CHECK_RET(ithc_dma_prd_alloc, ithc, &rx->prds, NUM_RX_BUF, num_pages, DMA_FROM_DEVICE); ++ for (unsigned i = 0; i < NUM_RX_BUF; i++) ++ CHECK_RET(ithc_dma_data_alloc, ithc, &rx->prds, &rx->bufs[i]); ++ writeb(DMA_RX_CONTROL2_RESET, &ithc->regs->dma_rx[channel].control2); ++ lo_hi_writeq(rx->prds.dma_addr, &ithc->regs->dma_rx[channel].addr); ++ writeb(NUM_RX_BUF - 1, &ithc->regs->dma_rx[channel].num_bufs); ++ writeb(num_pages - 1, &ithc->regs->dma_rx[channel].num_prds); ++ u8 head = readb(&ithc->regs->dma_rx[channel].head); ++ if (head) { pci_err(ithc->pci, "head is nonzero (%u)\n", head); return -EIO; } ++ for (unsigned i = 0; i < NUM_RX_BUF; i++) ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &rx->prds, &rx->bufs[i], i); ++ writeb(head ^ DMA_RX_WRAP_FLAG, &ithc->regs->dma_rx[channel].tail); ++ return 0; ++} ++void ithc_dma_rx_enable(struct ithc *ithc, u8 channel) { ++ bitsb_set(&ithc->regs->dma_rx[channel].control, DMA_RX_CONTROL_ENABLE | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_DATA); ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[1].status, DMA_RX_STATUS_ENABLED, DMA_RX_STATUS_ENABLED); ++} ++ ++int ithc_dma_tx_init(struct ithc *ithc) { ++ struct ithc_dma_tx *tx = &ithc->dma_tx; ++ mutex_init(&tx->mutex); ++ tx->max_size = DEVCFG_DMA_TX_SIZE(ithc->config.dma_buf_sizes); ++ unsigned num_pages = (tx->max_size + PAGE_SIZE - 1) / PAGE_SIZE; ++ pci_dbg(ithc->pci, "allocating tx buffers: size = %u, pages = %u\n", tx->max_size, num_pages); ++ CHECK_RET(ithc_dma_prd_alloc, ithc, &tx->prds, 1, num_pages, DMA_TO_DEVICE); ++ CHECK_RET(ithc_dma_data_alloc, ithc, &tx->prds, &tx->buf); ++ lo_hi_writeq(tx->prds.dma_addr, &ithc->regs->dma_tx.addr); ++ writeb(num_pages - 1, &ithc->regs->dma_tx.num_prds); ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ return 0; ++} ++ ++static int ithc_dma_rx_process_buf(struct ithc *ithc, struct ithc_dma_data_buffer *data, u8 channel, u8 buf) { ++ if (buf >= NUM_RX_BUF) { ++ pci_err(ithc->pci, "invalid dma ringbuffer index\n"); ++ return -EINVAL; ++ } ++ ithc_set_active(ithc); ++ u32 len = data->data_size; ++ struct ithc_dma_rx_header *hdr = data->addr; ++ u8 *hiddata = (void *)(hdr + 1); ++ if (len >= sizeof *hdr && hdr->code == DMA_RX_CODE_RESET) { ++ CHECK(ithc_reset, ithc); ++ } else if (len < sizeof *hdr || len != sizeof *hdr + hdr->data_size) { ++ if (hdr->code == DMA_RX_CODE_INPUT_REPORT) { ++ // When the CPU enters a low power state during DMA, we can get truncated messages. ++ // Typically this will be a single touch HID report that is only 1 byte, or a multitouch report that is 257 bytes. ++ // See also ithc_set_active(). ++ } else { ++ pci_err(ithc->pci, "invalid dma rx data! channel %u, buffer %u, size %u, code %u, data size %u\n", channel, buf, len, hdr->code, hdr->data_size); ++ print_hex_dump_debug(DEVNAME " data: ", DUMP_PREFIX_OFFSET, 32, 1, hdr, min(len, 0x400u), 0); ++ } ++ } else if (hdr->code == DMA_RX_CODE_REPORT_DESCRIPTOR && hdr->data_size > 8) { ++ CHECK(hid_parse_report, ithc->hid, hiddata + 8, hdr->data_size - 8); ++ WRITE_ONCE(ithc->hid_parse_done, true); ++ wake_up(&ithc->wait_hid_parse); ++ } else if (hdr->code == DMA_RX_CODE_INPUT_REPORT) { ++ CHECK(hid_input_report, ithc->hid, HID_INPUT_REPORT, hiddata, hdr->data_size, 1); ++ } else if (hdr->code == DMA_RX_CODE_FEATURE_REPORT) { ++ bool done = false; ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ if (ithc->hid_get_feature_buf) { ++ if (hdr->data_size < ithc->hid_get_feature_size) ithc->hid_get_feature_size = hdr->data_size; ++ memcpy(ithc->hid_get_feature_buf, hiddata, ithc->hid_get_feature_size); ++ ithc->hid_get_feature_buf = NULL; ++ done = true; ++ } ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ if (done) wake_up(&ithc->wait_hid_get_feature); ++ else CHECK(hid_input_report, ithc->hid, HID_FEATURE_REPORT, hiddata, hdr->data_size, 1); ++ } else { ++ pci_dbg(ithc->pci, "unhandled dma rx data! channel %u, buffer %u, size %u, code %u\n", channel, buf, len, hdr->code); ++ print_hex_dump_debug(DEVNAME " data: ", DUMP_PREFIX_OFFSET, 32, 1, hdr, min(len, 0x400u), 0); ++ } ++ return 0; ++} ++ ++static int ithc_dma_rx_unlocked(struct ithc *ithc, u8 channel) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ unsigned n = rx->num_received; ++ u8 head_wrap = readb(&ithc->regs->dma_rx[channel].head); ++ while (1) { ++ u8 tail = n % NUM_RX_BUF; ++ u8 tail_wrap = tail | ((n / NUM_RX_BUF) & 1 ? 0 : DMA_RX_WRAP_FLAG); ++ writeb(tail_wrap, &ithc->regs->dma_rx[channel].tail); ++ // ringbuffer is full if tail_wrap == head_wrap ++ // ringbuffer is empty if tail_wrap == head_wrap ^ WRAP_FLAG ++ if (tail_wrap == (head_wrap ^ DMA_RX_WRAP_FLAG)) return 0; ++ ++ // take the buffer that the device just filled ++ struct ithc_dma_data_buffer *b = &rx->bufs[n % NUM_RX_BUF]; ++ CHECK_RET(ithc_dma_data_buffer_get, ithc, &rx->prds, b, tail); ++ rx->num_received = ++n; ++ ++ // process data ++ CHECK(ithc_dma_rx_process_buf, ithc, b, channel, tail); ++ ++ // give the buffer back to the device ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &rx->prds, b, tail); ++ } ++} ++int ithc_dma_rx(struct ithc *ithc, u8 channel) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ mutex_lock(&rx->mutex); ++ int ret = ithc_dma_rx_unlocked(ithc, channel); ++ mutex_unlock(&rx->mutex); ++ return ret; ++} ++ ++static int ithc_dma_tx_unlocked(struct ithc *ithc, u32 cmdcode, u32 datasize, void *data) { ++ pci_dbg(ithc->pci, "dma tx command %u, size %u\n", cmdcode, datasize); ++ struct ithc_dma_tx_header *hdr; ++ u8 padding = datasize & 3 ? 4 - (datasize & 3) : 0; ++ unsigned fullsize = sizeof *hdr + datasize + padding; ++ if (fullsize > ithc->dma_tx.max_size || fullsize > PAGE_SIZE) return -EINVAL; ++ CHECK_RET(ithc_dma_data_buffer_get, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ ++ ithc->dma_tx.buf.data_size = fullsize; ++ hdr = ithc->dma_tx.buf.addr; ++ hdr->code = cmdcode; ++ hdr->data_size = datasize; ++ u8 *dest = (void *)(hdr + 1); ++ memcpy(dest, data, datasize); ++ dest += datasize; ++ for (u8 p = 0; p < padding; p++) *dest++ = 0; ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ ++ bitsb_set(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND); ++ CHECK_RET(waitb, ithc, &ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND, 0); ++ writel(DMA_TX_STATUS_DONE, &ithc->regs->dma_tx.status); ++ return 0; ++} ++int ithc_dma_tx(struct ithc *ithc, u32 cmdcode, u32 datasize, void *data) { ++ mutex_lock(&ithc->dma_tx.mutex); ++ int ret = ithc_dma_tx_unlocked(ithc, cmdcode, datasize, data); ++ mutex_unlock(&ithc->dma_tx.mutex); ++ return ret; ++} ++ +diff --git a/drivers/hid/ithc/ithc-dma.h b/drivers/hid/ithc/ithc-dma.h +new file mode 100644 +index 000000000000..d9f2c19a13f3 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-dma.h +@@ -0,0 +1,67 @@ ++#define PRD_SIZE_MASK 0xffffff ++#define PRD_FLAG_END 0x1000000 ++#define PRD_FLAG_SUCCESS 0x2000000 ++#define PRD_FLAG_ERROR 0x4000000 ++ ++struct ithc_phys_region_desc { ++ u64 addr; // physical addr/1024 ++ u32 size; // num bytes, PRD_FLAG_END marks last prd for data split over multiple prds ++ u32 unused; ++}; ++ ++#define DMA_RX_CODE_INPUT_REPORT 3 ++#define DMA_RX_CODE_FEATURE_REPORT 4 ++#define DMA_RX_CODE_REPORT_DESCRIPTOR 5 ++#define DMA_RX_CODE_RESET 7 ++ ++struct ithc_dma_rx_header { ++ u32 code; ++ u32 data_size; ++ u32 _unknown[14]; ++}; ++ ++#define DMA_TX_CODE_SET_FEATURE 3 ++#define DMA_TX_CODE_GET_FEATURE 4 ++#define DMA_TX_CODE_OUTPUT_REPORT 5 ++#define DMA_TX_CODE_GET_REPORT_DESCRIPTOR 7 ++ ++struct ithc_dma_tx_header { ++ u32 code; ++ u32 data_size; ++}; ++ ++struct ithc_dma_prd_buffer { ++ void *addr; ++ dma_addr_t dma_addr; ++ u32 size; ++ u32 num_pages; // per data buffer ++ enum dma_data_direction dir; ++}; ++ ++struct ithc_dma_data_buffer { ++ void *addr; ++ struct sg_table *sgt; ++ int active_idx; ++ u32 data_size; ++}; ++ ++struct ithc_dma_tx { ++ struct mutex mutex; ++ u32 max_size; ++ struct ithc_dma_prd_buffer prds; ++ struct ithc_dma_data_buffer buf; ++}; ++ ++struct ithc_dma_rx { ++ struct mutex mutex; ++ u32 num_received; ++ struct ithc_dma_prd_buffer prds; ++ struct ithc_dma_data_buffer bufs[NUM_RX_BUF]; ++}; ++ ++int ithc_dma_rx_init(struct ithc *ithc, u8 channel, const char *devname); ++void ithc_dma_rx_enable(struct ithc *ithc, u8 channel); ++int ithc_dma_tx_init(struct ithc *ithc); ++int ithc_dma_rx(struct ithc *ithc, u8 channel); ++int ithc_dma_tx(struct ithc *ithc, u32 cmdcode, u32 datasize, void *cmddata); ++ +diff --git a/drivers/hid/ithc/ithc-main.c b/drivers/hid/ithc/ithc-main.c +new file mode 100644 +index 000000000000..09512b9cb4d3 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-main.c +@@ -0,0 +1,534 @@ ++#include "ithc.h" ++ ++MODULE_DESCRIPTION("Intel Touch Host Controller driver"); ++MODULE_LICENSE("Dual BSD/GPL"); ++ ++// Lakefield ++#define PCI_DEVICE_ID_INTEL_THC_LKF_PORT1 0x98d0 ++#define PCI_DEVICE_ID_INTEL_THC_LKF_PORT2 0x98d1 ++// Tiger Lake ++#define PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT1 0xa0d0 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT2 0xa0d1 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT1 0x43d0 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT2 0x43d1 ++// Alder Lake ++#define PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT1 0x7ad8 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT2 0x7ad9 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT1 0x51d0 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT2 0x51d1 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT1 0x54d0 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT2 0x54d1 ++// Raptor Lake ++#define PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT1 0x7a58 ++#define PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT2 0x7a59 ++// Meteor Lake ++#define PCI_DEVICE_ID_INTEL_THC_MTL_PORT1 0x7e48 ++#define PCI_DEVICE_ID_INTEL_THC_MTL_PORT2 0x7e4a ++ ++static const struct pci_device_id ithc_pci_tbl[] = { ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_LKF_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_LKF_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_MTL_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_MTL_PORT2) }, ++ {} ++}; ++MODULE_DEVICE_TABLE(pci, ithc_pci_tbl); ++ ++// Module parameters ++ ++static bool ithc_use_polling = false; ++module_param_named(poll, ithc_use_polling, bool, 0); ++MODULE_PARM_DESC(poll, "Use polling instead of interrupts"); ++ ++static bool ithc_use_rx0 = false; ++module_param_named(rx0, ithc_use_rx0, bool, 0); ++MODULE_PARM_DESC(rx0, "Use DMA RX channel 0"); ++ ++static bool ithc_use_rx1 = true; ++module_param_named(rx1, ithc_use_rx1, bool, 0); ++MODULE_PARM_DESC(rx1, "Use DMA RX channel 1"); ++ ++static bool ithc_log_regs_enabled = false; ++module_param_named(logregs, ithc_log_regs_enabled, bool, 0); ++MODULE_PARM_DESC(logregs, "Log changes in register values (for debugging)"); ++ ++// Sysfs attributes ++ ++static bool ithc_is_config_valid(struct ithc *ithc) { ++ return ithc->config.device_id == DEVCFG_DEVICE_ID_TIC; ++} ++ ++static ssize_t vendor_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "0x%04x", ithc->config.vendor_id); ++} ++static DEVICE_ATTR_RO(vendor); ++static ssize_t product_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "0x%04x", ithc->config.product_id); ++} ++static DEVICE_ATTR_RO(product); ++static ssize_t revision_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "%u", ithc->config.revision); ++} ++static DEVICE_ATTR_RO(revision); ++static ssize_t fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ u32 v = ithc->config.fw_version; ++ return sprintf(buf, "%i.%i.%i.%i", v >> 24, v >> 16 & 0xff, v >> 8 & 0xff, v & 0xff); ++} ++static DEVICE_ATTR_RO(fw_version); ++ ++static const struct attribute_group *ithc_attribute_groups[] = { ++ &(const struct attribute_group){ ++ .name = DEVNAME, ++ .attrs = (struct attribute *[]){ ++ &dev_attr_vendor.attr, ++ &dev_attr_product.attr, ++ &dev_attr_revision.attr, ++ &dev_attr_fw_version.attr, ++ NULL ++ }, ++ }, ++ NULL ++}; ++ ++// HID setup ++ ++static int ithc_hid_start(struct hid_device *hdev) { return 0; } ++static void ithc_hid_stop(struct hid_device *hdev) { } ++static int ithc_hid_open(struct hid_device *hdev) { return 0; } ++static void ithc_hid_close(struct hid_device *hdev) { } ++ ++static int ithc_hid_parse(struct hid_device *hdev) { ++ struct ithc *ithc = hdev->driver_data; ++ u64 val = 0; ++ WRITE_ONCE(ithc->hid_parse_done, false); ++ CHECK_RET(ithc_dma_tx, ithc, DMA_TX_CODE_GET_REPORT_DESCRIPTOR, sizeof val, &val); ++ if (!wait_event_timeout(ithc->wait_hid_parse, READ_ONCE(ithc->hid_parse_done), msecs_to_jiffies(1000))) return -ETIMEDOUT; ++ return 0; ++} ++ ++static int ithc_hid_raw_request(struct hid_device *hdev, unsigned char reportnum, __u8 *buf, size_t len, unsigned char rtype, int reqtype) { ++ struct ithc *ithc = hdev->driver_data; ++ if (!buf || !len) return -EINVAL; ++ u32 code; ++ if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT) code = DMA_TX_CODE_OUTPUT_REPORT; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT) code = DMA_TX_CODE_SET_FEATURE; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT) code = DMA_TX_CODE_GET_FEATURE; ++ else { ++ pci_err(ithc->pci, "unhandled hid request %i %i for report id %i\n", rtype, reqtype, reportnum); ++ return -EINVAL; ++ } ++ buf[0] = reportnum; ++ if (reqtype == HID_REQ_GET_REPORT) { ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ ithc->hid_get_feature_buf = buf; ++ ithc->hid_get_feature_size = len; ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ int r = CHECK(ithc_dma_tx, ithc, code, 1, buf); ++ if (!r) { ++ r = wait_event_interruptible_timeout(ithc->wait_hid_get_feature, !ithc->hid_get_feature_buf, msecs_to_jiffies(1000)); ++ if (!r) r = -ETIMEDOUT; ++ else if (r < 0) r = -EINTR; ++ else r = 0; ++ } ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ ithc->hid_get_feature_buf = NULL; ++ if (!r) r = ithc->hid_get_feature_size; ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ return r; ++ } ++ CHECK_RET(ithc_dma_tx, ithc, code, len, buf); ++ return 0; ++} ++ ++static struct hid_ll_driver ithc_ll_driver = { ++ .start = ithc_hid_start, ++ .stop = ithc_hid_stop, ++ .open = ithc_hid_open, ++ .close = ithc_hid_close, ++ .parse = ithc_hid_parse, ++ .raw_request = ithc_hid_raw_request, ++}; ++ ++static void ithc_hid_devres_release(struct device *dev, void *res) { ++ struct hid_device **hidm = res; ++ if (*hidm) hid_destroy_device(*hidm); ++} ++ ++static int ithc_hid_init(struct ithc *ithc) { ++ struct hid_device **hidm = devres_alloc(ithc_hid_devres_release, sizeof *hidm, GFP_KERNEL); ++ if (!hidm) return -ENOMEM; ++ devres_add(&ithc->pci->dev, hidm); ++ struct hid_device *hid = hid_allocate_device(); ++ if (IS_ERR(hid)) return PTR_ERR(hid); ++ *hidm = hid; ++ ++ strscpy(hid->name, DEVFULLNAME, sizeof(hid->name)); ++ strscpy(hid->phys, ithc->phys, sizeof(hid->phys)); ++ hid->ll_driver = &ithc_ll_driver; ++ hid->bus = BUS_PCI; ++ hid->vendor = ithc->config.vendor_id; ++ hid->product = ithc->config.product_id; ++ hid->version = 0x100; ++ hid->dev.parent = &ithc->pci->dev; ++ hid->driver_data = ithc; ++ ++ ithc->hid = hid; ++ return 0; ++} ++ ++// Interrupts/polling ++ ++static void ithc_activity_timer_callback(struct timer_list *t) { ++ struct ithc *ithc = container_of(t, struct ithc, activity_timer); ++ cpu_latency_qos_update_request(&ithc->activity_qos, PM_QOS_DEFAULT_VALUE); ++} ++ ++void ithc_set_active(struct ithc *ithc) { ++ // When CPU usage is very low, the CPU can enter various low power states (C2-C10). ++ // This disrupts DMA, causing truncated DMA messages. ERROR_FLAG_DMA_UNKNOWN_12 will be set when this happens. ++ // The amount of truncated messages can become very high, resulting in user-visible effects (laggy/stuttering cursor). ++ // To avoid this, we use a CPU latency QoS request to prevent the CPU from entering low power states during touch interactions. ++ cpu_latency_qos_update_request(&ithc->activity_qos, 0); ++ mod_timer(&ithc->activity_timer, jiffies + msecs_to_jiffies(1000)); ++} ++ ++static int ithc_set_device_enabled(struct ithc *ithc, bool enable) { ++ u32 x = ithc->config.touch_cfg = (ithc->config.touch_cfg & ~(u32)DEVCFG_TOUCH_MASK) | DEVCFG_TOUCH_UNKNOWN_2 ++ | (enable ? DEVCFG_TOUCH_ENABLE | DEVCFG_TOUCH_UNKNOWN_3 | DEVCFG_TOUCH_UNKNOWN_4 : 0); ++ return ithc_spi_command(ithc, SPI_CMD_CODE_WRITE, offsetof(struct ithc_device_config, touch_cfg), sizeof x, &x); ++} ++ ++static void ithc_disable_interrupts(struct ithc *ithc) { ++ writel(0, &ithc->regs->error_control); ++ bitsb(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_IRQ, 0); ++ bitsb(&ithc->regs->dma_rx[0].control, DMA_RX_CONTROL_IRQ_UNKNOWN_1 | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_UNKNOWN_4 | DMA_RX_CONTROL_IRQ_DATA, 0); ++ bitsb(&ithc->regs->dma_rx[1].control, DMA_RX_CONTROL_IRQ_UNKNOWN_1 | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_UNKNOWN_4 | DMA_RX_CONTROL_IRQ_DATA, 0); ++ bitsb(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_IRQ, 0); ++} ++ ++static void ithc_clear_dma_rx_interrupts(struct ithc *ithc, unsigned channel) { ++ writel(DMA_RX_STATUS_ERROR | DMA_RX_STATUS_UNKNOWN_4 | DMA_RX_STATUS_HAVE_DATA, &ithc->regs->dma_rx[channel].status); ++} ++ ++static void ithc_clear_interrupts(struct ithc *ithc) { ++ writel(0xffffffff, &ithc->regs->error_flags); ++ writel(ERROR_STATUS_DMA | ERROR_STATUS_SPI, &ithc->regs->error_status); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ ithc_clear_dma_rx_interrupts(ithc, 0); ++ ithc_clear_dma_rx_interrupts(ithc, 1); ++ writel(DMA_TX_STATUS_DONE | DMA_TX_STATUS_ERROR | DMA_TX_STATUS_UNKNOWN_2, &ithc->regs->dma_tx.status); ++} ++ ++static void ithc_process(struct ithc *ithc) { ++ ithc_log_regs(ithc); ++ ++ // read and clear error bits ++ u32 err = readl(&ithc->regs->error_flags); ++ if (err) { ++ if (err & ~ERROR_FLAG_DMA_UNKNOWN_12) pci_err(ithc->pci, "error flags: 0x%08x\n", err); ++ writel(err, &ithc->regs->error_flags); ++ } ++ ++ // process DMA rx ++ if (ithc_use_rx0) { ++ ithc_clear_dma_rx_interrupts(ithc, 0); ++ ithc_dma_rx(ithc, 0); ++ } ++ if (ithc_use_rx1) { ++ ithc_clear_dma_rx_interrupts(ithc, 1); ++ ithc_dma_rx(ithc, 1); ++ } ++ ++ ithc_log_regs(ithc); ++} ++ ++static irqreturn_t ithc_interrupt_thread(int irq, void *arg) { ++ struct ithc *ithc = arg; ++ pci_dbg(ithc->pci, "IRQ! err=%08x/%08x/%08x, cmd=%02x/%08x, rx0=%02x/%08x, rx1=%02x/%08x, tx=%02x/%08x\n", ++ readl(&ithc->regs->error_control), readl(&ithc->regs->error_status), readl(&ithc->regs->error_flags), ++ readb(&ithc->regs->spi_cmd.control), readl(&ithc->regs->spi_cmd.status), ++ readb(&ithc->regs->dma_rx[0].control), readl(&ithc->regs->dma_rx[0].status), ++ readb(&ithc->regs->dma_rx[1].control), readl(&ithc->regs->dma_rx[1].status), ++ readb(&ithc->regs->dma_tx.control), readl(&ithc->regs->dma_tx.status)); ++ ithc_process(ithc); ++ return IRQ_HANDLED; ++} ++ ++static int ithc_poll_thread(void *arg) { ++ struct ithc *ithc = arg; ++ unsigned sleep = 100; ++ while (!kthread_should_stop()) { ++ u32 n = ithc->dma_rx[1].num_received; ++ ithc_process(ithc); ++ if (n != ithc->dma_rx[1].num_received) sleep = 20; ++ else sleep = min(200u, sleep + (sleep >> 4) + 1); ++ msleep_interruptible(sleep); ++ } ++ return 0; ++} ++ ++// Device initialization and shutdown ++ ++static void ithc_disable(struct ithc *ithc) { ++ bitsl_set(&ithc->regs->control_bits, CONTROL_QUIESCE); ++ CHECK(waitl, ithc, &ithc->regs->control_bits, CONTROL_IS_QUIESCED, CONTROL_IS_QUIESCED); ++ bitsl(&ithc->regs->control_bits, CONTROL_NRESET, 0); ++ bitsb(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_SEND, 0); ++ bitsb(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND, 0); ++ bitsb(&ithc->regs->dma_rx[0].control, DMA_RX_CONTROL_ENABLE, 0); ++ bitsb(&ithc->regs->dma_rx[1].control, DMA_RX_CONTROL_ENABLE, 0); ++ ithc_disable_interrupts(ithc); ++ ithc_clear_interrupts(ithc); ++} ++ ++static int ithc_init_device(struct ithc *ithc) { ++ ithc_log_regs(ithc); ++ bool was_enabled = (readl(&ithc->regs->control_bits) & CONTROL_NRESET) != 0; ++ ithc_disable(ithc); ++ CHECK_RET(waitl, ithc, &ithc->regs->control_bits, CONTROL_READY, CONTROL_READY); ++ ithc_set_spi_config(ithc, 10, 0); ++ bitsl_set(&ithc->regs->dma_rx[0].unknown_init_bits, 0x80000000); // seems to help with reading config ++ ++ if (was_enabled) if (msleep_interruptible(100)) return -EINTR; ++ bitsl(&ithc->regs->control_bits, CONTROL_QUIESCE, 0); ++ CHECK_RET(waitl, ithc, &ithc->regs->control_bits, CONTROL_IS_QUIESCED, 0); ++ for (int retries = 0; ; retries++) { ++ ithc_log_regs(ithc); ++ bitsl_set(&ithc->regs->control_bits, CONTROL_NRESET); ++ if (!waitl(ithc, &ithc->regs->state, 0xf, 2)) break; ++ if (retries > 5) { ++ pci_err(ithc->pci, "too many retries, failed to reset device\n"); ++ return -ETIMEDOUT; ++ } ++ pci_err(ithc->pci, "invalid state, retrying reset\n"); ++ bitsl(&ithc->regs->control_bits, CONTROL_NRESET, 0); ++ if (msleep_interruptible(1000)) return -EINTR; ++ } ++ ithc_log_regs(ithc); ++ ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[0].status, DMA_RX_STATUS_UNKNOWN_4, DMA_RX_STATUS_UNKNOWN_4); ++ ++ // read config ++ for (int retries = 0; ; retries++) { ++ ithc_log_regs(ithc); ++ memset(&ithc->config, 0, sizeof ithc->config); ++ CHECK_RET(ithc_spi_command, ithc, SPI_CMD_CODE_READ, 0, sizeof ithc->config, &ithc->config); ++ u32 *p = (void *)&ithc->config; ++ pci_info(ithc->pci, "config: %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x\n", ++ p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); ++ if (ithc_is_config_valid(ithc)) break; ++ if (retries > 10) { ++ pci_err(ithc->pci, "failed to read config, unknown device ID 0x%08x\n", ithc->config.device_id); ++ return -EIO; ++ } ++ pci_err(ithc->pci, "failed to read config, retrying\n"); ++ if (msleep_interruptible(100)) return -EINTR; ++ } ++ ithc_log_regs(ithc); ++ ++ CHECK_RET(ithc_set_spi_config, ithc, DEVCFG_SPI_MAX_FREQ(ithc->config.spi_config), DEVCFG_SPI_MODE(ithc->config.spi_config)); ++ CHECK_RET(ithc_set_device_enabled, ithc, true); ++ ithc_log_regs(ithc); ++ return 0; ++} ++ ++int ithc_reset(struct ithc *ithc) { ++ // FIXME This should probably do devres_release_group()+ithc_start(). But because this is called during DMA ++ // processing, that would have to be done asynchronously (schedule_work()?). And with extra locking? ++ pci_err(ithc->pci, "reset\n"); ++ CHECK(ithc_init_device, ithc); ++ if (ithc_use_rx0) ithc_dma_rx_enable(ithc, 0); ++ if (ithc_use_rx1) ithc_dma_rx_enable(ithc, 1); ++ ithc_log_regs(ithc); ++ pci_dbg(ithc->pci, "reset completed\n"); ++ return 0; ++} ++ ++static void ithc_stop(void *res) { ++ struct ithc *ithc = res; ++ pci_dbg(ithc->pci, "stopping\n"); ++ ithc_log_regs(ithc); ++ if (ithc->poll_thread) CHECK(kthread_stop, ithc->poll_thread); ++ if (ithc->irq >= 0) disable_irq(ithc->irq); ++ CHECK(ithc_set_device_enabled, ithc, false); ++ ithc_disable(ithc); ++ del_timer_sync(&ithc->activity_timer); ++ cpu_latency_qos_remove_request(&ithc->activity_qos); ++ // clear dma config ++ for(unsigned i = 0; i < 2; i++) { ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[i].status, DMA_RX_STATUS_ENABLED, 0); ++ lo_hi_writeq(0, &ithc->regs->dma_rx[i].addr); ++ writeb(0, &ithc->regs->dma_rx[i].num_bufs); ++ writeb(0, &ithc->regs->dma_rx[i].num_prds); ++ } ++ lo_hi_writeq(0, &ithc->regs->dma_tx.addr); ++ writeb(0, &ithc->regs->dma_tx.num_prds); ++ ithc_log_regs(ithc); ++ pci_dbg(ithc->pci, "stopped\n"); ++} ++ ++static void ithc_clear_drvdata(void *res) { ++ struct pci_dev *pci = res; ++ pci_set_drvdata(pci, NULL); ++} ++ ++static int ithc_start(struct pci_dev *pci) { ++ pci_dbg(pci, "starting\n"); ++ if (pci_get_drvdata(pci)) { ++ pci_err(pci, "device already initialized\n"); ++ return -EINVAL; ++ } ++ if (!devres_open_group(&pci->dev, ithc_start, GFP_KERNEL)) return -ENOMEM; ++ ++ struct ithc *ithc = devm_kzalloc(&pci->dev, sizeof *ithc, GFP_KERNEL); ++ if (!ithc) return -ENOMEM; ++ ithc->irq = -1; ++ ithc->pci = pci; ++ snprintf(ithc->phys, sizeof ithc->phys, "pci-%s/" DEVNAME, pci_name(pci)); ++ init_waitqueue_head(&ithc->wait_hid_parse); ++ init_waitqueue_head(&ithc->wait_hid_get_feature); ++ mutex_init(&ithc->hid_get_feature_mutex); ++ pci_set_drvdata(pci, ithc); ++ CHECK_RET(devm_add_action_or_reset, &pci->dev, ithc_clear_drvdata, pci); ++ if (ithc_log_regs_enabled) ithc->prev_regs = devm_kzalloc(&pci->dev, sizeof *ithc->prev_regs, GFP_KERNEL); ++ ++ CHECK_RET(pcim_enable_device, pci); ++ pci_set_master(pci); ++ CHECK_RET(pcim_iomap_regions, pci, BIT(0), DEVNAME " regs"); ++ CHECK_RET(dma_set_mask_and_coherent, &pci->dev, DMA_BIT_MASK(64)); ++ CHECK_RET(pci_set_power_state, pci, PCI_D0); ++ ithc->regs = pcim_iomap_table(pci)[0]; ++ ++ if (!ithc_use_polling) { ++ CHECK_RET(pci_alloc_irq_vectors, pci, 1, 1, PCI_IRQ_MSI | PCI_IRQ_MSIX); ++ ithc->irq = CHECK(pci_irq_vector, pci, 0); ++ if (ithc->irq < 0) return ithc->irq; ++ } ++ ++ CHECK_RET(ithc_init_device, ithc); ++ CHECK(devm_device_add_groups, &pci->dev, ithc_attribute_groups); ++ if (ithc_use_rx0) CHECK_RET(ithc_dma_rx_init, ithc, 0, ithc_use_rx1 ? DEVNAME "0" : DEVNAME); ++ if (ithc_use_rx1) CHECK_RET(ithc_dma_rx_init, ithc, 1, ithc_use_rx0 ? DEVNAME "1" : DEVNAME); ++ CHECK_RET(ithc_dma_tx_init, ithc); ++ ++ CHECK_RET(ithc_hid_init, ithc); ++ ++ cpu_latency_qos_add_request(&ithc->activity_qos, PM_QOS_DEFAULT_VALUE); ++ timer_setup(&ithc->activity_timer, ithc_activity_timer_callback, 0); ++ ++ // add ithc_stop callback AFTER setting up DMA buffers, so that polling/irqs/DMA are disabled BEFORE the buffers are freed ++ CHECK_RET(devm_add_action_or_reset, &pci->dev, ithc_stop, ithc); ++ ++ if (ithc_use_polling) { ++ pci_info(pci, "using polling instead of irq\n"); ++ // use a thread instead of simple timer because we want to be able to sleep ++ ithc->poll_thread = kthread_run(ithc_poll_thread, ithc, DEVNAME "poll"); ++ if (IS_ERR(ithc->poll_thread)) { ++ int err = PTR_ERR(ithc->poll_thread); ++ ithc->poll_thread = NULL; ++ return err; ++ } ++ } else { ++ CHECK_RET(devm_request_threaded_irq, &pci->dev, ithc->irq, NULL, ithc_interrupt_thread, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, DEVNAME, ithc); ++ } ++ ++ if (ithc_use_rx0) ithc_dma_rx_enable(ithc, 0); ++ if (ithc_use_rx1) ithc_dma_rx_enable(ithc, 1); ++ ++ // hid_add_device can only be called after irq/polling is started and DMA is enabled, because it calls ithc_hid_parse which reads the report descriptor via DMA ++ CHECK_RET(hid_add_device, ithc->hid); ++ ++ CHECK(ithc_debug_init, ithc); ++ ++ pci_dbg(pci, "started\n"); ++ return 0; ++} ++ ++static int ithc_probe(struct pci_dev *pci, const struct pci_device_id *id) { ++ pci_dbg(pci, "device probe\n"); ++ return ithc_start(pci); ++} ++ ++static void ithc_remove(struct pci_dev *pci) { ++ pci_dbg(pci, "device remove\n"); ++ // all cleanup is handled by devres ++} ++ ++static int ithc_suspend(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm suspend\n"); ++ devres_release_group(dev, ithc_start); ++ return 0; ++} ++ ++static int ithc_resume(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm resume\n"); ++ return ithc_start(pci); ++} ++ ++static int ithc_freeze(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm freeze\n"); ++ devres_release_group(dev, ithc_start); ++ return 0; ++} ++ ++static int ithc_thaw(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm thaw\n"); ++ return ithc_start(pci); ++} ++ ++static int ithc_restore(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm restore\n"); ++ return ithc_start(pci); ++} ++ ++static struct pci_driver ithc_driver = { ++ .name = DEVNAME, ++ .id_table = ithc_pci_tbl, ++ .probe = ithc_probe, ++ .remove = ithc_remove, ++ .driver.pm = &(const struct dev_pm_ops) { ++ .suspend = ithc_suspend, ++ .resume = ithc_resume, ++ .freeze = ithc_freeze, ++ .thaw = ithc_thaw, ++ .restore = ithc_restore, ++ }, ++ //.dev_groups = ithc_attribute_groups, // could use this (since 5.14), however the attributes won't have valid values until config has been read anyway ++}; ++ ++static int __init ithc_init(void) { ++ return pci_register_driver(&ithc_driver); ++} ++ ++static void __exit ithc_exit(void) { ++ pci_unregister_driver(&ithc_driver); ++} ++ ++module_init(ithc_init); ++module_exit(ithc_exit); ++ +diff --git a/drivers/hid/ithc/ithc-regs.c b/drivers/hid/ithc/ithc-regs.c +new file mode 100644 +index 000000000000..85d567b05761 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-regs.c +@@ -0,0 +1,64 @@ ++#include "ithc.h" ++ ++#define reg_num(r) (0x1fff & (u16)(__force u64)(r)) ++ ++void bitsl(__iomem u32 *reg, u32 mask, u32 val) { ++ if (val & ~mask) pr_err("register 0x%x: invalid value 0x%x for bitmask 0x%x\n", reg_num(reg), val, mask); ++ writel((readl(reg) & ~mask) | (val & mask), reg); ++} ++ ++void bitsb(__iomem u8 *reg, u8 mask, u8 val) { ++ if (val & ~mask) pr_err("register 0x%x: invalid value 0x%x for bitmask 0x%x\n", reg_num(reg), val, mask); ++ writeb((readb(reg) & ~mask) | (val & mask), reg); ++} ++ ++int waitl(struct ithc *ithc, __iomem u32 *reg, u32 mask, u32 val) { ++ pci_dbg(ithc->pci, "waiting for reg 0x%04x mask 0x%08x val 0x%08x\n", reg_num(reg), mask, val); ++ u32 x; ++ if (readl_poll_timeout(reg, x, (x & mask) == val, 200, 1000*1000)) { ++ pci_err(ithc->pci, "timed out waiting for reg 0x%04x mask 0x%08x val 0x%08x\n", reg_num(reg), mask, val); ++ return -ETIMEDOUT; ++ } ++ pci_dbg(ithc->pci, "done waiting\n"); ++ return 0; ++} ++ ++int waitb(struct ithc *ithc, __iomem u8 *reg, u8 mask, u8 val) { ++ pci_dbg(ithc->pci, "waiting for reg 0x%04x mask 0x%02x val 0x%02x\n", reg_num(reg), mask, val); ++ u8 x; ++ if (readb_poll_timeout(reg, x, (x & mask) == val, 200, 1000*1000)) { ++ pci_err(ithc->pci, "timed out waiting for reg 0x%04x mask 0x%02x val 0x%02x\n", reg_num(reg), mask, val); ++ return -ETIMEDOUT; ++ } ++ pci_dbg(ithc->pci, "done waiting\n"); ++ return 0; ++} ++ ++int ithc_set_spi_config(struct ithc *ithc, u8 speed, u8 mode) { ++ pci_dbg(ithc->pci, "setting SPI speed to %i, mode %i\n", speed, mode); ++ if (mode == 3) mode = 2; ++ bitsl(&ithc->regs->spi_config, ++ SPI_CONFIG_MODE(0xff) | SPI_CONFIG_SPEED(0xff) | SPI_CONFIG_UNKNOWN_18(0xff) | SPI_CONFIG_SPEED2(0xff), ++ SPI_CONFIG_MODE(mode) | SPI_CONFIG_SPEED(speed) | SPI_CONFIG_UNKNOWN_18(0) | SPI_CONFIG_SPEED2(speed)); ++ return 0; ++} ++ ++int ithc_spi_command(struct ithc *ithc, u8 command, u32 offset, u32 size, void *data) { ++ pci_dbg(ithc->pci, "SPI command %u, size %u, offset %u\n", command, size, offset); ++ if (size > sizeof ithc->regs->spi_cmd.data) return -EINVAL; ++ CHECK_RET(waitl, ithc, &ithc->regs->spi_cmd.status, SPI_CMD_STATUS_BUSY, 0); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ writeb(command, &ithc->regs->spi_cmd.code); ++ writew(size, &ithc->regs->spi_cmd.size); ++ writel(offset, &ithc->regs->spi_cmd.offset); ++ u32 *p = data, n = (size + 3) / 4; ++ for (u32 i = 0; i < n; i++) writel(p[i], &ithc->regs->spi_cmd.data[i]); ++ bitsb_set(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_SEND); ++ CHECK_RET(waitl, ithc, &ithc->regs->spi_cmd.status, SPI_CMD_STATUS_BUSY, 0); ++ if ((readl(&ithc->regs->spi_cmd.status) & (SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR)) != SPI_CMD_STATUS_DONE) return -EIO; ++ if (readw(&ithc->regs->spi_cmd.size) != size) return -EMSGSIZE; ++ for (u32 i = 0; i < n; i++) p[i] = readl(&ithc->regs->spi_cmd.data[i]); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ return 0; ++} ++ +diff --git a/drivers/hid/ithc/ithc-regs.h b/drivers/hid/ithc/ithc-regs.h +new file mode 100644 +index 000000000000..1a96092ed7ee +--- /dev/null ++++ b/drivers/hid/ithc/ithc-regs.h +@@ -0,0 +1,186 @@ ++#define CONTROL_QUIESCE BIT(1) ++#define CONTROL_IS_QUIESCED BIT(2) ++#define CONTROL_NRESET BIT(3) ++#define CONTROL_READY BIT(29) ++ ++#define SPI_CONFIG_MODE(x) (((x) & 3) << 2) ++#define SPI_CONFIG_SPEED(x) (((x) & 7) << 4) ++#define SPI_CONFIG_UNKNOWN_18(x) (((x) & 3) << 18) ++#define SPI_CONFIG_SPEED2(x) (((x) & 0xf) << 20) // high bit = high speed mode? ++ ++#define ERROR_CONTROL_UNKNOWN_0 BIT(0) ++#define ERROR_CONTROL_DISABLE_DMA BIT(1) // clears DMA_RX_CONTROL_ENABLE when a DMA error occurs ++#define ERROR_CONTROL_UNKNOWN_2 BIT(2) ++#define ERROR_CONTROL_UNKNOWN_3 BIT(3) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_9 BIT(9) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_10 BIT(10) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_12 BIT(12) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_13 BIT(13) ++#define ERROR_CONTROL_UNKNOWN_16(x) (((x) & 0xff) << 16) // spi error code irq? ++#define ERROR_CONTROL_SET_DMA_STATUS BIT(29) // sets DMA_RX_STATUS_ERROR when a DMA error occurs ++ ++#define ERROR_STATUS_DMA BIT(28) ++#define ERROR_STATUS_SPI BIT(30) ++ ++#define ERROR_FLAG_DMA_UNKNOWN_9 BIT(9) ++#define ERROR_FLAG_DMA_UNKNOWN_10 BIT(10) ++#define ERROR_FLAG_DMA_UNKNOWN_12 BIT(12) // set when we receive a truncated DMA message ++#define ERROR_FLAG_DMA_UNKNOWN_13 BIT(13) ++#define ERROR_FLAG_SPI_BUS_TURNAROUND BIT(16) ++#define ERROR_FLAG_SPI_RESPONSE_TIMEOUT BIT(17) ++#define ERROR_FLAG_SPI_INTRA_PACKET_TIMEOUT BIT(18) ++#define ERROR_FLAG_SPI_INVALID_RESPONSE BIT(19) ++#define ERROR_FLAG_SPI_HS_RX_TIMEOUT BIT(20) ++#define ERROR_FLAG_SPI_TOUCH_IC_INIT BIT(21) ++ ++#define SPI_CMD_CONTROL_SEND BIT(0) // cleared by device when sending is complete ++#define SPI_CMD_CONTROL_IRQ BIT(1) ++ ++#define SPI_CMD_CODE_READ 4 ++#define SPI_CMD_CODE_WRITE 6 ++ ++#define SPI_CMD_STATUS_DONE BIT(0) ++#define SPI_CMD_STATUS_ERROR BIT(1) ++#define SPI_CMD_STATUS_BUSY BIT(3) ++ ++#define DMA_TX_CONTROL_SEND BIT(0) // cleared by device when sending is complete ++#define DMA_TX_CONTROL_IRQ BIT(3) ++ ++#define DMA_TX_STATUS_DONE BIT(0) ++#define DMA_TX_STATUS_ERROR BIT(1) ++#define DMA_TX_STATUS_UNKNOWN_2 BIT(2) ++#define DMA_TX_STATUS_UNKNOWN_3 BIT(3) // busy? ++ ++#define DMA_RX_CONTROL_ENABLE BIT(0) ++#define DMA_RX_CONTROL_IRQ_UNKNOWN_1 BIT(1) // rx1 only? ++#define DMA_RX_CONTROL_IRQ_ERROR BIT(3) // rx1 only? ++#define DMA_RX_CONTROL_IRQ_UNKNOWN_4 BIT(4) // rx0 only? ++#define DMA_RX_CONTROL_IRQ_DATA BIT(5) ++ ++#define DMA_RX_CONTROL2_UNKNOWN_5 BIT(5) // rx0 only? ++#define DMA_RX_CONTROL2_RESET BIT(7) // resets ringbuffer indices ++ ++#define DMA_RX_WRAP_FLAG BIT(7) ++ ++#define DMA_RX_STATUS_ERROR BIT(3) ++#define DMA_RX_STATUS_UNKNOWN_4 BIT(4) // set in rx0 after using CONTROL_NRESET when it becomes possible to read config (can take >100ms) ++#define DMA_RX_STATUS_HAVE_DATA BIT(5) ++#define DMA_RX_STATUS_ENABLED BIT(8) ++ ++#define COUNTER_RESET BIT(31) ++ ++struct ithc_registers { ++ /* 0000 */ u32 _unknown_0000[1024]; ++ /* 1000 */ u32 _unknown_1000; ++ /* 1004 */ u32 _unknown_1004; ++ /* 1008 */ u32 control_bits; ++ /* 100c */ u32 _unknown_100c; ++ /* 1010 */ u32 spi_config; ++ /* 1014 */ u32 _unknown_1014[3]; ++ /* 1020 */ u32 error_control; ++ /* 1024 */ u32 error_status; // write to clear ++ /* 1028 */ u32 error_flags; // write to clear ++ /* 102c */ u32 _unknown_102c[5]; ++ struct { ++ /* 1040 */ u8 control; ++ /* 1041 */ u8 code; ++ /* 1042 */ u16 size; ++ /* 1044 */ u32 status; // write to clear ++ /* 1048 */ u32 offset; ++ /* 104c */ u32 data[16]; ++ /* 108c */ u32 _unknown_108c; ++ } spi_cmd; ++ struct { ++ /* 1090 */ u64 addr; // cannot be written with writeq(), must use lo_hi_writeq() ++ /* 1098 */ u8 control; ++ /* 1099 */ u8 _unknown_1099; ++ /* 109a */ u8 _unknown_109a; ++ /* 109b */ u8 num_prds; ++ /* 109c */ u32 status; // write to clear ++ } dma_tx; ++ /* 10a0 */ u32 _unknown_10a0[7]; ++ /* 10bc */ u32 state; // is 0xe0000402 (dev config val 0) after CONTROL_NRESET, 0xe0000461 after first touch, 0xe0000401 after DMA_RX_CODE_RESET ++ /* 10c0 */ u32 _unknown_10c0[8]; ++ /* 10e0 */ u32 _unknown_10e0_counters[3]; ++ /* 10ec */ u32 _unknown_10ec[5]; ++ struct { ++ /* 1100/1200 */ u64 addr; // cannot be written with writeq(), must use lo_hi_writeq() ++ /* 1108/1208 */ u8 num_bufs; ++ /* 1109/1209 */ u8 num_prds; ++ /* 110a/120a */ u16 _unknown_110a; ++ /* 110c/120c */ u8 control; ++ /* 110d/120d */ u8 head; ++ /* 110e/120e */ u8 tail; ++ /* 110f/120f */ u8 control2; ++ /* 1110/1210 */ u32 status; // write to clear ++ /* 1114/1214 */ u32 _unknown_1114; ++ /* 1118/1218 */ u64 _unknown_1118_guc_addr; ++ /* 1120/1220 */ u32 _unknown_1120_guc; ++ /* 1124/1224 */ u32 _unknown_1124_guc; ++ /* 1128/1228 */ u32 unknown_init_bits; // bit 2 = guc related, bit 3 = rx1 related, bit 4 = guc related ++ /* 112c/122c */ u32 _unknown_112c; ++ /* 1130/1230 */ u64 _unknown_1130_guc_addr; ++ /* 1138/1238 */ u32 _unknown_1138_guc; ++ /* 113c/123c */ u32 _unknown_113c; ++ /* 1140/1240 */ u32 _unknown_1140_guc; ++ /* 1144/1244 */ u32 _unknown_1144[23]; ++ /* 11a0/12a0 */ u32 _unknown_11a0_counters[6]; ++ /* 11b8/12b8 */ u32 _unknown_11b8[18]; ++ } dma_rx[2]; ++}; ++static_assert(sizeof(struct ithc_registers) == 0x1300); ++ ++#define DEVCFG_DMA_RX_SIZE(x) ((((x) & 0x3fff) + 1) << 6) ++#define DEVCFG_DMA_TX_SIZE(x) (((((x) >> 14) & 0x3ff) + 1) << 6) ++ ++#define DEVCFG_TOUCH_MASK 0x3f ++#define DEVCFG_TOUCH_ENABLE BIT(0) ++#define DEVCFG_TOUCH_UNKNOWN_1 BIT(1) ++#define DEVCFG_TOUCH_UNKNOWN_2 BIT(2) ++#define DEVCFG_TOUCH_UNKNOWN_3 BIT(3) ++#define DEVCFG_TOUCH_UNKNOWN_4 BIT(4) ++#define DEVCFG_TOUCH_UNKNOWN_5 BIT(5) ++#define DEVCFG_TOUCH_UNKNOWN_6 BIT(6) ++ ++#define DEVCFG_DEVICE_ID_TIC 0x43495424 // "$TIC" ++ ++#define DEVCFG_SPI_MAX_FREQ(x) (((x) >> 1) & 0xf) // high bit = use high speed mode? ++#define DEVCFG_SPI_MODE(x) (((x) >> 6) & 3) ++#define DEVCFG_SPI_UNKNOWN_8(x) (((x) >> 8) & 0x3f) ++#define DEVCFG_SPI_NEEDS_HEARTBEAT BIT(20) ++#define DEVCFG_SPI_HEARTBEAT_INTERVAL (((x) >> 21) & 7) ++#define DEVCFG_SPI_UNKNOWN_25 BIT(25) ++#define DEVCFG_SPI_UNKNOWN_26 BIT(26) ++#define DEVCFG_SPI_UNKNOWN_27 BIT(27) ++#define DEVCFG_SPI_DELAY (((x) >> 28) & 7) ++#define DEVCFG_SPI_USE_EXT_READ_CFG BIT(31) ++ ++struct ithc_device_config { ++ u32 _unknown_00; // 00 = 0xe0000402 (0xe0000401 after DMA_RX_CODE_RESET) ++ u32 _unknown_04; // 04 = 0x00000000 ++ u32 dma_buf_sizes; // 08 = 0x000a00ff ++ u32 touch_cfg; // 0c = 0x0000001c ++ u32 _unknown_10; // 10 = 0x0000001c ++ u32 device_id; // 14 = 0x43495424 = "$TIC" ++ u32 spi_config; // 18 = 0xfda00a2e ++ u16 vendor_id; // 1c = 0x045e = Microsoft Corp. ++ u16 product_id; // 1e = 0x0c1a ++ u32 revision; // 20 = 0x00000001 ++ u32 fw_version; // 24 = 0x05008a8b = 5.0.138.139 ++ u32 _unknown_28; // 28 = 0x00000000 ++ u32 fw_mode; // 2c = 0x00000000 ++ u32 _unknown_30; // 30 = 0x00000000 ++ u32 _unknown_34; // 34 = 0x0404035e (u8,u8,u8,u8 = version?) ++ u32 _unknown_38; // 38 = 0x000001c0 (0x000001c1 after DMA_RX_CODE_RESET) ++ u32 _unknown_3c; // 3c = 0x00000002 ++}; ++ ++void bitsl(__iomem u32 *reg, u32 mask, u32 val); ++void bitsb(__iomem u8 *reg, u8 mask, u8 val); ++#define bitsl_set(reg, x) bitsl(reg, x, x) ++#define bitsb_set(reg, x) bitsb(reg, x, x) ++int waitl(struct ithc *ithc, __iomem u32 *reg, u32 mask, u32 val); ++int waitb(struct ithc *ithc, __iomem u8 *reg, u8 mask, u8 val); ++int ithc_set_spi_config(struct ithc *ithc, u8 speed, u8 mode); ++int ithc_spi_command(struct ithc *ithc, u8 command, u32 offset, u32 size, void *data); ++ +diff --git a/drivers/hid/ithc/ithc.h b/drivers/hid/ithc/ithc.h +new file mode 100644 +index 000000000000..6a9b0d480bc1 +--- /dev/null ++++ b/drivers/hid/ithc/ithc.h +@@ -0,0 +1,60 @@ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define DEVNAME "ithc" ++#define DEVFULLNAME "Intel Touch Host Controller" ++ ++#undef pr_fmt ++#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt ++ ++#define CHECK(fn, ...) ({ int r = fn(__VA_ARGS__); if (r < 0) pci_err(ithc->pci, "%s: %s failed with %i\n", __func__, #fn, r); r; }) ++#define CHECK_RET(...) do { int r = CHECK(__VA_ARGS__); if (r < 0) return r; } while(0) ++ ++#define NUM_RX_BUF 16 ++ ++struct ithc; ++ ++#include "ithc-regs.h" ++#include "ithc-dma.h" ++ ++struct ithc { ++ char phys[32]; ++ struct pci_dev *pci; ++ int irq; ++ struct task_struct *poll_thread; ++ struct pm_qos_request activity_qos; ++ struct timer_list activity_timer; ++ ++ struct hid_device *hid; ++ bool hid_parse_done; ++ wait_queue_head_t wait_hid_parse; ++ wait_queue_head_t wait_hid_get_feature; ++ struct mutex hid_get_feature_mutex; ++ void *hid_get_feature_buf; ++ size_t hid_get_feature_size; ++ ++ struct ithc_registers __iomem *regs; ++ struct ithc_registers *prev_regs; // for debugging ++ struct ithc_device_config config; ++ struct ithc_dma_rx dma_rx[2]; ++ struct ithc_dma_tx dma_tx; ++}; ++ ++int ithc_reset(struct ithc *ithc); ++void ithc_set_active(struct ithc *ithc); ++int ithc_debug_init(struct ithc *ithc); ++void ithc_log_regs(struct ithc *ithc); ++ +diff --git a/drivers/i2c/i2c-core-acpi.c b/drivers/i2c/i2c-core-acpi.c +index d6037a328669..a290ebc77aea 100644 +--- a/drivers/i2c/i2c-core-acpi.c ++++ b/drivers/i2c/i2c-core-acpi.c +@@ -628,6 +628,28 @@ static int acpi_gsb_i2c_write_bytes(struct i2c_client *client, + return (ret == 1) ? 0 : -EIO; + } + ++static int acpi_gsb_i2c_write_raw_bytes(struct i2c_client *client, ++ u8 *data, u8 data_len) ++{ ++ struct i2c_msg msgs[1]; ++ int ret = AE_OK; ++ ++ msgs[0].addr = client->addr; ++ msgs[0].flags = client->flags; ++ msgs[0].len = data_len + 1; ++ msgs[0].buf = data; ++ ++ ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); ++ ++ if (ret < 0) { ++ dev_err(&client->adapter->dev, "i2c write failed: %d\n", ret); ++ return ret; ++ } ++ ++ /* 1 transfer must have completed successfully */ ++ return (ret == 1) ? 0 : -EIO; ++} ++ + static acpi_status + i2c_acpi_space_handler(u32 function, acpi_physical_address command, + u32 bits, u64 *value64, +@@ -729,6 +751,19 @@ i2c_acpi_space_handler(u32 function, acpi_physical_address command, + } + break; + ++ case ACPI_GSB_ACCESS_ATTRIB_RAW_BYTES: ++ if (action == ACPI_READ) { ++ dev_warn(&adapter->dev, ++ "protocol 0x%02x not supported for client 0x%02x\n", ++ accessor_type, client->addr); ++ ret = AE_BAD_PARAMETER; ++ goto err; ++ } else { ++ status = acpi_gsb_i2c_write_raw_bytes(client, ++ gsb->data, info->access_length); ++ } ++ break; ++ + default: + dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n", + accessor_type, client->addr); +diff --git a/drivers/input/misc/soc_button_array.c b/drivers/input/misc/soc_button_array.c +index 09489380afda..0f02411a60f1 100644 +--- a/drivers/input/misc/soc_button_array.c ++++ b/drivers/input/misc/soc_button_array.c +@@ -507,8 +507,8 @@ static const struct soc_device_data soc_device_MSHW0028 = { + * Both, the Surface Pro 4 (surfacepro3_button.c) and the above mentioned + * devices use MSHW0040 for power and volume buttons, however the way they + * have to be addressed differs. Make sure that we only load this drivers +- * for the correct devices by checking the OEM Platform Revision provided by +- * the _DSM method. ++ * for the correct devices by checking if the OEM Platform Revision DSM call ++ * exists. + */ + #define MSHW0040_DSM_REVISION 0x01 + #define MSHW0040_DSM_GET_OMPR 0x02 // get OEM Platform Revision +@@ -519,31 +519,14 @@ static const guid_t MSHW0040_DSM_UUID = + static int soc_device_check_MSHW0040(struct device *dev) + { + acpi_handle handle = ACPI_HANDLE(dev); +- union acpi_object *result; +- u64 oem_platform_rev = 0; // valid revisions are nonzero +- +- // get OEM platform revision +- result = acpi_evaluate_dsm_typed(handle, &MSHW0040_DSM_UUID, +- MSHW0040_DSM_REVISION, +- MSHW0040_DSM_GET_OMPR, NULL, +- ACPI_TYPE_INTEGER); +- +- if (result) { +- oem_platform_rev = result->integer.value; +- ACPI_FREE(result); +- } +- +- /* +- * If the revision is zero here, the _DSM evaluation has failed. This +- * indicates that we have a Pro 4 or Book 1 and this driver should not +- * be used. +- */ +- if (oem_platform_rev == 0) +- return -ENODEV; ++ bool exists; + +- dev_dbg(dev, "OEM Platform Revision %llu\n", oem_platform_rev); ++ // check if OEM platform revision DSM call exists ++ exists = acpi_check_dsm(handle, &MSHW0040_DSM_UUID, ++ MSHW0040_DSM_REVISION, ++ BIT(MSHW0040_DSM_GET_OMPR)); + +- return 0; ++ return exists ? 0 : -ENODEV; + } + + /* +diff --git a/drivers/iommu/intel/iommu.c b/drivers/iommu/intel/iommu.c +index 7c2f4bd33582..3ebd2260cdab 100644 +--- a/drivers/iommu/intel/iommu.c ++++ b/drivers/iommu/intel/iommu.c +@@ -37,6 +37,8 @@ + #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY) + #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB) + #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA) ++#define IS_IPTS(pdev) ((pdev)->vendor == PCI_VENDOR_ID_INTEL && \ ++ ((pdev)->device == 0x9d3e)) + #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e) + + #define IOAPIC_RANGE_START (0xfee00000) +@@ -287,12 +289,14 @@ int intel_iommu_enabled = 0; + EXPORT_SYMBOL_GPL(intel_iommu_enabled); + + static int dmar_map_gfx = 1; ++static int dmar_map_ipts = 1; + static int intel_iommu_superpage = 1; + static int iommu_identity_mapping; + static int iommu_skip_te_disable; + + #define IDENTMAP_GFX 2 + #define IDENTMAP_AZALIA 4 ++#define IDENTMAP_IPTS 16 + + const struct iommu_ops intel_iommu_ops; + +@@ -2588,6 +2592,9 @@ static int device_def_domain_type(struct device *dev) + + if ((iommu_identity_mapping & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev)) + return IOMMU_DOMAIN_IDENTITY; ++ ++ if ((iommu_identity_mapping & IDENTMAP_IPTS) && IS_IPTS(pdev)) ++ return IOMMU_DOMAIN_IDENTITY; + } + + return 0; +@@ -2977,6 +2984,9 @@ static int __init init_dmars(void) + if (!dmar_map_gfx) + iommu_identity_mapping |= IDENTMAP_GFX; + ++ if (!dmar_map_ipts) ++ iommu_identity_mapping |= IDENTMAP_IPTS; ++ + check_tylersburg_isoch(); + + ret = si_domain_init(hw_pass_through); +@@ -4819,6 +4829,17 @@ static void quirk_iommu_igfx(struct pci_dev *dev) + dmar_map_gfx = 0; + } + ++static void quirk_iommu_ipts(struct pci_dev *dev) ++{ ++ if (!IS_IPTS(dev)) ++ return; ++ ++ if (risky_device(dev)) ++ return; ++ ++ pci_info(dev, "Passthrough IOMMU for IPTS\n"); ++ dmar_map_ipts = 0; ++} + /* G4x/GM45 integrated gfx dmar support is totally busted. */ + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_igfx); +@@ -4854,6 +4875,9 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1632, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163A, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163D, quirk_iommu_igfx); + ++/* disable IPTS dmar support */ ++DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9D3E, quirk_iommu_ipts); ++ + static void quirk_iommu_rwbf(struct pci_dev *dev) + { + if (risky_device(dev)) +diff --git a/drivers/iommu/intel/irq_remapping.c b/drivers/iommu/intel/irq_remapping.c +index df9e261af0b5..bc2a0aefedf2 100644 +--- a/drivers/iommu/intel/irq_remapping.c ++++ b/drivers/iommu/intel/irq_remapping.c +@@ -390,6 +390,22 @@ static int set_msi_sid(struct irte *irte, struct pci_dev *dev) + data.busmatch_count = 0; + pci_for_each_dma_alias(dev, set_msi_sid_cb, &data); + ++ /* ++ * The Intel Touch Host Controller is at 00:10.6, but for some reason ++ * the MSI interrupts have request id 01:05.0. ++ * Disable id verification to work around this. ++ * FIXME Find proper fix or turn this into a quirk. ++ */ ++ if (dev->vendor == PCI_VENDOR_ID_INTEL && (dev->class >> 8) == PCI_CLASS_INPUT_PEN) { ++ switch(dev->device) { ++ case 0x98d0: case 0x98d1: // LKF ++ case 0xa0d0: case 0xa0d1: // TGL LP ++ case 0x43d0: case 0x43d1: // TGL H ++ set_irte_sid(irte, SVT_NO_VERIFY, SQ_ALL_16, 0); ++ return 0; ++ } ++ } ++ + /* + * DMA alias provides us with a PCI device and alias. The only case + * where the it will return an alias on a different bus than the +diff --git a/drivers/misc/mei/hw-me-regs.h b/drivers/misc/mei/hw-me-regs.h +index bdc65d50b945..08723c01d727 100644 +--- a/drivers/misc/mei/hw-me-regs.h ++++ b/drivers/misc/mei/hw-me-regs.h +@@ -92,6 +92,7 @@ + #define MEI_DEV_ID_CDF 0x18D3 /* Cedar Fork */ + + #define MEI_DEV_ID_ICP_LP 0x34E0 /* Ice Lake Point LP */ ++#define MEI_DEV_ID_ICP_LP_3 0x34E4 /* Ice Lake Point LP 3 (iTouch) */ + #define MEI_DEV_ID_ICP_N 0x38E0 /* Ice Lake Point N */ + + #define MEI_DEV_ID_JSP_N 0x4DE0 /* Jasper Lake Point N */ +diff --git a/drivers/misc/mei/pci-me.c b/drivers/misc/mei/pci-me.c +index 5bf0d50d55a0..c13864512229 100644 +--- a/drivers/misc/mei/pci-me.c ++++ b/drivers/misc/mei/pci-me.c +@@ -97,6 +97,7 @@ static const struct pci_device_id mei_me_pci_tbl[] = { + {MEI_PCI_DEVICE(MEI_DEV_ID_CMP_H_3, MEI_ME_PCH8_ITOUCH_CFG)}, + + {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_LP, MEI_ME_PCH12_CFG)}, ++ {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_LP_3, MEI_ME_PCH12_CFG)}, + {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_N, MEI_ME_PCH12_CFG)}, + + {MEI_PCI_DEVICE(MEI_DEV_ID_TGP_LP, MEI_ME_PCH15_CFG)}, +diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c +index 5eb131ab916f..67f074a126d1 100644 +--- a/drivers/net/wireless/ath/ath10k/core.c ++++ b/drivers/net/wireless/ath/ath10k/core.c +@@ -38,6 +38,9 @@ static bool fw_diag_log; + /* frame mode values are mapped as per enum ath10k_hw_txrx_mode */ + unsigned int ath10k_frame_mode = ATH10K_HW_TXRX_NATIVE_WIFI; + ++static char *override_board = ""; ++static char *override_board2 = ""; ++ + unsigned long ath10k_coredump_mask = BIT(ATH10K_FW_CRASH_DUMP_REGISTERS) | + BIT(ATH10K_FW_CRASH_DUMP_CE_DATA); + +@@ -50,6 +53,9 @@ module_param(fw_diag_log, bool, 0644); + module_param_named(frame_mode, ath10k_frame_mode, uint, 0644); + module_param_named(coredump_mask, ath10k_coredump_mask, ulong, 0444); + ++module_param(override_board, charp, 0644); ++module_param(override_board2, charp, 0644); ++ + MODULE_PARM_DESC(debug_mask, "Debugging mask"); + MODULE_PARM_DESC(uart_print, "Uart target debugging"); + MODULE_PARM_DESC(skip_otp, "Skip otp failure for calibration in testmode"); +@@ -59,6 +65,9 @@ MODULE_PARM_DESC(frame_mode, + MODULE_PARM_DESC(coredump_mask, "Bitfield of what to include in firmware crash file"); + MODULE_PARM_DESC(fw_diag_log, "Diag based fw log debugging"); + ++MODULE_PARM_DESC(override_board, "Override for board.bin file"); ++MODULE_PARM_DESC(override_board2, "Override for board-2.bin file"); ++ + static const struct ath10k_hw_params ath10k_hw_params_list[] = { + { + .id = QCA988X_HW_2_0_VERSION, +@@ -911,6 +920,42 @@ static int ath10k_init_configure_target(struct ath10k *ar) + return 0; + } + ++static const char *ath10k_override_board_fw_file(struct ath10k *ar, ++ const char *file) ++{ ++ if (strcmp(file, "board.bin") == 0) { ++ if (strcmp(override_board, "") == 0) ++ return file; ++ ++ if (strcmp(override_board, "none") == 0) { ++ dev_info(ar->dev, "firmware override: pretending 'board.bin' does not exist\n"); ++ return NULL; ++ } ++ ++ dev_info(ar->dev, "firmware override: replacing 'board.bin' with '%s'\n", ++ override_board); ++ ++ return override_board; ++ } ++ ++ if (strcmp(file, "board-2.bin") == 0) { ++ if (strcmp(override_board2, "") == 0) ++ return file; ++ ++ if (strcmp(override_board2, "none") == 0) { ++ dev_info(ar->dev, "firmware override: pretending 'board-2.bin' does not exist\n"); ++ return NULL; ++ } ++ ++ dev_info(ar->dev, "firmware override: replacing 'board-2.bin' with '%s'\n", ++ override_board2); ++ ++ return override_board2; ++ } ++ ++ return file; ++} ++ + static const struct firmware *ath10k_fetch_fw_file(struct ath10k *ar, + const char *dir, + const char *file) +@@ -925,6 +970,19 @@ static const struct firmware *ath10k_fetch_fw_file(struct ath10k *ar, + if (dir == NULL) + dir = "."; + ++ /* HACK: Override board.bin and board-2.bin files if specified. ++ * ++ * Some Surface devices perform better with a different board ++ * configuration. To this end, one would need to replace the board.bin ++ * file with the modified config and remove the board-2.bin file. ++ * Unfortunately, that's not a solution that we can easily package. So ++ * we add module options to perform these overrides here. ++ */ ++ ++ file = ath10k_override_board_fw_file(ar, file); ++ if (!file) ++ return ERR_PTR(-ENOENT); ++ + snprintf(filename, sizeof(filename), "%s/%s", dir, file); + ret = firmware_request_nowarn(&fw, filename, ar->dev); + ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot fw request '%s': %d\n", +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie.c b/drivers/net/wireless/marvell/mwifiex/pcie.c +index 9a698a16a8f3..5e1a341f63df 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie.c +@@ -368,6 +368,7 @@ static int mwifiex_pcie_probe(struct pci_dev *pdev, + const struct pci_device_id *ent) + { + struct pcie_service_card *card; ++ struct pci_dev *parent_pdev = pci_upstream_bridge(pdev); + int ret; + + pr_debug("info: vendor=0x%4.04X device=0x%4.04X rev=%d\n", +@@ -409,6 +410,12 @@ static int mwifiex_pcie_probe(struct pci_dev *pdev, + return -1; + } + ++ /* disable bridge_d3 for Surface gen4+ devices to fix fw crashing ++ * after suspend ++ */ ++ if (card->quirks & QUIRK_NO_BRIDGE_D3) ++ parent_pdev->bridge_d3 = false; ++ + return 0; + } + +@@ -1762,9 +1769,21 @@ mwifiex_pcie_send_boot_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb) + static int mwifiex_pcie_init_fw_port(struct mwifiex_adapter *adapter) + { + struct pcie_service_card *card = adapter->card; ++ struct pci_dev *pdev = card->dev; ++ struct pci_dev *parent_pdev = pci_upstream_bridge(pdev); + const struct mwifiex_pcie_card_reg *reg = card->pcie.reg; + int tx_wrap = card->txbd_wrptr & reg->tx_wrap_mask; + ++ /* Trigger a function level reset of the PCI bridge device, this makes ++ * the firmware of PCIe 88W8897 cards stop reporting a fixed LTR value ++ * that prevents the system from entering package C10 and S0ix powersaving ++ * states. ++ * We need to do it here because it must happen after firmware ++ * initialization and this function is called after that is done. ++ */ ++ if (card->quirks & QUIRK_DO_FLR_ON_BRIDGE) ++ pci_reset_function(parent_pdev); ++ + /* Write the RX ring read pointer in to reg->rx_rdptr */ + if (mwifiex_write_reg(adapter, reg->rx_rdptr, card->rxbd_rdptr | + tx_wrap)) { +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +index dd6d21f1dbfd..99b024ecbade 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +@@ -13,7 +13,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 5", +@@ -22,7 +24,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 5 (LTE)", +@@ -31,7 +35,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 6", +@@ -39,7 +45,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Book 1", +@@ -47,7 +55,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Book 2", +@@ -55,7 +65,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Laptop 1", +@@ -63,7 +75,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Laptop 2", +@@ -71,7 +85,9 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + {} + }; +@@ -89,6 +105,11 @@ void mwifiex_initialize_quirks(struct pcie_service_card *card) + dev_info(&pdev->dev, "no quirks enabled\n"); + if (card->quirks & QUIRK_FW_RST_D3COLD) + dev_info(&pdev->dev, "quirk reset_d3cold enabled\n"); ++ if (card->quirks & QUIRK_DO_FLR_ON_BRIDGE) ++ dev_info(&pdev->dev, "quirk do_flr_on_bridge enabled\n"); ++ if (card->quirks & QUIRK_NO_BRIDGE_D3) ++ dev_info(&pdev->dev, ++ "quirk no_brigde_d3 enabled\n"); + } + + static void mwifiex_pcie_set_power_d3cold(struct pci_dev *pdev) +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +index d6ff964aec5b..c14eb56eb911 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +@@ -4,6 +4,8 @@ + #include "pcie.h" + + #define QUIRK_FW_RST_D3COLD BIT(0) ++#define QUIRK_DO_FLR_ON_BRIDGE BIT(1) ++#define QUIRK_NO_BRIDGE_D3 BIT(2) + + void mwifiex_initialize_quirks(struct pcie_service_card *card); + int mwifiex_pcie_reset_d3cold_quirk(struct pci_dev *pdev); +diff --git a/drivers/pci/pci-driver.c b/drivers/pci/pci-driver.c +index 57ddcc59af30..497cbadd2c6c 100644 +--- a/drivers/pci/pci-driver.c ++++ b/drivers/pci/pci-driver.c +@@ -507,6 +507,9 @@ static void pci_device_shutdown(struct device *dev) + struct pci_dev *pci_dev = to_pci_dev(dev); + struct pci_driver *drv = pci_dev->driver; + ++ if (pci_dev->no_shutdown) ++ return; ++ + pm_runtime_resume(dev); + + if (drv && drv->shutdown) +diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c +index 25edf55de985..6ab563cc58f6 100644 +--- a/drivers/pci/quirks.c ++++ b/drivers/pci/quirks.c +@@ -6124,3 +6124,39 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a2d, dpc_log_size); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a2f, dpc_log_size); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a31, dpc_log_size); + #endif ++ ++static const struct dmi_system_id no_shutdown_dmi_table[] = { ++ /* ++ * Systems on which some devices should not be touched during shutdown. ++ */ ++ { ++ .ident = "Microsoft Surface Pro 9", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "Surface Pro 9"), ++ }, ++ }, ++ { ++ .ident = "Microsoft Surface Laptop 5", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 5"), ++ }, ++ }, ++ {} ++}; ++ ++static void quirk_no_shutdown(struct pci_dev *dev) ++{ ++ if (!dmi_check_system(no_shutdown_dmi_table)) ++ return; ++ ++ dev->no_shutdown = 1; ++ pci_info(dev, "disabling shutdown ops for [%04x:%04x]\n", ++ dev->vendor, dev->device); ++} ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x461e, quirk_no_shutdown); // Thunderbolt 4 USB Controller ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x461f, quirk_no_shutdown); // Thunderbolt 4 PCI Express Root Port ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x462f, quirk_no_shutdown); // Thunderbolt 4 PCI Express Root Port ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x466d, quirk_no_shutdown); // Thunderbolt 4 NHI ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x46a8, quirk_no_shutdown); // GPU +diff --git a/drivers/platform/surface/Kconfig b/drivers/platform/surface/Kconfig +index b629e82af97c..68656e8f309e 100644 +--- a/drivers/platform/surface/Kconfig ++++ b/drivers/platform/surface/Kconfig +@@ -149,6 +149,13 @@ config SURFACE_AGGREGATOR_TABLET_SWITCH + Select M or Y here, if you want to provide tablet-mode switch input + events on the Surface Pro 8, Surface Pro X, and Surface Laptop Studio. + ++config SURFACE_BOOK1_DGPU_SWITCH ++ tristate "Surface Book 1 dGPU Switch Driver" ++ depends on SYSFS ++ help ++ This driver provides a sysfs switch to set the power-state of the ++ discrete GPU found on the Microsoft Surface Book 1. ++ + config SURFACE_DTX + tristate "Surface DTX (Detachment System) Driver" + depends on SURFACE_AGGREGATOR +diff --git a/drivers/platform/surface/Makefile b/drivers/platform/surface/Makefile +index 53344330939b..7efcd0cdb532 100644 +--- a/drivers/platform/surface/Makefile ++++ b/drivers/platform/surface/Makefile +@@ -12,6 +12,7 @@ obj-$(CONFIG_SURFACE_AGGREGATOR_CDEV) += surface_aggregator_cdev.o + obj-$(CONFIG_SURFACE_AGGREGATOR_HUB) += surface_aggregator_hub.o + obj-$(CONFIG_SURFACE_AGGREGATOR_REGISTRY) += surface_aggregator_registry.o + obj-$(CONFIG_SURFACE_AGGREGATOR_TABLET_SWITCH) += surface_aggregator_tabletsw.o ++obj-$(CONFIG_SURFACE_BOOK1_DGPU_SWITCH) += surfacebook1_dgpu_switch.o + obj-$(CONFIG_SURFACE_DTX) += surface_dtx.o + obj-$(CONFIG_SURFACE_GPE) += surface_gpe.o + obj-$(CONFIG_SURFACE_HOTPLUG) += surface_hotplug.o +diff --git a/drivers/platform/surface/surface3-wmi.c b/drivers/platform/surface/surface3-wmi.c +index ca4602bcc7de..490b9731068a 100644 +--- a/drivers/platform/surface/surface3-wmi.c ++++ b/drivers/platform/surface/surface3-wmi.c +@@ -37,6 +37,13 @@ static const struct dmi_system_id surface3_dmi_table[] = { + DMI_MATCH(DMI_PRODUCT_NAME, "Surface 3"), + }, + }, ++ { ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ }, + #endif + { } + }; +diff --git a/drivers/platform/surface/surface_gpe.c b/drivers/platform/surface/surface_gpe.c +index c219b840d491..69c4352e8406 100644 +--- a/drivers/platform/surface/surface_gpe.c ++++ b/drivers/platform/surface/surface_gpe.c +@@ -41,6 +41,11 @@ static const struct property_entry lid_device_props_l4F[] = { + {}, + }; + ++static const struct property_entry lid_device_props_l52[] = { ++ PROPERTY_ENTRY_U32("gpe", 0x52), ++ {}, ++}; ++ + static const struct property_entry lid_device_props_l57[] = { + PROPERTY_ENTRY_U32("gpe", 0x57), + {}, +@@ -107,6 +112,18 @@ static const struct dmi_system_id dmi_lid_device_table[] = { + }, + .driver_data = (void *)lid_device_props_l4B, + }, ++ { ++ /* ++ * We match for SKU here due to product name clash with the ARM ++ * version. ++ */ ++ .ident = "Surface Pro 9", ++ .matches = { ++ DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_9_2038"), ++ }, ++ .driver_data = (void *)lid_device_props_l52, ++ }, + { + .ident = "Surface Book 1", + .matches = { +diff --git a/drivers/platform/surface/surfacebook1_dgpu_switch.c b/drivers/platform/surface/surfacebook1_dgpu_switch.c +new file mode 100644 +index 000000000000..8b816ed8f35c +--- /dev/null ++++ b/drivers/platform/surface/surfacebook1_dgpu_switch.c +@@ -0,0 +1,162 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++ ++#include ++#include ++#include ++#include ++ ++ ++#ifdef pr_fmt ++#undef pr_fmt ++#endif ++#define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ ++ ++ ++static const guid_t dgpu_sw_guid = GUID_INIT(0x6fd05c69, 0xcde3, 0x49f4, ++ 0x95, 0xed, 0xab, 0x16, 0x65, 0x49, 0x80, 0x35); ++ ++#define DGPUSW_ACPI_PATH_DSM "\\_SB_.PCI0.LPCB.EC0_.VGBI" ++#define DGPUSW_ACPI_PATH_HGON "\\_SB_.PCI0.RP05.HGON" ++#define DGPUSW_ACPI_PATH_HGOF "\\_SB_.PCI0.RP05.HGOF" ++ ++ ++static int sb1_dgpu_sw_dsmcall(void) ++{ ++ union acpi_object *ret; ++ acpi_handle handle; ++ acpi_status status; ++ ++ status = acpi_get_handle(NULL, DGPUSW_ACPI_PATH_DSM, &handle); ++ if (status) ++ return -EINVAL; ++ ++ ret = acpi_evaluate_dsm_typed(handle, &dgpu_sw_guid, 1, 1, NULL, ACPI_TYPE_BUFFER); ++ if (!ret) ++ return -EINVAL; ++ ++ ACPI_FREE(ret); ++ return 0; ++} ++ ++static int sb1_dgpu_sw_hgon(void) ++{ ++ struct acpi_buffer buf = {ACPI_ALLOCATE_BUFFER, NULL}; ++ acpi_status status; ++ ++ status = acpi_evaluate_object(NULL, DGPUSW_ACPI_PATH_HGON, NULL, &buf); ++ if (status) { ++ pr_err("failed to run HGON: %d\n", status); ++ return -EINVAL; ++ } ++ ++ if (buf.pointer) ++ ACPI_FREE(buf.pointer); ++ ++ pr_info("turned-on dGPU via HGON\n"); ++ return 0; ++} ++ ++static int sb1_dgpu_sw_hgof(void) ++{ ++ struct acpi_buffer buf = {ACPI_ALLOCATE_BUFFER, NULL}; ++ acpi_status status; ++ ++ status = acpi_evaluate_object(NULL, DGPUSW_ACPI_PATH_HGOF, NULL, &buf); ++ if (status) { ++ pr_err("failed to run HGOF: %d\n", status); ++ return -EINVAL; ++ } ++ ++ if (buf.pointer) ++ ACPI_FREE(buf.pointer); ++ ++ pr_info("turned-off dGPU via HGOF\n"); ++ return 0; ++} ++ ++ ++static ssize_t dgpu_dsmcall_store(struct device *dev, struct device_attribute *attr, ++ const char *buf, size_t len) ++{ ++ int status, value; ++ ++ status = kstrtoint(buf, 0, &value); ++ if (status < 0) ++ return status; ++ ++ if (value != 1) ++ return -EINVAL; ++ ++ status = sb1_dgpu_sw_dsmcall(); ++ ++ return status < 0 ? status : len; ++} ++ ++static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr, ++ const char *buf, size_t len) ++{ ++ bool power; ++ int status; ++ ++ status = kstrtobool(buf, &power); ++ if (status < 0) ++ return status; ++ ++ if (power) ++ status = sb1_dgpu_sw_hgon(); ++ else ++ status = sb1_dgpu_sw_hgof(); ++ ++ return status < 0 ? status : len; ++} ++ ++static DEVICE_ATTR_WO(dgpu_dsmcall); ++static DEVICE_ATTR_WO(dgpu_power); ++ ++static struct attribute *sb1_dgpu_sw_attrs[] = { ++ &dev_attr_dgpu_dsmcall.attr, ++ &dev_attr_dgpu_power.attr, ++ NULL, ++}; ++ ++static const struct attribute_group sb1_dgpu_sw_attr_group = { ++ .attrs = sb1_dgpu_sw_attrs, ++}; ++ ++ ++static int sb1_dgpu_sw_probe(struct platform_device *pdev) ++{ ++ return sysfs_create_group(&pdev->dev.kobj, &sb1_dgpu_sw_attr_group); ++} ++ ++static int sb1_dgpu_sw_remove(struct platform_device *pdev) ++{ ++ sysfs_remove_group(&pdev->dev.kobj, &sb1_dgpu_sw_attr_group); ++ return 0; ++} ++ ++/* ++ * The dGPU power seems to be actually handled by MSHW0040. However, that is ++ * also the power-/volume-button device with a mainline driver. So let's use ++ * MSHW0041 instead for now, which seems to be the LTCH (latch/DTX) device. ++ */ ++static const struct acpi_device_id sb1_dgpu_sw_match[] = { ++ { "MSHW0041", }, ++ { }, ++}; ++MODULE_DEVICE_TABLE(acpi, sb1_dgpu_sw_match); ++ ++static struct platform_driver sb1_dgpu_sw = { ++ .probe = sb1_dgpu_sw_probe, ++ .remove = sb1_dgpu_sw_remove, ++ .driver = { ++ .name = "surfacebook1_dgpu_switch", ++ .acpi_match_table = sb1_dgpu_sw_match, ++ .probe_type = PROBE_PREFER_ASYNCHRONOUS, ++ }, ++}; ++module_platform_driver(sb1_dgpu_sw); ++ ++MODULE_AUTHOR("Maximilian Luz "); ++MODULE_DESCRIPTION("Discrete GPU Power-Switch for Surface Book 1"); ++MODULE_LICENSE("GPL"); +diff --git a/drivers/platform/surface/surfacepro3_button.c b/drivers/platform/surface/surfacepro3_button.c +index 2755601f979c..4240c98ca226 100644 +--- a/drivers/platform/surface/surfacepro3_button.c ++++ b/drivers/platform/surface/surfacepro3_button.c +@@ -149,7 +149,8 @@ static int surface_button_resume(struct device *dev) + /* + * Surface Pro 4 and Surface Book 2 / Surface Pro 2017 use the same device + * ID (MSHW0040) for the power/volume buttons. Make sure this is the right +- * device by checking for the _DSM method and OEM Platform Revision. ++ * device by checking for the _DSM method and OEM Platform Revision DSM ++ * function. + * + * Returns true if the driver should bind to this device, i.e. the device is + * either MSWH0028 (Pro 3) or MSHW0040 on a Pro 4 or Book 1. +@@ -157,30 +158,11 @@ static int surface_button_resume(struct device *dev) + static bool surface_button_check_MSHW0040(struct acpi_device *dev) + { + acpi_handle handle = dev->handle; +- union acpi_object *result; +- u64 oem_platform_rev = 0; // valid revisions are nonzero +- +- // get OEM platform revision +- result = acpi_evaluate_dsm_typed(handle, &MSHW0040_DSM_UUID, +- MSHW0040_DSM_REVISION, +- MSHW0040_DSM_GET_OMPR, +- NULL, ACPI_TYPE_INTEGER); +- +- /* +- * If evaluating the _DSM fails, the method is not present. This means +- * that we have either MSHW0028 or MSHW0040 on Pro 4 or Book 1, so we +- * should use this driver. We use revision 0 indicating it is +- * unavailable. +- */ +- +- if (result) { +- oem_platform_rev = result->integer.value; +- ACPI_FREE(result); +- } +- +- dev_dbg(&dev->dev, "OEM Platform Revision %llu\n", oem_platform_rev); + +- return oem_platform_rev == 0; ++ // make sure that OEM platform revision DSM call does not exist ++ return !acpi_check_dsm(handle, &MSHW0040_DSM_UUID, ++ MSHW0040_DSM_REVISION, ++ BIT(MSHW0040_DSM_GET_OMPR)); + } + + +diff --git a/drivers/usb/core/quirks.c b/drivers/usb/core/quirks.c +index 934b3d997702..2c6604c6e8e1 100644 +--- a/drivers/usb/core/quirks.c ++++ b/drivers/usb/core/quirks.c +@@ -220,6 +220,9 @@ static const struct usb_device_id usb_quirk_list[] = { + /* Microsoft Surface Dock Ethernet (RTL8153 GigE) */ + { USB_DEVICE(0x045e, 0x07c6), .driver_info = USB_QUIRK_NO_LPM }, + ++ /* Microsoft Surface Go 3 Type-Cover */ ++ { USB_DEVICE(0x045e, 0x09b5), .driver_info = USB_QUIRK_DELAY_INIT }, ++ + /* Cherry Stream G230 2.0 (G85-231) and 3.0 (G85-232) */ + { USB_DEVICE(0x046a, 0x0023), .driver_info = USB_QUIRK_RESET_RESUME }, + +diff --git a/include/linux/pci.h b/include/linux/pci.h +index a5dda515fcd1..69f6fc707ae5 100644 +--- a/include/linux/pci.h ++++ b/include/linux/pci.h +@@ -464,6 +464,7 @@ struct pci_dev { + unsigned int no_vf_scan:1; /* Don't scan for VFs after IOV enablement */ + unsigned int no_command_memory:1; /* No PCI_COMMAND_MEMORY */ + unsigned int rom_bar_overlap:1; /* ROM BAR disable broken */ ++ unsigned int no_shutdown:1; /* Do not touch device on shutdown */ + pci_dev_flags_t dev_flags; + atomic_t enable_cnt; /* pci_enable_device has been called */ + +diff --git a/sound/soc/codecs/rt5645.c b/sound/soc/codecs/rt5645.c +index 7c7cbb6362ea..81a8ff40e86e 100644 +--- a/sound/soc/codecs/rt5645.c ++++ b/sound/soc/codecs/rt5645.c +@@ -3717,6 +3717,15 @@ static const struct dmi_system_id dmi_platform_data[] = { + }, + .driver_data = (void *)&intel_braswell_platform_data, + }, ++ { ++ .ident = "Microsoft Surface 3", ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ .driver_data = (void *)&intel_braswell_platform_data, ++ }, + { + /* + * Match for the GPDwin which unfortunately uses somewhat +diff --git a/sound/soc/intel/common/soc-acpi-intel-cht-match.c b/sound/soc/intel/common/soc-acpi-intel-cht-match.c +index 6beb00858c33..d82d77387a0a 100644 +--- a/sound/soc/intel/common/soc-acpi-intel-cht-match.c ++++ b/sound/soc/intel/common/soc-acpi-intel-cht-match.c +@@ -27,6 +27,14 @@ static const struct dmi_system_id cht_table[] = { + DMI_MATCH(DMI_PRODUCT_NAME, "Surface 3"), + }, + }, ++ { ++ .callback = cht_surface_quirk_cb, ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ }, + { } + }; + +-- +2.40.0 + +From 730b831da4bda377aaa8863bb9dfbe477ded7c3b Mon Sep 17 00:00:00 2001 +From: Peter Jung +Date: Sat, 22 Apr 2023 11:46:32 +0200 +Subject: [PATCH 11/12] zram + +Signed-off-by: Peter Jung +--- + drivers/block/zram/zram_drv.c | 381 ++++++++++++---------------------- + drivers/block/zram/zram_drv.h | 1 - + 2 files changed, 136 insertions(+), 246 deletions(-) + +diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c +index aa490da3cef2..f1e51eb2aba1 100644 +--- a/drivers/block/zram/zram_drv.c ++++ b/drivers/block/zram/zram_drv.c +@@ -54,9 +54,8 @@ static size_t huge_class_size; + static const struct block_device_operations zram_devops; + + static void zram_free_page(struct zram *zram, size_t index); +-static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec, +- u32 index, int offset, struct bio *bio); +- ++static int zram_read_page(struct zram *zram, struct page *page, u32 index, ++ struct bio *parent); + + static int zram_slot_trylock(struct zram *zram, u32 index) + { +@@ -174,36 +173,6 @@ static inline u32 zram_get_priority(struct zram *zram, u32 index) + return prio & ZRAM_COMP_PRIORITY_MASK; + } + +-/* +- * Check if request is within bounds and aligned on zram logical blocks. +- */ +-static inline bool valid_io_request(struct zram *zram, +- sector_t start, unsigned int size) +-{ +- u64 end, bound; +- +- /* unaligned request */ +- if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1))) +- return false; +- if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1))) +- return false; +- +- end = start + (size >> SECTOR_SHIFT); +- bound = zram->disksize >> SECTOR_SHIFT; +- /* out of range */ +- if (unlikely(start >= bound || end > bound || start > end)) +- return false; +- +- /* I/O request is valid */ +- return true; +-} +- +-static void update_position(u32 *index, int *offset, struct bio_vec *bvec) +-{ +- *index += (*offset + bvec->bv_len) / PAGE_SIZE; +- *offset = (*offset + bvec->bv_len) % PAGE_SIZE; +-} +- + static inline void update_used_max(struct zram *zram, + const unsigned long pages) + { +@@ -606,41 +575,16 @@ static void free_block_bdev(struct zram *zram, unsigned long blk_idx) + atomic64_dec(&zram->stats.bd_count); + } + +-static void zram_page_end_io(struct bio *bio) +-{ +- struct page *page = bio_first_page_all(bio); +- +- page_endio(page, op_is_write(bio_op(bio)), +- blk_status_to_errno(bio->bi_status)); +- bio_put(bio); +-} +- +-/* +- * Returns 1 if the submission is successful. +- */ +-static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec, ++static void read_from_bdev_async(struct zram *zram, struct page *page, + unsigned long entry, struct bio *parent) + { + struct bio *bio; + +- bio = bio_alloc(zram->bdev, 1, parent ? parent->bi_opf : REQ_OP_READ, +- GFP_NOIO); +- if (!bio) +- return -ENOMEM; +- ++ bio = bio_alloc(zram->bdev, 1, parent->bi_opf, GFP_NOIO); + bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9); +- if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) { +- bio_put(bio); +- return -EIO; +- } +- +- if (!parent) +- bio->bi_end_io = zram_page_end_io; +- else +- bio_chain(bio, parent); +- ++ __bio_add_page(bio, page, PAGE_SIZE, 0); ++ bio_chain(bio, parent); + submit_bio(bio); +- return 1; + } + + #define PAGE_WB_SIG "page_index=" +@@ -701,10 +645,6 @@ static ssize_t writeback_store(struct device *dev, + } + + for (; nr_pages != 0; index++, nr_pages--) { +- struct bio_vec bvec; +- +- bvec_set_page(&bvec, page, PAGE_SIZE, 0); +- + spin_lock(&zram->wb_limit_lock); + if (zram->wb_limit_enable && !zram->bd_wb_limit) { + spin_unlock(&zram->wb_limit_lock); +@@ -748,7 +688,7 @@ static ssize_t writeback_store(struct device *dev, + /* Need for hugepage writeback racing */ + zram_set_flag(zram, index, ZRAM_IDLE); + zram_slot_unlock(zram, index); +- if (zram_bvec_read(zram, &bvec, index, 0, NULL)) { ++ if (zram_read_page(zram, page, index, NULL)) { + zram_slot_lock(zram, index); + zram_clear_flag(zram, index, ZRAM_UNDER_WB); + zram_clear_flag(zram, index, ZRAM_IDLE); +@@ -759,9 +699,8 @@ static ssize_t writeback_store(struct device *dev, + bio_init(&bio, zram->bdev, &bio_vec, 1, + REQ_OP_WRITE | REQ_SYNC); + bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9); ++ bio_add_page(&bio, page, PAGE_SIZE, 0); + +- bio_add_page(&bio, bvec.bv_page, bvec.bv_len, +- bvec.bv_offset); + /* + * XXX: A single page IO would be inefficient for write + * but it would be not bad as starter. +@@ -829,19 +768,20 @@ struct zram_work { + struct work_struct work; + struct zram *zram; + unsigned long entry; +- struct bio *bio; +- struct bio_vec bvec; ++ struct page *page; ++ int error; + }; + +-#if PAGE_SIZE != 4096 + static void zram_sync_read(struct work_struct *work) + { + struct zram_work *zw = container_of(work, struct zram_work, work); +- struct zram *zram = zw->zram; +- unsigned long entry = zw->entry; +- struct bio *bio = zw->bio; ++ struct bio_vec bv; ++ struct bio bio; + +- read_from_bdev_async(zram, &zw->bvec, entry, bio); ++ bio_init(&bio, zw->zram->bdev, &bv, 1, REQ_OP_READ); ++ bio.bi_iter.bi_sector = zw->entry * (PAGE_SIZE >> 9); ++ __bio_add_page(&bio, zw->page, PAGE_SIZE, 0); ++ zw->error = submit_bio_wait(&bio); + } + + /* +@@ -849,45 +789,39 @@ static void zram_sync_read(struct work_struct *work) + * chained IO with parent IO in same context, it's a deadlock. To avoid that, + * use a worker thread context. + */ +-static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec, +- unsigned long entry, struct bio *bio) ++static int read_from_bdev_sync(struct zram *zram, struct page *page, ++ unsigned long entry) + { + struct zram_work work; + +- work.bvec = *bvec; ++ if (WARN_ON_ONCE(PAGE_SIZE != 4096)) ++ return -EIO; ++ ++ work.page = page; + work.zram = zram; + work.entry = entry; +- work.bio = bio; + + INIT_WORK_ONSTACK(&work.work, zram_sync_read); + queue_work(system_unbound_wq, &work.work); + flush_work(&work.work); + destroy_work_on_stack(&work.work); + +- return 1; +-} +-#else +-static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec, +- unsigned long entry, struct bio *bio) +-{ +- WARN_ON(1); +- return -EIO; ++ return work.error; + } +-#endif + +-static int read_from_bdev(struct zram *zram, struct bio_vec *bvec, +- unsigned long entry, struct bio *parent, bool sync) ++static int read_from_bdev(struct zram *zram, struct page *page, ++ unsigned long entry, struct bio *parent) + { + atomic64_inc(&zram->stats.bd_reads); +- if (sync) +- return read_from_bdev_sync(zram, bvec, entry, parent); +- else +- return read_from_bdev_async(zram, bvec, entry, parent); ++ if (!parent) ++ return read_from_bdev_sync(zram, page, entry); ++ read_from_bdev_async(zram, page, entry, parent); ++ return 0; + } + #else + static inline void reset_bdev(struct zram *zram) {}; +-static int read_from_bdev(struct zram *zram, struct bio_vec *bvec, +- unsigned long entry, struct bio *parent, bool sync) ++static int read_from_bdev(struct zram *zram, struct page *page, ++ unsigned long entry, struct bio *parent) + { + return -EIO; + } +@@ -1190,10 +1124,9 @@ static ssize_t io_stat_show(struct device *dev, + + down_read(&zram->init_lock); + ret = scnprintf(buf, PAGE_SIZE, +- "%8llu %8llu %8llu %8llu\n", ++ "%8llu %8llu 0 %8llu\n", + (u64)atomic64_read(&zram->stats.failed_reads), + (u64)atomic64_read(&zram->stats.failed_writes), +- (u64)atomic64_read(&zram->stats.invalid_io), + (u64)atomic64_read(&zram->stats.notify_free)); + up_read(&zram->init_lock); + +@@ -1371,20 +1304,6 @@ static void zram_free_page(struct zram *zram, size_t index) + ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB)); + } + +-/* +- * Reads a page from the writeback devices. Corresponding ZRAM slot +- * should be unlocked. +- */ +-static int zram_bvec_read_from_bdev(struct zram *zram, struct page *page, +- u32 index, struct bio *bio, bool partial_io) +-{ +- struct bio_vec bvec; +- +- bvec_set_page(&bvec, page, PAGE_SIZE, 0); +- return read_from_bdev(zram, &bvec, zram_get_element(zram, index), bio, +- partial_io); +-} +- + /* + * Reads (decompresses if needed) a page from zspool (zsmalloc). + * Corresponding ZRAM slot should be locked. +@@ -1434,8 +1353,8 @@ static int zram_read_from_zspool(struct zram *zram, struct page *page, + return ret; + } + +-static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index, +- struct bio *bio, bool partial_io) ++static int zram_read_page(struct zram *zram, struct page *page, u32 index, ++ struct bio *parent) + { + int ret; + +@@ -1445,11 +1364,14 @@ static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index, + ret = zram_read_from_zspool(zram, page, index); + zram_slot_unlock(zram, index); + } else { +- /* Slot should be unlocked before the function call */ ++ /* ++ * The slot should be unlocked before reading from the backing ++ * device. ++ */ + zram_slot_unlock(zram, index); + +- ret = zram_bvec_read_from_bdev(zram, page, index, bio, +- partial_io); ++ ret = read_from_bdev(zram, page, zram_get_element(zram, index), ++ parent); + } + + /* Should NEVER happen. Return bio error if it does. */ +@@ -1459,39 +1381,34 @@ static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index, + return ret; + } + +-static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec, +- u32 index, int offset, struct bio *bio) ++/* ++ * Use a temporary buffer to decompress the page, as the decompressor ++ * always expects a full page for the output. ++ */ ++static int zram_bvec_read_partial(struct zram *zram, struct bio_vec *bvec, ++ u32 index, int offset) + { ++ struct page *page = alloc_page(GFP_NOIO); + int ret; +- struct page *page; + +- page = bvec->bv_page; +- if (is_partial_io(bvec)) { +- /* Use a temporary buffer to decompress the page */ +- page = alloc_page(GFP_NOIO|__GFP_HIGHMEM); +- if (!page) +- return -ENOMEM; +- } +- +- ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec)); +- if (unlikely(ret)) +- goto out; +- +- if (is_partial_io(bvec)) { +- void *src = kmap_atomic(page); ++ if (!page) ++ return -ENOMEM; ++ ret = zram_read_page(zram, page, index, NULL); ++ if (likely(!ret)) ++ memcpy_to_bvec(bvec, page_address(page) + offset); ++ __free_page(page); ++ return ret; ++} + +- memcpy_to_bvec(bvec, src + offset); +- kunmap_atomic(src); +- } +-out: ++static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec, ++ u32 index, int offset, struct bio *bio) ++{ + if (is_partial_io(bvec)) +- __free_page(page); +- +- return ret; ++ return zram_bvec_read_partial(zram, bvec, index, offset); ++ return zram_read_page(zram, bvec->bv_page, index, bio); + } + +-static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec, +- u32 index, struct bio *bio) ++static int zram_write_page(struct zram *zram, struct page *page, u32 index) + { + int ret = 0; + unsigned long alloced_pages; +@@ -1499,7 +1416,6 @@ static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec, + unsigned int comp_len = 0; + void *src, *dst, *mem; + struct zcomp_strm *zstrm; +- struct page *page = bvec->bv_page; + unsigned long element = 0; + enum zram_pageflags flags = 0; + +@@ -1617,40 +1533,33 @@ static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec, + return ret; + } + +-static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, +- u32 index, int offset, struct bio *bio) ++/* ++ * This is a partial IO. Read the full page before writing the changes. ++ */ ++static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec, ++ u32 index, int offset, struct bio *bio) + { ++ struct page *page = alloc_page(GFP_NOIO); + int ret; +- struct page *page = NULL; +- struct bio_vec vec; +- +- vec = *bvec; +- if (is_partial_io(bvec)) { +- void *dst; +- /* +- * This is a partial IO. We need to read the full page +- * before to write the changes. +- */ +- page = alloc_page(GFP_NOIO|__GFP_HIGHMEM); +- if (!page) +- return -ENOMEM; +- +- ret = __zram_bvec_read(zram, page, index, bio, true); +- if (ret) +- goto out; + +- dst = kmap_atomic(page); +- memcpy_from_bvec(dst + offset, bvec); +- kunmap_atomic(dst); ++ if (!page) ++ return -ENOMEM; + +- bvec_set_page(&vec, page, PAGE_SIZE, 0); ++ ret = zram_read_page(zram, page, index, bio); ++ if (!ret) { ++ memcpy_from_bvec(page_address(page) + offset, bvec); ++ ret = zram_write_page(zram, page, index); + } ++ __free_page(page); ++ return ret; ++} + +- ret = __zram_bvec_write(zram, &vec, index, bio); +-out: ++static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, ++ u32 index, int offset, struct bio *bio) ++{ + if (is_partial_io(bvec)) +- __free_page(page); +- return ret; ++ return zram_bvec_write_partial(zram, bvec, index, offset, bio); ++ return zram_write_page(zram, bvec->bv_page, index); + } + + #ifdef CONFIG_ZRAM_MULTI_COMP +@@ -1761,7 +1670,7 @@ static int zram_recompress(struct zram *zram, u32 index, struct page *page, + + /* + * No direct reclaim (slow path) for handle allocation and no +- * re-compression attempt (unlike in __zram_bvec_write()) since ++ * re-compression attempt (unlike in zram_write_bvec()) since + * we already have stored that object in zsmalloc. If we cannot + * alloc memory for recompressed object then we bail out and + * simply keep the old (existing) object in zsmalloc. +@@ -1921,15 +1830,12 @@ static ssize_t recompress_store(struct device *dev, + } + #endif + +-/* +- * zram_bio_discard - handler on discard request +- * @index: physical block index in PAGE_SIZE units +- * @offset: byte offset within physical block +- */ +-static void zram_bio_discard(struct zram *zram, u32 index, +- int offset, struct bio *bio) ++static void zram_bio_discard(struct zram *zram, struct bio *bio) + { + size_t n = bio->bi_iter.bi_size; ++ u32 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT; ++ u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) << ++ SECTOR_SHIFT; + + /* + * zram manages data in physical block size units. Because logical block +@@ -1957,80 +1863,58 @@ static void zram_bio_discard(struct zram *zram, u32 index, + index++; + n -= PAGE_SIZE; + } ++ ++ bio_endio(bio); + } + +-/* +- * Returns errno if it has some problem. Otherwise return 0 or 1. +- * Returns 0 if IO request was done synchronously +- * Returns 1 if IO request was successfully submitted. +- */ +-static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index, +- int offset, enum req_op op, struct bio *bio) ++static void zram_bio_read(struct zram *zram, struct bio *bio) + { +- int ret; +- +- if (!op_is_write(op)) { +- ret = zram_bvec_read(zram, bvec, index, offset, bio); +- flush_dcache_page(bvec->bv_page); +- } else { +- ret = zram_bvec_write(zram, bvec, index, offset, bio); +- } ++ struct bvec_iter iter; ++ struct bio_vec bv; ++ unsigned long start_time; + +- zram_slot_lock(zram, index); +- zram_accessed(zram, index); +- zram_slot_unlock(zram, index); ++ start_time = bio_start_io_acct(bio); ++ bio_for_each_segment(bv, bio, iter) { ++ u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT; ++ u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) << ++ SECTOR_SHIFT; + +- if (unlikely(ret < 0)) { +- if (!op_is_write(op)) ++ if (zram_bvec_read(zram, &bv, index, offset, bio) < 0) { + atomic64_inc(&zram->stats.failed_reads); +- else +- atomic64_inc(&zram->stats.failed_writes); +- } ++ bio->bi_status = BLK_STS_IOERR; ++ break; ++ } ++ flush_dcache_page(bv.bv_page); + +- return ret; ++ zram_slot_lock(zram, index); ++ zram_accessed(zram, index); ++ zram_slot_unlock(zram, index); ++ } ++ bio_end_io_acct(bio, start_time); ++ bio_endio(bio); + } + +-static void __zram_make_request(struct zram *zram, struct bio *bio) ++static void zram_bio_write(struct zram *zram, struct bio *bio) + { +- int offset; +- u32 index; +- struct bio_vec bvec; + struct bvec_iter iter; ++ struct bio_vec bv; + unsigned long start_time; + +- index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT; +- offset = (bio->bi_iter.bi_sector & +- (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT; +- +- switch (bio_op(bio)) { +- case REQ_OP_DISCARD: +- case REQ_OP_WRITE_ZEROES: +- zram_bio_discard(zram, index, offset, bio); +- bio_endio(bio); +- return; +- default: +- break; +- } +- + start_time = bio_start_io_acct(bio); +- bio_for_each_segment(bvec, bio, iter) { +- struct bio_vec bv = bvec; +- unsigned int unwritten = bvec.bv_len; +- +- do { +- bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset, +- unwritten); +- if (zram_bvec_rw(zram, &bv, index, offset, +- bio_op(bio), bio) < 0) { +- bio->bi_status = BLK_STS_IOERR; +- break; +- } ++ bio_for_each_segment(bv, bio, iter) { ++ u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT; ++ u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) << ++ SECTOR_SHIFT; + +- bv.bv_offset += bv.bv_len; +- unwritten -= bv.bv_len; ++ if (zram_bvec_write(zram, &bv, index, offset, bio) < 0) { ++ atomic64_inc(&zram->stats.failed_writes); ++ bio->bi_status = BLK_STS_IOERR; ++ break; ++ } + +- update_position(&index, &offset, &bv); +- } while (unwritten); ++ zram_slot_lock(zram, index); ++ zram_accessed(zram, index); ++ zram_slot_unlock(zram, index); + } + bio_end_io_acct(bio, start_time); + bio_endio(bio); +@@ -2043,14 +1927,21 @@ static void zram_submit_bio(struct bio *bio) + { + struct zram *zram = bio->bi_bdev->bd_disk->private_data; + +- if (!valid_io_request(zram, bio->bi_iter.bi_sector, +- bio->bi_iter.bi_size)) { +- atomic64_inc(&zram->stats.invalid_io); +- bio_io_error(bio); +- return; ++ switch (bio_op(bio)) { ++ case REQ_OP_READ: ++ zram_bio_read(zram, bio); ++ break; ++ case REQ_OP_WRITE: ++ zram_bio_write(zram, bio); ++ break; ++ case REQ_OP_DISCARD: ++ case REQ_OP_WRITE_ZEROES: ++ zram_bio_discard(zram, bio); ++ break; ++ default: ++ WARN_ON_ONCE(1); ++ bio_endio(bio); + } +- +- __zram_make_request(zram, bio); + } + + static void zram_slot_free_notify(struct block_device *bdev, +diff --git a/drivers/block/zram/zram_drv.h b/drivers/block/zram/zram_drv.h +index c5254626f051..ca7a15bd4845 100644 +--- a/drivers/block/zram/zram_drv.h ++++ b/drivers/block/zram/zram_drv.h +@@ -78,7 +78,6 @@ struct zram_stats { + atomic64_t compr_data_size; /* compressed size of pages stored */ + atomic64_t failed_reads; /* can happen when memory is too low */ + atomic64_t failed_writes; /* can happen when memory is too low */ +- atomic64_t invalid_io; /* non-page-aligned I/O requests */ + atomic64_t notify_free; /* no. of swap slot free notifications */ + atomic64_t same_pages; /* no. of same element filled pages */ + atomic64_t huge_pages; /* no. of huge pages */ +-- +2.40.0 + +From 4030d3d48b4efcd13d661e16eacc6185a0122357 Mon Sep 17 00:00:00 2001 +From: Peter Jung +Date: Sat, 22 Apr 2023 11:46:46 +0200 +Subject: [PATCH 12/12] zstd: import 1.5.5 Signed-off-by: Peter Jung --- diff --git a/patches/0002-eevdf.patch b/patches/0002-eevdf.patch index 0df5c7b..4b5787c 100644 --- a/patches/0002-eevdf.patch +++ b/patches/0002-eevdf.patch @@ -1,6 +1,6 @@ -From 40a2f9f3e7e56936385c5a97957cd43fbb85fd32 Mon Sep 17 00:00:00 2001 +From 0365d5da967f712e2210bc34b0bd3c17aa752ad3 Mon Sep 17 00:00:00 2001 From: Peter Jung -Date: Sun, 9 Apr 2023 21:35:07 +0200 +Date: Mon, 17 Apr 2023 18:43:10 +0200 Subject: [PATCH] EEVDF Signed-off-by: Peter Jung @@ -13,11 +13,11 @@ Signed-off-by: Peter Jung init/init_task.c | 3 +- kernel/sched/core.c | 67 +- kernel/sched/debug.c | 50 +- - kernel/sched/fair.c | 1171 ++++++++++------------- + kernel/sched/fair.c | 1230 +++++++++++------------ kernel/sched/features.h | 28 +- kernel/sched/sched.h | 23 +- tools/include/uapi/linux/sched.h | 4 +- - 12 files changed, 697 insertions(+), 717 deletions(-) + 12 files changed, 756 insertions(+), 717 deletions(-) diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst index f67c0829350b..a39dfda3d032 100644 @@ -476,7 +476,7 @@ index 8d64fba16cfe..e0d10ac21016 100644 P(dl.runtime); P(dl.deadline); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index 115be8a965f2..76bd212ee5bd 100644 +index 0f92281fbed9..917f0cc106b6 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -47,6 +47,7 @@ @@ -608,7 +608,7 @@ index 115be8a965f2..76bd212ee5bd 100644 const struct sched_class fair_sched_class; -@@ -619,35 +569,203 @@ static inline bool entity_before(const struct sched_entity *a, +@@ -619,35 +569,229 @@ static inline bool entity_before(const struct sched_entity *a, return (s64)(a->vruntime - b->vruntime) < 0; } @@ -624,34 +624,60 @@ index 115be8a965f2..76bd212ee5bd 100644 +/* + * Compute virtual time from the per-task service numbers: + * -+ * Fair schedulers conserve lag: \Sum lag_i = 0 ++ * Fair schedulers conserve lag: + * -+ * lag_i = S - s_i = w_i * (V - v_i) ++ * \Sum lag_i = 0 + * -+ * \Sum lag_i = 0 -> \Sum w_i * (V - v_i) = V * \Sum w_i - \Sum w_i * v_i = 0 ++ * Where lag_i is given by: + * -+ * From which we solve V: ++ * lag_i = S - s_i = w_i * (V - v_i) + * -+ * \Sum v_i * w_i -+ * V = -------------- -+ * \Sum w_i ++ * Where S is the ideal service time and V is it's virtual time counterpart. ++ * Therefore: ++ * ++ * \Sum lag_i = 0 ++ * \Sum w_i * (V - v_i) = 0 ++ * \Sum w_i * V - w_i * v_i = 0 ++ * ++ * From which we can solve an expression for V in v_i (which we have in ++ * se->vruntime): ++ * ++ * \Sum v_i * w_i \Sum v_i * w_i ++ * V = -------------- = -------------- ++ * \Sum w_i W ++ * ++ * Specifically, this is the weighted average of all entity virtual runtimes. ++ * ++ * [[ NOTE: this is only equal to the ideal scheduler under the condition ++ * that join/leave operations happen at lag_i = 0, otherwise the ++ * virtual time has non-continguous motion equivalent to: ++ * ++ * V +-= lag_i / W ++ * ++ * Also see the comment in place_entity() that deals with this. ]] + * + * However, since v_i is u64, and the multiplcation could easily overflow + * transform it into a relative form that uses smaller quantities: + * -+ * Substitute: v_i == (v_i - v) + v ++ * Substitute: v_i == (v_i - v0) + v0 + * -+ * \Sum ((v_i - v) + v) * w_i \Sum (v_i - v) * w_i -+ * V = -------------------------- = -------------------- + v -+ * \Sum w_i \Sum w_i ++ * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i ++ * V = ---------------------------- = --------------------- + v0 ++ * W W + * -+ * min_vruntime = v -+ * avg_vruntime = \Sum (v_i - v) * w_i -+ * cfs_rq->load = \Sum w_i ++ * Which we track using: ++ * ++ * v0 := cfs_rq->min_vruntime ++ * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime ++ * \Sum w_i := cfs_rq->avg_load + * + * Since min_vruntime is a monotonic increasing variable that closely tracks + * the per-task service, these deltas: (v_i - v), will be in the order of the + * maximal (virtual) lag induced in the system due to quantisation. ++ * ++ * Also, we use scale_load_down() to reduce the size. ++ * ++ * As measured, the max (key * weight) value was ~44 bits for a kernel build. + */ +static void +avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) @@ -829,7 +855,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) -@@ -655,17 +773,51 @@ static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) +@@ -655,17 +799,51 @@ static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) return entity_before(__node_2_se(a), __node_2_se(b)); } @@ -883,7 +909,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) -@@ -678,14 +830,81 @@ struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) +@@ -678,14 +856,81 @@ struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) return __node_2_se(left); } @@ -929,7 +955,8 @@ index 115be8a965f2..76bd212ee5bd 100644 + node = node->rb_left; + continue; + } -+ + +- return __node_2_se(next); + /* + * If this entity has an earlier deadline than the previous + * best, take this one. If it also has the earliest deadline @@ -964,13 +991,12 @@ index 115be8a965f2..76bd212ee5bd 100644 + return left; + } + } - -- return __node_2_se(next); ++ + return best; } #ifdef CONFIG_SCHED_DEBUG -@@ -707,104 +926,43 @@ int sched_update_scaling(void) +@@ -707,104 +952,43 @@ int sched_update_scaling(void) { unsigned int factor = get_update_sysctl_factor(); @@ -997,12 +1023,12 @@ index 115be8a965f2..76bd212ee5bd 100644 { - if (unlikely(se->load.weight != NICE_0_LOAD)) - delta = __calc_delta(delta, NICE_0_LOAD, &se->load); +- +- return delta; +-} + u32 weight = sched_prio_to_weight[prio]; + u64 base = sysctl_sched_base_slice; -- return delta; --} -- -/* - * The idea is to set a period in which each task runs once. - * @@ -1096,7 +1122,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } #include "pelt.h" -@@ -939,6 +1097,7 @@ static void update_curr(struct cfs_rq *cfs_rq) +@@ -939,6 +1123,7 @@ static void update_curr(struct cfs_rq *cfs_rq) schedstat_add(cfs_rq->exec_clock, delta_exec); curr->vruntime += calc_delta_fair(delta_exec, curr); @@ -1104,7 +1130,7 @@ index 115be8a965f2..76bd212ee5bd 100644 update_min_vruntime(cfs_rq); if (entity_is_task(curr)) { -@@ -3336,16 +3495,28 @@ dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { } +@@ -3336,16 +3521,28 @@ dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { } static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, unsigned long weight) { @@ -1133,7 +1159,7 @@ index 115be8a965f2..76bd212ee5bd 100644 #ifdef CONFIG_SMP do { u32 divider = get_pelt_divider(&se->avg); -@@ -3355,9 +3526,11 @@ static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, +@@ -3355,9 +3552,11 @@ static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, #endif enqueue_load_avg(cfs_rq, se); @@ -1147,7 +1173,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } void reweight_task(struct task_struct *p, int prio) -@@ -4653,158 +4826,135 @@ static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {} +@@ -4653,158 +4852,168 @@ static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {} #endif /* CONFIG_SMP */ @@ -1211,20 +1237,53 @@ index 115be8a965f2..76bd212ee5bd 100644 + * If we want to place a task and preserve lag, we have to + * consider the effect of the new entity on the weighted + * average and compensate for this, otherwise lag can quickly -+ * evaporate: ++ * evaporate. + * -+ * l_i = V - v_i <=> v_i = V - l_i ++ * Lag is defined as: + * -+ * V = v_avg = W*v_avg / W ++ * lag_i = S - s_i = w_i * (V - v_i) + * -+ * V' = (W*v_avg + w_i*v_i) / (W + w_i) -+ * = (W*v_avg + w_i(v_avg - l_i)) / (W + w_i) -+ * = v_avg + w_i*l_i/(W + w_i) ++ * To avoid the 'w_i' term all over the place, we only track ++ * the virtual lag: + * -+ * l_i' = V' - v_i = v_avg + w_i*l_i/(W + w_i) - (v_avg - l) -+ * = l_i - w_i*l_i/(W + w_i) ++ * vl_i = V - v_i <=> v_i = V - vl_i + * -+ * l_i = (W + w_i) * l_i' / W ++ * And we take V to be the weighted average of all v: ++ * ++ * V = (\Sum w_j*v_j) / W ++ * ++ * Where W is: \Sum w_j ++ * ++ * Then, the weighted average after adding an entity with lag ++ * vl_i is given by: ++ * ++ * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) ++ * = (W*V + w_i*(V - vl_i)) / (W + w_i) ++ * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) ++ * = (V*(W + w_i) - w_i*l) / (W + w_i) ++ * = V - w_i*vl_i / (W + w_i) ++ * ++ * And the actual lag after adding an entity with vl_i is: ++ * ++ * vl'_i = V' - v_i ++ * = V - w_i*vl_i / (W + w_i) - (V - vl_i) ++ * = vl_i - w_i*vl_i / (W + w_i) ++ * ++ * Which is strictly less than vl_i. So in order to preserve lag ++ * we should inflate the lag before placement such that the ++ * effective lag after placement comes out right. ++ * ++ * As such, invert the above relation for vl'_i to get the vl_i ++ * we need to use such that the lag after placement is the lag ++ * we computed before dequeue. ++ * ++ * vl'_i = vl_i - w_i*vl_i / (W + w_i) ++ * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) ++ * ++ * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i ++ * = W*vl_i ++ * ++ * vl_i = (W + w_i)*vl'_i / W + */ + load = cfs_rq->avg_load; + if (curr && curr->on_rq) @@ -1403,7 +1462,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* * When enqueuing a sched_entity, we must: * - Update loads to have both entity and cfs_rq synced with now. -@@ -4816,18 +4966,28 @@ enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) +@@ -4816,18 +5025,28 @@ enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) */ update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); se_update_runnable(se); @@ -1435,7 +1494,7 @@ index 115be8a965f2..76bd212ee5bd 100644 if (!curr) __enqueue_entity(cfs_rq, se); se->on_rq = 1; -@@ -4839,17 +4999,6 @@ enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) +@@ -4839,17 +5058,6 @@ enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) } } @@ -1453,7 +1512,7 @@ index 115be8a965f2..76bd212ee5bd 100644 static void __clear_buddies_next(struct sched_entity *se) { for_each_sched_entity(se) { -@@ -4861,27 +5010,10 @@ static void __clear_buddies_next(struct sched_entity *se) +@@ -4861,27 +5069,10 @@ static void __clear_buddies_next(struct sched_entity *se) } } @@ -1481,7 +1540,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); -@@ -4915,20 +5047,12 @@ dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) +@@ -4915,20 +5106,12 @@ dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) clear_buddies(cfs_rq, se); @@ -1503,7 +1562,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* return excess runtime on last dequeue */ return_cfs_rq_runtime(cfs_rq); -@@ -4953,44 +5077,14 @@ dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) +@@ -4953,44 +5136,14 @@ dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) static void check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr) { @@ -1549,7 +1608,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static void -@@ -5031,9 +5125,6 @@ set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) +@@ -5031,9 +5184,6 @@ set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) se->prev_sum_exec_runtime = se->sum_exec_runtime; } @@ -1559,30 +1618,27 @@ index 115be8a965f2..76bd212ee5bd 100644 /* * Pick the next process, keeping these things in mind, in this order: * 1) keep things fair between processes/task groups -@@ -5044,50 +5135,14 @@ wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se); +@@ -5044,50 +5194,14 @@ wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se); static struct sched_entity * pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr) { - struct sched_entity *left = __pick_first_entity(cfs_rq); - struct sched_entity *se; - - /* +- /* - * If curr is set we have to see if its left of the leftmost entity - * still in the tree, provided there was anything in the tree at all. -+ * Enabling NEXT_BUDDY will affect latency but not fairness. - */ +- */ - if (!left || (curr && entity_before(curr, left))) - left = curr; - - se = left; /* ideally we run the leftmost entity */ -+ if (sched_feat(NEXT_BUDDY) && -+ cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) -+ return cfs_rq->next; - -- /* +- + /* - * Avoid running the skip buddy, if running something else can - * be done without getting too unfair. -- */ ++ * Enabling NEXT_BUDDY will affect latency but not fairness. + */ - if (cfs_rq->skip && cfs_rq->skip == se) { - struct sched_entity *second; - @@ -1597,7 +1653,10 @@ index 115be8a965f2..76bd212ee5bd 100644 - if (second && wakeup_preempt_entity(second, left) < 1) - se = second; - } -- ++ if (sched_feat(NEXT_BUDDY) && ++ cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) ++ return cfs_rq->next; + - if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) { - /* - * Someone really wants this to run. If it's not unfair, run it. @@ -1615,7 +1674,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq); -@@ -5104,8 +5159,6 @@ static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) +@@ -5104,8 +5218,6 @@ static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) /* throttle cfs_rqs exceeding runtime */ check_cfs_rq_runtime(cfs_rq); @@ -1624,7 +1683,7 @@ index 115be8a965f2..76bd212ee5bd 100644 if (prev->on_rq) { update_stats_wait_start_fair(cfs_rq, prev); /* Put 'current' back into the tree. */ -@@ -6149,13 +6202,12 @@ static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} +@@ -6149,13 +6261,12 @@ static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} static void hrtick_start_fair(struct rq *rq, struct task_struct *p) { struct sched_entity *se = &p->se; @@ -1639,7 +1698,7 @@ index 115be8a965f2..76bd212ee5bd 100644 s64 delta = slice - ran; if (delta < 0) { -@@ -6179,8 +6231,7 @@ static void hrtick_update(struct rq *rq) +@@ -6179,8 +6290,7 @@ static void hrtick_update(struct rq *rq) if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class) return; @@ -1649,7 +1708,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } #else /* !CONFIG_SCHED_HRTICK */ static inline void -@@ -6221,17 +6272,6 @@ static int sched_idle_rq(struct rq *rq) +@@ -6221,17 +6331,6 @@ static int sched_idle_rq(struct rq *rq) rq->nr_running); } @@ -1667,7 +1726,7 @@ index 115be8a965f2..76bd212ee5bd 100644 #ifdef CONFIG_SMP static int sched_idle_cpu(int cpu) { -@@ -6333,18 +6373,6 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) +@@ -6333,18 +6432,6 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) static void set_next_buddy(struct sched_entity *se); @@ -1686,7 +1745,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* * The dequeue_task method is called before nr_running is * decreased. We remove the task from the rbtree and -@@ -6417,7 +6445,6 @@ static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) +@@ -6417,7 +6504,6 @@ static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) dequeue_throttle: util_est_update(&rq->cfs, p, task_sleep); @@ -1694,7 +1753,7 @@ index 115be8a965f2..76bd212ee5bd 100644 hrtick_update(rq); } -@@ -6551,23 +6578,6 @@ static int wake_wide(struct task_struct *p) +@@ -6551,23 +6637,6 @@ static int wake_wide(struct task_struct *p) return 1; } @@ -1718,7 +1777,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* * The purpose of wake_affine() is to quickly determine on which CPU we can run * soonest. For the purpose of speed we only consider the waking and previous -@@ -6604,11 +6614,6 @@ wake_affine_idle(int this_cpu, int prev_cpu, int sync) +@@ -6604,11 +6673,6 @@ wake_affine_idle(int this_cpu, int prev_cpu, int sync) if (available_idle_cpu(prev_cpu)) return prev_cpu; @@ -1730,7 +1789,7 @@ index 115be8a965f2..76bd212ee5bd 100644 return nr_cpumask_bits; } -@@ -6983,20 +6988,6 @@ static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool +@@ -6983,20 +7047,6 @@ static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool /* overloaded LLC is unlikely to have idle cpu/core */ if (nr == 1) return -1; @@ -1751,7 +1810,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } } -@@ -7729,18 +7720,6 @@ static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) +@@ -7729,18 +7779,6 @@ static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) { struct sched_entity *se = &p->se; @@ -1770,7 +1829,7 @@ index 115be8a965f2..76bd212ee5bd 100644 if (!task_on_rq_migrating(p)) { remove_entity_load_avg(se); -@@ -7778,66 +7757,6 @@ balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) +@@ -7778,66 +7816,6 @@ balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) } #endif /* CONFIG_SMP */ @@ -1837,7 +1896,7 @@ index 115be8a965f2..76bd212ee5bd 100644 static void set_next_buddy(struct sched_entity *se) { for_each_sched_entity(se) { -@@ -7849,12 +7768,6 @@ static void set_next_buddy(struct sched_entity *se) +@@ -7849,12 +7827,6 @@ static void set_next_buddy(struct sched_entity *se) } } @@ -1850,7 +1909,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* * Preempt the current task with a newly woken task if needed: */ -@@ -7863,7 +7776,6 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ +@@ -7863,7 +7835,6 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ struct task_struct *curr = rq->curr; struct sched_entity *se = &curr->se, *pse = &p->se; struct cfs_rq *cfs_rq = task_cfs_rq(curr); @@ -1858,7 +1917,7 @@ index 115be8a965f2..76bd212ee5bd 100644 int next_buddy_marked = 0; int cse_is_idle, pse_is_idle; -@@ -7879,7 +7791,7 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ +@@ -7879,7 +7850,7 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ if (unlikely(throttled_hierarchy(cfs_rq_of(pse)))) return; @@ -1867,7 +1926,7 @@ index 115be8a965f2..76bd212ee5bd 100644 set_next_buddy(pse); next_buddy_marked = 1; } -@@ -7924,35 +7836,19 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ +@@ -7924,35 +7895,19 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ if (cse_is_idle != pse_is_idle) return; @@ -1910,7 +1969,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } #ifdef CONFIG_SMP -@@ -8153,8 +8049,6 @@ static void put_prev_task_fair(struct rq *rq, struct task_struct *prev) +@@ -8153,8 +8108,6 @@ static void put_prev_task_fair(struct rq *rq, struct task_struct *prev) /* * sched_yield() is very simple @@ -1919,7 +1978,7 @@ index 115be8a965f2..76bd212ee5bd 100644 */ static void yield_task_fair(struct rq *rq) { -@@ -8170,21 +8064,19 @@ static void yield_task_fair(struct rq *rq) +@@ -8170,21 +8123,19 @@ static void yield_task_fair(struct rq *rq) clear_buddies(cfs_rq, se); @@ -1953,7 +2012,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) -@@ -8427,8 +8319,7 @@ static int task_hot(struct task_struct *p, struct lb_env *env) +@@ -8427,8 +8378,7 @@ static int task_hot(struct task_struct *p, struct lb_env *env) * Buddy candidates are cache hot: */ if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && @@ -1963,7 +2022,7 @@ index 115be8a965f2..76bd212ee5bd 100644 return 1; if (sysctl_sched_migration_cost == -1) -@@ -11932,8 +11823,8 @@ static void rq_offline_fair(struct rq *rq) +@@ -11942,8 +11892,8 @@ static void rq_offline_fair(struct rq *rq) static inline bool __entity_slice_used(struct sched_entity *se, int min_nr_tasks) { @@ -1973,7 +2032,7 @@ index 115be8a965f2..76bd212ee5bd 100644 return (rtime * min_nr_tasks > slice); } -@@ -12077,8 +11968,8 @@ static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) +@@ -12087,8 +12037,8 @@ static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) */ static void task_fork_fair(struct task_struct *p) { @@ -1983,7 +2042,7 @@ index 115be8a965f2..76bd212ee5bd 100644 struct rq *rq = this_rq(); struct rq_flags rf; -@@ -12087,22 +11978,9 @@ static void task_fork_fair(struct task_struct *p) +@@ -12097,22 +12047,9 @@ static void task_fork_fair(struct task_struct *p) cfs_rq = task_cfs_rq(current); curr = cfs_rq->curr; @@ -2008,7 +2067,7 @@ index 115be8a965f2..76bd212ee5bd 100644 rq_unlock(rq, &rf); } -@@ -12131,34 +12009,6 @@ prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio) +@@ -12141,34 +12078,6 @@ prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio) check_preempt_curr(rq, p, 0); } @@ -2043,7 +2102,7 @@ index 115be8a965f2..76bd212ee5bd 100644 #ifdef CONFIG_FAIR_GROUP_SCHED /* * Propagate the changes of the sched_entity across the tg tree to make it -@@ -12229,16 +12079,6 @@ static void attach_entity_cfs_rq(struct sched_entity *se) +@@ -12239,16 +12148,6 @@ static void attach_entity_cfs_rq(struct sched_entity *se) static void detach_task_cfs_rq(struct task_struct *p) { struct sched_entity *se = &p->se; @@ -2060,7 +2119,7 @@ index 115be8a965f2..76bd212ee5bd 100644 detach_entity_cfs_rq(se); } -@@ -12246,12 +12086,8 @@ static void detach_task_cfs_rq(struct task_struct *p) +@@ -12256,12 +12155,8 @@ static void detach_task_cfs_rq(struct task_struct *p) static void attach_task_cfs_rq(struct task_struct *p) { struct sched_entity *se = &p->se; @@ -2073,7 +2132,7 @@ index 115be8a965f2..76bd212ee5bd 100644 } static void switched_from_fair(struct rq *rq, struct task_struct *p) -@@ -12362,6 +12198,7 @@ int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) +@@ -12372,6 +12267,7 @@ int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) goto err; tg->shares = NICE_0_LOAD; @@ -2081,7 +2140,7 @@ index 115be8a965f2..76bd212ee5bd 100644 init_cfs_bandwidth(tg_cfs_bandwidth(tg)); -@@ -12460,6 +12297,9 @@ void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, +@@ -12470,6 +12366,9 @@ void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, } se->my_q = cfs_rq; @@ -2091,7 +2150,7 @@ index 115be8a965f2..76bd212ee5bd 100644 /* guarantee group entities always have weight */ update_load_set(&se->load, NICE_0_LOAD); se->parent = parent; -@@ -12590,6 +12430,29 @@ int sched_group_set_idle(struct task_group *tg, long idle) +@@ -12600,6 +12499,29 @@ int sched_group_set_idle(struct task_group *tg, long idle) return 0; } @@ -2121,7 +2180,7 @@ index 115be8a965f2..76bd212ee5bd 100644 #else /* CONFIG_FAIR_GROUP_SCHED */ void free_fair_sched_group(struct task_group *tg) { } -@@ -12616,7 +12479,7 @@ static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task +@@ -12626,7 +12548,7 @@ static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task * idle runqueue: */ if (rq->cfs.load.weight) diff --git a/patches/0003-bore.patch b/patches/0003-bore.patch deleted file mode 100644 index 09b4f45..0000000 --- a/patches/0003-bore.patch +++ /dev/null @@ -1,424 +0,0 @@ -From d1d05832308e210422f7c52d052b026deb9fabf1 Mon Sep 17 00:00:00 2001 -From: Peter Jung -Date: Thu, 6 Apr 2023 19:12:01 +0200 -Subject: [PATCH] bore - -Signed-off-by: Peter Jung ---- - include/linux/sched.h | 6 ++ - init/Kconfig | 20 ++++++ - kernel/sched/core.c | 30 ++++++++ - kernel/sched/debug.c | 3 + - kernel/sched/fair.c | 149 +++++++++++++++++++++++++++++++++++++++- - kernel/sched/features.h | 8 +++ - 6 files changed, 213 insertions(+), 3 deletions(-) - -diff --git a/include/linux/sched.h b/include/linux/sched.h -index 63d242164b1a..39a046d6cf90 100644 ---- a/include/linux/sched.h -+++ b/include/linux/sched.h -@@ -555,6 +555,12 @@ struct sched_entity { - u64 sum_exec_runtime; - u64 vruntime; - u64 prev_sum_exec_runtime; -+#ifdef CONFIG_SCHED_BORE -+ u64 prev_burst_time; -+ u64 burst_time; -+ u64 max_burst_time; -+ u8 penalty_score; -+#endif // CONFIG_SCHED_BORE - - u64 nr_migrations; - -diff --git a/init/Kconfig b/init/Kconfig -index 1fb5f313d18f..6595e5ed2416 100644 ---- a/init/Kconfig -+++ b/init/Kconfig -@@ -1285,6 +1285,26 @@ config CHECKPOINT_RESTORE - - If unsure, say N here. - -+config SCHED_BORE -+ bool "Burst-Oriented Response Enhancer" -+ default y -+ help -+ In Desktop and Mobile computing, one might prefer interactive -+ tasks to keep responsive no matter what they run in the background. -+ -+ Enabling this kernel feature modifies the scheduler to discriminate -+ tasks by their burst time (runtime since it last went sleeping or -+ yielding state) and prioritize those that run less bursty. -+ Such tasks usually include window compositor, widgets backend, -+ terminal emulator, video playback, games and so on. -+ With a little impact to scheduling fairness, it may improve -+ responsiveness especially under heavy background workload. -+ -+ You can turn it off by setting the sysctl kernel.sched_bore = 0. -+ Enabling this feature implies NO_GENTLE_FAIR_SLEEPERS by default. -+ -+ If unsure say Y here. -+ - config SCHED_AUTOGROUP - bool "Automatic process group scheduling" - select CGROUPS -diff --git a/kernel/sched/core.c b/kernel/sched/core.c -index 0d18c3969f90..34db768f6ba8 100644 ---- a/kernel/sched/core.c -+++ b/kernel/sched/core.c -@@ -4418,6 +4418,22 @@ int wake_up_state(struct task_struct *p, unsigned int state) - return try_to_wake_up(p, state, 0); - } - -+#ifdef CONFIG_SCHED_BORE -+static inline void adjust_prev_burst(struct task_struct *p) -+{ -+ u32 cnt = 0; -+ u64 sum = 0, avg = 0; -+ struct task_struct *sib; -+ list_for_each_entry(sib, &p->sibling, sibling) { -+ cnt++; -+ sum += sib->se.max_burst_time >> 8; -+ } -+ if (cnt) avg = div_u64(sum, cnt) << 8; -+ if (p->se.prev_burst_time < avg) p->se.prev_burst_time = avg; -+ p->se.max_burst_time = p->se.prev_burst_time; -+} -+#endif // CONFIG_SCHED_BORE -+ - /* - * Perform scheduler related setup for a newly forked process p. - * p is forked by current. -@@ -4434,6 +4450,9 @@ static void __sched_fork(unsigned long clone_flags, struct task_struct *p) - p->se.prev_sum_exec_runtime = 0; - p->se.nr_migrations = 0; - p->se.vruntime = 0; -+#ifdef CONFIG_SCHED_BORE -+ p->se.burst_time = 0; -+#endif // CONFIG_SCHED_BORE - INIT_LIST_HEAD(&p->se.group_node); - - #ifdef CONFIG_FAIR_GROUP_SCHED -@@ -4659,6 +4678,9 @@ late_initcall(sched_core_sysctl_init); - int sched_fork(unsigned long clone_flags, struct task_struct *p) - { - __sched_fork(clone_flags, p); -+#ifdef CONFIG_SCHED_BORE -+ adjust_prev_burst(p); -+#endif // CONFIG_SCHED_BORE - /* - * We mark the process as NEW here. This guarantees that - * nobody will actually run it, and a signal or other external -@@ -9126,6 +9148,10 @@ void __init init_idle(struct task_struct *idle, int cpu) - - idle->__state = TASK_RUNNING; - idle->se.exec_start = sched_clock(); -+#ifdef CONFIG_SCHED_BORE -+ idle->se.prev_burst_time = 0; -+ idle->se.max_burst_time = 0; -+#endif //CONFIG_SCHED_BORE - /* - * PF_KTHREAD should already be set at this point; regardless, make it - * look like a proper per-CPU kthread. -@@ -9793,6 +9819,10 @@ void __init sched_init(void) - BUG_ON(&dl_sched_class != &stop_sched_class + 1); - #endif - -+#ifdef CONFIG_SCHED_BORE -+ printk(KERN_INFO "BORE (Burst-Oriented Response Enhancer) CPU Scheduler modification 2.1.1 by Masahito Suzuki"); -+#endif // CONFIG_SCHED_BORE -+ - wait_bit_init(); - - #ifdef CONFIG_FAIR_GROUP_SCHED -diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c -index 1637b65ba07a..752c43a9ff13 100644 ---- a/kernel/sched/debug.c -+++ b/kernel/sched/debug.c -@@ -547,6 +547,9 @@ print_task(struct seq_file *m, struct rq *rq, struct task_struct *p) - SPLIT_NS(schedstat_val_or_zero(p->stats.sum_sleep_runtime)), - SPLIT_NS(schedstat_val_or_zero(p->stats.sum_block_runtime))); - -+#ifdef CONFIG_SCHED_BORE -+ SEQ_printf(m, " %2d", p->se.penalty_score); -+#endif - #ifdef CONFIG_NUMA_BALANCING - SEQ_printf(m, " %d %d", task_node(p), task_numa_group_id(p)); - #endif -diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index 6986ea31c984..ee461e4586ca 100644 ---- a/kernel/sched/fair.c -+++ b/kernel/sched/fair.c -@@ -19,6 +19,9 @@ - * - * Adaptive scheduling granularity, math enhancements by Peter Zijlstra - * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra -+ * -+ * Burst-Oriented Response Enhancer (BORE) CPU Scheduler -+ * Copyright (C) 2021-2023 Masahito Suzuki - */ - #include - #include -@@ -126,6 +129,16 @@ static unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL; - - const_debug unsigned int sysctl_sched_migration_cost = 500000UL; - -+#ifdef CONFIG_SCHED_BORE -+unsigned int __read_mostly sched_bore = 3; -+unsigned int __read_mostly sched_burst_penalty_offset = 12; -+unsigned int __read_mostly sched_burst_penalty_scale = 1292; -+unsigned int __read_mostly sched_burst_smoothness = 1; -+static int three = 3; -+static int sixty_four = 64; -+static int maxval_12_bits = 4095; -+#endif // CONFIG_SCHED_BORE -+ - int sched_thermal_decay_shift; - static int __init setup_sched_thermal_decay_shift(char *str) - { -@@ -185,6 +198,44 @@ static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536; - - #ifdef CONFIG_SYSCTL - static struct ctl_table sched_fair_sysctls[] = { -+#ifdef CONFIG_SCHED_BORE -+ { -+ .procname = "sched_bore", -+ .data = &sched_bore, -+ .maxlen = sizeof(unsigned int), -+ .mode = 0644, -+ .proc_handler = &proc_dointvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &three, -+ }, -+ { -+ .procname = "sched_burst_penalty_offset", -+ .data = &sched_burst_penalty_offset, -+ .maxlen = sizeof(unsigned int), -+ .mode = 0644, -+ .proc_handler = &proc_dointvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &sixty_four, -+ }, -+ { -+ .procname = "sched_burst_penalty_scale", -+ .data = &sched_burst_penalty_scale, -+ .maxlen = sizeof(unsigned int), -+ .mode = 0644, -+ .proc_handler = &proc_dointvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &maxval_12_bits, -+ }, -+ { -+ .procname = "sched_burst_smoothness", -+ .data = &sched_burst_smoothness, -+ .maxlen = sizeof(unsigned int), -+ .mode = 0644, -+ .proc_handler = &proc_dointvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &three, -+ }, -+#endif // CONFIG_SCHED_BORE - { - .procname = "sched_child_runs_first", - .data = &sysctl_sched_child_runs_first, -@@ -891,6 +942,47 @@ static void update_tg_load_avg(struct cfs_rq *cfs_rq) - } - #endif /* CONFIG_SMP */ - -+#ifdef CONFIG_SCHED_BORE -+static inline u32 __calc_bits10(u64 burst_time) { -+ u32 bits = fls64(burst_time); -+ u32 fdigs = likely(bits) ? bits - 1 : 0; -+ return (bits << 10) | (burst_time << (64 - fdigs) >> 54); -+} -+ -+static inline u32 __calc_burst_score(u32 bits10, u32 offset) { -+ u32 val10 = max((s32)0, (s32)bits10 - (s32)(offset << 10)); -+ return min((u32)39, val10 * sched_burst_penalty_scale >> 20); -+} -+ -+static void update_burst_score(struct sched_entity *se) { -+ u32 bits10 = __calc_bits10(se->max_burst_time); -+ se->penalty_score = __calc_burst_score(bits10, sched_burst_penalty_offset); -+} -+ -+static inline u64 penalty_scale(u64 delta, struct sched_entity *se) { -+ return mul_u64_u32_shr(delta, sched_prio_to_wmult[se->penalty_score], 22); -+} -+ -+static inline u64 preempt_scale( -+ u64 delta, struct sched_entity *curr, struct sched_entity *se) { -+ -+ u32 score = max(0, (s32)se->penalty_score - (s32)curr->penalty_score) >> 1; -+ return mul_u64_u32_shr(delta, sched_prio_to_wmult[min(39, 20 + score)], 22); -+} -+ -+static inline u64 binary_smooth(u64 old, u64 new, unsigned int smoothness) { -+ return (new + old * ((1 << smoothness) - 1)) >> smoothness; -+} -+ -+static void reset_burst(struct sched_entity *se) { -+ se->prev_burst_time = binary_smooth( -+ se->prev_burst_time, se->burst_time, sched_burst_smoothness); -+ se->burst_time = 0; -+ -+ se->max_burst_time = se->prev_burst_time; -+} -+#endif // CONFIG_SCHED_BORE -+ - /* - * Update the current task's runtime statistics. - */ -@@ -920,6 +1012,14 @@ static void update_curr(struct cfs_rq *cfs_rq) - curr->sum_exec_runtime += delta_exec; - schedstat_add(cfs_rq->exec_clock, delta_exec); - -+#ifdef CONFIG_SCHED_BORE -+ curr->burst_time += delta_exec; -+ curr->max_burst_time = max(curr->max_burst_time, curr->burst_time); -+ update_burst_score(curr); -+ if (sched_bore & 1) -+ curr->vruntime += penalty_scale(calc_delta_fair(delta_exec, curr), curr); -+ else -+#endif // CONFIG_SCHED_BORE - curr->vruntime += calc_delta_fair(delta_exec, curr); - update_min_vruntime(cfs_rq); - -@@ -5013,8 +5113,14 @@ set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) - se->prev_sum_exec_runtime = se->sum_exec_runtime; - } - -+#ifdef CONFIG_SCHED_BORE -+static int -+wakeup_preempt_entity_bscale(struct sched_entity *curr, -+ struct sched_entity *se, bool do_scale); -+#else // CONFIG_SCHED_BORE - static int - wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se); -+#endif // CONFIG_SCHED_BORE - - /* - * Pick the next process, keeping these things in mind, in this order: -@@ -5053,16 +5159,34 @@ pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr) - second = curr; - } - -+#ifdef CONFIG_SCHED_BORE -+ if (second && wakeup_preempt_entity_bscale( -+ second, left, sched_bore & 2) < 1) -+#else // CONFIG_SCHED_BORE - if (second && wakeup_preempt_entity(second, left) < 1) -+#endif // CONFIG_SCHED_BORE - se = second; - } - -- if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) { -+#ifdef CONFIG_SCHED_BORE -+ if (cfs_rq->next && wakeup_preempt_entity_bscale( -+ cfs_rq->next, left, sched_bore & 2) < 1) -+#else // CONFIG_SCHED_BORE -+ if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) -+#endif // CONFIG_SCHED_BORE -+ { - /* - * Someone really wants this to run. If it's not unfair, run it. - */ - se = cfs_rq->next; -- } else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) { -+ } -+#ifdef CONFIG_SCHED_BORE -+ else if (cfs_rq->last && wakeup_preempt_entity_bscale( -+ cfs_rq->last, left, sched_bore & 2) < 1) -+#else // CONFIG_SCHED_BORE -+ else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) -+#endif // CONFIG_SCHED_BORE -+ { - /* - * Prefer last buddy, try to return the CPU to a preempted task. - */ -@@ -6331,6 +6455,9 @@ static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) - util_est_dequeue(&rq->cfs, p); - - for_each_sched_entity(se) { -+#ifdef CONFIG_SCHED_BORE -+ if (task_sleep) reset_burst(se); -+#endif // CONFIG_SCHED_BORE - cfs_rq = cfs_rq_of(se); - dequeue_entity(cfs_rq, se, flags); - -@@ -7746,7 +7873,12 @@ static unsigned long wakeup_gran(struct sched_entity *se) - * - */ - static int -+#ifdef CONFIG_SCHED_BORE -+wakeup_preempt_entity_bscale(struct sched_entity *curr, -+ struct sched_entity *se, bool do_scale) -+#else // CONFIG_SCHED_BORE - wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se) -+#endif // CONFIG_SCHED_BORE - { - s64 gran, vdiff = curr->vruntime - se->vruntime; - -@@ -7754,6 +7886,9 @@ wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se) - return -1; - - gran = wakeup_gran(se); -+#ifdef CONFIG_SCHED_BORE -+ if (do_scale) gran = preempt_scale(gran, curr, se); -+#endif // CONFIG_SCHED_BORE - if (vdiff > gran) - return 1; - -@@ -7858,7 +7993,12 @@ static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_ - return; - - update_curr(cfs_rq_of(se)); -- if (wakeup_preempt_entity(se, pse) == 1) { -+#ifdef CONFIG_SCHED_BORE -+ if (wakeup_preempt_entity_bscale(se, pse, sched_bore & 2) == 1) -+#else // CONFIG_SCHED_BORE -+ if (wakeup_preempt_entity(se, pse) == 1) -+#endif // CONFIG_SCHED_BORE -+ { - /* - * Bias pick_next to pick the sched entity that is - * triggering this preemption. -@@ -8094,6 +8234,9 @@ static void yield_task_fair(struct rq *rq) - struct task_struct *curr = rq->curr; - struct cfs_rq *cfs_rq = task_cfs_rq(curr); - struct sched_entity *se = &curr->se; -+#ifdef CONFIG_SCHED_BORE -+ reset_burst(se); -+#endif // CONFIG_SCHED_BORE - - /* - * Are we the only task in the tree? -diff --git a/kernel/sched/features.h b/kernel/sched/features.h -index ee7f23c76bd3..3115bde98211 100644 ---- a/kernel/sched/features.h -+++ b/kernel/sched/features.h -@@ -4,7 +4,11 @@ - * them to run sooner, but does not allow tons of sleepers to - * rip the spread apart. - */ -+#ifdef CONFIG_SCHED_BORE -+SCHED_FEAT(GENTLE_FAIR_SLEEPERS, false) -+#else // CONFIG_SCHED_BORE - SCHED_FEAT(GENTLE_FAIR_SLEEPERS, true) -+#endif // CONFIG_SCHED_BORE - - /* - * Place new tasks ahead so that they do not starve already running -@@ -17,7 +21,11 @@ SCHED_FEAT(START_DEBIT, true) - * wakeup-preemption), since its likely going to consume data we - * touched, increases cache locality. - */ -+#ifdef CONFIG_SCHED_BORE -+SCHED_FEAT(NEXT_BUDDY, true) -+#else // CONFIG_SCHED_BORE - SCHED_FEAT(NEXT_BUDDY, false) -+#endif // CONFIG_SCHED_BORE - - /* - * Prefer to schedule the task that ran last (when we did --- -2.40.0 diff --git a/patches/surface/0001-surface3-oemb.patch b/patches/surface/0001-surface3-oemb.patch new file mode 100644 index 0000000..f5efb3c --- /dev/null +++ b/patches/surface/0001-surface3-oemb.patch @@ -0,0 +1,101 @@ +From 67964b7a12cbfbc30d41534803dc6aa0c89d6383 Mon Sep 17 00:00:00 2001 +From: Tsuchiya Yuto +Date: Sun, 18 Oct 2020 16:42:44 +0900 +Subject: [PATCH] (surface3-oemb) add DMI matches for Surface 3 with broken DMI + table + +On some Surface 3, the DMI table gets corrupted for unknown reasons +and breaks existing DMI matching used for device-specific quirks. + +This commit adds the (broken) DMI data into dmi_system_id tables used +for quirks so that each driver can enable quirks even on the affected +systems. + +On affected systems, DMI data will look like this: + $ grep . /sys/devices/virtual/dmi/id/{bios_vendor,board_name,board_vendor,\ + chassis_vendor,product_name,sys_vendor} + /sys/devices/virtual/dmi/id/bios_vendor:American Megatrends Inc. + /sys/devices/virtual/dmi/id/board_name:OEMB + /sys/devices/virtual/dmi/id/board_vendor:OEMB + /sys/devices/virtual/dmi/id/chassis_vendor:OEMB + /sys/devices/virtual/dmi/id/product_name:OEMB + /sys/devices/virtual/dmi/id/sys_vendor:OEMB + +Expected: + $ grep . /sys/devices/virtual/dmi/id/{bios_vendor,board_name,board_vendor,\ + chassis_vendor,product_name,sys_vendor} + /sys/devices/virtual/dmi/id/bios_vendor:American Megatrends Inc. + /sys/devices/virtual/dmi/id/board_name:Surface 3 + /sys/devices/virtual/dmi/id/board_vendor:Microsoft Corporation + /sys/devices/virtual/dmi/id/chassis_vendor:Microsoft Corporation + /sys/devices/virtual/dmi/id/product_name:Surface 3 + /sys/devices/virtual/dmi/id/sys_vendor:Microsoft Corporation + +Signed-off-by: Tsuchiya Yuto +Patchset: surface3-oemb +--- + drivers/platform/surface/surface3-wmi.c | 7 +++++++ + sound/soc/codecs/rt5645.c | 9 +++++++++ + sound/soc/intel/common/soc-acpi-intel-cht-match.c | 8 ++++++++ + 3 files changed, 24 insertions(+) + +diff --git a/drivers/platform/surface/surface3-wmi.c b/drivers/platform/surface/surface3-wmi.c +index ca4602bcc7dea..490b9731068ae 100644 +--- a/drivers/platform/surface/surface3-wmi.c ++++ b/drivers/platform/surface/surface3-wmi.c +@@ -37,6 +37,13 @@ static const struct dmi_system_id surface3_dmi_table[] = { + DMI_MATCH(DMI_PRODUCT_NAME, "Surface 3"), + }, + }, ++ { ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ }, + #endif + { } + }; +diff --git a/sound/soc/codecs/rt5645.c b/sound/soc/codecs/rt5645.c +index 620ecbfa4a7a8..b07d06d2971a8 100644 +--- a/sound/soc/codecs/rt5645.c ++++ b/sound/soc/codecs/rt5645.c +@@ -3717,6 +3717,15 @@ static const struct dmi_system_id dmi_platform_data[] = { + }, + .driver_data = (void *)&intel_braswell_platform_data, + }, ++ { ++ .ident = "Microsoft Surface 3", ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ .driver_data = (void *)&intel_braswell_platform_data, ++ }, + { + /* + * Match for the GPDwin which unfortunately uses somewhat +diff --git a/sound/soc/intel/common/soc-acpi-intel-cht-match.c b/sound/soc/intel/common/soc-acpi-intel-cht-match.c +index 6beb00858c33f..d82d77387a0a6 100644 +--- a/sound/soc/intel/common/soc-acpi-intel-cht-match.c ++++ b/sound/soc/intel/common/soc-acpi-intel-cht-match.c +@@ -27,6 +27,14 @@ static const struct dmi_system_id cht_table[] = { + DMI_MATCH(DMI_PRODUCT_NAME, "Surface 3"), + }, + }, ++ { ++ .callback = cht_surface_quirk_cb, ++ .matches = { ++ DMI_MATCH(DMI_BIOS_VENDOR, "American Megatrends Inc."), ++ DMI_MATCH(DMI_SYS_VENDOR, "OEMB"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "OEMB"), ++ }, ++ }, + { } + }; + +-- +2.40.0 + diff --git a/patches/surface/0002-mwifiex.patch b/patches/surface/0002-mwifiex.patch new file mode 100644 index 0000000..9a82713 --- /dev/null +++ b/patches/surface/0002-mwifiex.patch @@ -0,0 +1,400 @@ +From efd716f5123331754ebfc53bccfef07e17fb328b Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Jonas=20Dre=C3=9Fler?= +Date: Tue, 3 Nov 2020 13:28:04 +0100 +Subject: [PATCH] mwifiex: Add quirk resetting the PCI bridge on MS Surface + devices + +The most recent firmware of the 88W8897 card reports a hardcoded LTR +value to the system during initialization, probably as an (unsuccessful) +attempt of the developers to fix firmware crashes. This LTR value +prevents most of the Microsoft Surface devices from entering deep +powersaving states (either platform C-State 10 or S0ix state), because +the exit latency of that state would be higher than what the card can +tolerate. + +Turns out the card works just the same (including the firmware crashes) +no matter if that hardcoded LTR value is reported or not, so it's kind +of useless and only prevents us from saving power. + +To get rid of those hardcoded LTR reports, it's possible to reset the +PCI bridge device after initializing the cards firmware. I'm not exactly +sure why that works, maybe the power management subsystem of the PCH +resets its stored LTR values when doing a function level reset of the +bridge device. Doing the reset once after starting the wifi firmware +works very well, probably because the firmware only reports that LTR +value a single time during firmware startup. + +Patchset: mwifiex +--- + drivers/net/wireless/marvell/mwifiex/pcie.c | 12 +++++++++ + .../wireless/marvell/mwifiex/pcie_quirks.c | 26 +++++++++++++------ + .../wireless/marvell/mwifiex/pcie_quirks.h | 1 + + 3 files changed, 31 insertions(+), 8 deletions(-) + +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie.c b/drivers/net/wireless/marvell/mwifiex/pcie.c +index 9a698a16a8f38..14687342bc81c 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie.c +@@ -1762,9 +1762,21 @@ mwifiex_pcie_send_boot_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb) + static int mwifiex_pcie_init_fw_port(struct mwifiex_adapter *adapter) + { + struct pcie_service_card *card = adapter->card; ++ struct pci_dev *pdev = card->dev; ++ struct pci_dev *parent_pdev = pci_upstream_bridge(pdev); + const struct mwifiex_pcie_card_reg *reg = card->pcie.reg; + int tx_wrap = card->txbd_wrptr & reg->tx_wrap_mask; + ++ /* Trigger a function level reset of the PCI bridge device, this makes ++ * the firmware of PCIe 88W8897 cards stop reporting a fixed LTR value ++ * that prevents the system from entering package C10 and S0ix powersaving ++ * states. ++ * We need to do it here because it must happen after firmware ++ * initialization and this function is called after that is done. ++ */ ++ if (card->quirks & QUIRK_DO_FLR_ON_BRIDGE) ++ pci_reset_function(parent_pdev); ++ + /* Write the RX ring read pointer in to reg->rx_rdptr */ + if (mwifiex_write_reg(adapter, reg->rx_rdptr, card->rxbd_rdptr | + tx_wrap)) { +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +index dd6d21f1dbfd7..f46b06f8d6435 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +@@ -13,7 +13,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Pro 5", +@@ -22,7 +23,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Pro 5 (LTE)", +@@ -31,7 +33,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Pro 6", +@@ -39,7 +42,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Book 1", +@@ -47,7 +51,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Book 2", +@@ -55,7 +60,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Laptop 1", +@@ -63,7 +69,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + { + .ident = "Surface Laptop 2", +@@ -71,7 +78,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"), + }, +- .driver_data = (void *)QUIRK_FW_RST_D3COLD, ++ .driver_data = (void *)(QUIRK_FW_RST_D3COLD | ++ QUIRK_DO_FLR_ON_BRIDGE), + }, + {} + }; +@@ -89,6 +97,8 @@ void mwifiex_initialize_quirks(struct pcie_service_card *card) + dev_info(&pdev->dev, "no quirks enabled\n"); + if (card->quirks & QUIRK_FW_RST_D3COLD) + dev_info(&pdev->dev, "quirk reset_d3cold enabled\n"); ++ if (card->quirks & QUIRK_DO_FLR_ON_BRIDGE) ++ dev_info(&pdev->dev, "quirk do_flr_on_bridge enabled\n"); + } + + static void mwifiex_pcie_set_power_d3cold(struct pci_dev *pdev) +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +index d6ff964aec5bf..5d30ae39d65ec 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +@@ -4,6 +4,7 @@ + #include "pcie.h" + + #define QUIRK_FW_RST_D3COLD BIT(0) ++#define QUIRK_DO_FLR_ON_BRIDGE BIT(1) + + void mwifiex_initialize_quirks(struct pcie_service_card *card); + int mwifiex_pcie_reset_d3cold_quirk(struct pci_dev *pdev); +-- +2.40.0 + +From 2de203271a35cc09eff860df2f35c5ca5e6ae52c Mon Sep 17 00:00:00 2001 +From: Tsuchiya Yuto +Date: Sun, 4 Oct 2020 00:11:49 +0900 +Subject: [PATCH] mwifiex: pcie: disable bridge_d3 for Surface gen4+ + +Currently, mwifiex fw will crash after suspend on recent kernel series. +On Windows, it seems that the root port of wifi will never enter D3 state +(stay on D0 state). And on Linux, disabling the D3 state for the +bridge fixes fw crashing after suspend. + +This commit disables the D3 state of root port on driver initialization +and fixes fw crashing after suspend. + +Signed-off-by: Tsuchiya Yuto +Patchset: mwifiex +--- + drivers/net/wireless/marvell/mwifiex/pcie.c | 7 +++++ + .../wireless/marvell/mwifiex/pcie_quirks.c | 27 +++++++++++++------ + .../wireless/marvell/mwifiex/pcie_quirks.h | 1 + + 3 files changed, 27 insertions(+), 8 deletions(-) + +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie.c b/drivers/net/wireless/marvell/mwifiex/pcie.c +index 14687342bc81c..5e1a341f63dff 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie.c +@@ -368,6 +368,7 @@ static int mwifiex_pcie_probe(struct pci_dev *pdev, + const struct pci_device_id *ent) + { + struct pcie_service_card *card; ++ struct pci_dev *parent_pdev = pci_upstream_bridge(pdev); + int ret; + + pr_debug("info: vendor=0x%4.04X device=0x%4.04X rev=%d\n", +@@ -409,6 +410,12 @@ static int mwifiex_pcie_probe(struct pci_dev *pdev, + return -1; + } + ++ /* disable bridge_d3 for Surface gen4+ devices to fix fw crashing ++ * after suspend ++ */ ++ if (card->quirks & QUIRK_NO_BRIDGE_D3) ++ parent_pdev->bridge_d3 = false; ++ + return 0; + } + +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +index f46b06f8d6435..99b024ecbadea 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.c +@@ -14,7 +14,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 5", +@@ -24,7 +25,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 5 (LTE)", +@@ -34,7 +36,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Pro 6", +@@ -43,7 +46,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Book 1", +@@ -52,7 +56,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Book 2", +@@ -61,7 +66,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Laptop 1", +@@ -70,7 +76,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + { + .ident = "Surface Laptop 2", +@@ -79,7 +86,8 @@ static const struct dmi_system_id mwifiex_quirk_table[] = { + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"), + }, + .driver_data = (void *)(QUIRK_FW_RST_D3COLD | +- QUIRK_DO_FLR_ON_BRIDGE), ++ QUIRK_DO_FLR_ON_BRIDGE | ++ QUIRK_NO_BRIDGE_D3), + }, + {} + }; +@@ -99,6 +107,9 @@ void mwifiex_initialize_quirks(struct pcie_service_card *card) + dev_info(&pdev->dev, "quirk reset_d3cold enabled\n"); + if (card->quirks & QUIRK_DO_FLR_ON_BRIDGE) + dev_info(&pdev->dev, "quirk do_flr_on_bridge enabled\n"); ++ if (card->quirks & QUIRK_NO_BRIDGE_D3) ++ dev_info(&pdev->dev, ++ "quirk no_brigde_d3 enabled\n"); + } + + static void mwifiex_pcie_set_power_d3cold(struct pci_dev *pdev) +diff --git a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +index 5d30ae39d65ec..c14eb56eb9118 100644 +--- a/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h ++++ b/drivers/net/wireless/marvell/mwifiex/pcie_quirks.h +@@ -5,6 +5,7 @@ + + #define QUIRK_FW_RST_D3COLD BIT(0) + #define QUIRK_DO_FLR_ON_BRIDGE BIT(1) ++#define QUIRK_NO_BRIDGE_D3 BIT(2) + + void mwifiex_initialize_quirks(struct pcie_service_card *card); + int mwifiex_pcie_reset_d3cold_quirk(struct pci_dev *pdev); +-- +2.40.0 + +From 16c7b19c13e1edab7f236baa59f8f685a4d719b4 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Jonas=20Dre=C3=9Fler?= +Date: Thu, 25 Mar 2021 11:33:02 +0100 +Subject: [PATCH] Bluetooth: btusb: Lower passive lescan interval on Marvell + 88W8897 + +The Marvell 88W8897 combined wifi and bluetooth card (pcie+usb version) +is used in a lot of Microsoft Surface devices, and all those devices +suffer from very low 2.4GHz wifi connection speeds while bluetooth is +enabled. The reason for that is that the default passive scanning +interval for Bluetooth Low Energy devices is quite high in Linux +(interval of 60 msec and scan window of 30 msec, see hci_core.c), and +the Marvell chip is known for its bad bt+wifi coexisting performance. + +So decrease that passive scan interval and make the scan window shorter +on this particular device to allow for spending more time transmitting +wifi signals: The new scan interval is 250 msec (0x190 * 0.625 msec) and +the new scan window is 6.25 msec (0xa * 0,625 msec). + +This change has a very large impact on the 2.4GHz wifi speeds and gets +it up to performance comparable with the Windows driver, which seems to +apply a similar quirk. + +The interval and window length were tested and found to work very well +with a lot of Bluetooth Low Energy devices, including the Surface Pen, a +Bluetooth Speaker and two modern Bluetooth headphones. All devices were +discovered immediately after turning them on. Even lower values were +also tested, but they introduced longer delays until devices get +discovered. + +Patchset: mwifiex +--- + drivers/bluetooth/btusb.c | 15 +++++++++++++++ + 1 file changed, 15 insertions(+) + +diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c +index 5c536151ef836..4de564dd1c604 100644 +--- a/drivers/bluetooth/btusb.c ++++ b/drivers/bluetooth/btusb.c +@@ -65,6 +65,7 @@ static struct usb_driver btusb_driver; + #define BTUSB_INTEL_BROKEN_INITIAL_NCMD BIT(25) + #define BTUSB_INTEL_NO_WBS_SUPPORT BIT(26) + #define BTUSB_ACTIONS_SEMI BIT(27) ++#define BTUSB_LOWER_LESCAN_INTERVAL BIT(28) + + static const struct usb_device_id btusb_table[] = { + /* Generic Bluetooth USB device */ +@@ -468,6 +469,7 @@ static const struct usb_device_id blacklist_table[] = { + { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL }, ++ { USB_DEVICE(0x1286, 0x204c), .driver_info = BTUSB_LOWER_LESCAN_INTERVAL }, + + /* Intel Bluetooth devices */ + { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_COMBINED }, +@@ -4033,6 +4035,19 @@ static int btusb_probe(struct usb_interface *intf, + if (id->driver_info & BTUSB_MARVELL) + hdev->set_bdaddr = btusb_set_bdaddr_marvell; + ++ /* The Marvell 88W8897 combined wifi and bluetooth card is known for ++ * very bad bt+wifi coexisting performance. ++ * ++ * Decrease the passive BT Low Energy scan interval a bit ++ * (0x0190 * 0.625 msec = 250 msec) and make the scan window shorter ++ * (0x000a * 0,625 msec = 6.25 msec). This allows for significantly ++ * higher wifi throughput while passively scanning for BT LE devices. ++ */ ++ if (id->driver_info & BTUSB_LOWER_LESCAN_INTERVAL) { ++ hdev->le_scan_interval = 0x0190; ++ hdev->le_scan_window = 0x000a; ++ } ++ + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) && + (id->driver_info & BTUSB_MEDIATEK)) { + hdev->setup = btusb_mtk_setup; +-- +2.40.0 + diff --git a/patches/surface/0003-ath10k.patch b/patches/surface/0003-ath10k.patch new file mode 100644 index 0000000..dbb4f0a --- /dev/null +++ b/patches/surface/0003-ath10k.patch @@ -0,0 +1,121 @@ +From b33823bea207cfd93a97f5af82c1e9fbdc9cbd2b Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sat, 27 Feb 2021 00:45:52 +0100 +Subject: [PATCH] ath10k: Add module parameters to override board files + +Some Surface devices, specifically the Surface Go and AMD version of the +Surface Laptop 3 (wich both come with QCA6174 WiFi chips), work better +with a different board file, as it seems that the firmeware included +upstream is buggy. + +As it is generally not a good idea to randomly overwrite files, let +alone doing so via packages, we add module parameters to override those +file names in the driver. This allows us to package/deploy the override +via a modprobe.d config. + +Signed-off-by: Maximilian Luz +Patchset: ath10k +--- + drivers/net/wireless/ath/ath10k/core.c | 58 ++++++++++++++++++++++++++ + 1 file changed, 58 insertions(+) + +diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c +index 5eb131ab916fd..67f074a126d1f 100644 +--- a/drivers/net/wireless/ath/ath10k/core.c ++++ b/drivers/net/wireless/ath/ath10k/core.c +@@ -38,6 +38,9 @@ static bool fw_diag_log; + /* frame mode values are mapped as per enum ath10k_hw_txrx_mode */ + unsigned int ath10k_frame_mode = ATH10K_HW_TXRX_NATIVE_WIFI; + ++static char *override_board = ""; ++static char *override_board2 = ""; ++ + unsigned long ath10k_coredump_mask = BIT(ATH10K_FW_CRASH_DUMP_REGISTERS) | + BIT(ATH10K_FW_CRASH_DUMP_CE_DATA); + +@@ -50,6 +53,9 @@ module_param(fw_diag_log, bool, 0644); + module_param_named(frame_mode, ath10k_frame_mode, uint, 0644); + module_param_named(coredump_mask, ath10k_coredump_mask, ulong, 0444); + ++module_param(override_board, charp, 0644); ++module_param(override_board2, charp, 0644); ++ + MODULE_PARM_DESC(debug_mask, "Debugging mask"); + MODULE_PARM_DESC(uart_print, "Uart target debugging"); + MODULE_PARM_DESC(skip_otp, "Skip otp failure for calibration in testmode"); +@@ -59,6 +65,9 @@ MODULE_PARM_DESC(frame_mode, + MODULE_PARM_DESC(coredump_mask, "Bitfield of what to include in firmware crash file"); + MODULE_PARM_DESC(fw_diag_log, "Diag based fw log debugging"); + ++MODULE_PARM_DESC(override_board, "Override for board.bin file"); ++MODULE_PARM_DESC(override_board2, "Override for board-2.bin file"); ++ + static const struct ath10k_hw_params ath10k_hw_params_list[] = { + { + .id = QCA988X_HW_2_0_VERSION, +@@ -911,6 +920,42 @@ static int ath10k_init_configure_target(struct ath10k *ar) + return 0; + } + ++static const char *ath10k_override_board_fw_file(struct ath10k *ar, ++ const char *file) ++{ ++ if (strcmp(file, "board.bin") == 0) { ++ if (strcmp(override_board, "") == 0) ++ return file; ++ ++ if (strcmp(override_board, "none") == 0) { ++ dev_info(ar->dev, "firmware override: pretending 'board.bin' does not exist\n"); ++ return NULL; ++ } ++ ++ dev_info(ar->dev, "firmware override: replacing 'board.bin' with '%s'\n", ++ override_board); ++ ++ return override_board; ++ } ++ ++ if (strcmp(file, "board-2.bin") == 0) { ++ if (strcmp(override_board2, "") == 0) ++ return file; ++ ++ if (strcmp(override_board2, "none") == 0) { ++ dev_info(ar->dev, "firmware override: pretending 'board-2.bin' does not exist\n"); ++ return NULL; ++ } ++ ++ dev_info(ar->dev, "firmware override: replacing 'board-2.bin' with '%s'\n", ++ override_board2); ++ ++ return override_board2; ++ } ++ ++ return file; ++} ++ + static const struct firmware *ath10k_fetch_fw_file(struct ath10k *ar, + const char *dir, + const char *file) +@@ -925,6 +970,19 @@ static const struct firmware *ath10k_fetch_fw_file(struct ath10k *ar, + if (dir == NULL) + dir = "."; + ++ /* HACK: Override board.bin and board-2.bin files if specified. ++ * ++ * Some Surface devices perform better with a different board ++ * configuration. To this end, one would need to replace the board.bin ++ * file with the modified config and remove the board-2.bin file. ++ * Unfortunately, that's not a solution that we can easily package. So ++ * we add module options to perform these overrides here. ++ */ ++ ++ file = ath10k_override_board_fw_file(ar, file); ++ if (!file) ++ return ERR_PTR(-ENOENT); ++ + snprintf(filename, sizeof(filename), "%s/%s", dir, file); + ret = firmware_request_nowarn(&fw, filename, ar->dev); + ath10k_dbg(ar, ATH10K_DBG_BOOT, "boot fw request '%s': %d\n", +-- +2.40.0 + diff --git a/patches/surface/0004-ipts.patch b/patches/surface/0004-ipts.patch new file mode 100644 index 0000000..51f2e43 --- /dev/null +++ b/patches/surface/0004-ipts.patch @@ -0,0 +1,2988 @@ +From 002f1450b4741bd1372e5b8ce3f321c0d8eb6e5d Mon Sep 17 00:00:00 2001 +From: Dorian Stoll +Date: Thu, 30 Jul 2020 13:21:53 +0200 +Subject: [PATCH] misc: mei: Add missing IPTS device IDs + +Patchset: ipts +--- + drivers/misc/mei/hw-me-regs.h | 1 + + drivers/misc/mei/pci-me.c | 1 + + 2 files changed, 2 insertions(+) + +diff --git a/drivers/misc/mei/hw-me-regs.h b/drivers/misc/mei/hw-me-regs.h +index bdc65d50b945f..08723c01d7275 100644 +--- a/drivers/misc/mei/hw-me-regs.h ++++ b/drivers/misc/mei/hw-me-regs.h +@@ -92,6 +92,7 @@ + #define MEI_DEV_ID_CDF 0x18D3 /* Cedar Fork */ + + #define MEI_DEV_ID_ICP_LP 0x34E0 /* Ice Lake Point LP */ ++#define MEI_DEV_ID_ICP_LP_3 0x34E4 /* Ice Lake Point LP 3 (iTouch) */ + #define MEI_DEV_ID_ICP_N 0x38E0 /* Ice Lake Point N */ + + #define MEI_DEV_ID_JSP_N 0x4DE0 /* Jasper Lake Point N */ +diff --git a/drivers/misc/mei/pci-me.c b/drivers/misc/mei/pci-me.c +index 5bf0d50d55a00..c13864512229f 100644 +--- a/drivers/misc/mei/pci-me.c ++++ b/drivers/misc/mei/pci-me.c +@@ -97,6 +97,7 @@ static const struct pci_device_id mei_me_pci_tbl[] = { + {MEI_PCI_DEVICE(MEI_DEV_ID_CMP_H_3, MEI_ME_PCH8_ITOUCH_CFG)}, + + {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_LP, MEI_ME_PCH12_CFG)}, ++ {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_LP_3, MEI_ME_PCH12_CFG)}, + {MEI_PCI_DEVICE(MEI_DEV_ID_ICP_N, MEI_ME_PCH12_CFG)}, + + {MEI_PCI_DEVICE(MEI_DEV_ID_TGP_LP, MEI_ME_PCH15_CFG)}, +-- +2.40.0 + +From ec89960d938c0c34f9506e49d5bd7e6aa97646b3 Mon Sep 17 00:00:00 2001 +From: Liban Hannan +Date: Tue, 12 Apr 2022 23:31:12 +0100 +Subject: [PATCH] iommu: ipts: use IOMMU passthrough mode for IPTS + +Adds a quirk so that IOMMU uses passthrough mode for the IPTS device. +Otherwise, when IOMMU is enabled, IPTS produces DMAR errors like: + +DMAR: [DMA Read NO_PASID] Request device [00:16.4] fault addr +0x104ea3000 [fault reason 0x06] PTE Read access is not set + +This is very similar to the bug described at: +https://bugs.launchpad.net/bugs/1958004 + +Fixed with the following patch which this patch basically copies: +https://launchpadlibrarian.net/586396847/43255ca.diff +Patchset: ipts +--- + drivers/iommu/intel/iommu.c | 24 ++++++++++++++++++++++++ + 1 file changed, 24 insertions(+) + +diff --git a/drivers/iommu/intel/iommu.c b/drivers/iommu/intel/iommu.c +index 52afcdaf7c7f1..08e35f9e67a62 100644 +--- a/drivers/iommu/intel/iommu.c ++++ b/drivers/iommu/intel/iommu.c +@@ -37,6 +37,8 @@ + #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY) + #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB) + #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA) ++#define IS_IPTS(pdev) ((pdev)->vendor == PCI_VENDOR_ID_INTEL && \ ++ ((pdev)->device == 0x9d3e)) + #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e) + + #define IOAPIC_RANGE_START (0xfee00000) +@@ -287,12 +289,14 @@ int intel_iommu_enabled = 0; + EXPORT_SYMBOL_GPL(intel_iommu_enabled); + + static int dmar_map_gfx = 1; ++static int dmar_map_ipts = 1; + static int intel_iommu_superpage = 1; + static int iommu_identity_mapping; + static int iommu_skip_te_disable; + + #define IDENTMAP_GFX 2 + #define IDENTMAP_AZALIA 4 ++#define IDENTMAP_IPTS 16 + + const struct iommu_ops intel_iommu_ops; + +@@ -2584,6 +2588,9 @@ static int device_def_domain_type(struct device *dev) + + if ((iommu_identity_mapping & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev)) + return IOMMU_DOMAIN_IDENTITY; ++ ++ if ((iommu_identity_mapping & IDENTMAP_IPTS) && IS_IPTS(pdev)) ++ return IOMMU_DOMAIN_IDENTITY; + } + + return 0; +@@ -2973,6 +2980,9 @@ static int __init init_dmars(void) + if (!dmar_map_gfx) + iommu_identity_mapping |= IDENTMAP_GFX; + ++ if (!dmar_map_ipts) ++ iommu_identity_mapping |= IDENTMAP_IPTS; ++ + check_tylersburg_isoch(); + + ret = si_domain_init(hw_pass_through); +@@ -4813,6 +4823,17 @@ static void quirk_iommu_igfx(struct pci_dev *dev) + dmar_map_gfx = 0; + } + ++static void quirk_iommu_ipts(struct pci_dev *dev) ++{ ++ if (!IS_IPTS(dev)) ++ return; ++ ++ if (risky_device(dev)) ++ return; ++ ++ pci_info(dev, "Passthrough IOMMU for IPTS\n"); ++ dmar_map_ipts = 0; ++} + /* G4x/GM45 integrated gfx dmar support is totally busted. */ + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_igfx); +@@ -4848,6 +4869,9 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1632, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163A, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163D, quirk_iommu_igfx); + ++/* disable IPTS dmar support */ ++DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9D3E, quirk_iommu_ipts); ++ + static void quirk_iommu_rwbf(struct pci_dev *dev) + { + if (risky_device(dev)) +-- +2.40.0 + +From 508335220b01070721aac345e3ba9547a2a00548 Mon Sep 17 00:00:00 2001 +From: Dorian Stoll +Date: Sun, 11 Dec 2022 12:00:59 +0100 +Subject: [PATCH] hid: Add support for Intel Precise Touch and Stylus + +Based on linux-surface/intel-precise-touch@8abe268 + +Signed-off-by: Dorian Stoll +Patchset: ipts +--- + drivers/hid/Kconfig | 2 + + drivers/hid/Makefile | 2 + + drivers/hid/ipts/Kconfig | 14 + + drivers/hid/ipts/Makefile | 14 + + drivers/hid/ipts/cmd.c | 62 +++++ + drivers/hid/ipts/cmd.h | 61 ++++ + drivers/hid/ipts/context.h | 51 ++++ + drivers/hid/ipts/control.c | 495 +++++++++++++++++++++++++++++++++ + drivers/hid/ipts/control.h | 127 +++++++++ + drivers/hid/ipts/desc.h | 81 ++++++ + drivers/hid/ipts/hid.c | 348 +++++++++++++++++++++++ + drivers/hid/ipts/hid.h | 22 ++ + drivers/hid/ipts/main.c | 127 +++++++++ + drivers/hid/ipts/mei.c | 189 +++++++++++++ + drivers/hid/ipts/mei.h | 67 +++++ + drivers/hid/ipts/receiver.c | 249 +++++++++++++++++ + drivers/hid/ipts/receiver.h | 17 ++ + drivers/hid/ipts/resources.c | 108 +++++++ + drivers/hid/ipts/resources.h | 39 +++ + drivers/hid/ipts/spec-data.h | 100 +++++++ + drivers/hid/ipts/spec-device.h | 285 +++++++++++++++++++ + drivers/hid/ipts/spec-hid.h | 35 +++ + drivers/hid/ipts/thread.c | 85 ++++++ + drivers/hid/ipts/thread.h | 60 ++++ + 24 files changed, 2640 insertions(+) + create mode 100644 drivers/hid/ipts/Kconfig + create mode 100644 drivers/hid/ipts/Makefile + create mode 100644 drivers/hid/ipts/cmd.c + create mode 100644 drivers/hid/ipts/cmd.h + create mode 100644 drivers/hid/ipts/context.h + create mode 100644 drivers/hid/ipts/control.c + create mode 100644 drivers/hid/ipts/control.h + create mode 100644 drivers/hid/ipts/desc.h + create mode 100644 drivers/hid/ipts/hid.c + create mode 100644 drivers/hid/ipts/hid.h + create mode 100644 drivers/hid/ipts/main.c + create mode 100644 drivers/hid/ipts/mei.c + create mode 100644 drivers/hid/ipts/mei.h + create mode 100644 drivers/hid/ipts/receiver.c + create mode 100644 drivers/hid/ipts/receiver.h + create mode 100644 drivers/hid/ipts/resources.c + create mode 100644 drivers/hid/ipts/resources.h + create mode 100644 drivers/hid/ipts/spec-data.h + create mode 100644 drivers/hid/ipts/spec-device.h + create mode 100644 drivers/hid/ipts/spec-hid.h + create mode 100644 drivers/hid/ipts/thread.c + create mode 100644 drivers/hid/ipts/thread.h + +diff --git a/drivers/hid/Kconfig b/drivers/hid/Kconfig +index e2a5d30c88956..a4af77fcca209 100644 +--- a/drivers/hid/Kconfig ++++ b/drivers/hid/Kconfig +@@ -1291,4 +1291,6 @@ source "drivers/hid/amd-sfh-hid/Kconfig" + + source "drivers/hid/surface-hid/Kconfig" + ++source "drivers/hid/ipts/Kconfig" ++ + endmenu +diff --git a/drivers/hid/Makefile b/drivers/hid/Makefile +index e8014c1a2f8b6..e48300bcea9be 100644 +--- a/drivers/hid/Makefile ++++ b/drivers/hid/Makefile +@@ -164,3 +164,5 @@ obj-$(INTEL_ISH_FIRMWARE_DOWNLOADER) += intel-ish-hid/ + obj-$(CONFIG_AMD_SFH_HID) += amd-sfh-hid/ + + obj-$(CONFIG_SURFACE_HID_CORE) += surface-hid/ ++ ++obj-$(CONFIG_HID_IPTS) += ipts/ +diff --git a/drivers/hid/ipts/Kconfig b/drivers/hid/ipts/Kconfig +new file mode 100644 +index 0000000000000..297401bd388dd +--- /dev/null ++++ b/drivers/hid/ipts/Kconfig +@@ -0,0 +1,14 @@ ++# SPDX-License-Identifier: GPL-2.0-or-later ++ ++config HID_IPTS ++ tristate "Intel Precise Touch & Stylus" ++ depends on INTEL_MEI ++ depends on HID ++ help ++ Say Y here if your system has a touchscreen using Intels ++ Precise Touch & Stylus (IPTS) technology. ++ ++ If unsure say N. ++ ++ To compile this driver as a module, choose M here: the ++ module will be called ipts. +diff --git a/drivers/hid/ipts/Makefile b/drivers/hid/ipts/Makefile +new file mode 100644 +index 0000000000000..0fe655bccdc0f +--- /dev/null ++++ b/drivers/hid/ipts/Makefile +@@ -0,0 +1,14 @@ ++# SPDX-License-Identifier: GPL-2.0-or-later ++# ++# Makefile for the IPTS touchscreen driver ++# ++ ++obj-$(CONFIG_HID_IPTS) += ipts.o ++ipts-objs := cmd.o ++ipts-objs += control.o ++ipts-objs += hid.o ++ipts-objs += main.o ++ipts-objs += mei.o ++ipts-objs += receiver.o ++ipts-objs += resources.o ++ipts-objs += thread.o +diff --git a/drivers/hid/ipts/cmd.c b/drivers/hid/ipts/cmd.c +new file mode 100644 +index 0000000000000..7fd69271ccd52 +--- /dev/null ++++ b/drivers/hid/ipts/cmd.c +@@ -0,0 +1,62 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "mei.h" ++#include "spec-device.h" ++ ++int ipts_cmd_recv_timeout(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp, u64 timeout) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!rsp) ++ return -EFAULT; ++ ++ /* ++ * In a response, the command code will have the most significant bit flipped to 1. ++ * If code is passed to ipts_mei_recv as is, no messages will be received. ++ */ ++ ret = ipts_mei_recv(&ipts->mei, code | IPTS_RSP_BIT, rsp, timeout); ++ if (ret < 0) ++ return ret; ++ ++ dev_dbg(ipts->dev, "Received 0x%02X with status 0x%02X\n", code, rsp->status); ++ ++ /* ++ * Some devices will always return this error. ++ * It is allowed to ignore it and to try continuing. ++ */ ++ if (rsp->status == IPTS_STATUS_COMPAT_CHECK_FAIL) ++ rsp->status = IPTS_STATUS_SUCCESS; ++ ++ return 0; ++} ++ ++int ipts_cmd_send(struct ipts_context *ipts, enum ipts_command_code code, void *data, size_t size) ++{ ++ struct ipts_command cmd = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.cmd = code; ++ ++ if (data && size > 0) ++ memcpy(cmd.payload, data, size); ++ ++ dev_dbg(ipts->dev, "Sending 0x%02X with %ld bytes payload\n", code, size); ++ return ipts_mei_send(&ipts->mei, &cmd, sizeof(cmd.cmd) + size); ++} +diff --git a/drivers/hid/ipts/cmd.h b/drivers/hid/ipts/cmd.h +new file mode 100644 +index 0000000000000..924758ffee671 +--- /dev/null ++++ b/drivers/hid/ipts/cmd.h +@@ -0,0 +1,61 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CMD_H ++#define IPTS_CMD_H ++ ++#include ++ ++#include "context.h" ++#include "spec-device.h" ++ ++/* ++ * The default timeout for receiving responses ++ */ ++#define IPTS_CMD_DEFAULT_TIMEOUT 1000 ++ ++/* ++ * ipts_cmd_recv_timeout() - Receives a response to a command. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command / response. ++ * @rsp: The address that the received response will be copied to. ++ * @timeout: How many milliseconds the function will wait at most. ++ * ++ * A negative timeout means to wait forever. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++int ipts_cmd_recv_timeout(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp, u64 timeout); ++ ++/* ++ * ipts_cmd_recv() - Receives a response to a command. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command / response. ++ * @rsp: The address that the received response will be copied to. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++static inline int ipts_cmd_recv(struct ipts_context *ipts, enum ipts_command_code code, ++ struct ipts_response *rsp) ++{ ++ return ipts_cmd_recv_timeout(ipts, code, rsp, IPTS_CMD_DEFAULT_TIMEOUT); ++} ++ ++/* ++ * ipts_cmd_send() - Executes a command on the device. ++ * @ipts: The IPTS driver context. ++ * @code: The type of the command to execute. ++ * @data: The payload containing parameters for the command. ++ * @size: The size of the payload. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_cmd_send(struct ipts_context *ipts, enum ipts_command_code code, void *data, size_t size); ++ ++#endif /* IPTS_CMD_H */ +diff --git a/drivers/hid/ipts/context.h b/drivers/hid/ipts/context.h +new file mode 100644 +index 0000000000000..3450a95e66ee8 +--- /dev/null ++++ b/drivers/hid/ipts/context.h +@@ -0,0 +1,51 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CONTEXT_H ++#define IPTS_CONTEXT_H ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "mei.h" ++#include "resources.h" ++#include "spec-device.h" ++#include "thread.h" ++ ++struct ipts_context { ++ struct device *dev; ++ struct ipts_mei mei; ++ ++ enum ipts_mode mode; ++ ++ /* ++ * Prevents concurrent GET_FEATURE reports. ++ */ ++ struct mutex feature_lock; ++ struct completion feature_event; ++ ++ /* ++ * These are not inside of struct ipts_resources ++ * because they don't own the memory they point to. ++ */ ++ struct ipts_buffer feature_report; ++ struct ipts_buffer descriptor; ++ ++ struct hid_device *hid; ++ struct ipts_device_info info; ++ struct ipts_resources resources; ++ ++ struct ipts_thread receiver_loop; ++}; ++ ++#endif /* IPTS_CONTEXT_H */ +diff --git a/drivers/hid/ipts/control.c b/drivers/hid/ipts/control.c +new file mode 100644 +index 0000000000000..2f61500b5119c +--- /dev/null ++++ b/drivers/hid/ipts/control.c +@@ -0,0 +1,495 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "control.h" ++#include "desc.h" ++#include "hid.h" ++#include "receiver.h" ++#include "resources.h" ++#include "spec-data.h" ++#include "spec-device.h" ++ ++static int ipts_control_get_device_info(struct ipts_context *ipts, struct ipts_device_info *info) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!info) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_GET_DEVICE_INFO, NULL, 0); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_GET_DEVICE_INFO, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "GET_DEVICE_INFO: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ memcpy(info, rsp.payload, sizeof(*info)); ++ return 0; ++} ++ ++static int ipts_control_set_mode(struct ipts_context *ipts, enum ipts_mode mode) ++{ ++ int ret = 0; ++ struct ipts_set_mode cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.mode = mode; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_SET_MODE, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MODE: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_SET_MODE, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MODE: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "SET_MODE: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++static int ipts_control_set_mem_window(struct ipts_context *ipts, struct ipts_resources *res) ++{ ++ int ret = 0; ++ struct ipts_mem_window cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ cmd.data_addr_lower[i] = lower_32_bits(res->data[i].dma_address); ++ cmd.data_addr_upper[i] = upper_32_bits(res->data[i].dma_address); ++ cmd.feedback_addr_lower[i] = lower_32_bits(res->feedback[i].dma_address); ++ cmd.feedback_addr_upper[i] = upper_32_bits(res->feedback[i].dma_address); ++ } ++ ++ cmd.workqueue_addr_lower = lower_32_bits(res->workqueue.dma_address); ++ cmd.workqueue_addr_upper = upper_32_bits(res->workqueue.dma_address); ++ ++ cmd.doorbell_addr_lower = lower_32_bits(res->doorbell.dma_address); ++ cmd.doorbell_addr_upper = upper_32_bits(res->doorbell.dma_address); ++ ++ cmd.hid2me_addr_lower = lower_32_bits(res->hid2me.dma_address); ++ cmd.hid2me_addr_upper = upper_32_bits(res->hid2me.dma_address); ++ ++ cmd.workqueue_size = IPTS_WORKQUEUE_SIZE; ++ cmd.workqueue_item_size = IPTS_WORKQUEUE_ITEM_SIZE; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_SET_MEM_WINDOW, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_SET_MEM_WINDOW, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "SET_MEM_WINDOW: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++static int ipts_control_get_descriptor(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_data_header *header = NULL; ++ struct ipts_get_descriptor cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->resources.descriptor.address) ++ return -EFAULT; ++ ++ memset(ipts->resources.descriptor.address, 0, ipts->resources.descriptor.size); ++ ++ cmd.addr_lower = lower_32_bits(ipts->resources.descriptor.dma_address); ++ cmd.addr_upper = upper_32_bits(ipts->resources.descriptor.dma_address); ++ cmd.magic = 8; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_GET_DESCRIPTOR, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_GET_DESCRIPTOR, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "GET_DESCRIPTOR: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ header = (struct ipts_data_header *)ipts->resources.descriptor.address; ++ ++ if (header->type == IPTS_DATA_TYPE_DESCRIPTOR) { ++ ipts->descriptor.address = &header->data[8]; ++ ipts->descriptor.size = header->size - 8; ++ ++ return 0; ++ } ++ ++ return -ENODATA; ++} ++ ++int ipts_control_request_flush(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_quiesce_io cmd = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_QUIESCE_IO, &cmd, sizeof(cmd)); ++ if (ret) ++ dev_err(ipts->dev, "QUIESCE_IO: send failed: %d\n", ret); ++ ++ return ret; ++} ++ ++int ipts_control_wait_flush(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_QUIESCE_IO, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "QUIESCE_IO: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ if (rsp.status == IPTS_STATUS_TIMEOUT) ++ return -EAGAIN; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "QUIESCE_IO: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_request_data(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_READY_FOR_DATA, NULL, 0); ++ if (ret) ++ dev_err(ipts->dev, "READY_FOR_DATA: send failed: %d\n", ret); ++ ++ return ret; ++} ++ ++int ipts_control_wait_data(struct ipts_context *ipts, bool shutdown) ++{ ++ int ret = 0; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!shutdown) ++ ret = ipts_cmd_recv_timeout(ipts, IPTS_CMD_READY_FOR_DATA, &rsp, 0); ++ else ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_READY_FOR_DATA, &rsp); ++ ++ if (ret) { ++ if (ret != -EAGAIN) ++ dev_err(ipts->dev, "READY_FOR_DATA: recv failed: %d\n", ret); ++ ++ return ret; ++ } ++ ++ /* ++ * During shutdown, it is possible that the sensor has already been disabled. ++ */ ++ if (rsp.status == IPTS_STATUS_SENSOR_DISABLED) ++ return 0; ++ ++ if (rsp.status == IPTS_STATUS_TIMEOUT) ++ return -EAGAIN; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "READY_FOR_DATA: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) ++{ ++ int ret = 0; ++ struct ipts_feedback cmd = { 0 }; ++ struct ipts_response rsp = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ cmd.buffer = buffer; ++ ++ ret = ipts_cmd_send(ipts, IPTS_CMD_FEEDBACK, &cmd, sizeof(cmd)); ++ if (ret) { ++ dev_err(ipts->dev, "FEEDBACK: send failed: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_cmd_recv(ipts, IPTS_CMD_FEEDBACK, &rsp); ++ if (ret) { ++ dev_err(ipts->dev, "FEEDBACK: recv failed: %d\n", ret); ++ return ret; ++ } ++ ++ /* ++ * We don't know what feedback data looks like so we are sending zeros. ++ * See also ipts_control_refill_buffer. ++ */ ++ if (rsp.status == IPTS_STATUS_INVALID_PARAMS) ++ return 0; ++ ++ if (rsp.status != IPTS_STATUS_SUCCESS) { ++ dev_err(ipts->dev, "FEEDBACK: cmd failed: %d\n", rsp.status); ++ return -EBADR; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_cmd_type cmd, ++ enum ipts_feedback_data_type type, void *data, size_t size) ++{ ++ struct ipts_feedback_header *header = NULL; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->resources.hid2me.address) ++ return -EFAULT; ++ ++ memset(ipts->resources.hid2me.address, 0, ipts->resources.hid2me.size); ++ header = (struct ipts_feedback_header *)ipts->resources.hid2me.address; ++ ++ header->cmd_type = cmd; ++ header->data_type = type; ++ header->size = size; ++ header->buffer = IPTS_HID2ME_BUFFER; ++ ++ if (size + sizeof(*header) > ipts->resources.hid2me.size) ++ return -EINVAL; ++ ++ if (data && size > 0) ++ memcpy(header->payload, data, size); ++ ++ return ipts_control_send_feedback(ipts, IPTS_HID2ME_BUFFER); ++} ++ ++static inline int ipts_control_reset_sensor(struct ipts_context *ipts) ++{ ++ return ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_SOFT_RESET, ++ IPTS_FEEDBACK_DATA_TYPE_VENDOR, NULL, 0); ++} ++ ++int ipts_control_start(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ struct ipts_device_info info = { 0 }; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "Starting IPTS\n"); ++ ++ ret = ipts_control_get_device_info(ipts, &info); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to get device info: %d\n", ret); ++ return ret; ++ } ++ ++ ipts->info = info; ++ ++ ret = ipts_resources_init(&ipts->resources, ipts->dev, info.data_size, info.feedback_size); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to allocate buffers: %d", ret); ++ return ret; ++ } ++ ++ dev_info(ipts->dev, "IPTS EDS Version: %d\n", info.intf_eds); ++ ++ /* ++ * Handle newer devices ++ */ ++ if (info.intf_eds > 1) { ++ /* ++ * Fetching the descriptor will only work on newer devices. ++ * For older devices, a fallback descriptor will be used. ++ */ ++ ret = ipts_control_get_descriptor(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to fetch HID descriptor: %d\n", ret); ++ return ret; ++ } ++ ++ /* ++ * Newer devices can be directly initialized in doorbell mode. ++ */ ++ ipts->mode = IPTS_MODE_DOORBELL; ++ } ++ ++ ret = ipts_control_set_mode(ipts, ipts->mode); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to set mode: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_set_mem_window(ipts, &ipts->resources); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to set memory window: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_receiver_start(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to start receiver: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_request_data(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request data: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_hid_init(ipts, info); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to initialize HID device: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static int _ipts_control_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "Stopping IPTS\n"); ++ ++ ret = ipts_receiver_stop(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to stop receiver: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_reset_sensor(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to reset sensor: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_resources_free(&ipts->resources); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to free resources: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ ret = _ipts_control_stop(ipts); ++ if (ret) ++ return ret; ++ ++ ret = ipts_hid_free(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to free HID device: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_control_restart(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ ret = _ipts_control_stop(ipts); ++ if (ret) ++ return ret; ++ ++ /* ++ * Give the sensor some time to come back from resetting ++ */ ++ msleep(1000); ++ ++ ret = ipts_control_start(ipts); ++ if (ret) ++ return ret; ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/control.h b/drivers/hid/ipts/control.h +new file mode 100644 +index 0000000000000..744bb92d682a0 +--- /dev/null ++++ b/drivers/hid/ipts/control.h +@@ -0,0 +1,127 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_CONTROL_H ++#define IPTS_CONTROL_H ++ ++#include ++ ++#include "context.h" ++#include "spec-data.h" ++#include "spec-device.h" ++ ++/* ++ * ipts_control_request_flush() - Stop the data flow. ++ * @ipts: The IPTS driver context. ++ * ++ * Runs the command to stop the data flow on the device. ++ * All outstanding data needs to be acknowledged using feedback before the command will return. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_request_flush(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_flush() - Wait until data flow has been stopped. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_wait_flush(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_flush() - Notify the device that the driver can receive new data. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_request_data(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_wait_data() - Wait until new data is available. ++ * @ipts: The IPTS driver context. ++ * @block: Whether to block execution until data is available. ++ * ++ * In doorbell mode, this function will never return while the data flow is active. Instead, ++ * the doorbell will be incremented when new data is available. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no data is available. ++ */ ++int ipts_control_wait_data(struct ipts_context *ipts, bool block); ++ ++/* ++ * ipts_control_send_feedback() - Submits a feedback buffer to the device. ++ * @ipts: The IPTS driver context. ++ * @buffer: The ID of the buffer containing feedback data. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer); ++ ++/* ++ * ipts_control_hid2me_feedback() - Sends HID2ME feedback, a special type of feedback. ++ * @ipts: The IPTS driver context. ++ * @cmd: The command that will be run on the device. ++ * @type: The type of the payload that is sent to the device. ++ * @data: The payload of the feedback command. ++ * @size: The size of the payload. ++ * ++ * HID2ME feedback is a special type of feedback, because it allows interfacing with ++ * the HID API of the device at any moment, without requiring a buffer that has to ++ * be acknowledged. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_cmd_type cmd, ++ enum ipts_feedback_data_type type, void *data, size_t size); ++ ++/* ++ * ipts_control_refill_buffer() - Acknowledges that data in a buffer has been processed. ++ * @ipts: The IPTS driver context. ++ * @buffer: The buffer that has been processed and can be refilled. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++static inline int ipts_control_refill_buffer(struct ipts_context *ipts, u32 buffer) ++{ ++ /* ++ * IPTS expects structured data in the feedback buffer matching the buffer that will be ++ * refilled. We don't know what that data looks like, so we just keep the buffer empty. ++ * This results in an INVALID_PARAMS error, but the buffer gets refilled without an issue. ++ * Sending a minimal structure with the buffer ID fixes the error, but breaks refilling ++ * the buffers on some devices. ++ */ ++ ++ return ipts_control_send_feedback(ipts, buffer); ++} ++ ++/* ++ * ipts_control_start() - Initialized the device and starts the data flow. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_start(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_stop() - Stops the data flow and resets the device. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_stop(struct ipts_context *ipts); ++ ++/* ++ * ipts_control_restart() - Stops the device and starts it again. ++ * @ipts: The IPTS driver context. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_control_restart(struct ipts_context *ipts); ++ ++#endif /* IPTS_CONTROL_H */ +diff --git a/drivers/hid/ipts/desc.h b/drivers/hid/ipts/desc.h +new file mode 100644 +index 0000000000000..c058974a03a1e +--- /dev/null ++++ b/drivers/hid/ipts/desc.h +@@ -0,0 +1,81 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_DESC_H ++#define IPTS_DESC_H ++ ++#include ++ ++#define IPTS_HID_REPORT_SINGLETOUCH 64 ++#define IPTS_HID_REPORT_DATA 65 ++#define IPTS_HID_REPORT_SET_MODE 66 ++ ++#define IPTS_HID_REPORT_DATA_SIZE 7485 ++ ++/* ++ * HID descriptor for singletouch data. ++ * This descriptor should be present on all IPTS devices. ++ */ ++static const u8 ipts_singletouch_descriptor[] = { ++ 0x05, 0x0D, /* Usage Page (Digitizer), */ ++ 0x09, 0x04, /* Usage (Touchscreen), */ ++ 0xA1, 0x01, /* Collection (Application), */ ++ 0x85, 0x40, /* Report ID (64), */ ++ 0x09, 0x42, /* Usage (Tip Switch), */ ++ 0x15, 0x00, /* Logical Minimum (0), */ ++ 0x25, 0x01, /* Logical Maximum (1), */ ++ 0x75, 0x01, /* Report Size (1), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x95, 0x07, /* Report Count (7), */ ++ 0x81, 0x03, /* Input (Constant, Variable), */ ++ 0x05, 0x01, /* Usage Page (Desktop), */ ++ 0x09, 0x30, /* Usage (X), */ ++ 0x75, 0x10, /* Report Size (16), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0xA4, /* Push, */ ++ 0x55, 0x0E, /* Unit Exponent (14), */ ++ 0x65, 0x11, /* Unit (Centimeter), */ ++ 0x46, 0x76, 0x0B, /* Physical Maximum (2934), */ ++ 0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x09, 0x31, /* Usage (Y), */ ++ 0x46, 0x74, 0x06, /* Physical Maximum (1652), */ ++ 0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0xB4, /* Pop, */ ++ 0xC0, /* End Collection */ ++}; ++ ++/* ++ * Fallback HID descriptor for older devices that do not have ++ * the ability to query their HID descriptor. ++ */ ++static const u8 ipts_fallback_descriptor[] = { ++ 0x05, 0x0D, /* Usage Page (Digitizer), */ ++ 0x09, 0x0F, /* Usage (Capacitive Hm Digitizer), */ ++ 0xA1, 0x01, /* Collection (Application), */ ++ 0x85, 0x41, /* Report ID (65), */ ++ 0x09, 0x56, /* Usage (Scan Time), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0x75, 0x10, /* Report Size (16), */ ++ 0x81, 0x02, /* Input (Variable), */ ++ 0x09, 0x61, /* Usage (Gesture Char Quality), */ ++ 0x75, 0x08, /* Report Size (8), */ ++ 0x96, 0x3D, 0x1D, /* Report Count (7485), */ ++ 0x81, 0x03, /* Input (Constant, Variable), */ ++ 0x85, 0x42, /* Report ID (66), */ ++ 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ ++ 0x09, 0xC8, /* Usage (C8h), */ ++ 0x75, 0x08, /* Report Size (8), */ ++ 0x95, 0x01, /* Report Count (1), */ ++ 0xB1, 0x02, /* Feature (Variable), */ ++ 0xC0, /* End Collection, */ ++}; ++ ++#endif /* IPTS_DESC_H */ +diff --git a/drivers/hid/ipts/hid.c b/drivers/hid/ipts/hid.c +new file mode 100644 +index 0000000000000..6782394e8dde3 +--- /dev/null ++++ b/drivers/hid/ipts/hid.c +@@ -0,0 +1,348 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "control.h" ++#include "desc.h" ++#include "hid.h" ++#include "spec-data.h" ++#include "spec-device.h" ++#include "spec-hid.h" ++ ++static int ipts_hid_start(struct hid_device *hid) ++{ ++ return 0; ++} ++ ++static void ipts_hid_stop(struct hid_device *hid) ++{ ++} ++ ++static int ipts_hid_switch_mode(struct ipts_context *ipts, enum ipts_mode mode) ++{ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->mode == mode) ++ return 0; ++ ++ /* ++ * This is only allowed on older devices. ++ */ ++ if (ipts->info.intf_eds > 1) ++ return 0; ++ ++ ipts->mode = mode; ++ return ipts_control_restart(ipts); ++} ++ ++static int ipts_hid_parse(struct hid_device *hid) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ bool has_native_descriptor = false; ++ ++ u8 *buffer = NULL; ++ size_t size = 0; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ size = sizeof(ipts_singletouch_descriptor); ++ has_native_descriptor = ipts->descriptor.address && ipts->descriptor.size > 0; ++ ++ if (has_native_descriptor) ++ size += ipts->descriptor.size; ++ else ++ size += sizeof(ipts_fallback_descriptor); ++ ++ buffer = kzalloc(size, GFP_KERNEL); ++ if (!buffer) ++ return -ENOMEM; ++ ++ memcpy(buffer, ipts_singletouch_descriptor, sizeof(ipts_singletouch_descriptor)); ++ ++ if (has_native_descriptor) { ++ memcpy(&buffer[sizeof(ipts_singletouch_descriptor)], ipts->descriptor.address, ++ ipts->descriptor.size); ++ } else { ++ memcpy(&buffer[sizeof(ipts_singletouch_descriptor)], ipts_fallback_descriptor, ++ sizeof(ipts_fallback_descriptor)); ++ } ++ ++ ret = hid_parse_report(hid, buffer, size); ++ kfree(buffer); ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to parse HID descriptor: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static int ipts_hid_get_feature(struct ipts_context *ipts, unsigned char reportnum, __u8 *buf, ++ size_t size, enum ipts_feedback_data_type type) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ mutex_lock(&ipts->feature_lock); ++ ++ memset(buf, 0, size); ++ buf[0] = reportnum; ++ ++ memset(&ipts->feature_report, 0, sizeof(ipts->feature_report)); ++ reinit_completion(&ipts->feature_event); ++ ++ ret = ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, type, buf, size); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to send hid2me feedback: %d\n", ret); ++ goto out; ++ } ++ ++ ret = wait_for_completion_timeout(&ipts->feature_event, msecs_to_jiffies(5000)); ++ if (ret == 0) { ++ dev_warn(ipts->dev, "GET_FEATURES timed out!\n"); ++ ret = -EIO; ++ goto out; ++ } ++ ++ if (!ipts->feature_report.address) { ++ ret = -EFAULT; ++ goto out; ++ } ++ ++ if (ipts->feature_report.size > size) { ++ ret = -ETOOSMALL; ++ goto out; ++ } ++ ++ ret = ipts->feature_report.size; ++ memcpy(buf, ipts->feature_report.address, ipts->feature_report.size); ++ ++out: ++ mutex_unlock(&ipts->feature_lock); ++ return ret; ++} ++ ++static int ipts_hid_set_feature(struct ipts_context *ipts, unsigned char reportnum, __u8 *buf, ++ size_t size, enum ipts_feedback_data_type type) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ buf[0] = reportnum; ++ ++ ret = ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, type, buf, size); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send hid2me feedback: %d\n", ret); ++ ++ return ret; ++} ++ ++static int ipts_hid_raw_request(struct hid_device *hid, unsigned char reportnum, __u8 *buf, ++ size_t size, unsigned char rtype, int reqtype) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ enum ipts_feedback_data_type type = IPTS_FEEDBACK_DATA_TYPE_VENDOR; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!buf) ++ return -EFAULT; ++ ++ if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT) ++ type = IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES; ++ else ++ return -EIO; ++ ++ // Implemente mode switching report for older devices without native HID support ++ if (type == IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES && reportnum == IPTS_HID_REPORT_SET_MODE) { ++ ret = ipts_hid_switch_mode(ipts, buf[1]); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to switch modes: %d\n", ret); ++ return ret; ++ } ++ } ++ ++ if (reqtype == HID_REQ_GET_REPORT) ++ return ipts_hid_get_feature(ipts, reportnum, buf, size, type); ++ else ++ return ipts_hid_set_feature(ipts, reportnum, buf, size, type); ++} ++ ++static int ipts_hid_output_report(struct hid_device *hid, __u8 *data, size_t size) ++{ ++ struct ipts_context *ipts = NULL; ++ ++ if (!hid) ++ return -ENODEV; ++ ++ ipts = hid->driver_data; ++ ++ return ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, ++ IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT, data, size); ++} ++ ++static struct hid_ll_driver ipts_hid_driver = { ++ .start = ipts_hid_start, ++ .stop = ipts_hid_stop, ++ .open = ipts_hid_start, ++ .close = ipts_hid_stop, ++ .parse = ipts_hid_parse, ++ .raw_request = ipts_hid_raw_request, ++ .output_report = ipts_hid_output_report, ++}; ++ ++int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) ++{ ++ int ret = 0; ++ u8 *temp = NULL; ++ struct ipts_hid_header *frame = NULL; ++ struct ipts_data_header *header = NULL; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->hid) ++ return -ENODEV; ++ ++ header = (struct ipts_data_header *)ipts->resources.data[buffer].address; ++ ++ if (!header) ++ return -EFAULT; ++ ++ if (header->size == 0) ++ return 0; ++ ++ if (header->type == IPTS_DATA_TYPE_HID) ++ return hid_input_report(ipts->hid, HID_INPUT_REPORT, header->data, header->size, 1); ++ ++ if (header->type == IPTS_DATA_TYPE_GET_FEATURES) { ++ ipts->feature_report.address = header->data; ++ ipts->feature_report.size = header->size; ++ ++ complete_all(&ipts->feature_event); ++ return 0; ++ } ++ ++ if (header->type != IPTS_DATA_TYPE_FRAME) ++ return 0; ++ ++ if (header->size + 3 + sizeof(struct ipts_hid_header) > IPTS_HID_REPORT_DATA_SIZE) ++ return -ERANGE; ++ ++ temp = kzalloc(IPTS_HID_REPORT_DATA_SIZE, GFP_KERNEL); ++ if (!temp) ++ return -ENOMEM; ++ ++ /* ++ * Synthesize a HID report matching the devices that natively send HID reports ++ */ ++ temp[0] = IPTS_HID_REPORT_DATA; ++ ++ frame = (struct ipts_hid_header *)&temp[3]; ++ frame->type = IPTS_HID_FRAME_TYPE_RAW; ++ frame->size = header->size + sizeof(*frame); ++ ++ memcpy(frame->data, header->data, header->size); ++ ++ ret = hid_input_report(ipts->hid, HID_INPUT_REPORT, temp, IPTS_HID_REPORT_DATA_SIZE, 1); ++ kfree(temp); ++ ++ return ret; ++} ++ ++int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->hid) ++ return 0; ++ ++ ipts->hid = hid_allocate_device(); ++ if (IS_ERR(ipts->hid)) { ++ int err = PTR_ERR(ipts->hid); ++ ++ dev_err(ipts->dev, "Failed to allocate HID device: %d\n", err); ++ return err; ++ } ++ ++ ipts->hid->driver_data = ipts; ++ ipts->hid->dev.parent = ipts->dev; ++ ipts->hid->ll_driver = &ipts_hid_driver; ++ ++ ipts->hid->vendor = info.vendor; ++ ipts->hid->product = info.product; ++ ipts->hid->group = HID_GROUP_MULTITOUCH; ++ ++ snprintf(ipts->hid->name, sizeof(ipts->hid->name), "IPTS %04X:%04X", info.vendor, ++ info.product); ++ ++ ret = hid_add_device(ipts->hid); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to add HID device: %d\n", ret); ++ ipts_hid_free(ipts); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_hid_free(struct ipts_context *ipts) ++{ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (!ipts->hid) ++ return 0; ++ ++ hid_destroy_device(ipts->hid); ++ ipts->hid = NULL; ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/hid.h b/drivers/hid/ipts/hid.h +new file mode 100644 +index 0000000000000..62bf3cd486081 +--- /dev/null ++++ b/drivers/hid/ipts/hid.h +@@ -0,0 +1,22 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2022-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_HID_H ++#define IPTS_HID_H ++ ++#include ++ ++#include "context.h" ++#include "spec-device.h" ++ ++int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer); ++ ++int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info); ++int ipts_hid_free(struct ipts_context *ipts); ++ ++#endif /* IPTS_HID_H */ +diff --git a/drivers/hid/ipts/main.c b/drivers/hid/ipts/main.c +new file mode 100644 +index 0000000000000..0f20c6c08c38c +--- /dev/null ++++ b/drivers/hid/ipts/main.c +@@ -0,0 +1,127 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "control.h" ++#include "mei.h" ++#include "receiver.h" ++#include "spec-device.h" ++ ++/* ++ * The MEI client ID for IPTS functionality. ++ */ ++#define IPTS_ID UUID_LE(0x3e8d0870, 0x271a, 0x4208, 0x8e, 0xb5, 0x9a, 0xcb, 0x94, 0x02, 0xae, 0x04) ++ ++static int ipts_set_dma_mask(struct mei_cl_device *cldev) ++{ ++ if (!cldev) ++ return -EFAULT; ++ ++ if (!dma_coerce_mask_and_coherent(&cldev->dev, DMA_BIT_MASK(64))) ++ return 0; ++ ++ return dma_coerce_mask_and_coherent(&cldev->dev, DMA_BIT_MASK(32)); ++} ++ ++static int ipts_probe(struct mei_cl_device *cldev, const struct mei_cl_device_id *id) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) ++ return -EFAULT; ++ ++ ret = ipts_set_dma_mask(cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to set DMA mask for IPTS: %d\n", ret); ++ return ret; ++ } ++ ++ ret = mei_cldev_enable(cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to enable MEI device: %d\n", ret); ++ return ret; ++ } ++ ++ ipts = devm_kzalloc(&cldev->dev, sizeof(*ipts), GFP_KERNEL); ++ if (!ipts) { ++ mei_cldev_disable(cldev); ++ return -ENOMEM; ++ } ++ ++ ret = ipts_mei_init(&ipts->mei, cldev); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to init MEI bus logic: %d\n", ret); ++ return ret; ++ } ++ ++ ipts->dev = &cldev->dev; ++ ipts->mode = IPTS_MODE_EVENT; ++ ++ mutex_init(&ipts->feature_lock); ++ init_completion(&ipts->feature_event); ++ ++ mei_cldev_set_drvdata(cldev, ipts); ++ ++ ret = ipts_control_start(ipts); ++ if (ret) { ++ dev_err(&cldev->dev, "Failed to start IPTS: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static void ipts_remove(struct mei_cl_device *cldev) ++{ ++ int ret = 0; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) { ++ pr_err("MEI device is NULL!"); ++ return; ++ } ++ ++ ipts = mei_cldev_get_drvdata(cldev); ++ ++ ret = ipts_control_stop(ipts); ++ if (ret) ++ dev_err(&cldev->dev, "Failed to stop IPTS: %d\n", ret); ++ ++ mei_cldev_disable(cldev); ++} ++ ++static struct mei_cl_device_id ipts_device_id_table[] = { ++ { .uuid = IPTS_ID, .version = MEI_CL_VERSION_ANY }, ++ {}, ++}; ++MODULE_DEVICE_TABLE(mei, ipts_device_id_table); ++ ++static struct mei_cl_driver ipts_driver = { ++ .id_table = ipts_device_id_table, ++ .name = "ipts", ++ .probe = ipts_probe, ++ .remove = ipts_remove, ++}; ++module_mei_cl_driver(ipts_driver); ++ ++MODULE_DESCRIPTION("IPTS touchscreen driver"); ++MODULE_AUTHOR("Dorian Stoll "); ++MODULE_LICENSE("GPL"); +diff --git a/drivers/hid/ipts/mei.c b/drivers/hid/ipts/mei.c +new file mode 100644 +index 0000000000000..26666fd99b0c7 +--- /dev/null ++++ b/drivers/hid/ipts/mei.c +@@ -0,0 +1,189 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "context.h" ++#include "mei.h" ++ ++static void locked_list_add(struct list_head *new, struct list_head *head, ++ struct rw_semaphore *lock) ++{ ++ down_write(lock); ++ list_add(new, head); ++ up_write(lock); ++} ++ ++static void locked_list_del(struct list_head *entry, struct rw_semaphore *lock) ++{ ++ down_write(lock); ++ list_del(entry); ++ up_write(lock); ++} ++ ++static void ipts_mei_incoming(struct mei_cl_device *cldev) ++{ ++ ssize_t ret = 0; ++ struct ipts_mei_message *entry = NULL; ++ struct ipts_context *ipts = NULL; ++ ++ if (!cldev) { ++ pr_err("MEI device is NULL!"); ++ return; ++ } ++ ++ ipts = mei_cldev_get_drvdata(cldev); ++ if (!ipts) { ++ pr_err("IPTS driver context is NULL!"); ++ return; ++ } ++ ++ entry = devm_kzalloc(ipts->dev, sizeof(*entry), GFP_KERNEL); ++ if (!entry) ++ return; ++ ++ INIT_LIST_HEAD(&entry->list); ++ ++ do { ++ ret = mei_cldev_recv(cldev, (u8 *)&entry->rsp, sizeof(entry->rsp)); ++ } while (ret == -EINTR); ++ ++ if (ret < 0) { ++ dev_err(ipts->dev, "Error while reading response: %ld\n", ret); ++ return; ++ } ++ ++ if (ret == 0) { ++ dev_err(ipts->dev, "Received empty response\n"); ++ return; ++ } ++ ++ locked_list_add(&entry->list, &ipts->mei.messages, &ipts->mei.message_lock); ++ wake_up_all(&ipts->mei.message_queue); ++} ++ ++static int ipts_mei_search(struct ipts_mei *mei, enum ipts_command_code code, ++ struct ipts_response *rsp) ++{ ++ struct ipts_mei_message *entry = NULL; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!rsp) ++ return -EFAULT; ++ ++ down_read(&mei->message_lock); ++ ++ /* ++ * Iterate over the list of received messages, and check if there is one ++ * matching the requested command code. ++ */ ++ list_for_each_entry(entry, &mei->messages, list) { ++ if (entry->rsp.cmd == code) ++ break; ++ } ++ ++ up_read(&mei->message_lock); ++ ++ /* ++ * If entry is not the list head, this means that the loop above has been stopped early, ++ * and that we found a matching element. We drop the message from the list and return it. ++ */ ++ if (!list_entry_is_head(entry, &mei->messages, list)) { ++ locked_list_del(&entry->list, &mei->message_lock); ++ ++ *rsp = entry->rsp; ++ devm_kfree(&mei->cldev->dev, entry); ++ ++ return 0; ++ } ++ ++ return -EAGAIN; ++} ++ ++int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts_response *rsp, ++ u64 timeout) ++{ ++ int ret = 0; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ /* ++ * A timeout of 0 means check and return immideately. ++ */ ++ if (timeout == 0) ++ return ipts_mei_search(mei, code, rsp); ++ ++ /* ++ * A timeout of less than 0 means to wait forever. ++ */ ++ if (timeout < 0) { ++ wait_event(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0); ++ return 0; ++ } ++ ++ ret = wait_event_timeout(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0, ++ msecs_to_jiffies(timeout)); ++ ++ if (ret > 0) ++ return 0; ++ ++ return -EAGAIN; ++} ++ ++int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length) ++{ ++ int ret = 0; ++ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!mei->cldev) ++ return -EFAULT; ++ ++ if (!data) ++ return -EFAULT; ++ ++ do { ++ ret = mei_cldev_send(mei->cldev, (u8 *)data, length); ++ } while (ret == -EINTR); ++ ++ if (ret < 0) ++ return ret; ++ ++ return 0; ++} ++ ++int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev) ++{ ++ if (!mei) ++ return -EFAULT; ++ ++ if (!cldev) ++ return -EFAULT; ++ ++ mei->cldev = cldev; ++ ++ INIT_LIST_HEAD(&mei->messages); ++ init_waitqueue_head(&mei->message_queue); ++ init_rwsem(&mei->message_lock); ++ ++ mei_cldev_register_rx_cb(cldev, ipts_mei_incoming); ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/mei.h b/drivers/hid/ipts/mei.h +new file mode 100644 +index 0000000000000..eadacae54c400 +--- /dev/null ++++ b/drivers/hid/ipts/mei.h +@@ -0,0 +1,67 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_MEI_H ++#define IPTS_MEI_H ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include "spec-device.h" ++ ++struct ipts_mei_message { ++ struct list_head list; ++ struct ipts_response rsp; ++}; ++ ++struct ipts_mei { ++ struct mei_cl_device *cldev; ++ ++ struct list_head messages; ++ ++ wait_queue_head_t message_queue; ++ struct rw_semaphore message_lock; ++}; ++ ++/* ++ * ipts_mei_recv() - Receive data from a MEI device. ++ * @mei: The IPTS MEI device context. ++ * @code: The IPTS command code to look for. ++ * @rsp: The address that the received data will be copied to. ++ * @timeout: How many milliseconds the function will wait at most. ++ * ++ * A negative timeout means to wait forever. ++ * ++ * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. ++ */ ++int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts_response *rsp, ++ u64 timeout); ++ ++/* ++ * ipts_mei_send() - Send data to a MEI device. ++ * @ipts: The IPTS MEI device context. ++ * @data: The data to send. ++ * @size: The size of the data. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length); ++ ++/* ++ * ipts_mei_init() - Initialize the MEI device context. ++ * @mei: The MEI device context to initialize. ++ * @cldev: The MEI device the context will be bound to. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev); ++ ++#endif /* IPTS_MEI_H */ +diff --git a/drivers/hid/ipts/receiver.c b/drivers/hid/ipts/receiver.c +new file mode 100644 +index 0000000000000..77234f9e0e178 +--- /dev/null ++++ b/drivers/hid/ipts/receiver.c +@@ -0,0 +1,249 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "cmd.h" ++#include "context.h" ++#include "control.h" ++#include "hid.h" ++#include "resources.h" ++#include "spec-device.h" ++#include "thread.h" ++ ++static void ipts_receiver_next_doorbell(struct ipts_context *ipts) ++{ ++ u32 *doorbell = (u32 *)ipts->resources.doorbell.address; ++ *doorbell = *doorbell + 1; ++} ++ ++static u32 ipts_receiver_current_doorbell(struct ipts_context *ipts) ++{ ++ u32 *doorbell = (u32 *)ipts->resources.doorbell.address; ++ return *doorbell; ++} ++ ++static void ipts_receiver_backoff(time64_t last, u32 n) ++{ ++ /* ++ * If the last change was less than n seconds ago, ++ * sleep for a shorter period so that new data can be ++ * processed quickly. If there was no change for more than ++ * n seconds, sleep longer to avoid wasting CPU cycles. ++ */ ++ if (last + n > ktime_get_seconds()) ++ msleep(20); ++ else ++ msleep(200); ++} ++ ++static int ipts_receiver_event_loop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ u32 buffer = 0; ++ ++ struct ipts_context *ipts = NULL; ++ time64_t last = ktime_get_seconds(); ++ ++ if (!thread) ++ return -EFAULT; ++ ++ ipts = thread->data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "IPTS running in event mode\n"); ++ ++ while (!ipts_thread_should_stop(thread)) { ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_control_wait_data(ipts, false); ++ if (ret == -EAGAIN) ++ break; ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ continue; ++ } ++ ++ buffer = ipts_receiver_current_doorbell(ipts) % IPTS_BUFFERS; ++ ipts_receiver_next_doorbell(ipts); ++ ++ ret = ipts_hid_input_data(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to process buffer: %d\n", ret); ++ ++ ret = ipts_control_refill_buffer(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send feedback: %d\n", ret); ++ ++ ret = ipts_control_request_data(ipts); ++ if (ret) ++ dev_err(ipts->dev, "Failed to request data: %d\n", ret); ++ ++ last = ktime_get_seconds(); ++ } ++ ++ ipts_receiver_backoff(last, 5); ++ } ++ ++ ret = ipts_control_request_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request flush: %d\n", ret); ++ return ret; ++ } ++ ++ ret = ipts_control_wait_data(ipts, true); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ ret = ipts_control_wait_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ return 0; ++} ++ ++static int ipts_receiver_doorbell_loop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ u32 buffer = 0; ++ ++ u32 doorbell = 0; ++ u32 lastdb = 0; ++ ++ struct ipts_context *ipts = NULL; ++ time64_t last = ktime_get_seconds(); ++ ++ if (!thread) ++ return -EFAULT; ++ ++ ipts = thread->data; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ dev_info(ipts->dev, "IPTS running in doorbell mode\n"); ++ ++ while (true) { ++ if (ipts_thread_should_stop(thread)) { ++ ret = ipts_control_request_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to request flush: %d\n", ret); ++ return ret; ++ } ++ } ++ ++ doorbell = ipts_receiver_current_doorbell(ipts); ++ ++ /* ++ * After filling up one of the data buffers, IPTS will increment ++ * the doorbell. The value of the doorbell stands for the *next* ++ * buffer that IPTS is going to fill. ++ */ ++ while (lastdb != doorbell) { ++ buffer = lastdb % IPTS_BUFFERS; ++ ++ ret = ipts_hid_input_data(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to process buffer: %d\n", ret); ++ ++ ret = ipts_control_refill_buffer(ipts, buffer); ++ if (ret) ++ dev_err(ipts->dev, "Failed to send feedback: %d\n", ret); ++ ++ last = ktime_get_seconds(); ++ lastdb++; ++ } ++ ++ if (ipts_thread_should_stop(thread)) ++ break; ++ ++ ipts_receiver_backoff(last, 5); ++ } ++ ++ ret = ipts_control_wait_data(ipts, true); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ ret = ipts_control_wait_flush(ipts); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); ++ ++ if (ret != -EAGAIN) ++ return ret; ++ else ++ return 0; ++ } ++ ++ return 0; ++} ++ ++int ipts_receiver_start(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ if (ipts->mode == IPTS_MODE_EVENT) { ++ ret = ipts_thread_start(&ipts->receiver_loop, ipts_receiver_event_loop, ipts, ++ "ipts_event"); ++ } else if (ipts->mode == IPTS_MODE_DOORBELL) { ++ ret = ipts_thread_start(&ipts->receiver_loop, ipts_receiver_doorbell_loop, ipts, ++ "ipts_doorbell"); ++ } else { ++ ret = -EINVAL; ++ } ++ ++ if (ret) { ++ dev_err(ipts->dev, "Failed to start receiver loop: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++int ipts_receiver_stop(struct ipts_context *ipts) ++{ ++ int ret = 0; ++ ++ if (!ipts) ++ return -EFAULT; ++ ++ ret = ipts_thread_stop(&ipts->receiver_loop); ++ if (ret) { ++ dev_err(ipts->dev, "Failed to stop receiver loop: %d\n", ret); ++ return ret; ++ } ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/receiver.h b/drivers/hid/ipts/receiver.h +new file mode 100644 +index 0000000000000..96070f34fbcaa +--- /dev/null ++++ b/drivers/hid/ipts/receiver.h +@@ -0,0 +1,17 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_RECEIVER_H ++#define IPTS_RECEIVER_H ++ ++#include "context.h" ++ ++int ipts_receiver_start(struct ipts_context *ipts); ++int ipts_receiver_stop(struct ipts_context *ipts); ++ ++#endif /* IPTS_RECEIVER_H */ +diff --git a/drivers/hid/ipts/resources.c b/drivers/hid/ipts/resources.c +new file mode 100644 +index 0000000000000..80ba5885bb55d +--- /dev/null ++++ b/drivers/hid/ipts/resources.c +@@ -0,0 +1,108 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++ ++#include "resources.h" ++#include "spec-device.h" ++ ++static int ipts_resources_alloc_buffer(struct ipts_buffer *buffer, struct device *dev, size_t size) ++{ ++ if (!buffer) ++ return -EFAULT; ++ ++ if (buffer->address) ++ return 0; ++ ++ buffer->address = dma_alloc_coherent(dev, size, &buffer->dma_address, GFP_KERNEL); ++ ++ if (!buffer->address) ++ return -ENOMEM; ++ ++ buffer->size = size; ++ buffer->device = dev; ++ ++ return 0; ++} ++ ++static void ipts_resources_free_buffer(struct ipts_buffer *buffer) ++{ ++ if (!buffer->address) ++ return; ++ ++ dma_free_coherent(buffer->device, buffer->size, buffer->address, buffer->dma_address); ++ ++ buffer->address = NULL; ++ buffer->size = 0; ++ ++ buffer->dma_address = 0; ++ buffer->device = NULL; ++} ++ ++int ipts_resources_init(struct ipts_resources *res, struct device *dev, size_t ds, size_t fs) ++{ ++ int ret = 0; ++ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_resources_alloc_buffer(&res->data[i], dev, ds); ++ if (ret) ++ goto err; ++ } ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) { ++ ret = ipts_resources_alloc_buffer(&res->feedback[i], dev, fs); ++ if (ret) ++ goto err; ++ } ++ ++ ret = ipts_resources_alloc_buffer(&res->doorbell, dev, sizeof(u32)); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->workqueue, dev, sizeof(u32)); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->hid2me, dev, fs); ++ if (ret) ++ goto err; ++ ++ ret = ipts_resources_alloc_buffer(&res->descriptor, dev, ds + 8); ++ if (ret) ++ goto err; ++ ++ return 0; ++ ++err: ++ ++ ipts_resources_free(res); ++ return ret; ++} ++ ++int ipts_resources_free(struct ipts_resources *res) ++{ ++ if (!res) ++ return -EFAULT; ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) ++ ipts_resources_free_buffer(&res->data[i]); ++ ++ for (int i = 0; i < IPTS_BUFFERS; i++) ++ ipts_resources_free_buffer(&res->feedback[i]); ++ ++ ipts_resources_free_buffer(&res->doorbell); ++ ipts_resources_free_buffer(&res->workqueue); ++ ipts_resources_free_buffer(&res->hid2me); ++ ipts_resources_free_buffer(&res->descriptor); ++ ++ return 0; ++} +diff --git a/drivers/hid/ipts/resources.h b/drivers/hid/ipts/resources.h +new file mode 100644 +index 0000000000000..6cbb24a8a0543 +--- /dev/null ++++ b/drivers/hid/ipts/resources.h +@@ -0,0 +1,39 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_RESOURCES_H ++#define IPTS_RESOURCES_H ++ ++#include ++#include ++ ++#include "spec-device.h" ++ ++struct ipts_buffer { ++ u8 *address; ++ size_t size; ++ ++ dma_addr_t dma_address; ++ struct device *device; ++}; ++ ++struct ipts_resources { ++ struct ipts_buffer data[IPTS_BUFFERS]; ++ struct ipts_buffer feedback[IPTS_BUFFERS]; ++ ++ struct ipts_buffer doorbell; ++ struct ipts_buffer workqueue; ++ struct ipts_buffer hid2me; ++ ++ struct ipts_buffer descriptor; ++}; ++ ++int ipts_resources_init(struct ipts_resources *res, struct device *dev, size_t ds, size_t fs); ++int ipts_resources_free(struct ipts_resources *res); ++ ++#endif /* IPTS_RESOURCES_H */ +diff --git a/drivers/hid/ipts/spec-data.h b/drivers/hid/ipts/spec-data.h +new file mode 100644 +index 0000000000000..e8dd98895a7ee +--- /dev/null ++++ b/drivers/hid/ipts/spec-data.h +@@ -0,0 +1,100 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_DATA_H ++#define IPTS_SPEC_DATA_H ++ ++#include ++#include ++ ++/** ++ * enum ipts_feedback_cmd_type - Commands that can be executed on the sensor through feedback. ++ */ ++enum ipts_feedback_cmd_type { ++ IPTS_FEEDBACK_CMD_TYPE_NONE = 0, ++ IPTS_FEEDBACK_CMD_TYPE_SOFT_RESET = 1, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_ARMED = 2, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_SENSING = 3, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_SLEEP = 4, ++ IPTS_FEEDBACK_CMD_TYPE_GOTO_DOZE = 5, ++ IPTS_FEEDBACK_CMD_TYPE_HARD_RESET = 6, ++}; ++ ++/** ++ * enum ipts_feedback_data_type - Defines what data a feedback buffer contains. ++ * @IPTS_FEEDBACK_DATA_TYPE_VENDOR: The buffer contains vendor specific feedback. ++ * @IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES: The buffer contains a HID set features report. ++ * @IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES: The buffer contains a HID get features report. ++ * @IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT: The buffer contains a HID output report. ++ * @IPTS_FEEDBACK_DATA_TYPE_STORE_DATA: The buffer contains calibration data for the sensor. ++ */ ++enum ipts_feedback_data_type { ++ IPTS_FEEDBACK_DATA_TYPE_VENDOR = 0, ++ IPTS_FEEDBACK_DATA_TYPE_SET_FEATURES = 1, ++ IPTS_FEEDBACK_DATA_TYPE_GET_FEATURES = 2, ++ IPTS_FEEDBACK_DATA_TYPE_OUTPUT_REPORT = 3, ++ IPTS_FEEDBACK_DATA_TYPE_STORE_DATA = 4, ++}; ++ ++/** ++ * struct ipts_feedback_header - Header that is prefixed to the data in a feedback buffer. ++ * @cmd_type: A command that should be executed on the sensor. ++ * @size: The size of the payload to be written. ++ * @buffer: The ID of the buffer that contains this feedback data. ++ * @protocol: The protocol version of the EDS. ++ * @data_type: The type of data that the buffer contains. ++ * @spi_offset: The offset at which to write the payload data to the sensor. ++ * @payload: Payload for the feedback command, or 0 if no payload is sent. ++ */ ++struct ipts_feedback_header { ++ enum ipts_feedback_cmd_type cmd_type; ++ u32 size; ++ u32 buffer; ++ u32 protocol; ++ enum ipts_feedback_data_type data_type; ++ u32 spi_offset; ++ u8 reserved[40]; ++ u8 payload[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_feedback_header) == 64); ++ ++/** ++ * enum ipts_data_type - Defines what type of data a buffer contains. ++ * @IPTS_DATA_TYPE_FRAME: Raw data frame. ++ * @IPTS_DATA_TYPE_ERROR: Error data. ++ * @IPTS_DATA_TYPE_VENDOR: Vendor specific data. ++ * @IPTS_DATA_TYPE_HID: A HID report. ++ * @IPTS_DATA_TYPE_GET_FEATURES: The response to a GET_FEATURES HID2ME command. ++ */ ++enum ipts_data_type { ++ IPTS_DATA_TYPE_FRAME = 0x00, ++ IPTS_DATA_TYPE_ERROR = 0x01, ++ IPTS_DATA_TYPE_VENDOR = 0x02, ++ IPTS_DATA_TYPE_HID = 0x03, ++ IPTS_DATA_TYPE_GET_FEATURES = 0x04, ++ IPTS_DATA_TYPE_DESCRIPTOR = 0x05, ++}; ++ ++/** ++ * struct ipts_data_header - Header that is prefixed to the data in a data buffer. ++ * @type: What data the buffer contains. ++ * @size: How much data the buffer contains. ++ * @buffer: Which buffer the data is in. ++ */ ++struct ipts_data_header { ++ enum ipts_data_type type; ++ u32 size; ++ u32 buffer; ++ u8 reserved[52]; ++ u8 data[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_data_header) == 64); ++ ++#endif /* IPTS_SPEC_DATA_H */ +diff --git a/drivers/hid/ipts/spec-device.h b/drivers/hid/ipts/spec-device.h +new file mode 100644 +index 0000000000000..93f673d981f7f +--- /dev/null ++++ b/drivers/hid/ipts/spec-device.h +@@ -0,0 +1,285 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_DEVICE_H ++#define IPTS_SPEC_DEVICE_H ++ ++#include ++#include ++ ++/* ++ * The amount of buffers that IPTS can use for data transfer. ++ */ ++#define IPTS_BUFFERS 16 ++ ++/* ++ * The buffer ID that is used for HID2ME feedback ++ */ ++#define IPTS_HID2ME_BUFFER IPTS_BUFFERS ++ ++/** ++ * enum ipts_command - Commands that can be sent to the IPTS hardware. ++ * @IPTS_CMD_GET_DEVICE_INFO: Retrieves vendor information from the device. ++ * @IPTS_CMD_SET_MODE: Changes the mode that the device will operate in. ++ * @IPTS_CMD_SET_MEM_WINDOW: Configures memory buffers for passing data between device and driver. ++ * @IPTS_CMD_QUIESCE_IO: Stops the data flow from the device to the driver. ++ * @IPTS_CMD_READY_FOR_DATA: Informs the device that the driver is ready to receive data. ++ * @IPTS_CMD_FEEDBACK: Informs the device that a buffer was processed and can be refilled. ++ * @IPTS_CMD_CLEAR_MEM_WINDOW: Stops the data flow and clears the buffer addresses on the device. ++ * @IPTS_CMD_RESET_SENSOR: Resets the sensor to its default state. ++ * @IPTS_CMD_GET_DESCRIPTOR: Retrieves the HID descriptor of the device. ++ */ ++enum ipts_command_code { ++ IPTS_CMD_GET_DEVICE_INFO = 0x01, ++ IPTS_CMD_SET_MODE = 0x02, ++ IPTS_CMD_SET_MEM_WINDOW = 0x03, ++ IPTS_CMD_QUIESCE_IO = 0x04, ++ IPTS_CMD_READY_FOR_DATA = 0x05, ++ IPTS_CMD_FEEDBACK = 0x06, ++ IPTS_CMD_CLEAR_MEM_WINDOW = 0x07, ++ IPTS_CMD_RESET_SENSOR = 0x0B, ++ IPTS_CMD_GET_DESCRIPTOR = 0x0F, ++}; ++ ++/** ++ * enum ipts_status - Possible status codes returned by the IPTS device. ++ * @IPTS_STATUS_SUCCESS: Operation completed successfully. ++ * @IPTS_STATUS_INVALID_PARAMS: Command contained an invalid payload. ++ * @IPTS_STATUS_ACCESS_DENIED: ME could not validate a buffer address. ++ * @IPTS_STATUS_CMD_SIZE_ERROR: Command contains an invalid payload. ++ * @IPTS_STATUS_NOT_READY: Buffer addresses have not been set. ++ * @IPTS_STATUS_REQUEST_OUTSTANDING: There is an outstanding command of the same type. ++ * @IPTS_STATUS_NO_SENSOR_FOUND: No sensor could be found. ++ * @IPTS_STATUS_OUT_OF_MEMORY: Not enough free memory for requested operation. ++ * @IPTS_STATUS_INTERNAL_ERROR: An unexpected error occurred. ++ * @IPTS_STATUS_SENSOR_DISABLED: The sensor has been disabled and must be reinitialized. ++ * @IPTS_STATUS_COMPAT_CHECK_FAIL: Compatibility revision check between sensor and ME failed. ++ * The host can ignore this error and attempt to continue. ++ * @IPTS_STATUS_SENSOR_EXPECTED_RESET: The sensor went through a reset initiated by the driver. ++ * @IPTS_STATUS_SENSOR_UNEXPECTED_RESET: The sensor went through an unexpected reset. ++ * @IPTS_STATUS_RESET_FAILED: Requested sensor reset failed to complete. ++ * @IPTS_STATUS_TIMEOUT: The operation timed out. ++ * @IPTS_STATUS_TEST_MODE_FAIL: Test mode pattern did not match expected values. ++ * @IPTS_STATUS_SENSOR_FAIL_FATAL: The sensor reported an error during reset sequence. ++ * Further progress is not possible. ++ * @IPTS_STATUS_SENSOR_FAIL_NONFATAL: The sensor reported an error during reset sequence. ++ * The driver can attempt to continue. ++ * @IPTS_STATUS_INVALID_DEVICE_CAPS: The device reported invalid capabilities. ++ * @IPTS_STATUS_QUIESCE_IO_IN_PROGRESS: Command cannot be completed until Quiesce IO is done. ++ */ ++enum ipts_status { ++ IPTS_STATUS_SUCCESS = 0x00, ++ IPTS_STATUS_INVALID_PARAMS = 0x01, ++ IPTS_STATUS_ACCESS_DENIED = 0x02, ++ IPTS_STATUS_CMD_SIZE_ERROR = 0x03, ++ IPTS_STATUS_NOT_READY = 0x04, ++ IPTS_STATUS_REQUEST_OUTSTANDING = 0x05, ++ IPTS_STATUS_NO_SENSOR_FOUND = 0x06, ++ IPTS_STATUS_OUT_OF_MEMORY = 0x07, ++ IPTS_STATUS_INTERNAL_ERROR = 0x08, ++ IPTS_STATUS_SENSOR_DISABLED = 0x09, ++ IPTS_STATUS_COMPAT_CHECK_FAIL = 0x0A, ++ IPTS_STATUS_SENSOR_EXPECTED_RESET = 0x0B, ++ IPTS_STATUS_SENSOR_UNEXPECTED_RESET = 0x0C, ++ IPTS_STATUS_RESET_FAILED = 0x0D, ++ IPTS_STATUS_TIMEOUT = 0x0E, ++ IPTS_STATUS_TEST_MODE_FAIL = 0x0F, ++ IPTS_STATUS_SENSOR_FAIL_FATAL = 0x10, ++ IPTS_STATUS_SENSOR_FAIL_NONFATAL = 0x11, ++ IPTS_STATUS_INVALID_DEVICE_CAPS = 0x12, ++ IPTS_STATUS_QUIESCE_IO_IN_PROGRESS = 0x13, ++}; ++ ++/** ++ * struct ipts_command - Message that is sent to the device for calling a command. ++ * @cmd: The command that will be called. ++ * @payload: Payload containing parameters for the called command. ++ */ ++struct ipts_command { ++ enum ipts_command_code cmd; ++ u8 payload[320]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_command) == 324); ++ ++/** ++ * enum ipts_mode - Configures what data the device produces and how its sent. ++ * @IPTS_MODE_EVENT: The device will send an event once a buffer was filled. ++ * Older devices will return singletouch data in this mode. ++ * @IPTS_MODE_DOORBELL: The device will notify the driver by incrementing the doorbell value. ++ * Older devices will return multitouch data in this mode. ++ */ ++enum ipts_mode { ++ IPTS_MODE_EVENT = 0x00, ++ IPTS_MODE_DOORBELL = 0x01, ++}; ++ ++/** ++ * struct ipts_set_mode - Payload for the SET_MODE command. ++ * @mode: Changes the mode that IPTS will operate in. ++ */ ++struct ipts_set_mode { ++ enum ipts_mode mode; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_set_mode) == 16); ++ ++#define IPTS_WORKQUEUE_SIZE 8192 ++#define IPTS_WORKQUEUE_ITEM_SIZE 16 ++ ++/** ++ * struct ipts_mem_window - Payload for the SET_MEM_WINDOW command. ++ * @data_addr_lower: Lower 32 bits of the data buffer addresses. ++ * @data_addr_upper: Upper 32 bits of the data buffer addresses. ++ * @workqueue_addr_lower: Lower 32 bits of the workqueue buffer address. ++ * @workqueue_addr_upper: Upper 32 bits of the workqueue buffer address. ++ * @doorbell_addr_lower: Lower 32 bits of the doorbell buffer address. ++ * @doorbell_addr_upper: Upper 32 bits of the doorbell buffer address. ++ * @feedbackaddr_lower: Lower 32 bits of the feedback buffer addresses. ++ * @feedbackaddr_upper: Upper 32 bits of the feedback buffer addresses. ++ * @hid2me_addr_lower: Lower 32 bits of the hid2me buffer address. ++ * @hid2me_addr_upper: Upper 32 bits of the hid2me buffer address. ++ * @hid2me_size: Size of the hid2me feedback buffer. ++ * @workqueue_item_size: Magic value. Must be 16. ++ * @workqueue_size: Magic value. Must be 8192. ++ * ++ * The workqueue related items in this struct are required for using ++ * GuC submission with binary processing firmware. Since this driver does ++ * not use GuC submission and instead exports raw data to userspace, these ++ * items are not actually used, but they need to be allocated and passed ++ * to the device, otherwise initialization will fail. ++ */ ++struct ipts_mem_window { ++ u32 data_addr_lower[IPTS_BUFFERS]; ++ u32 data_addr_upper[IPTS_BUFFERS]; ++ u32 workqueue_addr_lower; ++ u32 workqueue_addr_upper; ++ u32 doorbell_addr_lower; ++ u32 doorbell_addr_upper; ++ u32 feedback_addr_lower[IPTS_BUFFERS]; ++ u32 feedback_addr_upper[IPTS_BUFFERS]; ++ u32 hid2me_addr_lower; ++ u32 hid2me_addr_upper; ++ u32 hid2me_size; ++ u8 reserved1; ++ u8 workqueue_item_size; ++ u16 workqueue_size; ++ u8 reserved[32]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_mem_window) == 320); ++ ++/** ++ * struct ipts_quiesce_io - Payload for the QUIESCE_IO command. ++ */ ++struct ipts_quiesce_io { ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_quiesce_io) == 12); ++ ++/** ++ * struct ipts_feedback - Payload for the FEEDBACK command. ++ * @buffer: The buffer that the device should refill. ++ */ ++struct ipts_feedback { ++ u32 buffer; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_feedback) == 16); ++ ++/** ++ * enum ipts_reset_type - Possible ways of resetting the device. ++ * @IPTS_RESET_TYPE_HARD: Perform hardware reset using GPIO pin. ++ * @IPTS_RESET_TYPE_SOFT: Perform software reset using SPI command. ++ */ ++enum ipts_reset_type { ++ IPTS_RESET_TYPE_HARD = 0x00, ++ IPTS_RESET_TYPE_SOFT = 0x01, ++}; ++ ++/** ++ * struct ipts_reset - Payload for the RESET_SENSOR command. ++ * @type: How the device should get reset. ++ */ ++struct ipts_reset_sensor { ++ enum ipts_reset_type type; ++ u8 reserved[4]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_reset_sensor) == 8); ++ ++/** ++ * struct ipts_get_descriptor - Payload for the GET_DESCRIPTOR command. ++ * @addr_lower: The lower 32 bits of the descriptor buffer address. ++ * @addr_upper: The upper 32 bits of the descriptor buffer address. ++ * @magic: A magic value. Must be 8. ++ */ ++struct ipts_get_descriptor { ++ u32 addr_lower; ++ u32 addr_upper; ++ u32 magic; ++ u8 reserved[12]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_get_descriptor) == 24); ++ ++/* ++ * The type of a response is indicated by a ++ * command code, with the most significant bit flipped to 1. ++ */ ++#define IPTS_RSP_BIT BIT(31) ++ ++/** ++ * struct ipts_response - Data returned from the device in response to a command. ++ * @cmd: The command that this response answers (IPTS_RSP_BIT will be 1). ++ * @status: The return code of the command. ++ * @payload: The data that was produced by the command. ++ */ ++struct ipts_response { ++ enum ipts_command_code cmd; ++ enum ipts_status status; ++ u8 payload[80]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_response) == 88); ++ ++/** ++ * struct ipts_device_info - Vendor information of the IPTS device. ++ * @vendor: Vendor ID of this device. ++ * @product: Product ID of this device. ++ * @hw_version: Hardware revision of this device. ++ * @fw_version: Firmware revision of this device. ++ * @data_size: Requested size for a data buffer. ++ * @feedback_size: Requested size for a feedback buffer. ++ * @mode: Mode that the device currently operates in. ++ * @max_contacts: Maximum amount of concurrent touches the sensor can process. ++ */ ++struct ipts_device_info { ++ u16 vendor; ++ u16 product; ++ u32 hw_version; ++ u32 fw_version; ++ u32 data_size; ++ u32 feedback_size; ++ enum ipts_mode mode; ++ u8 max_contacts; ++ u8 reserved1[3]; ++ u8 sensor_min_eds; ++ u8 sensor_maj_eds; ++ u8 me_min_eds; ++ u8 me_maj_eds; ++ u8 intf_eds; ++ u8 reserved2[11]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_device_info) == 44); ++ ++#endif /* IPTS_SPEC_DEVICE_H */ +diff --git a/drivers/hid/ipts/spec-hid.h b/drivers/hid/ipts/spec-hid.h +new file mode 100644 +index 0000000000000..ea70f29ff00cb +--- /dev/null ++++ b/drivers/hid/ipts/spec-hid.h +@@ -0,0 +1,35 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2020-2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_SPEC_HID_H ++#define IPTS_SPEC_HID_H ++ ++#include ++#include ++ ++/* ++ * Made-up type for passing raw IPTS data in a HID report. ++ */ ++#define IPTS_HID_FRAME_TYPE_RAW 0xEE ++ ++/** ++ * struct ipts_hid_frame - Header that is prefixed to raw IPTS data wrapped in a HID report. ++ * @size: Size of the data inside the report, including this header. ++ * @type: What type of data does this report contain. ++ */ ++struct ipts_hid_header { ++ u32 size; ++ u8 reserved1; ++ u8 type; ++ u8 reserved2; ++ u8 data[]; ++} __packed; ++ ++static_assert(sizeof(struct ipts_hid_header) == 7); ++ ++#endif /* IPTS_SPEC_HID_H */ +diff --git a/drivers/hid/ipts/thread.c b/drivers/hid/ipts/thread.c +new file mode 100644 +index 0000000000000..8b46f775c1070 +--- /dev/null ++++ b/drivers/hid/ipts/thread.c +@@ -0,0 +1,85 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include "thread.h" ++ ++bool ipts_thread_should_stop(struct ipts_thread *thread) ++{ ++ if (!thread) ++ return false; ++ ++ return READ_ONCE(thread->should_stop); ++} ++ ++static int ipts_thread_runner(void *data) ++{ ++ int ret = 0; ++ struct ipts_thread *thread = data; ++ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!thread->threadfn) ++ return -EFAULT; ++ ++ ret = thread->threadfn(thread); ++ complete_all(&thread->done); ++ ++ return ret; ++} ++ ++int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), ++ void *data, const char *name) ++{ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!threadfn) ++ return -EFAULT; ++ ++ init_completion(&thread->done); ++ ++ thread->data = data; ++ thread->should_stop = false; ++ thread->threadfn = threadfn; ++ ++ thread->thread = kthread_run(ipts_thread_runner, thread, name); ++ return PTR_ERR_OR_ZERO(thread->thread); ++} ++ ++int ipts_thread_stop(struct ipts_thread *thread) ++{ ++ int ret = 0; ++ ++ if (!thread) ++ return -EFAULT; ++ ++ if (!thread->thread) ++ return 0; ++ ++ WRITE_ONCE(thread->should_stop, true); ++ ++ /* ++ * Make sure that the write has gone through before waiting. ++ */ ++ wmb(); ++ ++ wait_for_completion(&thread->done); ++ ret = kthread_stop(thread->thread); ++ ++ thread->thread = NULL; ++ thread->data = NULL; ++ thread->threadfn = NULL; ++ ++ return ret; ++} +diff --git a/drivers/hid/ipts/thread.h b/drivers/hid/ipts/thread.h +new file mode 100644 +index 0000000000000..a314843599fc3 +--- /dev/null ++++ b/drivers/hid/ipts/thread.h +@@ -0,0 +1,60 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Copyright (c) 2016 Intel Corporation ++ * Copyright (c) 2023 Dorian Stoll ++ * ++ * Linux driver for Intel Precise Touch & Stylus ++ */ ++ ++#ifndef IPTS_THREAD_H ++#define IPTS_THREAD_H ++ ++#include ++#include ++#include ++ ++/* ++ * This wrapper over kthread is necessary, because calling kthread_stop makes it impossible ++ * to issue MEI commands from that thread while it shuts itself down. By using a custom ++ * boolean variable and a completion object, we can call kthread_stop only when the thread ++ * already finished all of its work and has returned. ++ */ ++struct ipts_thread { ++ struct task_struct *thread; ++ ++ bool should_stop; ++ struct completion done; ++ ++ void *data; ++ int (*threadfn)(struct ipts_thread *thread); ++}; ++ ++/* ++ * ipts_thread_should_stop() - Returns true if the thread is asked to terminate. ++ * @thread: The current thread. ++ * ++ * Returns: true if the thread should stop, false if not. ++ */ ++bool ipts_thread_should_stop(struct ipts_thread *thread); ++ ++/* ++ * ipts_thread_start() - Starts an IPTS thread. ++ * @thread: The thread to initialize and start. ++ * @threadfn: The function to execute. ++ * @data: An argument that will be passed to threadfn. ++ * @name: The name of the new thread. ++ * ++ * Returns: 0 on success, <0 on error. ++ */ ++int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), ++ void *data, const char name[]); ++ ++/* ++ * ipts_thread_stop() - Asks the thread to terminate and waits until it has finished. ++ * @thread: The thread that should stop. ++ * ++ * Returns: The return value of the thread function. ++ */ ++int ipts_thread_stop(struct ipts_thread *thread); ++ ++#endif /* IPTS_THREAD_H */ +-- +2.40.0 + diff --git a/patches/surface/0005-ithc.patch b/patches/surface/0005-ithc.patch new file mode 100644 index 0000000..797a2b5 --- /dev/null +++ b/patches/surface/0005-ithc.patch @@ -0,0 +1,1433 @@ +From f07217f4ff2153f65c4acfffd6db69821bc75a12 Mon Sep 17 00:00:00 2001 +From: Dorian Stoll +Date: Sun, 11 Dec 2022 12:03:38 +0100 +Subject: [PATCH] iommu: intel: Disable source id verification for ITHC + +Signed-off-by: Dorian Stoll +Patchset: ithc +--- + drivers/iommu/intel/irq_remapping.c | 16 ++++++++++++++++ + 1 file changed, 16 insertions(+) + +diff --git a/drivers/iommu/intel/irq_remapping.c b/drivers/iommu/intel/irq_remapping.c +index f58f5f57af782..59a6a458d9bfa 100644 +--- a/drivers/iommu/intel/irq_remapping.c ++++ b/drivers/iommu/intel/irq_remapping.c +@@ -394,6 +394,22 @@ static int set_msi_sid(struct irte *irte, struct pci_dev *dev) + data.busmatch_count = 0; + pci_for_each_dma_alias(dev, set_msi_sid_cb, &data); + ++ /* ++ * The Intel Touch Host Controller is at 00:10.6, but for some reason ++ * the MSI interrupts have request id 01:05.0. ++ * Disable id verification to work around this. ++ * FIXME Find proper fix or turn this into a quirk. ++ */ ++ if (dev->vendor == PCI_VENDOR_ID_INTEL && (dev->class >> 8) == PCI_CLASS_INPUT_PEN) { ++ switch(dev->device) { ++ case 0x98d0: case 0x98d1: // LKF ++ case 0xa0d0: case 0xa0d1: // TGL LP ++ case 0x43d0: case 0x43d1: // TGL H ++ set_irte_sid(irte, SVT_NO_VERIFY, SQ_ALL_16, 0); ++ return 0; ++ } ++ } ++ + /* + * DMA alias provides us with a PCI device and alias. The only case + * where the it will return an alias on a different bus than the +-- +2.40.0 + +From c7eb973cd2ff39eedbd00f78b7b5240549edb89e Mon Sep 17 00:00:00 2001 +From: Dorian Stoll +Date: Sun, 11 Dec 2022 12:10:54 +0100 +Subject: [PATCH] hid: Add support for Intel Touch Host Controller + +Based on quo/ithc-linux@55803a2 + +Signed-off-by: Dorian Stoll +Patchset: ithc +--- + drivers/hid/Kconfig | 2 + + drivers/hid/Makefile | 1 + + drivers/hid/ithc/Kbuild | 6 + + drivers/hid/ithc/Kconfig | 12 + + drivers/hid/ithc/ithc-debug.c | 96 ++++++ + drivers/hid/ithc/ithc-dma.c | 258 ++++++++++++++++ + drivers/hid/ithc/ithc-dma.h | 67 +++++ + drivers/hid/ithc/ithc-main.c | 534 ++++++++++++++++++++++++++++++++++ + drivers/hid/ithc/ithc-regs.c | 64 ++++ + drivers/hid/ithc/ithc-regs.h | 186 ++++++++++++ + drivers/hid/ithc/ithc.h | 60 ++++ + 11 files changed, 1286 insertions(+) + create mode 100644 drivers/hid/ithc/Kbuild + create mode 100644 drivers/hid/ithc/Kconfig + create mode 100644 drivers/hid/ithc/ithc-debug.c + create mode 100644 drivers/hid/ithc/ithc-dma.c + create mode 100644 drivers/hid/ithc/ithc-dma.h + create mode 100644 drivers/hid/ithc/ithc-main.c + create mode 100644 drivers/hid/ithc/ithc-regs.c + create mode 100644 drivers/hid/ithc/ithc-regs.h + create mode 100644 drivers/hid/ithc/ithc.h + +diff --git a/drivers/hid/Kconfig b/drivers/hid/Kconfig +index a4af77fcca209..4ece2a06949bf 100644 +--- a/drivers/hid/Kconfig ++++ b/drivers/hid/Kconfig +@@ -1293,4 +1293,6 @@ source "drivers/hid/surface-hid/Kconfig" + + source "drivers/hid/ipts/Kconfig" + ++source "drivers/hid/ithc/Kconfig" ++ + endmenu +diff --git a/drivers/hid/Makefile b/drivers/hid/Makefile +index e48300bcea9be..8ef7308b0f9d7 100644 +--- a/drivers/hid/Makefile ++++ b/drivers/hid/Makefile +@@ -166,3 +166,4 @@ obj-$(CONFIG_AMD_SFH_HID) += amd-sfh-hid/ + obj-$(CONFIG_SURFACE_HID_CORE) += surface-hid/ + + obj-$(CONFIG_HID_IPTS) += ipts/ ++obj-$(CONFIG_HID_ITHC) += ithc/ +diff --git a/drivers/hid/ithc/Kbuild b/drivers/hid/ithc/Kbuild +new file mode 100644 +index 0000000000000..aea83f2ac07b4 +--- /dev/null ++++ b/drivers/hid/ithc/Kbuild +@@ -0,0 +1,6 @@ ++obj-$(CONFIG_HID_ITHC) := ithc.o ++ ++ithc-objs := ithc-main.o ithc-regs.o ithc-dma.o ithc-debug.o ++ ++ccflags-y := -std=gnu11 -Wno-declaration-after-statement ++ +diff --git a/drivers/hid/ithc/Kconfig b/drivers/hid/ithc/Kconfig +new file mode 100644 +index 0000000000000..ede7130236096 +--- /dev/null ++++ b/drivers/hid/ithc/Kconfig +@@ -0,0 +1,12 @@ ++config HID_ITHC ++ tristate "Intel Touch Host Controller" ++ depends on PCI ++ depends on HID ++ help ++ Say Y here if your system has a touchscreen using Intels ++ Touch Host Controller (ITHC / IPTS) technology. ++ ++ If unsure say N. ++ ++ To compile this driver as a module, choose M here: the ++ module will be called ithc. +diff --git a/drivers/hid/ithc/ithc-debug.c b/drivers/hid/ithc/ithc-debug.c +new file mode 100644 +index 0000000000000..57bf125c45bd5 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-debug.c +@@ -0,0 +1,96 @@ ++#include "ithc.h" ++ ++void ithc_log_regs(struct ithc *ithc) { ++ if (!ithc->prev_regs) return; ++ u32 __iomem *cur = (__iomem void*)ithc->regs; ++ u32 *prev = (void*)ithc->prev_regs; ++ for (int i = 1024; i < sizeof *ithc->regs / 4; i++) { ++ u32 x = readl(cur + i); ++ if (x != prev[i]) { ++ pci_info(ithc->pci, "reg %04x: %08x -> %08x\n", i * 4, prev[i], x); ++ prev[i] = x; ++ } ++ } ++} ++ ++static ssize_t ithc_debugfs_cmd_write(struct file *f, const char __user *buf, size_t len, loff_t *offset) { ++ struct ithc *ithc = file_inode(f)->i_private; ++ char cmd[256]; ++ if (!ithc || !ithc->pci) return -ENODEV; ++ if (!len) return -EINVAL; ++ if (len >= sizeof cmd) return -EINVAL; ++ if (copy_from_user(cmd, buf, len)) return -EFAULT; ++ cmd[len] = 0; ++ if (cmd[len-1] == '\n') cmd[len-1] = 0; ++ pci_info(ithc->pci, "debug command: %s\n", cmd); ++ u32 n = 0; ++ const char *s = cmd + 1; ++ u32 a[32]; ++ while (*s && *s != '\n') { ++ if (n >= ARRAY_SIZE(a)) return -EINVAL; ++ if (*s++ != ' ') return -EINVAL; ++ char *e; ++ a[n++] = simple_strtoul(s, &e, 0); ++ if (e == s) return -EINVAL; ++ s = e; ++ } ++ ithc_log_regs(ithc); ++ switch(cmd[0]) { ++ case 'x': // reset ++ ithc_reset(ithc); ++ break; ++ case 'w': // write register: offset mask value ++ if (n != 3 || (a[0] & 3)) return -EINVAL; ++ pci_info(ithc->pci, "debug write 0x%04x = 0x%08x (mask 0x%08x)\n", a[0], a[2], a[1]); ++ bitsl(((__iomem u32 *)ithc->regs) + a[0] / 4, a[1], a[2]); ++ break; ++ case 'r': // read register: offset ++ if (n != 1 || (a[0] & 3)) return -EINVAL; ++ pci_info(ithc->pci, "debug read 0x%04x = 0x%08x\n", a[0], readl(((__iomem u32 *)ithc->regs) + a[0] / 4)); ++ break; ++ case 's': // spi command: cmd offset len data... ++ // read config: s 4 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ++ // set touch cfg: s 6 12 4 XX ++ if (n < 3 || a[2] > (n - 3) * 4) return -EINVAL; ++ pci_info(ithc->pci, "debug spi command %u with %u bytes of data\n", a[0], a[2]); ++ if (!CHECK(ithc_spi_command, ithc, a[0], a[1], a[2], a + 3)) ++ for (u32 i = 0; i < (a[2] + 3) / 4; i++) pci_info(ithc->pci, "resp %u = 0x%08x\n", i, a[3+i]); ++ break; ++ case 'd': // dma command: cmd len data... ++ // get report descriptor: d 7 8 0 0 ++ // enable multitouch: d 3 2 0x0105 ++ if (n < 2 || a[1] > (n - 2) * 4) return -EINVAL; ++ pci_info(ithc->pci, "debug dma command %u with %u bytes of data\n", a[0], a[1]); ++ if (ithc_dma_tx(ithc, a[0], a[1], a + 2)) pci_err(ithc->pci, "dma tx failed\n"); ++ break; ++ default: ++ return -EINVAL; ++ } ++ ithc_log_regs(ithc); ++ return len; ++} ++ ++static const struct file_operations ithc_debugfops_cmd = { ++ .owner = THIS_MODULE, ++ .write = ithc_debugfs_cmd_write, ++}; ++ ++static void ithc_debugfs_devres_release(struct device *dev, void *res) { ++ struct dentry **dbgm = res; ++ if (*dbgm) debugfs_remove_recursive(*dbgm); ++} ++ ++int ithc_debug_init(struct ithc *ithc) { ++ struct dentry **dbgm = devres_alloc(ithc_debugfs_devres_release, sizeof *dbgm, GFP_KERNEL); ++ if (!dbgm) return -ENOMEM; ++ devres_add(&ithc->pci->dev, dbgm); ++ struct dentry *dbg = debugfs_create_dir(DEVNAME, NULL); ++ if (IS_ERR(dbg)) return PTR_ERR(dbg); ++ *dbgm = dbg; ++ ++ struct dentry *cmd = debugfs_create_file("cmd", 0220, dbg, ithc, &ithc_debugfops_cmd); ++ if (IS_ERR(cmd)) return PTR_ERR(cmd); ++ ++ return 0; ++} ++ +diff --git a/drivers/hid/ithc/ithc-dma.c b/drivers/hid/ithc/ithc-dma.c +new file mode 100644 +index 0000000000000..7e89b3496918d +--- /dev/null ++++ b/drivers/hid/ithc/ithc-dma.c +@@ -0,0 +1,258 @@ ++#include "ithc.h" ++ ++static int ithc_dma_prd_alloc(struct ithc *ithc, struct ithc_dma_prd_buffer *p, unsigned num_buffers, unsigned num_pages, enum dma_data_direction dir) { ++ p->num_pages = num_pages; ++ p->dir = dir; ++ p->size = round_up(num_buffers * num_pages * sizeof(struct ithc_phys_region_desc), PAGE_SIZE); ++ p->addr = dmam_alloc_coherent(&ithc->pci->dev, p->size, &p->dma_addr, GFP_KERNEL); ++ if (!p->addr) return -ENOMEM; ++ if (p->dma_addr & (PAGE_SIZE - 1)) return -EFAULT; ++ return 0; ++} ++ ++struct ithc_sg_table { ++ void *addr; ++ struct sg_table sgt; ++ enum dma_data_direction dir; ++}; ++static void ithc_dma_sgtable_free(struct sg_table *sgt) { ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_sg(sgt, sg, i) { ++ struct page *p = sg_page(sg); ++ if (p) __free_page(p); ++ } ++ sg_free_table(sgt); ++} ++static void ithc_dma_data_devres_release(struct device *dev, void *res) { ++ struct ithc_sg_table *sgt = res; ++ if (sgt->addr) vunmap(sgt->addr); ++ dma_unmap_sgtable(dev, &sgt->sgt, sgt->dir, 0); ++ ithc_dma_sgtable_free(&sgt->sgt); ++} ++ ++static int ithc_dma_data_alloc(struct ithc* ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b) { ++ // We don't use dma_alloc_coherent for data buffers, because they don't have to be contiguous (we can use one PRD per page) or coherent (they are unidirectional). ++ // Instead we use an sg_table of individually allocated pages (5.13 has dma_alloc_noncontiguous for this, but we'd like to support 5.10 for now). ++ struct page *pages[16]; ++ if (prds->num_pages == 0 || prds->num_pages > ARRAY_SIZE(pages)) return -EINVAL; ++ b->active_idx = -1; ++ struct ithc_sg_table *sgt = devres_alloc(ithc_dma_data_devres_release, sizeof *sgt, GFP_KERNEL); ++ if (!sgt) return -ENOMEM; ++ sgt->dir = prds->dir; ++ if (!sg_alloc_table(&sgt->sgt, prds->num_pages, GFP_KERNEL)) { ++ struct scatterlist *sg; ++ int i; ++ bool ok = true; ++ for_each_sgtable_sg(&sgt->sgt, sg, i) { ++ struct page *p = pages[i] = alloc_page(GFP_KERNEL | __GFP_ZERO); // don't need __GFP_DMA for PCI DMA ++ if (!p) { ok = false; break; } ++ sg_set_page(sg, p, PAGE_SIZE, 0); ++ } ++ if (ok && !dma_map_sgtable(&ithc->pci->dev, &sgt->sgt, prds->dir, 0)) { ++ devres_add(&ithc->pci->dev, sgt); ++ b->sgt = &sgt->sgt; ++ b->addr = sgt->addr = vmap(pages, prds->num_pages, 0, PAGE_KERNEL); ++ if (!b->addr) return -ENOMEM; ++ return 0; ++ } ++ ithc_dma_sgtable_free(&sgt->sgt); ++ } ++ devres_free(sgt); ++ return -ENOMEM; ++} ++ ++static int ithc_dma_data_buffer_put(struct ithc *ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b, unsigned idx) { ++ struct ithc_phys_region_desc *prd = prds->addr; ++ prd += idx * prds->num_pages; ++ if (b->active_idx >= 0) { pci_err(ithc->pci, "buffer already active\n"); return -EINVAL; } ++ b->active_idx = idx; ++ if (prds->dir == DMA_TO_DEVICE) { ++ if (b->data_size > PAGE_SIZE) return -EINVAL; ++ prd->addr = sg_dma_address(b->sgt->sgl) >> 10; ++ prd->size = b->data_size | PRD_FLAG_END; ++ flush_kernel_vmap_range(b->addr, b->data_size); ++ } else if (prds->dir == DMA_FROM_DEVICE) { ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_dma_sg(b->sgt, sg, i) { ++ prd->addr = sg_dma_address(sg) >> 10; ++ prd->size = sg_dma_len(sg); ++ prd++; ++ } ++ prd[-1].size |= PRD_FLAG_END; ++ } ++ dma_wmb(); // for the prds ++ dma_sync_sgtable_for_device(&ithc->pci->dev, b->sgt, prds->dir); ++ return 0; ++} ++ ++static int ithc_dma_data_buffer_get(struct ithc *ithc, struct ithc_dma_prd_buffer *prds, struct ithc_dma_data_buffer *b, unsigned idx) { ++ struct ithc_phys_region_desc *prd = prds->addr; ++ prd += idx * prds->num_pages; ++ if (b->active_idx != idx) { pci_err(ithc->pci, "wrong buffer index\n"); return -EINVAL; } ++ b->active_idx = -1; ++ if (prds->dir == DMA_FROM_DEVICE) { ++ dma_rmb(); // for the prds ++ b->data_size = 0; ++ struct scatterlist *sg; ++ int i; ++ for_each_sgtable_dma_sg(b->sgt, sg, i) { ++ unsigned size = prd->size; ++ b->data_size += size & PRD_SIZE_MASK; ++ if (size & PRD_FLAG_END) break; ++ if ((size & PRD_SIZE_MASK) != sg_dma_len(sg)) { pci_err(ithc->pci, "truncated prd\n"); break; } ++ prd++; ++ } ++ invalidate_kernel_vmap_range(b->addr, b->data_size); ++ } ++ dma_sync_sgtable_for_cpu(&ithc->pci->dev, b->sgt, prds->dir); ++ return 0; ++} ++ ++int ithc_dma_rx_init(struct ithc *ithc, u8 channel, const char *devname) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ mutex_init(&rx->mutex); ++ u32 buf_size = DEVCFG_DMA_RX_SIZE(ithc->config.dma_buf_sizes); ++ unsigned num_pages = (buf_size + PAGE_SIZE - 1) / PAGE_SIZE; ++ pci_dbg(ithc->pci, "allocating rx buffers: num = %u, size = %u, pages = %u\n", NUM_RX_BUF, buf_size, num_pages); ++ CHECK_RET(ithc_dma_prd_alloc, ithc, &rx->prds, NUM_RX_BUF, num_pages, DMA_FROM_DEVICE); ++ for (unsigned i = 0; i < NUM_RX_BUF; i++) ++ CHECK_RET(ithc_dma_data_alloc, ithc, &rx->prds, &rx->bufs[i]); ++ writeb(DMA_RX_CONTROL2_RESET, &ithc->regs->dma_rx[channel].control2); ++ lo_hi_writeq(rx->prds.dma_addr, &ithc->regs->dma_rx[channel].addr); ++ writeb(NUM_RX_BUF - 1, &ithc->regs->dma_rx[channel].num_bufs); ++ writeb(num_pages - 1, &ithc->regs->dma_rx[channel].num_prds); ++ u8 head = readb(&ithc->regs->dma_rx[channel].head); ++ if (head) { pci_err(ithc->pci, "head is nonzero (%u)\n", head); return -EIO; } ++ for (unsigned i = 0; i < NUM_RX_BUF; i++) ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &rx->prds, &rx->bufs[i], i); ++ writeb(head ^ DMA_RX_WRAP_FLAG, &ithc->regs->dma_rx[channel].tail); ++ return 0; ++} ++void ithc_dma_rx_enable(struct ithc *ithc, u8 channel) { ++ bitsb_set(&ithc->regs->dma_rx[channel].control, DMA_RX_CONTROL_ENABLE | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_DATA); ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[1].status, DMA_RX_STATUS_ENABLED, DMA_RX_STATUS_ENABLED); ++} ++ ++int ithc_dma_tx_init(struct ithc *ithc) { ++ struct ithc_dma_tx *tx = &ithc->dma_tx; ++ mutex_init(&tx->mutex); ++ tx->max_size = DEVCFG_DMA_TX_SIZE(ithc->config.dma_buf_sizes); ++ unsigned num_pages = (tx->max_size + PAGE_SIZE - 1) / PAGE_SIZE; ++ pci_dbg(ithc->pci, "allocating tx buffers: size = %u, pages = %u\n", tx->max_size, num_pages); ++ CHECK_RET(ithc_dma_prd_alloc, ithc, &tx->prds, 1, num_pages, DMA_TO_DEVICE); ++ CHECK_RET(ithc_dma_data_alloc, ithc, &tx->prds, &tx->buf); ++ lo_hi_writeq(tx->prds.dma_addr, &ithc->regs->dma_tx.addr); ++ writeb(num_pages - 1, &ithc->regs->dma_tx.num_prds); ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ return 0; ++} ++ ++static int ithc_dma_rx_process_buf(struct ithc *ithc, struct ithc_dma_data_buffer *data, u8 channel, u8 buf) { ++ if (buf >= NUM_RX_BUF) { ++ pci_err(ithc->pci, "invalid dma ringbuffer index\n"); ++ return -EINVAL; ++ } ++ ithc_set_active(ithc); ++ u32 len = data->data_size; ++ struct ithc_dma_rx_header *hdr = data->addr; ++ u8 *hiddata = (void *)(hdr + 1); ++ if (len >= sizeof *hdr && hdr->code == DMA_RX_CODE_RESET) { ++ CHECK(ithc_reset, ithc); ++ } else if (len < sizeof *hdr || len != sizeof *hdr + hdr->data_size) { ++ if (hdr->code == DMA_RX_CODE_INPUT_REPORT) { ++ // When the CPU enters a low power state during DMA, we can get truncated messages. ++ // Typically this will be a single touch HID report that is only 1 byte, or a multitouch report that is 257 bytes. ++ // See also ithc_set_active(). ++ } else { ++ pci_err(ithc->pci, "invalid dma rx data! channel %u, buffer %u, size %u, code %u, data size %u\n", channel, buf, len, hdr->code, hdr->data_size); ++ print_hex_dump_debug(DEVNAME " data: ", DUMP_PREFIX_OFFSET, 32, 1, hdr, min(len, 0x400u), 0); ++ } ++ } else if (hdr->code == DMA_RX_CODE_REPORT_DESCRIPTOR && hdr->data_size > 8) { ++ CHECK(hid_parse_report, ithc->hid, hiddata + 8, hdr->data_size - 8); ++ WRITE_ONCE(ithc->hid_parse_done, true); ++ wake_up(&ithc->wait_hid_parse); ++ } else if (hdr->code == DMA_RX_CODE_INPUT_REPORT) { ++ CHECK(hid_input_report, ithc->hid, HID_INPUT_REPORT, hiddata, hdr->data_size, 1); ++ } else if (hdr->code == DMA_RX_CODE_FEATURE_REPORT) { ++ bool done = false; ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ if (ithc->hid_get_feature_buf) { ++ if (hdr->data_size < ithc->hid_get_feature_size) ithc->hid_get_feature_size = hdr->data_size; ++ memcpy(ithc->hid_get_feature_buf, hiddata, ithc->hid_get_feature_size); ++ ithc->hid_get_feature_buf = NULL; ++ done = true; ++ } ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ if (done) wake_up(&ithc->wait_hid_get_feature); ++ else CHECK(hid_input_report, ithc->hid, HID_FEATURE_REPORT, hiddata, hdr->data_size, 1); ++ } else { ++ pci_dbg(ithc->pci, "unhandled dma rx data! channel %u, buffer %u, size %u, code %u\n", channel, buf, len, hdr->code); ++ print_hex_dump_debug(DEVNAME " data: ", DUMP_PREFIX_OFFSET, 32, 1, hdr, min(len, 0x400u), 0); ++ } ++ return 0; ++} ++ ++static int ithc_dma_rx_unlocked(struct ithc *ithc, u8 channel) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ unsigned n = rx->num_received; ++ u8 head_wrap = readb(&ithc->regs->dma_rx[channel].head); ++ while (1) { ++ u8 tail = n % NUM_RX_BUF; ++ u8 tail_wrap = tail | ((n / NUM_RX_BUF) & 1 ? 0 : DMA_RX_WRAP_FLAG); ++ writeb(tail_wrap, &ithc->regs->dma_rx[channel].tail); ++ // ringbuffer is full if tail_wrap == head_wrap ++ // ringbuffer is empty if tail_wrap == head_wrap ^ WRAP_FLAG ++ if (tail_wrap == (head_wrap ^ DMA_RX_WRAP_FLAG)) return 0; ++ ++ // take the buffer that the device just filled ++ struct ithc_dma_data_buffer *b = &rx->bufs[n % NUM_RX_BUF]; ++ CHECK_RET(ithc_dma_data_buffer_get, ithc, &rx->prds, b, tail); ++ rx->num_received = ++n; ++ ++ // process data ++ CHECK(ithc_dma_rx_process_buf, ithc, b, channel, tail); ++ ++ // give the buffer back to the device ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &rx->prds, b, tail); ++ } ++} ++int ithc_dma_rx(struct ithc *ithc, u8 channel) { ++ struct ithc_dma_rx *rx = &ithc->dma_rx[channel]; ++ mutex_lock(&rx->mutex); ++ int ret = ithc_dma_rx_unlocked(ithc, channel); ++ mutex_unlock(&rx->mutex); ++ return ret; ++} ++ ++static int ithc_dma_tx_unlocked(struct ithc *ithc, u32 cmdcode, u32 datasize, void *data) { ++ pci_dbg(ithc->pci, "dma tx command %u, size %u\n", cmdcode, datasize); ++ struct ithc_dma_tx_header *hdr; ++ u8 padding = datasize & 3 ? 4 - (datasize & 3) : 0; ++ unsigned fullsize = sizeof *hdr + datasize + padding; ++ if (fullsize > ithc->dma_tx.max_size || fullsize > PAGE_SIZE) return -EINVAL; ++ CHECK_RET(ithc_dma_data_buffer_get, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ ++ ithc->dma_tx.buf.data_size = fullsize; ++ hdr = ithc->dma_tx.buf.addr; ++ hdr->code = cmdcode; ++ hdr->data_size = datasize; ++ u8 *dest = (void *)(hdr + 1); ++ memcpy(dest, data, datasize); ++ dest += datasize; ++ for (u8 p = 0; p < padding; p++) *dest++ = 0; ++ CHECK_RET(ithc_dma_data_buffer_put, ithc, &ithc->dma_tx.prds, &ithc->dma_tx.buf, 0); ++ ++ bitsb_set(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND); ++ CHECK_RET(waitb, ithc, &ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND, 0); ++ writel(DMA_TX_STATUS_DONE, &ithc->regs->dma_tx.status); ++ return 0; ++} ++int ithc_dma_tx(struct ithc *ithc, u32 cmdcode, u32 datasize, void *data) { ++ mutex_lock(&ithc->dma_tx.mutex); ++ int ret = ithc_dma_tx_unlocked(ithc, cmdcode, datasize, data); ++ mutex_unlock(&ithc->dma_tx.mutex); ++ return ret; ++} ++ +diff --git a/drivers/hid/ithc/ithc-dma.h b/drivers/hid/ithc/ithc-dma.h +new file mode 100644 +index 0000000000000..d9f2c19a13f3a +--- /dev/null ++++ b/drivers/hid/ithc/ithc-dma.h +@@ -0,0 +1,67 @@ ++#define PRD_SIZE_MASK 0xffffff ++#define PRD_FLAG_END 0x1000000 ++#define PRD_FLAG_SUCCESS 0x2000000 ++#define PRD_FLAG_ERROR 0x4000000 ++ ++struct ithc_phys_region_desc { ++ u64 addr; // physical addr/1024 ++ u32 size; // num bytes, PRD_FLAG_END marks last prd for data split over multiple prds ++ u32 unused; ++}; ++ ++#define DMA_RX_CODE_INPUT_REPORT 3 ++#define DMA_RX_CODE_FEATURE_REPORT 4 ++#define DMA_RX_CODE_REPORT_DESCRIPTOR 5 ++#define DMA_RX_CODE_RESET 7 ++ ++struct ithc_dma_rx_header { ++ u32 code; ++ u32 data_size; ++ u32 _unknown[14]; ++}; ++ ++#define DMA_TX_CODE_SET_FEATURE 3 ++#define DMA_TX_CODE_GET_FEATURE 4 ++#define DMA_TX_CODE_OUTPUT_REPORT 5 ++#define DMA_TX_CODE_GET_REPORT_DESCRIPTOR 7 ++ ++struct ithc_dma_tx_header { ++ u32 code; ++ u32 data_size; ++}; ++ ++struct ithc_dma_prd_buffer { ++ void *addr; ++ dma_addr_t dma_addr; ++ u32 size; ++ u32 num_pages; // per data buffer ++ enum dma_data_direction dir; ++}; ++ ++struct ithc_dma_data_buffer { ++ void *addr; ++ struct sg_table *sgt; ++ int active_idx; ++ u32 data_size; ++}; ++ ++struct ithc_dma_tx { ++ struct mutex mutex; ++ u32 max_size; ++ struct ithc_dma_prd_buffer prds; ++ struct ithc_dma_data_buffer buf; ++}; ++ ++struct ithc_dma_rx { ++ struct mutex mutex; ++ u32 num_received; ++ struct ithc_dma_prd_buffer prds; ++ struct ithc_dma_data_buffer bufs[NUM_RX_BUF]; ++}; ++ ++int ithc_dma_rx_init(struct ithc *ithc, u8 channel, const char *devname); ++void ithc_dma_rx_enable(struct ithc *ithc, u8 channel); ++int ithc_dma_tx_init(struct ithc *ithc); ++int ithc_dma_rx(struct ithc *ithc, u8 channel); ++int ithc_dma_tx(struct ithc *ithc, u32 cmdcode, u32 datasize, void *cmddata); ++ +diff --git a/drivers/hid/ithc/ithc-main.c b/drivers/hid/ithc/ithc-main.c +new file mode 100644 +index 0000000000000..09512b9cb4d31 +--- /dev/null ++++ b/drivers/hid/ithc/ithc-main.c +@@ -0,0 +1,534 @@ ++#include "ithc.h" ++ ++MODULE_DESCRIPTION("Intel Touch Host Controller driver"); ++MODULE_LICENSE("Dual BSD/GPL"); ++ ++// Lakefield ++#define PCI_DEVICE_ID_INTEL_THC_LKF_PORT1 0x98d0 ++#define PCI_DEVICE_ID_INTEL_THC_LKF_PORT2 0x98d1 ++// Tiger Lake ++#define PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT1 0xa0d0 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT2 0xa0d1 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT1 0x43d0 ++#define PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT2 0x43d1 ++// Alder Lake ++#define PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT1 0x7ad8 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT2 0x7ad9 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT1 0x51d0 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT2 0x51d1 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT1 0x54d0 ++#define PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT2 0x54d1 ++// Raptor Lake ++#define PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT1 0x7a58 ++#define PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT2 0x7a59 ++// Meteor Lake ++#define PCI_DEVICE_ID_INTEL_THC_MTL_PORT1 0x7e48 ++#define PCI_DEVICE_ID_INTEL_THC_MTL_PORT2 0x7e4a ++ ++static const struct pci_device_id ithc_pci_tbl[] = { ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_LKF_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_LKF_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_LP_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_TGL_H_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_S_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_P_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_ADL_M_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_RPL_S_PORT2) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_MTL_PORT1) }, ++ { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_THC_MTL_PORT2) }, ++ {} ++}; ++MODULE_DEVICE_TABLE(pci, ithc_pci_tbl); ++ ++// Module parameters ++ ++static bool ithc_use_polling = false; ++module_param_named(poll, ithc_use_polling, bool, 0); ++MODULE_PARM_DESC(poll, "Use polling instead of interrupts"); ++ ++static bool ithc_use_rx0 = false; ++module_param_named(rx0, ithc_use_rx0, bool, 0); ++MODULE_PARM_DESC(rx0, "Use DMA RX channel 0"); ++ ++static bool ithc_use_rx1 = true; ++module_param_named(rx1, ithc_use_rx1, bool, 0); ++MODULE_PARM_DESC(rx1, "Use DMA RX channel 1"); ++ ++static bool ithc_log_regs_enabled = false; ++module_param_named(logregs, ithc_log_regs_enabled, bool, 0); ++MODULE_PARM_DESC(logregs, "Log changes in register values (for debugging)"); ++ ++// Sysfs attributes ++ ++static bool ithc_is_config_valid(struct ithc *ithc) { ++ return ithc->config.device_id == DEVCFG_DEVICE_ID_TIC; ++} ++ ++static ssize_t vendor_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "0x%04x", ithc->config.vendor_id); ++} ++static DEVICE_ATTR_RO(vendor); ++static ssize_t product_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "0x%04x", ithc->config.product_id); ++} ++static DEVICE_ATTR_RO(product); ++static ssize_t revision_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ return sprintf(buf, "%u", ithc->config.revision); ++} ++static DEVICE_ATTR_RO(revision); ++static ssize_t fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { ++ struct ithc *ithc = dev_get_drvdata(dev); ++ if (!ithc || !ithc_is_config_valid(ithc)) return -ENODEV; ++ u32 v = ithc->config.fw_version; ++ return sprintf(buf, "%i.%i.%i.%i", v >> 24, v >> 16 & 0xff, v >> 8 & 0xff, v & 0xff); ++} ++static DEVICE_ATTR_RO(fw_version); ++ ++static const struct attribute_group *ithc_attribute_groups[] = { ++ &(const struct attribute_group){ ++ .name = DEVNAME, ++ .attrs = (struct attribute *[]){ ++ &dev_attr_vendor.attr, ++ &dev_attr_product.attr, ++ &dev_attr_revision.attr, ++ &dev_attr_fw_version.attr, ++ NULL ++ }, ++ }, ++ NULL ++}; ++ ++// HID setup ++ ++static int ithc_hid_start(struct hid_device *hdev) { return 0; } ++static void ithc_hid_stop(struct hid_device *hdev) { } ++static int ithc_hid_open(struct hid_device *hdev) { return 0; } ++static void ithc_hid_close(struct hid_device *hdev) { } ++ ++static int ithc_hid_parse(struct hid_device *hdev) { ++ struct ithc *ithc = hdev->driver_data; ++ u64 val = 0; ++ WRITE_ONCE(ithc->hid_parse_done, false); ++ CHECK_RET(ithc_dma_tx, ithc, DMA_TX_CODE_GET_REPORT_DESCRIPTOR, sizeof val, &val); ++ if (!wait_event_timeout(ithc->wait_hid_parse, READ_ONCE(ithc->hid_parse_done), msecs_to_jiffies(1000))) return -ETIMEDOUT; ++ return 0; ++} ++ ++static int ithc_hid_raw_request(struct hid_device *hdev, unsigned char reportnum, __u8 *buf, size_t len, unsigned char rtype, int reqtype) { ++ struct ithc *ithc = hdev->driver_data; ++ if (!buf || !len) return -EINVAL; ++ u32 code; ++ if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT) code = DMA_TX_CODE_OUTPUT_REPORT; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT) code = DMA_TX_CODE_SET_FEATURE; ++ else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT) code = DMA_TX_CODE_GET_FEATURE; ++ else { ++ pci_err(ithc->pci, "unhandled hid request %i %i for report id %i\n", rtype, reqtype, reportnum); ++ return -EINVAL; ++ } ++ buf[0] = reportnum; ++ if (reqtype == HID_REQ_GET_REPORT) { ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ ithc->hid_get_feature_buf = buf; ++ ithc->hid_get_feature_size = len; ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ int r = CHECK(ithc_dma_tx, ithc, code, 1, buf); ++ if (!r) { ++ r = wait_event_interruptible_timeout(ithc->wait_hid_get_feature, !ithc->hid_get_feature_buf, msecs_to_jiffies(1000)); ++ if (!r) r = -ETIMEDOUT; ++ else if (r < 0) r = -EINTR; ++ else r = 0; ++ } ++ mutex_lock(&ithc->hid_get_feature_mutex); ++ ithc->hid_get_feature_buf = NULL; ++ if (!r) r = ithc->hid_get_feature_size; ++ mutex_unlock(&ithc->hid_get_feature_mutex); ++ return r; ++ } ++ CHECK_RET(ithc_dma_tx, ithc, code, len, buf); ++ return 0; ++} ++ ++static struct hid_ll_driver ithc_ll_driver = { ++ .start = ithc_hid_start, ++ .stop = ithc_hid_stop, ++ .open = ithc_hid_open, ++ .close = ithc_hid_close, ++ .parse = ithc_hid_parse, ++ .raw_request = ithc_hid_raw_request, ++}; ++ ++static void ithc_hid_devres_release(struct device *dev, void *res) { ++ struct hid_device **hidm = res; ++ if (*hidm) hid_destroy_device(*hidm); ++} ++ ++static int ithc_hid_init(struct ithc *ithc) { ++ struct hid_device **hidm = devres_alloc(ithc_hid_devres_release, sizeof *hidm, GFP_KERNEL); ++ if (!hidm) return -ENOMEM; ++ devres_add(&ithc->pci->dev, hidm); ++ struct hid_device *hid = hid_allocate_device(); ++ if (IS_ERR(hid)) return PTR_ERR(hid); ++ *hidm = hid; ++ ++ strscpy(hid->name, DEVFULLNAME, sizeof(hid->name)); ++ strscpy(hid->phys, ithc->phys, sizeof(hid->phys)); ++ hid->ll_driver = &ithc_ll_driver; ++ hid->bus = BUS_PCI; ++ hid->vendor = ithc->config.vendor_id; ++ hid->product = ithc->config.product_id; ++ hid->version = 0x100; ++ hid->dev.parent = &ithc->pci->dev; ++ hid->driver_data = ithc; ++ ++ ithc->hid = hid; ++ return 0; ++} ++ ++// Interrupts/polling ++ ++static void ithc_activity_timer_callback(struct timer_list *t) { ++ struct ithc *ithc = container_of(t, struct ithc, activity_timer); ++ cpu_latency_qos_update_request(&ithc->activity_qos, PM_QOS_DEFAULT_VALUE); ++} ++ ++void ithc_set_active(struct ithc *ithc) { ++ // When CPU usage is very low, the CPU can enter various low power states (C2-C10). ++ // This disrupts DMA, causing truncated DMA messages. ERROR_FLAG_DMA_UNKNOWN_12 will be set when this happens. ++ // The amount of truncated messages can become very high, resulting in user-visible effects (laggy/stuttering cursor). ++ // To avoid this, we use a CPU latency QoS request to prevent the CPU from entering low power states during touch interactions. ++ cpu_latency_qos_update_request(&ithc->activity_qos, 0); ++ mod_timer(&ithc->activity_timer, jiffies + msecs_to_jiffies(1000)); ++} ++ ++static int ithc_set_device_enabled(struct ithc *ithc, bool enable) { ++ u32 x = ithc->config.touch_cfg = (ithc->config.touch_cfg & ~(u32)DEVCFG_TOUCH_MASK) | DEVCFG_TOUCH_UNKNOWN_2 ++ | (enable ? DEVCFG_TOUCH_ENABLE | DEVCFG_TOUCH_UNKNOWN_3 | DEVCFG_TOUCH_UNKNOWN_4 : 0); ++ return ithc_spi_command(ithc, SPI_CMD_CODE_WRITE, offsetof(struct ithc_device_config, touch_cfg), sizeof x, &x); ++} ++ ++static void ithc_disable_interrupts(struct ithc *ithc) { ++ writel(0, &ithc->regs->error_control); ++ bitsb(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_IRQ, 0); ++ bitsb(&ithc->regs->dma_rx[0].control, DMA_RX_CONTROL_IRQ_UNKNOWN_1 | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_UNKNOWN_4 | DMA_RX_CONTROL_IRQ_DATA, 0); ++ bitsb(&ithc->regs->dma_rx[1].control, DMA_RX_CONTROL_IRQ_UNKNOWN_1 | DMA_RX_CONTROL_IRQ_ERROR | DMA_RX_CONTROL_IRQ_UNKNOWN_4 | DMA_RX_CONTROL_IRQ_DATA, 0); ++ bitsb(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_IRQ, 0); ++} ++ ++static void ithc_clear_dma_rx_interrupts(struct ithc *ithc, unsigned channel) { ++ writel(DMA_RX_STATUS_ERROR | DMA_RX_STATUS_UNKNOWN_4 | DMA_RX_STATUS_HAVE_DATA, &ithc->regs->dma_rx[channel].status); ++} ++ ++static void ithc_clear_interrupts(struct ithc *ithc) { ++ writel(0xffffffff, &ithc->regs->error_flags); ++ writel(ERROR_STATUS_DMA | ERROR_STATUS_SPI, &ithc->regs->error_status); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ ithc_clear_dma_rx_interrupts(ithc, 0); ++ ithc_clear_dma_rx_interrupts(ithc, 1); ++ writel(DMA_TX_STATUS_DONE | DMA_TX_STATUS_ERROR | DMA_TX_STATUS_UNKNOWN_2, &ithc->regs->dma_tx.status); ++} ++ ++static void ithc_process(struct ithc *ithc) { ++ ithc_log_regs(ithc); ++ ++ // read and clear error bits ++ u32 err = readl(&ithc->regs->error_flags); ++ if (err) { ++ if (err & ~ERROR_FLAG_DMA_UNKNOWN_12) pci_err(ithc->pci, "error flags: 0x%08x\n", err); ++ writel(err, &ithc->regs->error_flags); ++ } ++ ++ // process DMA rx ++ if (ithc_use_rx0) { ++ ithc_clear_dma_rx_interrupts(ithc, 0); ++ ithc_dma_rx(ithc, 0); ++ } ++ if (ithc_use_rx1) { ++ ithc_clear_dma_rx_interrupts(ithc, 1); ++ ithc_dma_rx(ithc, 1); ++ } ++ ++ ithc_log_regs(ithc); ++} ++ ++static irqreturn_t ithc_interrupt_thread(int irq, void *arg) { ++ struct ithc *ithc = arg; ++ pci_dbg(ithc->pci, "IRQ! err=%08x/%08x/%08x, cmd=%02x/%08x, rx0=%02x/%08x, rx1=%02x/%08x, tx=%02x/%08x\n", ++ readl(&ithc->regs->error_control), readl(&ithc->regs->error_status), readl(&ithc->regs->error_flags), ++ readb(&ithc->regs->spi_cmd.control), readl(&ithc->regs->spi_cmd.status), ++ readb(&ithc->regs->dma_rx[0].control), readl(&ithc->regs->dma_rx[0].status), ++ readb(&ithc->regs->dma_rx[1].control), readl(&ithc->regs->dma_rx[1].status), ++ readb(&ithc->regs->dma_tx.control), readl(&ithc->regs->dma_tx.status)); ++ ithc_process(ithc); ++ return IRQ_HANDLED; ++} ++ ++static int ithc_poll_thread(void *arg) { ++ struct ithc *ithc = arg; ++ unsigned sleep = 100; ++ while (!kthread_should_stop()) { ++ u32 n = ithc->dma_rx[1].num_received; ++ ithc_process(ithc); ++ if (n != ithc->dma_rx[1].num_received) sleep = 20; ++ else sleep = min(200u, sleep + (sleep >> 4) + 1); ++ msleep_interruptible(sleep); ++ } ++ return 0; ++} ++ ++// Device initialization and shutdown ++ ++static void ithc_disable(struct ithc *ithc) { ++ bitsl_set(&ithc->regs->control_bits, CONTROL_QUIESCE); ++ CHECK(waitl, ithc, &ithc->regs->control_bits, CONTROL_IS_QUIESCED, CONTROL_IS_QUIESCED); ++ bitsl(&ithc->regs->control_bits, CONTROL_NRESET, 0); ++ bitsb(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_SEND, 0); ++ bitsb(&ithc->regs->dma_tx.control, DMA_TX_CONTROL_SEND, 0); ++ bitsb(&ithc->regs->dma_rx[0].control, DMA_RX_CONTROL_ENABLE, 0); ++ bitsb(&ithc->regs->dma_rx[1].control, DMA_RX_CONTROL_ENABLE, 0); ++ ithc_disable_interrupts(ithc); ++ ithc_clear_interrupts(ithc); ++} ++ ++static int ithc_init_device(struct ithc *ithc) { ++ ithc_log_regs(ithc); ++ bool was_enabled = (readl(&ithc->regs->control_bits) & CONTROL_NRESET) != 0; ++ ithc_disable(ithc); ++ CHECK_RET(waitl, ithc, &ithc->regs->control_bits, CONTROL_READY, CONTROL_READY); ++ ithc_set_spi_config(ithc, 10, 0); ++ bitsl_set(&ithc->regs->dma_rx[0].unknown_init_bits, 0x80000000); // seems to help with reading config ++ ++ if (was_enabled) if (msleep_interruptible(100)) return -EINTR; ++ bitsl(&ithc->regs->control_bits, CONTROL_QUIESCE, 0); ++ CHECK_RET(waitl, ithc, &ithc->regs->control_bits, CONTROL_IS_QUIESCED, 0); ++ for (int retries = 0; ; retries++) { ++ ithc_log_regs(ithc); ++ bitsl_set(&ithc->regs->control_bits, CONTROL_NRESET); ++ if (!waitl(ithc, &ithc->regs->state, 0xf, 2)) break; ++ if (retries > 5) { ++ pci_err(ithc->pci, "too many retries, failed to reset device\n"); ++ return -ETIMEDOUT; ++ } ++ pci_err(ithc->pci, "invalid state, retrying reset\n"); ++ bitsl(&ithc->regs->control_bits, CONTROL_NRESET, 0); ++ if (msleep_interruptible(1000)) return -EINTR; ++ } ++ ithc_log_regs(ithc); ++ ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[0].status, DMA_RX_STATUS_UNKNOWN_4, DMA_RX_STATUS_UNKNOWN_4); ++ ++ // read config ++ for (int retries = 0; ; retries++) { ++ ithc_log_regs(ithc); ++ memset(&ithc->config, 0, sizeof ithc->config); ++ CHECK_RET(ithc_spi_command, ithc, SPI_CMD_CODE_READ, 0, sizeof ithc->config, &ithc->config); ++ u32 *p = (void *)&ithc->config; ++ pci_info(ithc->pci, "config: %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x\n", ++ p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); ++ if (ithc_is_config_valid(ithc)) break; ++ if (retries > 10) { ++ pci_err(ithc->pci, "failed to read config, unknown device ID 0x%08x\n", ithc->config.device_id); ++ return -EIO; ++ } ++ pci_err(ithc->pci, "failed to read config, retrying\n"); ++ if (msleep_interruptible(100)) return -EINTR; ++ } ++ ithc_log_regs(ithc); ++ ++ CHECK_RET(ithc_set_spi_config, ithc, DEVCFG_SPI_MAX_FREQ(ithc->config.spi_config), DEVCFG_SPI_MODE(ithc->config.spi_config)); ++ CHECK_RET(ithc_set_device_enabled, ithc, true); ++ ithc_log_regs(ithc); ++ return 0; ++} ++ ++int ithc_reset(struct ithc *ithc) { ++ // FIXME This should probably do devres_release_group()+ithc_start(). But because this is called during DMA ++ // processing, that would have to be done asynchronously (schedule_work()?). And with extra locking? ++ pci_err(ithc->pci, "reset\n"); ++ CHECK(ithc_init_device, ithc); ++ if (ithc_use_rx0) ithc_dma_rx_enable(ithc, 0); ++ if (ithc_use_rx1) ithc_dma_rx_enable(ithc, 1); ++ ithc_log_regs(ithc); ++ pci_dbg(ithc->pci, "reset completed\n"); ++ return 0; ++} ++ ++static void ithc_stop(void *res) { ++ struct ithc *ithc = res; ++ pci_dbg(ithc->pci, "stopping\n"); ++ ithc_log_regs(ithc); ++ if (ithc->poll_thread) CHECK(kthread_stop, ithc->poll_thread); ++ if (ithc->irq >= 0) disable_irq(ithc->irq); ++ CHECK(ithc_set_device_enabled, ithc, false); ++ ithc_disable(ithc); ++ del_timer_sync(&ithc->activity_timer); ++ cpu_latency_qos_remove_request(&ithc->activity_qos); ++ // clear dma config ++ for(unsigned i = 0; i < 2; i++) { ++ CHECK(waitl, ithc, &ithc->regs->dma_rx[i].status, DMA_RX_STATUS_ENABLED, 0); ++ lo_hi_writeq(0, &ithc->regs->dma_rx[i].addr); ++ writeb(0, &ithc->regs->dma_rx[i].num_bufs); ++ writeb(0, &ithc->regs->dma_rx[i].num_prds); ++ } ++ lo_hi_writeq(0, &ithc->regs->dma_tx.addr); ++ writeb(0, &ithc->regs->dma_tx.num_prds); ++ ithc_log_regs(ithc); ++ pci_dbg(ithc->pci, "stopped\n"); ++} ++ ++static void ithc_clear_drvdata(void *res) { ++ struct pci_dev *pci = res; ++ pci_set_drvdata(pci, NULL); ++} ++ ++static int ithc_start(struct pci_dev *pci) { ++ pci_dbg(pci, "starting\n"); ++ if (pci_get_drvdata(pci)) { ++ pci_err(pci, "device already initialized\n"); ++ return -EINVAL; ++ } ++ if (!devres_open_group(&pci->dev, ithc_start, GFP_KERNEL)) return -ENOMEM; ++ ++ struct ithc *ithc = devm_kzalloc(&pci->dev, sizeof *ithc, GFP_KERNEL); ++ if (!ithc) return -ENOMEM; ++ ithc->irq = -1; ++ ithc->pci = pci; ++ snprintf(ithc->phys, sizeof ithc->phys, "pci-%s/" DEVNAME, pci_name(pci)); ++ init_waitqueue_head(&ithc->wait_hid_parse); ++ init_waitqueue_head(&ithc->wait_hid_get_feature); ++ mutex_init(&ithc->hid_get_feature_mutex); ++ pci_set_drvdata(pci, ithc); ++ CHECK_RET(devm_add_action_or_reset, &pci->dev, ithc_clear_drvdata, pci); ++ if (ithc_log_regs_enabled) ithc->prev_regs = devm_kzalloc(&pci->dev, sizeof *ithc->prev_regs, GFP_KERNEL); ++ ++ CHECK_RET(pcim_enable_device, pci); ++ pci_set_master(pci); ++ CHECK_RET(pcim_iomap_regions, pci, BIT(0), DEVNAME " regs"); ++ CHECK_RET(dma_set_mask_and_coherent, &pci->dev, DMA_BIT_MASK(64)); ++ CHECK_RET(pci_set_power_state, pci, PCI_D0); ++ ithc->regs = pcim_iomap_table(pci)[0]; ++ ++ if (!ithc_use_polling) { ++ CHECK_RET(pci_alloc_irq_vectors, pci, 1, 1, PCI_IRQ_MSI | PCI_IRQ_MSIX); ++ ithc->irq = CHECK(pci_irq_vector, pci, 0); ++ if (ithc->irq < 0) return ithc->irq; ++ } ++ ++ CHECK_RET(ithc_init_device, ithc); ++ CHECK(devm_device_add_groups, &pci->dev, ithc_attribute_groups); ++ if (ithc_use_rx0) CHECK_RET(ithc_dma_rx_init, ithc, 0, ithc_use_rx1 ? DEVNAME "0" : DEVNAME); ++ if (ithc_use_rx1) CHECK_RET(ithc_dma_rx_init, ithc, 1, ithc_use_rx0 ? DEVNAME "1" : DEVNAME); ++ CHECK_RET(ithc_dma_tx_init, ithc); ++ ++ CHECK_RET(ithc_hid_init, ithc); ++ ++ cpu_latency_qos_add_request(&ithc->activity_qos, PM_QOS_DEFAULT_VALUE); ++ timer_setup(&ithc->activity_timer, ithc_activity_timer_callback, 0); ++ ++ // add ithc_stop callback AFTER setting up DMA buffers, so that polling/irqs/DMA are disabled BEFORE the buffers are freed ++ CHECK_RET(devm_add_action_or_reset, &pci->dev, ithc_stop, ithc); ++ ++ if (ithc_use_polling) { ++ pci_info(pci, "using polling instead of irq\n"); ++ // use a thread instead of simple timer because we want to be able to sleep ++ ithc->poll_thread = kthread_run(ithc_poll_thread, ithc, DEVNAME "poll"); ++ if (IS_ERR(ithc->poll_thread)) { ++ int err = PTR_ERR(ithc->poll_thread); ++ ithc->poll_thread = NULL; ++ return err; ++ } ++ } else { ++ CHECK_RET(devm_request_threaded_irq, &pci->dev, ithc->irq, NULL, ithc_interrupt_thread, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, DEVNAME, ithc); ++ } ++ ++ if (ithc_use_rx0) ithc_dma_rx_enable(ithc, 0); ++ if (ithc_use_rx1) ithc_dma_rx_enable(ithc, 1); ++ ++ // hid_add_device can only be called after irq/polling is started and DMA is enabled, because it calls ithc_hid_parse which reads the report descriptor via DMA ++ CHECK_RET(hid_add_device, ithc->hid); ++ ++ CHECK(ithc_debug_init, ithc); ++ ++ pci_dbg(pci, "started\n"); ++ return 0; ++} ++ ++static int ithc_probe(struct pci_dev *pci, const struct pci_device_id *id) { ++ pci_dbg(pci, "device probe\n"); ++ return ithc_start(pci); ++} ++ ++static void ithc_remove(struct pci_dev *pci) { ++ pci_dbg(pci, "device remove\n"); ++ // all cleanup is handled by devres ++} ++ ++static int ithc_suspend(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm suspend\n"); ++ devres_release_group(dev, ithc_start); ++ return 0; ++} ++ ++static int ithc_resume(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm resume\n"); ++ return ithc_start(pci); ++} ++ ++static int ithc_freeze(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm freeze\n"); ++ devres_release_group(dev, ithc_start); ++ return 0; ++} ++ ++static int ithc_thaw(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm thaw\n"); ++ return ithc_start(pci); ++} ++ ++static int ithc_restore(struct device *dev) { ++ struct pci_dev *pci = to_pci_dev(dev); ++ pci_dbg(pci, "pm restore\n"); ++ return ithc_start(pci); ++} ++ ++static struct pci_driver ithc_driver = { ++ .name = DEVNAME, ++ .id_table = ithc_pci_tbl, ++ .probe = ithc_probe, ++ .remove = ithc_remove, ++ .driver.pm = &(const struct dev_pm_ops) { ++ .suspend = ithc_suspend, ++ .resume = ithc_resume, ++ .freeze = ithc_freeze, ++ .thaw = ithc_thaw, ++ .restore = ithc_restore, ++ }, ++ //.dev_groups = ithc_attribute_groups, // could use this (since 5.14), however the attributes won't have valid values until config has been read anyway ++}; ++ ++static int __init ithc_init(void) { ++ return pci_register_driver(&ithc_driver); ++} ++ ++static void __exit ithc_exit(void) { ++ pci_unregister_driver(&ithc_driver); ++} ++ ++module_init(ithc_init); ++module_exit(ithc_exit); ++ +diff --git a/drivers/hid/ithc/ithc-regs.c b/drivers/hid/ithc/ithc-regs.c +new file mode 100644 +index 0000000000000..85d567b05761f +--- /dev/null ++++ b/drivers/hid/ithc/ithc-regs.c +@@ -0,0 +1,64 @@ ++#include "ithc.h" ++ ++#define reg_num(r) (0x1fff & (u16)(__force u64)(r)) ++ ++void bitsl(__iomem u32 *reg, u32 mask, u32 val) { ++ if (val & ~mask) pr_err("register 0x%x: invalid value 0x%x for bitmask 0x%x\n", reg_num(reg), val, mask); ++ writel((readl(reg) & ~mask) | (val & mask), reg); ++} ++ ++void bitsb(__iomem u8 *reg, u8 mask, u8 val) { ++ if (val & ~mask) pr_err("register 0x%x: invalid value 0x%x for bitmask 0x%x\n", reg_num(reg), val, mask); ++ writeb((readb(reg) & ~mask) | (val & mask), reg); ++} ++ ++int waitl(struct ithc *ithc, __iomem u32 *reg, u32 mask, u32 val) { ++ pci_dbg(ithc->pci, "waiting for reg 0x%04x mask 0x%08x val 0x%08x\n", reg_num(reg), mask, val); ++ u32 x; ++ if (readl_poll_timeout(reg, x, (x & mask) == val, 200, 1000*1000)) { ++ pci_err(ithc->pci, "timed out waiting for reg 0x%04x mask 0x%08x val 0x%08x\n", reg_num(reg), mask, val); ++ return -ETIMEDOUT; ++ } ++ pci_dbg(ithc->pci, "done waiting\n"); ++ return 0; ++} ++ ++int waitb(struct ithc *ithc, __iomem u8 *reg, u8 mask, u8 val) { ++ pci_dbg(ithc->pci, "waiting for reg 0x%04x mask 0x%02x val 0x%02x\n", reg_num(reg), mask, val); ++ u8 x; ++ if (readb_poll_timeout(reg, x, (x & mask) == val, 200, 1000*1000)) { ++ pci_err(ithc->pci, "timed out waiting for reg 0x%04x mask 0x%02x val 0x%02x\n", reg_num(reg), mask, val); ++ return -ETIMEDOUT; ++ } ++ pci_dbg(ithc->pci, "done waiting\n"); ++ return 0; ++} ++ ++int ithc_set_spi_config(struct ithc *ithc, u8 speed, u8 mode) { ++ pci_dbg(ithc->pci, "setting SPI speed to %i, mode %i\n", speed, mode); ++ if (mode == 3) mode = 2; ++ bitsl(&ithc->regs->spi_config, ++ SPI_CONFIG_MODE(0xff) | SPI_CONFIG_SPEED(0xff) | SPI_CONFIG_UNKNOWN_18(0xff) | SPI_CONFIG_SPEED2(0xff), ++ SPI_CONFIG_MODE(mode) | SPI_CONFIG_SPEED(speed) | SPI_CONFIG_UNKNOWN_18(0) | SPI_CONFIG_SPEED2(speed)); ++ return 0; ++} ++ ++int ithc_spi_command(struct ithc *ithc, u8 command, u32 offset, u32 size, void *data) { ++ pci_dbg(ithc->pci, "SPI command %u, size %u, offset %u\n", command, size, offset); ++ if (size > sizeof ithc->regs->spi_cmd.data) return -EINVAL; ++ CHECK_RET(waitl, ithc, &ithc->regs->spi_cmd.status, SPI_CMD_STATUS_BUSY, 0); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ writeb(command, &ithc->regs->spi_cmd.code); ++ writew(size, &ithc->regs->spi_cmd.size); ++ writel(offset, &ithc->regs->spi_cmd.offset); ++ u32 *p = data, n = (size + 3) / 4; ++ for (u32 i = 0; i < n; i++) writel(p[i], &ithc->regs->spi_cmd.data[i]); ++ bitsb_set(&ithc->regs->spi_cmd.control, SPI_CMD_CONTROL_SEND); ++ CHECK_RET(waitl, ithc, &ithc->regs->spi_cmd.status, SPI_CMD_STATUS_BUSY, 0); ++ if ((readl(&ithc->regs->spi_cmd.status) & (SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR)) != SPI_CMD_STATUS_DONE) return -EIO; ++ if (readw(&ithc->regs->spi_cmd.size) != size) return -EMSGSIZE; ++ for (u32 i = 0; i < n; i++) p[i] = readl(&ithc->regs->spi_cmd.data[i]); ++ writel(SPI_CMD_STATUS_DONE | SPI_CMD_STATUS_ERROR, &ithc->regs->spi_cmd.status); ++ return 0; ++} ++ +diff --git a/drivers/hid/ithc/ithc-regs.h b/drivers/hid/ithc/ithc-regs.h +new file mode 100644 +index 0000000000000..1a96092ed7eed +--- /dev/null ++++ b/drivers/hid/ithc/ithc-regs.h +@@ -0,0 +1,186 @@ ++#define CONTROL_QUIESCE BIT(1) ++#define CONTROL_IS_QUIESCED BIT(2) ++#define CONTROL_NRESET BIT(3) ++#define CONTROL_READY BIT(29) ++ ++#define SPI_CONFIG_MODE(x) (((x) & 3) << 2) ++#define SPI_CONFIG_SPEED(x) (((x) & 7) << 4) ++#define SPI_CONFIG_UNKNOWN_18(x) (((x) & 3) << 18) ++#define SPI_CONFIG_SPEED2(x) (((x) & 0xf) << 20) // high bit = high speed mode? ++ ++#define ERROR_CONTROL_UNKNOWN_0 BIT(0) ++#define ERROR_CONTROL_DISABLE_DMA BIT(1) // clears DMA_RX_CONTROL_ENABLE when a DMA error occurs ++#define ERROR_CONTROL_UNKNOWN_2 BIT(2) ++#define ERROR_CONTROL_UNKNOWN_3 BIT(3) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_9 BIT(9) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_10 BIT(10) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_12 BIT(12) ++#define ERROR_CONTROL_IRQ_DMA_UNKNOWN_13 BIT(13) ++#define ERROR_CONTROL_UNKNOWN_16(x) (((x) & 0xff) << 16) // spi error code irq? ++#define ERROR_CONTROL_SET_DMA_STATUS BIT(29) // sets DMA_RX_STATUS_ERROR when a DMA error occurs ++ ++#define ERROR_STATUS_DMA BIT(28) ++#define ERROR_STATUS_SPI BIT(30) ++ ++#define ERROR_FLAG_DMA_UNKNOWN_9 BIT(9) ++#define ERROR_FLAG_DMA_UNKNOWN_10 BIT(10) ++#define ERROR_FLAG_DMA_UNKNOWN_12 BIT(12) // set when we receive a truncated DMA message ++#define ERROR_FLAG_DMA_UNKNOWN_13 BIT(13) ++#define ERROR_FLAG_SPI_BUS_TURNAROUND BIT(16) ++#define ERROR_FLAG_SPI_RESPONSE_TIMEOUT BIT(17) ++#define ERROR_FLAG_SPI_INTRA_PACKET_TIMEOUT BIT(18) ++#define ERROR_FLAG_SPI_INVALID_RESPONSE BIT(19) ++#define ERROR_FLAG_SPI_HS_RX_TIMEOUT BIT(20) ++#define ERROR_FLAG_SPI_TOUCH_IC_INIT BIT(21) ++ ++#define SPI_CMD_CONTROL_SEND BIT(0) // cleared by device when sending is complete ++#define SPI_CMD_CONTROL_IRQ BIT(1) ++ ++#define SPI_CMD_CODE_READ 4 ++#define SPI_CMD_CODE_WRITE 6 ++ ++#define SPI_CMD_STATUS_DONE BIT(0) ++#define SPI_CMD_STATUS_ERROR BIT(1) ++#define SPI_CMD_STATUS_BUSY BIT(3) ++ ++#define DMA_TX_CONTROL_SEND BIT(0) // cleared by device when sending is complete ++#define DMA_TX_CONTROL_IRQ BIT(3) ++ ++#define DMA_TX_STATUS_DONE BIT(0) ++#define DMA_TX_STATUS_ERROR BIT(1) ++#define DMA_TX_STATUS_UNKNOWN_2 BIT(2) ++#define DMA_TX_STATUS_UNKNOWN_3 BIT(3) // busy? ++ ++#define DMA_RX_CONTROL_ENABLE BIT(0) ++#define DMA_RX_CONTROL_IRQ_UNKNOWN_1 BIT(1) // rx1 only? ++#define DMA_RX_CONTROL_IRQ_ERROR BIT(3) // rx1 only? ++#define DMA_RX_CONTROL_IRQ_UNKNOWN_4 BIT(4) // rx0 only? ++#define DMA_RX_CONTROL_IRQ_DATA BIT(5) ++ ++#define DMA_RX_CONTROL2_UNKNOWN_5 BIT(5) // rx0 only? ++#define DMA_RX_CONTROL2_RESET BIT(7) // resets ringbuffer indices ++ ++#define DMA_RX_WRAP_FLAG BIT(7) ++ ++#define DMA_RX_STATUS_ERROR BIT(3) ++#define DMA_RX_STATUS_UNKNOWN_4 BIT(4) // set in rx0 after using CONTROL_NRESET when it becomes possible to read config (can take >100ms) ++#define DMA_RX_STATUS_HAVE_DATA BIT(5) ++#define DMA_RX_STATUS_ENABLED BIT(8) ++ ++#define COUNTER_RESET BIT(31) ++ ++struct ithc_registers { ++ /* 0000 */ u32 _unknown_0000[1024]; ++ /* 1000 */ u32 _unknown_1000; ++ /* 1004 */ u32 _unknown_1004; ++ /* 1008 */ u32 control_bits; ++ /* 100c */ u32 _unknown_100c; ++ /* 1010 */ u32 spi_config; ++ /* 1014 */ u32 _unknown_1014[3]; ++ /* 1020 */ u32 error_control; ++ /* 1024 */ u32 error_status; // write to clear ++ /* 1028 */ u32 error_flags; // write to clear ++ /* 102c */ u32 _unknown_102c[5]; ++ struct { ++ /* 1040 */ u8 control; ++ /* 1041 */ u8 code; ++ /* 1042 */ u16 size; ++ /* 1044 */ u32 status; // write to clear ++ /* 1048 */ u32 offset; ++ /* 104c */ u32 data[16]; ++ /* 108c */ u32 _unknown_108c; ++ } spi_cmd; ++ struct { ++ /* 1090 */ u64 addr; // cannot be written with writeq(), must use lo_hi_writeq() ++ /* 1098 */ u8 control; ++ /* 1099 */ u8 _unknown_1099; ++ /* 109a */ u8 _unknown_109a; ++ /* 109b */ u8 num_prds; ++ /* 109c */ u32 status; // write to clear ++ } dma_tx; ++ /* 10a0 */ u32 _unknown_10a0[7]; ++ /* 10bc */ u32 state; // is 0xe0000402 (dev config val 0) after CONTROL_NRESET, 0xe0000461 after first touch, 0xe0000401 after DMA_RX_CODE_RESET ++ /* 10c0 */ u32 _unknown_10c0[8]; ++ /* 10e0 */ u32 _unknown_10e0_counters[3]; ++ /* 10ec */ u32 _unknown_10ec[5]; ++ struct { ++ /* 1100/1200 */ u64 addr; // cannot be written with writeq(), must use lo_hi_writeq() ++ /* 1108/1208 */ u8 num_bufs; ++ /* 1109/1209 */ u8 num_prds; ++ /* 110a/120a */ u16 _unknown_110a; ++ /* 110c/120c */ u8 control; ++ /* 110d/120d */ u8 head; ++ /* 110e/120e */ u8 tail; ++ /* 110f/120f */ u8 control2; ++ /* 1110/1210 */ u32 status; // write to clear ++ /* 1114/1214 */ u32 _unknown_1114; ++ /* 1118/1218 */ u64 _unknown_1118_guc_addr; ++ /* 1120/1220 */ u32 _unknown_1120_guc; ++ /* 1124/1224 */ u32 _unknown_1124_guc; ++ /* 1128/1228 */ u32 unknown_init_bits; // bit 2 = guc related, bit 3 = rx1 related, bit 4 = guc related ++ /* 112c/122c */ u32 _unknown_112c; ++ /* 1130/1230 */ u64 _unknown_1130_guc_addr; ++ /* 1138/1238 */ u32 _unknown_1138_guc; ++ /* 113c/123c */ u32 _unknown_113c; ++ /* 1140/1240 */ u32 _unknown_1140_guc; ++ /* 1144/1244 */ u32 _unknown_1144[23]; ++ /* 11a0/12a0 */ u32 _unknown_11a0_counters[6]; ++ /* 11b8/12b8 */ u32 _unknown_11b8[18]; ++ } dma_rx[2]; ++}; ++static_assert(sizeof(struct ithc_registers) == 0x1300); ++ ++#define DEVCFG_DMA_RX_SIZE(x) ((((x) & 0x3fff) + 1) << 6) ++#define DEVCFG_DMA_TX_SIZE(x) (((((x) >> 14) & 0x3ff) + 1) << 6) ++ ++#define DEVCFG_TOUCH_MASK 0x3f ++#define DEVCFG_TOUCH_ENABLE BIT(0) ++#define DEVCFG_TOUCH_UNKNOWN_1 BIT(1) ++#define DEVCFG_TOUCH_UNKNOWN_2 BIT(2) ++#define DEVCFG_TOUCH_UNKNOWN_3 BIT(3) ++#define DEVCFG_TOUCH_UNKNOWN_4 BIT(4) ++#define DEVCFG_TOUCH_UNKNOWN_5 BIT(5) ++#define DEVCFG_TOUCH_UNKNOWN_6 BIT(6) ++ ++#define DEVCFG_DEVICE_ID_TIC 0x43495424 // "$TIC" ++ ++#define DEVCFG_SPI_MAX_FREQ(x) (((x) >> 1) & 0xf) // high bit = use high speed mode? ++#define DEVCFG_SPI_MODE(x) (((x) >> 6) & 3) ++#define DEVCFG_SPI_UNKNOWN_8(x) (((x) >> 8) & 0x3f) ++#define DEVCFG_SPI_NEEDS_HEARTBEAT BIT(20) ++#define DEVCFG_SPI_HEARTBEAT_INTERVAL (((x) >> 21) & 7) ++#define DEVCFG_SPI_UNKNOWN_25 BIT(25) ++#define DEVCFG_SPI_UNKNOWN_26 BIT(26) ++#define DEVCFG_SPI_UNKNOWN_27 BIT(27) ++#define DEVCFG_SPI_DELAY (((x) >> 28) & 7) ++#define DEVCFG_SPI_USE_EXT_READ_CFG BIT(31) ++ ++struct ithc_device_config { ++ u32 _unknown_00; // 00 = 0xe0000402 (0xe0000401 after DMA_RX_CODE_RESET) ++ u32 _unknown_04; // 04 = 0x00000000 ++ u32 dma_buf_sizes; // 08 = 0x000a00ff ++ u32 touch_cfg; // 0c = 0x0000001c ++ u32 _unknown_10; // 10 = 0x0000001c ++ u32 device_id; // 14 = 0x43495424 = "$TIC" ++ u32 spi_config; // 18 = 0xfda00a2e ++ u16 vendor_id; // 1c = 0x045e = Microsoft Corp. ++ u16 product_id; // 1e = 0x0c1a ++ u32 revision; // 20 = 0x00000001 ++ u32 fw_version; // 24 = 0x05008a8b = 5.0.138.139 ++ u32 _unknown_28; // 28 = 0x00000000 ++ u32 fw_mode; // 2c = 0x00000000 ++ u32 _unknown_30; // 30 = 0x00000000 ++ u32 _unknown_34; // 34 = 0x0404035e (u8,u8,u8,u8 = version?) ++ u32 _unknown_38; // 38 = 0x000001c0 (0x000001c1 after DMA_RX_CODE_RESET) ++ u32 _unknown_3c; // 3c = 0x00000002 ++}; ++ ++void bitsl(__iomem u32 *reg, u32 mask, u32 val); ++void bitsb(__iomem u8 *reg, u8 mask, u8 val); ++#define bitsl_set(reg, x) bitsl(reg, x, x) ++#define bitsb_set(reg, x) bitsb(reg, x, x) ++int waitl(struct ithc *ithc, __iomem u32 *reg, u32 mask, u32 val); ++int waitb(struct ithc *ithc, __iomem u8 *reg, u8 mask, u8 val); ++int ithc_set_spi_config(struct ithc *ithc, u8 speed, u8 mode); ++int ithc_spi_command(struct ithc *ithc, u8 command, u32 offset, u32 size, void *data); ++ +diff --git a/drivers/hid/ithc/ithc.h b/drivers/hid/ithc/ithc.h +new file mode 100644 +index 0000000000000..6a9b0d480bc15 +--- /dev/null ++++ b/drivers/hid/ithc/ithc.h +@@ -0,0 +1,60 @@ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define DEVNAME "ithc" ++#define DEVFULLNAME "Intel Touch Host Controller" ++ ++#undef pr_fmt ++#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt ++ ++#define CHECK(fn, ...) ({ int r = fn(__VA_ARGS__); if (r < 0) pci_err(ithc->pci, "%s: %s failed with %i\n", __func__, #fn, r); r; }) ++#define CHECK_RET(...) do { int r = CHECK(__VA_ARGS__); if (r < 0) return r; } while(0) ++ ++#define NUM_RX_BUF 16 ++ ++struct ithc; ++ ++#include "ithc-regs.h" ++#include "ithc-dma.h" ++ ++struct ithc { ++ char phys[32]; ++ struct pci_dev *pci; ++ int irq; ++ struct task_struct *poll_thread; ++ struct pm_qos_request activity_qos; ++ struct timer_list activity_timer; ++ ++ struct hid_device *hid; ++ bool hid_parse_done; ++ wait_queue_head_t wait_hid_parse; ++ wait_queue_head_t wait_hid_get_feature; ++ struct mutex hid_get_feature_mutex; ++ void *hid_get_feature_buf; ++ size_t hid_get_feature_size; ++ ++ struct ithc_registers __iomem *regs; ++ struct ithc_registers *prev_regs; // for debugging ++ struct ithc_device_config config; ++ struct ithc_dma_rx dma_rx[2]; ++ struct ithc_dma_tx dma_tx; ++}; ++ ++int ithc_reset(struct ithc *ithc); ++void ithc_set_active(struct ithc *ithc); ++int ithc_debug_init(struct ithc *ithc); ++void ithc_log_regs(struct ithc *ithc); ++ +-- +2.40.0 + diff --git a/patches/surface/0006-surface-sam.patch b/patches/surface/0006-surface-sam.patch new file mode 100644 index 0000000..e3b0e36 --- /dev/null +++ b/patches/surface/0006-surface-sam.patch @@ -0,0 +1,2065 @@ +From 778a2db8ce2dcbd906a54a8485fd7d709676b49e Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:20 +0100 +Subject: [PATCH] platform/surface: aggregator: Improve documentation and + handling of message target and source IDs + +The `tid_in` and `tid_out` fields of the serial hub protocol command +struct (struct ssh_command) are actually source and target IDs, +indicating the peer from which the message originated and the peer for +which it is intended. + +Change the naming of those fields accordingly and improve the protocol +documentation. Additionally, introduce an enum containing all currently +known peers, i.e. targets and sources. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-3-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + .../driver-api/surface_aggregator/client.rst | 4 +- + .../driver-api/surface_aggregator/ssh.rst | 36 +++++++++-------- + .../platform/surface/aggregator/controller.c | 12 +++--- + .../platform/surface/aggregator/ssh_msgb.h | 4 +- + .../surface/aggregator/ssh_request_layer.c | 11 ++--- + include/linux/surface_aggregator/controller.h | 4 +- + include/linux/surface_aggregator/serial_hub.h | 40 +++++++++++++------ + 7 files changed, 64 insertions(+), 47 deletions(-) + +diff --git a/Documentation/driver-api/surface_aggregator/client.rst b/Documentation/driver-api/surface_aggregator/client.rst +index 27f95abdbe997..9d7411223a848 100644 +--- a/Documentation/driver-api/surface_aggregator/client.rst ++++ b/Documentation/driver-api/surface_aggregator/client.rst +@@ -191,7 +191,7 @@ data received from it is converted from little-endian to host endianness. + * they do not correspond to an actual SAM/EC request. + */ + rqst.target_category = SSAM_SSH_TC_SAM; +- rqst.target_id = 0x01; ++ rqst.target_id = SSAM_SSH_TID_SAM; + rqst.command_id = 0x02; + rqst.instance_id = 0x03; + rqst.flags = SSAM_REQUEST_HAS_RESPONSE; +@@ -241,7 +241,7 @@ one of the generator macros, for example via: + + SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, { + .target_category = SSAM_SSH_TC_TMP, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x03, + .instance_id = 0x00, + }); +diff --git a/Documentation/driver-api/surface_aggregator/ssh.rst b/Documentation/driver-api/surface_aggregator/ssh.rst +index bf007d6c98732..18fd0f0aee84b 100644 +--- a/Documentation/driver-api/surface_aggregator/ssh.rst ++++ b/Documentation/driver-api/surface_aggregator/ssh.rst +@@ -13,6 +13,7 @@ + .. |DATA_NSQ| replace:: ``DATA_NSQ`` + .. |TC| replace:: ``TC`` + .. |TID| replace:: ``TID`` ++.. |SID| replace:: ``SID`` + .. |IID| replace:: ``IID`` + .. |RQID| replace:: ``RQID`` + .. |CID| replace:: ``CID`` +@@ -219,13 +220,13 @@ following fields, packed together and in order: + - |u8| + - Target category. + +- * - |TID| (out) ++ * - |TID| + - |u8| +- - Target ID for outgoing (host to EC) commands. ++ - Target ID for commands/messages. + +- * - |TID| (in) ++ * - |SID| + - |u8| +- - Target ID for incoming (EC to host) commands. ++ - Source ID for commands/messages. + + * - |IID| + - |u8| +@@ -286,19 +287,20 @@ general, however, a single target category should map to a single reserved + event request ID. + + Furthermore, requests, responses, and events have an associated target ID +-(``TID``). This target ID is split into output (host to EC) and input (EC to +-host) fields, with the respecting other field (e.g. output field on incoming +-messages) set to zero. Two ``TID`` values are known: Primary (``0x01``) and +-secondary (``0x02``). In general, the response to a request should have the +-same ``TID`` value, however, the field (output vs. input) should be used in +-accordance to the direction in which the response is sent (i.e. on the input +-field, as responses are generally sent from the EC to the host). +- +-Note that, even though requests and events should be uniquely identifiable +-by target category and command ID alone, the EC may require specific +-target ID and instance ID values to accept a command. A command that is +-accepted for ``TID=1``, for example, may not be accepted for ``TID=2`` +-and vice versa. ++(``TID``) and source ID (``SID``). These two fields indicate where a message ++originates from (``SID``) and what the intended target of the message is ++(``TID``). Note that a response to a specific request therefore has the source ++and target IDs swapped when compared to the original request (i.e. the request ++target is the response source and the request source is the response target). ++See (:c:type:`enum ssh_request_id `) for possible values of ++both. ++ ++Note that, even though requests and events should be uniquely identifiable by ++target category and command ID alone, the EC may require specific target ID and ++instance ID values to accept a command. A command that is accepted for ++``TID=1``, for example, may not be accepted for ``TID=2`` and vice versa. While ++this may not always hold in reality, you can think of different target/source ++IDs indicating different physical ECs with potentially different feature sets. + + + Limitations and Observations +diff --git a/drivers/platform/surface/aggregator/controller.c b/drivers/platform/surface/aggregator/controller.c +index c6537a1b3a2ec..2c99f51ccd4ec 100644 +--- a/drivers/platform/surface/aggregator/controller.c ++++ b/drivers/platform/surface/aggregator/controller.c +@@ -994,7 +994,7 @@ static void ssam_handle_event(struct ssh_rtl *rtl, + + item->rqid = get_unaligned_le16(&cmd->rqid); + item->event.target_category = cmd->tc; +- item->event.target_id = cmd->tid_in; ++ item->event.target_id = cmd->sid; + item->event.command_id = cmd->cid; + item->event.instance_id = cmd->iid; + memcpy(&item->event.data[0], data->ptr, data->len); +@@ -1779,35 +1779,35 @@ EXPORT_SYMBOL_GPL(ssam_request_sync_with_buffer); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_get_firmware_version, __le32, { + .target_category = SSAM_SSH_TC_SAM, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x13, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_off, u8, { + .target_category = SSAM_SSH_TC_SAM, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x15, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_on, u8, { + .target_category = SSAM_SSH_TC_SAM, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x16, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_exit, u8, { + .target_category = SSAM_SSH_TC_SAM, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x33, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_entry, u8, { + .target_category = SSAM_SSH_TC_SAM, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x34, + .instance_id = 0x00, + }); +diff --git a/drivers/platform/surface/aggregator/ssh_msgb.h b/drivers/platform/surface/aggregator/ssh_msgb.h +index f3ecad92eefd8..438873e060986 100644 +--- a/drivers/platform/surface/aggregator/ssh_msgb.h ++++ b/drivers/platform/surface/aggregator/ssh_msgb.h +@@ -189,8 +189,8 @@ static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq, u16 rqid, + + __msgb_push_u8(msgb, SSH_PLD_TYPE_CMD); /* Payload type. */ + __msgb_push_u8(msgb, rqst->target_category); /* Target category. */ +- __msgb_push_u8(msgb, rqst->target_id); /* Target ID (out). */ +- __msgb_push_u8(msgb, 0x00); /* Target ID (in). */ ++ __msgb_push_u8(msgb, rqst->target_id); /* Target ID. */ ++ __msgb_push_u8(msgb, SSAM_SSH_TID_HOST); /* Source ID. */ + __msgb_push_u8(msgb, rqst->instance_id); /* Instance ID. */ + __msgb_push_u16(msgb, rqid); /* Request ID. */ + __msgb_push_u8(msgb, rqst->command_id); /* Command ID. */ +diff --git a/drivers/platform/surface/aggregator/ssh_request_layer.c b/drivers/platform/surface/aggregator/ssh_request_layer.c +index 69132976d297e..90634dcacabf2 100644 +--- a/drivers/platform/surface/aggregator/ssh_request_layer.c ++++ b/drivers/platform/surface/aggregator/ssh_request_layer.c +@@ -920,13 +920,14 @@ static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct ssam_span *data) + * Check if the message was intended for us. If not, drop it. + * + * Note: We will need to change this to handle debug messages. On newer +- * generation devices, these seem to be sent to tid_out=0x03. We as +- * host can still receive them as they can be forwarded via an override +- * option on SAM, but doing so does not change tid_out=0x00. ++ * generation devices, these seem to be sent to SSAM_SSH_TID_DEBUG. We ++ * as host can still receive them as they can be forwarded via an ++ * override option on SAM, but doing so does not change the target ID ++ * to SSAM_SSH_TID_HOST. + */ +- if (command->tid_out != 0x00) { ++ if (command->tid != SSAM_SSH_TID_HOST) { + rtl_warn(rtl, "rtl: dropping message not intended for us (tid = %#04x)\n", +- command->tid_out); ++ command->tid); + return; + } + +diff --git a/include/linux/surface_aggregator/controller.h b/include/linux/surface_aggregator/controller.h +index d11a1c6e3186a..8932bc0bae187 100644 +--- a/include/linux/surface_aggregator/controller.h ++++ b/include/linux/surface_aggregator/controller.h +@@ -912,10 +912,10 @@ enum ssam_event_mask { + }) + + #define SSAM_EVENT_REGISTRY_SAM \ +- SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c) ++ SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, SSAM_SSH_TID_SAM, 0x0b, 0x0c) + + #define SSAM_EVENT_REGISTRY_KIP \ +- SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28) ++ SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, SSAM_SSH_TID_KIP, 0x27, 0x28) + + #define SSAM_EVENT_REGISTRY_REG(tid)\ + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, tid, 0x01, 0x02) +diff --git a/include/linux/surface_aggregator/serial_hub.h b/include/linux/surface_aggregator/serial_hub.h +index 45501b6e54e8a..5c4ae1a261831 100644 +--- a/include/linux/surface_aggregator/serial_hub.h ++++ b/include/linux/surface_aggregator/serial_hub.h +@@ -83,23 +83,21 @@ enum ssh_payload_type { + + /** + * struct ssh_command - Payload of a command-type frame. +- * @type: The type of the payload. See &enum ssh_payload_type. Should be +- * SSH_PLD_TYPE_CMD for this struct. +- * @tc: Command target category. +- * @tid_out: Output target ID. Should be zero if this an incoming (EC to host) +- * message. +- * @tid_in: Input target ID. Should be zero if this is an outgoing (host to +- * EC) message. +- * @iid: Instance ID. +- * @rqid: Request ID. Used to match requests with responses and differentiate +- * between responses and events. +- * @cid: Command ID. ++ * @type: The type of the payload. See &enum ssh_payload_type. Should be ++ * SSH_PLD_TYPE_CMD for this struct. ++ * @tc: Command target category. ++ * @tid: Target ID. Indicates the target of the message. ++ * @sid: Source ID. Indicates the source of the message. ++ * @iid: Instance ID. ++ * @rqid: Request ID. Used to match requests with responses and differentiate ++ * between responses and events. ++ * @cid: Command ID. + */ + struct ssh_command { + u8 type; + u8 tc; +- u8 tid_out; +- u8 tid_in; ++ u8 tid; ++ u8 sid; + u8 iid; + __le16 rqid; + u8 cid; +@@ -280,6 +278,22 @@ struct ssam_span { + size_t len; + }; + ++/** ++ * enum ssam_ssh_tid - Target/source IDs for Serial Hub messages. ++ * @SSAM_SSH_TID_HOST: We as the kernel Serial Hub driver. ++ * @SSAM_SSH_TID_SAM: The Surface Aggregator EC. ++ * @SSAM_SSH_TID_KIP: Keyboard and perihperal controller. ++ * @SSAM_SSH_TID_DEBUG: Debug connector. ++ * @SSAM_SSH_TID_SURFLINK: SurfLink connector. ++ */ ++enum ssam_ssh_tid { ++ SSAM_SSH_TID_HOST = 0x00, ++ SSAM_SSH_TID_SAM = 0x01, ++ SSAM_SSH_TID_KIP = 0x02, ++ SSAM_SSH_TID_DEBUG = 0x03, ++ SSAM_SSH_TID_SURFLINK = 0x04, ++}; ++ + /* + * Known SSH/EC target categories. + * +-- +2.40.0 + +From 7a7544bea5dfe1af1dc4d7c37d082437a4c58b54 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:21 +0100 +Subject: [PATCH] platform/surface: aggregator: Add target and source IDs to + command trace events + +Add command source and target IDs to trace events. + +Tracing support for the Surface Aggregator driver was originally +implemented at a time when only two peers were known: Host and SAM. We +now know that there are at least five, with three actively being used +(Host, SAM, KIP; four with Debug if you want to count manually enabling +that interface). So it makes sense to also explicitly name the peers +involved when tracing. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-4-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/aggregator/trace.h | 73 +++++++++++++++++++-- + 1 file changed, 67 insertions(+), 6 deletions(-) + +diff --git a/drivers/platform/surface/aggregator/trace.h b/drivers/platform/surface/aggregator/trace.h +index 2a2c17771d014..55cc61bba1da6 100644 +--- a/drivers/platform/surface/aggregator/trace.h ++++ b/drivers/platform/surface/aggregator/trace.h +@@ -96,6 +96,7 @@ TRACE_DEFINE_ENUM(SSAM_SSH_TC_POS); + #define SSAM_SEQ_NOT_APPLICABLE ((u16)-1) + #define SSAM_RQID_NOT_APPLICABLE ((u32)-1) + #define SSAM_SSH_TC_NOT_APPLICABLE 0 ++#define SSAM_SSH_TID_NOT_APPLICABLE ((u8)-1) + + #ifndef _SURFACE_AGGREGATOR_TRACE_HELPERS + #define _SURFACE_AGGREGATOR_TRACE_HELPERS +@@ -150,12 +151,44 @@ static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p) + return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(rqid)]); + } + ++/** ++ * ssam_trace_get_request_tid() - Read the packet's request target ID. ++ * @p: The packet. ++ * ++ * Return: Returns the packet's request target ID (TID) field if the packet ++ * represents a request with command data, or %SSAM_SSH_TID_NOT_APPLICABLE ++ * if not (e.g. flush request, control packet). ++ */ ++static inline u32 ssam_trace_get_request_tid(const struct ssh_packet *p) ++{ ++ if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0)) ++ return SSAM_SSH_TID_NOT_APPLICABLE; ++ ++ return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(tid)]); ++} ++ ++/** ++ * ssam_trace_get_request_sid() - Read the packet's request source ID. ++ * @p: The packet. ++ * ++ * Return: Returns the packet's request source ID (SID) field if the packet ++ * represents a request with command data, or %SSAM_SSH_TID_NOT_APPLICABLE ++ * if not (e.g. flush request, control packet). ++ */ ++static inline u32 ssam_trace_get_request_sid(const struct ssh_packet *p) ++{ ++ if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0)) ++ return SSAM_SSH_TID_NOT_APPLICABLE; ++ ++ return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(sid)]); ++} ++ + /** + * ssam_trace_get_request_tc() - Read the packet's request target category. + * @p: The packet. + * + * Return: Returns the packet's request target category (TC) field if the +- * packet represents a request with command data, or %SSAM_TC_NOT_APPLICABLE ++ * packet represents a request with command data, or %SSAM_SSH_TC_NOT_APPLICABLE + * if not (e.g. flush request, control packet). + */ + static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p) +@@ -232,8 +265,18 @@ static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p) + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \ + ) + +-#define ssam_show_ssh_tc(rqid) \ +- __print_symbolic(rqid, \ ++#define ssam_show_ssh_tid(tid) \ ++ __print_symbolic(tid, \ ++ { SSAM_SSH_TID_NOT_APPLICABLE, "N/A" }, \ ++ { SSAM_SSH_TID_HOST, "Host" }, \ ++ { SSAM_SSH_TID_SAM, "SAM" }, \ ++ { SSAM_SSH_TID_KIP, "KIP" }, \ ++ { SSAM_SSH_TID_DEBUG, "Debug" }, \ ++ { SSAM_SSH_TID_SURFLINK, "SurfLink" } \ ++ ) ++ ++#define ssam_show_ssh_tc(tc) \ ++ __print_symbolic(tc, \ + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \ + { SSAM_SSH_TC_SAM, "SAM" }, \ + { SSAM_SSH_TC_BAT, "BAT" }, \ +@@ -313,6 +356,8 @@ DECLARE_EVENT_CLASS(ssam_command_class, + TP_STRUCT__entry( + __field(u16, rqid) + __field(u16, len) ++ __field(u8, tid) ++ __field(u8, sid) + __field(u8, tc) + __field(u8, cid) + __field(u8, iid) +@@ -320,14 +365,18 @@ DECLARE_EVENT_CLASS(ssam_command_class, + + TP_fast_assign( + __entry->rqid = get_unaligned_le16(&cmd->rqid); ++ __entry->tid = cmd->tid; ++ __entry->sid = cmd->sid; + __entry->tc = cmd->tc; + __entry->cid = cmd->cid; + __entry->iid = cmd->iid; + __entry->len = len; + ), + +- TP_printk("rqid=%#06x, tc=%s, cid=%#04x, iid=%#04x, len=%u", ++ TP_printk("rqid=%#06x, tid=%s, sid=%s, tc=%s, cid=%#04x, iid=%#04x, len=%u", + __entry->rqid, ++ ssam_show_ssh_tid(__entry->tid), ++ ssam_show_ssh_tid(__entry->sid), + ssam_show_ssh_tc(__entry->tc), + __entry->cid, + __entry->iid, +@@ -430,6 +479,8 @@ DECLARE_EVENT_CLASS(ssam_request_class, + __field(u8, tc) + __field(u16, cid) + __field(u16, iid) ++ __field(u8, tid) ++ __field(u8, sid) + ), + + TP_fast_assign( +@@ -439,16 +490,20 @@ DECLARE_EVENT_CLASS(ssam_request_class, + __entry->state = READ_ONCE(request->state); + __entry->rqid = ssam_trace_get_request_id(p); + ssam_trace_ptr_uid(p, __entry->uid); ++ __entry->tid = ssam_trace_get_request_tid(p); ++ __entry->sid = ssam_trace_get_request_sid(p); + __entry->tc = ssam_trace_get_request_tc(p); + __entry->cid = ssam_trace_get_command_field_u8(p, cid); + __entry->iid = ssam_trace_get_command_field_u8(p, iid); + ), + +- TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s", ++ TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tid=%s, sid=%s, tc=%s, cid=%s, iid=%s", + __entry->uid, + ssam_show_request_id(__entry->rqid), + ssam_show_request_type(__entry->state), + ssam_show_request_state(__entry->state), ++ ssam_show_ssh_tid(__entry->tid), ++ ssam_show_ssh_tid(__entry->sid), + ssam_show_ssh_tc(__entry->tc), + ssam_show_generic_u8_field(__entry->cid), + ssam_show_generic_u8_field(__entry->iid) +@@ -474,6 +529,8 @@ DECLARE_EVENT_CLASS(ssam_request_status_class, + __field(u8, tc) + __field(u16, cid) + __field(u16, iid) ++ __field(u8, tid) ++ __field(u8, sid) + ), + + TP_fast_assign( +@@ -484,16 +541,20 @@ DECLARE_EVENT_CLASS(ssam_request_status_class, + __entry->rqid = ssam_trace_get_request_id(p); + __entry->status = status; + ssam_trace_ptr_uid(p, __entry->uid); ++ __entry->tid = ssam_trace_get_request_tid(p); ++ __entry->sid = ssam_trace_get_request_sid(p); + __entry->tc = ssam_trace_get_request_tc(p); + __entry->cid = ssam_trace_get_command_field_u8(p, cid); + __entry->iid = ssam_trace_get_command_field_u8(p, iid); + ), + +- TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d", ++ TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tid=%s, sid=%s, tc=%s, cid=%s, iid=%s, status=%d", + __entry->uid, + ssam_show_request_id(__entry->rqid), + ssam_show_request_type(__entry->state), + ssam_show_request_state(__entry->state), ++ ssam_show_ssh_tid(__entry->tid), ++ ssam_show_ssh_tid(__entry->sid), + ssam_show_ssh_tc(__entry->tc), + ssam_show_generic_u8_field(__entry->cid), + ssam_show_generic_u8_field(__entry->iid), +-- +2.40.0 + +From bf7023d6b488b105cf31620d274b840cb69903c6 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:22 +0100 +Subject: [PATCH] platform/surface: aggregator_hub: Use target-ID enum instead + of hard-coding values + +Instead of hard-coding the target ID, use the respective enum +ssam_ssh_tid value. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-5-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/surface_aggregator_hub.c | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/drivers/platform/surface/surface_aggregator_hub.c b/drivers/platform/surface/surface_aggregator_hub.c +index 43061514be382..62f27cdb6ca8f 100644 +--- a/drivers/platform/surface/surface_aggregator_hub.c ++++ b/drivers/platform/surface/surface_aggregator_hub.c +@@ -214,7 +214,7 @@ static void ssam_hub_remove(struct ssam_device *sdev) + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_query_opmode, u8, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x0d, + .instance_id = 0x00, + }); +@@ -292,7 +292,7 @@ static const struct ssam_hub_desc base_hub = { + + SSAM_DEFINE_SYNC_REQUEST_R(__ssam_kip_query_state, u8, { + .target_category = SSAM_SSH_TC_KIP, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x2c, + .instance_id = 0x00, + }); +-- +2.40.0 + +From 0e4e08a89e876ab9a2c249723bdeb854014caa2a Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:23 +0100 +Subject: [PATCH] platform/surface: aggregator_tabletsw: Use target-ID enum + instead of hard-coding values + +Instead of hard-coding the target ID, use the respective enum +ssam_ssh_tid value. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-6-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/surface_aggregator_tabletsw.c | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) + +diff --git a/drivers/platform/surface/surface_aggregator_tabletsw.c b/drivers/platform/surface/surface_aggregator_tabletsw.c +index 27d95a6a78513..bd8cd453c393a 100644 +--- a/drivers/platform/surface/surface_aggregator_tabletsw.c ++++ b/drivers/platform/surface/surface_aggregator_tabletsw.c +@@ -247,7 +247,7 @@ static bool ssam_kip_cover_state_is_tablet_mode(struct ssam_tablet_sw *sw, u32 s + + SSAM_DEFINE_SYNC_REQUEST_R(__ssam_kip_get_cover_state, u8, { + .target_category = SSAM_SSH_TC_KIP, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x1d, + .instance_id = 0x00, + }); +@@ -371,7 +371,7 @@ static int ssam_pos_get_sources_list(struct ssam_tablet_sw *sw, struct ssam_sour + int status; + + rqst.target_category = SSAM_SSH_TC_POS; +- rqst.target_id = 0x01; ++ rqst.target_id = SSAM_SSH_TID_SAM; + rqst.command_id = 0x01; + rqst.instance_id = 0x00; + rqst.flags = SSAM_REQUEST_HAS_RESPONSE; +@@ -430,7 +430,7 @@ static int ssam_pos_get_source(struct ssam_tablet_sw *sw, u32 *source_id) + + SSAM_DEFINE_SYNC_REQUEST_WR(__ssam_pos_get_posture_for_source, __le32, __le32, { + .target_category = SSAM_SSH_TC_POS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x02, + .instance_id = 0x00, + }); +-- +2.40.0 + +From ee1aa0af02119f77a220275b91fab59094635284 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:24 +0100 +Subject: [PATCH] platform/surface: dtx: Use target-ID enum instead of + hard-coding values + +Instead of hard-coding the target ID, use the respective enum +ssam_ssh_tid value. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-7-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/surface_dtx.c | 18 +++++++++--------- + 1 file changed, 9 insertions(+), 9 deletions(-) + +diff --git a/drivers/platform/surface/surface_dtx.c b/drivers/platform/surface/surface_dtx.c +index ed36944467f9f..0de76a784a35f 100644 +--- a/drivers/platform/surface/surface_dtx.c ++++ b/drivers/platform/surface/surface_dtx.c +@@ -71,63 +71,63 @@ static_assert(sizeof(struct ssam_bas_base_info) == 2); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_lock, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x06, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_unlock, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x07, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_request, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x08, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_confirm, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x09, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_heartbeat, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x0a, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_cancel, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x0b, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_base, struct ssam_bas_base_info, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x0c, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_device_mode, u8, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x0d, + .instance_id = 0x00, + }); + + SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_latch_status, u8, { + .target_category = SSAM_SSH_TC_BAS, +- .target_id = 0x01, ++ .target_id = SSAM_SSH_TID_SAM, + .command_id = 0x11, + .instance_id = 0x00, + }); +-- +2.40.0 + +From d6c563a663aadd47bb16fa754b8b75b44624a456 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:25 +0100 +Subject: [PATCH] HID: surface-hid: Use target-ID enum instead of hard-coding + values + +Instead of hard-coding the target ID, use the respective enum +ssam_ssh_tid value. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-8-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/hid/surface-hid/surface_kbd.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/drivers/hid/surface-hid/surface_kbd.c b/drivers/hid/surface-hid/surface_kbd.c +index 0635341bc5174..42933bf3e925f 100644 +--- a/drivers/hid/surface-hid/surface_kbd.c ++++ b/drivers/hid/surface-hid/surface_kbd.c +@@ -250,7 +250,7 @@ static int surface_kbd_probe(struct platform_device *pdev) + + shid->uid.domain = SSAM_DOMAIN_SERIALHUB; + shid->uid.category = SSAM_SSH_TC_KBD; +- shid->uid.target = 2; ++ shid->uid.target = SSAM_SSH_TID_KIP; + shid->uid.instance = 0; + shid->uid.function = 0; + +-- +2.40.0 + +From 036831a2ce3ed84af6d8b47021c223257bf2ee83 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:26 +0100 +Subject: [PATCH] platform/surface: aggregator: Enforce use of target-ID enum + in device ID macros + +Similar to the target category (TC), the target ID (TID) can be one +value out of a small number of choices, given in enum ssam_ssh_tid. + +In the device ID macros, SSAM_SDEV() and SSAM_VDEV() we already use text +expansion to, both, remove some textual clutter for the target category +values and enforce that the value belongs to the known set. Now that we +know the names for the target IDs, use the same trick for them as well. + +Also rename the SSAM_ANY_x macros to SSAM_SSH_x_ANY to better fit in. + +Signed-off-by: Maximilian Luz +Acked-by: Sebastian Reichel +Link: https://lore.kernel.org/r/20221202223327.690880-9-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/hid/surface-hid/surface_hid.c | 2 +- + .../platform/surface/surface_aggregator_hub.c | 4 +- + .../surface/surface_aggregator_tabletsw.c | 4 +- + drivers/platform/surface/surface_dtx.c | 2 +- + .../surface/surface_platform_profile.c | 2 +- + drivers/power/supply/surface_battery.c | 4 +- + drivers/power/supply/surface_charger.c | 2 +- + include/linux/surface_aggregator/device.h | 50 +++++++++---------- + 8 files changed, 35 insertions(+), 35 deletions(-) + +diff --git a/drivers/hid/surface-hid/surface_hid.c b/drivers/hid/surface-hid/surface_hid.c +index d4aa8c81903ae..aa80d83a83d1b 100644 +--- a/drivers/hid/surface-hid/surface_hid.c ++++ b/drivers/hid/surface-hid/surface_hid.c +@@ -230,7 +230,7 @@ static void surface_hid_remove(struct ssam_device *sdev) + } + + static const struct ssam_device_id surface_hid_match[] = { +- { SSAM_SDEV(HID, SSAM_ANY_TID, SSAM_ANY_IID, 0x00) }, ++ { SSAM_SDEV(HID, ANY, SSAM_SSH_IID_ANY, 0x00) }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, surface_hid_match); +diff --git a/drivers/platform/surface/surface_aggregator_hub.c b/drivers/platform/surface/surface_aggregator_hub.c +index 62f27cdb6ca8f..6abd1efe20883 100644 +--- a/drivers/platform/surface/surface_aggregator_hub.c ++++ b/drivers/platform/surface/surface_aggregator_hub.c +@@ -348,8 +348,8 @@ static const struct ssam_hub_desc kip_hub = { + /* -- Driver registration. -------------------------------------------------- */ + + static const struct ssam_device_id ssam_hub_match[] = { +- { SSAM_VDEV(HUB, 0x01, SSAM_SSH_TC_KIP, 0x00), (unsigned long)&kip_hub }, +- { SSAM_VDEV(HUB, 0x02, SSAM_SSH_TC_BAS, 0x00), (unsigned long)&base_hub }, ++ { SSAM_VDEV(HUB, SAM, SSAM_SSH_TC_KIP, 0x00), (unsigned long)&kip_hub }, ++ { SSAM_VDEV(HUB, KIP, SSAM_SSH_TC_BAS, 0x00), (unsigned long)&base_hub }, + { } + }; + MODULE_DEVICE_TABLE(ssam, ssam_hub_match); +diff --git a/drivers/platform/surface/surface_aggregator_tabletsw.c b/drivers/platform/surface/surface_aggregator_tabletsw.c +index bd8cd453c393a..6147aa8879391 100644 +--- a/drivers/platform/surface/surface_aggregator_tabletsw.c ++++ b/drivers/platform/surface/surface_aggregator_tabletsw.c +@@ -510,8 +510,8 @@ static const struct ssam_tablet_sw_desc ssam_pos_sw_desc = { + /* -- Driver registration. -------------------------------------------------- */ + + static const struct ssam_device_id ssam_tablet_sw_match[] = { +- { SSAM_SDEV(KIP, 0x01, 0x00, 0x01), (unsigned long)&ssam_kip_sw_desc }, +- { SSAM_SDEV(POS, 0x01, 0x00, 0x01), (unsigned long)&ssam_pos_sw_desc }, ++ { SSAM_SDEV(KIP, SAM, 0x00, 0x01), (unsigned long)&ssam_kip_sw_desc }, ++ { SSAM_SDEV(POS, SAM, 0x00, 0x01), (unsigned long)&ssam_pos_sw_desc }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, ssam_tablet_sw_match); +diff --git a/drivers/platform/surface/surface_dtx.c b/drivers/platform/surface/surface_dtx.c +index 0de76a784a35f..30cbde278c599 100644 +--- a/drivers/platform/surface/surface_dtx.c ++++ b/drivers/platform/surface/surface_dtx.c +@@ -1214,7 +1214,7 @@ static void surface_dtx_ssam_remove(struct ssam_device *sdev) + } + + static const struct ssam_device_id surface_dtx_ssam_match[] = { +- { SSAM_SDEV(BAS, 0x01, 0x00, 0x00) }, ++ { SSAM_SDEV(BAS, SAM, 0x00, 0x00) }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, surface_dtx_ssam_match); +diff --git a/drivers/platform/surface/surface_platform_profile.c b/drivers/platform/surface/surface_platform_profile.c +index fbf2e11fd6ce7..f433a13c3689a 100644 +--- a/drivers/platform/surface/surface_platform_profile.c ++++ b/drivers/platform/surface/surface_platform_profile.c +@@ -169,7 +169,7 @@ static void surface_platform_profile_remove(struct ssam_device *sdev) + } + + static const struct ssam_device_id ssam_platform_profile_match[] = { +- { SSAM_SDEV(TMP, 0x01, 0x00, 0x01) }, ++ { SSAM_SDEV(TMP, SAM, 0x00, 0x01) }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, ssam_platform_profile_match); +diff --git a/drivers/power/supply/surface_battery.c b/drivers/power/supply/surface_battery.c +index 540707882bb0a..19d2f8834e56d 100644 +--- a/drivers/power/supply/surface_battery.c ++++ b/drivers/power/supply/surface_battery.c +@@ -852,8 +852,8 @@ static const struct spwr_psy_properties spwr_psy_props_bat2_sb3 = { + }; + + static const struct ssam_device_id surface_battery_match[] = { +- { SSAM_SDEV(BAT, 0x01, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat1 }, +- { SSAM_SDEV(BAT, 0x02, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat2_sb3 }, ++ { SSAM_SDEV(BAT, SAM, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat1 }, ++ { SSAM_SDEV(BAT, KIP, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat2_sb3 }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, surface_battery_match); +diff --git a/drivers/power/supply/surface_charger.c b/drivers/power/supply/surface_charger.c +index 59182d55742d0..cabdd8da12d08 100644 +--- a/drivers/power/supply/surface_charger.c ++++ b/drivers/power/supply/surface_charger.c +@@ -260,7 +260,7 @@ static const struct spwr_psy_properties spwr_psy_props_adp1 = { + }; + + static const struct ssam_device_id surface_ac_match[] = { +- { SSAM_SDEV(BAT, 0x01, 0x01, 0x01), (unsigned long)&spwr_psy_props_adp1 }, ++ { SSAM_SDEV(BAT, SAM, 0x01, 0x01), (unsigned long)&spwr_psy_props_adp1 }, + { }, + }; + MODULE_DEVICE_TABLE(ssam, surface_ac_match); +diff --git a/include/linux/surface_aggregator/device.h b/include/linux/surface_aggregator/device.h +index 46c45d1b63682..4da20b7a0ee5e 100644 +--- a/include/linux/surface_aggregator/device.h ++++ b/include/linux/surface_aggregator/device.h +@@ -68,9 +68,9 @@ struct ssam_device_uid { + * match_flags member of the device ID structure. Do not use them directly + * with struct ssam_device_id or struct ssam_device_uid. + */ +-#define SSAM_ANY_TID 0xffff +-#define SSAM_ANY_IID 0xffff +-#define SSAM_ANY_FUN 0xffff ++#define SSAM_SSH_TID_ANY 0xffff ++#define SSAM_SSH_IID_ANY 0xffff ++#define SSAM_SSH_FUN_ANY 0xffff + + /** + * SSAM_DEVICE() - Initialize a &struct ssam_device_id with the given +@@ -83,25 +83,25 @@ struct ssam_device_uid { + * + * Initializes a &struct ssam_device_id with the given parameters. See &struct + * ssam_device_uid for details regarding the parameters. The special values +- * %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be used to specify that ++ * %SSAM_SSH_TID_ANY, %SSAM_SSH_IID_ANY, and %SSAM_SSH_FUN_ANY can be used to specify that + * matching should ignore target ID, instance ID, and/or sub-function, + * respectively. This macro initializes the ``match_flags`` field based on the + * given parameters. + * + * Note: The parameters @d and @cat must be valid &u8 values, the parameters +- * @tid, @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID, +- * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not ++ * @tid, @iid, and @fun must be either valid &u8 values or %SSAM_SSH_TID_ANY, ++ * %SSAM_SSH_IID_ANY, or %SSAM_SSH_FUN_ANY, respectively. Other non-&u8 values are not + * allowed. + */ + #define SSAM_DEVICE(d, cat, tid, iid, fun) \ +- .match_flags = (((tid) != SSAM_ANY_TID) ? SSAM_MATCH_TARGET : 0) \ +- | (((iid) != SSAM_ANY_IID) ? SSAM_MATCH_INSTANCE : 0) \ +- | (((fun) != SSAM_ANY_FUN) ? SSAM_MATCH_FUNCTION : 0), \ ++ .match_flags = (((tid) != SSAM_SSH_TID_ANY) ? SSAM_MATCH_TARGET : 0) \ ++ | (((iid) != SSAM_SSH_IID_ANY) ? SSAM_MATCH_INSTANCE : 0) \ ++ | (((fun) != SSAM_SSH_FUN_ANY) ? SSAM_MATCH_FUNCTION : 0), \ + .domain = d, \ + .category = cat, \ +- .target = __builtin_choose_expr((tid) != SSAM_ANY_TID, (tid), 0), \ +- .instance = __builtin_choose_expr((iid) != SSAM_ANY_IID, (iid), 0), \ +- .function = __builtin_choose_expr((fun) != SSAM_ANY_FUN, (fun), 0) ++ .target = __builtin_choose_expr((tid) != SSAM_SSH_TID_ANY, (tid), 0), \ ++ .instance = __builtin_choose_expr((iid) != SSAM_SSH_IID_ANY, (iid), 0), \ ++ .function = __builtin_choose_expr((fun) != SSAM_SSH_FUN_ANY, (fun), 0) + + /** + * SSAM_VDEV() - Initialize a &struct ssam_device_id as virtual device with +@@ -113,18 +113,18 @@ struct ssam_device_uid { + * + * Initializes a &struct ssam_device_id with the given parameters in the + * virtual domain. See &struct ssam_device_uid for details regarding the +- * parameters. The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and +- * %SSAM_ANY_FUN can be used to specify that matching should ignore target ID, ++ * parameters. The special values %SSAM_SSH_TID_ANY, %SSAM_SSH_IID_ANY, and ++ * %SSAM_SSH_FUN_ANY can be used to specify that matching should ignore target ID, + * instance ID, and/or sub-function, respectively. This macro initializes the + * ``match_flags`` field based on the given parameters. + * + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid, +- * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID, +- * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not ++ * @iid, and @fun must be either valid &u8 values or %SSAM_SSH_TID_ANY, ++ * %SSAM_SSH_IID_ANY, or %SSAM_SSH_FUN_ANY, respectively. Other non-&u8 values are not + * allowed. + */ + #define SSAM_VDEV(cat, tid, iid, fun) \ +- SSAM_DEVICE(SSAM_DOMAIN_VIRTUAL, SSAM_VIRTUAL_TC_##cat, tid, iid, fun) ++ SSAM_DEVICE(SSAM_DOMAIN_VIRTUAL, SSAM_VIRTUAL_TC_##cat, SSAM_SSH_TID_##tid, iid, fun) + + /** + * SSAM_SDEV() - Initialize a &struct ssam_device_id as physical SSH device +@@ -136,18 +136,18 @@ struct ssam_device_uid { + * + * Initializes a &struct ssam_device_id with the given parameters in the SSH + * domain. See &struct ssam_device_uid for details regarding the parameters. +- * The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be +- * used to specify that matching should ignore target ID, instance ID, and/or +- * sub-function, respectively. This macro initializes the ``match_flags`` +- * field based on the given parameters. ++ * The special values %SSAM_SSH_TID_ANY, %SSAM_SSH_IID_ANY, and ++ * %SSAM_SSH_FUN_ANY can be used to specify that matching should ignore target ++ * ID, instance ID, and/or sub-function, respectively. This macro initializes ++ * the ``match_flags`` field based on the given parameters. + * + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid, +- * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID, +- * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not +- * allowed. ++ * @iid, and @fun must be either valid &u8 values or %SSAM_SSH_TID_ANY, ++ * %SSAM_SSH_IID_ANY, or %SSAM_SSH_FUN_ANY, respectively. Other non-&u8 values ++ * are not allowed. + */ + #define SSAM_SDEV(cat, tid, iid, fun) \ +- SSAM_DEVICE(SSAM_DOMAIN_SERIALHUB, SSAM_SSH_TC_##cat, tid, iid, fun) ++ SSAM_DEVICE(SSAM_DOMAIN_SERIALHUB, SSAM_SSH_TC_##cat, SSAM_SSH_TID_##tid, iid, fun) + + /* + * enum ssam_device_flags - Flags for SSAM client devices. +-- +2.40.0 + +From 5fcfeffcaaeaf3c70164a9eeb4fdccfca8a83724 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 2 Dec 2022 23:33:27 +0100 +Subject: [PATCH] platform/surface: aggregator_registry: Fix target-ID of + base-hub + +The target ID of the base hub is currently set to KIP (keyboard/ +peripherals). However, even though it manages such devices with the KIP +target ID, the base hub itself is actually accessed via the SAM target +ID. So set it accordingly. + +Note that the target ID of the hub can be chosen arbitrarily and does +not directly correspond to any physical or virtual component of the EC. +This change is only a code improvement intended for consistency and +clarity, it does not fix an actual bug. + +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221202223327.690880-10-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/surface_aggregator_hub.c | 2 +- + drivers/platform/surface/surface_aggregator_registry.c | 2 +- + 2 files changed, 2 insertions(+), 2 deletions(-) + +diff --git a/drivers/platform/surface/surface_aggregator_hub.c b/drivers/platform/surface/surface_aggregator_hub.c +index 6abd1efe20883..8b8b80228c147 100644 +--- a/drivers/platform/surface/surface_aggregator_hub.c ++++ b/drivers/platform/surface/surface_aggregator_hub.c +@@ -349,7 +349,7 @@ static const struct ssam_hub_desc kip_hub = { + + static const struct ssam_device_id ssam_hub_match[] = { + { SSAM_VDEV(HUB, SAM, SSAM_SSH_TC_KIP, 0x00), (unsigned long)&kip_hub }, +- { SSAM_VDEV(HUB, KIP, SSAM_SSH_TC_BAS, 0x00), (unsigned long)&base_hub }, ++ { SSAM_VDEV(HUB, SAM, SSAM_SSH_TC_BAS, 0x00), (unsigned long)&base_hub }, + { } + }; + MODULE_DEVICE_TABLE(ssam, ssam_hub_match); +diff --git a/drivers/platform/surface/surface_aggregator_registry.c b/drivers/platform/surface/surface_aggregator_registry.c +index 023f126121d7d..296f72d52e6a6 100644 +--- a/drivers/platform/surface/surface_aggregator_registry.c ++++ b/drivers/platform/surface/surface_aggregator_registry.c +@@ -46,7 +46,7 @@ static const struct software_node ssam_node_hub_kip = { + + /* Base device hub (devices attached to Surface Book 3 base). */ + static const struct software_node ssam_node_hub_base = { +- .name = "ssam:00:00:02:11:00", ++ .name = "ssam:00:00:01:11:00", + .parent = &ssam_node_root, + }; + +-- +2.40.0 + +From 93a1a375c4f1ce074bd307172dedb2ca97306b6c Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Tue, 20 Dec 2022 18:56:08 +0100 +Subject: [PATCH] platform/surface: aggregator: Rename top-level request + functions to avoid ambiguities + +We currently have a struct ssam_request_sync and a function +ssam_request_sync(). While this is valid C, there are some downsides to +it. + +One of these is that current Sphinx versions (>= 3.0) cannot +disambiguate between the two (see disucssion and pull request linked +below). It instead emits a "WARNING: Duplicate C declaration" and links +for the struct and function in the resulting documentation link to the +same entry (i.e. both to either function or struct documentation) +instead of their respective own entries. + +While we could just ignore that and wait for a fix, there's also a point +to be made that the current naming can be somewhat confusing when +searching (e.g. via grep) or trying to understand the levels of +abstraction at play: + +We currently have struct ssam_request_sync and associated functions +ssam_request_sync_[alloc|free|init|wait|...]() operating on this struct. +However, function ssam_request_sync() is one abstraction level above +this. Similarly, ssam_request_sync_with_buffer() is not a function +operating on struct ssam_request_sync, but rather a sibling to +ssam_request_sync(), both using the struct under the hood. + +Therefore, rename the top level request functions: + + ssam_request_sync() -> ssam_request_do_sync() + ssam_request_sync_with_buffer() -> ssam_request_do_sync_with_buffer() + ssam_request_sync_onstack() -> ssam_request_do_sync_onstack() + +Link: https://lore.kernel.org/all/085e0ada65c11da9303d07e70c510dc45f21315b.1656756450.git.mchehab@kernel.org/ +Link: https://github.com/sphinx-doc/sphinx/pull/8313 +Signed-off-by: Maximilian Luz +Link: https://lore.kernel.org/r/20221220175608.1436273-2-luzmaximilian@gmail.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + .../driver-api/surface_aggregator/client.rst | 8 +-- + drivers/hid/surface-hid/surface_hid.c | 6 +- + drivers/hid/surface-hid/surface_kbd.c | 6 +- + drivers/platform/surface/aggregator/bus.c | 6 +- + .../platform/surface/aggregator/controller.c | 32 +++++------ + .../platform/surface/surface_acpi_notify.c | 2 +- + .../surface/surface_aggregator_cdev.c | 6 +- + .../surface/surface_aggregator_tabletsw.c | 2 +- + include/linux/surface_aggregator/controller.h | 56 +++++++++---------- + include/linux/surface_aggregator/device.h | 8 +-- + 10 files changed, 66 insertions(+), 66 deletions(-) + +diff --git a/Documentation/driver-api/surface_aggregator/client.rst b/Documentation/driver-api/surface_aggregator/client.rst +index 9d7411223a848..e100ab0a24cc4 100644 +--- a/Documentation/driver-api/surface_aggregator/client.rst ++++ b/Documentation/driver-api/surface_aggregator/client.rst +@@ -19,7 +19,7 @@ + .. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister` + .. |ssam_device_notifier_register| replace:: :c:func:`ssam_device_notifier_register` + .. |ssam_device_notifier_unregister| replace:: :c:func:`ssam_device_notifier_unregister` +-.. |ssam_request_sync| replace:: :c:func:`ssam_request_sync` ++.. |ssam_request_do_sync| replace:: :c:func:`ssam_request_do_sync` + .. |ssam_event_mask| replace:: :c:type:`enum ssam_event_mask ` + + +@@ -209,12 +209,12 @@ data received from it is converted from little-endian to host endianness. + * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification + * above. + */ +- status = ssam_request_sync(ctrl, &rqst, &resp); ++ status = ssam_request_do_sync(ctrl, &rqst, &resp); + + /* + * Alternatively use + * +- * ssam_request_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le)); ++ * ssam_request_do_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le)); + * + * to perform the request, allocating the message buffer directly + * on the stack as opposed to allocation via kzalloc(). +@@ -230,7 +230,7 @@ data received from it is converted from little-endian to host endianness. + return status; + } + +-Note that |ssam_request_sync| in its essence is a wrapper over lower-level ++Note that |ssam_request_do_sync| in its essence is a wrapper over lower-level + request primitives, which may also be used to perform requests. Refer to its + implementation and documentation for more details. + +diff --git a/drivers/hid/surface-hid/surface_hid.c b/drivers/hid/surface-hid/surface_hid.c +index aa80d83a83d1b..61e5814b0ad7d 100644 +--- a/drivers/hid/surface-hid/surface_hid.c ++++ b/drivers/hid/surface-hid/surface_hid.c +@@ -80,7 +80,7 @@ static int ssam_hid_get_descriptor(struct surface_hid_device *shid, u8 entry, u8 + + rsp.length = 0; + +- status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp, ++ status = ssam_retry(ssam_request_do_sync_onstack, shid->ctrl, &rqst, &rsp, + sizeof(*slice)); + if (status) + return status; +@@ -131,7 +131,7 @@ static int ssam_hid_set_raw_report(struct surface_hid_device *shid, u8 rprt_id, + + buf[0] = rprt_id; + +- return ssam_retry(ssam_request_sync, shid->ctrl, &rqst, NULL); ++ return ssam_retry(ssam_request_do_sync, shid->ctrl, &rqst, NULL); + } + + static int ssam_hid_get_raw_report(struct surface_hid_device *shid, u8 rprt_id, u8 *buf, size_t len) +@@ -151,7 +151,7 @@ static int ssam_hid_get_raw_report(struct surface_hid_device *shid, u8 rprt_id, + rsp.length = 0; + rsp.pointer = buf; + +- return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(rprt_id)); ++ return ssam_retry(ssam_request_do_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(rprt_id)); + } + + static u32 ssam_hid_event_fn(struct ssam_event_notifier *nf, const struct ssam_event *event) +diff --git a/drivers/hid/surface-hid/surface_kbd.c b/drivers/hid/surface-hid/surface_kbd.c +index 42933bf3e925f..4fbce201db6a1 100644 +--- a/drivers/hid/surface-hid/surface_kbd.c ++++ b/drivers/hid/surface-hid/surface_kbd.c +@@ -49,7 +49,7 @@ static int ssam_kbd_get_descriptor(struct surface_hid_device *shid, u8 entry, u8 + rsp.length = 0; + rsp.pointer = buf; + +- status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(entry)); ++ status = ssam_retry(ssam_request_do_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(entry)); + if (status) + return status; + +@@ -75,7 +75,7 @@ static int ssam_kbd_set_caps_led(struct surface_hid_device *shid, bool value) + rqst.length = sizeof(value_u8); + rqst.payload = &value_u8; + +- return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, NULL, sizeof(value_u8)); ++ return ssam_retry(ssam_request_do_sync_onstack, shid->ctrl, &rqst, NULL, sizeof(value_u8)); + } + + static int ssam_kbd_get_feature_report(struct surface_hid_device *shid, u8 *buf, size_t len) +@@ -97,7 +97,7 @@ static int ssam_kbd_get_feature_report(struct surface_hid_device *shid, u8 *buf, + rsp.length = 0; + rsp.pointer = buf; + +- status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(payload)); ++ status = ssam_retry(ssam_request_do_sync_onstack, shid->ctrl, &rqst, &rsp, sizeof(payload)); + if (status) + return status; + +diff --git a/drivers/platform/surface/aggregator/bus.c b/drivers/platform/surface/aggregator/bus.c +index b501a79f2a08a..da0baba5ed51f 100644 +--- a/drivers/platform/surface/aggregator/bus.c ++++ b/drivers/platform/surface/aggregator/bus.c +@@ -136,9 +136,9 @@ int ssam_device_add(struct ssam_device *sdev) + * is always valid and can be used for requests as long as the client + * device we add here is registered as child under it. This essentially + * guarantees that the client driver can always expect the preconditions +- * for functions like ssam_request_sync (controller has to be started +- * and is not suspended) to hold and thus does not have to check for +- * them. ++ * for functions like ssam_request_do_sync() (controller has to be ++ * started and is not suspended) to hold and thus does not have to check ++ * for them. + * + * Note that for this to work, the controller has to be a parent device. + * If it is not a direct parent, care has to be taken that the device is +diff --git a/drivers/platform/surface/aggregator/controller.c b/drivers/platform/surface/aggregator/controller.c +index 2c99f51ccd4ec..535581c0471c5 100644 +--- a/drivers/platform/surface/aggregator/controller.c ++++ b/drivers/platform/surface/aggregator/controller.c +@@ -1674,7 +1674,7 @@ int ssam_request_sync_submit(struct ssam_controller *ctrl, + EXPORT_SYMBOL_GPL(ssam_request_sync_submit); + + /** +- * ssam_request_sync() - Execute a synchronous request. ++ * ssam_request_do_sync() - Execute a synchronous request. + * @ctrl: The controller via which the request will be submitted. + * @spec: The request specification and payload. + * @rsp: The response buffer. +@@ -1686,9 +1686,9 @@ EXPORT_SYMBOL_GPL(ssam_request_sync_submit); + * + * Return: Returns the status of the request or any failure during setup. + */ +-int ssam_request_sync(struct ssam_controller *ctrl, +- const struct ssam_request *spec, +- struct ssam_response *rsp) ++int ssam_request_do_sync(struct ssam_controller *ctrl, ++ const struct ssam_request *spec, ++ struct ssam_response *rsp) + { + struct ssam_request_sync *rqst; + struct ssam_span buf; +@@ -1722,10 +1722,10 @@ int ssam_request_sync(struct ssam_controller *ctrl, + ssam_request_sync_free(rqst); + return status; + } +-EXPORT_SYMBOL_GPL(ssam_request_sync); ++EXPORT_SYMBOL_GPL(ssam_request_do_sync); + + /** +- * ssam_request_sync_with_buffer() - Execute a synchronous request with the ++ * ssam_request_do_sync_with_buffer() - Execute a synchronous request with the + * provided buffer as back-end for the message buffer. + * @ctrl: The controller via which the request will be submitted. + * @spec: The request specification and payload. +@@ -1738,17 +1738,17 @@ EXPORT_SYMBOL_GPL(ssam_request_sync); + * SSH_COMMAND_MESSAGE_LENGTH() macro can be used to compute the required + * message buffer size. + * +- * This function does essentially the same as ssam_request_sync(), but instead +- * of dynamically allocating the request and message data buffer, it uses the +- * provided message data buffer and stores the (small) request struct on the +- * heap. ++ * This function does essentially the same as ssam_request_do_sync(), but ++ * instead of dynamically allocating the request and message data buffer, it ++ * uses the provided message data buffer and stores the (small) request struct ++ * on the heap. + * + * Return: Returns the status of the request or any failure during setup. + */ +-int ssam_request_sync_with_buffer(struct ssam_controller *ctrl, +- const struct ssam_request *spec, +- struct ssam_response *rsp, +- struct ssam_span *buf) ++int ssam_request_do_sync_with_buffer(struct ssam_controller *ctrl, ++ const struct ssam_request *spec, ++ struct ssam_response *rsp, ++ struct ssam_span *buf) + { + struct ssam_request_sync rqst; + ssize_t len; +@@ -1772,7 +1772,7 @@ int ssam_request_sync_with_buffer(struct ssam_controller *ctrl, + + return status; + } +-EXPORT_SYMBOL_GPL(ssam_request_sync_with_buffer); ++EXPORT_SYMBOL_GPL(ssam_request_do_sync_with_buffer); + + + /* -- Internal SAM requests. ------------------------------------------------ */ +@@ -1864,7 +1864,7 @@ static int __ssam_ssh_event_request(struct ssam_controller *ctrl, + result.length = 0; + result.pointer = &buf; + +- status = ssam_retry(ssam_request_sync_onstack, ctrl, &rqst, &result, ++ status = ssam_retry(ssam_request_do_sync_onstack, ctrl, &rqst, &result, + sizeof(params)); + + return status < 0 ? status : buf; +diff --git a/drivers/platform/surface/surface_acpi_notify.c b/drivers/platform/surface/surface_acpi_notify.c +index 50500e562963d..897cdd9c3aae8 100644 +--- a/drivers/platform/surface/surface_acpi_notify.c ++++ b/drivers/platform/surface/surface_acpi_notify.c +@@ -590,7 +590,7 @@ static acpi_status san_rqst(struct san_data *d, struct gsb_buffer *buffer) + return san_rqst_fixup_suspended(d, &rqst, buffer); + } + +- status = __ssam_retry(ssam_request_sync_onstack, SAN_REQUEST_NUM_TRIES, ++ status = __ssam_retry(ssam_request_do_sync_onstack, SAN_REQUEST_NUM_TRIES, + d->ctrl, &rqst, &rsp, SAN_GSB_MAX_RQSX_PAYLOAD); + + if (!status) { +diff --git a/drivers/platform/surface/surface_aggregator_cdev.c b/drivers/platform/surface/surface_aggregator_cdev.c +index 492c82e691827..07f0ed658369b 100644 +--- a/drivers/platform/surface/surface_aggregator_cdev.c ++++ b/drivers/platform/surface/surface_aggregator_cdev.c +@@ -302,8 +302,8 @@ static long ssam_cdev_request(struct ssam_cdev_client *client, struct ssam_cdev_ + * theoretical maximum (SSH_COMMAND_MAX_PAYLOAD_SIZE) of the + * underlying protocol (note that nothing remotely this size + * should ever be allocated in any normal case). This size is +- * validated later in ssam_request_sync(), for allocation the +- * bound imposed by u16 should be enough. ++ * validated later in ssam_request_do_sync(), for allocation ++ * the bound imposed by u16 should be enough. + */ + spec.payload = kzalloc(spec.length, GFP_KERNEL); + if (!spec.payload) { +@@ -342,7 +342,7 @@ static long ssam_cdev_request(struct ssam_cdev_client *client, struct ssam_cdev_ + } + + /* Perform request. */ +- status = ssam_request_sync(client->cdev->ctrl, &spec, &rsp); ++ status = ssam_request_do_sync(client->cdev->ctrl, &spec, &rsp); + if (status) + goto out; + +diff --git a/drivers/platform/surface/surface_aggregator_tabletsw.c b/drivers/platform/surface/surface_aggregator_tabletsw.c +index 6147aa8879391..9fed800c7cc09 100644 +--- a/drivers/platform/surface/surface_aggregator_tabletsw.c ++++ b/drivers/platform/surface/surface_aggregator_tabletsw.c +@@ -382,7 +382,7 @@ static int ssam_pos_get_sources_list(struct ssam_tablet_sw *sw, struct ssam_sour + rsp.length = 0; + rsp.pointer = (u8 *)sources; + +- status = ssam_retry(ssam_request_sync_onstack, sw->sdev->ctrl, &rqst, &rsp, 0); ++ status = ssam_retry(ssam_request_do_sync_onstack, sw->sdev->ctrl, &rqst, &rsp, 0); + if (status) + return status; + +diff --git a/include/linux/surface_aggregator/controller.h b/include/linux/surface_aggregator/controller.h +index 8932bc0bae187..cb7980805920a 100644 +--- a/include/linux/surface_aggregator/controller.h ++++ b/include/linux/surface_aggregator/controller.h +@@ -207,17 +207,17 @@ static inline int ssam_request_sync_wait(struct ssam_request_sync *rqst) + return rqst->status; + } + +-int ssam_request_sync(struct ssam_controller *ctrl, +- const struct ssam_request *spec, +- struct ssam_response *rsp); ++int ssam_request_do_sync(struct ssam_controller *ctrl, ++ const struct ssam_request *spec, ++ struct ssam_response *rsp); + +-int ssam_request_sync_with_buffer(struct ssam_controller *ctrl, +- const struct ssam_request *spec, +- struct ssam_response *rsp, +- struct ssam_span *buf); ++int ssam_request_do_sync_with_buffer(struct ssam_controller *ctrl, ++ const struct ssam_request *spec, ++ struct ssam_response *rsp, ++ struct ssam_span *buf); + + /** +- * ssam_request_sync_onstack - Execute a synchronous request on the stack. ++ * ssam_request_do_sync_onstack - Execute a synchronous request on the stack. + * @ctrl: The controller via which the request is submitted. + * @rqst: The request specification. + * @rsp: The response buffer. +@@ -227,7 +227,7 @@ int ssam_request_sync_with_buffer(struct ssam_controller *ctrl, + * fully initializes it via the provided request specification, submits it, + * and finally waits for its completion before returning its status. This + * helper macro essentially allocates the request message buffer on the stack +- * and then calls ssam_request_sync_with_buffer(). ++ * and then calls ssam_request_do_sync_with_buffer(). + * + * Note: The @payload_len parameter specifies the maximum payload length, used + * for buffer allocation. The actual payload length may be smaller. +@@ -235,12 +235,12 @@ int ssam_request_sync_with_buffer(struct ssam_controller *ctrl, + * Return: Returns the status of the request or any failure during setup, i.e. + * zero on success and a negative value on failure. + */ +-#define ssam_request_sync_onstack(ctrl, rqst, rsp, payload_len) \ ++#define ssam_request_do_sync_onstack(ctrl, rqst, rsp, payload_len) \ + ({ \ + u8 __data[SSH_COMMAND_MESSAGE_LENGTH(payload_len)]; \ + struct ssam_span __buf = { &__data[0], ARRAY_SIZE(__data) }; \ + \ +- ssam_request_sync_with_buffer(ctrl, rqst, rsp, &__buf); \ ++ ssam_request_do_sync_with_buffer(ctrl, rqst, rsp, &__buf); \ + }) + + /** +@@ -349,7 +349,7 @@ struct ssam_request_spec_md { + * zero on success and negative on failure. The ``ctrl`` parameter is the + * controller via which the request is being sent. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_N(name, spec...) \ +@@ -366,7 +366,7 @@ struct ssam_request_spec_md { + rqst.length = 0; \ + rqst.payload = NULL; \ + \ +- return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \ ++ return ssam_request_do_sync_onstack(ctrl, &rqst, NULL, 0); \ + } + + /** +@@ -389,7 +389,7 @@ struct ssam_request_spec_md { + * parameter is the controller via which the request is sent. The request + * argument is specified via the ``arg`` pointer. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_W(name, atype, spec...) \ +@@ -406,8 +406,8 @@ struct ssam_request_spec_md { + rqst.length = sizeof(atype); \ + rqst.payload = (u8 *)arg; \ + \ +- return ssam_request_sync_onstack(ctrl, &rqst, NULL, \ +- sizeof(atype)); \ ++ return ssam_request_do_sync_onstack(ctrl, &rqst, NULL, \ ++ sizeof(atype)); \ + } + + /** +@@ -430,7 +430,7 @@ struct ssam_request_spec_md { + * the controller via which the request is sent. The request's return value is + * written to the memory pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_R(name, rtype, spec...) \ +@@ -453,7 +453,7 @@ struct ssam_request_spec_md { + rsp.length = 0; \ + rsp.pointer = (u8 *)ret; \ + \ +- status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \ ++ status = ssam_request_do_sync_onstack(ctrl, &rqst, &rsp, 0); \ + if (status) \ + return status; \ + \ +@@ -491,7 +491,7 @@ struct ssam_request_spec_md { + * request argument is specified via the ``arg`` pointer. The request's return + * value is written to the memory pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_WR(name, atype, rtype, spec...) \ +@@ -514,7 +514,7 @@ struct ssam_request_spec_md { + rsp.length = 0; \ + rsp.pointer = (u8 *)ret; \ + \ +- status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, sizeof(atype)); \ ++ status = ssam_request_do_sync_onstack(ctrl, &rqst, &rsp, sizeof(atype)); \ + if (status) \ + return status; \ + \ +@@ -550,7 +550,7 @@ struct ssam_request_spec_md { + * parameter is the controller via which the request is sent, ``tid`` the + * target ID for the request, and ``iid`` the instance ID. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_MD_N(name, spec...) \ +@@ -567,7 +567,7 @@ struct ssam_request_spec_md { + rqst.length = 0; \ + rqst.payload = NULL; \ + \ +- return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \ ++ return ssam_request_do_sync_onstack(ctrl, &rqst, NULL, 0); \ + } + + /** +@@ -592,7 +592,7 @@ struct ssam_request_spec_md { + * ``tid`` the target ID for the request, and ``iid`` the instance ID. The + * request argument is specified via the ``arg`` pointer. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_MD_W(name, atype, spec...) \ +@@ -609,7 +609,7 @@ struct ssam_request_spec_md { + rqst.length = sizeof(atype); \ + rqst.payload = (u8 *)arg; \ + \ +- return ssam_request_sync_onstack(ctrl, &rqst, NULL, \ ++ return ssam_request_do_sync_onstack(ctrl, &rqst, NULL, \ + sizeof(atype)); \ + } + +@@ -635,7 +635,7 @@ struct ssam_request_spec_md { + * the target ID for the request, and ``iid`` the instance ID. The request's + * return value is written to the memory pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_MD_R(name, rtype, spec...) \ +@@ -658,7 +658,7 @@ struct ssam_request_spec_md { + rsp.length = 0; \ + rsp.pointer = (u8 *)ret; \ + \ +- status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \ ++ status = ssam_request_do_sync_onstack(ctrl, &rqst, &rsp, 0); \ + if (status) \ + return status; \ + \ +@@ -698,7 +698,7 @@ struct ssam_request_spec_md { + * The request argument is specified via the ``arg`` pointer. The request's + * return value is written to the memory pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_MD_WR(name, atype, rtype, spec...) \ +@@ -722,7 +722,7 @@ struct ssam_request_spec_md { + rsp.length = 0; \ + rsp.pointer = (u8 *)ret; \ + \ +- status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, sizeof(atype)); \ ++ status = ssam_request_do_sync_onstack(ctrl, &rqst, &rsp, sizeof(atype)); \ + if (status) \ + return status; \ + \ +diff --git a/include/linux/surface_aggregator/device.h b/include/linux/surface_aggregator/device.h +index 4da20b7a0ee5e..1545e5567b152 100644 +--- a/include/linux/surface_aggregator/device.h ++++ b/include/linux/surface_aggregator/device.h +@@ -456,7 +456,7 @@ static inline int ssam_device_register_clients(struct ssam_device *sdev) + * device of the request and by association the controller via which the + * request is sent. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_CL_N(name, spec...) \ +@@ -490,7 +490,7 @@ static inline int ssam_device_register_clients(struct ssam_device *sdev) + * which the request is sent. The request's argument is specified via the + * ``arg`` pointer. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_CL_W(name, atype, spec...) \ +@@ -524,7 +524,7 @@ static inline int ssam_device_register_clients(struct ssam_device *sdev) + * the request is sent. The request's return value is written to the memory + * pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_CL_R(name, rtype, spec...) \ +@@ -560,7 +560,7 @@ static inline int ssam_device_register_clients(struct ssam_device *sdev) + * specified via the ``arg`` pointer. The request's return value is written to + * the memory pointed to by the ``ret`` parameter. + * +- * Refer to ssam_request_sync_onstack() for more details on the behavior of ++ * Refer to ssam_request_do_sync_onstack() for more details on the behavior of + * the generated function. + */ + #define SSAM_DEFINE_SYNC_REQUEST_CL_WR(name, atype, rtype, spec...) \ +-- +2.40.0 + +From cbda18650bf1a358a7f55882abd9f523ed8b4b85 Mon Sep 17 00:00:00 2001 +From: Andy Shevchenko +Date: Wed, 18 Jan 2023 11:38:23 +0200 +Subject: [PATCH] platform/surface: Switch to use acpi_evaluate_dsm_typed() + +The acpi_evaluate_dsm_typed() provides a way to check the type of the +object evaluated by _DSM call. Use it instead of open coded variant. + +Signed-off-by: Andy Shevchenko +Reviewed-by: Maximilian Luz +Link: https://lore.kernel.org/r/20230118093823.39679-1-andriy.shevchenko@linux.intel.com +Reviewed-by: Hans de Goede +Signed-off-by: Hans de Goede +Patchset: surface-sam +--- + drivers/platform/surface/surface_hotplug.c | 13 +++---------- + 1 file changed, 3 insertions(+), 10 deletions(-) + +diff --git a/drivers/platform/surface/surface_hotplug.c b/drivers/platform/surface/surface_hotplug.c +index f004a24952013..7b6d887dccdbf 100644 +--- a/drivers/platform/surface/surface_hotplug.c ++++ b/drivers/platform/surface/surface_hotplug.c +@@ -101,18 +101,12 @@ static void shps_dsm_notify_irq(struct platform_device *pdev, enum shps_irq_type + param.type = ACPI_TYPE_INTEGER; + param.integer.value = value; + +- result = acpi_evaluate_dsm(handle, &shps_dsm_guid, SHPS_DSM_REVISION, +- shps_dsm_fn_for_irq(type), ¶m); +- ++ result = acpi_evaluate_dsm_typed(handle, &shps_dsm_guid, SHPS_DSM_REVISION, ++ shps_dsm_fn_for_irq(type), ¶m, ACPI_TYPE_BUFFER); + if (!result) { + dev_err(&pdev->dev, "IRQ notification via DSM failed (irq=%d, gpio=%d)\n", + type, value); + +- } else if (result->type != ACPI_TYPE_BUFFER) { +- dev_err(&pdev->dev, +- "IRQ notification via DSM failed: unexpected result type (irq=%d, gpio=%d)\n", +- type, value); +- + } else if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) { + dev_err(&pdev->dev, + "IRQ notification via DSM failed: unexpected result value (irq=%d, gpio=%d)\n", +@@ -121,8 +115,7 @@ static void shps_dsm_notify_irq(struct platform_device *pdev, enum shps_irq_type + + mutex_unlock(&sdev->lock[type]); + +- if (result) +- ACPI_FREE(result); ++ ACPI_FREE(result); + } + + static irqreturn_t shps_handle_irq(int irq, void *data) +-- +2.40.0 + +From 807bfac2ed7c426d2ee50b138cb12c3287b3d378 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sat, 4 Mar 2023 20:09:36 +0100 +Subject: [PATCH] platform/surface: aggregator_tabletsw: Properly handle + different posture source IDs + +The device posture subsystem (POS) can provide different posture +sources. Different sources can provide different posture states and +sources can be identified by their ID. + +For example, screen posture of the Surface Laptop Studio (SLS), which is +currently the only supported source, uses a source ID of 0x03. The +Surface Pro 9 uses the same subsystem for its Type-Cover, however, +provides different states for that under the ID 0x00. + +To eventually support the Surface Pro 9 and potential future devices, we +need to properly disambiguate between source IDs. Therefore, add the +source ID to the state we carry and determine the tablet-mode state (as +well as state names) based on that. + +Signed-off-by: Maximilian Luz +Patchset: surface-sam +--- + .../surface/surface_aggregator_tabletsw.c | 123 ++++++++++++------ + 1 file changed, 84 insertions(+), 39 deletions(-) + +diff --git a/drivers/platform/surface/surface_aggregator_tabletsw.c b/drivers/platform/surface/surface_aggregator_tabletsw.c +index 9fed800c7cc09..e8682f52558f3 100644 +--- a/drivers/platform/surface/surface_aggregator_tabletsw.c ++++ b/drivers/platform/surface/surface_aggregator_tabletsw.c +@@ -20,16 +20,23 @@ + + struct ssam_tablet_sw; + ++struct ssam_tablet_sw_state { ++ u32 source; ++ u32 state; ++}; ++ + struct ssam_tablet_sw_ops { +- int (*get_state)(struct ssam_tablet_sw *sw, u32 *state); +- const char *(*state_name)(struct ssam_tablet_sw *sw, u32 state); +- bool (*state_is_tablet_mode)(struct ssam_tablet_sw *sw, u32 state); ++ int (*get_state)(struct ssam_tablet_sw *sw, struct ssam_tablet_sw_state *state); ++ const char *(*state_name)(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state); ++ bool (*state_is_tablet_mode)(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state); + }; + + struct ssam_tablet_sw { + struct ssam_device *sdev; + +- u32 state; ++ struct ssam_tablet_sw_state state; + struct work_struct update_work; + struct input_dev *mode_switch; + +@@ -45,9 +52,11 @@ struct ssam_tablet_sw_desc { + + struct { + u32 (*notify)(struct ssam_event_notifier *nf, const struct ssam_event *event); +- int (*get_state)(struct ssam_tablet_sw *sw, u32 *state); +- const char *(*state_name)(struct ssam_tablet_sw *sw, u32 state); +- bool (*state_is_tablet_mode)(struct ssam_tablet_sw *sw, u32 state); ++ int (*get_state)(struct ssam_tablet_sw *sw, struct ssam_tablet_sw_state *state); ++ const char *(*state_name)(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state); ++ bool (*state_is_tablet_mode)(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state); + } ops; + + struct { +@@ -61,7 +70,7 @@ struct ssam_tablet_sw_desc { + static ssize_t state_show(struct device *dev, struct device_attribute *attr, char *buf) + { + struct ssam_tablet_sw *sw = dev_get_drvdata(dev); +- const char *state = sw->ops.state_name(sw, sw->state); ++ const char *state = sw->ops.state_name(sw, &sw->state); + + return sysfs_emit(buf, "%s\n", state); + } +@@ -79,19 +88,19 @@ static const struct attribute_group ssam_tablet_sw_group = { + static void ssam_tablet_sw_update_workfn(struct work_struct *work) + { + struct ssam_tablet_sw *sw = container_of(work, struct ssam_tablet_sw, update_work); ++ struct ssam_tablet_sw_state state; + int tablet, status; +- u32 state; + + status = sw->ops.get_state(sw, &state); + if (status) + return; + +- if (sw->state == state) ++ if (sw->state.source == state.source && sw->state.state == state.state) + return; + sw->state = state; + + /* Send SW_TABLET_MODE event. */ +- tablet = sw->ops.state_is_tablet_mode(sw, state); ++ tablet = sw->ops.state_is_tablet_mode(sw, &state); + input_report_switch(sw->mode_switch, SW_TABLET_MODE, tablet); + input_sync(sw->mode_switch); + } +@@ -146,7 +155,7 @@ static int ssam_tablet_sw_probe(struct ssam_device *sdev) + sw->mode_switch->id.bustype = BUS_HOST; + sw->mode_switch->dev.parent = &sdev->dev; + +- tablet = sw->ops.state_is_tablet_mode(sw, sw->state); ++ tablet = sw->ops.state_is_tablet_mode(sw, &sw->state); + input_set_capability(sw->mode_switch, EV_SW, SW_TABLET_MODE); + input_report_switch(sw->mode_switch, SW_TABLET_MODE, tablet); + +@@ -203,9 +212,10 @@ enum ssam_kip_cover_state { + SSAM_KIP_COVER_STATE_FOLDED_BACK = 0x05, + }; + +-static const char *ssam_kip_cover_state_name(struct ssam_tablet_sw *sw, u32 state) ++static const char *ssam_kip_cover_state_name(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state) + { +- switch (state) { ++ switch (state->state) { + case SSAM_KIP_COVER_STATE_DISCONNECTED: + return "disconnected"; + +@@ -222,14 +232,15 @@ static const char *ssam_kip_cover_state_name(struct ssam_tablet_sw *sw, u32 stat + return "folded-back"; + + default: +- dev_warn(&sw->sdev->dev, "unknown KIP cover state: %u\n", state); ++ dev_warn(&sw->sdev->dev, "unknown KIP cover state: %u\n", state->state); + return ""; + } + } + +-static bool ssam_kip_cover_state_is_tablet_mode(struct ssam_tablet_sw *sw, u32 state) ++static bool ssam_kip_cover_state_is_tablet_mode(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state) + { +- switch (state) { ++ switch (state->state) { + case SSAM_KIP_COVER_STATE_DISCONNECTED: + case SSAM_KIP_COVER_STATE_FOLDED_CANVAS: + case SSAM_KIP_COVER_STATE_FOLDED_BACK: +@@ -240,7 +251,7 @@ static bool ssam_kip_cover_state_is_tablet_mode(struct ssam_tablet_sw *sw, u32 s + return false; + + default: +- dev_warn(&sw->sdev->dev, "unknown KIP cover state: %d\n", sw->state); ++ dev_warn(&sw->sdev->dev, "unknown KIP cover state: %d\n", state->state); + return true; + } + } +@@ -252,7 +263,7 @@ SSAM_DEFINE_SYNC_REQUEST_R(__ssam_kip_get_cover_state, u8, { + .instance_id = 0x00, + }); + +-static int ssam_kip_get_cover_state(struct ssam_tablet_sw *sw, u32 *state) ++static int ssam_kip_get_cover_state(struct ssam_tablet_sw *sw, struct ssam_tablet_sw_state *state) + { + int status; + u8 raw; +@@ -263,7 +274,8 @@ static int ssam_kip_get_cover_state(struct ssam_tablet_sw *sw, u32 *state) + return status; + } + +- *state = raw; ++ state->source = 0; /* Unused for KIP switch. */ ++ state->state = raw; + return 0; + } + +@@ -312,11 +324,15 @@ MODULE_PARM_DESC(tablet_mode_in_slate_state, "Enable tablet mode in slate device + #define SSAM_EVENT_POS_CID_POSTURE_CHANGED 0x03 + #define SSAM_POS_MAX_SOURCES 4 + +-enum ssam_pos_state { +- SSAM_POS_POSTURE_LID_CLOSED = 0x00, +- SSAM_POS_POSTURE_LAPTOP = 0x01, +- SSAM_POS_POSTURE_SLATE = 0x02, +- SSAM_POS_POSTURE_TABLET = 0x03, ++enum ssam_pos_source_id { ++ SSAM_POS_SOURCE_SLS = 0x03, ++}; ++ ++enum ssam_pos_state_sls { ++ SSAM_POS_SLS_LID_CLOSED = 0x00, ++ SSAM_POS_SLS_LAPTOP = 0x01, ++ SSAM_POS_SLS_SLATE = 0x02, ++ SSAM_POS_SLS_TABLET = 0x03, + }; + + struct ssam_sources_list { +@@ -324,42 +340,68 @@ struct ssam_sources_list { + __le32 id[SSAM_POS_MAX_SOURCES]; + } __packed; + +-static const char *ssam_pos_state_name(struct ssam_tablet_sw *sw, u32 state) ++static const char *ssam_pos_state_name_sls(struct ssam_tablet_sw *sw, u32 state) + { + switch (state) { +- case SSAM_POS_POSTURE_LID_CLOSED: ++ case SSAM_POS_SLS_LID_CLOSED: + return "closed"; + +- case SSAM_POS_POSTURE_LAPTOP: ++ case SSAM_POS_SLS_LAPTOP: + return "laptop"; + +- case SSAM_POS_POSTURE_SLATE: ++ case SSAM_POS_SLS_SLATE: + return "slate"; + +- case SSAM_POS_POSTURE_TABLET: ++ case SSAM_POS_SLS_TABLET: + return "tablet"; + + default: +- dev_warn(&sw->sdev->dev, "unknown device posture: %u\n", state); ++ dev_warn(&sw->sdev->dev, "unknown device posture for SLS: %u\n", state); + return ""; + } + } + +-static bool ssam_pos_state_is_tablet_mode(struct ssam_tablet_sw *sw, u32 state) ++static const char *ssam_pos_state_name(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state) ++{ ++ switch (state->source) { ++ case SSAM_POS_SOURCE_SLS: ++ return ssam_pos_state_name_sls(sw, state->state); ++ ++ default: ++ dev_warn(&sw->sdev->dev, "unknown device posture source: %u\n", state->source); ++ return ""; ++ } ++} ++ ++static bool ssam_pos_state_is_tablet_mode_sls(struct ssam_tablet_sw *sw, u32 state) + { + switch (state) { +- case SSAM_POS_POSTURE_LAPTOP: +- case SSAM_POS_POSTURE_LID_CLOSED: ++ case SSAM_POS_SLS_LAPTOP: ++ case SSAM_POS_SLS_LID_CLOSED: + return false; + +- case SSAM_POS_POSTURE_SLATE: ++ case SSAM_POS_SLS_SLATE: + return tablet_mode_in_slate_state; + +- case SSAM_POS_POSTURE_TABLET: ++ case SSAM_POS_SLS_TABLET: + return true; + + default: +- dev_warn(&sw->sdev->dev, "unknown device posture: %u\n", state); ++ dev_warn(&sw->sdev->dev, "unknown device posture for SLS: %u\n", state); ++ return true; ++ } ++} ++ ++static bool ssam_pos_state_is_tablet_mode(struct ssam_tablet_sw *sw, ++ const struct ssam_tablet_sw_state *state) ++{ ++ switch (state->source) { ++ case SSAM_POS_SOURCE_SLS: ++ return ssam_pos_state_is_tablet_mode_sls(sw, state->state); ++ ++ default: ++ dev_warn(&sw->sdev->dev, "unknown device posture source: %u\n", state->source); + return true; + } + } +@@ -450,9 +492,10 @@ static int ssam_pos_get_posture_for_source(struct ssam_tablet_sw *sw, u32 source + return 0; + } + +-static int ssam_pos_get_posture(struct ssam_tablet_sw *sw, u32 *state) ++static int ssam_pos_get_posture(struct ssam_tablet_sw *sw, struct ssam_tablet_sw_state *state) + { + u32 source_id; ++ u32 source_state; + int status; + + status = ssam_pos_get_source(sw, &source_id); +@@ -461,13 +504,15 @@ static int ssam_pos_get_posture(struct ssam_tablet_sw *sw, u32 *state) + return status; + } + +- status = ssam_pos_get_posture_for_source(sw, source_id, state); ++ status = ssam_pos_get_posture_for_source(sw, source_id, &source_state); + if (status) { + dev_err(&sw->sdev->dev, "failed to get posture value for source %u: %d\n", + source_id, status); + return status; + } + ++ state->source = source_id; ++ state->state = source_state; + return 0; + } + +-- +2.40.0 + +From e02b980f674971a8a4e85bf910c7d6f50483d5d0 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sun, 19 Feb 2023 23:33:43 +0100 +Subject: [PATCH] platform/surface: aggregator_tabletsw: Add support for + Type-Cover posture source + +Implement support for the Type-Cover posture source (ID 0x00), found on +the Surface Pro 9. + +Signed-off-by: Maximilian Luz +Patchset: surface-sam +--- + .../surface/surface_aggregator_tabletsw.c | 57 +++++++++++++++++++ + 1 file changed, 57 insertions(+) + +diff --git a/drivers/platform/surface/surface_aggregator_tabletsw.c b/drivers/platform/surface/surface_aggregator_tabletsw.c +index e8682f52558f3..8f52b62d1c195 100644 +--- a/drivers/platform/surface/surface_aggregator_tabletsw.c ++++ b/drivers/platform/surface/surface_aggregator_tabletsw.c +@@ -325,9 +325,18 @@ MODULE_PARM_DESC(tablet_mode_in_slate_state, "Enable tablet mode in slate device + #define SSAM_POS_MAX_SOURCES 4 + + enum ssam_pos_source_id { ++ SSAM_POS_SOURCE_COVER = 0x00, + SSAM_POS_SOURCE_SLS = 0x03, + }; + ++enum ssam_pos_state_cover { ++ SSAM_POS_COVER_DISCONNECTED = 0x01, ++ SSAM_POS_COVER_CLOSED = 0x02, ++ SSAM_POS_COVER_LAPTOP = 0x03, ++ SSAM_POS_COVER_FOLDED_CANVAS = 0x04, ++ SSAM_POS_COVER_FOLDED_BACK = 0x05, ++}; ++ + enum ssam_pos_state_sls { + SSAM_POS_SLS_LID_CLOSED = 0x00, + SSAM_POS_SLS_LAPTOP = 0x01, +@@ -340,6 +349,30 @@ struct ssam_sources_list { + __le32 id[SSAM_POS_MAX_SOURCES]; + } __packed; + ++static const char *ssam_pos_state_name_cover(struct ssam_tablet_sw *sw, u32 state) ++{ ++ switch (state) { ++ case SSAM_POS_COVER_DISCONNECTED: ++ return "disconnected"; ++ ++ case SSAM_POS_COVER_CLOSED: ++ return "closed"; ++ ++ case SSAM_POS_COVER_LAPTOP: ++ return "laptop"; ++ ++ case SSAM_POS_COVER_FOLDED_CANVAS: ++ return "folded-canvas"; ++ ++ case SSAM_POS_COVER_FOLDED_BACK: ++ return "folded-back"; ++ ++ default: ++ dev_warn(&sw->sdev->dev, "unknown device posture for type-cover: %u\n", state); ++ return ""; ++ } ++} ++ + static const char *ssam_pos_state_name_sls(struct ssam_tablet_sw *sw, u32 state) + { + switch (state) { +@@ -365,6 +398,9 @@ static const char *ssam_pos_state_name(struct ssam_tablet_sw *sw, + const struct ssam_tablet_sw_state *state) + { + switch (state->source) { ++ case SSAM_POS_SOURCE_COVER: ++ return ssam_pos_state_name_cover(sw, state->state); ++ + case SSAM_POS_SOURCE_SLS: + return ssam_pos_state_name_sls(sw, state->state); + +@@ -374,6 +410,24 @@ static const char *ssam_pos_state_name(struct ssam_tablet_sw *sw, + } + } + ++static bool ssam_pos_state_is_tablet_mode_cover(struct ssam_tablet_sw *sw, u32 state) ++{ ++ switch (state) { ++ case SSAM_POS_COVER_DISCONNECTED: ++ case SSAM_POS_COVER_FOLDED_CANVAS: ++ case SSAM_POS_COVER_FOLDED_BACK: ++ return true; ++ ++ case SSAM_POS_COVER_CLOSED: ++ case SSAM_POS_COVER_LAPTOP: ++ return false; ++ ++ default: ++ dev_warn(&sw->sdev->dev, "unknown device posture for type-cover: %u\n", state); ++ return true; ++ } ++} ++ + static bool ssam_pos_state_is_tablet_mode_sls(struct ssam_tablet_sw *sw, u32 state) + { + switch (state) { +@@ -397,6 +451,9 @@ static bool ssam_pos_state_is_tablet_mode(struct ssam_tablet_sw *sw, + const struct ssam_tablet_sw_state *state) + { + switch (state->source) { ++ case SSAM_POS_SOURCE_COVER: ++ return ssam_pos_state_is_tablet_mode_cover(sw, state->state); ++ + case SSAM_POS_SOURCE_SLS: + return ssam_pos_state_is_tablet_mode_sls(sw, state->state); + +-- +2.40.0 + +From b9470768b196195f4e44378299c78f478dbb5096 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sun, 19 Feb 2023 23:41:18 +0100 +Subject: [PATCH] platform/surface: aggregator_registry: Add support for + tablet-mode switch on Surface Pro 9 + +Add support for the POS-subsystem tablet-mode switch used on the Surface +Pro 9. + +Signed-off-by: Maximilian Luz +Patchset: surface-sam +--- + drivers/platform/surface/surface_aggregator_registry.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/drivers/platform/surface/surface_aggregator_registry.c b/drivers/platform/surface/surface_aggregator_registry.c +index 296f72d52e6a6..0fe5be5396525 100644 +--- a/drivers/platform/surface/surface_aggregator_registry.c ++++ b/drivers/platform/surface/surface_aggregator_registry.c +@@ -305,7 +305,7 @@ static const struct software_node *ssam_node_group_sp9[] = { + &ssam_node_bat_ac, + &ssam_node_bat_main, + &ssam_node_tmp_pprof, +- /* TODO: Tablet mode switch (via POS subsystem) */ ++ &ssam_node_pos_tablet_switch, + &ssam_node_hid_kip_keyboard, + &ssam_node_hid_kip_penstash, + &ssam_node_hid_kip_touchpad, +-- +2.40.0 + diff --git a/patches/surface/0007-surface-sam-over-hid.patch b/patches/surface/0007-surface-sam-over-hid.patch new file mode 100644 index 0000000..7acd3c8 --- /dev/null +++ b/patches/surface/0007-surface-sam-over-hid.patch @@ -0,0 +1,335 @@ +From 210d383e29aee631650f951351fae9712da009ef Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sat, 25 Jul 2020 17:19:53 +0200 +Subject: [PATCH] i2c: acpi: Implement RawBytes read access + +Microsoft Surface Pro 4 and Book 1 devices access the MSHW0030 I2C +device via a generic serial bus operation region and RawBytes read +access. On the Surface Book 1, this access is required to turn on (and +off) the discrete GPU. + +Multiple things are to note here: + +a) The RawBytes access is device/driver dependent. The ACPI + specification states: + + > Raw accesses assume that the writer has knowledge of the bus that + > the access is made over and the device that is being accessed. The + > protocol may only ensure that the buffer is transmitted to the + > appropriate driver, but the driver must be able to interpret the + > buffer to communicate to a register. + + Thus this implementation may likely not work on other devices + accessing I2C via the RawBytes accessor type. + +b) The MSHW0030 I2C device is an HID-over-I2C device which seems to + serve multiple functions: + + 1. It is the main access point for the legacy-type Surface Aggregator + Module (also referred to as SAM-over-HID, as opposed to the newer + SAM-over-SSH/UART). It has currently not been determined on how + support for the legacy SAM should be implemented. Likely via a + custom HID driver. + + 2. It seems to serve as the HID device for the Integrated Sensor Hub. + This might complicate matters with regards to implementing a + SAM-over-HID driver required by legacy SAM. + +In light of this, the simplest approach has been chosen for now. +However, it may make more sense regarding breakage and compatibility to +either provide functionality for replacing or enhancing the default +operation region handler via some additional API functions, or even to +completely blacklist MSHW0030 from the I2C core and provide a custom +driver for it. + +Replacing/enhancing the default operation region handler would, however, +either require some sort of secondary driver and access point for it, +from which the new API functions would be called and the new handler +(part) would be installed, or hard-coding them via some sort of +quirk-like interface into the I2C core. + +Signed-off-by: Maximilian Luz +Patchset: surface-sam-over-hid +--- + drivers/i2c/i2c-core-acpi.c | 35 +++++++++++++++++++++++++++++++++++ + 1 file changed, 35 insertions(+) + +diff --git a/drivers/i2c/i2c-core-acpi.c b/drivers/i2c/i2c-core-acpi.c +index 4dd777cc0c89f..b2338618163ad 100644 +--- a/drivers/i2c/i2c-core-acpi.c ++++ b/drivers/i2c/i2c-core-acpi.c +@@ -639,6 +639,28 @@ static int acpi_gsb_i2c_write_bytes(struct i2c_client *client, + return (ret == 1) ? 0 : -EIO; + } + ++static int acpi_gsb_i2c_write_raw_bytes(struct i2c_client *client, ++ u8 *data, u8 data_len) ++{ ++ struct i2c_msg msgs[1]; ++ int ret = AE_OK; ++ ++ msgs[0].addr = client->addr; ++ msgs[0].flags = client->flags; ++ msgs[0].len = data_len + 1; ++ msgs[0].buf = data; ++ ++ ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); ++ ++ if (ret < 0) { ++ dev_err(&client->adapter->dev, "i2c write failed: %d\n", ret); ++ return ret; ++ } ++ ++ /* 1 transfer must have completed successfully */ ++ return (ret == 1) ? 0 : -EIO; ++} ++ + static acpi_status + i2c_acpi_space_handler(u32 function, acpi_physical_address command, + u32 bits, u64 *value64, +@@ -740,6 +762,19 @@ i2c_acpi_space_handler(u32 function, acpi_physical_address command, + } + break; + ++ case ACPI_GSB_ACCESS_ATTRIB_RAW_BYTES: ++ if (action == ACPI_READ) { ++ dev_warn(&adapter->dev, ++ "protocol 0x%02x not supported for client 0x%02x\n", ++ accessor_type, client->addr); ++ ret = AE_BAD_PARAMETER; ++ goto err; ++ } else { ++ status = acpi_gsb_i2c_write_raw_bytes(client, ++ gsb->data, info->access_length); ++ } ++ break; ++ + default: + dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n", + accessor_type, client->addr); +-- +2.40.0 + +From 40308d86e91a5396416b378ba73dd96d3f5d5dfa Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sat, 13 Feb 2021 16:41:18 +0100 +Subject: [PATCH] platform/surface: Add driver for Surface Book 1 dGPU switch + +Add driver exposing the discrete GPU power-switch of the Microsoft +Surface Book 1 to user-space. + +On the Surface Book 1, the dGPU power is controlled via the Surface +System Aggregator Module (SAM). The specific SAM-over-HID command for +this is exposed via ACPI. This module provides a simple driver exposing +the ACPI call via a sysfs parameter to user-space, so that users can +easily power-on/-off the dGPU. + +Patchset: surface-sam-over-hid +--- + drivers/platform/surface/Kconfig | 7 + + drivers/platform/surface/Makefile | 1 + + .../surface/surfacebook1_dgpu_switch.c | 162 ++++++++++++++++++ + 3 files changed, 170 insertions(+) + create mode 100644 drivers/platform/surface/surfacebook1_dgpu_switch.c + +diff --git a/drivers/platform/surface/Kconfig b/drivers/platform/surface/Kconfig +index b629e82af97c0..68656e8f309ed 100644 +--- a/drivers/platform/surface/Kconfig ++++ b/drivers/platform/surface/Kconfig +@@ -149,6 +149,13 @@ config SURFACE_AGGREGATOR_TABLET_SWITCH + Select M or Y here, if you want to provide tablet-mode switch input + events on the Surface Pro 8, Surface Pro X, and Surface Laptop Studio. + ++config SURFACE_BOOK1_DGPU_SWITCH ++ tristate "Surface Book 1 dGPU Switch Driver" ++ depends on SYSFS ++ help ++ This driver provides a sysfs switch to set the power-state of the ++ discrete GPU found on the Microsoft Surface Book 1. ++ + config SURFACE_DTX + tristate "Surface DTX (Detachment System) Driver" + depends on SURFACE_AGGREGATOR +diff --git a/drivers/platform/surface/Makefile b/drivers/platform/surface/Makefile +index 53344330939bf..7efcd0cdb5329 100644 +--- a/drivers/platform/surface/Makefile ++++ b/drivers/platform/surface/Makefile +@@ -12,6 +12,7 @@ obj-$(CONFIG_SURFACE_AGGREGATOR_CDEV) += surface_aggregator_cdev.o + obj-$(CONFIG_SURFACE_AGGREGATOR_HUB) += surface_aggregator_hub.o + obj-$(CONFIG_SURFACE_AGGREGATOR_REGISTRY) += surface_aggregator_registry.o + obj-$(CONFIG_SURFACE_AGGREGATOR_TABLET_SWITCH) += surface_aggregator_tabletsw.o ++obj-$(CONFIG_SURFACE_BOOK1_DGPU_SWITCH) += surfacebook1_dgpu_switch.o + obj-$(CONFIG_SURFACE_DTX) += surface_dtx.o + obj-$(CONFIG_SURFACE_GPE) += surface_gpe.o + obj-$(CONFIG_SURFACE_HOTPLUG) += surface_hotplug.o +diff --git a/drivers/platform/surface/surfacebook1_dgpu_switch.c b/drivers/platform/surface/surfacebook1_dgpu_switch.c +new file mode 100644 +index 0000000000000..8b816ed8f35c6 +--- /dev/null ++++ b/drivers/platform/surface/surfacebook1_dgpu_switch.c +@@ -0,0 +1,162 @@ ++// SPDX-License-Identifier: GPL-2.0-or-later ++ ++#include ++#include ++#include ++#include ++ ++ ++#ifdef pr_fmt ++#undef pr_fmt ++#endif ++#define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ ++ ++ ++static const guid_t dgpu_sw_guid = GUID_INIT(0x6fd05c69, 0xcde3, 0x49f4, ++ 0x95, 0xed, 0xab, 0x16, 0x65, 0x49, 0x80, 0x35); ++ ++#define DGPUSW_ACPI_PATH_DSM "\\_SB_.PCI0.LPCB.EC0_.VGBI" ++#define DGPUSW_ACPI_PATH_HGON "\\_SB_.PCI0.RP05.HGON" ++#define DGPUSW_ACPI_PATH_HGOF "\\_SB_.PCI0.RP05.HGOF" ++ ++ ++static int sb1_dgpu_sw_dsmcall(void) ++{ ++ union acpi_object *ret; ++ acpi_handle handle; ++ acpi_status status; ++ ++ status = acpi_get_handle(NULL, DGPUSW_ACPI_PATH_DSM, &handle); ++ if (status) ++ return -EINVAL; ++ ++ ret = acpi_evaluate_dsm_typed(handle, &dgpu_sw_guid, 1, 1, NULL, ACPI_TYPE_BUFFER); ++ if (!ret) ++ return -EINVAL; ++ ++ ACPI_FREE(ret); ++ return 0; ++} ++ ++static int sb1_dgpu_sw_hgon(void) ++{ ++ struct acpi_buffer buf = {ACPI_ALLOCATE_BUFFER, NULL}; ++ acpi_status status; ++ ++ status = acpi_evaluate_object(NULL, DGPUSW_ACPI_PATH_HGON, NULL, &buf); ++ if (status) { ++ pr_err("failed to run HGON: %d\n", status); ++ return -EINVAL; ++ } ++ ++ if (buf.pointer) ++ ACPI_FREE(buf.pointer); ++ ++ pr_info("turned-on dGPU via HGON\n"); ++ return 0; ++} ++ ++static int sb1_dgpu_sw_hgof(void) ++{ ++ struct acpi_buffer buf = {ACPI_ALLOCATE_BUFFER, NULL}; ++ acpi_status status; ++ ++ status = acpi_evaluate_object(NULL, DGPUSW_ACPI_PATH_HGOF, NULL, &buf); ++ if (status) { ++ pr_err("failed to run HGOF: %d\n", status); ++ return -EINVAL; ++ } ++ ++ if (buf.pointer) ++ ACPI_FREE(buf.pointer); ++ ++ pr_info("turned-off dGPU via HGOF\n"); ++ return 0; ++} ++ ++ ++static ssize_t dgpu_dsmcall_store(struct device *dev, struct device_attribute *attr, ++ const char *buf, size_t len) ++{ ++ int status, value; ++ ++ status = kstrtoint(buf, 0, &value); ++ if (status < 0) ++ return status; ++ ++ if (value != 1) ++ return -EINVAL; ++ ++ status = sb1_dgpu_sw_dsmcall(); ++ ++ return status < 0 ? status : len; ++} ++ ++static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr, ++ const char *buf, size_t len) ++{ ++ bool power; ++ int status; ++ ++ status = kstrtobool(buf, &power); ++ if (status < 0) ++ return status; ++ ++ if (power) ++ status = sb1_dgpu_sw_hgon(); ++ else ++ status = sb1_dgpu_sw_hgof(); ++ ++ return status < 0 ? status : len; ++} ++ ++static DEVICE_ATTR_WO(dgpu_dsmcall); ++static DEVICE_ATTR_WO(dgpu_power); ++ ++static struct attribute *sb1_dgpu_sw_attrs[] = { ++ &dev_attr_dgpu_dsmcall.attr, ++ &dev_attr_dgpu_power.attr, ++ NULL, ++}; ++ ++static const struct attribute_group sb1_dgpu_sw_attr_group = { ++ .attrs = sb1_dgpu_sw_attrs, ++}; ++ ++ ++static int sb1_dgpu_sw_probe(struct platform_device *pdev) ++{ ++ return sysfs_create_group(&pdev->dev.kobj, &sb1_dgpu_sw_attr_group); ++} ++ ++static int sb1_dgpu_sw_remove(struct platform_device *pdev) ++{ ++ sysfs_remove_group(&pdev->dev.kobj, &sb1_dgpu_sw_attr_group); ++ return 0; ++} ++ ++/* ++ * The dGPU power seems to be actually handled by MSHW0040. However, that is ++ * also the power-/volume-button device with a mainline driver. So let's use ++ * MSHW0041 instead for now, which seems to be the LTCH (latch/DTX) device. ++ */ ++static const struct acpi_device_id sb1_dgpu_sw_match[] = { ++ { "MSHW0041", }, ++ { }, ++}; ++MODULE_DEVICE_TABLE(acpi, sb1_dgpu_sw_match); ++ ++static struct platform_driver sb1_dgpu_sw = { ++ .probe = sb1_dgpu_sw_probe, ++ .remove = sb1_dgpu_sw_remove, ++ .driver = { ++ .name = "surfacebook1_dgpu_switch", ++ .acpi_match_table = sb1_dgpu_sw_match, ++ .probe_type = PROBE_PREFER_ASYNCHRONOUS, ++ }, ++}; ++module_platform_driver(sb1_dgpu_sw); ++ ++MODULE_AUTHOR("Maximilian Luz "); ++MODULE_DESCRIPTION("Discrete GPU Power-Switch for Surface Book 1"); ++MODULE_LICENSE("GPL"); +-- +2.40.0 + diff --git a/patches/surface/0008-surface-button.patch b/patches/surface/0008-surface-button.patch new file mode 100644 index 0000000..03ebb3a --- /dev/null +++ b/patches/surface/0008-surface-button.patch @@ -0,0 +1,149 @@ +From 95137da18e3280468a9ae8c8c08665c23d6331d3 Mon Sep 17 00:00:00 2001 +From: Sachi King +Date: Tue, 5 Oct 2021 00:05:09 +1100 +Subject: [PATCH] Input: soc_button_array - support AMD variant Surface devices + +The power button on the AMD variant of the Surface Laptop uses the +same MSHW0040 device ID as the 5th and later generation of Surface +devices, however they report 0 for their OEM platform revision. As the +_DSM does not exist on the devices requiring special casing, check for +the existance of the _DSM to determine if soc_button_array should be +loaded. + +Fixes: c394159310d0 ("Input: soc_button_array - add support for newer surface devices") +Co-developed-by: Maximilian Luz + +Signed-off-by: Sachi King +Patchset: surface-button +--- + drivers/input/misc/soc_button_array.c | 33 +++++++-------------------- + 1 file changed, 8 insertions(+), 25 deletions(-) + +diff --git a/drivers/input/misc/soc_button_array.c b/drivers/input/misc/soc_button_array.c +index 09489380afda7..0f02411a60f1c 100644 +--- a/drivers/input/misc/soc_button_array.c ++++ b/drivers/input/misc/soc_button_array.c +@@ -507,8 +507,8 @@ static const struct soc_device_data soc_device_MSHW0028 = { + * Both, the Surface Pro 4 (surfacepro3_button.c) and the above mentioned + * devices use MSHW0040 for power and volume buttons, however the way they + * have to be addressed differs. Make sure that we only load this drivers +- * for the correct devices by checking the OEM Platform Revision provided by +- * the _DSM method. ++ * for the correct devices by checking if the OEM Platform Revision DSM call ++ * exists. + */ + #define MSHW0040_DSM_REVISION 0x01 + #define MSHW0040_DSM_GET_OMPR 0x02 // get OEM Platform Revision +@@ -519,31 +519,14 @@ static const guid_t MSHW0040_DSM_UUID = + static int soc_device_check_MSHW0040(struct device *dev) + { + acpi_handle handle = ACPI_HANDLE(dev); +- union acpi_object *result; +- u64 oem_platform_rev = 0; // valid revisions are nonzero +- +- // get OEM platform revision +- result = acpi_evaluate_dsm_typed(handle, &MSHW0040_DSM_UUID, +- MSHW0040_DSM_REVISION, +- MSHW0040_DSM_GET_OMPR, NULL, +- ACPI_TYPE_INTEGER); +- +- if (result) { +- oem_platform_rev = result->integer.value; +- ACPI_FREE(result); +- } +- +- /* +- * If the revision is zero here, the _DSM evaluation has failed. This +- * indicates that we have a Pro 4 or Book 1 and this driver should not +- * be used. +- */ +- if (oem_platform_rev == 0) +- return -ENODEV; ++ bool exists; + +- dev_dbg(dev, "OEM Platform Revision %llu\n", oem_platform_rev); ++ // check if OEM platform revision DSM call exists ++ exists = acpi_check_dsm(handle, &MSHW0040_DSM_UUID, ++ MSHW0040_DSM_REVISION, ++ BIT(MSHW0040_DSM_GET_OMPR)); + +- return 0; ++ return exists ? 0 : -ENODEV; + } + + /* +-- +2.40.0 + +From 30283e8c20af0d8bdf9f7d7075ca85d34b4c8870 Mon Sep 17 00:00:00 2001 +From: Sachi King +Date: Tue, 5 Oct 2021 00:22:57 +1100 +Subject: [PATCH] platform/surface: surfacepro3_button: don't load on amd + variant + +The AMD variant of the Surface Laptop report 0 for their OEM platform +revision. The Surface devices that require the surfacepro3_button +driver do not have the _DSM that gets the OEM platform revision. If the +method does not exist, load surfacepro3_button. + +Fixes: 64dd243d7356 ("platform/x86: surfacepro3_button: Fix device check") +Co-developed-by: Maximilian Luz + +Signed-off-by: Sachi King +Patchset: surface-button +--- + drivers/platform/surface/surfacepro3_button.c | 30 ++++--------------- + 1 file changed, 6 insertions(+), 24 deletions(-) + +diff --git a/drivers/platform/surface/surfacepro3_button.c b/drivers/platform/surface/surfacepro3_button.c +index 2755601f979cd..4240c98ca2265 100644 +--- a/drivers/platform/surface/surfacepro3_button.c ++++ b/drivers/platform/surface/surfacepro3_button.c +@@ -149,7 +149,8 @@ static int surface_button_resume(struct device *dev) + /* + * Surface Pro 4 and Surface Book 2 / Surface Pro 2017 use the same device + * ID (MSHW0040) for the power/volume buttons. Make sure this is the right +- * device by checking for the _DSM method and OEM Platform Revision. ++ * device by checking for the _DSM method and OEM Platform Revision DSM ++ * function. + * + * Returns true if the driver should bind to this device, i.e. the device is + * either MSWH0028 (Pro 3) or MSHW0040 on a Pro 4 or Book 1. +@@ -157,30 +158,11 @@ static int surface_button_resume(struct device *dev) + static bool surface_button_check_MSHW0040(struct acpi_device *dev) + { + acpi_handle handle = dev->handle; +- union acpi_object *result; +- u64 oem_platform_rev = 0; // valid revisions are nonzero +- +- // get OEM platform revision +- result = acpi_evaluate_dsm_typed(handle, &MSHW0040_DSM_UUID, +- MSHW0040_DSM_REVISION, +- MSHW0040_DSM_GET_OMPR, +- NULL, ACPI_TYPE_INTEGER); +- +- /* +- * If evaluating the _DSM fails, the method is not present. This means +- * that we have either MSHW0028 or MSHW0040 on Pro 4 or Book 1, so we +- * should use this driver. We use revision 0 indicating it is +- * unavailable. +- */ +- +- if (result) { +- oem_platform_rev = result->integer.value; +- ACPI_FREE(result); +- } +- +- dev_dbg(&dev->dev, "OEM Platform Revision %llu\n", oem_platform_rev); + +- return oem_platform_rev == 0; ++ // make sure that OEM platform revision DSM call does not exist ++ return !acpi_check_dsm(handle, &MSHW0040_DSM_UUID, ++ MSHW0040_DSM_REVISION, ++ BIT(MSHW0040_DSM_GET_OMPR)); + } + + +-- +2.40.0 + diff --git a/patches/surface/0009-surface-typecover.patch b/patches/surface/0009-surface-typecover.patch new file mode 100644 index 0000000..5eb34b1 --- /dev/null +++ b/patches/surface/0009-surface-typecover.patch @@ -0,0 +1,574 @@ +From 3d290bb729d71c5952ccb275803d451e2bb6557a Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sat, 18 Feb 2023 01:02:49 +0100 +Subject: [PATCH] USB: quirks: Add USB_QUIRK_DELAY_INIT for Surface Go 3 + Type-Cover + +The touchpad on the Type-Cover of the Surface Go 3 is sometimes not +being initialized properly. Apply USB_QUIRK_DELAY_INIT to fix this +issue. + +More specifically, the device in question is a fairly standard modern +touchpad with pointer and touchpad input modes. During setup, the device +needs to be switched from pointer- to touchpad-mode (which is done in +hid-multitouch) to fully utilize it as intended. Unfortunately, however, +this seems to occasionally fail silently, leaving the device in +pointer-mode. Applying USB_QUIRK_DELAY_INIT seems to fix this. + +Link: https://github.com/linux-surface/linux-surface/issues/1059 +Signed-off-by: Maximilian Luz +Patchset: surface-typecover +--- + drivers/usb/core/quirks.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/drivers/usb/core/quirks.c b/drivers/usb/core/quirks.c +index 934b3d997702e..2c6604c6e8e12 100644 +--- a/drivers/usb/core/quirks.c ++++ b/drivers/usb/core/quirks.c +@@ -220,6 +220,9 @@ static const struct usb_device_id usb_quirk_list[] = { + /* Microsoft Surface Dock Ethernet (RTL8153 GigE) */ + { USB_DEVICE(0x045e, 0x07c6), .driver_info = USB_QUIRK_NO_LPM }, + ++ /* Microsoft Surface Go 3 Type-Cover */ ++ { USB_DEVICE(0x045e, 0x09b5), .driver_info = USB_QUIRK_DELAY_INIT }, ++ + /* Cherry Stream G230 2.0 (G85-231) and 3.0 (G85-232) */ + { USB_DEVICE(0x046a, 0x0023), .driver_info = USB_QUIRK_RESET_RESUME }, + +-- +2.40.0 + +From de05852c9a1295c7e8f415b6c12059fd9519b901 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?Jonas=20Dre=C3=9Fler?= +Date: Thu, 5 Nov 2020 13:09:45 +0100 +Subject: [PATCH] hid/multitouch: Turn off Type Cover keyboard backlight when + suspending + +The Type Cover for Microsoft Surface devices supports a special usb +control request to disable or enable the built-in keyboard backlight. +On Windows, this request happens when putting the device into suspend or +resuming it, without it the backlight of the Type Cover will remain +enabled for some time even though the computer is suspended, which looks +weird to the user. + +So add support for this special usb control request to hid-multitouch, +which is the driver that's handling the Type Cover. + +The reason we have to use a pm_notifier for this instead of the usual +suspend/resume methods is that those won't get called in case the usb +device is already autosuspended. + +Also, if the device is autosuspended, we have to briefly autoresume it +in order to send the request. Doing that should be fine, the usb-core +driver does something similar during suspend inside choose_wakeup(). + +To make sure we don't send that request to every device but only to +devices which support it, add a new quirk +MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER to hid-multitouch. For now this quirk +is only enabled for the usb id of the Surface Pro 2017 Type Cover, which +is where I confirmed that it's working. + +Patchset: surface-typecover +--- + drivers/hid/hid-multitouch.c | 100 ++++++++++++++++++++++++++++++++++- + 1 file changed, 98 insertions(+), 2 deletions(-) + +diff --git a/drivers/hid/hid-multitouch.c b/drivers/hid/hid-multitouch.c +index e31be0cb8b850..63fd042aba6ba 100644 +--- a/drivers/hid/hid-multitouch.c ++++ b/drivers/hid/hid-multitouch.c +@@ -34,7 +34,10 @@ + #include + #include + #include ++#include + #include ++#include ++#include + #include + #include + #include +@@ -47,6 +50,7 @@ MODULE_DESCRIPTION("HID multitouch panels"); + MODULE_LICENSE("GPL"); + + #include "hid-ids.h" ++#include "usbhid/usbhid.h" + + /* quirks to control the device */ + #define MT_QUIRK_NOT_SEEN_MEANS_UP BIT(0) +@@ -72,12 +76,15 @@ MODULE_LICENSE("GPL"); + #define MT_QUIRK_FORCE_MULTI_INPUT BIT(20) + #define MT_QUIRK_DISABLE_WAKEUP BIT(21) + #define MT_QUIRK_ORIENTATION_INVERT BIT(22) ++#define MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT BIT(23) + + #define MT_INPUTMODE_TOUCHSCREEN 0x02 + #define MT_INPUTMODE_TOUCHPAD 0x03 + + #define MT_BUTTONTYPE_CLICKPAD 0 + ++#define MS_TYPE_COVER_FEATURE_REPORT_USAGE 0xff050086 ++ + enum latency_mode { + HID_LATENCY_NORMAL = 0, + HID_LATENCY_HIGH = 1, +@@ -169,6 +176,8 @@ struct mt_device { + + struct list_head applications; + struct list_head reports; ++ ++ struct notifier_block pm_notifier; + }; + + static void mt_post_parse_default_settings(struct mt_device *td, +@@ -213,6 +222,7 @@ static void mt_post_parse(struct mt_device *td, struct mt_application *app); + #define MT_CLS_GOOGLE 0x0111 + #define MT_CLS_RAZER_BLADE_STEALTH 0x0112 + #define MT_CLS_SMART_TECH 0x0113 ++#define MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER 0x0114 + + #define MT_DEFAULT_MAXCONTACT 10 + #define MT_MAX_MAXCONTACT 250 +@@ -397,6 +407,16 @@ static const struct mt_class mt_classes[] = { + MT_QUIRK_CONTACT_CNT_ACCURATE | + MT_QUIRK_SEPARATE_APP_REPORT, + }, ++ { .name = MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER, ++ .quirks = MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT | ++ MT_QUIRK_ALWAYS_VALID | ++ MT_QUIRK_IGNORE_DUPLICATES | ++ MT_QUIRK_HOVERING | ++ MT_QUIRK_CONTACT_CNT_ACCURATE | ++ MT_QUIRK_STICKY_FINGERS | ++ MT_QUIRK_WIN8_PTP_BUTTONS, ++ .export_all_inputs = true ++ }, + { } + }; + +@@ -1728,6 +1748,69 @@ static void mt_expired_timeout(struct timer_list *t) + clear_bit_unlock(MT_IO_FLAGS_RUNNING, &td->mt_io_flags); + } + ++static void get_type_cover_backlight_field(struct hid_device *hdev, ++ struct hid_field **field) ++{ ++ struct hid_report_enum *rep_enum; ++ struct hid_report *rep; ++ struct hid_field *cur_field; ++ int i, j; ++ ++ rep_enum = &hdev->report_enum[HID_FEATURE_REPORT]; ++ list_for_each_entry(rep, &rep_enum->report_list, list) { ++ for (i = 0; i < rep->maxfield; i++) { ++ cur_field = rep->field[i]; ++ ++ for (j = 0; j < cur_field->maxusage; j++) { ++ if (cur_field->usage[j].hid ++ == MS_TYPE_COVER_FEATURE_REPORT_USAGE) { ++ *field = cur_field; ++ return; ++ } ++ } ++ } ++ } ++} ++ ++static void update_keyboard_backlight(struct hid_device *hdev, bool enabled) ++{ ++ struct usb_device *udev = hid_to_usb_dev(hdev); ++ struct hid_field *field = NULL; ++ ++ /* Wake up the device in case it's already suspended */ ++ pm_runtime_get_sync(&udev->dev); ++ ++ get_type_cover_backlight_field(hdev, &field); ++ if (!field) { ++ hid_err(hdev, "couldn't find backlight field\n"); ++ goto out; ++ } ++ ++ field->value[field->index] = enabled ? 0x01ff00ff : 0x00ff00ff; ++ hid_hw_request(hdev, field->report, HID_REQ_SET_REPORT); ++ ++out: ++ pm_runtime_put_sync(&udev->dev); ++} ++ ++static int mt_pm_notifier(struct notifier_block *notifier, ++ unsigned long pm_event, ++ void *unused) ++{ ++ struct mt_device *td = ++ container_of(notifier, struct mt_device, pm_notifier); ++ struct hid_device *hdev = td->hdev; ++ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT) { ++ if (pm_event == PM_SUSPEND_PREPARE) ++ update_keyboard_backlight(hdev, 0); ++ else if (pm_event == PM_POST_SUSPEND) ++ update_keyboard_backlight(hdev, 1); ++ } ++ ++ return NOTIFY_DONE; ++} ++ + static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + { + int ret, i; +@@ -1751,6 +1834,9 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + td->inputmode_value = MT_INPUTMODE_TOUCHSCREEN; + hid_set_drvdata(hdev, td); + ++ td->pm_notifier.notifier_call = mt_pm_notifier; ++ register_pm_notifier(&td->pm_notifier); ++ + INIT_LIST_HEAD(&td->applications); + INIT_LIST_HEAD(&td->reports); + +@@ -1789,15 +1875,19 @@ static int mt_probe(struct hid_device *hdev, const struct hid_device_id *id) + timer_setup(&td->release_timer, mt_expired_timeout, 0); + + ret = hid_parse(hdev); +- if (ret != 0) ++ if (ret != 0) { ++ unregister_pm_notifier(&td->pm_notifier); + return ret; ++ } + + if (mtclass->quirks & MT_QUIRK_FIX_CONST_CONTACT_ID) + mt_fix_const_fields(hdev, HID_DG_CONTACTID); + + ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); +- if (ret) ++ if (ret) { ++ unregister_pm_notifier(&td->pm_notifier); + return ret; ++ } + + ret = sysfs_create_group(&hdev->dev.kobj, &mt_attribute_group); + if (ret) +@@ -1849,6 +1939,7 @@ static void mt_remove(struct hid_device *hdev) + { + struct mt_device *td = hid_get_drvdata(hdev); + ++ unregister_pm_notifier(&td->pm_notifier); + del_timer_sync(&td->release_timer); + + sysfs_remove_group(&hdev->dev.kobj, &mt_attribute_group); +@@ -2226,6 +2317,11 @@ static const struct hid_device_id mt_devices[] = { + MT_USB_DEVICE(USB_VENDOR_ID_XIROKU, + USB_DEVICE_ID_XIROKU_CSR2) }, + ++ /* Microsoft Surface type cover */ ++ { .driver_data = MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER, ++ HID_DEVICE(HID_BUS_ANY, HID_GROUP_ANY, ++ USB_VENDOR_ID_MICROSOFT, 0x09c0) }, ++ + /* Google MT devices */ + { .driver_data = MT_CLS_GOOGLE, + HID_DEVICE(HID_BUS_ANY, HID_GROUP_ANY, USB_VENDOR_ID_GOOGLE, +-- +2.40.0 + +From f8bf8b278e663f3c7cfc269a1c5cffd7342a906b Mon Sep 17 00:00:00 2001 +From: PJungkamp +Date: Fri, 25 Feb 2022 12:04:25 +0100 +Subject: [PATCH] hid/multitouch: Add support for surface pro type cover tablet + switch + +The Surface Pro Type Cover has several non standard HID usages in it's +hid report descriptor. +I noticed that, upon folding the typecover back, a vendor specific range +of 4 32 bit integer hid usages is transmitted. +Only the first byte of the message seems to convey reliable information +about the keyboard state. + +0x22 => Normal (keys enabled) +0x33 => Folded back (keys disabled) +0x53 => Rotated left/right side up (keys disabled) +0x13 => Cover closed (keys disabled) +0x43 => Folded back and Tablet upside down (keys disabled) +This list may not be exhaustive. + +The tablet mode switch will be disabled for a value of 0x22 and enabled +on any other value. + +Patchset: surface-typecover +--- + drivers/hid/hid-multitouch.c | 148 +++++++++++++++++++++++++++++------ + 1 file changed, 122 insertions(+), 26 deletions(-) + +diff --git a/drivers/hid/hid-multitouch.c b/drivers/hid/hid-multitouch.c +index 63fd042aba6ba..508a250ff4bf1 100644 +--- a/drivers/hid/hid-multitouch.c ++++ b/drivers/hid/hid-multitouch.c +@@ -77,6 +77,7 @@ MODULE_LICENSE("GPL"); + #define MT_QUIRK_DISABLE_WAKEUP BIT(21) + #define MT_QUIRK_ORIENTATION_INVERT BIT(22) + #define MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT BIT(23) ++#define MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH BIT(24) + + #define MT_INPUTMODE_TOUCHSCREEN 0x02 + #define MT_INPUTMODE_TOUCHPAD 0x03 +@@ -84,6 +85,8 @@ MODULE_LICENSE("GPL"); + #define MT_BUTTONTYPE_CLICKPAD 0 + + #define MS_TYPE_COVER_FEATURE_REPORT_USAGE 0xff050086 ++#define MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE 0xff050072 ++#define MS_TYPE_COVER_APPLICATION 0xff050050 + + enum latency_mode { + HID_LATENCY_NORMAL = 0, +@@ -409,6 +412,7 @@ static const struct mt_class mt_classes[] = { + }, + { .name = MT_CLS_WIN_8_MS_SURFACE_TYPE_COVER, + .quirks = MT_QUIRK_HAS_TYPE_COVER_BACKLIGHT | ++ MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH | + MT_QUIRK_ALWAYS_VALID | + MT_QUIRK_IGNORE_DUPLICATES | + MT_QUIRK_HOVERING | +@@ -1390,6 +1394,9 @@ static int mt_input_mapping(struct hid_device *hdev, struct hid_input *hi, + field->application != HID_CP_CONSUMER_CONTROL && + field->application != HID_GD_WIRELESS_RADIO_CTLS && + field->application != HID_GD_SYSTEM_MULTIAXIS && ++ !(field->application == MS_TYPE_COVER_APPLICATION && ++ application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) && + !(field->application == HID_VD_ASUS_CUSTOM_MEDIA_KEYS && + application->quirks & MT_QUIRK_ASUS_CUSTOM_UP)) + return -1; +@@ -1417,6 +1424,21 @@ static int mt_input_mapping(struct hid_device *hdev, struct hid_input *hi, + return 1; + } + ++ /* ++ * The Microsoft Surface Pro Typecover has a non-standard HID ++ * tablet mode switch on a vendor specific usage page with vendor ++ * specific usage. ++ */ ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ usage->type = EV_SW; ++ usage->code = SW_TABLET_MODE; ++ *max = SW_MAX; ++ *bit = hi->input->swbit; ++ return 1; ++ } ++ + if (rdata->is_mt_collection) + return mt_touch_input_mapping(hdev, hi, field, usage, bit, max, + application); +@@ -1438,6 +1460,7 @@ static int mt_input_mapped(struct hid_device *hdev, struct hid_input *hi, + { + struct mt_device *td = hid_get_drvdata(hdev); + struct mt_report_data *rdata; ++ struct input_dev *input; + + rdata = mt_find_report_data(td, field->report); + if (rdata && rdata->is_mt_collection) { +@@ -1445,6 +1468,19 @@ static int mt_input_mapped(struct hid_device *hdev, struct hid_input *hi, + return -1; + } + ++ /* ++ * We own an input device which acts as a tablet mode switch for ++ * the Surface Pro Typecover. ++ */ ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ rdata->application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ input = hi->input; ++ input_set_capability(input, EV_SW, SW_TABLET_MODE); ++ input_report_switch(input, SW_TABLET_MODE, 0); ++ return -1; ++ } ++ + /* let hid-core decide for the others */ + return 0; + } +@@ -1454,11 +1490,21 @@ static int mt_event(struct hid_device *hid, struct hid_field *field, + { + struct mt_device *td = hid_get_drvdata(hid); + struct mt_report_data *rdata; ++ struct input_dev *input; + + rdata = mt_find_report_data(td, field->report); + if (rdata && rdata->is_mt_collection) + return mt_touch_event(hid, field, usage, value); + ++ if (field->application == MS_TYPE_COVER_APPLICATION && ++ rdata->application->quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH && ++ usage->hid == MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE) { ++ input = field->hidinput->input; ++ input_report_switch(input, SW_TABLET_MODE, (value & 0xFF) != 0x22); ++ input_sync(input); ++ return 1; ++ } ++ + return 0; + } + +@@ -1611,6 +1657,42 @@ static void mt_post_parse(struct mt_device *td, struct mt_application *app) + app->quirks &= ~MT_QUIRK_CONTACT_CNT_ACCURATE; + } + ++static int get_type_cover_field(struct hid_report_enum *rep_enum, ++ struct hid_field **field, int usage) ++{ ++ struct hid_report *rep; ++ struct hid_field *cur_field; ++ int i, j; ++ ++ list_for_each_entry(rep, &rep_enum->report_list, list) { ++ for (i = 0; i < rep->maxfield; i++) { ++ cur_field = rep->field[i]; ++ if (cur_field->application != MS_TYPE_COVER_APPLICATION) ++ continue; ++ for (j = 0; j < cur_field->maxusage; j++) { ++ if (cur_field->usage[j].hid == usage) { ++ *field = cur_field; ++ return true; ++ } ++ } ++ } ++ } ++ return false; ++} ++ ++static void request_type_cover_tablet_mode_switch(struct hid_device *hdev) ++{ ++ struct hid_field *field; ++ ++ if (get_type_cover_field(&hdev->report_enum[HID_INPUT_REPORT], ++ &field, ++ MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE)) { ++ hid_hw_request(hdev, field->report, HID_REQ_GET_REPORT); ++ } else { ++ hid_err(hdev, "couldn't find tablet mode field\n"); ++ } ++} ++ + static int mt_input_configured(struct hid_device *hdev, struct hid_input *hi) + { + struct mt_device *td = hid_get_drvdata(hdev); +@@ -1660,6 +1742,13 @@ static int mt_input_configured(struct hid_device *hdev, struct hid_input *hi) + /* force BTN_STYLUS to allow tablet matching in udev */ + __set_bit(BTN_STYLUS, hi->input->keybit); + break; ++ case MS_TYPE_COVER_APPLICATION: ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) { ++ suffix = "Tablet Mode Switch"; ++ request_type_cover_tablet_mode_switch(hdev); ++ break; ++ } ++ fallthrough; + default: + suffix = "UNKNOWN"; + break; +@@ -1748,30 +1837,6 @@ static void mt_expired_timeout(struct timer_list *t) + clear_bit_unlock(MT_IO_FLAGS_RUNNING, &td->mt_io_flags); + } + +-static void get_type_cover_backlight_field(struct hid_device *hdev, +- struct hid_field **field) +-{ +- struct hid_report_enum *rep_enum; +- struct hid_report *rep; +- struct hid_field *cur_field; +- int i, j; +- +- rep_enum = &hdev->report_enum[HID_FEATURE_REPORT]; +- list_for_each_entry(rep, &rep_enum->report_list, list) { +- for (i = 0; i < rep->maxfield; i++) { +- cur_field = rep->field[i]; +- +- for (j = 0; j < cur_field->maxusage; j++) { +- if (cur_field->usage[j].hid +- == MS_TYPE_COVER_FEATURE_REPORT_USAGE) { +- *field = cur_field; +- return; +- } +- } +- } +- } +-} +- + static void update_keyboard_backlight(struct hid_device *hdev, bool enabled) + { + struct usb_device *udev = hid_to_usb_dev(hdev); +@@ -1780,8 +1845,9 @@ static void update_keyboard_backlight(struct hid_device *hdev, bool enabled) + /* Wake up the device in case it's already suspended */ + pm_runtime_get_sync(&udev->dev); + +- get_type_cover_backlight_field(hdev, &field); +- if (!field) { ++ if (!get_type_cover_field(&hdev->report_enum[HID_FEATURE_REPORT], ++ &field, ++ MS_TYPE_COVER_FEATURE_REPORT_USAGE)) { + hid_err(hdev, "couldn't find backlight field\n"); + goto out; + } +@@ -1916,13 +1982,24 @@ static int mt_suspend(struct hid_device *hdev, pm_message_t state) + + static int mt_reset_resume(struct hid_device *hdev) + { ++ struct mt_device *td = hid_get_drvdata(hdev); ++ + mt_release_contacts(hdev); + mt_set_modes(hdev, HID_LATENCY_NORMAL, true, true); ++ ++ /* Request an update on the typecover folding state on resume ++ * after reset. ++ */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) ++ request_type_cover_tablet_mode_switch(hdev); ++ + return 0; + } + + static int mt_resume(struct hid_device *hdev) + { ++ struct mt_device *td = hid_get_drvdata(hdev); ++ + /* Some Elan legacy devices require SET_IDLE to be set on resume. + * It should be safe to send it to other devices too. + * Tested on 3M, Stantum, Cypress, Zytronic, eGalax, and Elan panels. */ +@@ -1931,6 +2008,10 @@ static int mt_resume(struct hid_device *hdev) + + mt_set_modes(hdev, HID_LATENCY_NORMAL, true, true); + ++ /* Request an update on the typecover folding state on resume. */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) ++ request_type_cover_tablet_mode_switch(hdev); ++ + return 0; + } + #endif +@@ -1938,6 +2019,21 @@ static int mt_resume(struct hid_device *hdev) + static void mt_remove(struct hid_device *hdev) + { + struct mt_device *td = hid_get_drvdata(hdev); ++ struct hid_field *field; ++ struct input_dev *input; ++ ++ /* Reset tablet mode switch on disconnect. */ ++ if (td->mtclass.quirks & MT_QUIRK_HAS_TYPE_COVER_TABLET_MODE_SWITCH) { ++ if (get_type_cover_field(&hdev->report_enum[HID_INPUT_REPORT], ++ &field, ++ MS_TYPE_COVER_TABLET_MODE_SWITCH_USAGE)) { ++ input = field->hidinput->input; ++ input_report_switch(input, SW_TABLET_MODE, 0); ++ input_sync(input); ++ } else { ++ hid_err(hdev, "couldn't find tablet mode field\n"); ++ } ++ } + + unregister_pm_notifier(&td->pm_notifier); + del_timer_sync(&td->release_timer); +-- +2.40.0 + diff --git a/patches/surface/0010-surface-shutdown.patch b/patches/surface/0010-surface-shutdown.patch new file mode 100644 index 0000000..a392139 --- /dev/null +++ b/patches/surface/0010-surface-shutdown.patch @@ -0,0 +1,97 @@ +From d335694ac0657ca040b1f2fa9799a16d862b2923 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sun, 19 Feb 2023 22:12:24 +0100 +Subject: [PATCH] PCI: Add quirk to prevent calling shutdown mehtod + +Work around buggy EFI firmware: On some Microsoft Surface devices +(Surface Pro 9 and Surface Laptop 5) the EFI ResetSystem call with +EFI_RESET_SHUTDOWN doesn't function properly. Instead of shutting the +system down, it returns and the system stays on. + +It turns out that this only happens after PCI shutdown callbacks ran for +specific devices. Excluding those devices from the shutdown process +makes the ResetSystem call work as expected. + +TODO: Maybe we can find a better way or the root cause of this? + +Not-Signed-off-by: Maximilian Luz +Patchset: surface-shutdown +--- + drivers/pci/pci-driver.c | 3 +++ + drivers/pci/quirks.c | 36 ++++++++++++++++++++++++++++++++++++ + include/linux/pci.h | 1 + + 3 files changed, 40 insertions(+) + +diff --git a/drivers/pci/pci-driver.c b/drivers/pci/pci-driver.c +index 7a19f11daca3a..e6b8c9ef7c216 100644 +--- a/drivers/pci/pci-driver.c ++++ b/drivers/pci/pci-driver.c +@@ -507,6 +507,9 @@ static void pci_device_shutdown(struct device *dev) + struct pci_dev *pci_dev = to_pci_dev(dev); + struct pci_driver *drv = pci_dev->driver; + ++ if (pci_dev->no_shutdown) ++ return; ++ + pm_runtime_resume(dev); + + if (drv && drv->shutdown) +diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c +index 494fa46f57671..106fb2ff855b2 100644 +--- a/drivers/pci/quirks.c ++++ b/drivers/pci/quirks.c +@@ -6015,3 +6015,39 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a2d, dpc_log_size); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a2f, dpc_log_size); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9a31, dpc_log_size); + #endif ++ ++static const struct dmi_system_id no_shutdown_dmi_table[] = { ++ /* ++ * Systems on which some devices should not be touched during shutdown. ++ */ ++ { ++ .ident = "Microsoft Surface Pro 9", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "Surface Pro 9"), ++ }, ++ }, ++ { ++ .ident = "Microsoft Surface Laptop 5", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 5"), ++ }, ++ }, ++ {} ++}; ++ ++static void quirk_no_shutdown(struct pci_dev *dev) ++{ ++ if (!dmi_check_system(no_shutdown_dmi_table)) ++ return; ++ ++ dev->no_shutdown = 1; ++ pci_info(dev, "disabling shutdown ops for [%04x:%04x]\n", ++ dev->vendor, dev->device); ++} ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x461e, quirk_no_shutdown); // Thunderbolt 4 USB Controller ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x461f, quirk_no_shutdown); // Thunderbolt 4 PCI Express Root Port ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x462f, quirk_no_shutdown); // Thunderbolt 4 PCI Express Root Port ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x466d, quirk_no_shutdown); // Thunderbolt 4 NHI ++DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x46a8, quirk_no_shutdown); // GPU +diff --git a/include/linux/pci.h b/include/linux/pci.h +index 7e8e8633ad905..a09234cf28796 100644 +--- a/include/linux/pci.h ++++ b/include/linux/pci.h +@@ -464,6 +464,7 @@ struct pci_dev { + unsigned int no_vf_scan:1; /* Don't scan for VFs after IOV enablement */ + unsigned int no_command_memory:1; /* No PCI_COMMAND_MEMORY */ + unsigned int rom_bar_overlap:1; /* ROM BAR disable broken */ ++ unsigned int no_shutdown:1; /* Do not touch device on shutdown */ + pci_dev_flags_t dev_flags; + atomic_t enable_cnt; /* pci_enable_device has been called */ + +-- +2.40.0 + diff --git a/patches/surface/0011-surface-gpe.patch b/patches/surface/0011-surface-gpe.patch new file mode 100644 index 0000000..1815611 --- /dev/null +++ b/patches/surface/0011-surface-gpe.patch @@ -0,0 +1,51 @@ +From bec43860c192a554c7923f82ddd6403d36aa9c1c Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Sun, 12 Mar 2023 01:41:57 +0100 +Subject: [PATCH] platform/surface: gpe: Add support for Surface Pro 9 + +Add the lid GPE used by the Surface Pro 9. + +Signed-off-by: Maximilian Luz +Patchset: surface-gpe +--- + drivers/platform/surface/surface_gpe.c | 17 +++++++++++++++++ + 1 file changed, 17 insertions(+) + +diff --git a/drivers/platform/surface/surface_gpe.c b/drivers/platform/surface/surface_gpe.c +index c219b840d491a..69c4352e8406b 100644 +--- a/drivers/platform/surface/surface_gpe.c ++++ b/drivers/platform/surface/surface_gpe.c +@@ -41,6 +41,11 @@ static const struct property_entry lid_device_props_l4F[] = { + {}, + }; + ++static const struct property_entry lid_device_props_l52[] = { ++ PROPERTY_ENTRY_U32("gpe", 0x52), ++ {}, ++}; ++ + static const struct property_entry lid_device_props_l57[] = { + PROPERTY_ENTRY_U32("gpe", 0x57), + {}, +@@ -107,6 +112,18 @@ static const struct dmi_system_id dmi_lid_device_table[] = { + }, + .driver_data = (void *)lid_device_props_l4B, + }, ++ { ++ /* ++ * We match for SKU here due to product name clash with the ARM ++ * version. ++ */ ++ .ident = "Surface Pro 9", ++ .matches = { ++ DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_9_2038"), ++ }, ++ .driver_data = (void *)lid_device_props_l52, ++ }, + { + .ident = "Surface Book 1", + .matches = { +-- +2.40.0 + diff --git a/patches/surface/0012-cameras.patch b/patches/surface/0012-cameras.patch new file mode 100644 index 0000000..57d7227 --- /dev/null +++ b/patches/surface/0012-cameras.patch @@ -0,0 +1,2943 @@ +From 56240912f92185264a4f3e509d962f3bf87d6de1 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Sun, 10 Oct 2021 20:56:57 +0200 +Subject: [PATCH] ACPI: delay enumeration of devices with a _DEP pointing to an + INT3472 device + +The clk and regulator frameworks expect clk/regulator consumer-devices +to have info about the consumed clks/regulators described in the device's +fw_node. + +To work around cases where this info is not present in the firmware tables, +which is often the case on x86/ACPI devices, both frameworks allow the +provider-driver to attach info about consumers to the clks/regulators +when registering these. + +This causes problems with the probe ordering wrt drivers for consumers +of these clks/regulators. Since the lookups are only registered when the +provider-driver binds, trying to get these clks/regulators before then +results in a -ENOENT error for clks and a dummy regulator for regulators. + +One case where we hit this issue is camera sensors such as e.g. the OV8865 +sensor found on the Microsoft Surface Go. The sensor uses clks, regulators +and GPIOs provided by a TPS68470 PMIC which is described in an INT3472 +ACPI device. There is special platform code handling this and setting +platform_data with the necessary consumer info on the MFD cells +instantiated for the PMIC under: drivers/platform/x86/intel/int3472. + +For this to work properly the ov8865 driver must not bind to the I2C-client +for the OV8865 sensor until after the TPS68470 PMIC gpio, regulator and +clk MFD cells have all been fully setup. + +The OV8865 on the Microsoft Surface Go is just one example, all X86 +devices using the Intel IPU3 camera block found on recent Intel SoCs +have similar issues where there is an INT3472 HID ACPI-device, which +describes the clks and regulators, and the driver for this INT3472 device +must be fully initialized before the sensor driver (any sensor driver) +binds for things to work properly. + +On these devices the ACPI nodes describing the sensors all have a _DEP +dependency on the matching INT3472 ACPI device (there is one per sensor). + +This allows solving the probe-ordering problem by delaying the enumeration +(instantiation of the I2C-client in the ov8865 example) of ACPI-devices +which have a _DEP dependency on an INT3472 device. + +The new acpi_dev_ready_for_enumeration() helper used for this is also +exported because for devices, which have the enumeration_by_parent flag +set, the parent-driver will do its own scan of child ACPI devices and +it will try to enumerate those during its probe(). Code doing this such +as e.g. the i2c-core-acpi.c code must call this new helper to ensure +that it too delays the enumeration until all the _DEP dependencies are +met on devices which have the new honor_deps flag set. + +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/acpi/scan.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/drivers/acpi/scan.c b/drivers/acpi/scan.c +index 0c6f06abe3f47..4fc320f424e8e 100644 +--- a/drivers/acpi/scan.c ++++ b/drivers/acpi/scan.c +@@ -2106,6 +2106,9 @@ static acpi_status acpi_bus_check_add_2(acpi_handle handle, u32 lvl_not_used, + + static void acpi_default_enumeration(struct acpi_device *device) + { ++ if (!acpi_dev_ready_for_enumeration(device)) ++ return; ++ + /* + * Do not enumerate devices with enumeration_by_parent flag set as + * they will be enumerated by their respective parents. +-- +2.40.0 + +From 9f596394ab56d947ca5de48c2f8128b05025fe46 Mon Sep 17 00:00:00 2001 +From: zouxiaoh +Date: Fri, 25 Jun 2021 08:52:59 +0800 +Subject: [PATCH] iommu: intel-ipu: use IOMMU passthrough mode for Intel IPUs + +Intel IPU(Image Processing Unit) has its own (IO)MMU hardware, +The IPU driver allocates its own page table that is not mapped +via the DMA, and thus the Intel IOMMU driver blocks access giving +this error: DMAR: DRHD: handling fault status reg 3 DMAR: +[DMA Read] Request device [00:05.0] PASID ffffffff +fault addr 76406000 [fault reason 06] PTE Read access is not set +As IPU is not an external facing device which is not risky, so use +IOMMU passthrough mode for Intel IPUs. + +Change-Id: I6dcccdadac308cf42e20a18e1b593381391e3e6b +Depends-On: Iacd67578e8c6a9b9ac73285f52b4081b72fb68a6 +Tracked-On: #JIITL8-411 +Signed-off-by: Bingbu Cao +Signed-off-by: zouxiaoh +Signed-off-by: Xu Chongyang +Patchset: cameras +--- + drivers/iommu/intel/iommu.c | 30 ++++++++++++++++++++++++++++++ + 1 file changed, 30 insertions(+) + +diff --git a/drivers/iommu/intel/iommu.c b/drivers/iommu/intel/iommu.c +index 08e35f9e67a62..a8f20384dfd4b 100644 +--- a/drivers/iommu/intel/iommu.c ++++ b/drivers/iommu/intel/iommu.c +@@ -37,6 +37,12 @@ + #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY) + #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB) + #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA) ++#define IS_INTEL_IPU(pdev) ((pdev)->vendor == PCI_VENDOR_ID_INTEL && \ ++ ((pdev)->device == 0x9a19 || \ ++ (pdev)->device == 0x9a39 || \ ++ (pdev)->device == 0x4e19 || \ ++ (pdev)->device == 0x465d || \ ++ (pdev)->device == 0x1919)) + #define IS_IPTS(pdev) ((pdev)->vendor == PCI_VENDOR_ID_INTEL && \ + ((pdev)->device == 0x9d3e)) + #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e) +@@ -290,12 +296,14 @@ EXPORT_SYMBOL_GPL(intel_iommu_enabled); + + static int dmar_map_gfx = 1; + static int dmar_map_ipts = 1; ++static int dmar_map_ipu = 1; + static int intel_iommu_superpage = 1; + static int iommu_identity_mapping; + static int iommu_skip_te_disable; + + #define IDENTMAP_GFX 2 + #define IDENTMAP_AZALIA 4 ++#define IDENTMAP_IPU 8 + #define IDENTMAP_IPTS 16 + + const struct iommu_ops intel_iommu_ops; +@@ -2589,6 +2597,9 @@ static int device_def_domain_type(struct device *dev) + if ((iommu_identity_mapping & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev)) + return IOMMU_DOMAIN_IDENTITY; + ++ if ((iommu_identity_mapping & IDENTMAP_IPU) && IS_INTEL_IPU(pdev)) ++ return IOMMU_DOMAIN_IDENTITY; ++ + if ((iommu_identity_mapping & IDENTMAP_IPTS) && IS_IPTS(pdev)) + return IOMMU_DOMAIN_IDENTITY; + } +@@ -2980,6 +2991,9 @@ static int __init init_dmars(void) + if (!dmar_map_gfx) + iommu_identity_mapping |= IDENTMAP_GFX; + ++ if (!dmar_map_ipu) ++ iommu_identity_mapping |= IDENTMAP_IPU; ++ + if (!dmar_map_ipts) + iommu_identity_mapping |= IDENTMAP_IPTS; + +@@ -4823,6 +4837,18 @@ static void quirk_iommu_igfx(struct pci_dev *dev) + dmar_map_gfx = 0; + } + ++static void quirk_iommu_ipu(struct pci_dev *dev) ++{ ++ if (!IS_INTEL_IPU(dev)) ++ return; ++ ++ if (risky_device(dev)) ++ return; ++ ++ pci_info(dev, "Passthrough IOMMU for integrated Intel IPU\n"); ++ dmar_map_ipu = 0; ++} ++ + static void quirk_iommu_ipts(struct pci_dev *dev) + { + if (!IS_IPTS(dev)) +@@ -4834,6 +4860,7 @@ static void quirk_iommu_ipts(struct pci_dev *dev) + pci_info(dev, "Passthrough IOMMU for IPTS\n"); + dmar_map_ipts = 0; + } ++ + /* G4x/GM45 integrated gfx dmar support is totally busted. */ + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_igfx); +@@ -4869,6 +4896,9 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1632, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163A, quirk_iommu_igfx); + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163D, quirk_iommu_igfx); + ++/* disable IPU dmar support */ ++DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_ANY_ID, quirk_iommu_ipu); ++ + /* disable IPTS dmar support */ + DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x9D3E, quirk_iommu_ipts); + +-- +2.40.0 + +From 7df4522c095c27ccbe662cd1e72e8e6116173d28 Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Sun, 10 Oct 2021 20:57:02 +0200 +Subject: [PATCH] platform/x86: int3472: Enable I2c daisy chain + +The TPS68470 PMIC has an I2C passthrough mode through which I2C traffic +can be forwarded to a device connected to the PMIC as though it were +connected directly to the system bus. Enable this mode when the chip +is initialised. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/platform/x86/intel/int3472/tps68470.c | 7 +++++++ + 1 file changed, 7 insertions(+) + +diff --git a/drivers/platform/x86/intel/int3472/tps68470.c b/drivers/platform/x86/intel/int3472/tps68470.c +index 5b8d1a9620a5d..6a0ff035cf209 100644 +--- a/drivers/platform/x86/intel/int3472/tps68470.c ++++ b/drivers/platform/x86/intel/int3472/tps68470.c +@@ -46,6 +46,13 @@ static int tps68470_chip_init(struct device *dev, struct regmap *regmap) + return ret; + } + ++ /* Enable I2C daisy chain */ ++ ret = regmap_write(regmap, TPS68470_REG_S_I2C_CTL, 0x03); ++ if (ret) { ++ dev_err(dev, "Failed to enable i2c daisy chain\n"); ++ return ret; ++ } ++ + dev_info(dev, "TPS68470 REVID: 0x%02x\n", version); + + return 0; +-- +2.40.0 + +From b5d9851b25d2f41c2d8b566a227695eb40e6eb3b Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Thu, 28 Oct 2021 21:55:16 +0100 +Subject: [PATCH] media: i2c: Add driver for DW9719 VCM + +Add a driver for the DW9719 VCM. The driver creates a v4l2 subdevice +and registers a control to set the desired focus. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + MAINTAINERS | 7 + + drivers/media/i2c/Kconfig | 11 + + drivers/media/i2c/Makefile | 1 + + drivers/media/i2c/dw9719.c | 425 +++++++++++++++++++++++++++++++++++++ + 4 files changed, 444 insertions(+) + create mode 100644 drivers/media/i2c/dw9719.c + +diff --git a/MAINTAINERS b/MAINTAINERS +index f77188f30210f..164d6078a6a32 100644 +--- a/MAINTAINERS ++++ b/MAINTAINERS +@@ -6362,6 +6362,13 @@ T: git git://linuxtv.org/media_tree.git + F: Documentation/devicetree/bindings/media/i2c/dongwoon,dw9714.yaml + F: drivers/media/i2c/dw9714.c + ++DONGWOON DW9719 LENS VOICE COIL DRIVER ++M: Daniel Scally ++L: linux-media@vger.kernel.org ++S: Maintained ++T: git git://linuxtv.org/media_tree.git ++F: drivers/media/i2c/dw9719.c ++ + DONGWOON DW9768 LENS VOICE COIL DRIVER + M: Dongchun Zhu + L: linux-media@vger.kernel.org +diff --git a/drivers/media/i2c/Kconfig b/drivers/media/i2c/Kconfig +index 833241897d637..8cfd7b6c4bf54 100644 +--- a/drivers/media/i2c/Kconfig ++++ b/drivers/media/i2c/Kconfig +@@ -847,6 +847,17 @@ config VIDEO_DW9714 + capability. This is designed for linear control of + voice coil motors, controlled via I2C serial interface. + ++config VIDEO_DW9719 ++ tristate "DW9719 lens voice coil support" ++ depends on I2C && VIDEO_V4L2 ++ select MEDIA_CONTROLLER ++ select VIDEO_V4L2_SUBDEV_API ++ select V4L2_ASYNC ++ help ++ This is a driver for the DW9719 camera lens voice coil. ++ This is designed for linear control of voice coil motors, ++ controlled via I2C serial interface. ++ + config VIDEO_DW9768 + tristate "DW9768 lens voice coil support" + depends on I2C && VIDEO_DEV +diff --git a/drivers/media/i2c/Makefile b/drivers/media/i2c/Makefile +index 4d6c052bb5a7f..29e4d61ce310f 100644 +--- a/drivers/media/i2c/Makefile ++++ b/drivers/media/i2c/Makefile +@@ -30,6 +30,7 @@ obj-$(CONFIG_VIDEO_CS5345) += cs5345.o + obj-$(CONFIG_VIDEO_CS53L32A) += cs53l32a.o + obj-$(CONFIG_VIDEO_CX25840) += cx25840/ + obj-$(CONFIG_VIDEO_DW9714) += dw9714.o ++obj-$(CONFIG_VIDEO_DW9719) += dw9719.o + obj-$(CONFIG_VIDEO_DW9768) += dw9768.o + obj-$(CONFIG_VIDEO_DW9807_VCM) += dw9807-vcm.o + obj-$(CONFIG_VIDEO_ET8EK8) += et8ek8/ +diff --git a/drivers/media/i2c/dw9719.c b/drivers/media/i2c/dw9719.c +new file mode 100644 +index 0000000000000..180b04d2a6b3a +--- /dev/null ++++ b/drivers/media/i2c/dw9719.c +@@ -0,0 +1,425 @@ ++// SPDX-License-Identifier: GPL-2.0 ++// Copyright (c) 2012 Intel Corporation ++ ++/* ++ * Based on linux/modules/camera/drivers/media/i2c/imx/dw9719.c in this repo: ++ * https://github.com/ZenfoneArea/android_kernel_asus_zenfone5 ++ */ ++ ++#include ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++#define DW9719_MAX_FOCUS_POS 1023 ++#define DW9719_CTRL_STEPS 16 ++#define DW9719_CTRL_DELAY_US 1000 ++#define DELAY_MAX_PER_STEP_NS (1000000 * 1023) ++ ++#define DW9719_INFO 0 ++#define DW9719_ID 0xF1 ++#define DW9719_CONTROL 2 ++#define DW9719_VCM_CURRENT 3 ++ ++#define DW9719_MODE 6 ++#define DW9719_VCM_FREQ 7 ++ ++#define DW9719_MODE_SAC3 0x40 ++#define DW9719_DEFAULT_VCM_FREQ 0x60 ++#define DW9719_ENABLE_RINGING 0x02 ++ ++#define NUM_REGULATORS 2 ++ ++#define to_dw9719_device(x) container_of(x, struct dw9719_device, sd) ++ ++struct dw9719_device { ++ struct device *dev; ++ struct i2c_client *client; ++ struct regulator_bulk_data regulators[NUM_REGULATORS]; ++ struct v4l2_subdev sd; ++ ++ struct dw9719_v4l2_ctrls { ++ struct v4l2_ctrl_handler handler; ++ struct v4l2_ctrl *focus; ++ } ctrls; ++}; ++ ++static int dw9719_i2c_rd8(struct i2c_client *client, u8 reg, u8 *val) ++{ ++ struct i2c_msg msg[2]; ++ u8 buf[2] = { reg }; ++ int ret; ++ ++ msg[0].addr = client->addr; ++ msg[0].flags = 0; ++ msg[0].len = 1; ++ msg[0].buf = buf; ++ ++ msg[1].addr = client->addr; ++ msg[1].flags = I2C_M_RD; ++ msg[1].len = 1; ++ msg[1].buf = &buf[1]; ++ *val = 0; ++ ++ ret = i2c_transfer(client->adapter, msg, 2); ++ if (ret < 0) ++ return ret; ++ ++ *val = buf[1]; ++ ++ return 0; ++} ++ ++static int dw9719_i2c_wr8(struct i2c_client *client, u8 reg, u8 val) ++{ ++ struct i2c_msg msg; ++ int ret; ++ ++ u8 buf[2] = { reg, val }; ++ ++ msg.addr = client->addr; ++ msg.flags = 0; ++ msg.len = sizeof(buf); ++ msg.buf = buf; ++ ++ ret = i2c_transfer(client->adapter, &msg, 1); ++ ++ return ret < 0 ? ret : 0; ++} ++ ++static int dw9719_i2c_wr16(struct i2c_client *client, u8 reg, u16 val) ++{ ++ struct i2c_msg msg; ++ u8 buf[3] = { reg }; ++ int ret; ++ ++ put_unaligned_be16(val, buf + 1); ++ ++ msg.addr = client->addr; ++ msg.flags = 0; ++ msg.len = sizeof(buf); ++ msg.buf = buf; ++ ++ ret = i2c_transfer(client->adapter, &msg, 1); ++ ++ return ret < 0 ? ret : 0; ++} ++ ++static int dw9719_detect(struct dw9719_device *dw9719) ++{ ++ int ret; ++ u8 val; ++ ++ ret = dw9719_i2c_rd8(dw9719->client, DW9719_INFO, &val); ++ if (ret < 0) ++ return ret; ++ ++ if (val != DW9719_ID) { ++ dev_err(dw9719->dev, "Failed to detect correct id\n"); ++ ret = -ENXIO; ++ } ++ ++ return 0; ++} ++ ++static int dw9719_power_down(struct dw9719_device *dw9719) ++{ ++ return regulator_bulk_disable(NUM_REGULATORS, dw9719->regulators); ++} ++ ++static int dw9719_power_up(struct dw9719_device *dw9719) ++{ ++ int ret; ++ ++ ret = regulator_bulk_enable(NUM_REGULATORS, dw9719->regulators); ++ if (ret) ++ return ret; ++ ++ /* Jiggle SCL pin to wake up device */ ++ ret = dw9719_i2c_wr8(dw9719->client, DW9719_CONTROL, 1); ++ ++ /* Need 100us to transit from SHUTDOWN to STANDBY*/ ++ usleep_range(100, 1000); ++ ++ ret = dw9719_i2c_wr8(dw9719->client, DW9719_CONTROL, ++ DW9719_ENABLE_RINGING); ++ if (ret < 0) ++ goto fail_powerdown; ++ ++ ret = dw9719_i2c_wr8(dw9719->client, DW9719_MODE, DW9719_MODE_SAC3); ++ if (ret < 0) ++ goto fail_powerdown; ++ ++ ret = dw9719_i2c_wr8(dw9719->client, DW9719_VCM_FREQ, ++ DW9719_DEFAULT_VCM_FREQ); ++ if (ret < 0) ++ goto fail_powerdown; ++ ++ return 0; ++ ++fail_powerdown: ++ dw9719_power_down(dw9719); ++ return ret; ++} ++ ++static int dw9719_t_focus_abs(struct dw9719_device *dw9719, s32 value) ++{ ++ int ret; ++ ++ value = clamp(value, 0, DW9719_MAX_FOCUS_POS); ++ ret = dw9719_i2c_wr16(dw9719->client, DW9719_VCM_CURRENT, value); ++ if (ret < 0) ++ return ret; ++ ++ return 0; ++} ++ ++static int dw9719_set_ctrl(struct v4l2_ctrl *ctrl) ++{ ++ struct dw9719_device *dw9719 = container_of(ctrl->handler, ++ struct dw9719_device, ++ ctrls.handler); ++ int ret; ++ ++ /* Only apply changes to the controls if the device is powered up */ ++ if (!pm_runtime_get_if_in_use(dw9719->dev)) ++ return 0; ++ ++ switch (ctrl->id) { ++ case V4L2_CID_FOCUS_ABSOLUTE: ++ ret = dw9719_t_focus_abs(dw9719, ctrl->val); ++ break; ++ default: ++ ret = -EINVAL; ++ } ++ ++ pm_runtime_put(dw9719->dev); ++ ++ return ret; ++} ++ ++static const struct v4l2_ctrl_ops dw9719_ctrl_ops = { ++ .s_ctrl = dw9719_set_ctrl, ++}; ++ ++static int __maybe_unused dw9719_suspend(struct device *dev) ++{ ++ struct v4l2_subdev *sd = dev_get_drvdata(dev); ++ struct dw9719_device *dw9719 = to_dw9719_device(sd); ++ int ret; ++ int val; ++ ++ for (val = dw9719->ctrls.focus->val; val >= 0; ++ val -= DW9719_CTRL_STEPS) { ++ ret = dw9719_t_focus_abs(dw9719, val); ++ if (ret) ++ return ret; ++ ++ usleep_range(DW9719_CTRL_DELAY_US, DW9719_CTRL_DELAY_US + 10); ++ } ++ ++ return dw9719_power_down(dw9719); ++} ++ ++static int __maybe_unused dw9719_resume(struct device *dev) ++{ ++ struct v4l2_subdev *sd = dev_get_drvdata(dev); ++ struct dw9719_device *dw9719 = to_dw9719_device(sd); ++ int current_focus = dw9719->ctrls.focus->val; ++ int ret; ++ int val; ++ ++ ret = dw9719_power_up(dw9719); ++ if (ret) ++ return ret; ++ ++ for (val = current_focus % DW9719_CTRL_STEPS; val < current_focus; ++ val += DW9719_CTRL_STEPS) { ++ ret = dw9719_t_focus_abs(dw9719, val); ++ if (ret) ++ goto err_power_down; ++ ++ usleep_range(DW9719_CTRL_DELAY_US, DW9719_CTRL_DELAY_US + 10); ++ } ++ ++ return 0; ++ ++err_power_down: ++ dw9719_power_down(dw9719); ++ return ret; ++} ++ ++static int dw9719_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) ++{ ++ return pm_runtime_resume_and_get(sd->dev); ++} ++ ++static int dw9719_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) ++{ ++ pm_runtime_put(sd->dev); ++ ++ return 0; ++} ++ ++static const struct v4l2_subdev_internal_ops dw9719_internal_ops = { ++ .open = dw9719_open, ++ .close = dw9719_close, ++}; ++ ++static int dw9719_init_controls(struct dw9719_device *dw9719) ++{ ++ const struct v4l2_ctrl_ops *ops = &dw9719_ctrl_ops; ++ int ret; ++ ++ ret = v4l2_ctrl_handler_init(&dw9719->ctrls.handler, 1); ++ if (ret) ++ return ret; ++ ++ dw9719->ctrls.focus = v4l2_ctrl_new_std(&dw9719->ctrls.handler, ops, ++ V4L2_CID_FOCUS_ABSOLUTE, 0, ++ DW9719_MAX_FOCUS_POS, 1, 0); ++ ++ if (dw9719->ctrls.handler.error) { ++ dev_err(dw9719->dev, "Error initialising v4l2 ctrls\n"); ++ ret = dw9719->ctrls.handler.error; ++ goto err_free_handler; ++ } ++ ++ dw9719->sd.ctrl_handler = &dw9719->ctrls.handler; ++ ++ return ret; ++ ++err_free_handler: ++ v4l2_ctrl_handler_free(&dw9719->ctrls.handler); ++ return ret; ++} ++ ++static const struct v4l2_subdev_ops dw9719_ops = { }; ++ ++static int dw9719_probe(struct i2c_client *client) ++{ ++ struct dw9719_device *dw9719; ++ int ret; ++ ++ dw9719 = devm_kzalloc(&client->dev, sizeof(*dw9719), GFP_KERNEL); ++ if (!dw9719) ++ return -ENOMEM; ++ ++ dw9719->client = client; ++ dw9719->dev = &client->dev; ++ ++ dw9719->regulators[0].supply = "vdd"; ++ /* ++ * The DW9719 has only the 1 VDD voltage input, but some PMICs such as ++ * the TPS68470 PMIC have I2C passthrough capability, to disconnect the ++ * sensor's I2C pins from the I2C bus when the sensors VSIO (Sensor-IO) ++ * is off, because some sensors then short these pins to ground; ++ * and the DW9719 might sit behind this passthrough, this it needs to ++ * enable VSIO as that will also enable the I2C passthrough. ++ */ ++ dw9719->regulators[1].supply = "vsio"; ++ ++ ret = devm_regulator_bulk_get(&client->dev, NUM_REGULATORS, ++ dw9719->regulators); ++ if (ret) ++ return dev_err_probe(&client->dev, ret, "getting regulators\n"); ++ ++ v4l2_i2c_subdev_init(&dw9719->sd, client, &dw9719_ops); ++ dw9719->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ++ dw9719->sd.internal_ops = &dw9719_internal_ops; ++ ++ ret = dw9719_init_controls(dw9719); ++ if (ret) ++ return ret; ++ ++ ret = media_entity_pads_init(&dw9719->sd.entity, 0, NULL); ++ if (ret < 0) ++ goto err_free_ctrl_handler; ++ ++ dw9719->sd.entity.function = MEDIA_ENT_F_LENS; ++ ++ /* ++ * We need the driver to work in the event that pm runtime is disable in ++ * the kernel, so power up and verify the chip now. In the event that ++ * runtime pm is disabled this will leave the chip on, so that the lens ++ * will work. ++ */ ++ ++ ret = dw9719_power_up(dw9719); ++ if (ret) ++ goto err_cleanup_media; ++ ++ ret = dw9719_detect(dw9719); ++ if (ret) ++ goto err_powerdown; ++ ++ pm_runtime_set_active(&client->dev); ++ pm_runtime_get_noresume(&client->dev); ++ pm_runtime_enable(&client->dev); ++ ++ ret = v4l2_async_register_subdev(&dw9719->sd); ++ if (ret < 0) ++ goto err_pm_runtime; ++ ++ pm_runtime_set_autosuspend_delay(&client->dev, 1000); ++ pm_runtime_use_autosuspend(&client->dev); ++ pm_runtime_put_autosuspend(&client->dev); ++ ++ return ret; ++ ++err_pm_runtime: ++ pm_runtime_disable(&client->dev); ++ pm_runtime_put_noidle(&client->dev); ++err_powerdown: ++ dw9719_power_down(dw9719); ++err_cleanup_media: ++ media_entity_cleanup(&dw9719->sd.entity); ++err_free_ctrl_handler: ++ v4l2_ctrl_handler_free(&dw9719->ctrls.handler); ++ ++ return ret; ++} ++ ++static void dw9719_remove(struct i2c_client *client) ++{ ++ struct v4l2_subdev *sd = i2c_get_clientdata(client); ++ struct dw9719_device *dw9719 = container_of(sd, struct dw9719_device, ++ sd); ++ ++ pm_runtime_disable(&client->dev); ++ v4l2_async_unregister_subdev(sd); ++ v4l2_ctrl_handler_free(&dw9719->ctrls.handler); ++ media_entity_cleanup(&dw9719->sd.entity); ++} ++ ++static const struct i2c_device_id dw9719_id_table[] = { ++ { "dw9719" }, ++ { } ++}; ++MODULE_DEVICE_TABLE(i2c, dw9719_id_table); ++ ++static const struct dev_pm_ops dw9719_pm_ops = { ++ SET_RUNTIME_PM_OPS(dw9719_suspend, dw9719_resume, NULL) ++}; ++ ++static struct i2c_driver dw9719_i2c_driver = { ++ .driver = { ++ .name = "dw9719", ++ .pm = &dw9719_pm_ops, ++ }, ++ .probe_new = dw9719_probe, ++ .remove = dw9719_remove, ++ .id_table = dw9719_id_table, ++}; ++module_i2c_driver(dw9719_i2c_driver); ++ ++MODULE_AUTHOR("Daniel Scally "); ++MODULE_DESCRIPTION("DW9719 VCM Driver"); ++MODULE_LICENSE("GPL"); +-- +2.40.0 + +From 1b9c5b1902d5dd389fced7a51649e88834ee4c45 Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Wed, 4 May 2022 23:21:45 +0100 +Subject: [PATCH] media: ipu3-cio2: Move functionality from .complete() to + .bound() + +Creating links and registering subdev nodes during the .complete() +callback has the unfortunate effect of preventing all cameras that +connect to a notifier from working if any one of their drivers fails +to probe. Moving the functionality from .complete() to .bound() allows +those camera sensor drivers that did probe correctly to work regardless. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/media/pci/intel/ipu3/ipu3-cio2-main.c | 65 +++++++------------ + 1 file changed, 23 insertions(+), 42 deletions(-) + +diff --git a/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c b/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c +index 3b76a9d0383a8..38f9f4da1922e 100644 +--- a/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c ++++ b/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c +@@ -1383,7 +1383,10 @@ static int cio2_notifier_bound(struct v4l2_async_notifier *notifier, + { + struct cio2_device *cio2 = to_cio2_device(notifier); + struct sensor_async_subdev *s_asd = to_sensor_asd(asd); ++ struct device *dev = &cio2->pci_dev->dev; + struct cio2_queue *q; ++ unsigned int pad; ++ int ret; + + if (cio2->queue[s_asd->csi2.port].sensor) + return -EBUSY; +@@ -1394,7 +1397,26 @@ static int cio2_notifier_bound(struct v4l2_async_notifier *notifier, + q->sensor = sd; + q->csi_rx_base = cio2->base + CIO2_REG_PIPE_BASE(q->csi2.port); + +- return 0; ++ for (pad = 0; pad < q->sensor->entity.num_pads; pad++) ++ if (q->sensor->entity.pads[pad].flags & ++ MEDIA_PAD_FL_SOURCE) ++ break; ++ ++ if (pad == q->sensor->entity.num_pads) { ++ dev_err(dev, "failed to find src pad for %s\n", ++ q->sensor->name); ++ return -ENXIO; ++ } ++ ++ ret = media_create_pad_link(&q->sensor->entity, pad, &q->subdev.entity, ++ CIO2_PAD_SINK, 0); ++ if (ret) { ++ dev_err(dev, "failed to create link for %s\n", ++ q->sensor->name); ++ return ret; ++ } ++ ++ return v4l2_device_register_subdev_nodes(&cio2->v4l2_dev); + } + + /* The .unbind callback */ +@@ -1408,50 +1430,9 @@ static void cio2_notifier_unbind(struct v4l2_async_notifier *notifier, + cio2->queue[s_asd->csi2.port].sensor = NULL; + } + +-/* .complete() is called after all subdevices have been located */ +-static int cio2_notifier_complete(struct v4l2_async_notifier *notifier) +-{ +- struct cio2_device *cio2 = to_cio2_device(notifier); +- struct device *dev = &cio2->pci_dev->dev; +- struct sensor_async_subdev *s_asd; +- struct v4l2_async_subdev *asd; +- struct cio2_queue *q; +- unsigned int pad; +- int ret; +- +- list_for_each_entry(asd, &cio2->notifier.asd_list, asd_list) { +- s_asd = to_sensor_asd(asd); +- q = &cio2->queue[s_asd->csi2.port]; +- +- for (pad = 0; pad < q->sensor->entity.num_pads; pad++) +- if (q->sensor->entity.pads[pad].flags & +- MEDIA_PAD_FL_SOURCE) +- break; +- +- if (pad == q->sensor->entity.num_pads) { +- dev_err(dev, "failed to find src pad for %s\n", +- q->sensor->name); +- return -ENXIO; +- } +- +- ret = media_create_pad_link( +- &q->sensor->entity, pad, +- &q->subdev.entity, CIO2_PAD_SINK, +- 0); +- if (ret) { +- dev_err(dev, "failed to create link for %s\n", +- q->sensor->name); +- return ret; +- } +- } +- +- return v4l2_device_register_subdev_nodes(&cio2->v4l2_dev); +-} +- + static const struct v4l2_async_notifier_operations cio2_async_ops = { + .bound = cio2_notifier_bound, + .unbind = cio2_notifier_unbind, +- .complete = cio2_notifier_complete, + }; + + static int cio2_parse_firmware(struct cio2_device *cio2) +-- +2.40.0 + +From f449b95f198517633020e069475fbbc29a192895 Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Thu, 2 Jun 2022 22:15:56 +0100 +Subject: [PATCH] media: ipu3-cio2: Re-add .complete() to ipu3-cio2 + +Removing the .complete() callback had some unintended consequences. +Because the VCM driver is not directly linked to the ipu3-cio2 +driver .bound() never gets called for it, which means its devnode +is never created if it probes late. Because .complete() waits for +any sub-notifiers to also be complete it is captured in that call. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/media/pci/intel/ipu3/ipu3-cio2-main.c | 9 +++++++++ + 1 file changed, 9 insertions(+) + +diff --git a/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c b/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c +index 38f9f4da1922e..82681df7d794f 100644 +--- a/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c ++++ b/drivers/media/pci/intel/ipu3/ipu3-cio2-main.c +@@ -1430,9 +1430,18 @@ static void cio2_notifier_unbind(struct v4l2_async_notifier *notifier, + cio2->queue[s_asd->csi2.port].sensor = NULL; + } + ++/* .complete() is called after all subdevices have been located */ ++static int cio2_notifier_complete(struct v4l2_async_notifier *notifier) ++{ ++ struct cio2_device *cio2 = to_cio2_device(notifier); ++ ++ return v4l2_device_register_subdev_nodes(&cio2->v4l2_dev); ++} ++ + static const struct v4l2_async_notifier_operations cio2_async_ops = { + .bound = cio2_notifier_bound, + .unbind = cio2_notifier_unbind, ++ .complete = cio2_notifier_complete, + }; + + static int cio2_parse_firmware(struct cio2_device *cio2) +-- +2.40.0 + +From 0ad6c3c8e0184919c51c4adb566969b9fe1e8288 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Fri, 15 Jul 2022 23:48:00 +0200 +Subject: [PATCH] drivers/media/i2c: Fix DW9719 dependencies + +It should depend on VIDEO_DEV instead of VIDEO_V4L2. + +Signed-off-by: Maximilian Luz +Patchset: cameras +--- + drivers/media/i2c/Kconfig | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/drivers/media/i2c/Kconfig b/drivers/media/i2c/Kconfig +index 8cfd7b6c4bf54..11b8acd7cc5fe 100644 +--- a/drivers/media/i2c/Kconfig ++++ b/drivers/media/i2c/Kconfig +@@ -849,7 +849,7 @@ config VIDEO_DW9714 + + config VIDEO_DW9719 + tristate "DW9719 lens voice coil support" +- depends on I2C && VIDEO_V4L2 ++ depends on I2C && VIDEO_DEV + select MEDIA_CONTROLLER + select VIDEO_V4L2_SUBDEV_API + select V4L2_ASYNC +-- +2.40.0 + +From 72a302f12c71d49515f4a2fbf554160f6470c990 Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Thu, 2 Mar 2023 12:59:39 +0000 +Subject: [PATCH] platform/x86: int3472: Remap reset GPIO for INT347E + +ACPI _HID INT347E represents the OmniVision 7251 camera sensor. The +driver for this sensor expects a single pin named "enable", but on +some Microsoft Surface platforms the sensor is assigned a single +GPIO who's type flag is INT3472_GPIO_TYPE_RESET. + +Remap the GPIO pin's function from "reset" to "enable". This is done +outside of the existing remap table since it is a more widespread +discrepancy than that method is designed for. Additionally swap the +polarity of the pin to match the driver's expectation. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/platform/x86/intel/int3472/discrete.c | 14 ++++++++++++++ + 1 file changed, 14 insertions(+) + +diff --git a/drivers/platform/x86/intel/int3472/discrete.c b/drivers/platform/x86/intel/int3472/discrete.c +index c42c3faa2c32d..6f4b8e24eb56c 100644 +--- a/drivers/platform/x86/intel/int3472/discrete.c ++++ b/drivers/platform/x86/intel/int3472/discrete.c +@@ -108,6 +108,9 @@ static int skl_int3472_map_gpio_to_sensor(struct int3472_discrete_device *int347 + { + const struct int3472_sensor_config *sensor_config; + char *path = agpio->resource_source.string_ptr; ++ const struct acpi_device_id ov7251_ids[] = { ++ { "INT347E" }, ++ }; + struct gpiod_lookup *table_entry; + struct acpi_device *adev; + acpi_handle handle; +@@ -130,6 +133,17 @@ static int skl_int3472_map_gpio_to_sensor(struct int3472_discrete_device *int347 + } + } + ++ /* ++ * In addition to the function remap table we need to bulk remap the ++ * "reset" GPIO for the OmniVision 7251 sensor, as the driver for that ++ * expects its only GPIO pin to be called "enable" (and to have the ++ * opposite polarity). ++ */ ++ if (!strcmp(func, "reset") && !acpi_match_device_ids(int3472->sensor, ov7251_ids)) { ++ func = "enable"; ++ polarity = GPIO_ACTIVE_HIGH; ++ } ++ + /* Functions mapped to NULL should not be mapped to the sensor */ + if (!func) + return 0; +-- +2.40.0 + +From e906323a5b30c2b942e2af09765e549ed0e4c528 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 20 Jan 2023 12:45:15 +0100 +Subject: [PATCH] leds: led-class: Add led_module_get() helper + +Split out part of of_led_get() into a generic led_module_get() helper +function. + +This is a preparation patch for adding a generic (non devicetree specific) +led_get() function. + +Reviewed-by: Andy Shevchenko +Reviewed-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/leds/led-class.c | 31 ++++++++++++++++++------------- + 1 file changed, 18 insertions(+), 13 deletions(-) + +diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c +index aa39b2a48fdff..743d97b082dcb 100644 +--- a/drivers/leds/led-class.c ++++ b/drivers/leds/led-class.c +@@ -215,6 +215,23 @@ static int led_resume(struct device *dev) + + static SIMPLE_DEV_PM_OPS(leds_class_dev_pm_ops, led_suspend, led_resume); + ++static struct led_classdev *led_module_get(struct device *led_dev) ++{ ++ struct led_classdev *led_cdev; ++ ++ if (!led_dev) ++ return ERR_PTR(-EPROBE_DEFER); ++ ++ led_cdev = dev_get_drvdata(led_dev); ++ ++ if (!try_module_get(led_cdev->dev->parent->driver->owner)) { ++ put_device(led_cdev->dev); ++ return ERR_PTR(-ENODEV); ++ } ++ ++ return led_cdev; ++} ++ + /** + * of_led_get() - request a LED device via the LED framework + * @np: device node to get the LED device from +@@ -226,7 +243,6 @@ static SIMPLE_DEV_PM_OPS(leds_class_dev_pm_ops, led_suspend, led_resume); + struct led_classdev *of_led_get(struct device_node *np, int index) + { + struct device *led_dev; +- struct led_classdev *led_cdev; + struct device_node *led_node; + + led_node = of_parse_phandle(np, "leds", index); +@@ -235,19 +251,8 @@ struct led_classdev *of_led_get(struct device_node *np, int index) + + led_dev = class_find_device_by_of_node(leds_class, led_node); + of_node_put(led_node); +- put_device(led_dev); +- +- if (!led_dev) +- return ERR_PTR(-EPROBE_DEFER); +- +- led_cdev = dev_get_drvdata(led_dev); + +- if (!try_module_get(led_cdev->dev->parent->driver->owner)) { +- put_device(led_cdev->dev); +- return ERR_PTR(-ENODEV); +- } +- +- return led_cdev; ++ return led_module_get(led_dev); + } + EXPORT_SYMBOL_GPL(of_led_get); + +-- +2.40.0 + +From e90a4c3af7b393ee587006a73738c47b0937e537 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 20 Jan 2023 12:45:16 +0100 +Subject: [PATCH] leds: led-class: Add __devm_led_get() helper + +Add a __devm_led_get() helper which registers a passed in led_classdev +with devm for unregistration. + +This is a preparation patch for adding a generic (non devicetree specific) +devm_led_get() function. + +Reviewed-by: Andy Shevchenko +Reviewed-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/leds/led-class.c | 29 +++++++++++++++++------------ + 1 file changed, 17 insertions(+), 12 deletions(-) + +diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c +index 743d97b082dcb..4904d140a560a 100644 +--- a/drivers/leds/led-class.c ++++ b/drivers/leds/led-class.c +@@ -274,6 +274,22 @@ static void devm_led_release(struct device *dev, void *res) + led_put(*p); + } + ++static struct led_classdev *__devm_led_get(struct device *dev, struct led_classdev *led) ++{ ++ struct led_classdev **dr; ++ ++ dr = devres_alloc(devm_led_release, sizeof(struct led_classdev *), GFP_KERNEL); ++ if (!dr) { ++ led_put(led); ++ return ERR_PTR(-ENOMEM); ++ } ++ ++ *dr = led; ++ devres_add(dev, dr); ++ ++ return led; ++} ++ + /** + * devm_of_led_get - Resource-managed request of a LED device + * @dev: LED consumer +@@ -289,7 +305,6 @@ struct led_classdev *__must_check devm_of_led_get(struct device *dev, + int index) + { + struct led_classdev *led; +- struct led_classdev **dr; + + if (!dev) + return ERR_PTR(-EINVAL); +@@ -298,17 +313,7 @@ struct led_classdev *__must_check devm_of_led_get(struct device *dev, + if (IS_ERR(led)) + return led; + +- dr = devres_alloc(devm_led_release, sizeof(struct led_classdev *), +- GFP_KERNEL); +- if (!dr) { +- led_put(led); +- return ERR_PTR(-ENOMEM); +- } +- +- *dr = led; +- devres_add(dev, dr); +- +- return led; ++ return __devm_led_get(dev, led); + } + EXPORT_SYMBOL_GPL(devm_of_led_get); + +-- +2.40.0 + +From 2fd15407f1aebf2344211d9789644d0cc8cfe7c1 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 20 Jan 2023 12:45:17 +0100 +Subject: [PATCH] leds: led-class: Add generic [devm_]led_get() + +Add a generic [devm_]led_get() method which can be used on both devicetree +and non devicetree platforms to get a LED classdev associated with +a specific function on a specific device, e.g. the privacy LED associated +with a specific camera sensor. + +Note unlike of_led_get() this takes a string describing the function +rather then an index. This is done because e.g. camera sensors might +have a privacy LED, or a flash LED, or both and using an index +approach leaves it unclear what the function of index 0 is if there is +only 1 LED. + +This uses a lookup-table mechanism for non devicetree platforms. +This allows the platform code to map specific LED class_dev-s to a specific +device,function combinations this way. + +For devicetree platforms getting the LED by function-name could be made +to work using the standard devicetree pattern of adding a -names string +array to map names to the indexes. + +Reviewed-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/leds/led-class.c | 84 ++++++++++++++++++++++++++++++++++++++++ + include/linux/leds.h | 21 ++++++++++ + 2 files changed, 105 insertions(+) + +diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c +index 4904d140a560a..0c4b8d8d2b4fe 100644 +--- a/drivers/leds/led-class.c ++++ b/drivers/leds/led-class.c +@@ -23,6 +23,8 @@ + #include "leds.h" + + static struct class *leds_class; ++static DEFINE_MUTEX(leds_lookup_lock); ++static LIST_HEAD(leds_lookup_list); + + static ssize_t brightness_show(struct device *dev, + struct device_attribute *attr, char *buf) +@@ -317,6 +319,88 @@ struct led_classdev *__must_check devm_of_led_get(struct device *dev, + } + EXPORT_SYMBOL_GPL(devm_of_led_get); + ++/** ++ * led_get() - request a LED device via the LED framework ++ * @dev: device for which to get the LED device ++ * @con_id: name of the LED from the device's point of view ++ * ++ * @return a pointer to a LED device or ERR_PTR(errno) on failure. ++ */ ++struct led_classdev *led_get(struct device *dev, char *con_id) ++{ ++ struct led_lookup_data *lookup; ++ const char *provider = NULL; ++ struct device *led_dev; ++ ++ mutex_lock(&leds_lookup_lock); ++ list_for_each_entry(lookup, &leds_lookup_list, list) { ++ if (!strcmp(lookup->dev_id, dev_name(dev)) && ++ !strcmp(lookup->con_id, con_id)) { ++ provider = kstrdup_const(lookup->provider, GFP_KERNEL); ++ break; ++ } ++ } ++ mutex_unlock(&leds_lookup_lock); ++ ++ if (!provider) ++ return ERR_PTR(-ENOENT); ++ ++ led_dev = class_find_device_by_name(leds_class, provider); ++ kfree_const(provider); ++ ++ return led_module_get(led_dev); ++} ++EXPORT_SYMBOL_GPL(led_get); ++ ++/** ++ * devm_led_get() - request a LED device via the LED framework ++ * @dev: device for which to get the LED device ++ * @con_id: name of the LED from the device's point of view ++ * ++ * The LED device returned from this function is automatically released ++ * on driver detach. ++ * ++ * @return a pointer to a LED device or ERR_PTR(errno) on failure. ++ */ ++struct led_classdev *devm_led_get(struct device *dev, char *con_id) ++{ ++ struct led_classdev *led; ++ ++ led = led_get(dev, con_id); ++ if (IS_ERR(led)) ++ return led; ++ ++ return __devm_led_get(dev, led); ++} ++EXPORT_SYMBOL_GPL(devm_led_get); ++ ++/** ++ * led_add_lookup() - Add a LED lookup table entry ++ * @led_lookup: the lookup table entry to add ++ * ++ * Add a LED lookup table entry. On systems without devicetree the lookup table ++ * is used by led_get() to find LEDs. ++ */ ++void led_add_lookup(struct led_lookup_data *led_lookup) ++{ ++ mutex_lock(&leds_lookup_lock); ++ list_add_tail(&led_lookup->list, &leds_lookup_list); ++ mutex_unlock(&leds_lookup_lock); ++} ++EXPORT_SYMBOL_GPL(led_add_lookup); ++ ++/** ++ * led_remove_lookup() - Remove a LED lookup table entry ++ * @led_lookup: the lookup table entry to remove ++ */ ++void led_remove_lookup(struct led_lookup_data *led_lookup) ++{ ++ mutex_lock(&leds_lookup_lock); ++ list_del(&led_lookup->list); ++ mutex_unlock(&leds_lookup_lock); ++} ++EXPORT_SYMBOL_GPL(led_remove_lookup); ++ + static int led_classdev_next_name(const char *init_name, char *name, + size_t len) + { +diff --git a/include/linux/leds.h b/include/linux/leds.h +index ba4861ec73d30..31cb74b90ffcd 100644 +--- a/include/linux/leds.h ++++ b/include/linux/leds.h +@@ -39,6 +39,21 @@ enum led_default_state { + LEDS_DEFSTATE_KEEP = 2, + }; + ++/** ++ * struct led_lookup_data - represents a single LED lookup entry ++ * ++ * @list: internal list of all LED lookup entries ++ * @provider: name of led_classdev providing the LED ++ * @dev_id: name of the device associated with this LED ++ * @con_id: name of the LED from the device's point of view ++ */ ++struct led_lookup_data { ++ struct list_head list; ++ const char *provider; ++ const char *dev_id; ++ const char *con_id; ++}; ++ + struct led_init_data { + /* device fwnode handle */ + struct fwnode_handle *fwnode; +@@ -211,6 +226,12 @@ void devm_led_classdev_unregister(struct device *parent, + void led_classdev_suspend(struct led_classdev *led_cdev); + void led_classdev_resume(struct led_classdev *led_cdev); + ++void led_add_lookup(struct led_lookup_data *led_lookup); ++void led_remove_lookup(struct led_lookup_data *led_lookup); ++ ++struct led_classdev *__must_check led_get(struct device *dev, char *con_id); ++struct led_classdev *__must_check devm_led_get(struct device *dev, char *con_id); ++ + extern struct led_classdev *of_led_get(struct device_node *np, int index); + extern void led_put(struct led_classdev *led_cdev); + struct led_classdev *__must_check devm_of_led_get(struct device *dev, +-- +2.40.0 + +From fd05482ce75c24299ab7625e658a31a406ee8406 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 20 Jan 2023 12:45:18 +0100 +Subject: [PATCH] leds: led-class: Add devicetree support to led_get() + +Turn of_led_get() into a more generic __of_led_get() helper function, +which can lookup LEDs in devicetree by either name or index. + +And use this new helper to add devicetree support to the generic +(non devicetree specific) [devm_]led_get() function. + +This uses the standard devicetree pattern of adding a -names string array +to map names to the indexes for an array of resources. + +Note the new led-names property for LED consumers is not added +to the devicetree documentation because there seems to be no +documentation for the leds property itself to extend it with this. +It seems that how LED consumers should be described is not documented +at all ATM. + +This patch is marked as RFC because of both the missing devicetree +documentation and because there are no devicetree users of +the generic [devm_]led_get() function for now. + +Reviewed-by: Andy Shevchenko +Reviewed-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/leds/led-class.c | 37 ++++++++++++++++++++++++++++--------- + 1 file changed, 28 insertions(+), 9 deletions(-) + +diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c +index 0c4b8d8d2b4fe..2f3af6e302082 100644 +--- a/drivers/leds/led-class.c ++++ b/drivers/leds/led-class.c +@@ -234,19 +234,18 @@ static struct led_classdev *led_module_get(struct device *led_dev) + return led_cdev; + } + +-/** +- * of_led_get() - request a LED device via the LED framework +- * @np: device node to get the LED device from +- * @index: the index of the LED +- * +- * Returns the LED device parsed from the phandle specified in the "leds" +- * property of a device tree node or a negative error-code on failure. +- */ +-struct led_classdev *of_led_get(struct device_node *np, int index) ++static struct led_classdev *__of_led_get(struct device_node *np, int index, ++ const char *name) + { + struct device *led_dev; + struct device_node *led_node; + ++ /* ++ * For named LEDs, first look up the name in the "led-names" property. ++ * If it cannot be found, then of_parse_phandle() will propagate the error. ++ */ ++ if (name) ++ index = of_property_match_string(np, "led-names", name); + led_node = of_parse_phandle(np, "leds", index); + if (!led_node) + return ERR_PTR(-ENOENT); +@@ -256,6 +255,19 @@ struct led_classdev *of_led_get(struct device_node *np, int index) + + return led_module_get(led_dev); + } ++ ++/** ++ * of_led_get() - request a LED device via the LED framework ++ * @np: device node to get the LED device from ++ * @index: the index of the LED ++ * ++ * Returns the LED device parsed from the phandle specified in the "leds" ++ * property of a device tree node or a negative error-code on failure. ++ */ ++struct led_classdev *of_led_get(struct device_node *np, int index) ++{ ++ return __of_led_get(np, index, NULL); ++} + EXPORT_SYMBOL_GPL(of_led_get); + + /** +@@ -329,9 +341,16 @@ EXPORT_SYMBOL_GPL(devm_of_led_get); + struct led_classdev *led_get(struct device *dev, char *con_id) + { + struct led_lookup_data *lookup; ++ struct led_classdev *led_cdev; + const char *provider = NULL; + struct device *led_dev; + ++ if (dev->of_node) { ++ led_cdev = __of_led_get(dev->of_node, -1, con_id); ++ if (!IS_ERR(led_cdev) || PTR_ERR(led_cdev) != -ENOENT) ++ return led_cdev; ++ } ++ + mutex_lock(&leds_lookup_lock); + list_for_each_entry(lookup, &leds_lookup_list, list) { + if (!strcmp(lookup->dev_id, dev_name(dev)) && +-- +2.40.0 + +From c721c947fadaf0849f4cd32f2206c43c0f8c8c8e Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 20 Jan 2023 12:45:19 +0100 +Subject: [PATCH] media: v4l2-core: Built async and fwnode code into + videodev.ko + +Currently the videodev.ko code may be builtin while e.g. v4l2-fwnode.ko +is build as a module. + +This makes it hard to add code depending on other subsystems spanning +both videodev.ko and v4l2-fwnode.ko. Specifically this block adding code +depending on the LED subsystem. + +This is made even harder because CONFIG_V4L2_FWNODE is selected, +not depended on so it itself cannot depend on another subsystem without +editing all the Kconfig symbols selecting it to also list the dependency +and there are many of such symbols. + +Adding a "select LED_CLASS if NEW_LEDS" to CONFIG_V4L2_FWNODE leads +to Kconfig erroring out with "error: recursive dependency detected!". + +To fix this dependency mess, change the V4L2_FWNODE and V4L2_ASYNC +(which V4L2_FWNODE selects) Kconfig symbols from tristate to bools and +link their code into videodev.ko instead of making them separate modules. + +This will allow using IS_REACHABLE(LED_CLASS) for the new LED integration +code without needing to worry that it expands to 0 in some places and +1 in other places because some of the code being builtin vs modular. + +On x86_64 this leads to the following size changes for videodev.ko + +[hans@shalem linux]$ size drivers/media/v4l2-core/videodev.ko + +Before: + text data bss dec hex filename + 218206 14395 2448 235049 39629 drivers/media/v4l2-core/videodev.ko +After: + text data bss dec hex filename + 243213 17615 2456 263284 40474 drivers/media/v4l2-core/videodev.ko + +So (as expected) there is some increase in size here, but it +really is not that much. + +And the uncompressed no-debuginfo .ko file disk-usage actually shrinks +by 17 KiB (comparing the slightly larger videodev.ko against the +3 original modules) and loading time will also be better. + +Acked-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/media/v4l2-core/Kconfig | 4 ++-- + drivers/media/v4l2-core/Makefile | 4 ++-- + drivers/media/v4l2-core/v4l2-async.c | 17 ++++------------- + drivers/media/v4l2-core/v4l2-dev-priv.h | 19 +++++++++++++++++++ + drivers/media/v4l2-core/v4l2-dev.c | 8 ++++++++ + drivers/media/v4l2-core/v4l2-fwnode.c | 6 ------ + 6 files changed, 35 insertions(+), 23 deletions(-) + create mode 100644 drivers/media/v4l2-core/v4l2-dev-priv.h + +diff --git a/drivers/media/v4l2-core/Kconfig b/drivers/media/v4l2-core/Kconfig +index 348559bc24689..73574d9460105 100644 +--- a/drivers/media/v4l2-core/Kconfig ++++ b/drivers/media/v4l2-core/Kconfig +@@ -68,11 +68,11 @@ config V4L2_FLASH_LED_CLASS + When in doubt, say N. + + config V4L2_FWNODE +- tristate ++ bool + select V4L2_ASYNC + + config V4L2_ASYNC +- tristate ++ bool + + # Used by drivers that need Videobuf modules + config VIDEOBUF_GEN +diff --git a/drivers/media/v4l2-core/Makefile b/drivers/media/v4l2-core/Makefile +index 41d91bd10cf28..8c5a1ab8d939a 100644 +--- a/drivers/media/v4l2-core/Makefile ++++ b/drivers/media/v4l2-core/Makefile +@@ -15,7 +15,9 @@ videodev-objs := v4l2-dev.o v4l2-ioctl.o v4l2-device.o v4l2-fh.o \ + + # Please keep it alphabetically sorted by Kconfig name + # (e. g. LC_ALL=C sort Makefile) ++videodev-$(CONFIG_V4L2_ASYNC) += v4l2-async.o + videodev-$(CONFIG_COMPAT) += v4l2-compat-ioctl32.o ++videodev-$(CONFIG_V4L2_FWNODE) += v4l2-fwnode.o + videodev-$(CONFIG_MEDIA_CONTROLLER) += v4l2-mc.o + videodev-$(CONFIG_SPI) += v4l2-spi.o + videodev-$(CONFIG_TRACEPOINTS) += v4l2-trace.o +@@ -24,9 +26,7 @@ videodev-$(CONFIG_VIDEO_V4L2_I2C) += v4l2-i2c.o + # Please keep it alphabetically sorted by Kconfig name + # (e. g. LC_ALL=C sort Makefile) + +-obj-$(CONFIG_V4L2_ASYNC) += v4l2-async.o + obj-$(CONFIG_V4L2_FLASH_LED_CLASS) += v4l2-flash-led-class.o +-obj-$(CONFIG_V4L2_FWNODE) += v4l2-fwnode.o + obj-$(CONFIG_V4L2_H264) += v4l2-h264.o + obj-$(CONFIG_V4L2_JPEG_HELPER) += v4l2-jpeg.o + obj-$(CONFIG_V4L2_MEM2MEM_DEV) += v4l2-mem2mem.o +diff --git a/drivers/media/v4l2-core/v4l2-async.c b/drivers/media/v4l2-core/v4l2-async.c +index 2f1b718a91893..024d6b82b50af 100644 +--- a/drivers/media/v4l2-core/v4l2-async.c ++++ b/drivers/media/v4l2-core/v4l2-async.c +@@ -11,7 +11,6 @@ + #include + #include + #include +-#include + #include + #include + #include +@@ -24,6 +23,8 @@ + #include + #include + ++#include "v4l2-dev-priv.h" ++ + static int v4l2_async_nf_call_bound(struct v4l2_async_notifier *n, + struct v4l2_subdev *subdev, + struct v4l2_async_subdev *asd) +@@ -900,25 +901,15 @@ DEFINE_SHOW_ATTRIBUTE(pending_subdevs); + + static struct dentry *v4l2_async_debugfs_dir; + +-static int __init v4l2_async_init(void) ++void __init v4l2_async_debugfs_init(void) + { + v4l2_async_debugfs_dir = debugfs_create_dir("v4l2-async", NULL); + debugfs_create_file("pending_async_subdevices", 0444, + v4l2_async_debugfs_dir, NULL, + &pending_subdevs_fops); +- +- return 0; + } + +-static void __exit v4l2_async_exit(void) ++void __exit v4l2_async_debugfs_exit(void) + { + debugfs_remove_recursive(v4l2_async_debugfs_dir); + } +- +-subsys_initcall(v4l2_async_init); +-module_exit(v4l2_async_exit); +- +-MODULE_AUTHOR("Guennadi Liakhovetski "); +-MODULE_AUTHOR("Sakari Ailus "); +-MODULE_AUTHOR("Ezequiel Garcia "); +-MODULE_LICENSE("GPL"); +diff --git a/drivers/media/v4l2-core/v4l2-dev-priv.h b/drivers/media/v4l2-core/v4l2-dev-priv.h +new file mode 100644 +index 0000000000000..b5b1ee78be20a +--- /dev/null ++++ b/drivers/media/v4l2-core/v4l2-dev-priv.h +@@ -0,0 +1,19 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * Video capture interface for Linux version 2 private header. ++ * ++ * Copyright (C) 2023 Hans de Goede ++ */ ++ ++#ifndef _V4L2_DEV_PRIV_H_ ++#define _V4L2_DEV_PRIV_H_ ++ ++#if IS_ENABLED(CONFIG_V4L2_ASYNC) ++void v4l2_async_debugfs_init(void); ++void v4l2_async_debugfs_exit(void); ++#else ++static inline void v4l2_async_debugfs_init(void) {} ++static inline void v4l2_async_debugfs_exit(void) {} ++#endif ++ ++#endif +diff --git a/drivers/media/v4l2-core/v4l2-dev.c b/drivers/media/v4l2-core/v4l2-dev.c +index 397d553177fa7..10ba2e4196a65 100644 +--- a/drivers/media/v4l2-core/v4l2-dev.c ++++ b/drivers/media/v4l2-core/v4l2-dev.c +@@ -31,6 +31,8 @@ + #include + #include + ++#include "v4l2-dev-priv.h" ++ + #define VIDEO_NUM_DEVICES 256 + #define VIDEO_NAME "video4linux" + +@@ -1190,6 +1192,7 @@ static int __init videodev_init(void) + return -EIO; + } + ++ v4l2_async_debugfs_init(); + return 0; + } + +@@ -1197,6 +1200,7 @@ static void __exit videodev_exit(void) + { + dev_t dev = MKDEV(VIDEO_MAJOR, 0); + ++ v4l2_async_debugfs_exit(); + class_unregister(&video_class); + unregister_chrdev_region(dev, VIDEO_NUM_DEVICES); + } +@@ -1205,6 +1209,10 @@ subsys_initcall(videodev_init); + module_exit(videodev_exit) + + MODULE_AUTHOR("Alan Cox, Mauro Carvalho Chehab , Bill Dirks, Justin Schoeman, Gerd Knorr"); ++MODULE_AUTHOR("Guennadi Liakhovetski "); ++MODULE_AUTHOR("Sakari Ailus "); ++MODULE_AUTHOR("Ezequiel Garcia "); ++MODULE_AUTHOR("Sylwester Nawrocki "); + MODULE_DESCRIPTION("Video4Linux2 core driver"); + MODULE_LICENSE("GPL"); + MODULE_ALIAS_CHARDEV_MAJOR(VIDEO_MAJOR); +diff --git a/drivers/media/v4l2-core/v4l2-fwnode.c b/drivers/media/v4l2-core/v4l2-fwnode.c +index 3d9533c1b2029..c8a2264262bca 100644 +--- a/drivers/media/v4l2-core/v4l2-fwnode.c ++++ b/drivers/media/v4l2-core/v4l2-fwnode.c +@@ -17,7 +17,6 @@ + #include + #include + #include +-#include + #include + #include + #include +@@ -1328,8 +1327,3 @@ int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd) + return ret; + } + EXPORT_SYMBOL_GPL(v4l2_async_register_subdev_sensor); +- +-MODULE_LICENSE("GPL"); +-MODULE_AUTHOR("Sakari Ailus "); +-MODULE_AUTHOR("Sylwester Nawrocki "); +-MODULE_AUTHOR("Guennadi Liakhovetski "); +-- +2.40.0 + +From de5866d009ef5ac839e85a53f93ce04b2a92409d Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 27 Jan 2023 21:37:25 +0100 +Subject: [PATCH] media: v4l2-core: Make the v4l2-core code enable/disable the + privacy LED if present + +Make v4l2_async_register_subdev_sensor() try to get a privacy LED +associated with the sensor and extend the call_s_stream() wrapper to +enable/disable the privacy LED if found. + +This makes the core handle privacy LED control, rather then having to +duplicate this code in all the sensor drivers. + +Suggested-by: Sakari Ailus +Acked-by: Linus Walleij +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/media/v4l2-core/v4l2-async.c | 3 ++ + drivers/media/v4l2-core/v4l2-fwnode.c | 7 ++++ + drivers/media/v4l2-core/v4l2-subdev-priv.h | 14 +++++++ + drivers/media/v4l2-core/v4l2-subdev.c | 44 ++++++++++++++++++++++ + include/media/v4l2-subdev.h | 3 ++ + 5 files changed, 71 insertions(+) + create mode 100644 drivers/media/v4l2-core/v4l2-subdev-priv.h + +diff --git a/drivers/media/v4l2-core/v4l2-async.c b/drivers/media/v4l2-core/v4l2-async.c +index 024d6b82b50af..b26dcb8d423e1 100644 +--- a/drivers/media/v4l2-core/v4l2-async.c ++++ b/drivers/media/v4l2-core/v4l2-async.c +@@ -24,6 +24,7 @@ + #include + + #include "v4l2-dev-priv.h" ++#include "v4l2-subdev-priv.h" + + static int v4l2_async_nf_call_bound(struct v4l2_async_notifier *n, + struct v4l2_subdev *subdev, +@@ -823,6 +824,8 @@ void v4l2_async_unregister_subdev(struct v4l2_subdev *sd) + if (!sd->async_list.next) + return; + ++ v4l2_subdev_put_privacy_led(sd); ++ + mutex_lock(&list_lock); + + __v4l2_async_nf_unregister(sd->subdev_notifier); +diff --git a/drivers/media/v4l2-core/v4l2-fwnode.c b/drivers/media/v4l2-core/v4l2-fwnode.c +index c8a2264262bca..8501b6931d3a0 100644 +--- a/drivers/media/v4l2-core/v4l2-fwnode.c ++++ b/drivers/media/v4l2-core/v4l2-fwnode.c +@@ -27,6 +27,8 @@ + #include + #include + ++#include "v4l2-subdev-priv.h" ++ + static const struct v4l2_fwnode_bus_conv { + enum v4l2_fwnode_bus_type fwnode_bus_type; + enum v4l2_mbus_type mbus_type; +@@ -1301,6 +1303,10 @@ int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd) + + v4l2_async_nf_init(notifier); + ++ ret = v4l2_subdev_get_privacy_led(sd); ++ if (ret < 0) ++ goto out_cleanup; ++ + ret = v4l2_async_nf_parse_fwnode_sensor(sd->dev, notifier); + if (ret < 0) + goto out_cleanup; +@@ -1321,6 +1327,7 @@ int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd) + v4l2_async_nf_unregister(notifier); + + out_cleanup: ++ v4l2_subdev_put_privacy_led(sd); + v4l2_async_nf_cleanup(notifier); + kfree(notifier); + +diff --git a/drivers/media/v4l2-core/v4l2-subdev-priv.h b/drivers/media/v4l2-core/v4l2-subdev-priv.h +new file mode 100644 +index 0000000000000..7ad2812c3d8e3 +--- /dev/null ++++ b/drivers/media/v4l2-core/v4l2-subdev-priv.h +@@ -0,0 +1,14 @@ ++/* SPDX-License-Identifier: GPL-2.0-or-later */ ++/* ++ * V4L2 sub-device pivate header. ++ * ++ * Copyright (C) 2023 Hans de Goede ++ */ ++ ++#ifndef _V4L2_SUBDEV_PRIV_H_ ++#define _V4L2_SUBDEV_PRIV_H_ ++ ++int v4l2_subdev_get_privacy_led(struct v4l2_subdev *sd); ++void v4l2_subdev_put_privacy_led(struct v4l2_subdev *sd); ++ ++#endif +diff --git a/drivers/media/v4l2-core/v4l2-subdev.c b/drivers/media/v4l2-core/v4l2-subdev.c +index 4988a25bd8f46..9fd1836282859 100644 +--- a/drivers/media/v4l2-core/v4l2-subdev.c ++++ b/drivers/media/v4l2-core/v4l2-subdev.c +@@ -9,6 +9,7 @@ + */ + + #include ++#include + #include + #include + #include +@@ -23,6 +24,8 @@ + #include + #include + ++#include "v4l2-subdev-priv.h" ++ + #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) + static int subdev_fh_init(struct v4l2_subdev_fh *fh, struct v4l2_subdev *sd) + { +@@ -322,6 +325,14 @@ static int call_s_stream(struct v4l2_subdev *sd, int enable) + { + int ret; + ++#if IS_REACHABLE(CONFIG_LEDS_CLASS) ++ if (!IS_ERR_OR_NULL(sd->privacy_led)) { ++ if (enable) ++ led_set_brightness(sd->privacy_led, sd->privacy_led->max_brightness); ++ else ++ led_set_brightness(sd->privacy_led, 0); ++ } ++#endif + ret = sd->ops->video->s_stream(sd, enable); + + if (!enable && ret < 0) { +@@ -1090,6 +1101,7 @@ void v4l2_subdev_init(struct v4l2_subdev *sd, const struct v4l2_subdev_ops *ops) + sd->grp_id = 0; + sd->dev_priv = NULL; + sd->host_priv = NULL; ++ sd->privacy_led = NULL; + #if defined(CONFIG_MEDIA_CONTROLLER) + sd->entity.name = sd->name; + sd->entity.obj_type = MEDIA_ENTITY_TYPE_V4L2_SUBDEV; +@@ -1105,3 +1117,35 @@ void v4l2_subdev_notify_event(struct v4l2_subdev *sd, + v4l2_subdev_notify(sd, V4L2_DEVICE_NOTIFY_EVENT, (void *)ev); + } + EXPORT_SYMBOL_GPL(v4l2_subdev_notify_event); ++ ++int v4l2_subdev_get_privacy_led(struct v4l2_subdev *sd) ++{ ++#if IS_REACHABLE(CONFIG_LEDS_CLASS) ++ sd->privacy_led = led_get(sd->dev, "privacy-led"); ++ if (IS_ERR(sd->privacy_led) && PTR_ERR(sd->privacy_led) != -ENOENT) ++ return dev_err_probe(sd->dev, PTR_ERR(sd->privacy_led), "getting privacy LED\n"); ++ ++ if (!IS_ERR_OR_NULL(sd->privacy_led)) { ++ mutex_lock(&sd->privacy_led->led_access); ++ led_sysfs_disable(sd->privacy_led); ++ led_trigger_remove(sd->privacy_led); ++ led_set_brightness(sd->privacy_led, 0); ++ mutex_unlock(&sd->privacy_led->led_access); ++ } ++#endif ++ return 0; ++} ++EXPORT_SYMBOL_GPL(v4l2_subdev_get_privacy_led); ++ ++void v4l2_subdev_put_privacy_led(struct v4l2_subdev *sd) ++{ ++#if IS_REACHABLE(CONFIG_LEDS_CLASS) ++ if (!IS_ERR_OR_NULL(sd->privacy_led)) { ++ mutex_lock(&sd->privacy_led->led_access); ++ led_sysfs_enable(sd->privacy_led); ++ mutex_unlock(&sd->privacy_led->led_access); ++ led_put(sd->privacy_led); ++ } ++#endif ++} ++EXPORT_SYMBOL_GPL(v4l2_subdev_put_privacy_led); +diff --git a/include/media/v4l2-subdev.h b/include/media/v4l2-subdev.h +index b15fa9930f30c..0547313f98cc4 100644 +--- a/include/media/v4l2-subdev.h ++++ b/include/media/v4l2-subdev.h +@@ -38,6 +38,7 @@ struct v4l2_subdev; + struct v4l2_subdev_fh; + struct tuner_setup; + struct v4l2_mbus_frame_desc; ++struct led_classdev; + + /** + * struct v4l2_decode_vbi_line - used to decode_vbi_line +@@ -982,6 +983,8 @@ struct v4l2_subdev { + * appropriate functions. + */ + ++ struct led_classdev *privacy_led; ++ + /* + * TODO: active_state should most likely be changed from a pointer to an + * embedded field. For the time being it's kept as a pointer to more +-- +2.40.0 + +From 7149a5e25231f6286ee3745defecf743a3ed6fb1 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 27 Jan 2023 21:37:26 +0100 +Subject: [PATCH] platform/x86: int3472/discrete: Refactor GPIO to sensor + mapping + +Add a helper function to map the type returned by the _DSM +method to a function name + the default polarity for that function. + +And fold the INT3472_GPIO_TYPE_RESET and INT3472_GPIO_TYPE_POWERDOWN +cases into a single generic case. + +This is a preparation patch for further GPIO mapping changes. + +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/platform/x86/intel/int3472/discrete.c | 45 +++++++++++++++---- + 1 file changed, 36 insertions(+), 9 deletions(-) + +diff --git a/drivers/platform/x86/intel/int3472/discrete.c b/drivers/platform/x86/intel/int3472/discrete.c +index 6f4b8e24eb56c..443f8dcb1e733 100644 +--- a/drivers/platform/x86/intel/int3472/discrete.c ++++ b/drivers/platform/x86/intel/int3472/discrete.c +@@ -202,6 +202,36 @@ static int skl_int3472_map_gpio_to_clk(struct int3472_discrete_device *int3472, + return 0; + } + ++static void int3472_get_func_and_polarity(u8 type, const char **func, u32 *polarity) ++{ ++ switch (type) { ++ case INT3472_GPIO_TYPE_RESET: ++ *func = "reset"; ++ *polarity = GPIO_ACTIVE_LOW; ++ break; ++ case INT3472_GPIO_TYPE_POWERDOWN: ++ *func = "powerdown"; ++ *polarity = GPIO_ACTIVE_LOW; ++ break; ++ case INT3472_GPIO_TYPE_CLK_ENABLE: ++ *func = "clk-enable"; ++ *polarity = GPIO_ACTIVE_HIGH; ++ break; ++ case INT3472_GPIO_TYPE_PRIVACY_LED: ++ *func = "privacy-led"; ++ *polarity = GPIO_ACTIVE_HIGH; ++ break; ++ case INT3472_GPIO_TYPE_POWER_ENABLE: ++ *func = "power-enable"; ++ *polarity = GPIO_ACTIVE_HIGH; ++ break; ++ default: ++ *func = "unknown"; ++ *polarity = GPIO_ACTIVE_HIGH; ++ break; ++ } ++} ++ + /** + * skl_int3472_handle_gpio_resources: Map PMIC resources to consuming sensor + * @ares: A pointer to a &struct acpi_resource +@@ -241,6 +271,8 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + struct acpi_resource_gpio *agpio; + union acpi_object *obj; + const char *err_msg; ++ const char *func; ++ u32 polarity; + int ret; + u8 type; + +@@ -264,19 +296,14 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + + type = obj->integer.value & 0xff; + ++ int3472_get_func_and_polarity(type, &func, &polarity); ++ + switch (type) { + case INT3472_GPIO_TYPE_RESET: +- ret = skl_int3472_map_gpio_to_sensor(int3472, agpio, "reset", +- GPIO_ACTIVE_LOW); +- if (ret) +- err_msg = "Failed to map reset pin to sensor\n"; +- +- break; + case INT3472_GPIO_TYPE_POWERDOWN: +- ret = skl_int3472_map_gpio_to_sensor(int3472, agpio, "powerdown", +- GPIO_ACTIVE_LOW); ++ ret = skl_int3472_map_gpio_to_sensor(int3472, agpio, func, polarity); + if (ret) +- err_msg = "Failed to map powerdown pin to sensor\n"; ++ err_msg = "Failed to map GPIO pin to sensor\n"; + + break; + case INT3472_GPIO_TYPE_CLK_ENABLE: +-- +2.40.0 + +From 70ff97b13a7d99c3b64b297b44b538dc9b579336 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 27 Jan 2023 21:37:27 +0100 +Subject: [PATCH] platform/x86: int3472/discrete: Create a LED class device for + the privacy LED + +On some systems, e.g. the Lenovo ThinkPad X1 Yoga gen 7 and the ThinkPad +X1 Nano gen 2 there is no clock-enable pin, triggering the: +"No clk GPIO. The privacy LED won't work" warning and causing the privacy +LED to not work. + +Fix this by modeling the privacy LED as a LED class device rather then +integrating it with the registered clock. + +Note this relies on media subsys changes to actually turn the LED on/off +when the sensor's v4l2_subdev's s_stream() operand gets called. + +Signed-off-by: Hans de Goede +Patchset: cameras +--- + drivers/platform/x86/intel/int3472/Makefile | 2 +- + .../x86/intel/int3472/clk_and_regulator.c | 3 - + drivers/platform/x86/intel/int3472/common.h | 15 +++- + drivers/platform/x86/intel/int3472/discrete.c | 58 ++++----------- + drivers/platform/x86/intel/int3472/led.c | 74 +++++++++++++++++++ + 5 files changed, 105 insertions(+), 47 deletions(-) + create mode 100644 drivers/platform/x86/intel/int3472/led.c + +diff --git a/drivers/platform/x86/intel/int3472/Makefile b/drivers/platform/x86/intel/int3472/Makefile +index cfec7784c5c93..9f16cb5143973 100644 +--- a/drivers/platform/x86/intel/int3472/Makefile ++++ b/drivers/platform/x86/intel/int3472/Makefile +@@ -1,4 +1,4 @@ + obj-$(CONFIG_INTEL_SKL_INT3472) += intel_skl_int3472_discrete.o \ + intel_skl_int3472_tps68470.o +-intel_skl_int3472_discrete-y := discrete.o clk_and_regulator.o common.o ++intel_skl_int3472_discrete-y := discrete.o clk_and_regulator.o led.o common.o + intel_skl_int3472_tps68470-y := tps68470.o tps68470_board_data.o common.o +diff --git a/drivers/platform/x86/intel/int3472/clk_and_regulator.c b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +index 74dc2cff799ee..e3b597d933880 100644 +--- a/drivers/platform/x86/intel/int3472/clk_and_regulator.c ++++ b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +@@ -23,8 +23,6 @@ static int skl_int3472_clk_prepare(struct clk_hw *hw) + struct int3472_gpio_clock *clk = to_int3472_clk(hw); + + gpiod_set_value_cansleep(clk->ena_gpio, 1); +- gpiod_set_value_cansleep(clk->led_gpio, 1); +- + return 0; + } + +@@ -33,7 +31,6 @@ static void skl_int3472_clk_unprepare(struct clk_hw *hw) + struct int3472_gpio_clock *clk = to_int3472_clk(hw); + + gpiod_set_value_cansleep(clk->ena_gpio, 0); +- gpiod_set_value_cansleep(clk->led_gpio, 0); + } + + static int skl_int3472_clk_enable(struct clk_hw *hw) +diff --git a/drivers/platform/x86/intel/int3472/common.h b/drivers/platform/x86/intel/int3472/common.h +index 53270d19c73ab..82dc37e08882e 100644 +--- a/drivers/platform/x86/intel/int3472/common.h ++++ b/drivers/platform/x86/intel/int3472/common.h +@@ -6,6 +6,7 @@ + + #include + #include ++#include + #include + #include + #include +@@ -28,6 +29,8 @@ + #define GPIO_REGULATOR_NAME_LENGTH 21 + #define GPIO_REGULATOR_SUPPLY_NAME_LENGTH 9 + ++#define INT3472_LED_MAX_NAME_LEN 32 ++ + #define CIO2_SENSOR_SSDB_MCLKSPEED_OFFSET 86 + + #define INT3472_REGULATOR(_name, _supply, _ops) \ +@@ -96,10 +99,16 @@ struct int3472_discrete_device { + struct clk_hw clk_hw; + struct clk_lookup *cl; + struct gpio_desc *ena_gpio; +- struct gpio_desc *led_gpio; + u32 frequency; + } clock; + ++ struct int3472_pled { ++ struct led_classdev classdev; ++ struct led_lookup_data lookup; ++ char name[INT3472_LED_MAX_NAME_LEN]; ++ struct gpio_desc *gpio; ++ } pled; ++ + unsigned int ngpios; /* how many GPIOs have we seen */ + unsigned int n_sensor_gpios; /* how many have we mapped to sensor */ + struct gpiod_lookup_table gpios; +@@ -119,4 +128,8 @@ int skl_int3472_register_regulator(struct int3472_discrete_device *int3472, + struct acpi_resource_gpio *agpio); + void skl_int3472_unregister_regulator(struct int3472_discrete_device *int3472); + ++int skl_int3472_register_pled(struct int3472_discrete_device *int3472, ++ struct acpi_resource_gpio *agpio, u32 polarity); ++void skl_int3472_unregister_pled(struct int3472_discrete_device *int3472); ++ + #endif +diff --git a/drivers/platform/x86/intel/int3472/discrete.c b/drivers/platform/x86/intel/int3472/discrete.c +index 443f8dcb1e733..67d26f8a8d9a3 100644 +--- a/drivers/platform/x86/intel/int3472/discrete.c ++++ b/drivers/platform/x86/intel/int3472/discrete.c +@@ -169,37 +169,21 @@ static int skl_int3472_map_gpio_to_sensor(struct int3472_discrete_device *int347 + } + + static int skl_int3472_map_gpio_to_clk(struct int3472_discrete_device *int3472, +- struct acpi_resource_gpio *agpio, u8 type) ++ struct acpi_resource_gpio *agpio) + { + char *path = agpio->resource_source.string_ptr; + u16 pin = agpio->pin_table[0]; + struct gpio_desc *gpio; + +- switch (type) { +- case INT3472_GPIO_TYPE_CLK_ENABLE: +- gpio = acpi_get_and_request_gpiod(path, pin, "int3472,clk-enable"); +- if (IS_ERR(gpio)) +- return (PTR_ERR(gpio)); +- +- int3472->clock.ena_gpio = gpio; +- /* Ensure the pin is in output mode and non-active state */ +- gpiod_direction_output(int3472->clock.ena_gpio, 0); +- break; +- case INT3472_GPIO_TYPE_PRIVACY_LED: +- gpio = acpi_get_and_request_gpiod(path, pin, "int3472,privacy-led"); +- if (IS_ERR(gpio)) +- return (PTR_ERR(gpio)); ++ gpio = acpi_get_and_request_gpiod(path, pin, "int3472,clk-enable"); ++ if (IS_ERR(gpio)) ++ return (PTR_ERR(gpio)); + +- int3472->clock.led_gpio = gpio; +- /* Ensure the pin is in output mode and non-active state */ +- gpiod_direction_output(int3472->clock.led_gpio, 0); +- break; +- default: +- dev_err(int3472->dev, "Invalid GPIO type 0x%02x for clock\n", type); +- break; +- } ++ int3472->clock.ena_gpio = gpio; ++ /* Ensure the pin is in output mode and non-active state */ ++ gpiod_direction_output(int3472->clock.ena_gpio, 0); + +- return 0; ++ return skl_int3472_register_clock(int3472); + } + + static void int3472_get_func_and_polarity(u8 type, const char **func, u32 *polarity) +@@ -307,11 +291,16 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + + break; + case INT3472_GPIO_TYPE_CLK_ENABLE: +- case INT3472_GPIO_TYPE_PRIVACY_LED: +- ret = skl_int3472_map_gpio_to_clk(int3472, agpio, type); ++ ret = skl_int3472_map_gpio_to_clk(int3472, agpio); + if (ret) + err_msg = "Failed to map GPIO to clock\n"; + ++ break; ++ case INT3472_GPIO_TYPE_PRIVACY_LED: ++ ret = skl_int3472_register_pled(int3472, agpio, polarity); ++ if (ret) ++ err_msg = "Failed to register LED\n"; ++ + break; + case INT3472_GPIO_TYPE_POWER_ENABLE: + ret = skl_int3472_register_regulator(int3472, agpio); +@@ -355,21 +344,6 @@ static int skl_int3472_parse_crs(struct int3472_discrete_device *int3472) + + acpi_dev_free_resource_list(&resource_list); + +- /* +- * If we find no clock enable GPIO pin then the privacy LED won't work. +- * We've never seen that situation, but it's possible. Warn the user so +- * it's clear what's happened. +- */ +- if (int3472->clock.ena_gpio) { +- ret = skl_int3472_register_clock(int3472); +- if (ret) +- return ret; +- } else { +- if (int3472->clock.led_gpio) +- dev_warn(int3472->dev, +- "No clk GPIO. The privacy LED won't work\n"); +- } +- + int3472->gpios.dev_id = int3472->sensor_name; + gpiod_add_lookup_table(&int3472->gpios); + +@@ -386,8 +360,8 @@ static int skl_int3472_discrete_remove(struct platform_device *pdev) + skl_int3472_unregister_clock(int3472); + + gpiod_put(int3472->clock.ena_gpio); +- gpiod_put(int3472->clock.led_gpio); + ++ skl_int3472_unregister_pled(int3472); + skl_int3472_unregister_regulator(int3472); + + return 0; +diff --git a/drivers/platform/x86/intel/int3472/led.c b/drivers/platform/x86/intel/int3472/led.c +new file mode 100644 +index 0000000000000..251c6524458e7 +--- /dev/null ++++ b/drivers/platform/x86/intel/int3472/led.c +@@ -0,0 +1,74 @@ ++// SPDX-License-Identifier: GPL-2.0 ++/* Author: Hans de Goede */ ++ ++#include ++#include ++#include ++#include "common.h" ++ ++static int int3472_pled_set(struct led_classdev *led_cdev, ++ enum led_brightness brightness) ++{ ++ struct int3472_discrete_device *int3472 = ++ container_of(led_cdev, struct int3472_discrete_device, pled.classdev); ++ ++ gpiod_set_value_cansleep(int3472->pled.gpio, brightness); ++ return 0; ++} ++ ++int skl_int3472_register_pled(struct int3472_discrete_device *int3472, ++ struct acpi_resource_gpio *agpio, u32 polarity) ++{ ++ char *p, *path = agpio->resource_source.string_ptr; ++ int ret; ++ ++ if (int3472->pled.classdev.dev) ++ return -EBUSY; ++ ++ int3472->pled.gpio = acpi_get_and_request_gpiod(path, agpio->pin_table[0], ++ "int3472,privacy-led"); ++ if (IS_ERR(int3472->pled.gpio)) ++ return dev_err_probe(int3472->dev, PTR_ERR(int3472->pled.gpio), ++ "getting privacy LED GPIO\n"); ++ ++ if (polarity == GPIO_ACTIVE_LOW) ++ gpiod_toggle_active_low(int3472->pled.gpio); ++ ++ /* Ensure the pin is in output mode and non-active state */ ++ gpiod_direction_output(int3472->pled.gpio, 0); ++ ++ /* Generate the name, replacing the ':' in the ACPI devname with '_' */ ++ snprintf(int3472->pled.name, sizeof(int3472->pled.name), ++ "%s::privacy_led", acpi_dev_name(int3472->sensor)); ++ p = strchr(int3472->pled.name, ':'); ++ *p = '_'; ++ ++ int3472->pled.classdev.name = int3472->pled.name; ++ int3472->pled.classdev.max_brightness = 1; ++ int3472->pled.classdev.brightness_set_blocking = int3472_pled_set; ++ ++ ret = led_classdev_register(int3472->dev, &int3472->pled.classdev); ++ if (ret) ++ goto err_free_gpio; ++ ++ int3472->pled.lookup.provider = int3472->pled.name; ++ int3472->pled.lookup.dev_id = int3472->sensor_name; ++ int3472->pled.lookup.con_id = "privacy-led"; ++ led_add_lookup(&int3472->pled.lookup); ++ ++ return 0; ++ ++err_free_gpio: ++ gpiod_put(int3472->pled.gpio); ++ return ret; ++} ++ ++void skl_int3472_unregister_pled(struct int3472_discrete_device *int3472) ++{ ++ if (IS_ERR_OR_NULL(int3472->pled.classdev.dev)) ++ return; ++ ++ led_remove_lookup(&int3472->pled.lookup); ++ led_classdev_unregister(&int3472->pled.classdev); ++ gpiod_put(int3472->pled.gpio); ++} +-- +2.40.0 + +From 581e535b2341fbcb14838f8fc621adbe2cdedab9 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 27 Jan 2023 21:37:28 +0100 +Subject: [PATCH] platform/x86: int3472/discrete: Move GPIO request to + skl_int3472_register_clock() + +Move the requesting of the clk-enable GPIO to skl_int3472_register_clock() +(and move the gpiod_put to unregister). + +This mirrors the GPIO handling in skl_int3472_register_regulator() and +allows removing skl_int3472_map_gpio_to_clk() from discrete.c. + +Signed-off-by: Hans de Goede +Patchset: cameras +--- + .../x86/intel/int3472/clk_and_regulator.c | 28 +++++++++++++++-- + drivers/platform/x86/intel/int3472/common.h | 3 +- + drivers/platform/x86/intel/int3472/discrete.c | 30 ++----------------- + 3 files changed, 30 insertions(+), 31 deletions(-) + +diff --git a/drivers/platform/x86/intel/int3472/clk_and_regulator.c b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +index e3b597d933880..626e5e86f4e0c 100644 +--- a/drivers/platform/x86/intel/int3472/clk_and_regulator.c ++++ b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +@@ -86,18 +86,34 @@ static const struct clk_ops skl_int3472_clock_ops = { + .recalc_rate = skl_int3472_clk_recalc_rate, + }; + +-int skl_int3472_register_clock(struct int3472_discrete_device *int3472) ++int skl_int3472_register_clock(struct int3472_discrete_device *int3472, ++ struct acpi_resource_gpio *agpio) + { ++ char *path = agpio->resource_source.string_ptr; + struct clk_init_data init = { + .ops = &skl_int3472_clock_ops, + .flags = CLK_GET_RATE_NOCACHE, + }; + int ret; + ++ if (int3472->clock.cl) ++ return -EBUSY; ++ ++ int3472->clock.ena_gpio = acpi_get_and_request_gpiod(path, agpio->pin_table[0], ++ "int3472,clk-enable"); ++ if (IS_ERR(int3472->clock.ena_gpio)) ++ return dev_err_probe(int3472->dev, PTR_ERR(int3472->clock.ena_gpio), ++ "getting clk-enable GPIO\n"); ++ ++ /* Ensure the pin is in output mode and non-active state */ ++ gpiod_direction_output(int3472->clock.ena_gpio, 0); ++ + init.name = kasprintf(GFP_KERNEL, "%s-clk", + acpi_dev_name(int3472->adev)); +- if (!init.name) +- return -ENOMEM; ++ if (!init.name) { ++ ret = -ENOMEM; ++ goto out_put_gpio; ++ } + + int3472->clock.frequency = skl_int3472_get_clk_frequency(int3472); + +@@ -123,14 +139,20 @@ int skl_int3472_register_clock(struct int3472_discrete_device *int3472) + clk_unregister(int3472->clock.clk); + out_free_init_name: + kfree(init.name); ++out_put_gpio: ++ gpiod_put(int3472->clock.ena_gpio); + + return ret; + } + + void skl_int3472_unregister_clock(struct int3472_discrete_device *int3472) + { ++ if (!int3472->clock.cl) ++ return; ++ + clkdev_drop(int3472->clock.cl); + clk_unregister(int3472->clock.clk); ++ gpiod_put(int3472->clock.ena_gpio); + } + + int skl_int3472_register_regulator(struct int3472_discrete_device *int3472, +diff --git a/drivers/platform/x86/intel/int3472/common.h b/drivers/platform/x86/intel/int3472/common.h +index 82dc37e08882e..0d4fa7d00b5f6 100644 +--- a/drivers/platform/x86/intel/int3472/common.h ++++ b/drivers/platform/x86/intel/int3472/common.h +@@ -121,7 +121,8 @@ int skl_int3472_get_sensor_adev_and_name(struct device *dev, + struct acpi_device **sensor_adev_ret, + const char **name_ret); + +-int skl_int3472_register_clock(struct int3472_discrete_device *int3472); ++int skl_int3472_register_clock(struct int3472_discrete_device *int3472, ++ struct acpi_resource_gpio *agpio); + void skl_int3472_unregister_clock(struct int3472_discrete_device *int3472); + + int skl_int3472_register_regulator(struct int3472_discrete_device *int3472, +diff --git a/drivers/platform/x86/intel/int3472/discrete.c b/drivers/platform/x86/intel/int3472/discrete.c +index 67d26f8a8d9a3..7bac0dd850c83 100644 +--- a/drivers/platform/x86/intel/int3472/discrete.c ++++ b/drivers/platform/x86/intel/int3472/discrete.c +@@ -2,8 +2,6 @@ + /* Author: Dan Scally */ + + #include +-#include +-#include + #include + #include + #include +@@ -168,24 +166,6 @@ static int skl_int3472_map_gpio_to_sensor(struct int3472_discrete_device *int347 + return 0; + } + +-static int skl_int3472_map_gpio_to_clk(struct int3472_discrete_device *int3472, +- struct acpi_resource_gpio *agpio) +-{ +- char *path = agpio->resource_source.string_ptr; +- u16 pin = agpio->pin_table[0]; +- struct gpio_desc *gpio; +- +- gpio = acpi_get_and_request_gpiod(path, pin, "int3472,clk-enable"); +- if (IS_ERR(gpio)) +- return (PTR_ERR(gpio)); +- +- int3472->clock.ena_gpio = gpio; +- /* Ensure the pin is in output mode and non-active state */ +- gpiod_direction_output(int3472->clock.ena_gpio, 0); +- +- return skl_int3472_register_clock(int3472); +-} +- + static void int3472_get_func_and_polarity(u8 type, const char **func, u32 *polarity) + { + switch (type) { +@@ -291,9 +271,9 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + + break; + case INT3472_GPIO_TYPE_CLK_ENABLE: +- ret = skl_int3472_map_gpio_to_clk(int3472, agpio); ++ ret = skl_int3472_register_clock(int3472, agpio); + if (ret) +- err_msg = "Failed to map GPIO to clock\n"; ++ err_msg = "Failed to register clock\n"; + + break; + case INT3472_GPIO_TYPE_PRIVACY_LED: +@@ -356,11 +336,7 @@ static int skl_int3472_discrete_remove(struct platform_device *pdev) + + gpiod_remove_lookup_table(&int3472->gpios); + +- if (int3472->clock.cl) +- skl_int3472_unregister_clock(int3472); +- +- gpiod_put(int3472->clock.ena_gpio); +- ++ skl_int3472_unregister_clock(int3472); + skl_int3472_unregister_pled(int3472); + skl_int3472_unregister_regulator(int3472); + +-- +2.40.0 + +From cc126cf324325818a40c2a7c0fce33047804d340 Mon Sep 17 00:00:00 2001 +From: Hans de Goede +Date: Fri, 27 Jan 2023 21:37:29 +0100 +Subject: [PATCH] platform/x86: int3472/discrete: Get the polarity from the + _DSM entry + +According to: +https://github.com/intel/ipu6-drivers/blob/master/patch/int3472-support-independent-clock-and-LED-gpios-5.17%2B.patch + +Bits 31-24 of the _DSM pin entry integer value codes the active-value, +that is the actual physical signal (0 or 1) which needs to be output on +the pin to turn the sensor chip on (to make it active). + +So if bits 31-24 are 0 for a reset pin, then the actual value of the reset +pin needs to be 0 to take the chip out of reset. IOW in this case the reset +signal is active-high rather then the default active-low. + +And if bits 31-24 are 0 for a clk-en pin then the actual value of the clk +pin needs to be 0 to enable the clk. So in this case the clk-en signal +is active-low rather then the default active-high. + +IOW if bits 31-24 are 0 for a pin, then the default polarity of the pin +is inverted. + +Add a check for this and also propagate this new polarity to the clock +registration. + +Signed-off-by: Hans de Goede +Patchset: cameras +--- + .../platform/x86/intel/int3472/clk_and_regulator.c | 5 ++++- + drivers/platform/x86/intel/int3472/common.h | 2 +- + drivers/platform/x86/intel/int3472/discrete.c | 13 +++++++++++-- + 3 files changed, 16 insertions(+), 4 deletions(-) + +diff --git a/drivers/platform/x86/intel/int3472/clk_and_regulator.c b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +index 626e5e86f4e0c..1086c3d834945 100644 +--- a/drivers/platform/x86/intel/int3472/clk_and_regulator.c ++++ b/drivers/platform/x86/intel/int3472/clk_and_regulator.c +@@ -87,7 +87,7 @@ static const struct clk_ops skl_int3472_clock_ops = { + }; + + int skl_int3472_register_clock(struct int3472_discrete_device *int3472, +- struct acpi_resource_gpio *agpio) ++ struct acpi_resource_gpio *agpio, u32 polarity) + { + char *path = agpio->resource_source.string_ptr; + struct clk_init_data init = { +@@ -105,6 +105,9 @@ int skl_int3472_register_clock(struct int3472_discrete_device *int3472, + return dev_err_probe(int3472->dev, PTR_ERR(int3472->clock.ena_gpio), + "getting clk-enable GPIO\n"); + ++ if (polarity == GPIO_ACTIVE_LOW) ++ gpiod_toggle_active_low(int3472->clock.ena_gpio); ++ + /* Ensure the pin is in output mode and non-active state */ + gpiod_direction_output(int3472->clock.ena_gpio, 0); + +diff --git a/drivers/platform/x86/intel/int3472/common.h b/drivers/platform/x86/intel/int3472/common.h +index 0d4fa7d00b5f6..61688e450ce58 100644 +--- a/drivers/platform/x86/intel/int3472/common.h ++++ b/drivers/platform/x86/intel/int3472/common.h +@@ -122,7 +122,7 @@ int skl_int3472_get_sensor_adev_and_name(struct device *dev, + const char **name_ret); + + int skl_int3472_register_clock(struct int3472_discrete_device *int3472, +- struct acpi_resource_gpio *agpio); ++ struct acpi_resource_gpio *agpio, u32 polarity); + void skl_int3472_unregister_clock(struct int3472_discrete_device *int3472); + + int skl_int3472_register_regulator(struct int3472_discrete_device *int3472, +diff --git a/drivers/platform/x86/intel/int3472/discrete.c b/drivers/platform/x86/intel/int3472/discrete.c +index 7bac0dd850c83..d402289ddaab8 100644 +--- a/drivers/platform/x86/intel/int3472/discrete.c ++++ b/drivers/platform/x86/intel/int3472/discrete.c +@@ -234,11 +234,11 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + struct int3472_discrete_device *int3472 = data; + struct acpi_resource_gpio *agpio; + union acpi_object *obj; ++ u8 active_value, type; + const char *err_msg; + const char *func; + u32 polarity; + int ret; +- u8 type; + + if (!acpi_gpio_get_io_resource(ares, &agpio)) + return 1; +@@ -262,6 +262,15 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + + int3472_get_func_and_polarity(type, &func, &polarity); + ++ /* If bits 31-24 of the _DSM entry are all 0 then the signal is inverted */ ++ active_value = obj->integer.value >> 24; ++ if (!active_value) ++ polarity ^= GPIO_ACTIVE_LOW; ++ ++ dev_dbg(int3472->dev, "%s %s pin %d active-%s\n", func, ++ agpio->resource_source.string_ptr, agpio->pin_table[0], ++ (polarity == GPIO_ACTIVE_HIGH) ? "high" : "low"); ++ + switch (type) { + case INT3472_GPIO_TYPE_RESET: + case INT3472_GPIO_TYPE_POWERDOWN: +@@ -271,7 +280,7 @@ static int skl_int3472_handle_gpio_resources(struct acpi_resource *ares, + + break; + case INT3472_GPIO_TYPE_CLK_ENABLE: +- ret = skl_int3472_register_clock(int3472, agpio); ++ ret = skl_int3472_register_clock(int3472, agpio, polarity); + if (ret) + err_msg = "Failed to register clock\n"; + +-- +2.40.0 + +From 4b6896c6ca8ca93fd912c81130058e96ff4273a9 Mon Sep 17 00:00:00 2001 +From: Kate Hsuan +Date: Tue, 21 Mar 2023 23:37:16 +0800 +Subject: [PATCH] platform: x86: int3472: Add MFD cell for tps68470 LED + +Add MFD cell for tps68470-led. + +Reviewed-by: Daniel Scally +Signed-off-by: Kate Hsuan +Patchset: cameras +--- + drivers/platform/x86/intel/int3472/tps68470.c | 5 +++-- + 1 file changed, 3 insertions(+), 2 deletions(-) + +diff --git a/drivers/platform/x86/intel/int3472/tps68470.c b/drivers/platform/x86/intel/int3472/tps68470.c +index 6a0ff035cf209..2a7d01d3abc85 100644 +--- a/drivers/platform/x86/intel/int3472/tps68470.c ++++ b/drivers/platform/x86/intel/int3472/tps68470.c +@@ -17,7 +17,7 @@ + #define DESIGNED_FOR_CHROMEOS 1 + #define DESIGNED_FOR_WINDOWS 2 + +-#define TPS68470_WIN_MFD_CELL_COUNT 3 ++#define TPS68470_WIN_MFD_CELL_COUNT 4 + + static const struct mfd_cell tps68470_cros[] = { + { .name = "tps68470-gpio" }, +@@ -200,7 +200,8 @@ static int skl_int3472_tps68470_probe(struct i2c_client *client) + cells[1].name = "tps68470-regulator"; + cells[1].platform_data = (void *)board_data->tps68470_regulator_pdata; + cells[1].pdata_size = sizeof(struct tps68470_regulator_platform_data); +- cells[2].name = "tps68470-gpio"; ++ cells[2].name = "tps68470-led"; ++ cells[3].name = "tps68470-gpio"; + + for (i = 0; i < board_data->n_gpiod_lookups; i++) + gpiod_add_lookup_table(board_data->tps68470_gpio_lookup_tables[i]); +-- +2.40.0 + +From aa9cf51965d5dd22f00975c1dc00f403cdedb7be Mon Sep 17 00:00:00 2001 +From: Kate Hsuan +Date: Tue, 21 Mar 2023 23:37:17 +0800 +Subject: [PATCH] include: mfd: tps68470: Add masks for LEDA and LEDB + +Add flags for both LEDA(TPS68470_ILEDCTL_ENA), LEDB +(TPS68470_ILEDCTL_ENB), and current control mask for LEDB +(TPS68470_ILEDCTL_CTRLB) + +Reviewed-by: Daniel Scally +Reviewed-by: Hans de Goede +Signed-off-by: Kate Hsuan +Patchset: cameras +--- + include/linux/mfd/tps68470.h | 5 +++++ + 1 file changed, 5 insertions(+) + +diff --git a/include/linux/mfd/tps68470.h b/include/linux/mfd/tps68470.h +index 7807fa329db00..2d2abb25b944f 100644 +--- a/include/linux/mfd/tps68470.h ++++ b/include/linux/mfd/tps68470.h +@@ -34,6 +34,7 @@ + #define TPS68470_REG_SGPO 0x22 + #define TPS68470_REG_GPDI 0x26 + #define TPS68470_REG_GPDO 0x27 ++#define TPS68470_REG_ILEDCTL 0x28 + #define TPS68470_REG_VCMVAL 0x3C + #define TPS68470_REG_VAUX1VAL 0x3D + #define TPS68470_REG_VAUX2VAL 0x3E +@@ -94,4 +95,8 @@ + #define TPS68470_GPIO_MODE_OUT_CMOS 2 + #define TPS68470_GPIO_MODE_OUT_ODRAIN 3 + ++#define TPS68470_ILEDCTL_ENA BIT(2) ++#define TPS68470_ILEDCTL_ENB BIT(6) ++#define TPS68470_ILEDCTL_CTRLB GENMASK(5, 4) ++ + #endif /* __LINUX_MFD_TPS68470_H */ +-- +2.40.0 + +From 222a58980906a6145196331409ef25155aa93703 Mon Sep 17 00:00:00 2001 +From: Kate Hsuan +Date: Tue, 21 Mar 2023 23:37:18 +0800 +Subject: [PATCH] leds: tps68470: Add LED control for tps68470 + +There are two LED controllers, LEDA indicator LED and LEDB flash LED for +tps68470. LEDA can be enabled by setting TPS68470_ILEDCTL_ENA. Moreover, +tps68470 provides four levels of power status for LEDB. If the +properties called "ti,ledb-current" can be found, the current will be +set according to the property values. These two LEDs can be controlled +through the LED class of sysfs (tps68470-leda and tps68470-ledb). + +Signed-off-by: Kate Hsuan +Patchset: cameras +--- + drivers/leds/Kconfig | 12 +++ + drivers/leds/Makefile | 1 + + drivers/leds/leds-tps68470.c | 185 +++++++++++++++++++++++++++++++++++ + 3 files changed, 198 insertions(+) + create mode 100644 drivers/leds/leds-tps68470.c + +diff --git a/drivers/leds/Kconfig b/drivers/leds/Kconfig +index 499d0f215a8bf..f0caddb6ab757 100644 +--- a/drivers/leds/Kconfig ++++ b/drivers/leds/Kconfig +@@ -846,6 +846,18 @@ config LEDS_TPS6105X + It is a single boost converter primarily for white LEDs and + audio amplifiers. + ++config LEDS_TPS68470 ++ tristate "LED support for TI TPS68470" ++ depends on LEDS_CLASS ++ depends on INTEL_SKL_INT3472 ++ help ++ This driver supports TPS68470 PMIC with LED chip. ++ It provides two LED controllers, with the ability to drive 2 ++ indicator LEDs and 2 flash LEDs. ++ ++ To compile this driver as a module, choose M and it will be ++ called leds-tps68470 ++ + config LEDS_IP30 + tristate "LED support for SGI Octane machines" + depends on LEDS_CLASS +diff --git a/drivers/leds/Makefile b/drivers/leds/Makefile +index 4fd2f92cd1981..b381220400398 100644 +--- a/drivers/leds/Makefile ++++ b/drivers/leds/Makefile +@@ -82,6 +82,7 @@ obj-$(CONFIG_LEDS_TCA6507) += leds-tca6507.o + obj-$(CONFIG_LEDS_TI_LMU_COMMON) += leds-ti-lmu-common.o + obj-$(CONFIG_LEDS_TLC591XX) += leds-tlc591xx.o + obj-$(CONFIG_LEDS_TPS6105X) += leds-tps6105x.o ++obj-$(CONFIG_LEDS_TPS68470) += leds-tps68470.o + obj-$(CONFIG_LEDS_TURRIS_OMNIA) += leds-turris-omnia.o + obj-$(CONFIG_LEDS_WM831X_STATUS) += leds-wm831x-status.o + obj-$(CONFIG_LEDS_WM8350) += leds-wm8350.o +diff --git a/drivers/leds/leds-tps68470.c b/drivers/leds/leds-tps68470.c +new file mode 100644 +index 0000000000000..35aeb5db89c8f +--- /dev/null ++++ b/drivers/leds/leds-tps68470.c +@@ -0,0 +1,185 @@ ++// SPDX-License-Identifier: GPL-2.0 ++/* ++ * LED driver for TPS68470 PMIC ++ * ++ * Copyright (C) 2023 Red Hat ++ * ++ * Authors: ++ * Kate Hsuan ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++ ++#define lcdev_to_led(led_cdev) \ ++ container_of(led_cdev, struct tps68470_led, lcdev) ++ ++#define led_to_tps68470(led, index) \ ++ container_of(led, struct tps68470_device, leds[index]) ++ ++enum tps68470_led_ids { ++ TPS68470_ILED_A, ++ TPS68470_ILED_B, ++ TPS68470_NUM_LEDS ++}; ++ ++static const char *tps68470_led_names[] = { ++ [TPS68470_ILED_A] = "tps68470-iled_a", ++ [TPS68470_ILED_B] = "tps68470-iled_b", ++}; ++ ++struct tps68470_led { ++ unsigned int led_id; ++ struct led_classdev lcdev; ++}; ++ ++struct tps68470_device { ++ struct device *dev; ++ struct regmap *regmap; ++ struct tps68470_led leds[TPS68470_NUM_LEDS]; ++}; ++ ++enum ctrlb_current { ++ CTRLB_2MA = 0, ++ CTRLB_4MA = 1, ++ CTRLB_8MA = 2, ++ CTRLB_16MA = 3, ++}; ++ ++static int tps68470_brightness_set(struct led_classdev *led_cdev, enum led_brightness brightness) ++{ ++ struct tps68470_led *led = lcdev_to_led(led_cdev); ++ struct tps68470_device *tps68470 = led_to_tps68470(led, led->led_id); ++ struct regmap *regmap = tps68470->regmap; ++ ++ switch (led->led_id) { ++ case TPS68470_ILED_A: ++ return regmap_update_bits(regmap, TPS68470_REG_ILEDCTL, TPS68470_ILEDCTL_ENA, ++ brightness ? TPS68470_ILEDCTL_ENA : 0); ++ case TPS68470_ILED_B: ++ return regmap_update_bits(regmap, TPS68470_REG_ILEDCTL, TPS68470_ILEDCTL_ENB, ++ brightness ? TPS68470_ILEDCTL_ENB : 0); ++ } ++ return -EINVAL; ++} ++ ++static enum led_brightness tps68470_brightness_get(struct led_classdev *led_cdev) ++{ ++ struct tps68470_led *led = lcdev_to_led(led_cdev); ++ struct tps68470_device *tps68470 = led_to_tps68470(led, led->led_id); ++ struct regmap *regmap = tps68470->regmap; ++ int ret = 0; ++ int value = 0; ++ ++ ret = regmap_read(regmap, TPS68470_REG_ILEDCTL, &value); ++ if (ret) ++ return dev_err_probe(led_cdev->dev, -EINVAL, "failed on reading register\n"); ++ ++ switch (led->led_id) { ++ case TPS68470_ILED_A: ++ value = value & TPS68470_ILEDCTL_ENA; ++ break; ++ case TPS68470_ILED_B: ++ value = value & TPS68470_ILEDCTL_ENB; ++ break; ++ } ++ ++ return value ? LED_ON : LED_OFF; ++} ++ ++ ++static int tps68470_ledb_current_init(struct platform_device *pdev, ++ struct tps68470_device *tps68470) ++{ ++ int ret = 0; ++ unsigned int curr; ++ ++ /* configure LEDB current if the properties can be got */ ++ if (!device_property_read_u32(&pdev->dev, "ti,ledb-current", &curr)) { ++ if (curr > CTRLB_16MA) { ++ dev_err(&pdev->dev, ++ "Invalid LEDB current value: %d\n", ++ curr); ++ return -EINVAL; ++ } ++ ret = regmap_update_bits(tps68470->regmap, TPS68470_REG_ILEDCTL, ++ TPS68470_ILEDCTL_CTRLB, curr); ++ } ++ return ret; ++} ++ ++static int tps68470_leds_probe(struct platform_device *pdev) ++{ ++ int i = 0; ++ int ret = 0; ++ struct tps68470_device *tps68470; ++ struct tps68470_led *led; ++ struct led_classdev *lcdev; ++ ++ tps68470 = devm_kzalloc(&pdev->dev, sizeof(struct tps68470_device), ++ GFP_KERNEL); ++ if (!tps68470) ++ return -ENOMEM; ++ ++ tps68470->dev = &pdev->dev; ++ tps68470->regmap = dev_get_drvdata(pdev->dev.parent); ++ ++ for (i = 0; i < TPS68470_NUM_LEDS; i++) { ++ led = &tps68470->leds[i]; ++ lcdev = &led->lcdev; ++ ++ led->led_id = i; ++ ++ lcdev->name = devm_kasprintf(tps68470->dev, GFP_KERNEL, "%s::%s", ++ tps68470_led_names[i], LED_FUNCTION_INDICATOR); ++ if (!lcdev->name) ++ return -ENOMEM; ++ ++ lcdev->max_brightness = 1; ++ lcdev->brightness = 0; ++ lcdev->brightness_set_blocking = tps68470_brightness_set; ++ lcdev->brightness_get = tps68470_brightness_get; ++ lcdev->dev = &pdev->dev; ++ ++ ret = devm_led_classdev_register(tps68470->dev, lcdev); ++ if (ret) { ++ dev_err_probe(tps68470->dev, ret, ++ "error registering led\n"); ++ goto err_exit; ++ } ++ ++ if (i == TPS68470_ILED_B) { ++ ret = tps68470_ledb_current_init(pdev, tps68470); ++ if (ret) ++ goto err_exit; ++ } ++ } ++ ++err_exit: ++ if (ret) { ++ for (i = 0; i < TPS68470_NUM_LEDS; i++) { ++ if (tps68470->leds[i].lcdev.name) ++ devm_led_classdev_unregister(&pdev->dev, ++ &tps68470->leds[i].lcdev); ++ } ++ } ++ ++ return ret; ++} ++static struct platform_driver tps68470_led_driver = { ++ .driver = { ++ .name = "tps68470-led", ++ }, ++ .probe = tps68470_leds_probe, ++}; ++ ++module_platform_driver(tps68470_led_driver); ++ ++MODULE_ALIAS("platform:tps68470-led"); ++MODULE_DESCRIPTION("LED driver for TPS68470 PMIC"); ++MODULE_LICENSE("GPL v2"); +-- +2.40.0 + +From 938ba934aa628f28cb249ce1d32d77d6b44b4c3d Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Wed, 22 Mar 2023 11:01:42 +0000 +Subject: [PATCH] media: v4l2-core: Acquire privacy led in + v4l2_async_register_subdev() + +The current call to v4l2_subdev_get_privacy_led() is contained in +v4l2_async_register_subdev_sensor(), but that function isn't used by +all the sensor drivers. Move the acquisition of the privacy led to +v4l2_async_register_subdev() instead. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/media/v4l2-core/v4l2-async.c | 4 ++++ + drivers/media/v4l2-core/v4l2-fwnode.c | 4 ---- + 2 files changed, 4 insertions(+), 4 deletions(-) + +diff --git a/drivers/media/v4l2-core/v4l2-async.c b/drivers/media/v4l2-core/v4l2-async.c +index b26dcb8d423e1..43774d5acf5d1 100644 +--- a/drivers/media/v4l2-core/v4l2-async.c ++++ b/drivers/media/v4l2-core/v4l2-async.c +@@ -757,6 +757,10 @@ int v4l2_async_register_subdev(struct v4l2_subdev *sd) + struct v4l2_async_notifier *notifier; + int ret; + ++ ret = v4l2_subdev_get_privacy_led(sd); ++ if (ret < 0) ++ return ret; ++ + /* + * No reference taken. The reference is held by the device + * (struct v4l2_subdev.dev), and async sub-device does not +diff --git a/drivers/media/v4l2-core/v4l2-fwnode.c b/drivers/media/v4l2-core/v4l2-fwnode.c +index 8501b6931d3a0..077d85553b2b9 100644 +--- a/drivers/media/v4l2-core/v4l2-fwnode.c ++++ b/drivers/media/v4l2-core/v4l2-fwnode.c +@@ -1303,10 +1303,6 @@ int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd) + + v4l2_async_nf_init(notifier); + +- ret = v4l2_subdev_get_privacy_led(sd); +- if (ret < 0) +- goto out_cleanup; +- + ret = v4l2_async_nf_parse_fwnode_sensor(sd->dev, notifier); + if (ret < 0) + goto out_cleanup; +-- +2.40.0 + +From 00815059922465c2f29aceccff0e0a19e8a3f185 Mon Sep 17 00:00:00 2001 +From: Daniel Scally +Date: Tue, 21 Mar 2023 13:45:26 +0000 +Subject: [PATCH] media: i2c: Clarify that gain is Analogue gain in OV7251 + +Update the control ID for the gain control in the ov7251 driver to +V4L2_CID_ANALOGUE_GAIN. + +Signed-off-by: Daniel Scally +Patchset: cameras +--- + drivers/media/i2c/ov7251.c | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/drivers/media/i2c/ov7251.c b/drivers/media/i2c/ov7251.c +index 88e9874352853..ff7b2c26da835 100644 +--- a/drivers/media/i2c/ov7251.c ++++ b/drivers/media/i2c/ov7251.c +@@ -1051,7 +1051,7 @@ static int ov7251_s_ctrl(struct v4l2_ctrl *ctrl) + case V4L2_CID_EXPOSURE: + ret = ov7251_set_exposure(ov7251, ctrl->val); + break; +- case V4L2_CID_GAIN: ++ case V4L2_CID_ANALOGUE_GAIN: + ret = ov7251_set_gain(ov7251, ctrl->val); + break; + case V4L2_CID_TEST_PATTERN: +@@ -1551,7 +1551,7 @@ static int ov7251_init_ctrls(struct ov7251 *ov7251) + ov7251->exposure = v4l2_ctrl_new_std(&ov7251->ctrls, &ov7251_ctrl_ops, + V4L2_CID_EXPOSURE, 1, 32, 1, 32); + ov7251->gain = v4l2_ctrl_new_std(&ov7251->ctrls, &ov7251_ctrl_ops, +- V4L2_CID_GAIN, 16, 1023, 1, 16); ++ V4L2_CID_ANALOGUE_GAIN, 16, 1023, 1, 16); + v4l2_ctrl_new_std_menu_items(&ov7251->ctrls, &ov7251_ctrl_ops, + V4L2_CID_TEST_PATTERN, + ARRAY_SIZE(ov7251_test_pattern_menu) - 1, +-- +2.40.0 + diff --git a/patches/surface/0013-amd-gpio.patch b/patches/surface/0013-amd-gpio.patch new file mode 100644 index 0000000..bc8a666 --- /dev/null +++ b/patches/surface/0013-amd-gpio.patch @@ -0,0 +1,109 @@ +From 7e996cc2b2f8543e6b82fef715776ad2d6076af7 Mon Sep 17 00:00:00 2001 +From: Sachi King +Date: Sat, 29 May 2021 17:47:38 +1000 +Subject: [PATCH] ACPI: Add quirk for Surface Laptop 4 AMD missing irq 7 + override + +This patch is the work of Thomas Gleixner and is +copied from: +https://lore.kernel.org/lkml/87lf8ddjqx.ffs@nanos.tec.linutronix.de/ + +This patch adds a quirk to the ACPI setup to patch in the the irq 7 pin +setup that is missing in the laptops ACPI table. + +This patch was used for validation of the issue, and is not a proper +fix, but is probably a better temporary hack than continuing to probe +the Legacy PIC and run with the PIC in an unknown state. + +Patchset: amd-gpio +--- + arch/x86/kernel/acpi/boot.c | 17 +++++++++++++++++ + 1 file changed, 17 insertions(+) + +diff --git a/arch/x86/kernel/acpi/boot.c b/arch/x86/kernel/acpi/boot.c +index 0f762070a5e10..6362dd4522337 100644 +--- a/arch/x86/kernel/acpi/boot.c ++++ b/arch/x86/kernel/acpi/boot.c +@@ -22,6 +22,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -1252,6 +1253,17 @@ static void __init mp_config_acpi_legacy_irqs(void) + } + } + ++static const struct dmi_system_id surface_quirk[] __initconst = { ++ { ++ .ident = "Microsoft Surface Laptop 4 (AMD)", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_4_1952:1953") ++ }, ++ }, ++ {} ++}; ++ + /* + * Parse IOAPIC related entries in MADT + * returns 0 on success, < 0 on error +@@ -1307,6 +1319,11 @@ static int __init acpi_parse_madt_ioapic_entries(void) + acpi_sci_ioapic_setup(acpi_gbl_FADT.sci_interrupt, 0, 0, + acpi_gbl_FADT.sci_interrupt); + ++ if (dmi_check_system(surface_quirk)) { ++ pr_warn("Surface hack: Override irq 7\n"); ++ mp_override_legacy_irq(7, 3, 3, 7); ++ } ++ + /* Fill in identity legacy mappings where no override */ + mp_config_acpi_legacy_irqs(); + +-- +2.40.0 + +From c4b8d0e7087cbd85f086d13b24b2cbfd1d2c9e91 Mon Sep 17 00:00:00 2001 +From: Maximilian Luz +Date: Thu, 3 Jun 2021 14:04:26 +0200 +Subject: [PATCH] ACPI: Add AMD 13" Surface Laptop 4 model to irq 7 override + quirk + +The 13" version of the Surface Laptop 4 has the same problem as the 15" +version, but uses a different SKU. Add that SKU to the quirk as well. + +Patchset: amd-gpio +--- + arch/x86/kernel/acpi/boot.c | 9 ++++++++- + 1 file changed, 8 insertions(+), 1 deletion(-) + +diff --git a/arch/x86/kernel/acpi/boot.c b/arch/x86/kernel/acpi/boot.c +index 6362dd4522337..8a092c2c6fa86 100644 +--- a/arch/x86/kernel/acpi/boot.c ++++ b/arch/x86/kernel/acpi/boot.c +@@ -1255,12 +1255,19 @@ static void __init mp_config_acpi_legacy_irqs(void) + + static const struct dmi_system_id surface_quirk[] __initconst = { + { +- .ident = "Microsoft Surface Laptop 4 (AMD)", ++ .ident = "Microsoft Surface Laptop 4 (AMD 15\")", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_4_1952:1953") + }, + }, ++ { ++ .ident = "Microsoft Surface Laptop 4 (AMD 13\")", ++ .matches = { ++ DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), ++ DMI_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_4_1958:1959") ++ }, ++ }, + {} + }; + +-- +2.40.0 + diff --git a/patches/surface/0014-rtc.patch b/patches/surface/0014-rtc.patch new file mode 100644 index 0000000..8bd149c --- /dev/null +++ b/patches/surface/0014-rtc.patch @@ -0,0 +1,109 @@ +From c3f3a7ab79b01b35c9e488fc2d92a66b802d8df8 Mon Sep 17 00:00:00 2001 +From: "Bart Groeneveld | GPX Solutions B.V" +Date: Mon, 5 Dec 2022 16:08:46 +0100 +Subject: [PATCH] acpi: allow usage of acpi_tad on HW-reduced platforms + +The specification [1] allows so-called HW-reduced platforms, +which do not implement everything, especially the wakeup related stuff. + +In that case, it is still usable as a RTC. This is helpful for [2] +and [3], which is about a device with no other working RTC, +but it does have an HW-reduced TAD, which can be used as a RTC instead. + +[1]: https://uefi.org/specs/ACPI/6.5/09_ACPI_Defined_Devices_and_Device_Specific_Objects.html#time-and-alarm-device +[2]: https://bugzilla.kernel.org/show_bug.cgi?id=212313 +[3]: https://github.com/linux-surface/linux-surface/issues/415 + +Signed-off-by: Bart Groeneveld | GPX Solutions B.V. +Patchset: rtc +--- + drivers/acpi/acpi_tad.c | 35 ++++++++++++++++++++++++----------- + 1 file changed, 24 insertions(+), 11 deletions(-) + +diff --git a/drivers/acpi/acpi_tad.c b/drivers/acpi/acpi_tad.c +index e9b8e8305e23e..944276934e7ec 100644 +--- a/drivers/acpi/acpi_tad.c ++++ b/drivers/acpi/acpi_tad.c +@@ -432,6 +432,14 @@ static ssize_t caps_show(struct device *dev, struct device_attribute *attr, + + static DEVICE_ATTR_RO(caps); + ++static struct attribute *acpi_tad_attrs[] = { ++ &dev_attr_caps.attr, ++ NULL, ++}; ++static const struct attribute_group acpi_tad_attr_group = { ++ .attrs = acpi_tad_attrs, ++}; ++ + static ssize_t ac_alarm_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) + { +@@ -480,15 +488,14 @@ static ssize_t ac_status_show(struct device *dev, struct device_attribute *attr, + + static DEVICE_ATTR_RW(ac_status); + +-static struct attribute *acpi_tad_attrs[] = { +- &dev_attr_caps.attr, ++static struct attribute *acpi_tad_ac_attrs[] = { + &dev_attr_ac_alarm.attr, + &dev_attr_ac_policy.attr, + &dev_attr_ac_status.attr, + NULL, + }; +-static const struct attribute_group acpi_tad_attr_group = { +- .attrs = acpi_tad_attrs, ++static const struct attribute_group acpi_tad_ac_attr_group = { ++ .attrs = acpi_tad_ac_attrs, + }; + + static ssize_t dc_alarm_store(struct device *dev, struct device_attribute *attr, +@@ -563,13 +570,18 @@ static int acpi_tad_remove(struct platform_device *pdev) + + pm_runtime_get_sync(dev); + ++ if (dd->capabilities & ACPI_TAD_AC_WAKE) ++ sysfs_remove_group(&dev->kobj, &acpi_tad_ac_attr_group); ++ + if (dd->capabilities & ACPI_TAD_DC_WAKE) + sysfs_remove_group(&dev->kobj, &acpi_tad_dc_attr_group); + + sysfs_remove_group(&dev->kobj, &acpi_tad_attr_group); + +- acpi_tad_disable_timer(dev, ACPI_TAD_AC_TIMER); +- acpi_tad_clear_status(dev, ACPI_TAD_AC_TIMER); ++ if (dd->capabilities & ACPI_TAD_AC_WAKE) { ++ acpi_tad_disable_timer(dev, ACPI_TAD_AC_TIMER); ++ acpi_tad_clear_status(dev, ACPI_TAD_AC_TIMER); ++ } + if (dd->capabilities & ACPI_TAD_DC_WAKE) { + acpi_tad_disable_timer(dev, ACPI_TAD_DC_TIMER); + acpi_tad_clear_status(dev, ACPI_TAD_DC_TIMER); +@@ -604,11 +616,6 @@ static int acpi_tad_probe(struct platform_device *pdev) + return -ENODEV; + } + +- if (!acpi_has_method(handle, "_PRW")) { +- dev_info(dev, "Missing _PRW\n"); +- return -ENODEV; +- } +- + dd = devm_kzalloc(dev, sizeof(*dd), GFP_KERNEL); + if (!dd) + return -ENOMEM; +@@ -637,6 +644,12 @@ static int acpi_tad_probe(struct platform_device *pdev) + if (ret) + goto fail; + ++ if (caps & ACPI_TAD_AC_WAKE) { ++ ret = sysfs_create_group(&dev->kobj, &acpi_tad_ac_attr_group); ++ if (ret) ++ goto fail; ++ } ++ + if (caps & ACPI_TAD_DC_WAKE) { + ret = sysfs_create_group(&dev->kobj, &acpi_tad_dc_attr_group); + if (ret) +-- +2.40.0 + diff --git a/scripts/patch.sh b/scripts/patch.sh index 14039b8..0664d8f 100755 --- a/scripts/patch.sh +++ b/scripts/patch.sh @@ -7,8 +7,8 @@ echo "Pika Kernel - Applying patches" patch -Np1 < "../patches/0001-cachy-all.patch" # orig patch from cachy patch -Np1 < "../patches/0002-eevdf.patch" -# orig patch from cachy - 0001-bore-eevdf.patch - looks to not exist for 6.3 so switch to eevdf/cfs -#patch -Np1 < "../patches/0003-bore.patch" +# Linux-surface +patch -Np1 < "../patches/surface/*.patch" # HDR patch - Currently broken against 6.3 #patch -Np1 < "../patches/0004-hdr.patch" # Nintendo controller rumble patch diff --git a/scripts/source.sh b/scripts/source.sh index 4c457c0..931996a 100755 --- a/scripts/source.sh +++ b/scripts/source.sh @@ -2,7 +2,7 @@ echo "Pika Kernel - Getting source" -wget -nv https://git.kernel.org/torvalds/t/linux-6.3-rc6.tar.gz -tar -zxf ./linux-6.3-rc6.tar.gz +wget -nv https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.3.tar.xz +tar -zxf ./linux-6.3.tar.xz -cd linux-6.3-rc6 +cd linux-6.3