Update kernel to ab/13397946

Change-Id: I07ed4e0befe832b8470e3ee8a95b7ebcc6baf653
diff --git a/BUILD.bazel b/BUILD.bazel
new file mode 100644
index 0000000..0efbe7f
--- /dev/null
+++ b/BUILD.bazel
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
+load("//build/kernel/kleaf:kernel.bzl", "kernel_module")
+
+filegroup(
+    name = "headers",
+    srcs = glob([
+        "**/*.h",
+    ]),
+    visibility = [
+        "//private/devices/google:__subpackages__",
+        "//private/google-modules/fingerprint:__subpackages__",
+        "//private/google-modules/touch:__subpackages__",
+    ],
+)
+
+filegroup(
+    name = "touch.common.kconfig",
+    srcs = [
+        "Kconfig",
+    ],
+    visibility = [
+        "//private/devices/google:__subpackages__",
+        "//private/google-modules/fingerprint:__subpackages__",
+        "//private/google-modules/soc/gs:__pkg__",
+    ],
+)
+
+string_flag(
+    name = "touch_udfps_notification",
+    build_setting_default = "disabled",
+)
+
+config_setting(
+    name = "touch_udfps_notification_enabled",
+    flag_values = {
+        ":touch_udfps_notification": "enabled",
+    },
+)
+
+config_setting(
+    name = "touch_udfps_notification_disabled",
+    flag_values = {
+        ":touch_udfps_notification": "disabled",
+    },
+)
+
+kernel_module(
+    name = "touch.common",
+    srcs = glob([
+        "**/*.c",
+        "**/*.h",
+    ]) + [
+        "Kbuild",
+        "//private/google-modules/aoc:headers",
+        "//private/google-modules/display/common:headers",
+        "//private/google-modules/display/samsung:headers",
+        "//private/google-modules/display/samsung/include:headers",
+        "//private/google-modules/soc/gs:gs_soc_headers",
+    ],
+    outs = [
+        "goog_touch_interface.ko",
+        "heatmap.ko",
+        "touch_bus_negotiator.ko",
+        "touch_offload.ko",
+    ],
+    kernel_build = "//private/devices/google/common:kernel",
+    visibility = [
+        "//private/devices/google:__subpackages__",
+        "//private/google-modules/fingerprint:__subpackages__",
+        "//private/google-modules/soc/gs:__pkg__",
+        "//private/google-modules/touch:__subpackages__",
+    ],
+    deps = [
+        "//private/google-modules/aoc",
+        "//private/google-modules/display/common/gs_drm",
+        "//private/google-modules/display/samsung:display.samsung",
+        "//private/google-modules/soc/gs:gs_soc_module",
+    ],
+)
diff --git a/Kbuild b/Kbuild
new file mode 100644
index 0000000..86d8655
--- /dev/null
+++ b/Kbuild
@@ -0,0 +1,12 @@
+# SPDX-License-Identifier: GPL-2.0
+
+ccflags-y += -I$(srctree)/$(src)/include
+ccflags-y += -I$(srctree)/../private/google-modules/display
+ccflags-y += -I$(srctree)/../private/google-modules/display/common/include
+ccflags-y += -I$(srctree)/../private/google-modules/display/samsung/include/uapi
+ccflags-y += -I$(srctree)/../private/google-modules/aoc
+obj-$(CONFIG_TOUCHSCREEN_TBN)		+= touch_bus_negotiator.o
+obj-$(CONFIG_TOUCHSCREEN_HEATMAP)	+= heatmap.o
+obj-$(CONFIG_TOUCHSCREEN_OFFLOAD)	+= touch_offload.o
+obj-$(CONFIG_GOOG_TOUCH_INTERFACE)	+= goog_touch_interface.o
+
diff --git a/Kconfig b/Kconfig
new file mode 100644
index 0000000..63110f0
--- /dev/null
+++ b/Kconfig
@@ -0,0 +1,60 @@
+config TOUCHSCREEN_HEATMAP
+	tristate "Heatmap support for touchscreen"
+	select VIDEOBUF2_VMALLOC
+	help
+	  Do not explicitly select this option. The drivers that utilize
+	  this module must select this in their Kconfig.
+
+config TOUCHSCREEN_TBN
+	tristate "Touch Bus Negotiator for Google Pixel"
+	help
+	  Say Y here if you have a Google Pixel device. This module enables
+	  support for kernel touch drivers to coordinate bus access with remote
+	  processors (e.g. sensor DSP processor), which is required to enable
+	  low power touch gesture detection in processors other than AP.
+
+	  If unsure, say N.
+
+	  To compile this driver as a module, choose M here: the module will be
+	  called touch_bus_negotiator.
+
+config TOUCHSCREEN_TBN_AOC_CHANNEL_MODE
+	bool "AOC channel mode for TBN"
+	depends on TOUCHSCREEN_TBN
+	help
+	  Say Y here if you want to enable AOC channel mode for TBN.
+
+	  If unsure, say N.
+
+config TOUCHSCREEN_OFFLOAD
+	tristate "Touchscreen algorithm offload"
+	help
+	  Say Y here to enable touchscreen algorithm offload. This module allows
+	  the touchscreen driver to feed heatmap data into a char device to be
+	  consumed by a client outside the kernel.
+
+	  If unsure, say N.
+
+config GOOG_TOUCH_INTERFACE
+	tristate "Google Touch Interface (GTI)"
+	depends on TOUCHSCREEN_OFFLOAD
+	depends on TOUCHSCREEN_HEATMAP
+	help
+	  Say Y here if you want to enable the Google Touch Interface driver.
+
+	  If unsure, say N.
+
+config TOUCHSCREEN_SPI_FLASH
+        bool "Touchscreen with flash support"
+        default n
+        help
+          Say Y here if you have the touchscreen with flash support.
+
+          If unsure, say N.
+
+config GOOG_USI_STYLUS
+	tristate "Google USI Stylus Subsystem"
+	help
+	  Say Y here if you want to enable the Google USI Stylus Subsystem.
+
+	  If unsure, Say N.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..b842e4e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: GPL-2.0
+
+KERNEL_SRC ?= /lib/modules/$(shell uname -r)/build
+M ?= $(shell pwd)
+
+EXTRA_CFLAGS	+= -DDYNAMIC_DEBUG_MODULE
+EXTRA_SYMBOLS	+= $(OUT_DIR)/../private/google-modules/aoc/Module.symvers
+EXTRA_SYMBOLS	+= $(OUT_DIR)/../private/google-modules/display/common/gs_drm/Module.symvers
+EXTRA_SYMBOLS	+= $(OUT_DIR)/../private/google-modules/display/samsung/Module.symvers
+
+include $(KERNEL_SRC)/../private/google-modules/soc/gs/Makefile.include
+
+modules modules_install headers_install clean:
+	$(MAKE) -C $(KERNEL_SRC) M=$(M) \
+	EXTRA_CFLAGS="$(EXTRA_CFLAGS)" KBUILD_EXTRA_SYMBOLS="$(EXTRA_SYMBOLS)" $(@)
+
+modules_install: headers_install
diff --git a/goog_touch_interface.c b/goog_touch_interface.c
new file mode 100644
index 0000000..92ff4a8
--- /dev/null
+++ b/goog_touch_interface.c
@@ -0,0 +1,5279 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Google Touch Interface for Pixel devices.
+ *
+ * Copyright 2022 Google LLC.
+ */
+
+#include <linux/delay.h>
+#include <linux/module.h>
+#include <linux/input/mt.h>
+#include <linux/notifier.h>
+#include <linux/of.h>
+#include <linux/power_supply.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
+#include <trace/hooks/systrace.h>
+
+#if IS_ENABLED(CONFIG_GS_DRM_PANEL_UNIFIED)
+#include <gs_drm/gs_drm_connector.h>
+#endif
+#include <samsung/exynos_drm_connector.h>
+#include <samsung/panel/panel-samsung-drv.h>
+
+#include "goog_touch_interface.h"
+#include "touch_bus_negotiator.h"
+
+static struct class *gti_class;
+static u8 gti_dev_num;
+
+/*-----------------------------------------------------------------------------
+ * GTI/common: forward declarations, structures and functions.
+ */
+static void goog_input_flush_offload_fingers(struct goog_touch_interface *gti);
+static void goog_offload_set_running(struct goog_touch_interface *gti, bool running);
+static void goog_lookup_touch_report_rate(struct goog_touch_interface *gti);
+static int goog_precheck_heatmap(struct goog_touch_interface *gti);
+static void goog_set_display_state(struct goog_touch_interface *gti,
+	enum gti_display_state_setting display_state);
+static int goog_do_selftest(struct goog_touch_interface *gti);
+static void goog_notify_lptw_triggered(struct TbnLptwEvent *lptw, void *data);
+static int goog_notify_lptw_left(struct goog_touch_interface *gti);
+static void goog_track_lptw_slot(struct goog_touch_interface *gti, u16 x, u16 y, int slot_bit);
+static void gti_input_set_timestamp(struct goog_touch_interface *gti, ktime_t timestamp);
+static RAW_NOTIFIER_HEAD(lptw_notifier);
+
+/*-----------------------------------------------------------------------------
+ * GTI/proc: forward declarations, structures and functions.
+ */
+static int goog_proc_dump_show(struct seq_file *m, void *v);
+static int goog_proc_ms_base_show(struct seq_file *m, void *v);
+static int goog_proc_ms_diff_show(struct seq_file *m, void *v);
+static int goog_proc_ms_raw_show(struct seq_file *m, void *v);
+static int goog_proc_ss_base_show(struct seq_file *m, void *v);
+static int goog_proc_ss_diff_show(struct seq_file *m, void *v);
+static int goog_proc_ss_raw_show(struct seq_file *m, void *v);
+static struct proc_dir_entry *gti_proc_dir_root;
+static char *gti_proc_name[GTI_PROC_NUM] = {
+	[GTI_PROC_DUMP] = "dump",
+	[GTI_PROC_MS_BASE] = "ms_base",
+	[GTI_PROC_MS_DIFF] = "ms_diff",
+	[GTI_PROC_MS_RAW] = "ms_raw",
+	[GTI_PROC_SS_BASE] = "ss_base",
+	[GTI_PROC_SS_DIFF] = "ss_diff",
+	[GTI_PROC_SS_RAW] = "ss_raw",
+};
+static int (*gti_proc_show[GTI_PROC_NUM]) (struct seq_file *, void *) = {
+	[GTI_PROC_DUMP] = goog_proc_dump_show,
+	[GTI_PROC_MS_BASE] = goog_proc_ms_base_show,
+	[GTI_PROC_MS_DIFF] = goog_proc_ms_diff_show,
+	[GTI_PROC_MS_RAW] = goog_proc_ms_raw_show,
+	[GTI_PROC_SS_BASE] = goog_proc_ss_base_show,
+	[GTI_PROC_SS_DIFF] = goog_proc_ss_diff_show,
+	[GTI_PROC_SS_RAW] = goog_proc_ss_raw_show,
+};
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_dump);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ms_base);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ms_diff);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ms_raw);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ss_base);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ss_diff);
+DEFINE_PROC_SHOW_ATTRIBUTE(goog_proc_ss_raw);
+
+static void goog_proc_heatmap_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	struct gti_sensor_data_cmd *cmd = &gti->cmd.manual_sensor_data_cmd;
+	u16 tx = gti->offload.caps.heatmap_width;
+	u16 rx = gti->offload.caps.heatmap_height;
+	int x, y;
+
+	if (cmd->size == 0 || cmd->buffer == NULL) {
+		seq_puts(m, "result: N/A!\n");
+		GOOG_LOGW(gti, "result: N/A!\n");
+		return;
+	}
+
+	switch (cmd->type) {
+	case GTI_SENSOR_DATA_TYPE_MS_BASELINE:
+	case GTI_SENSOR_DATA_TYPE_MS_DIFF:
+	case GTI_SENSOR_DATA_TYPE_MS_RAW:
+		if (cmd->size == TOUCH_OFFLOAD_DATA_SIZE_2D(rx, tx)) {
+			seq_puts(m, "result:\n");
+			if (cmd->is_unsigned) {
+				for (y = 0; y < rx; y++) {
+					for (x = 0; x < tx; x++) {
+						seq_printf(m,  "%5u,",
+							((u16 *)cmd->buffer)[y * tx + x]);
+					}
+					seq_puts(m, "\n");
+				}
+			} else {
+				for (y = 0; y < rx; y++) {
+					for (x = 0; x < tx; x++) {
+						seq_printf(m,  "%5d,",
+							((s16 *)cmd->buffer)[y * tx + x]);
+					}
+					seq_puts(m, "\n");
+				}
+			}
+		} else {
+			seq_printf(m, "error: invalid buffer %p or size %d!\n",
+				cmd->buffer, cmd->size);
+			GOOG_LOGW(gti, "error: invalid buffer %p or size %d!\n",
+				cmd->buffer, cmd->size);
+		}
+		break;
+
+	case GTI_SENSOR_DATA_TYPE_SS_BASELINE:
+	case GTI_SENSOR_DATA_TYPE_SS_DIFF:
+	case GTI_SENSOR_DATA_TYPE_SS_RAW:
+		if (cmd->size == TOUCH_OFFLOAD_DATA_SIZE_1D(rx, tx)) {
+			seq_puts(m, "result:\n");
+			seq_puts(m, "TX:");
+			if (cmd->is_unsigned){
+				for (x = 0; x < tx; x++)
+					seq_printf(m, "%5u,", ((u16 *)cmd->buffer)[x]);
+				seq_puts(m, "\nRX:");
+				for (y = 0; y < rx; y++)
+					seq_printf(m, "%5u,", ((u16 *)cmd->buffer)[tx + y]);
+			} else {
+				for (x = 0; x < tx; x++)
+					seq_printf(m, "%5d,", ((s16 *)cmd->buffer)[x]);
+				seq_puts(m, "\nRX:");
+				for (y = 0; y < rx; y++)
+					seq_printf(m, "%5d,", ((s16 *)cmd->buffer)[tx + y]);
+			}
+			seq_puts(m, "\n");
+		} else {
+			seq_printf(m, "error: invalid buffer %p or size %d!\n",
+				cmd->buffer, cmd->size);
+			GOOG_LOGW(gti, "error: invalid buffer %p or size %d!\n",
+				cmd->buffer, cmd->size);
+		}
+		break;
+
+	default:
+		seq_printf(m, "error: invalid type %#x!\n", cmd->type);
+		GOOG_LOGE(gti, "error: invalid type %#x!\n", cmd->type);
+		break;
+	}
+}
+
+static int goog_proc_heatmap_process(struct seq_file *m, void *v, enum gti_sensor_data_type type)
+{
+	struct goog_touch_interface *gti = m->private;
+	struct gti_sensor_data_cmd *cmd = &gti->cmd.manual_sensor_data_cmd;
+	int ret = 0;
+
+	ret = goog_precheck_heatmap(gti);
+	if (ret) {
+		seq_puts(m, "N/A!\n");
+		goto heatmap_process_err;
+	}
+
+	switch (type) {
+	case GTI_SENSOR_DATA_TYPE_MS_BASELINE:
+	case GTI_SENSOR_DATA_TYPE_MS_DIFF:
+	case GTI_SENSOR_DATA_TYPE_MS_RAW:
+	case GTI_SENSOR_DATA_TYPE_SS_BASELINE:
+	case GTI_SENSOR_DATA_TYPE_SS_DIFF:
+	case GTI_SENSOR_DATA_TYPE_SS_RAW:
+		cmd->type = type;
+		break;
+
+	default:
+		seq_printf(m, "error: invalid type %#x!\n", type);
+		GOOG_LOGE(gti, "error: invalid type %#x!\n", type);
+		ret = -EINVAL;
+		break;
+	}
+
+	if (ret)
+		goto heatmap_process_err;
+
+	cmd->buffer = NULL;
+	cmd->size = 0;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_SENSOR_DATA_MANUAL);
+	if (ret) {
+		seq_printf(m, "error: %d!\n", ret);
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	} else {
+		GOOG_LOGI(gti, "type %#x.\n", type);
+	}
+
+heatmap_process_err:
+	if (ret) {
+		cmd->buffer = NULL;
+		cmd->size = 0;
+	}
+	return ret;
+}
+
+static int goog_proc_dump_show(struct seq_file *m, void *v)
+{
+	char trace_tag[128];
+	u64 i, hc_cnt, input_cnt;
+	int ret, slot;
+	ktime_t delta_time;
+	time64_t time64_utc;
+	s32 remainder;
+	struct tm utc;
+	struct goog_touch_interface *gti = m->private;
+	struct gti_debug_healthcheck *hc_history = gti->debug_healthcheck_history;
+	struct gti_debug_input *input_history = gti->debug_input_history;
+
+	hc_cnt = min_t(u64, gti->irq_index, GTI_DEBUG_HEALTHCHECK_KFIFO_LEN);
+	input_cnt = min_t(u64, gti->released_index, GTI_DEBUG_INPUT_KFIFO_LEN);
+
+	ret = mutex_lock_interruptible(&gti->input_process_lock);
+	if (ret) {
+		seq_puts(m, "error: has been interrupted!\n");
+		GOOG_LOGW(gti, "error: has been interrupted!\n");
+		return ret;
+	}
+
+	scnprintf(trace_tag, sizeof(trace_tag), "%s\n", __func__);
+	ATRACE_BEGIN(trace_tag);
+	gti_debug_healthcheck_dump(gti);
+	gti_debug_input_dump(gti);
+
+	seq_puts(m, "\t### Interrupt ###\n");
+	seq_printf(m, "%23s %8s %8s %12s\n", "TIME(UTC)", "INT#", "INPUT#", "SLOT-STATE");
+	for (i = 0 ; i < hc_cnt ; i++) {
+		if (hc_history[i].irq_index == 0)
+			continue;
+
+		time64_utc = div_s64_rem(ktime_to_ns(hc_history[i].irq_time),
+			NSEC_PER_SEC, &remainder);
+		time64_to_tm(time64_utc, 0, &utc);
+		seq_printf(m, "%4ld-%02d-%02d %02d:%02d:%02d.%03ld %8llu %8llu %#12lx\n",
+			utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
+			utc.tm_hour, utc.tm_min, utc.tm_sec, remainder/NSEC_PER_MSEC,
+			hc_history[i].irq_index,
+			hc_history[i].input_index, hc_history[i].slot_bit_active);
+	}
+	seq_puts(m, "\n");
+
+	seq_puts(m, "\t### Coordinate(s) ###\n");
+	seq_printf(m, "%23s %14s %8s %12s %12s %12s %12s\n",
+		"TIME(UTC)", "DURATION(MS)", "SLOT#", "INT#DOWN", "INT#UP",
+		"X-DELTA(PX)", "Y-DELTA(PX)");
+	for (i = 0 ; i < input_cnt ; i++) {
+		delta_time = ktime_sub(input_history[i].released.time,
+				input_history[i].pressed.time);
+		if (delta_time <= 0)
+			continue;
+
+		time64_utc = div_s64_rem(ktime_to_ns(input_history[i].pressed.time),
+			NSEC_PER_SEC, &remainder);
+		time64_to_tm(time64_utc, 0, &utc);
+		seq_printf(m, "%4ld-%02d-%02d %02d:%02d:%02d.%03ld %14lld %8d %12lld %12lld %12d %12d\n",
+			utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
+			utc.tm_hour, utc.tm_min, utc.tm_sec, remainder/NSEC_PER_MSEC,
+			ktime_to_ms(delta_time),
+			input_history[i].slot,
+			input_history[i].pressed.irq_index, input_history[i].released.irq_index,
+			input_history[i].released.coord.x - input_history[i].pressed.coord.x,
+			input_history[i].released.coord.y - input_history[i].pressed.coord.y);
+	}
+	seq_puts(m, "\n");
+
+	seq_puts(m, "\t### Unreleased Coordinate(s) ###\n");
+	seq_printf(m, "%8s %12s %12s %12s %12s %12s\n", "SLOT#", "X", "Y",
+		"PRESSURE", "MAJOR", "MINOR");
+	for_each_set_bit(slot, &gti->slot_bit_active, MAX_SLOTS) {
+		seq_printf(m, "%8d %12u %12u %12u %12u %12u\n", slot,
+			gti->offload.coords[slot].x, gti->offload.coords[slot].y,
+			gti->offload.coords[slot].pressure,
+			gti->offload.coords[slot].major, gti->offload.coords[slot].minor);
+	}
+	seq_puts(m, "\n");
+
+	mutex_unlock(&gti->input_process_lock);
+	seq_puts(m, "\n\n");
+	ATRACE_END();
+
+	return ret;
+}
+
+static int goog_proc_ms_base_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_MS_BASELINE);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static int goog_proc_ms_diff_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_MS_DIFF);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static int goog_proc_ms_raw_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_MS_RAW);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static int goog_proc_ss_base_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_SS_BASELINE);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static int goog_proc_ss_diff_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_SS_DIFF);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static int goog_proc_ss_raw_show(struct seq_file *m, void *v)
+{
+	struct goog_touch_interface *gti = m->private;
+	int ret;
+
+	if (!gti->manual_heatmap_from_irq) {
+		ret = mutex_lock_interruptible(&gti->input_heatmap_lock);
+		if (ret) {
+			seq_puts(m, "error: has been interrupted!\n");
+			GOOG_LOGW(gti, "error: has been interrupted!\n");
+			return ret;
+		}
+	}
+
+	ret = goog_proc_heatmap_process(m, v, GTI_SENSOR_DATA_TYPE_SS_RAW);
+	if (!ret)
+		goog_proc_heatmap_show(m, v);
+
+	if (!gti->manual_heatmap_from_irq)
+		mutex_unlock(&gti->input_heatmap_lock);
+
+	return ret;
+}
+
+static void goog_init_proc(struct goog_touch_interface *gti)
+{
+	int type;
+
+	if (!gti_proc_dir_root) {
+		gti_proc_dir_root = proc_mkdir(GTI_NAME, NULL);
+		if (!gti_proc_dir_root) {
+			pr_err("%s: proc_mkdir failed for %s!\n", __func__, GTI_NAME);
+			return;
+		}
+	}
+
+	gti->proc_dir = proc_mkdir_data(dev_name(gti->dev), 0555, gti_proc_dir_root, gti);
+	if (!gti->proc_dir) {
+		GOOG_ERR(gti, "proc_mkdir_data failed!\n");
+		return;
+	}
+
+	for (type = GTI_PROC_DUMP; type < GTI_PROC_NUM; type++) {
+		char *name = gti_proc_name[type];
+
+		if (gti_proc_show[type])
+			gti->proc_show[type] = proc_create_single_data(
+				name, 0555, gti->proc_dir, gti_proc_show[type], gti);
+		if (!gti->proc_show[type])
+			GOOG_ERR(gti, "proc_create_single_data failed for %s!\n", name);
+	}
+}
+
+/*-----------------------------------------------------------------------------
+ * GTI/sysfs: forward declarations, structures and functions.
+ */
+static ssize_t config_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t force_active_show(
+	struct device *dev, struct device_attribute *attr, char *buf);
+static ssize_t force_active_store(struct device *dev,
+	struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t fw_coord_filter_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t fw_coord_filter_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t fw_grip_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t fw_grip_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t fw_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t fw_palm_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t fw_palm_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t fw_ver_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t gesture_config_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t gesture_config_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t irq_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t irq_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t mf_mode_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t mf_mode_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t offload_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t offload_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t offload_id_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t panel_id_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t ping_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t reset_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t reset_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t scan_mode_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t scan_mode_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t screen_protector_mode_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t screen_protector_mode_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t self_test_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t sensing_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t sensing_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t test_limits_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t v4l2_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t v4l2_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t vrr_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t vrr_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+static ssize_t interactive_calibrate_show(struct device *dev,
+		struct device_attribute *attr, char *buf);
+static ssize_t interactive_calibrate_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size);
+
+static DEVICE_ATTR_RO(config_name);
+static DEVICE_ATTR_RW(force_active);
+static DEVICE_ATTR_RW(fw_coord_filter);
+static DEVICE_ATTR_RW(fw_grip);
+static DEVICE_ATTR_RO(fw_name);
+static DEVICE_ATTR_RW(fw_palm);
+static DEVICE_ATTR_RO(fw_ver);
+static DEVICE_ATTR_RW(gesture_config);
+static DEVICE_ATTR_RW(irq_enabled);
+static DEVICE_ATTR_RW(mf_mode);
+static DEVICE_ATTR_RW(offload_enabled);
+static DEVICE_ATTR_ADMIN_RO(offload_id);
+static DEVICE_ATTR_ADMIN_RO(panel_id);
+static DEVICE_ATTR_RO(ping);
+static DEVICE_ATTR_RW(reset);
+static DEVICE_ATTR_RW(scan_mode);
+static DEVICE_ATTR_RW(screen_protector_mode_enabled);
+static DEVICE_ATTR_RO(self_test);
+static DEVICE_ATTR_RW(sensing_enabled);
+static DEVICE_ATTR_RO(test_limits_name);
+static DEVICE_ATTR_RW(v4l2_enabled);
+static DEVICE_ATTR_RW(vrr_enabled);
+static DEVICE_ATTR_RW(interactive_calibrate);
+
+static struct attribute *goog_attributes[] = {
+	&dev_attr_config_name.attr,
+	&dev_attr_force_active.attr,
+	&dev_attr_fw_coord_filter.attr,
+	&dev_attr_fw_grip.attr,
+	&dev_attr_fw_name.attr,
+	&dev_attr_fw_palm.attr,
+	&dev_attr_fw_ver.attr,
+	&dev_attr_gesture_config.attr,
+	&dev_attr_irq_enabled.attr,
+	&dev_attr_mf_mode.attr,
+	&dev_attr_offload_enabled.attr,
+	&dev_attr_offload_id.attr,
+	&dev_attr_panel_id.attr,
+	&dev_attr_ping.attr,
+	&dev_attr_reset.attr,
+	&dev_attr_scan_mode.attr,
+	&dev_attr_screen_protector_mode_enabled.attr,
+	&dev_attr_self_test.attr,
+	&dev_attr_sensing_enabled.attr,
+	&dev_attr_test_limits_name.attr,
+	&dev_attr_v4l2_enabled.attr,
+	&dev_attr_vrr_enabled.attr,
+	&dev_attr_interactive_calibrate.attr,
+	NULL,
+};
+
+static struct attribute_group goog_attr_group = {
+	.attrs = goog_attributes,
+};
+
+static ssize_t config_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (gti->config_name[0] == '\0') {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %s\n", gti->config_name);
+	}
+	GOOG_INFO(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t force_active_show(
+	struct device *dev, struct device_attribute *attr, char *buf)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	ssize_t buf_idx = 0;
+	bool locked = false;
+
+	if (gti->ignore_force_active) {
+		GOOG_LOGW(gti, "operation not supported!\n");
+		return -EOPNOTSUPP;
+	}
+
+	locked = goog_pm_wake_check_locked(gti, GTI_PM_WAKELOCK_TYPE_FORCE_ACTIVE);
+	buf_idx += scnprintf(buf, PAGE_SIZE - buf_idx, "result: %s\n",
+		locked ? "locked" : "unlocked");
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t force_active_store(struct device *dev,
+	struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	u32 locked = 0;
+	int ret = 0;
+
+	if (buf == NULL || size < 0) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (kstrtou32(buf, 10, &locked)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (locked > 1) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (locked) {
+		if (gti->ignore_force_active)
+			GOOG_LOGW(gti, "operation not supported!\n");
+		else
+			ret = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_FORCE_ACTIVE, false);
+	} else {
+		if (gti->ignore_force_active)
+			GOOG_LOGW(gti, "operation not supported!\n");
+		else
+			ret = goog_pm_wake_unlock(gti, GTI_PM_WAKELOCK_TYPE_FORCE_ACTIVE);
+	}
+
+	if (ret < 0) {
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+		return ret;
+	}
+	return size;
+}
+
+static ssize_t fw_coord_filter_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret = 0;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	struct gti_coord_filter_cmd *cmd = &gti->cmd.coord_filter_cmd;
+
+	if (!gti->coord_filter_enabled) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+		GOOG_LOGE(gti, "%s", buf);
+		return buf_idx;
+	}
+
+	cmd->setting = GTI_COORD_FILTER_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_COORD_FILTER_ENABLED);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", cmd->setting | (gti->ignore_coord_filter_update << 1));
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t fw_coord_filter_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	int fw_coord_filter;
+
+	if (kstrtou32(buf, 10, &fw_coord_filter)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (!gti->coord_filter_enabled) {
+		GOOG_LOGE(gti, "error: not supported!\n");
+		return -EOPNOTSUPP;
+	}
+
+	gti->fw_coord_filter_enabled = fw_coord_filter & 0x01;
+	gti->ignore_coord_filter_update = (fw_coord_filter >> 1) & 0x01;
+	gti->cmd.coord_filter_cmd.setting = gti->fw_coord_filter_enabled ?
+			GTI_COORD_FILTER_ENABLE : GTI_COORD_FILTER_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_COORD_FILTER_ENABLED);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "fw_coord_filter= %u\n", fw_coord_filter);
+
+	return size;
+}
+
+static ssize_t fw_grip_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret = 0;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	struct gti_grip_cmd *cmd = &gti->cmd.grip_cmd;
+
+	cmd->setting = GTI_GRIP_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_GRIP_MODE);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", cmd->setting | (gti->ignore_grip_update << 1));
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t fw_grip_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	int fw_grip_mode = 0;
+	bool enabled = false;
+
+	if (kstrtou32(buf, 10, &fw_grip_mode)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	enabled = fw_grip_mode & 0x01;
+	gti->ignore_grip_update = (fw_grip_mode >> 1) & 0x01;
+	gti->cmd.grip_cmd.setting = enabled ? GTI_GRIP_ENABLE : GTI_GRIP_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_GRIP_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "fw_grip_mode: %u\n", fw_grip_mode);
+
+	return size;
+}
+
+static ssize_t fw_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (gti->fw_name[0] == '\0') {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %s\n", gti->fw_name);
+	}
+	GOOG_INFO(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t fw_palm_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret = 0;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	struct gti_palm_cmd *cmd = &gti->cmd.palm_cmd;
+
+	cmd->setting = GTI_PALM_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_PALM_MODE);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", cmd->setting | (gti->ignore_palm_update << 1));
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t fw_palm_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	int fw_palm_mode;
+	bool enabled;
+
+	if (kstrtou32(buf, 10, &fw_palm_mode)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	enabled = fw_palm_mode & 0x01;
+	gti->ignore_palm_update = (fw_palm_mode >> 1) & 0x01;
+	gti->cmd.palm_cmd.setting = enabled ? GTI_PALM_ENABLE : GTI_PALM_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_PALM_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "fw_palm_mode= %u\n", fw_palm_mode);
+
+	return size;
+}
+
+static ssize_t fw_ver_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	memset(gti->cmd.fw_version_cmd.buffer, 0, sizeof(gti->cmd.fw_version_cmd.buffer));
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_FW_VERSION);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %s\n", gti->cmd.fw_version_cmd.buffer);
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t gesture_config_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	int i = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	for (i = 0; i < GTI_GESTURE_PARAMS_MAX; i++) {
+		buf_idx += sysfs_emit_at(buf, buf_idx, "%s %u\n",
+				gesture_params_list[i],
+				gti->cmd.gesture_config_cmd.params[i]);
+	}
+
+	return buf_idx;
+}
+static ssize_t gesture_config_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	char *p, *temp_buf, *token;
+	u16 config = 0;
+	int retval = 0;
+	int i = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	temp_buf = kstrdup(buf, GFP_KERNEL);
+	if (!temp_buf)
+		return -ENOMEM;
+
+	goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_SYSFS, false);
+
+	p = temp_buf;
+
+	token = strsep(&p, " ");
+
+	if (!token || *token == '\0' || !p) {
+		retval = -EINVAL;
+		goto exit;
+	}
+
+	if (kstrtou16(p, 10, &config)) {
+		retval = -EINVAL;
+		goto exit;
+	}
+
+	memset(gti->cmd.gesture_config_cmd.updating_params, 0, GTI_GESTURE_PARAMS_MAX);
+
+	/* Set gesture parameters */
+	for (i = 0; i < GTI_GESTURE_PARAMS_MAX; i++) {
+		if (!strncmp(token, gesture_params_list[i], strlen(gesture_params_list[i]))) {
+			gti->cmd.gesture_config_cmd.params[i] = config;
+			gti->cmd.gesture_config_cmd.updating_params[i] = 1;
+			retval = goog_process_vendor_cmd(gti, GTI_CMD_SET_GESTURE_CONFIG);
+			if (retval) {
+				GOOG_ERR(gti, "Fail to set param %s, ret = %d!\n",
+						gesture_params_list[i], retval);
+				retval = -EBADRQC;
+				goto exit;
+			}
+			gti->gesture_config_enabled = true;
+			retval = size;
+		}
+	}
+
+	if (retval == 0)
+		retval = -EINVAL;
+
+exit:
+	goog_pm_wake_unlock(gti, GTI_PM_WAKELOCK_TYPE_SYSFS);
+	kfree(temp_buf);
+	return retval;
+}
+
+static ssize_t irq_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	gti->cmd.irq_cmd.setting = GTI_IRQ_MODE_NA;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_IRQ_MODE);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", gti->cmd.irq_cmd.setting);
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t irq_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret;
+	bool enabled;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (kstrtobool(buf, &enabled)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	gti->cmd.irq_cmd.setting = enabled;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_IRQ_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "irq_enabled= %u\n", gti->cmd.irq_cmd.setting);
+
+	return size;
+}
+
+static ssize_t mf_mode_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+		"result: %u\n", gti->mf_mode);
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t mf_mode_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	enum gti_mf_mode mode = 0;
+
+	if (buf == NULL || size < 0) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	if (kstrtou32(buf, 10, &mode)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	if (mode < GTI_MF_MODE_UNFILTER ||
+		mode > GTI_MF_MODE_AUTO_REPORT) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	gti->mf_mode = mode;
+	GOOG_LOGI(gti, "mf_mode= %u\n", gti->mf_mode);
+
+	return size;
+}
+
+static ssize_t offload_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+		"result: %d\n", gti->offload_enabled);
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t offload_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (kstrtobool(buf, &gti->offload_enabled)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+	} else {
+		GOOG_LOGI(gti, "offload_enabled= %d\n", gti->offload_enabled);
+		/* Force to turn off offload by request. */
+		if (!gti->offload_enabled)
+			goog_offload_set_running(gti, false);
+	}
+
+	return size;
+}
+
+static ssize_t offload_id_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx, "result: %c%c%c%c\n",
+			gti->offload_id_byte[0], gti->offload_id_byte[1], gti->offload_id_byte[2],
+			gti->offload_id_byte[3]);
+	GOOG_INFO(gti, "%s", buf);
+	return buf_idx;
+}
+
+static ssize_t panel_id_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (gti->panel_id < 0) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %d\n", gti->panel_id);
+	}
+	GOOG_INFO(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t ping_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	gti->cmd.ping_cmd.setting = GTI_PING_ENABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_PING);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+		gti->cmd.ping_cmd.setting = GTI_PING_NA;
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+		gti->cmd.ping_cmd.setting = GTI_PING_NA;
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: success.\n");
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t reset_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (gti->cmd.reset_cmd.setting == GTI_RESET_MODE_NOP ||
+		gti->cmd.reset_cmd.setting == GTI_RESET_MODE_NA) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", gti->cmd.reset_cmd.setting);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: success.\n");
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t reset_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	enum gti_reset_mode mode = 0;
+
+	if (buf == NULL || size < 0) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (kstrtou32(buf, 10, &mode)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	if (mode <= GTI_RESET_MODE_NOP ||
+		mode > GTI_RESET_MODE_AUTO) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return -EINVAL;
+	}
+
+	gti->cmd.reset_cmd.setting = mode;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_RESET);
+	if (ret == -EOPNOTSUPP) {
+		GOOG_LOGE(gti, "error: not supported!\n");
+		gti->cmd.reset_cmd.setting = GTI_RESET_MODE_NA;
+	} else if (ret) {
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+		gti->cmd.reset_cmd.setting = GTI_RESET_MODE_NA;
+	} else {
+		GOOG_LOGI(gti, "reset= 0x%x\n", mode);
+	}
+
+	return size;
+}
+
+static ssize_t scan_mode_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	gti->cmd.scan_cmd.setting = GTI_SCAN_MODE_NA;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_SCAN_MODE);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", gti->cmd.scan_cmd.setting);
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t scan_mode_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	enum gti_scan_mode mode = 0;
+
+	if (buf == NULL || size < 0) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	if (kstrtou32(buf, 10, &mode)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	if (mode < GTI_SCAN_MODE_AUTO ||
+		mode > GTI_SCAN_MODE_LP_IDLE) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	gti->cmd.scan_cmd.setting = mode;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_SCAN_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "scan_mode= %u\n", mode);
+
+	return size;
+}
+
+static ssize_t screen_protector_mode_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	struct gti_screen_protector_mode_cmd *cmd = &gti->cmd.screen_protector_mode_cmd;
+	bool enabled = false;
+
+	if (kstrtobool(buf, &enabled)) {
+		GOOG_LOGE(gti, "invalid input!\n");
+		return -EINVAL;
+	}
+
+	cmd->setting = enabled ? GTI_SCREEN_PROTECTOR_MODE_ENABLE : GTI_SCREEN_PROTECTOR_MODE_DISABLE;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_SCREEN_PROTECTOR_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "enabled= %u\n", enabled);
+	gti->screen_protector_mode_setting = enabled ?
+			GTI_SCREEN_PROTECTOR_MODE_ENABLE : GTI_SCREEN_PROTECTOR_MODE_DISABLE;
+	return size;
+}
+
+static ssize_t screen_protector_mode_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret = 0;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+	struct gti_screen_protector_mode_cmd *cmd = &gti->cmd.screen_protector_mode_cmd;
+
+	cmd->setting = GTI_SCREEN_PROTECTOR_MODE_NA;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_SCREEN_PROTECTOR_MODE);
+	if (ret == 0) {
+		buf_idx += scnprintf(buf, PAGE_SIZE - buf_idx, "result: %d\n",
+				cmd->setting == GTI_SCREEN_PROTECTOR_MODE_ENABLE);
+	} else {
+		buf_idx += scnprintf(buf, PAGE_SIZE - buf_idx, "error: %d\n", ret);
+	}
+	GOOG_LOGI(gti, "%s", buf);
+	return buf_idx;
+}
+
+static ssize_t self_test_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	gti->cmd.selftest_cmd.result = GTI_SELFTEST_RESULT_NA;
+	gti->cmd.selftest_cmd.is_ical = false;
+	memset(gti->cmd.selftest_cmd.buffer, 0, sizeof(gti->cmd.selftest_cmd.buffer));
+	ret = goog_do_selftest(gti);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += sysfs_emit_at(buf, buf_idx, "error: not supported!\n");
+	} else if (ret) {
+		buf_idx += sysfs_emit_at(buf, buf_idx, "error: %d!\n", ret);
+	} else {
+		switch (gti->cmd.selftest_cmd.result) {
+		case GTI_SELFTEST_RESULT_PASS:
+			buf_idx += sysfs_emit_at(buf, buf_idx, "result: PASS\n");
+			buf_idx += sysfs_emit_at(buf, buf_idx, "%s\n",
+					gti->cmd.selftest_cmd.buffer);
+			break;
+		case GTI_SELFTEST_RESULT_FAIL:
+			buf_idx += sysfs_emit_at(buf, buf_idx, "result: FAIL\n");
+			buf_idx += sysfs_emit_at(buf, buf_idx, "%s\n",
+					gti->cmd.selftest_cmd.buffer);
+			break;
+		case GTI_SELFTEST_RESULT_SHELL_CMDS_REDIRECT:
+			buf_idx += sysfs_emit_at(buf, buf_idx, "redirect: %s\n",
+					gti->cmd.selftest_cmd.buffer);
+			break;
+		default:
+			buf_idx += sysfs_emit_at(buf, buf_idx, "error: N/A!\n");
+			break;
+		}
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t sensing_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	int ret;
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	gti->cmd.sensing_cmd.setting = GTI_SENSING_MODE_NA;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_SENSING_MODE);
+	if (ret == -EOPNOTSUPP) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else if (ret) {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: %d!\n", ret);
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %u\n", gti->cmd.sensing_cmd.setting);
+	}
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t sensing_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	int ret;
+	bool enabled;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (kstrtobool(buf, &enabled)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	gti->cmd.sensing_cmd.setting = enabled;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_SENSING_MODE);
+	if (ret == -EOPNOTSUPP)
+		GOOG_LOGE(gti, "error: not supported!\n");
+	else if (ret)
+		GOOG_LOGE(gti, "error: %d!\n", ret);
+	else
+		GOOG_LOGI(gti, "sensing_enabled= %u\n", gti->cmd.sensing_cmd.setting);
+
+	return size;
+}
+
+static ssize_t test_limits_name_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (gti->test_limits_name[0] == '\0') {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"error: not supported!\n");
+	} else {
+		buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+			"result: %s\n", gti->test_limits_name);
+	}
+	GOOG_INFO(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t v4l2_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE - buf_idx,
+		"result: %d\n", gti->v4l2_enabled);
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t v4l2_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (kstrtobool(buf, &gti->v4l2_enabled))
+		GOOG_LOGE(gti, "error: invalid input!\n");
+	else
+		GOOG_LOGI(gti, "v4l2_enabled= %d\n", gti->v4l2_enabled);
+
+	return size;
+}
+
+static ssize_t vrr_enabled_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += scnprintf(buf + buf_idx, PAGE_SIZE,
+		"result: %d\n", gti->vrr_enabled);
+	GOOG_LOGI(gti, "%s", buf);
+
+	return buf_idx;
+}
+
+static ssize_t vrr_enabled_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	if (kstrtobool(buf, &gti->vrr_enabled)) {
+		GOOG_LOGE(gti, "error: invalid input!\n");
+	} else if (gti->report_rate_table_size == 0) {
+		GOOG_LOGE(gti, "error: No valid report rate table!\n");
+	} else {
+		GOOG_LOGI(gti, "vrr_enabled= %d\n", gti->vrr_enabled);
+		if (gti->vrr_enabled)
+			goog_lookup_touch_report_rate(gti);
+	}
+
+	return size;
+}
+
+/* -----------------------------------------------------------------------
+ * Interactive calibration states
+ *
+ * State "IDLE"/ 0 - idle, no operation underway => return to this state after
+ * an error and after certain timeouts have elapsed
+ *
+ * State "INIT_X" / X01 (101, 201, ...) - operation is beginning. The client
+ * has displayed warnings and will begin transitioning itself to the
+ * "screen off" / "do not touch" state
+ *
+ * State "RUN_X" / X02 (102, 202, ...) - screen is off and nothing is touching
+ * the screen. Operation can begin immediately when this state is entered
+ *
+ * State "END_X" / X03 (103, 203, ...) - the client has waited the designated
+ * time and will assume operation is complete, will read the status of this
+ * state as the final operation status. Transition back to the IDLE state will
+ * occur automatically.
+ */
+bool ical_state_idle(struct goog_touch_interface *gti, u32 next_state,
+			 u64 elapsed)
+{
+	/* Valid next-states are 'INIT_X', or 'IDLE' */
+	if (next_state == ICAL_STATE_IDLE) {
+		gti->ical_result = ICAL_RES_SUCCESS;
+		gti->ical_func_result = ICAL_RES_SUCCESS;
+		/* Do not update the ical timestamp */
+		return false;
+	} else if ((next_state == ICAL_STATE_INIT_CAL ||
+			next_state == ICAL_STATE_INIT_TEST ||
+			next_state == ICAL_STATE_INIT_RESET) &&
+			elapsed > MIN_DELAY_IDLE) {
+		gti->ical_state = next_state;
+		gti->ical_result = ICAL_RES_SUCCESS;
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns\n",
+			 gti->ical_state, next_state, MIN_DELAY_IDLE,
+			 elapsed);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+	return true;
+}
+
+void ical_state_init_cal(struct goog_touch_interface *gti, u32 next_state,
+			 u64 elapsed)
+{
+	int pm_ret = 0;
+	u32 ret;
+
+	pm_ret = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_SYSFS, false);
+	if (pm_ret < 0 && gti->tbn_enabled) {
+		GOOG_ERR(gti, "ical - error: invalid touch bus access!\n");
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL_INVALID_BUS_ACCESS;
+		return;
+	}
+
+	/* only valid next-state is 'RUN_CAL', as long as time elapsed
+	 * is within range. When 'RUN_CAL' is received calibration begins.
+	 */
+	if (next_state == ICAL_STATE_RUN_CAL &&
+	    elapsed > MIN_DELAY_INIT_CAL && elapsed < MAX_DELAY_INIT_CAL) {
+		/* Begin calibration */
+
+		gti->cmd.calibrate_cmd.result = GTI_CALIBRATE_RESULT_NA;
+		memset(gti->cmd.calibrate_cmd.buffer, 0,
+		       sizeof(gti->cmd.calibrate_cmd.buffer));
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_CALIBRATE);
+		if (ret == 0) {
+			if (gti->cmd.calibrate_cmd.result == GTI_CALIBRATE_RESULT_DONE) {
+				gti->ical_func_result = gti->cmd.calibrate_cmd.result;
+				GOOG_INFO(gti,
+					 "ical - CALIBRATE_RESULT_DONE - [%s]\n",
+					 gti->cmd.calibrate_cmd.buffer);
+			} else {
+				gti->ical_func_result = ICAL_RES_FAIL;
+				GOOG_ERR(gti,
+					 "ical - calibrate result other/fail - N/A or [%s]\n",
+					 gti->cmd.calibrate_cmd.buffer);
+			}
+
+			gti->ical_state = ICAL_STATE_RUN_CAL;
+			gti->ical_result = ICAL_RES_SUCCESS;
+		} else {
+			GOOG_ERR(gti, "ical - GTI_CMD_CALIBRATE fail(%d)\n", ret);
+			gti->ical_state = ICAL_STATE_IDLE;
+			gti->ical_result = ICAL_RES_FAIL;
+		}
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_INIT_CAL, elapsed,
+			 MAX_DELAY_INIT_CAL);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+
+	if (pm_ret == 0)
+		goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_SYSFS);
+
+}
+
+void ical_state_run_cal(struct goog_touch_interface *gti, u32 next_state,
+			 u64 elapsed)
+{
+	/* only valid next-state is 'END_CAL', as long as time elapsed
+	 * is within ranged.
+	 */
+	if (next_state == ICAL_STATE_END_CAL &&
+	    elapsed > MIN_DELAY_RUN_CAL && elapsed < MAX_DELAY_RUN_CAL) {
+		GOOG_INFO(gti,
+			 "ical - Calibration complete after %lluns\n",
+			 elapsed);
+
+		gti->ical_state = ICAL_STATE_END_CAL;
+		gti->ical_result = ICAL_RES_SUCCESS;
+
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_RUN_CAL, elapsed,
+			 MAX_DELAY_RUN_CAL);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+}
+
+void ical_state_end_cal(struct goog_touch_interface *gti, u32 next_state,
+			 u64 elapsed)
+{
+	/* Nothing to do but accept a transition back to IDLE.
+	 * Necessary because the interface only executes when called
+	 */
+	if (next_state == ICAL_STATE_IDLE &&
+	    elapsed > MIN_DELAY_END_CAL && elapsed < MAX_DELAY_END_CAL) {
+		gti->ical_result = ICAL_RES_SUCCESS;
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_END_CAL, elapsed,
+			 MAX_DELAY_END_CAL);
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+	gti->ical_state = ICAL_STATE_IDLE;
+}
+
+void ical_state_init_test(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	int pm_ret = 0;
+	u32 ret;
+
+	pm_ret = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_SYSFS, false);
+	if (pm_ret < 0 && gti->tbn_enabled) {
+		GOOG_ERR(gti, "ical - error: invalid touch bus access!\n");
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL_INVALID_BUS_ACCESS;
+		return;
+	}
+
+	/* only valid next-state is 'RUN_TEST', as long as time elapsed
+	 * is within range. When 'RUN_TEST' is received test begins.
+	 */
+	if (next_state == ICAL_STATE_RUN_TEST &&
+	    elapsed > MIN_DELAY_INIT_TEST && elapsed < MAX_DELAY_INIT_TEST) {
+		/* Begin selftest */
+
+		gti->cmd.selftest_cmd.result = GTI_SELFTEST_RESULT_NA;
+		gti->cmd.selftest_cmd.is_ical = true;
+		memset(gti->cmd.selftest_cmd.buffer, 0,
+		       sizeof(gti->cmd.selftest_cmd.buffer));
+		ret = goog_do_selftest(gti);
+		if (ret == 0) {
+			if (gti->cmd.selftest_cmd.result ==
+					GTI_SELFTEST_RESULT_DONE) {
+				gti->ical_func_result = gti->cmd.selftest_cmd.result;
+
+				GOOG_INFO(gti,
+					 "ical - SELFTEST_RESULT_DONE - [%s]\n",
+					 gti->cmd.selftest_cmd.buffer);
+			} else if (gti->cmd.selftest_cmd.result ==
+					GTI_SELFTEST_RESULT_SHELL_CMDS_REDIRECT) {
+				gti->ical_func_result = ICAL_RES_SUCCESS;
+
+				GOOG_ERR(gti,
+					 "ical - SELFTEST_RESULT_SHELL_CMDS_REDIRECT - [%s]\n",
+					 gti->cmd.selftest_cmd.buffer);
+			} else {
+				gti->ical_func_result = ICAL_RES_FAIL;
+
+				GOOG_ERR(gti,
+					 "ical - selftest result other/fail - N/A or [%s]\n",
+					 gti->cmd.selftest_cmd.buffer);
+			}
+
+			gti->ical_state = ICAL_STATE_RUN_TEST;
+			gti->ical_result = ICAL_RES_SUCCESS;
+		} else  {
+			GOOG_ERR(gti, "ical - GTI_CMD_SELFTEST fail(%d)\n", ret);
+			gti->ical_state = ICAL_STATE_IDLE;
+			gti->ical_result = ICAL_RES_FAIL;
+		}
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_INIT_TEST, elapsed,
+			 MAX_DELAY_INIT_TEST);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+
+	if (pm_ret == 0)
+		goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_SYSFS);
+
+}
+
+void ical_state_run_test(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	/* only valid next-state is 'END_TEST', as long as time elapsed
+	 * is within ranged.
+	 */
+	if (next_state == ICAL_STATE_END_TEST &&
+	    elapsed > MIN_DELAY_RUN_TEST && elapsed < MAX_DELAY_RUN_TEST) {
+		/* Check and evaluate self-test here */
+		gti->ical_state = ICAL_STATE_END_TEST;
+		gti->ical_result = ICAL_RES_SUCCESS;
+
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_RUN_TEST, elapsed,
+			 MAX_DELAY_RUN_TEST);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+}
+
+void ical_state_end_test(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	/* Nothing to do but accept a transition back to IDLE.
+	 * Necessary because the interface only executes when called
+	 */
+	if (next_state == ICAL_STATE_IDLE &&
+	    elapsed > MIN_DELAY_END_TEST && elapsed < MAX_DELAY_END_TEST) {
+		gti->ical_result = ICAL_RES_SUCCESS;
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_END_TEST, elapsed,
+			 MAX_DELAY_END_TEST);
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+	gti->ical_state = ICAL_STATE_IDLE;
+}
+
+void ical_state_init_reset(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	int pm_ret = 0;
+	u32 ret;
+
+	pm_ret = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_SYSFS, false);
+	if (pm_ret < 0 && gti->tbn_enabled) {
+		GOOG_ERR(gti, "ical - error: invalid touch bus access!\n");
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL_INVALID_BUS_ACCESS;
+		return;
+	}
+
+	/* only valid next-state is 'RUN_RESET', as long as time elapsed
+	 * is within range. When 'RUN_RESET' is received reset begins.
+	 */
+	if (next_state == ICAL_STATE_RUN_RESET &&
+	    elapsed > MIN_DELAY_INIT_RESET && elapsed < MAX_DELAY_INIT_RESET) {
+		/* Begin reset */
+		gti->cmd.reset_cmd.setting = GTI_RESET_MODE_AUTO;
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_RESET);
+		if (ret == 0) {
+			GOOG_INFO(gti, "ical - RESET_DONE\n");
+			gti->ical_state = ICAL_STATE_RUN_RESET;
+			gti->ical_func_result = ICAL_RES_SUCCESS;
+			gti->ical_result = ICAL_RES_SUCCESS;
+		} else  {
+			GOOG_ERR(gti, "ical - GTI_CMD_RESET fail(%d)\n", ret);
+			gti->ical_state = ICAL_STATE_IDLE;
+			gti->ical_func_result = ICAL_RES_NA;
+			gti->ical_result = ICAL_RES_FAIL;
+		}
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_INIT_RESET, elapsed,
+			 MAX_DELAY_INIT_RESET);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+
+	if (pm_ret == 0)
+		goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_SYSFS);
+
+}
+
+void ical_state_run_reset(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	/* only valid next-state is 'END_RESET', as long as time elapsed
+	 * is within ranged.
+	 */
+	if (next_state == ICAL_STATE_END_RESET &&
+	    elapsed > MIN_DELAY_RUN_RESET && elapsed < MAX_DELAY_RUN_RESET) {
+		/* Check and evaluate reset here */
+		gti->ical_state = ICAL_STATE_END_RESET;
+		gti->ical_result = ICAL_RES_SUCCESS;
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_RUN_RESET, elapsed,
+			 MAX_DELAY_RUN_RESET);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+}
+
+void ical_state_end_reset(struct goog_touch_interface *gti, u32 next_state,
+			  u64 elapsed)
+{
+	/* Nothing to do but accept a transition back to IDLE.
+	 * Necessary because the interface only executes when called
+	 */
+	if (next_state == ICAL_STATE_IDLE &&
+	    elapsed > MIN_DELAY_END_RESET && elapsed < MAX_DELAY_END_RESET) {
+		gti->ical_result = ICAL_RES_SUCCESS;
+	} else {
+		GOOG_ERR(gti,
+			 "ical - error: invalid transition or time! %u => %u, min=%lluns, t=%lluns, max=%lluns\n",
+			 gti->ical_state, next_state,
+			 MIN_DELAY_END_RESET, elapsed,
+			 MAX_DELAY_END_RESET);
+		gti->ical_result = ICAL_RES_FAIL;
+	}
+	gti->ical_state = ICAL_STATE_IDLE;
+}
+
+/* Advance the interactive calibration state machine */
+static ssize_t interactive_calibrate_store(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t size)
+{
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	u32 next_state = 0;
+	u64 entry_time = ktime_get_ns();
+	u64 elapsed = entry_time - gti->ical_timestamp_ns;
+
+	if (kstrtou32(buf, 10, &next_state)) {
+		GOOG_ERR(gti, "error: invalid input!\n");
+		return size;
+	}
+
+	GOOG_INFO(gti, "ical - [%u] start\n", next_state);
+
+	switch (gti->ical_state) {
+	case ICAL_STATE_IDLE:
+		if (ical_state_idle(gti, next_state, elapsed))
+			gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_INIT_CAL:
+		ical_state_init_cal(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_RUN_CAL:
+		ical_state_run_cal(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_END_CAL:
+		ical_state_end_cal(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_INIT_TEST:
+		ical_state_init_test(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_RUN_TEST:
+		ical_state_run_test(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_END_TEST:
+		ical_state_end_test(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_INIT_RESET:
+		ical_state_init_reset(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_RUN_RESET:
+		ical_state_run_reset(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	case ICAL_STATE_END_RESET:
+		ical_state_end_reset(gti, next_state, elapsed);
+		gti->ical_timestamp_ns = entry_time;
+		break;
+
+	default:
+		GOOG_ERR(gti, "ical - unknown/invalid current state = %u, but will go back to 0.\n",
+			 gti->ical_state);
+		gti->ical_state = ICAL_STATE_IDLE;
+		gti->ical_result = ICAL_RES_SUCCESS;
+		break;
+	}
+
+	return size;
+}
+
+/* Show result/status of the calibrate state machine */
+static ssize_t interactive_calibrate_show(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	ssize_t buf_idx = 0;
+	struct goog_touch_interface *gti = dev_get_drvdata(dev);
+
+	buf_idx += sysfs_emit_at(buf, buf_idx, "%d - %d\n",
+		gti->ical_result, gti->ical_func_result);
+
+	GOOG_INFO(gti, "ical - [%u](%d, %d) return\n",
+		gti->ical_state, gti->ical_result, gti->ical_func_result);
+
+	return buf_idx;
+}
+
+/*-----------------------------------------------------------------------------
+ * Debug: functions.
+ */
+#ifdef GTI_DEBUG_HEALTHCHECK_KFIFO_LEN
+inline void gti_debug_healthcheck_push(struct goog_touch_interface *gti)
+{
+	/*
+	 * Use kfifo as circular buffer by skipping one element
+	 * when fifo is full.
+	 */
+	if (kfifo_is_full(&gti->debug_fifo_healthcheck))
+		kfifo_skip(&gti->debug_fifo_healthcheck);
+	kfifo_in(&gti->debug_fifo_healthcheck, &gti->debug_healthcheck, 1);
+}
+
+inline void gti_debug_healthcheck_update(struct goog_touch_interface *gti, bool from_top_half)
+{
+	if (from_top_half) {
+		gti->debug_healthcheck.irq_time = ktime_get_real();
+		gti->debug_healthcheck.irq_index = gti->irq_index;
+	} else {
+		gti->debug_healthcheck.input_index = gti->input_index;
+		gti->debug_healthcheck.slot_bit_active = gti->slot_bit_active;
+		gti_debug_healthcheck_push(gti);
+	}
+}
+
+void gti_debug_healthcheck_dump(struct goog_touch_interface *gti)
+{
+	s16 i, count;
+	s64 delta;
+	s64 sec_delta;
+	u32 ms_delta;
+	ktime_t current_time = ktime_get_real();
+	struct gti_debug_healthcheck *last_fifo = gti->debug_healthcheck_history;
+
+	/*
+	 * Use peek to keep data without pop-out to support different timing
+	 * print-out by each caller.
+	 */
+	count = kfifo_out_peek(&gti->debug_fifo_healthcheck, last_fifo,
+				GTI_DEBUG_HEALTHCHECK_KFIFO_LEN);
+
+	i = max_t(s16, 0, count - GTI_DEBUG_HEALTHCHECK_LOGS_LEN);
+	for (; i < count ; i++) {
+		sec_delta = -1;
+		ms_delta = 0;
+		/*
+		 * Calculate the delta time between irq triggered and current time.
+		 */
+		delta = ktime_ms_delta(current_time, last_fifo[i].irq_time);
+		if (delta > 0)
+			sec_delta = div_u64_rem(delta, MSEC_PER_SEC, &ms_delta);
+		GOOG_INFO(gti, "dump-int: #%llu(%lld.%u): C#%llu(0x%lx).\n",
+			last_fifo[i].irq_index, sec_delta, ms_delta,
+			last_fifo[i].input_index, last_fifo[i].slot_bit_active);
+	}
+}
+#endif /* GTI_DEBUG_HEALTHCHECK_KFIFO_LEN */
+
+#ifdef GTI_DEBUG_INPUT_KFIFO_LEN
+inline void gti_debug_input_push(struct goog_touch_interface *gti, int slot)
+{
+	struct gti_debug_input fifo;
+
+	if (slot < 0 || slot >= MAX_SLOTS) {
+		GOOG_ERR(gti, "Invalid slot: %d\n", slot);
+		return;
+	}
+
+	/*
+	 * Use kfifo as circular buffer by skipping one element
+	 * when fifo is full.
+	 */
+	if (kfifo_is_full(&gti->debug_fifo_input))
+		kfifo_skip(&gti->debug_fifo_input);
+
+	memcpy(&fifo, &gti->debug_input[slot], sizeof(struct gti_debug_input));
+	kfifo_in(&gti->debug_fifo_input, &fifo, 1);
+}
+
+inline void gti_debug_input_update(struct goog_touch_interface *gti)
+{
+	int slot;
+	u64 irq_index = gti->irq_index;
+	ktime_t time = ktime_get_real();
+
+	for_each_set_bit(slot, &gti->slot_bit_changed, MAX_SLOTS) {
+		if (test_bit(slot, &gti->slot_bit_active)) {
+			gti->debug_input[slot].pressed.time = time;
+			gti->debug_input[slot].pressed.irq_index = irq_index;
+			memcpy(&gti->debug_input[slot].pressed.coord,
+				&gti->offload.coords[slot],
+				sizeof(struct TouchOffloadCoord));
+		} else {
+			gti->released_index++;
+			gti->debug_input[slot].released.time = time;
+			gti->debug_input[slot].released.irq_index = irq_index;
+			memcpy(&gti->debug_input[slot].released.coord,
+				&gti->offload.coords[slot],
+				sizeof(struct TouchOffloadCoord));
+			gti_debug_input_push(gti, slot);
+		}
+	}
+	gti->slot_bit_changed = 0;
+}
+
+void gti_debug_input_dump(struct goog_touch_interface *gti)
+{
+	int slot;
+	s16 i, count;
+	s64 delta;
+	s64 sec_delta_down;
+	u32 ms_delta_down;
+	s64 sec_delta_duration;
+	u32 ms_delta_duration;
+	s32 px_delta_x, px_delta_y;
+	ktime_t current_time = ktime_get_real();
+	struct gti_debug_input *last_fifo = gti->debug_input_history;
+
+	/*
+	 * Use peek to keep data without pop-out to support different timing
+	 * print-out by each caller.
+	 */
+	count = kfifo_out_peek(&gti->debug_fifo_input, last_fifo,
+				GTI_DEBUG_INPUT_KFIFO_LEN);
+
+	i = max_t(s16, 0, count - GTI_DEBUG_INPUT_LOGS_LEN);
+	for ( ; i < count ; i++) {
+		if (last_fifo[i].slot < 0 ||
+			last_fifo[i].slot >= MAX_SLOTS) {
+			GOOG_INFO(gti, "dump: #%d: invalid slot #!\n", last_fifo[i].slot);
+			continue;
+		}
+		sec_delta_down = -1;
+		ms_delta_down = 0;
+		/*
+		 * Calculate the delta time of finger down from current time.
+		 */
+		delta = ktime_ms_delta(current_time, last_fifo[i].pressed.time);
+		if (delta > 0)
+			sec_delta_down = div_u64_rem(delta, MSEC_PER_SEC, &ms_delta_down);
+
+		/*
+		 * Calculate the delta time of finger duration from finger up to down.
+		 */
+		sec_delta_duration = -1;
+		ms_delta_duration = 0;
+		px_delta_x = 0;
+		px_delta_y = 0;
+		if (ktime_compare(last_fifo[i].released.time,
+			last_fifo[i].pressed.time) > 0) {
+			delta = ktime_ms_delta(last_fifo[i].released.time,
+					last_fifo[i].pressed.time);
+			if (delta > 0) {
+				sec_delta_duration = div_u64_rem(delta, MSEC_PER_SEC,
+									&ms_delta_duration);
+				px_delta_x = last_fifo[i].released.coord.x -
+					last_fifo[i].pressed.coord.x;
+				px_delta_y = last_fifo[i].released.coord.y -
+					last_fifo[i].pressed.coord.y;
+			}
+		}
+
+		GOOG_INFO(gti, "dump: #%d: %lld.%u(%lld.%u) D(%d, %d) I(%llu, %llu).\n",
+			last_fifo[i].slot,
+			sec_delta_down, ms_delta_down,
+			sec_delta_duration, ms_delta_duration,
+			px_delta_x, px_delta_y,
+			last_fifo[i].pressed.irq_index, last_fifo[i].released.irq_index);
+		GOOG_DBG(gti, "dump-dbg: #%d: P(%u, %u) -> R(%u, %u).\n\n",
+			last_fifo[i].slot,
+			last_fifo[i].pressed.coord.x, last_fifo[i].pressed.coord.y,
+			last_fifo[i].released.coord.x, last_fifo[i].released.coord.y);
+	}
+	/* Extra check for unexpected case. */
+	for_each_set_bit(slot, &gti->slot_bit_active, MAX_SLOTS) {
+		GOOG_INFO(gti, "slot #%d(%u, %u, %u) is active!\n", slot,
+			gti->offload.coords[slot].x, gti->offload.coords[slot].y,
+			gti->offload.coords[slot].pressure);
+	}
+}
+#endif /* GTI_DEBUG_INPUT_KFIFO_LEN */
+
+/*-----------------------------------------------------------------------------
+ * DRM: functions and structures.
+ */
+struct drm_connector *get_bridge_connector(struct drm_bridge *bridge)
+{
+	struct drm_connector *connector;
+	struct drm_connector_list_iter conn_iter;
+
+	drm_connector_list_iter_begin(bridge->dev, &conn_iter);
+	drm_for_each_connector_iter(connector, &conn_iter) {
+		if (connector->encoder == bridge->encoder)
+			break;
+	}
+	drm_connector_list_iter_end(&conn_iter);
+	return connector;
+}
+
+static void panel_set_op_hz(struct work_struct *work)
+{
+	struct goog_touch_interface *gti = container_of(work,
+		struct goog_touch_interface, set_op_hz_work);
+	int ret = 0;
+
+	GOOG_LOGI(gti, "set panel op_hz: %d\n", gti->panel_op_hz);
+
+	gti->cmd.panel_speed_mode_cmd.setting = gti->panel_op_hz == 120 ?
+		GTI_PANEL_SPEED_MODE_HS : GTI_PANEL_SPEED_MODE_NS;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_PANEL_SPEED_MODE);
+	if (ret)
+		GOOG_LOGW(gti, "unexpected return(%d)!", ret);
+}
+
+static int panel_notifier_call(
+	struct notifier_block *nb, unsigned long id, void *data)
+{
+	struct goog_touch_interface *gti =
+		(struct goog_touch_interface *)container_of(nb,
+			struct goog_touch_interface, panel_notifier);
+
+	GOOG_LOGI(gti, "\n");
+
+	if (!gti->connector || !gti->connector->state)
+		gti->connector = get_bridge_connector(&gti->panel_bridge);
+
+	if (!gti->connector) return 0;
+
+#if IS_ENABLED(CONFIG_GS_DRM_PANEL_UNIFIED)
+	if (is_gs_drm_connector(gti->connector)) {
+		if (id == GS_PANEL_NOTIFIER_SET_OP_HZ) {
+			gti->panel_op_hz = *(unsigned int*)data;
+			if (gti->event_wq != NULL)
+				queue_work(gti->event_wq, &gti->set_op_hz_work);
+		}
+	}
+#endif
+	if (is_exynos_drm_connector(gti->connector)) {
+		if (id == EXYNOS_PANEL_NOTIFIER_SET_OP_HZ) {
+			gti->panel_op_hz = *(unsigned int*)data;
+			if (gti->event_wq != NULL)
+				queue_work(gti->event_wq, &gti->set_op_hz_work);
+		}
+	}
+
+	return 0;
+}
+
+static int panel_bridge_attach(struct drm_bridge *bridge, enum drm_bridge_attach_flags flags)
+{
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+
+	if (gti->panel_notifier_enabled) {
+		if (!gti->connector || !gti->connector->state)
+			gti->connector = get_bridge_connector(&gti->panel_bridge);
+
+		if (!gti->connector) {
+			GOOG_LOGW(gti, "can't get panel connector to resgister notification!\n");
+			return 0;
+		}
+
+		gti->panel_notifier.notifier_call = panel_notifier_call;
+#if IS_ENABLED(CONFIG_GS_DRM_PANEL_UNIFIED)
+		if (is_gs_drm_connector(gti->connector))
+			gs_connector_register_op_hz_notifier(gti->connector, &gti->panel_notifier);
+#endif
+		if (is_exynos_drm_connector(gti->connector))
+			exynos_panel_register_notifier(gti->connector, &gti->panel_notifier);
+	}
+
+	return 0;
+}
+
+static void panel_bridge_detach(struct drm_bridge *bridge)
+{
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+
+	if (gti->panel_notifier_enabled) {
+		if (!gti->connector || !gti->connector->state)
+			gti->connector = get_bridge_connector(&gti->panel_bridge);
+
+		if (!gti->connector) return;
+
+#if IS_ENABLED(CONFIG_GS_DRM_PANEL_UNIFIED)
+		if (is_gs_drm_connector(gti->connector))
+			gs_connector_unregister_op_hz_notifier(gti->connector, &gti->panel_notifier);
+#endif
+		if (is_exynos_drm_connector(gti->connector))
+			exynos_panel_unregister_notifier(gti->connector, &gti->panel_notifier);
+	}
+}
+
+static void panel_bridge_enable(struct drm_bridge *bridge)
+{
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+
+	if (gti->panel_is_lp_mode) {
+		GOOG_DBG(gti, "skip screen-on because of panel_is_lp_mode enabled!\n");
+		return;
+	}
+
+	goog_set_display_state(gti, GTI_DISPLAY_STATE_ON);
+}
+
+static void panel_bridge_disable(struct drm_bridge *bridge)
+{
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+
+	if (bridge->encoder && bridge->encoder->crtc) {
+		const struct drm_crtc_state *crtc_state = bridge->encoder->crtc->state;
+
+		if (drm_atomic_crtc_effectively_active(crtc_state))
+			return;
+	}
+
+	goog_set_display_state(gti, GTI_DISPLAY_STATE_OFF);
+}
+
+static bool panel_bridge_is_lp_mode(struct drm_connector *connector)
+{
+	if (connector && connector->state) {
+#if IS_ENABLED(CONFIG_GS_DRM_PANEL_UNIFIED)
+		if (is_gs_drm_connector(connector)) {
+			struct gs_drm_connector_state *s =
+				to_gs_connector_state(connector->state);
+
+			return s->gs_mode.is_lp_mode;
+		}
+#endif
+		if (is_exynos_drm_connector(connector)) {
+			struct exynos_drm_connector_state *s =
+				to_exynos_connector_state(connector->state);
+
+			return s->exynos_mode.is_lp_mode;
+		}
+	}
+	return false;
+}
+
+static void panel_bridge_mode_set(struct drm_bridge *bridge,
+				  const struct drm_display_mode *mode,
+				  const struct drm_display_mode *adjusted_mode)
+{
+	int ret = 0;
+	bool panel_is_lp_mode;
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+
+	if (!gti->connector || !gti->connector->state)
+		gti->connector = get_bridge_connector(bridge);
+
+	panel_is_lp_mode = panel_bridge_is_lp_mode(gti->connector);
+	if (gti->panel_is_lp_mode != panel_is_lp_mode) {
+		GOOG_INFO(gti, "panel_is_lp_mode changed from %d to %d.\n",
+			gti->panel_is_lp_mode, panel_is_lp_mode);
+
+		if (panel_is_lp_mode)
+			goog_set_display_state(gti, GTI_DISPLAY_STATE_OFF);
+		else
+			goog_set_display_state(gti, GTI_DISPLAY_STATE_ON);
+	}
+	gti->panel_is_lp_mode = panel_is_lp_mode;
+
+	if (mode) {
+		int vrefresh = drm_mode_vrefresh(mode);
+
+		if (gti->display_vrefresh != vrefresh) {
+			GOOG_DBG(gti, "display_vrefresh(Hz) changed to %d from %d.\n",
+				vrefresh, gti->display_vrefresh);
+			gti->display_vrefresh = vrefresh;
+			gti->cmd.display_vrefresh_cmd.setting = vrefresh;
+			gti->context_changed.display_refresh_rate = 1;
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_NOTIFY_DISPLAY_VREFRESH);
+			if (ret && ret != -EOPNOTSUPP)
+				GOOG_LOGW(gti, "unexpected return(%d)!", ret);
+
+			if (gti->vrr_enabled)
+				goog_lookup_touch_report_rate(gti);
+		}
+	}
+}
+
+static const struct drm_bridge_funcs panel_bridge_funcs = {
+	.attach = panel_bridge_attach,
+	.detach = panel_bridge_detach,
+	.enable = panel_bridge_enable,
+	.disable = panel_bridge_disable,
+	.mode_set = panel_bridge_mode_set,
+};
+
+static int register_panel_bridge(struct goog_touch_interface *gti)
+{
+	GOOG_LOGI(gti, "\n");
+
+	INIT_WORK(&gti->set_op_hz_work, panel_set_op_hz);
+
+#ifdef CONFIG_OF
+	gti->panel_bridge.of_node = gti->vendor_dev->of_node;
+#endif
+	gti->panel_bridge.funcs = &panel_bridge_funcs;
+	drm_bridge_add(&gti->panel_bridge);
+
+	return 0;
+}
+
+static void unregister_panel_bridge(struct drm_bridge *bridge)
+{
+	struct goog_touch_interface *gti =
+		container_of(bridge, struct goog_touch_interface, panel_bridge);
+	struct drm_bridge *node;
+
+	GOOG_LOGI(gti, "\n");
+	drm_bridge_remove(bridge);
+
+	if (!bridge->dev) /* not attached */
+		return;
+
+	drm_modeset_lock(&bridge->dev->mode_config.connection_mutex, NULL);
+	list_for_each_entry(node, &bridge->encoder->bridge_chain, chain_node) {
+		if (node == bridge) {
+			if (bridge->funcs->detach)
+				bridge->funcs->detach(bridge);
+			list_del(&bridge->chain_node);
+			break;
+		}
+	}
+	drm_modeset_unlock(&bridge->dev->mode_config.connection_mutex);
+	bridge->dev = NULL;
+}
+
+/*-----------------------------------------------------------------------------
+ * GTI: functions.
+ */
+static int goog_precheck_heatmap(struct goog_touch_interface *gti)
+{
+	int ret = 0;
+
+	/*
+	 * Check the PM wakelock state and pm state for bus ownership before
+	 * data request.
+	 */
+	if (!goog_pm_wake_get_locks(gti) || gti->pm.state == GTI_PM_SUSPEND) {
+		GOOG_WARN(gti, "N/A during inactive bus!\n");
+		ret = -ENODATA;
+	}
+
+	return ret;
+}
+
+static void goog_set_display_state(struct goog_touch_interface *gti,
+	enum gti_display_state_setting display_state)
+{
+	int ret = 0;
+
+	if (gti->display_state == display_state)
+		return;
+
+	switch (display_state) {
+	case GTI_DISPLAY_STATE_OFF:
+		GOOG_INFO(gti, "screen-off.\n");
+		ret = goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_SCREEN_ON);
+		if (ret < 0)
+			GOOG_INFO(gti, "Error while obtaining screen-off wakelock: %d!\n", ret);
+
+		break;
+	case GTI_DISPLAY_STATE_ON:
+		GOOG_INFO(gti, "screen-on.\n");
+		ret = goog_pm_wake_lock_nosync(gti, GTI_PM_WAKELOCK_TYPE_SCREEN_ON, false);
+		if (ret < 0)
+			GOOG_INFO(gti, "Error while obtaining screen-on wakelock: %d!\n", ret);
+
+		break;
+	default:
+		GOOG_ERR(gti, "Unexpected value(0x%X) of display state parameter.\n",
+			display_state);
+		return;
+	}
+
+	gti->context_changed.screen_state = 1;
+	gti->display_state = display_state;
+	gti->cmd.display_state_cmd.setting = display_state;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_NOTIFY_DISPLAY_STATE);
+	if (ret && ret != -EOPNOTSUPP)
+		GOOG_WARN(gti, "Unexpected vendor_cmd return(%d)!\n", ret);
+}
+
+static int goog_do_selftest(struct goog_touch_interface *gti)
+{
+	int ret = 0;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SELFTEST);
+	if (gti->reset_after_selftest && ret != EOPNOTSUPP) {
+		gti->cmd.reset_cmd.setting = GTI_RESET_MODE_AUTO;
+		goog_process_vendor_cmd(gti, GTI_CMD_RESET);
+	}
+	return ret;
+}
+
+bool goog_check_spi_dma_enabled(struct spi_device *spi_dev)
+{
+	bool ret = false;
+
+	if (spi_dev && spi_dev->controller) {
+		struct device_node *np = spi_dev->controller->dev.of_node;
+
+		ret = of_property_present(np, "dmas");
+	}
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_check_spi_dma_enabled);
+
+int goog_get_max_touch_report_rate(struct goog_touch_interface *gti)
+{
+	int max_idx;
+
+	if (!gti ||
+		!gti->report_rate_table_size ||
+		!gti->touch_report_rate_table) {
+		return -EOPNOTSUPP;
+	}
+
+	max_idx = gti->report_rate_table_size - 1;
+	return gti->touch_report_rate_table[max_idx];
+}
+EXPORT_SYMBOL_GPL(goog_get_max_touch_report_rate);
+
+int goog_get_panel_id(struct device_node *node)
+{
+	int id = -1;
+	int err;
+	int index;
+	struct of_phandle_args panelmap;
+	struct drm_panel *panel = NULL;
+
+	if (!of_property_read_bool(node, "goog,panel_map")) {
+		pr_warn("%s: panel_map doesn't exist!\n", __func__);
+		return id;
+	}
+
+	for (index = 0;; index++) {
+		err = of_parse_phandle_with_fixed_args(
+			node, "goog,panel_map", 1, index, &panelmap);
+		if (err) {
+			pr_warn("%s: Fail to find panel for index: %d!\n", __func__, index);
+			break;
+		}
+
+		panel = of_drm_find_panel(panelmap.np);
+		of_node_put(panelmap.np);
+		if (IS_ERR_OR_NULL(panel))
+			continue;
+
+		id = panelmap.args[0];
+		break;
+	}
+
+	return id;
+}
+EXPORT_SYMBOL_GPL(goog_get_panel_id);
+
+int goog_get_firmware_name(struct device_node *node, int id, char *name, size_t size)
+{
+	int err;
+	const char *fw_name;
+
+	err = of_property_read_string_index(node, "goog,firmware_names", id, &fw_name);
+	if (err == 0) {
+		strlcpy(name, fw_name, size);
+		pr_info("%s: found firmware name: %s\n", __func__, name);
+	} else {
+		pr_warn("%s: Fail to find firmware name!\n", __func__);
+	}
+	return err;
+}
+EXPORT_SYMBOL_GPL(goog_get_firmware_name);
+
+int goog_get_config_name(struct device_node *node, int id, char *name, size_t size)
+{
+	int err;
+	const char *config_name;
+
+	err = of_property_read_string_index(node, "goog,config_names", id, &config_name);
+	if (err == 0) {
+		strncpy(name, config_name, size);
+		pr_info("%s: found config name: %s\n", __func__, name);
+	} else {
+		pr_warn("%s: Fail to find config name!\n", __func__);
+	}
+	return err;
+}
+EXPORT_SYMBOL_GPL(goog_get_config_name);
+
+int goog_get_test_limits_name(struct device_node *node, int id, char *name, size_t size)
+{
+	int err;
+	const char *limits_name;
+
+	err = of_property_read_string_index(node, "goog,test_limits_names", id, &limits_name);
+	if (err == 0) {
+		strncpy(name, limits_name, size);
+		pr_info("%s: found test limits name: %s\n", __func__, name);
+	} else {
+		pr_warn("%s: Fail to find test limits name!\n", __func__);
+	}
+	return err;
+}
+EXPORT_SYMBOL_GPL(goog_get_test_limits_name);
+
+int goog_process_vendor_cmd(struct goog_touch_interface *gti, enum gti_cmd_type cmd_type)
+{
+	void *private_data = gti->vendor_private_data;
+	int ret = -ESRCH;
+
+	/* Use optional vendor operation if available. */
+	switch (cmd_type) {
+	case GTI_CMD_CALIBRATE:
+		ret = gti->options.calibrate(private_data, &gti->cmd.calibrate_cmd);
+		break;
+	case GTI_CMD_PING:
+		ret = gti->options.ping(private_data, &gti->cmd.ping_cmd);
+		break;
+	case GTI_CMD_RESET:
+		ret = gti->options.reset(private_data, &gti->cmd.reset_cmd);
+		break;
+	case GTI_CMD_SELFTEST:
+		ret = gti->options.selftest(private_data, &gti->cmd.selftest_cmd);
+		break;
+	case GTI_CMD_GET_CONTEXT_DRIVER:
+		ret = gti->options.get_context_driver(private_data, &gti->cmd.context_driver_cmd);
+		break;
+	case GTI_CMD_GET_CONTEXT_STYLUS:
+		ret = gti->options.get_context_stylus(private_data, &gti->cmd.context_stylus_cmd);
+		break;
+	case GTI_CMD_GET_COORD_FILTER_ENABLED:
+		ret = gti->options.get_coord_filter_enabled(private_data,
+				&gti->cmd.coord_filter_cmd);
+		break;
+	case GTI_CMD_GET_FW_VERSION:
+		ret = gti->options.get_fw_version(private_data, &gti->cmd.fw_version_cmd);
+		break;
+	case GTI_CMD_GET_GRIP_MODE:
+		ret = gti->options.get_grip_mode(private_data, &gti->cmd.grip_cmd);
+		break;
+	case GTI_CMD_GET_IRQ_MODE:
+		ret = gti->options.get_irq_mode(private_data, &gti->cmd.irq_cmd);
+		break;
+	case GTI_CMD_GET_PALM_MODE:
+		ret = gti->options.get_palm_mode(private_data, &gti->cmd.palm_cmd);
+		break;
+	case GTI_CMD_GET_SCAN_MODE:
+		ret = gti->options.get_scan_mode(private_data, &gti->cmd.scan_cmd);
+		break;
+	case GTI_CMD_GET_SCREEN_PROTECTOR_MODE:
+		ret = gti->options.get_screen_protector_mode(private_data,
+				&gti->cmd.screen_protector_mode_cmd);
+		break;
+	case GTI_CMD_GET_SENSING_MODE:
+		ret = gti->options.get_sensing_mode(private_data, &gti->cmd.sensing_cmd);
+		break;
+	case GTI_CMD_GET_SENSOR_DATA:
+		if (gti->cmd.sensor_data_cmd.type & TOUCH_SCAN_TYPE_MUTUAL) {
+			ret = gti->options.get_mutual_sensor_data(
+				private_data, &gti->cmd.sensor_data_cmd);
+		} else if (gti->cmd.sensor_data_cmd.type & TOUCH_SCAN_TYPE_SELF) {
+			ret = gti->options.get_self_sensor_data(
+				private_data, &gti->cmd.sensor_data_cmd);
+		}
+		break;
+	case GTI_CMD_GET_SENSOR_DATA_MANUAL:
+		if (gti->cmd.manual_sensor_data_cmd.type & TOUCH_SCAN_TYPE_MUTUAL) {
+			ret = gti->options.get_mutual_sensor_data(
+				private_data, &gti->cmd.manual_sensor_data_cmd);
+		} else if (gti->cmd.manual_sensor_data_cmd.type & TOUCH_SCAN_TYPE_SELF) {
+			ret = gti->options.get_self_sensor_data(
+				private_data, &gti->cmd.manual_sensor_data_cmd);
+		}
+		break;
+	case GTI_CMD_NOTIFY_DISPLAY_STATE:
+		ret = gti->options.notify_display_state(private_data,
+				&gti->cmd.display_state_cmd);
+		break;
+	case GTI_CMD_NOTIFY_DISPLAY_VREFRESH:
+		ret = gti->options.notify_display_vrefresh(private_data,
+				&gti->cmd.display_vrefresh_cmd);
+		break;
+	case GTI_CMD_SET_CONTINUOUS_REPORT:
+		ret = gti->options.set_continuous_report(private_data,
+				&gti->cmd.continuous_report_cmd);
+		break;
+	case GTI_CMD_SET_COORD_FILTER_ENABLED:
+		ret = gti->options.set_coord_filter_enabled(private_data,
+				&gti->cmd.coord_filter_cmd);
+		break;
+	case GTI_CMD_SET_GESTURE_CONFIG:
+		ret = gti->options.set_gesture_config(private_data, &gti->cmd.gesture_config_cmd);
+		break;
+	case GTI_CMD_SET_GRIP_MODE:
+		GOOG_INFO(gti, "Set firmware grip %s",
+				gti->cmd.grip_cmd.setting == GTI_GRIP_ENABLE ?
+				"enabled" : "disabled");
+		ret = gti->options.set_grip_mode(private_data, &gti->cmd.grip_cmd);
+		break;
+	case GTI_CMD_SET_HEATMAP_ENABLED:
+		ret = gti->options.set_heatmap_enabled(private_data, &gti->cmd.heatmap_cmd);
+		break;
+	case GTI_CMD_SET_IRQ_MODE:
+		ret = gti->options.set_irq_mode(private_data, &gti->cmd.irq_cmd);
+		break;
+	case GTI_CMD_SET_PALM_MODE:
+		GOOG_INFO(gti, "Set firmware palm %s",
+				gti->cmd.palm_cmd.setting == GTI_PALM_ENABLE ?
+				"enabled" : "disabled");
+		ret = gti->options.set_palm_mode(private_data, &gti->cmd.palm_cmd);
+		break;
+	case GTI_CMD_SET_PANEL_SPEED_MODE:
+		GOOG_INFO(gti, "Set panel speed mode: %s",
+				gti->cmd.panel_speed_mode_cmd.setting == GTI_PANEL_SPEED_MODE_NS ?
+				"NS" : "HS");
+		ret = gti->options.set_panel_speed_mode(private_data, &gti->cmd.panel_speed_mode_cmd);
+		break;
+	case GTI_CMD_SET_REPORT_RATE:
+		GOOG_INFO(gti, "Set touch report rate as %d Hz", gti->cmd.report_rate_cmd.setting);
+		ret = gti->options.set_report_rate(private_data, &gti->cmd.report_rate_cmd);
+		break;
+	case GTI_CMD_SET_SCAN_MODE:
+		ret = gti->options.set_scan_mode(private_data, &gti->cmd.scan_cmd);
+		break;
+	case GTI_CMD_SET_SCREEN_PROTECTOR_MODE:
+		GOOG_INFO(gti, "Set screen protector mode %s",
+				gti->cmd.screen_protector_mode_cmd.setting ==
+				GTI_SCREEN_PROTECTOR_MODE_ENABLE
+				? "enabled" : "disabled");
+		ret = gti->options.set_screen_protector_mode(private_data,
+				&gti->cmd.screen_protector_mode_cmd);
+		break;
+	case GTI_CMD_SET_SENSING_MODE:
+		ret = gti->options.set_sensing_mode(private_data, &gti->cmd.sensing_cmd);
+		break;
+	default:
+		break;
+	}
+
+	/* Back to vendor default handler if no optional operation available. */
+	if (ret == -ESRCH)
+		ret = gti->vendor_default_handler(private_data, cmd_type, &gti->cmd);
+
+	/* Take unsupported cmd_type as debug logs for compatibility check. */
+	if (ret == -EOPNOTSUPP) {
+		GOOG_DBG(gti, "unsupported request cmd_type %#x!\n", cmd_type);
+		ret = 0;
+	} else if (ret == -ESRCH) {
+		GOOG_DBG(gti, "No handler for cmd_type %#x!\n", cmd_type);
+		ret = 0;
+	}
+
+	return ret;
+}
+
+void goog_update_motion_filter(struct goog_touch_interface *gti, unsigned long slot_bit)
+{
+	int ret = 0;
+	const u32 mf_timeout_ms = 500;
+	unsigned long touches = hweight_long(slot_bit);
+	u32 next_state = gti->mf_state;
+
+	switch (gti->mf_mode) {
+	case GTI_MF_MODE_AUTO_REPORT:
+	case GTI_MF_MODE_UNFILTER:
+		next_state = GTI_MF_STATE_UNFILTERED;
+		break;
+	case GTI_MF_MODE_FILTER:
+		next_state = GTI_MF_STATE_FILTERED;
+		break;
+	case GTI_MF_MODE_DYNAMIC:
+	default:
+		/*
+		* Determine the next filter state. The motion filter is enabled by
+		* default and it is disabled while a single finger is touching the
+		* screen. If another finger is touched down or if a timeout expires,
+		* the motion filter is reenabled and remains enabled until all fingers
+		* are lifted.
+		*/
+		switch (next_state) {
+		case GTI_MF_STATE_FILTERED:
+			if (touches == 1) {
+				next_state = GTI_MF_STATE_UNFILTERED;
+				gti->mf_downtime = ktime_get();
+			}
+			break;
+		case GTI_MF_STATE_UNFILTERED:
+			if (touches == 0) {
+				next_state = GTI_MF_STATE_FILTERED;
+			} else if (touches > 1 ||
+					ktime_after(ktime_get(),
+					ktime_add_ms(gti->mf_downtime, mf_timeout_ms))) {
+				next_state = GTI_MF_STATE_FILTERED_LOCKED;
+			}
+			break;
+		case GTI_MF_STATE_FILTERED_LOCKED:
+			if (touches == 0)
+				next_state = GTI_MF_STATE_FILTERED;
+			break;
+		}
+		break;
+	}
+
+	/* Send command to setup continuous report. */
+	if ((next_state == GTI_MF_STATE_UNFILTERED) !=
+		(gti->mf_state == GTI_MF_STATE_UNFILTERED)) {
+		gti->cmd.continuous_report_cmd.setting = GTI_CONTINUOUS_REPORT_DISABLE;
+
+		if (next_state == GTI_MF_STATE_UNFILTERED)
+			gti->cmd.continuous_report_cmd.setting = GTI_CONTINUOUS_REPORT_ENABLE;
+
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_CONTINUOUS_REPORT);
+		if (ret)
+			GOOG_LOGW(gti, "unexpected return(%d)!", ret);
+	}
+
+	if (ret == 0)
+		gti->mf_state = next_state;
+}
+
+bool goog_v4l2_read_frame_cb(struct v4l2_heatmap *v4l2)
+{
+	struct goog_touch_interface *gti = container_of(v4l2, struct goog_touch_interface, v4l2);
+	bool ret = false;
+	u32 v4l2_size = gti->v4l2.width * gti->v4l2.height * 2;
+
+	if (gti->heatmap_buf && v4l2_size == gti->heatmap_buf_size) {
+		memcpy(v4l2->frame, gti->heatmap_buf, v4l2_size);
+		ret = true;
+	} else {
+		GOOG_LOGE(gti, "wrong pointer(%p) or size (W: %lu, H: %lu) vs %u\n",
+		gti->heatmap_buf, gti->v4l2.width, gti->v4l2.height, gti->heatmap_buf_size);
+	}
+
+	return ret;
+}
+
+void goog_v4l2_read(struct goog_touch_interface *gti, ktime_t timestamp, u64 frame_index)
+{
+	if (gti->v4l2_enabled) {
+		gti->v4l2.frame_index = frame_index;
+		heatmap_read(&gti->v4l2, ktime_to_ns(timestamp));
+	}
+}
+
+int goog_get_driver_status(struct goog_touch_interface *gti,
+		struct gti_context_driver_cmd *driver_cmd)
+{
+	gti->context_changed.offload_timestamp = 1;
+
+	driver_cmd->context_changed.value = gti->context_changed.value;
+	driver_cmd->screen_state = gti->display_state;
+	driver_cmd->display_refresh_rate = gti->display_vrefresh;
+	driver_cmd->touch_report_rate = gti->report_rate_setting;
+	driver_cmd->noise_state = gti->fw_status.noise_level;
+	driver_cmd->water_mode = gti->fw_status.water_mode;
+	driver_cmd->charger_state = gti->charger_state;
+	driver_cmd->offload_timestamp = ktime_get();
+
+	/* vendor driver overwrite the context */
+	return goog_process_vendor_cmd(gti, GTI_CMD_GET_CONTEXT_DRIVER);
+}
+
+int goog_offload_populate_coordinate_channel(struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, int channel)
+{
+	int i;
+	struct TouchOffloadDataCoord *dc;
+
+	if (channel < 0 || channel >= MAX_CHANNELS) {
+		GOOG_LOGE(gti, "Invalid channel: %d\n", channel);
+		return -EINVAL;
+	}
+
+	dc = (struct TouchOffloadDataCoord *)frame->channel_data[channel];
+	memset(dc, 0, frame->channel_data_size[channel]);
+	dc->header.channel_type = TOUCH_DATA_TYPE_COORD;
+	dc->header.channel_size = TOUCH_OFFLOAD_FRAME_SIZE_COORD;
+
+	for (i = 0; i < MAX_SLOTS; i++) {
+		dc->coords[i].x = gti->offload.coords[i].x;
+		dc->coords[i].y = gti->offload.coords[i].y;
+		dc->coords[i].major = gti->offload.coords[i].major;
+		dc->coords[i].minor = gti->offload.coords[i].minor;
+		dc->coords[i].pressure = gti->offload.coords[i].pressure;
+		dc->coords[i].rotation = gti->offload.coords[i].rotation;
+		dc->coords[i].status = gti->offload.coords[i].status;
+	}
+
+	return 0;
+}
+
+int goog_offload_populate_mutual_channel(struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, int channel, u8 *buffer, u32 size)
+{
+	struct TouchOffloadData2d *mutual;
+
+	if (channel < 0 || channel >= MAX_CHANNELS) {
+		GOOG_LOGE(gti, "Invalid channel: %d\n", channel);
+		return -EINVAL;
+	}
+
+	mutual = (struct TouchOffloadData2d *)frame->channel_data[channel];
+	mutual->heatmap_width = gti->offload.caps.heatmap_width;
+	mutual->heatmap_height = gti->offload.caps.heatmap_height;
+	mutual->header.channel_type = frame->channel_type[channel];
+	mutual->header.channel_size =
+		TOUCH_OFFLOAD_FRAME_SIZE_2D(mutual->heatmap_height, mutual->heatmap_width);
+	if (IS_ERR_OR_NULL(buffer) ||
+		size != TOUCH_OFFLOAD_DATA_SIZE_2D(mutual->heatmap_height, mutual->heatmap_width)) {
+		GOOG_LOGW(gti, "invalid buffer %p or size %u!\n", buffer, size);
+		return -EINVAL;
+	}
+	memcpy(mutual->data, buffer, size);
+
+	return 0;
+}
+
+int goog_offload_populate_self_channel(struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, int channel, u8 *buffer, u32 size)
+{
+	struct TouchOffloadData1d *self;
+
+	if (channel < 0 || channel >= MAX_CHANNELS) {
+		GOOG_LOGE(gti, "Invalid channel: %d\n", channel);
+		return -EINVAL;
+	}
+
+	self = (struct TouchOffloadData1d *)frame->channel_data[channel];
+	self->heatmap_width = gti->offload.caps.heatmap_width;
+	self->heatmap_height = gti->offload.caps.heatmap_height;
+	self->header.channel_type = frame->channel_type[channel];
+	self->header.channel_size =
+		TOUCH_OFFLOAD_FRAME_SIZE_1D(self->heatmap_height, self->heatmap_width);
+	if (IS_ERR_OR_NULL(buffer) ||
+		size != TOUCH_OFFLOAD_DATA_SIZE_1D(self->heatmap_height, self->heatmap_width)) {
+		GOOG_LOGW(gti, "invalid buffer %p or size %u!\n", buffer, size);
+		return -EINVAL;
+	}
+	memcpy(self->data, buffer, size);
+
+	return 0;
+}
+
+static void goog_offload_populate_driver_status_channel(
+		struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, int channel,
+		struct gti_context_driver_cmd *driver_cmd)
+{
+	struct TouchOffloadDriverStatus *ds =
+		(struct TouchOffloadDriverStatus *)frame->channel_data[channel];
+
+	memset(ds, 0, frame->channel_data_size[channel]);
+	ds->header.channel_type = (u32)CONTEXT_CHANNEL_TYPE_DRIVER_STATUS;
+	ds->header.channel_size = sizeof(struct TouchOffloadDriverStatus);
+
+	ds->contents.screen_state = driver_cmd->context_changed.screen_state;
+	ds->screen_state = driver_cmd->screen_state;
+
+	ds->contents.display_refresh_rate = driver_cmd->context_changed.display_refresh_rate;
+	ds->display_refresh_rate = driver_cmd->display_refresh_rate;
+
+	ds->contents.touch_report_rate = driver_cmd->context_changed.touch_report_rate;
+	ds->touch_report_rate = driver_cmd->touch_report_rate;
+
+	ds->contents.noise_state = driver_cmd->context_changed.noise_state;
+	ds->noise_state = driver_cmd->noise_state;
+
+	ds->contents.water_mode = driver_cmd->context_changed.water_mode;
+	ds->water_mode = driver_cmd->water_mode;
+
+	ds->contents.charger_state = driver_cmd->context_changed.charger_state;
+	ds->charger_state = driver_cmd->charger_state;
+
+	ds->contents.offload_timestamp = driver_cmd->context_changed.offload_timestamp;
+	ds->offload_timestamp = driver_cmd->offload_timestamp;
+}
+
+static void goog_offload_populate_stylus_status_channel(
+		struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, int channel,
+		struct gti_context_stylus_cmd *stylus_cmd)
+{
+	struct TouchOffloadStylusStatus *ss =
+		(struct TouchOffloadStylusStatus *)frame->channel_data[channel];
+
+	memset(ss, 0, frame->channel_data_size[channel]);
+	ss->header.channel_type = (u32)CONTEXT_CHANNEL_TYPE_STYLUS_STATUS;
+	ss->header.channel_size = sizeof(struct TouchOffloadStylusStatus);
+
+	ss->contents.coords = stylus_cmd->contents.coords;
+	ss->coords[0] = stylus_cmd->pen_offload_coord;
+
+	ss->contents.coords_timestamp = stylus_cmd->contents.coords_timestamp;
+	ss->coords_timestamp = stylus_cmd->pen_offload_coord_timestamp;
+
+	ss->contents.pen_paired = stylus_cmd->contents.pen_paired;
+	ss->pen_paired = stylus_cmd->pen_paired;
+
+	ss->contents.pen_active = stylus_cmd->contents.pen_active;
+	ss->pen_active = stylus_cmd->pen_active;
+}
+
+static int goog_get_sensor_data(struct goog_touch_interface *gti,
+		struct gti_sensor_data_cmd *cmd, bool reset_data)
+{
+	int ret = 0;
+	int err = 0;
+	u16 tx = gti->offload.caps.heatmap_width;
+	u16 rx = gti->offload.caps.heatmap_height;
+
+	if (reset_data) {
+		if (cmd->type == GTI_SENSOR_DATA_TYPE_MS) {
+			cmd->size = TOUCH_OFFLOAD_DATA_SIZE_2D(rx, tx);
+		} else if (cmd->type == GTI_SENSOR_DATA_TYPE_SS) {
+			cmd->size = TOUCH_OFFLOAD_DATA_SIZE_1D(rx, tx);
+		} else {
+			ret = -EINVAL;
+			goto exit;
+		}
+
+		memset(gti->heatmap_buf, 0, cmd->size);
+		cmd->buffer = gti->heatmap_buf;
+		goto exit;
+	}
+
+	err = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_SENSOR_DATA, true);
+	if (err < 0) {
+		GOOG_WARN(gti, "Fail to lock GTI_PM_WAKELOCK_TYPE_SENSOR_DATA: %d!\n", err);
+		ret = err;
+		goto exit;
+	}
+
+	err = goog_process_vendor_cmd(gti, GTI_CMD_GET_SENSOR_DATA);
+	if (err < 0) {
+		GOOG_WARN(gti, "Fail to get sensor data: %d!\n", err);
+		ret = err;
+	}
+
+	err = goog_pm_wake_unlock(gti, GTI_PM_WAKELOCK_TYPE_SENSOR_DATA);
+	if (err < 0)
+		GOOG_WARN(gti, "Fail to unlock GTI_PM_WAKELOCK_TYPE_SENSOR_DATA: %d!\n", err);
+
+exit:
+	return ret;
+}
+
+void goog_offload_populate_frame(struct goog_touch_interface *gti,
+		struct touch_offload_frame *frame, bool reset_data)
+{
+	char trace_tag[128];
+	u32 channel_type;
+	int i;
+	int ret;
+	struct gti_sensor_data_cmd *cmd = &gti->cmd.sensor_data_cmd;
+
+	scnprintf(trace_tag, sizeof(trace_tag), "%s: IDX=%llu IN_TS=%lld.\n",
+		__func__, gti->frame_index, gti->input_timestamp);
+	ATRACE_BEGIN(trace_tag);
+
+	frame->header.index = gti->frame_index;
+	frame->header.timestamp = gti->input_timestamp;
+
+	/*
+	 * TODO(b/201610482):
+	 * Porting for other channels, like driver status, stylus status
+	 * and others.
+	 */
+
+	/* Populate all channels */
+	for (i = 0; i < frame->num_channels; i++) {
+		channel_type = frame->channel_type[i];
+		GOOG_DBG(gti, "#%d: get data(type %#x) from vendor driver", i, channel_type);
+		ret = 0;
+		cmd->buffer = NULL;
+		cmd->size = 0;
+		if (channel_type == CONTEXT_CHANNEL_TYPE_DRIVER_STATUS) {
+			ATRACE_BEGIN("populate driver context");
+			ret = goog_get_driver_status(gti, &gti->cmd.context_driver_cmd);
+			if (ret == 0)
+				goog_offload_populate_driver_status_channel(
+						gti, frame, i,
+						&gti->cmd.context_driver_cmd);
+			ATRACE_END();
+		} else if (channel_type == CONTEXT_CHANNEL_TYPE_STYLUS_STATUS) {
+			ATRACE_BEGIN("populate stylus context");
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_GET_CONTEXT_STYLUS);
+			if (ret == 0)
+				goog_offload_populate_stylus_status_channel(
+						gti, frame, i,
+						&gti->cmd.context_stylus_cmd);
+			ATRACE_END();
+		} else if (channel_type == TOUCH_DATA_TYPE_COORD) {
+			ATRACE_BEGIN("populate coord");
+			ret = goog_offload_populate_coordinate_channel(gti, frame, i);
+			ATRACE_END();
+		} else if (channel_type & TOUCH_SCAN_TYPE_MUTUAL) {
+			ATRACE_BEGIN("populate mutual data");
+			cmd->type = GTI_SENSOR_DATA_TYPE_MS;
+			ret = goog_get_sensor_data(gti, cmd, reset_data);
+			if (ret) {
+				GOOG_LOGW(gti, "Fail to get data(type %#x, ret %d)!\n",
+					cmd->type, ret);
+				cmd->buffer = NULL;
+			}
+			ret = goog_offload_populate_mutual_channel(gti, frame, i,
+				cmd->buffer, cmd->size);
+			/* Backup strength data for v4l2. */
+			if (ret == 0 && (channel_type & TOUCH_DATA_TYPE_STRENGTH))
+				memcpy(gti->heatmap_buf, cmd->buffer, cmd->size);
+			ATRACE_END();
+		} else if (channel_type & TOUCH_SCAN_TYPE_SELF) {
+			ATRACE_BEGIN("populate self data");
+			cmd->type = GTI_SENSOR_DATA_TYPE_SS;
+			ret = goog_get_sensor_data(gti, cmd, reset_data);
+			if (ret) {
+				GOOG_LOGW(gti, "Fail to get data(type %#x, ret %d)!\n",
+					cmd->type, ret);
+				cmd->buffer = NULL;
+			}
+			ret = goog_offload_populate_self_channel(gti, frame, i,
+				cmd->buffer, cmd->size);
+			ATRACE_END();
+		} else {
+			GOOG_ERR(gti, "unrecognized channel_type %#x.\n", channel_type);
+		}
+
+		/*
+		 * TODO:
+		 * Handle the error return for respective channel type and recycle
+		 * the offload frame gracefully.
+		 */
+		if (ret) {
+			GOOG_DBG(gti, "skip to populate data(type %#x, ret %d)!\n",
+				channel_type, ret);
+		}
+	}
+
+	ATRACE_END();
+}
+
+void goog_update_fw_settings(struct goog_touch_interface *gti, bool force_update)
+{
+	int error;
+	int ret = 0;
+	int i = 0;
+	bool enabled = false;
+	u32 original_setting = 0;
+
+	error = goog_pm_wake_lock_nosync(gti, GTI_PM_WAKELOCK_TYPE_FW_SETTINGS, true);
+	if (error < 0) {
+		GOOG_DBG(gti, "Error while obtaining FW_SETTINGS wakelock: %d!\n", error);
+		return;
+	}
+
+	if(!gti->ignore_grip_update) {
+		original_setting = gti->cmd.grip_cmd.setting;
+		if (gti->offload.offload_running && gti->offload.config.filter_grip)
+			gti->cmd.grip_cmd.setting = GTI_GRIP_DISABLE;
+		else
+			gti->cmd.grip_cmd.setting = gti->default_grip_enabled;
+
+		if (force_update || (original_setting != gti->cmd.grip_cmd.setting)) {
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_GRIP_MODE);
+			if (ret)
+				GOOG_LOGE(gti, "unexpected return(%d)!", ret);
+		}
+	}
+
+	if(!gti->ignore_palm_update) {
+		original_setting = gti->cmd.palm_cmd.setting;
+		if (gti->offload.offload_running && gti->offload.config.filter_palm)
+			gti->cmd.palm_cmd.setting = GTI_PALM_DISABLE;
+		else
+			gti->cmd.palm_cmd.setting = gti->default_palm_enabled;
+		if (force_update || (original_setting != gti->cmd.palm_cmd.setting)) {
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_PALM_MODE);
+			if (ret)
+				GOOG_LOGE(gti, "unexpected return(%d)!", ret);
+		}
+	}
+
+	if (gti->coord_filter_enabled) {
+		original_setting = gti->cmd.coord_filter_cmd.setting;
+		if (!gti->ignore_coord_filter_update) {
+			if (gti->offload.offload_running && gti->offload.config.coord_filter)
+				enabled = false;
+			else
+				enabled = gti->default_coord_filter_enabled;
+		} else {
+			enabled = gti->fw_coord_filter_enabled;
+		}
+
+		gti->cmd.coord_filter_cmd.setting = enabled ?
+				GTI_COORD_FILTER_ENABLE : GTI_COORD_FILTER_DISABLE;
+		if (force_update || (original_setting != gti->cmd.coord_filter_cmd.setting)) {
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_COORD_FILTER_ENABLED);
+			if (ret)
+				GOOG_LOGE(gti, "unexpected return(%d)!", ret);
+		}
+	}
+
+	if (gti->offload.caps.continuous_reporting) {
+		if (gti->offload.offload_running && gti->offload.config.continuous_reporting)
+			gti->mf_mode = GTI_MF_MODE_UNFILTER;
+		else
+			gti->mf_mode = GTI_MF_MODE_DEFAULT;
+		if (!gti->offload.config.coord_filter && gti->mf_mode == GTI_MF_MODE_UNFILTER)
+			GOOG_INFO(gti, "Enable GTI_MF_MODE_UNFILTER during coord_filter disabled!");
+	}
+
+	original_setting = gti->cmd.screen_protector_mode_cmd.setting;
+	gti->cmd.screen_protector_mode_cmd.setting = gti->screen_protector_mode_setting;
+	if (force_update || (original_setting != gti->cmd.screen_protector_mode_cmd.setting)) {
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_SCREEN_PROTECTOR_MODE);
+		if (ret != 0) {
+			GOOG_ERR(gti, "Fail to %s screen protector mode!\n",
+				gti->screen_protector_mode_setting ==
+					GTI_SCREEN_PROTECTOR_MODE_ENABLE ? "enable" : "disable");
+		}
+	}
+
+	original_setting = gti->cmd.heatmap_cmd.setting;
+	gti->cmd.heatmap_cmd.setting = GTI_HEATMAP_ENABLE;
+	if (force_update || (original_setting != gti->cmd.heatmap_cmd.setting)) {
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_HEATMAP_ENABLED);
+		if (ret != 0)
+			GOOG_ERR(gti, "Fail to set report rate!\n");
+	}
+
+	if (gti->vrr_enabled) {
+		original_setting = gti->cmd.report_rate_cmd.setting;
+		gti->cmd.report_rate_cmd.setting = gti->report_rate_setting_next;
+		if (force_update || (original_setting != gti->cmd.report_rate_cmd.setting)) {
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_REPORT_RATE);
+			if (ret != 0)
+				GOOG_ERR(gti, "Fail to set report rate!\n");
+		}
+	}
+
+	if (gti->panel_notifier_enabled) {
+		GOOG_LOGI(gti, "set panel op_hz: %d\n", gti->panel_op_hz);
+		original_setting = gti->cmd.panel_speed_mode_cmd.setting;
+		gti->cmd.panel_speed_mode_cmd.setting = gti->panel_op_hz == 120 ?
+			GTI_PANEL_SPEED_MODE_HS : GTI_PANEL_SPEED_MODE_NS;
+		if (force_update || (original_setting != gti->cmd.panel_speed_mode_cmd.setting)) {
+			ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_PANEL_SPEED_MODE);
+			if (ret != 0)
+				GOOG_LOGE(gti, "unexpected return(%d)!", ret);
+		}
+	}
+
+	/* Update LPTW gesture configs. */
+	if (force_update && gti->gesture_config_enabled) {
+		gti->cmd.gesture_config_cmd.params[GTI_GESTURE_TYPE] = GTI_GESTURE_DISABLE;
+
+		for (i = GTI_LPTW_MIN_X; i < GTI_GESTURE_PARAMS_MAX; i++)
+			gti->cmd.gesture_config_cmd.updating_params[i] = 1;
+
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_GESTURE_CONFIG);
+		if (ret != 0)
+			GOOG_ERR(gti, "Fail to set gesture configs!\n");
+	}
+
+	/*
+	 * Enable continuous_report when lptw_track_finger is set otherwise it's
+	 * possible there is no coordinate report if coordinate doesn't change.
+	 */
+	if (force_update && gti->lptw_suppress_coords_enabled) {
+		gti->cmd.continuous_report_cmd.setting = GTI_CONTINUOUS_REPORT_ENABLE;
+		ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_CONTINUOUS_REPORT);
+		if (ret)
+			GOOG_LOGE(gti, "unexpected return(%d)!", ret);
+	}
+
+	error = goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_FW_SETTINGS);
+	if (error < 0)
+		GOOG_DBG(gti, "Error while releasing FW_SETTINGS wakelock: %d!\n", error);
+}
+
+static void goog_offload_set_running(struct goog_touch_interface *gti, bool running)
+{
+	if (gti->offload.offload_running != running) {
+		GOOG_INFO(gti, "Set offload_running=%d irq_index=%llu input_index=%llu IDX=%llu\n",
+			running, gti->irq_index, gti->input_index, gti->frame_index);
+
+		gti->offload.offload_running = running;
+
+		goog_update_fw_settings(gti, false);
+	}
+}
+
+static void goog_report_lptw_cancel(struct goog_touch_interface *gti,
+		unsigned long slot_bit_cancel)
+{
+	int i = 0;
+	int coord_x = (gti->lptw_track_min_x + gti->lptw_track_max_x) / 2;
+	int coord_y = (gti->lptw_track_min_y + gti->lptw_track_max_y) / 2;
+
+	/* Early return if notification succeed, otherwise report it by input. */
+	if (goog_notify_lptw_left(gti) == NOTIFY_OK)
+		return;
+
+	/* Skip reporting input cancel if the finger stays over 500ms. */
+	if (ktime_after(ktime_get(), ktime_add_ms(gti->lptw_cancel_time, 500)))
+		return;
+
+	GOOG_INFO(gti, "Report LPTW cancel coord, slot: %#lx.", slot_bit_cancel);
+
+	goog_input_lock(gti);
+	gti_input_set_timestamp(gti, ktime_get());
+	for (i = 0; i < MAX_SLOTS; i++) {
+		if (!test_bit(i, &slot_bit_cancel))
+			continue;
+		/* Finger down. */
+		input_mt_slot(gti->vendor_input_dev, i);
+		input_report_key(gti->vendor_input_dev, BTN_TOUCH, 1);
+		input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_FINGER, 1);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_POSITION_X, coord_x);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_POSITION_Y, coord_y);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_TOUCH_MAJOR, 200);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_TOUCH_MINOR, 200);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_PRESSURE, 1);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_ORIENTATION, 0);
+		input_sync(gti->vendor_input_dev);
+
+		/* Report MT_TOOL_PALM for canceling the touch event. */
+		input_mt_slot(gti->vendor_input_dev, i);
+		input_report_key(gti->vendor_input_dev, BTN_TOUCH, 1);
+		input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_PALM, 1);
+		input_sync(gti->vendor_input_dev);
+
+		/* Release touches. */
+		input_mt_slot(gti->vendor_input_dev, i);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_PRESSURE, 0);
+		input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_FINGER, 0);
+		input_report_abs(gti->vendor_input_dev, ABS_MT_TRACKING_ID, -1);
+		input_report_key(gti->vendor_input_dev, BTN_TOUCH, 0);
+		input_sync(gti->vendor_input_dev);
+	}
+
+	goog_input_unlock(gti);
+}
+
+static void goog_lptw_cancel_delayed_work(struct work_struct *work)
+{
+	struct goog_touch_interface *gti;
+	struct delayed_work *delayed_work;
+	delayed_work = container_of(work, struct delayed_work, work);
+	gti = container_of(delayed_work, struct goog_touch_interface, lptw_cancel_delayed_work);
+
+	gti->lptw_track_finger = false;
+	goog_report_lptw_cancel(gti, 1);
+}
+
+void goog_save_tracking_slot(struct goog_touch_interface *gti, u16 x, u16 y, int slot_bit)
+{
+	if ((x > gti->lptw_track_min_x) && (x < gti->lptw_track_max_x) &&
+		(y > gti->lptw_track_min_y) && (y < gti->lptw_track_max_y)) {
+		if (gti->slot_bit_lptw_track != 0) {
+			GOOG_WARN(gti, "More than one finger in the tracking area, new slot:%#x",
+					slot_bit);
+			return;
+		}
+		set_bit(slot_bit, &gti->slot_bit_lptw_track);
+		GOOG_INFO(gti, "LPTW track slot bit %#lx", gti->slot_bit_lptw_track);
+	}
+}
+
+void goog_offload_input_report(void *handle,
+		 struct TouchOffloadIocReport *report)
+{
+	struct goog_touch_interface *gti = (struct goog_touch_interface *)handle;
+	bool touch_down = 0;
+	unsigned int tool_type = MT_TOOL_FINGER;
+	int i;
+	int error;
+	unsigned long slot_bit_active = 0;
+	unsigned long slot_bit_cancel = 0;
+	char trace_tag[128];
+	ktime_t ktime = ktime_get();
+
+	scnprintf(trace_tag, sizeof(trace_tag),
+		"%s: IDX=%llu IN_TS=%lld TS=%lld DELTA=%lld ns.\n",
+		__func__, report->index,
+		ktime_to_ns(report->timestamp), ktime_to_ns(ktime),
+		ktime_to_ns(ktime_sub(ktime, report->timestamp)));
+	ATRACE_BEGIN(trace_tag);
+
+	if (gti->lptw_suppress_coords_enabled && gti->lptw_track_finger)
+		cancel_delayed_work_sync(&gti->lptw_cancel_delayed_work);
+
+	goog_input_lock(gti);
+
+	if (ktime_before(report->timestamp, gti->input_dev_mono_ktime)) {
+		GOOG_WARN(gti, "Drop obsolete input(IDX=%llu IN_TS=%lld TS=%lld DELTA=%lld ns)!\n",
+			report->index,
+			ktime_to_ns(report->timestamp),
+			ktime_to_ns(gti->input_dev_mono_ktime),
+			ktime_to_ns(ktime_sub(gti->input_dev_mono_ktime, report->timestamp)));
+		goog_input_unlock(gti);
+		ATRACE_END();
+		return;
+	}
+
+	gti_input_set_timestamp(gti, report->timestamp);
+	for (i = 0; i < MAX_SLOTS; i++) {
+		if (report->coords[i].status != COORD_STATUS_INACTIVE) {
+			switch (report->coords[i].status) {
+			case COORD_STATUS_EDGE:
+			case COORD_STATUS_PALM:
+			case COORD_STATUS_CANCEL:
+				tool_type = MT_TOOL_PALM;
+				break;
+			case COORD_STATUS_FINGER:
+			case COORD_STATUS_PEN:
+			default:
+				tool_type = MT_TOOL_FINGER;
+				break;
+			}
+			set_bit(i, &slot_bit_active);
+
+			if (gti->lptw_suppress_coords_enabled) {
+				if (gti->lptw_track_finger) {
+					goog_save_tracking_slot(gti, report->coords[i].x,
+							report->coords[i].y, i);
+				}
+
+				if (test_bit(i, &gti->slot_bit_lptw_track)) {
+					goog_track_lptw_slot(gti, report->coords[i].x,
+							report->coords[i].y, i);
+					GOOG_DBG(gti, "Skip reporting lptw tracking slot %d", i);
+					continue;
+				}
+			}
+
+			input_mt_slot(gti->vendor_input_dev, i);
+			touch_down = 1;
+			input_report_key(gti->vendor_input_dev, BTN_TOUCH, touch_down);
+			input_mt_report_slot_state(gti->vendor_input_dev, tool_type, 1);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_POSITION_X,
+				report->coords[i].x);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_POSITION_Y,
+				report->coords[i].y);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_TOUCH_MAJOR,
+				report->coords[i].major);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_TOUCH_MINOR,
+				report->coords[i].minor);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_PRESSURE,
+				max_t(int, 1, report->coords[i].pressure));
+			if (report->coords[i].pressure == 0)
+				GOOG_WARN(gti, "Unexpected ZERO pressure reporting(slot#%d)!", i);
+			if (gti->offload.caps.rotation_reporting)
+				input_report_abs(gti->vendor_input_dev, ABS_MT_ORIENTATION,
+					report->coords[i].rotation);
+		} else {
+			clear_bit(i, &slot_bit_active);
+			if (gti->lptw_suppress_coords_enabled &&
+					test_and_clear_bit(i, &gti->slot_bit_lptw_track)) {
+				set_bit(i, &slot_bit_cancel);
+				if (gti->slot_bit_lptw_track == 0)
+					GOOG_INFO(gti, "All lptw tracking slots released");
+				continue;
+			}
+
+			input_mt_slot(gti->vendor_input_dev, i);
+			input_report_abs(gti->vendor_input_dev, ABS_MT_PRESSURE, 0);
+			/*
+			 * Force to cancel the active figner(s) by MT_TOOL_PALM during screen-off.
+			 */
+			if (gti->display_state == GTI_DISPLAY_STATE_OFF &&
+				gti->vendor_input_dev->mt &&
+				input_mt_is_active(&gti->vendor_input_dev->mt->slots[i])) {
+				input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_PALM, 1);
+				input_sync(gti->vendor_input_dev);
+			}
+			input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_FINGER, 0);
+		}
+	}
+	input_report_key(gti->vendor_input_dev, BTN_TOUCH, touch_down);
+	input_sync(gti->vendor_input_dev);
+	goog_input_unlock(gti);
+
+	if (touch_down)
+		goog_v4l2_read(gti, report->timestamp, report->index);
+
+	if (gti->lptw_suppress_coords_enabled) {
+		if (slot_bit_cancel || (gti->lptw_track_finger && gti->slot_bit_lptw_track == 0))
+			goog_report_lptw_cancel(gti, slot_bit_cancel);
+		gti->lptw_track_finger = false;
+	}
+
+	if (gti->pm.state == GTI_PM_RESUME) {
+		error = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_OFFLOAD_REPORT, true);
+		if (error < 0) {
+			GOOG_WARN(gti, "Error while obtaining OFFLOAD_REPORT wakelock: %d!\n",
+				error);
+			ATRACE_END();
+			return;
+		}
+		goog_update_motion_filter(gti, slot_bit_active);
+		error = goog_pm_wake_unlock(gti, GTI_PM_WAKELOCK_TYPE_OFFLOAD_REPORT);
+		if (error < 0)
+			GOOG_WARN(gti, "Error while releasing OFFLOAD_REPORT wakelock: %d!\n",
+					error);
+	}
+	ATRACE_END();
+}
+
+static int gti_update_charger_state(struct goog_touch_interface *gti,
+	struct power_supply *psy)
+{
+	union power_supply_propval present_val = { 0 };
+	int ret = 0;
+
+	if (gti == NULL || psy == NULL)
+		return -ENODEV;
+
+	ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_PRESENT,
+		&present_val);
+	if (ret < 0) {
+		GOOG_WARN(gti,
+			"Error while getting power supply property: %d!\n", ret);
+	} else if ((u8)present_val.intval != gti->charger_state) {
+		/* Note: the expected values for present_val.intval are
+		 * 0 and 1. Cast to unsigned byte to ensure the
+		 * comparison is handled in the same variable data type.
+		 */
+		GOOG_INFO(gti, "Charger_state changed from %d to %d\n",
+			gti->charger_state, present_val.intval);
+		gti->context_changed.charger_state = 1;
+		gti->charger_state = (u8)present_val.intval;
+	}
+	return ret;
+}
+
+int gti_charger_state_change(struct notifier_block *nb, unsigned long action,
+			     void *data)
+{
+	struct goog_touch_interface *gti =
+		(struct goog_touch_interface *)container_of(nb,
+			struct goog_touch_interface, charger_notifier);
+	struct power_supply *psy = (struct power_supply *)data;
+
+	/* Attempt actual status parsing */
+	if (psy && psy->desc && action == PSY_EVENT_PROP_CHANGED &&
+			!strcmp(psy->desc->name, gti->usb_psy_name)) {
+		gti_update_charger_state(gti, psy);
+	}
+	return NOTIFY_DONE;
+}
+
+int goog_offload_probe(struct goog_touch_interface *gti)
+{
+	int ret = 0;
+	int err = 0;
+	u16 values[2];
+	struct device_node *np = gti->vendor_dev->of_node;
+	const char *offload_dev_name = NULL;
+	struct of_phandle_args;
+	u8 *offload_ids_array;
+	int offload_ids_size;
+	int id_size;
+	const char *usb_psy_name = NULL;
+	bool is_default_offload_id = false;
+
+	/*
+	 * TODO(b/201610482): rename DEVICE_NAME in touch_offload.h for more specific.
+	 */
+	if (!of_property_read_string(np, "goog,offload-device-name", &offload_dev_name)) {
+		scnprintf(gti->offload.device_name, sizeof(gti->offload.device_name),
+			"%s_%s", DEVICE_NAME, offload_dev_name);
+	}
+
+	offload_ids_size = of_property_count_u8_elems(np, "goog,touch_offload_ids");
+	if (offload_ids_size > 0 && gti->panel_id >= 0) {
+		id_size = sizeof(gti->offload_id);
+
+		offload_ids_array = devm_kzalloc(gti->vendor_dev, offload_ids_size, GFP_KERNEL);
+		if (offload_ids_array == NULL) {
+			GOOG_WARN(gti, "Fail to alloc offload_ids_array");
+			err = -ENOMEM;
+		} else {
+			err = of_property_read_u8_array(np, "goog,touch_offload_ids",
+				offload_ids_array, offload_ids_size);
+			if (err == 0) {
+				if (id_size * (gti->panel_id + 1) <= offload_ids_size) {
+					memcpy(&gti->offload_id, offload_ids_array + id_size * gti->panel_id, id_size);
+				} else {
+					GOOG_WARN(gti, "Panel id is invalid, id: %d, ids size: %d",
+							gti->panel_id, offload_ids_size);
+					err = -EINVAL;
+				}
+			} else {
+				GOOG_WARN(gti, "Fail to read touch_offload_ids");
+			}
+		}
+	} else {
+		err = of_property_read_u8_array(np, "goog,touch_offload_id",
+				gti->offload_id_byte, 4);
+	}
+
+	if (err < 0) {
+		GOOG_INFO(gti, "set default offload id: GOOG!\n");
+		gti->offload_id_byte[0] = 'G';
+		gti->offload_id_byte[1] = 'O';
+		gti->offload_id_byte[2] = 'O';
+		gti->offload_id_byte[3] = 'G';
+		is_default_offload_id = true;
+	}
+
+	gti->offload.caps.touch_offload_major_version = TOUCH_OFFLOAD_INTERFACE_MAJOR_VERSION;
+	gti->offload.caps.touch_offload_minor_version = TOUCH_OFFLOAD_INTERFACE_MINOR_VERSION;
+	gti->offload.caps.device_id = gti->offload_id;
+	gti->offload.caps.touch_width =
+		input_abs_get_max(gti->vendor_input_dev, ABS_MT_POSITION_X) + 1;
+	gti->offload.caps.touch_height =
+		input_abs_get_max(gti->vendor_input_dev, ABS_MT_POSITION_Y) + 1;
+
+	if (of_property_read_u16_array(np, "goog,channel-num",
+					  values, 2) == 0) {
+		gti->offload.caps.heatmap_width = values[0];
+		gti->offload.caps.heatmap_height = values[1];
+	} else {
+		GOOG_ERR(gti, "Please set \"goog,channel-num\" in dts!");
+		/*
+		 * TODO(b/356993163): Refine the GTI capability.
+		 */
+		gti->offload.caps.tx_size = 50;
+		gti->offload.caps.rx_size = 50;
+	}
+
+	/*
+	 * TODO(b/201610482): Set more offload caps from parameters or from dtsi?
+	 */
+	gti->offload.caps.heatmap_size = HEATMAP_SIZE_FULL;
+	gti->offload.caps.bus_type = BUS_TYPE_SPI;
+	if (of_property_read_u32(np, "spi-max-frequency",
+			&gti->offload.caps.bus_speed_hz))
+		gti->offload.caps.bus_speed_hz = 0;
+
+	if (is_default_offload_id ||
+			of_property_read_u16(np, "goog,offload-caps-data-types",
+			&gti->offload.caps.touch_data_types)) {
+		gti->offload.caps.touch_data_types =
+			TOUCH_DATA_TYPE_COORD | TOUCH_DATA_TYPE_STRENGTH |
+			TOUCH_DATA_TYPE_RAW | TOUCH_DATA_TYPE_BASELINE |
+			TOUCH_DATA_TYPE_FILTERED;
+	}
+	if (is_default_offload_id ||
+			of_property_read_u16(np, "goog,offload-caps-scan-types",
+			&gti->offload.caps.touch_scan_types)) {
+		gti->offload.caps.touch_scan_types =
+			TOUCH_SCAN_TYPE_MUTUAL | TOUCH_SCAN_TYPE_SELF;
+	}
+	if (is_default_offload_id ||
+			of_property_read_u16(np, "goog,offload-caps-context-channel-types",
+			&gti->offload.caps.context_channel_types)) {
+		gti->offload.caps.context_channel_types =
+			CONTEXT_CHANNEL_TYPE_DRIVER_STATUS;
+	}
+	GOOG_INFO(gti, "offload.caps: data_types %#x, scan_types %#x, context_channel_types %#x.\n",
+		gti->offload.caps.touch_data_types,
+		gti->offload.caps.touch_scan_types,
+		gti->offload.caps.context_channel_types);
+
+	gti->offload.caps.continuous_reporting = true;
+	gti->offload.caps.noise_reporting = false;
+	gti->offload.caps.cancel_reporting =
+		!of_property_read_bool(np, "goog,offload-caps-cancel-reporting-disabled");
+	gti->offload.caps.size_reporting = true;
+	gti->offload.caps.filter_grip = true;
+	gti->offload.caps.filter_palm = true;
+	gti->offload.caps.coord_filter = gti->coord_filter_enabled &&
+		of_property_read_bool(np, "goog,offload-caps-coord-filter");
+	gti->offload.caps.num_sensitivity_settings = 1;
+	gti->offload.caps.rotation_reporting =
+		!of_property_read_bool(np, "goog,offload-caps-rotation-reporting-disabled");
+
+	gti->offload.hcallback = (void *)gti;
+	gti->offload.report_cb = goog_offload_input_report;
+	ret = touch_offload_init(&gti->offload);
+	if (ret) {
+		GOOG_ERR(gti, "offload init failed, ret %d!\n", ret);
+		goto err_offload_probe;
+	}
+
+	gti->offload_enabled = of_property_read_bool(np, "goog,offload-enabled");
+	GOOG_INFO(gti, "offload.caps: Coord W/H: %d * %d (Heatmap W/H: %d * %d).\n",
+		gti->offload.caps.touch_width, gti->offload.caps.touch_height,
+		gti->offload.caps.heatmap_width, gti->offload.caps.heatmap_height);
+
+	GOOG_INFO(gti, "offload ID: \"%c%c%c%c\" / 0x%08X, offload_enabled=%d.\n",
+		gti->offload_id_byte[0], gti->offload_id_byte[1], gti->offload_id_byte[2],
+		gti->offload_id_byte[3], gti->offload_id, gti->offload_enabled);
+
+	GOOG_INFO(gti, "offload.caps: version: %u.%u\n",
+		gti->offload.caps.touch_offload_major_version,
+		gti->offload.caps.touch_offload_minor_version);
+
+	gti->default_grip_enabled = of_property_read_bool(np,
+			"goog,default-grip-disabled") ? GTI_GRIP_DISABLE : GTI_GRIP_ENABLE;
+	gti->default_palm_enabled = of_property_read_bool(np,
+			"goog,default-palm-disabled") ? GTI_PALM_DISABLE : GTI_PALM_ENABLE;
+	gti->default_coord_filter_enabled = of_property_read_bool(np,
+			"goog,default-coord-filter-disabled") ?
+			GTI_COORD_FILTER_DISABLE : GTI_COORD_FILTER_ENABLE;
+
+	gti->heatmap_buf_size =
+		gti->offload.caps.heatmap_width * gti->offload.caps.heatmap_height * sizeof(u16);
+	gti->heatmap_buf = devm_kzalloc(gti->vendor_dev, gti->heatmap_buf_size, GFP_KERNEL);
+	if (!gti->heatmap_buf) {
+		GOOG_ERR(gti, "heamap alloc failed!\n");
+		ret = -ENOMEM;
+		goto err_offload_probe;
+	}
+
+	/*
+	 * Heatmap_probe must be called before irq routine is registered,
+	 * because heatmap_read is called from the irq context.
+	 * If the ISR runs before heatmap_probe is finished, it will invoke
+	 * heatmap_read and cause NPE, since read_frame would not yet be set.
+	 */
+	gti->v4l2.parent_dev = gti->vendor_dev;
+	gti->v4l2.input_dev = gti->vendor_input_dev;
+	gti->v4l2.read_frame = goog_v4l2_read_frame_cb;
+	gti->v4l2.width = gti->offload.caps.heatmap_width;
+	gti->v4l2.height = gti->offload.caps.heatmap_height;
+	gti->v4l2.frame_index_enabled = true;
+
+	/* 120 Hz operation */
+	gti->v4l2.timeperframe.numerator = 1;
+	if (of_property_read_u32(np, "goog,report-rate",
+			&gti->v4l2.timeperframe.denominator))
+		gti->v4l2.timeperframe.denominator = 120;
+
+	ret = heatmap_probe(&gti->v4l2);
+	if (ret) {
+		GOOG_ERR(gti, "v4l2 init failed, ret %d!\n", ret);
+		goto err_offload_probe;
+	}
+	gti->v4l2_enabled = of_property_read_bool(np, "goog,v4l2-enabled");
+	GOOG_INFO(gti, "v4l2 W/H=(%lu, %lu), v4l2_enabled=%d.\n",
+		gti->v4l2.width, gti->v4l2.height, gti->v4l2_enabled);
+
+	if (!of_property_read_string(np, "goog,usb-psy-name", &usb_psy_name))
+		strlcpy(gti->usb_psy_name, usb_psy_name, sizeof(gti->usb_psy_name));
+	else
+		strlcpy(gti->usb_psy_name, "usb", sizeof(gti->usb_psy_name));
+
+	/* Register for charger plugging status */
+	gti->charger_notifier.notifier_call = gti_charger_state_change;
+	ret = power_supply_reg_notifier(&gti->charger_notifier);
+	if (ret) {
+		GOOG_ERR(gti, "Fail to register power_supply_reg_notifier!\n");
+		goto err_offload_probe;
+	}
+
+	gti_update_charger_state(gti,
+		power_supply_get_by_name(gti->usb_psy_name));
+
+err_offload_probe:
+	return ret;
+}
+
+void goog_offload_remove(struct goog_touch_interface *gti)
+{
+	gti->offload_enabled = false;
+	gti->v4l2_enabled = false;
+	power_supply_unreg_notifier(&gti->charger_notifier);
+	touch_offload_cleanup(&gti->offload);
+	heatmap_remove(&gti->v4l2);
+	devm_kfree(gti->vendor_dev, gti->heatmap_buf);
+}
+
+static void goog_input_flush_offload_fingers(struct goog_touch_interface *gti)
+{
+	int i;
+	struct TouchOffloadCoord *coords;
+	ktime_t timestamp;
+	int touch_down = 0;
+
+	goog_input_lock(gti);
+	coords = gti->offload.coords;
+	if (gti->input_timestamp_changed) {
+		timestamp = gti->input_timestamp;
+	} else {
+		GOOG_WARN(gti, "No timestamp set by vendor driver before input report!");
+		timestamp = ktime_get();
+	}
+	gti_input_set_timestamp(gti, timestamp);
+	for (i = 0; i < MAX_SLOTS; i++) {
+		input_mt_slot(gti->vendor_input_dev, i);
+		if (coords[i].status != COORD_STATUS_INACTIVE) {
+			touch_down |= 1;
+			input_report_key(gti->vendor_input_dev, BTN_TOUCH, touch_down);
+			input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_FINGER, true);
+			input_report_abs(gti->vendor_input_dev,
+				ABS_MT_POSITION_X, coords[i].x);
+			input_report_abs(gti->vendor_input_dev,
+				ABS_MT_POSITION_Y, coords[i].y);
+			input_report_abs(gti->vendor_input_dev,
+				ABS_MT_TOUCH_MAJOR, coords[i].major);
+			input_report_abs(gti->vendor_input_dev,
+				ABS_MT_TOUCH_MINOR, coords[i].minor);
+			input_report_abs(gti->vendor_input_dev,
+				ABS_MT_PRESSURE, max_t(int, 1, coords[i].pressure));
+			if (gti->offload.caps.rotation_reporting)
+				input_report_abs(gti->vendor_input_dev, ABS_MT_ORIENTATION,
+					coords[i].rotation);
+		} else {
+			input_report_abs(gti->vendor_input_dev, ABS_MT_PRESSURE, 0);
+			input_mt_report_slot_state(gti->vendor_input_dev, MT_TOOL_FINGER, false);
+		}
+	}
+	input_report_key(gti->vendor_input_dev, BTN_TOUCH, touch_down);
+	input_sync(gti->vendor_input_dev);
+	goog_input_unlock(gti);
+}
+
+int goog_input_process(struct goog_touch_interface *gti, bool reset_data)
+{
+	int ret = 0;
+	struct touch_offload_frame **frame = &gti->offload_frame;
+	bool input_flush;
+
+	/*
+	 * Only do the input process if active slot(s) update
+	 * or slot(s) state change or resetting frame data.
+	 */
+	if (!(gti->slot_bit_active & gti->slot_bit_in_use) &&
+		!gti->slot_bit_changed && !reset_data)
+		return -EPERM;
+
+	mutex_lock(&gti->input_process_lock);
+	gti->frame_index++;
+
+	/*
+	 * Increase the input index when any slot bit changed which
+	 * means the finger is down or up.
+	 */
+	if (gti->slot_bit_changed)
+		gti->input_index++;
+
+	/*
+	 * Flush offload coords back to legacy input reporting for the
+	 * following cases:
+	 * 1. offload_enabled is disabled.
+	 * 2. Fail to reserve frame.
+	 * 3. Fail to queue frame.
+	 * Otherwise, goog_offload_input_report() will report coords later.
+	 */
+	input_flush = true;
+	if (gti->offload_enabled) {
+		ret = touch_offload_reserve_frame(&gti->offload, frame);
+		if (ret != 0 || frame == NULL) {
+			if (gti->offload.offload_running && gti->debug_warning_limit) {
+				gti->debug_warning_limit--;
+				GOOG_WARN(gti, "offload: No buffers available, ret=%d IDX=%llu!\n",
+					ret, gti->frame_index);
+			}
+			goog_offload_set_running(gti, false);
+			ret = -EBUSY;
+		} else {
+			if (!gti->offload.offload_running)
+				gti->debug_warning_limit = TOUCH_OFFLOAD_BUFFER_NUM;
+			goog_offload_set_running(gti, true);
+			goog_offload_populate_frame(gti, *frame, reset_data);
+			ret = touch_offload_queue_frame(&gti->offload, *frame);
+			if (ret) {
+				GOOG_WARN(gti, "Fail to queue frame, ret=%d IDX=%llu!\n",
+					ret, gti->frame_index);
+			} else {
+				gti->offload_frame = NULL;
+				input_flush = false;
+			}
+		}
+	}
+	if (input_flush)
+		goog_input_flush_offload_fingers(gti);
+
+	/*
+	 * If offload is NOT running, read heatmap directly by callback.
+	 * Otherwise, heatmap will be handled for both offload and v4l2
+	 * during goog_offload_populate_frame().
+	 */
+	if (!gti->offload.offload_running && gti->v4l2_enabled) {
+		int ret;
+		struct gti_sensor_data_cmd *cmd = &gti->cmd.sensor_data_cmd;
+
+		cmd->buffer = NULL;
+		cmd->size = 0;
+		cmd->type = GTI_SENSOR_DATA_TYPE_MS;
+		ret = goog_get_sensor_data(gti, cmd, reset_data);
+		if (ret == 0 && cmd->buffer && cmd->size)
+			memcpy(gti->heatmap_buf, cmd->buffer, cmd->size);
+		goog_v4l2_read(gti, gti->input_timestamp, gti->frame_index);
+		goog_update_motion_filter(gti, gti->slot_bit_active);
+	}
+
+	gti_debug_input_update(gti);
+	gti->input_timestamp_changed = false;
+	gti->slot_bit_in_use = 0;
+
+	mutex_unlock(&gti->input_process_lock);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_input_process);
+
+void goog_input_lock(struct goog_touch_interface *gti)
+{
+	if (!gti)
+		return;
+	mutex_lock(&gti->input_lock);
+}
+EXPORT_SYMBOL_GPL(goog_input_lock);
+
+void goog_input_unlock(struct goog_touch_interface *gti)
+{
+	if (!gti)
+		return;
+	mutex_unlock(&gti->input_lock);
+}
+EXPORT_SYMBOL_GPL(goog_input_unlock);
+
+void goog_input_set_timestamp(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, ktime_t timestamp)
+{
+	if (!gti) {
+		input_set_timestamp(dev, timestamp);
+		return;
+	}
+	gti->input_timestamp = timestamp;
+	gti->input_timestamp_changed = true;
+}
+EXPORT_SYMBOL_GPL(goog_input_set_timestamp);
+
+void goog_input_mt_slot(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, int slot)
+{
+	if (!gti) {
+		input_mt_slot(dev, slot);
+		return;
+	}
+
+	if (slot < 0 || slot >= MAX_SLOTS) {
+		GOOG_ERR(gti, "Invalid slot: %d\n", slot);
+		return;
+	}
+
+	gti->slot = slot;
+	/*
+	 * Make sure the input timestamp should be set before updating 1st mt_slot.
+	 * This is for input report switch between offload and legacy.
+	 */
+	if (!gti->slot_bit_in_use && !gti->input_timestamp_changed)
+		GOOG_ERR(gti, "please exec goog_input_set_timestamp before %s!\n", __func__);
+	set_bit(slot, &gti->slot_bit_in_use);
+}
+EXPORT_SYMBOL_GPL(goog_input_mt_slot);
+
+void goog_input_mt_report_slot_state(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int tool_type, bool active)
+{
+	if (!gti) {
+		input_mt_report_slot_state(dev, tool_type, active);
+		return;
+	}
+
+	switch (tool_type) {
+	case MT_TOOL_FINGER:
+		if (active) {
+			gti->offload.coords[gti->slot].status = COORD_STATUS_FINGER;
+			if (!test_and_set_bit(gti->slot,
+					&gti->slot_bit_active)) {
+				set_bit(gti->slot, &gti->slot_bit_changed);
+			}
+		} else {
+			gti->offload.coords[gti->slot].status = COORD_STATUS_INACTIVE;
+			if (test_and_clear_bit(gti->slot,
+					&gti->slot_bit_active)) {
+				set_bit(gti->slot, &gti->slot_bit_changed);
+			}
+		}
+		break;
+
+	default:
+		GOOG_WARN(gti, "unexcepted input tool_type(%#x) active(%d)!\n",
+			tool_type, active);
+		break;
+	}
+}
+EXPORT_SYMBOL_GPL(goog_input_mt_report_slot_state);
+
+void goog_input_report_abs(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int code, int value)
+{
+	if (!gti) {
+		input_report_abs(dev, code, value);
+		return;
+	}
+
+	switch (code) {
+	case ABS_MT_POSITION_X:
+		gti->offload.coords[gti->slot].x = value;
+		if ((value > gti->abs_x_max) || (value < gti->abs_x_min)) {
+			GOOG_WARN(gti, "Unexpected x-coord (slot#%d range#(%d, %d)), x: %d!",
+					gti->slot, gti->abs_x_min, gti->abs_x_max, value);
+		}
+		break;
+	case ABS_MT_POSITION_Y:
+		gti->offload.coords[gti->slot].y = value;
+		if ((value > gti->abs_y_max) || (value < gti->abs_y_min)) {
+			GOOG_WARN(gti, "Unexpected y-coord (slot#%d range#(%d, %d)), y: %d!",
+					gti->slot, gti->abs_y_min, gti->abs_y_max, value);
+		}
+		break;
+	case ABS_MT_TOUCH_MAJOR:
+		gti->offload.coords[gti->slot].major =
+                    value * gti->resolution_scale_factor;
+		break;
+	case ABS_MT_TOUCH_MINOR:
+		gti->offload.coords[gti->slot].minor =
+                    value * gti->resolution_scale_factor;
+		break;
+	case ABS_MT_PRESSURE:
+		gti->offload.coords[gti->slot].pressure = value;
+		break;
+	case ABS_MT_ORIENTATION:
+		gti->offload.coords[gti->slot].rotation = value;
+		break;
+	default:
+		break;
+	}
+}
+EXPORT_SYMBOL_GPL(goog_input_report_abs);
+
+void goog_input_report_key(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int code, int value)
+{
+	if (!gti) {
+		input_report_key(dev, code, value);
+		return;
+	}
+}
+EXPORT_SYMBOL_GPL(goog_input_report_key);
+
+void goog_input_sync(struct goog_touch_interface *gti, struct input_dev *dev)
+{
+	if (!gti) {
+		input_sync(dev);
+		return;
+	}
+}
+EXPORT_SYMBOL_GPL(goog_input_sync);
+
+void goog_input_release_all_fingers(struct goog_touch_interface *gti)
+{
+	int i;
+
+	goog_input_lock(gti);
+
+	goog_input_set_timestamp(gti, gti->vendor_input_dev, ktime_get());
+	for (i = 0; i < MAX_SLOTS; i++) {
+		goog_input_mt_slot(gti, gti->vendor_input_dev, i);
+		goog_input_mt_report_slot_state(
+			gti, gti->vendor_input_dev, MT_TOOL_FINGER, false);
+	}
+	goog_input_report_key(gti, gti->vendor_input_dev, BTN_TOUCH, 0);
+	goog_input_sync(gti, gti->vendor_input_dev);
+
+	goog_input_unlock(gti);
+
+	goog_input_process(gti, true);
+}
+
+void goog_register_tbn(struct goog_touch_interface *gti)
+{
+	struct device_node *np = gti->vendor_dev->of_node;
+
+	gti->tbn_enabled = of_property_read_bool(np, "goog,tbn-enabled");
+	if (gti->tbn_enabled) {
+		if (register_tbn(&gti->tbn_register_mask)) {
+			GOOG_ERR(gti, "Fail to register tbn context!\n");
+			gti->tbn_enabled = false;
+		} else {
+			GOOG_INFO(gti, "tbn_register_mask = %#x.\n", gti->tbn_register_mask);
+			register_tbn_lptw_callback(goog_notify_lptw_triggered, gti);
+		}
+	}
+}
+
+static int goog_calibrate_nop(
+		void *private_data, struct gti_calibrate_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_context_driver_nop(
+		void *private_data, struct gti_context_driver_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_context_stylus_nop(
+		void *private_data, struct gti_context_stylus_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_coord_filter_enabled_nop(
+		void *private_data, struct gti_coord_filter_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_fw_version_nop(
+		void *private_data, struct gti_fw_version_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_grip_mode_nop(
+		void *private_data, struct gti_grip_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_irq_mode_nop(
+		void *private_data, struct gti_irq_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_mutual_sensor_data_nop(
+		void *private_data, struct gti_sensor_data_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_palm_mode_nop(
+		void *private_data, struct gti_palm_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_scan_mode_nop(
+		void *private_data, struct gti_scan_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_screen_protector_mode_nop(
+		void *private_data, struct gti_screen_protector_mode_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_self_sensor_data_nop(
+		void *private_data, struct gti_sensor_data_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_get_sensing_mode_nop(
+		void *private_data, struct gti_sensing_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_notify_display_state_nop(
+		void *private_data, struct gti_display_state_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_notify_display_vrefresh_nop(
+		void *private_data, struct gti_display_vrefresh_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_ping_nop(
+		void *private_data, struct gti_ping_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_reset_nop(
+		void *private_data, struct gti_reset_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_selftest_nop(
+		void *private_data, struct gti_selftest_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_continuous_report_nop(
+		void *private_data, struct gti_continuous_report_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_coord_filter_enabled_nop(
+		void *private_data, struct gti_coord_filter_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_gesture_config_nop(
+		void *private_data, struct gti_gesture_config_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_grip_mode_nop(
+		void *private_data, struct gti_grip_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_heatmap_enabled_nop(
+		void *private_data, struct gti_heatmap_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_irq_mode_nop(
+		void *private_data, struct gti_irq_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_palm_mode_nop(
+		void *private_data, struct gti_palm_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_panel_speed_mode_nop(
+		void *private_data, struct gti_panel_speed_mode_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_report_rate_nop(
+		void *private_data, struct gti_report_rate_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_scan_mode_nop(
+		void *private_data, struct gti_scan_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_screen_protector_mode_nop(
+		void *private_data, struct gti_screen_protector_mode_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+static int goog_set_sensing_mode_nop(
+		void *private_data, struct gti_sensing_cmd *cmd)
+{
+	return -ESRCH;
+}
+
+void goog_init_input(struct goog_touch_interface *gti)
+{
+	int i;
+
+	if (!gti)
+		return;
+
+	INIT_KFIFO(gti->debug_fifo_healthcheck);
+	INIT_KFIFO(gti->debug_fifo_input);
+	for (i = 0 ; i < MAX_SLOTS ; i++)
+		gti->debug_input[i].slot = i;
+	gti->debug_warning_limit = TOUCH_OFFLOAD_BUFFER_NUM;
+
+	if (gti->vendor_dev && gti->vendor_input_dev) {
+		gti->abs_x_max = input_abs_get_max(gti->vendor_input_dev, ABS_MT_POSITION_X);
+		gti->abs_x_min = input_abs_get_min(gti->vendor_input_dev, ABS_MT_POSITION_X);
+		gti->abs_y_max = input_abs_get_max(gti->vendor_input_dev, ABS_MT_POSITION_Y);
+		gti->abs_y_min = input_abs_get_min(gti->vendor_input_dev, ABS_MT_POSITION_Y);
+
+		/*
+		 * Initialize the ABS_MT_ORIENTATION to support orientation reporting.
+		 * Initialize the ABS_MT_TOUCH_MAJOR and ABS_MT_TOUCH_MINOR depending on
+		 * the larger values of ABS_MT_POSITION_X and ABS_MT_POSITION_Y to support
+		 * shape algo reporting.
+		 */
+		if (gti->offload.caps.rotation_reporting) {
+			int abs_x_max = gti->abs_x_max;
+			int abs_x_min = gti->abs_x_min;
+			int abs_x_res = input_abs_get_res(gti->vendor_input_dev, ABS_MT_POSITION_X);
+			int abs_y_max = gti->abs_y_max;
+			int abs_y_min = gti->abs_y_min;
+			int abs_y_res = input_abs_get_res(gti->vendor_input_dev, ABS_MT_POSITION_Y);
+			int abs_major_max = abs_x_max;
+			int abs_major_min = abs_x_min;
+			int abs_major_res = abs_x_res;
+			int abs_minor_max = abs_y_max;
+			int abs_minor_min = abs_y_min;
+			int abs_minor_res = abs_y_res;
+
+			if (abs_x_max < abs_y_max) {
+				swap(abs_major_max, abs_minor_max);
+				swap(abs_major_min, abs_minor_min);
+				swap(abs_major_res, abs_minor_res);
+			}
+			input_set_abs_params(gti->vendor_input_dev, ABS_MT_ORIENTATION,
+				-4096, 4096, 0, 0);
+			input_set_abs_params(gti->vendor_input_dev, ABS_MT_TOUCH_MAJOR,
+				abs_major_min, abs_major_max, 0, 0);
+			input_set_abs_params(gti->vendor_input_dev, ABS_MT_TOUCH_MINOR,
+				abs_minor_min, abs_minor_max, 0, 0);
+			input_abs_set_res(gti->vendor_input_dev, ABS_MT_TOUCH_MAJOR, abs_major_res);
+			input_abs_set_res(gti->vendor_input_dev, ABS_MT_TOUCH_MINOR, abs_minor_res);
+		}
+
+		/*
+		 * Initialize the ABS_MT_TOOL_TYPE to support touch cancel.
+		 */
+		input_set_abs_params(gti->vendor_input_dev, ABS_MT_TOOL_TYPE,
+			MT_TOOL_FINGER, MT_TOOL_PALM, 0, 0);
+	}
+}
+
+void goog_init_options(struct goog_touch_interface *gti,
+		struct gti_optional_configuration *options)
+{
+	u32 coords[4];
+	u16 display_resolution[2];
+	int touch_max_x = 0;
+	int display_max_x = 0;
+
+	/* Initialize the common features. */
+	gti->mf_mode = GTI_MF_MODE_DEFAULT;
+	gti->screen_protector_mode_setting = GTI_SCREEN_PROTECTOR_MODE_DISABLE;
+	gti->display_state = GTI_DISPLAY_STATE_ON;
+
+	gti->panel_id = -1;
+	gti->resolution_scale_factor = 1;
+	if (gti->vendor_dev) {
+		struct device_node *np = gti->vendor_dev->of_node;
+
+		gti->ignore_force_active = of_property_read_bool(np, "goog,ignore-force-active");
+		gti->coord_filter_enabled = of_property_read_bool(np, "goog,coord-filter-enabled");
+		gti->manual_heatmap_from_irq = of_property_read_bool(np,
+				"goog,manual-heatmap-from-irq");
+		gti->lptw_suppress_coords_enabled = of_property_read_bool(np,
+				"goog,lptw-suppress-coords-enabled");
+
+		if (of_property_read_u16_array(np, "goog,display-resolution",
+			display_resolution, 2) == 0) {
+			/* Scale the tracking area to touch resolution. */
+			touch_max_x = input_abs_get_max(gti->vendor_input_dev, ABS_MT_POSITION_X) + 1;
+			display_max_x = display_resolution[0];
+			if (touch_max_x != 0 && display_max_x != 0) {
+				gti->resolution_scale_factor = touch_max_x / display_max_x;
+			}
+		}
+		GOOG_LOGI(gti, "resolution_scale_factor %d", gti->resolution_scale_factor);
+		if (gti->lptw_suppress_coords_enabled) {
+			if (of_property_read_u32_array(np, "goog,lptw-tracking-area", coords, 4)) {
+				GOOG_LOGE(gti, "goog,lptw-tracking-area not found\n");
+				coords[0] = 200;
+				coords[1] = 200;
+				coords[2] = 200;
+				coords[3] = 200;
+			}
+			gti->lptw_track_min_x = coords[0] * gti->resolution_scale_factor;
+			gti->lptw_track_max_x = coords[1] * gti->resolution_scale_factor;
+			gti->lptw_track_min_y = coords[2] * gti->resolution_scale_factor;
+			gti->lptw_track_max_y = coords[3] * gti->resolution_scale_factor;
+			GOOG_LOGI(gti, "goog,lptw-tracking-area %d, %d, %d, %d\n",
+					gti->lptw_track_min_x, gti->lptw_track_max_x,
+					gti->lptw_track_min_y, gti->lptw_track_max_y);
+			INIT_DELAYED_WORK(&gti->lptw_cancel_delayed_work, goog_lptw_cancel_delayed_work);
+		}
+		gti->panel_notifier_enabled = of_property_read_bool(np,
+				"goog,panel-notifier-enabled");
+		gti->reset_after_selftest = of_property_read_bool(np,
+				"goog,reset-after-selftest");
+
+		gti->panel_id = goog_get_panel_id(np);
+		if (gti->panel_id >= 0) {
+			goog_get_firmware_name(np, gti->panel_id, gti->fw_name, sizeof(gti->fw_name));
+			goog_get_config_name(np, gti->panel_id, gti->config_name, sizeof(gti->config_name));
+			goog_get_test_limits_name(np, gti->panel_id, gti->test_limits_name,
+					sizeof(gti->test_limits_name));
+		}
+	}
+
+	/* Initialize default functions. */
+	gti->options.calibrate = goog_calibrate_nop;
+	gti->options.get_context_driver = goog_get_context_driver_nop;
+	gti->options.get_context_stylus = goog_get_context_stylus_nop;
+	gti->options.get_coord_filter_enabled = goog_get_coord_filter_enabled_nop;
+	gti->options.get_fw_version = goog_get_fw_version_nop;
+	gti->options.get_grip_mode = goog_get_grip_mode_nop;
+	gti->options.get_irq_mode = goog_get_irq_mode_nop;
+	gti->options.get_mutual_sensor_data = goog_get_mutual_sensor_data_nop;
+	gti->options.get_palm_mode = goog_get_palm_mode_nop;
+	gti->options.get_scan_mode = goog_get_scan_mode_nop;
+	gti->options.get_screen_protector_mode = goog_get_screen_protector_mode_nop;
+	gti->options.get_self_sensor_data = goog_get_self_sensor_data_nop;
+	gti->options.get_sensing_mode = goog_get_sensing_mode_nop;
+	gti->options.notify_display_state = goog_notify_display_state_nop;
+	gti->options.notify_display_vrefresh = goog_notify_display_vrefresh_nop;
+	gti->options.ping = goog_ping_nop;
+	gti->options.reset = goog_reset_nop;
+	gti->options.selftest = goog_selftest_nop;
+	gti->options.set_continuous_report = goog_set_continuous_report_nop;
+	gti->options.set_coord_filter_enabled = goog_set_coord_filter_enabled_nop;
+	gti->options.set_gesture_config = goog_set_gesture_config_nop;
+	gti->options.set_grip_mode = goog_set_grip_mode_nop;
+	gti->options.set_heatmap_enabled = goog_set_heatmap_enabled_nop;
+	gti->options.set_irq_mode = goog_set_irq_mode_nop;
+	gti->options.set_palm_mode = goog_set_palm_mode_nop;
+	gti->options.set_panel_speed_mode = goog_set_panel_speed_mode_nop;
+	gti->options.set_report_rate = goog_set_report_rate_nop;
+	gti->options.set_scan_mode = goog_set_scan_mode_nop;
+	gti->options.set_screen_protector_mode = goog_set_screen_protector_mode_nop;
+	gti->options.set_sensing_mode = goog_set_sensing_mode_nop;
+
+	/* Set optional operation if available. */
+	if (options) {
+		if (options->calibrate)
+			gti->options.calibrate = options->calibrate;
+		if (options->get_context_driver)
+			gti->options.get_context_driver = options->get_context_driver;
+		if (options->get_context_stylus)
+			gti->options.get_context_stylus = options->get_context_stylus;
+		if (options->get_coord_filter_enabled)
+			gti->options.get_coord_filter_enabled = options->get_coord_filter_enabled;
+		if (options->get_fw_version)
+			gti->options.get_fw_version = options->get_fw_version;
+		if (options->get_grip_mode)
+			gti->options.get_grip_mode = options->get_grip_mode;
+		if (options->get_irq_mode)
+			gti->options.get_irq_mode = options->get_irq_mode;
+		if (options->get_mutual_sensor_data)
+			gti->options.get_mutual_sensor_data = options->get_mutual_sensor_data;
+		if (options->get_palm_mode)
+			gti->options.get_palm_mode = options->get_palm_mode;
+		if (options->get_scan_mode)
+			gti->options.get_scan_mode = options->get_scan_mode;
+		if (options->get_screen_protector_mode)
+			gti->options.get_screen_protector_mode = options->get_screen_protector_mode;
+		if (options->get_self_sensor_data)
+			gti->options.get_self_sensor_data = options->get_self_sensor_data;
+		if (options->get_sensing_mode)
+			gti->options.get_sensing_mode = options->get_sensing_mode;
+		if (options->notify_display_state)
+			gti->options.notify_display_state = options->notify_display_state;
+		if (options->notify_display_vrefresh) {
+			gti->options.notify_display_vrefresh =
+				options->notify_display_vrefresh;
+		}
+		if (options->ping)
+			gti->options.ping = options->ping;
+		if (options->reset)
+			gti->options.reset = options->reset;
+		if (options->selftest)
+			gti->options.selftest = options->selftest;
+		if (options->set_continuous_report)
+			gti->options.set_continuous_report = options->set_continuous_report;
+		if (options->set_coord_filter_enabled)
+			gti->options.set_coord_filter_enabled = options->set_coord_filter_enabled;
+		if (options->set_gesture_config)
+			gti->options.set_gesture_config = options->set_gesture_config;
+		if (options->set_grip_mode)
+			gti->options.set_grip_mode = options->set_grip_mode;
+		if (options->set_heatmap_enabled)
+			gti->options.set_heatmap_enabled = options->set_heatmap_enabled;
+		if (options->set_irq_mode)
+			gti->options.set_irq_mode = options->set_irq_mode;
+		if (options->set_palm_mode)
+			gti->options.set_palm_mode = options->set_palm_mode;
+		if (options->set_panel_speed_mode)
+			gti->options.set_panel_speed_mode = options->set_panel_speed_mode;
+		if (options->set_report_rate)
+			gti->options.set_report_rate = options->set_report_rate;
+		if (options->set_scan_mode)
+			gti->options.set_scan_mode = options->set_scan_mode;
+		if (options->set_screen_protector_mode)
+			gti->options.set_screen_protector_mode = options->set_screen_protector_mode;
+		if (options->set_sensing_mode)
+			gti->options.set_sensing_mode = options->set_sensing_mode;
+
+		gti->options.post_irq_thread_fn = options->post_irq_thread_fn;
+	}
+}
+
+int goog_pm_wake_lock_nosync(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type, bool skip_pm_resume)
+{
+	struct gti_pm* pm = NULL;
+
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+	pm = &gti->pm;
+
+	mutex_lock(&pm->lock_mutex);
+
+	if (pm->locks & type) {
+		GOOG_DBG(gti, "unexpectedly lock: locks=0x%04X, type=0x%04X\n",
+				pm->locks, type);
+		mutex_unlock(&pm->lock_mutex);
+		return -EINVAL;
+	}
+
+	/*
+	 * If NON_WAKE_UP is set and the pm is suspend, we should ignore it.
+	 * For example, IRQs should only keep the bus active. IRQs received
+	 * while the pm is suspend should be ignored.
+	 */
+	if (skip_pm_resume && pm->locks == 0) {
+		mutex_unlock(&pm->lock_mutex);
+		return -EAGAIN;
+	}
+
+	pm->locks |= type;
+
+	if (skip_pm_resume) {
+		mutex_unlock(&pm->lock_mutex);
+		return 0;
+	}
+
+	pm->new_state = GTI_PM_RESUME;
+	pm->update_state = true;
+	if (gti->event_wq != NULL)
+		queue_work(gti->event_wq, &pm->state_update_work);
+	mutex_unlock(&pm->lock_mutex);
+	return 0;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_lock_nosync);
+
+int goog_pm_wake_lock(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type, bool skip_pm_resume)
+{
+	struct gti_pm* pm = NULL;
+	int ret = 0;
+
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+	pm = &gti->pm;
+
+	ret = goog_pm_wake_lock_nosync(gti, type, skip_pm_resume);
+	if (ret < 0) return ret;
+	if (gti->event_wq != NULL)
+		flush_workqueue(gti->event_wq);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_lock);
+
+int goog_pm_wake_unlock_nosync(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type)
+{
+	struct gti_pm* pm = NULL;
+	int ret = 0;
+
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+	pm = &gti->pm;
+
+	mutex_lock(&pm->lock_mutex);
+
+	if (!(pm->locks & type)) {
+		GOOG_DBG(gti, "unexpectedly unlock: locks=0x%04X, type=0x%04X\n",
+				pm->locks, type);
+		mutex_unlock(&pm->lock_mutex);
+		return -EINVAL;
+	}
+
+	pm->locks &= ~type;
+
+	if (pm->locks == 0) {
+		pm->new_state = GTI_PM_SUSPEND;
+		pm->update_state = true;
+		if (gti->event_wq != NULL)
+			queue_work(gti->event_wq, &pm->state_update_work);
+	}
+	mutex_unlock(&pm->lock_mutex);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_unlock_nosync);
+
+int goog_pm_wake_unlock(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type)
+{
+	struct gti_pm* pm = NULL;
+	int ret = 0;
+
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+	pm = &gti->pm;
+
+	ret = goog_pm_wake_unlock_nosync(gti, type);
+	if (ret < 0) return ret;
+	if (gti->event_wq != NULL)
+		flush_workqueue(gti->event_wq);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_unlock);
+
+bool goog_pm_wake_check_locked(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type)
+{
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+
+	return gti->pm.locks & type ? true : false;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_check_locked);
+
+u32 goog_pm_wake_get_locks(struct goog_touch_interface *gti)
+{
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+
+	return gti->pm.locks;
+}
+EXPORT_SYMBOL_GPL(goog_pm_wake_get_locks);
+
+static void goog_pm_suspend(struct gti_pm *pm)
+{
+	struct goog_touch_interface *gti = container_of(pm,
+			struct goog_touch_interface, pm);
+	int ret = 0;
+
+	/* exit directly if device is already in suspend state */
+	if (pm->state == GTI_PM_SUSPEND) {
+		GOOG_WARN(gti, "GTI already suspended!\n");
+		return;
+	}
+
+	GOOG_LOGI(gti, "irq_index: %llu, input_index: %llu.\n", gti->irq_index, gti->input_index);
+	pm->state = GTI_PM_SUSPEND;
+
+	if (pm->suspend)
+		pm->suspend(gti->vendor_dev);
+
+	if (gti->tbn_register_mask) {
+		ret = tbn_release_bus(gti->tbn_register_mask);
+		if (ret)
+			GOOG_ERR(gti, "tbn_release_bus failed, ret %d!\n", ret);
+	}
+	gti_debug_healthcheck_dump(gti);
+	gti_debug_input_dump(gti);
+
+	goog_input_release_all_fingers(gti);
+
+	pm_relax(gti->dev);
+}
+
+static void goog_pm_resume(struct gti_pm *pm)
+{
+	struct goog_touch_interface *gti = container_of(pm,
+			struct goog_touch_interface, pm);
+	int ret = 0;
+
+	/* exit directly if device isn't in suspend state */
+	if (pm->state == GTI_PM_RESUME) {
+		GOOG_WARN(gti, "GTI already resumed!\n");
+		return;
+	}
+
+	pm_stay_awake(gti->dev);
+
+	if (gti->tbn_register_mask) {
+		gti->lptw_triggered = false;
+		ret = tbn_request_bus_with_result(gti->tbn_register_mask, &gti->lptw_triggered);
+		if (ret)
+			GOOG_ERR(gti, "tbn_request_bus failed, ret %d!\n", ret);
+	}
+
+	if (gti->lptw_suppress_coords_enabled && gti->lptw_triggered)
+		gti->lptw_cancel_time = ktime_get();
+
+	if (pm->resume)
+		pm->resume(gti->vendor_dev);
+
+	if (gti->lptw_suppress_coords_enabled && gti->lptw_triggered) {
+		gti->lptw_track_finger = true;
+		gti->slot_bit_lptw_track = 0;
+		queue_delayed_work(gti->event_wq, &gti->lptw_cancel_delayed_work,
+				msecs_to_jiffies(20));
+	}
+
+	/*
+	 * Reinitialize the mf_state to the default, then goog_update_motion_filter()
+	 * could base on up-to-date mf_mode to change accordingly.
+	 */
+	gti->mf_state = GTI_MF_STATE_FILTERED;
+	pm->state = GTI_PM_RESUME;
+}
+
+void goog_pm_state_update_work(struct work_struct *work) {
+	struct gti_pm *pm = container_of(work, struct gti_pm, state_update_work);
+	enum gti_pm_state new_state;
+
+	mutex_lock(&pm->lock_mutex);
+	while (pm->update_state) {
+		pm->update_state = false;
+		new_state = pm->new_state;
+		mutex_unlock(&pm->lock_mutex);
+		if (new_state != pm->state) {
+			if (new_state == GTI_PM_RESUME)
+				goog_pm_resume(pm);
+			else
+				goog_pm_suspend(pm);
+		}
+		mutex_lock(&pm->lock_mutex);
+	}
+	mutex_unlock(&pm->lock_mutex);
+}
+
+int goog_pm_register_notification(struct goog_touch_interface *gti,
+		const struct dev_pm_ops* ops)
+{
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+
+	gti->pm.resume = ops->resume;
+	gti->pm.suspend = ops->suspend;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(goog_pm_register_notification);
+
+int goog_pm_unregister_notification(struct goog_touch_interface *gti)
+{
+	if ((gti == NULL) || !gti->pm.enabled)
+		return -ENODEV;
+
+	gti->pm.resume = NULL;
+	gti->pm.suspend = NULL;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(goog_pm_unregister_notification);
+
+void goog_notify_fw_status_changed(struct goog_touch_interface *gti,
+		enum gti_fw_status status, struct gti_fw_status_data* data)
+{
+	const char *gesture_type = "N/A";
+
+	if (!gti)
+		return;
+
+	switch (status) {
+	case GTI_FW_STATUS_RESET:
+		GOOG_INFO(gti, "Firmware has been reset\n");
+		/*
+		 * Reinitialize the mf_state to the default, then goog_update_motion_filter()
+		 * could base on up-to-date mf_mode to change accordingly.
+		 */
+		gti->mf_state = GTI_MF_STATE_FILTERED;
+		goog_input_release_all_fingers(gti);
+		goog_update_fw_settings(gti, true);
+		break;
+	case GTI_FW_STATUS_PALM_ENTER:
+		GOOG_INFO(gti, "Enter palm mode\n");
+		break;
+	case GTI_FW_STATUS_PALM_EXIT:
+		GOOG_INFO(gti, "Exit palm mode\n");
+		break;
+	case GTI_FW_STATUS_GRIP_ENTER:
+		GOOG_INFO(gti, "Enter grip mode\n");
+		break;
+	case GTI_FW_STATUS_GRIP_EXIT:
+		GOOG_INFO(gti, "Exit grip mode\n");
+		break;
+	case GTI_FW_STATUS_WATER_ENTER:
+		GOOG_INFO(gti, "Enter water mode\n");
+		gti->fw_status.water_mode = 1;
+		gti->context_changed.water_mode = 1;
+		break;
+	case GTI_FW_STATUS_WATER_EXIT:
+		GOOG_INFO(gti, "Exit water mode\n");
+		gti->fw_status.water_mode = 0;
+		gti->context_changed.water_mode = 1;
+		break;
+	case GTI_FW_STATUS_NOISE_MODE:
+		if (data == NULL) {
+			GOOG_INFO(gti, "Noise level is changed, level: unknown\n");
+		} else {
+			if (data->noise_level == GTI_NOISE_MODE_EXIT) {
+				GOOG_INFO(gti, "Exit noise mode\n");
+				gti->fw_status.noise_level= 0;
+			} else {
+				GOOG_INFO(gti, "Enter noise mode, level: %d\n", data->noise_level);
+				gti->fw_status.noise_level = data->noise_level;
+			}
+			gti->context_changed.noise_state = 1;
+		}
+		break;
+	case GTI_FW_STATUS_GESTURE_EVENT:
+		if (data->gesture_event.type == GTI_GESTURE_STTW)
+			gesture_type = "STTW";
+		else if (data->gesture_event.type == GTI_GESTURE_LPTW)
+			gesture_type = "LPTW";
+		GOOG_INFO(gti, "Gesture %s detected, x:%u y:%u major:%u minor:%u angle:%d.\n",
+				gesture_type,
+				data->gesture_event.x,
+				data->gesture_event.y,
+				data->gesture_event.major,
+				data->gesture_event.minor,
+				data->gesture_event.angle);
+		break;
+	default:
+		break;
+	}
+}
+EXPORT_SYMBOL_GPL(goog_notify_fw_status_changed);
+
+static int goog_pm_probe(struct goog_touch_interface *gti)
+{
+	struct gti_pm* pm = &gti->pm;
+	int ret = 0;
+
+	pm->state = GTI_PM_RESUME;
+	pm->locks = GTI_PM_WAKELOCK_TYPE_SCREEN_ON;
+
+	mutex_init(&pm->lock_mutex);
+	INIT_WORK(&pm->state_update_work, goog_pm_state_update_work);
+
+	device_init_wakeup(gti->dev, true);
+	pm_stay_awake(gti->dev);
+
+	/* init pm_qos. */
+	cpu_latency_qos_add_request(&gti->pm_qos_req, PM_QOS_DEFAULT_VALUE);
+	pm->enabled = true;
+
+	return ret;
+}
+
+static int goog_pm_remove(struct goog_touch_interface *gti)
+{
+	struct gti_pm* pm = &gti->pm;
+
+	if (pm->enabled) {
+		pm->enabled = false;
+		cpu_latency_qos_remove_request(&gti->pm_qos_req);
+
+		pm_relax(gti->dev);
+		device_init_wakeup(gti->dev, false);
+	}
+
+	return 0;
+}
+
+static void goog_lookup_touch_report_rate(struct goog_touch_interface *gti)
+{
+	int i;
+	u32 next_report_rate = 0;
+
+	for (i = 0; i < gti->report_rate_table_size; i++) {
+		if (gti->display_vrefresh <= gti->display_refresh_rate_table[i]) {
+			next_report_rate = gti->touch_report_rate_table[i];
+			break;
+		}
+	}
+
+	/*
+	 * Set the touch report as minimum value if the display_vrefresh is smaller
+	 * than the minimum value of goog,display-vrr-table.
+	 */
+	if (next_report_rate == 0)
+		next_report_rate = gti->touch_report_rate_table[0];
+
+	if (gti->report_rate_setting_next != next_report_rate) {
+		cancel_delayed_work_sync(&gti->set_report_rate_work);
+		gti->report_rate_setting_next = next_report_rate;
+	}
+
+	if (gti->report_rate_setting_next != gti->report_rate_setting &&
+			gti->pm.state == GTI_PM_RESUME &&
+			gti->event_wq != NULL) {
+		queue_delayed_work(gti->event_wq, &gti->set_report_rate_work,
+				(gti->report_rate_setting_next > gti->report_rate_setting) ?
+				msecs_to_jiffies(gti->increase_report_rate_delay * MSEC_PER_SEC) :
+				msecs_to_jiffies(gti->decrease_report_rate_delay * MSEC_PER_SEC));
+	}
+}
+
+static void goog_set_report_rate_work(struct work_struct *work)
+{
+	int ret;
+	struct goog_touch_interface *gti;
+	struct delayed_work *delayed_work;
+	delayed_work = container_of(work, struct delayed_work, work);
+	gti = container_of(delayed_work, struct goog_touch_interface, set_report_rate_work);
+
+	if (gti->pm.state == GTI_PM_SUSPEND)
+		return;
+
+	if (gti->report_rate_setting == gti->report_rate_setting_next)
+		return;
+
+	/* Retry it 10ms later if there is finger on the screen. */
+	if (gti->slot_bit_active) {
+		if (gti->event_wq != NULL) {
+			queue_delayed_work(gti->event_wq, &gti->set_report_rate_work,
+					msecs_to_jiffies(10));
+		}
+		return;
+	}
+
+	gti->cmd.report_rate_cmd.setting = gti->report_rate_setting_next;
+	ret = goog_process_vendor_cmd(gti, GTI_CMD_SET_REPORT_RATE);
+	if (ret != 0) {
+		GOOG_ERR(gti, "Fail to set report rate!\n");
+		return;
+	}
+
+	gti->report_rate_setting = gti->report_rate_setting_next;
+	gti->context_changed.touch_report_rate = 1;
+}
+
+static int goog_init_variable_report_rate(struct goog_touch_interface *gti)
+{
+	int table_size = 0;
+
+	if (!gti->event_wq) {
+		GOOG_ERR(gti, "No workqueue for variable report rate.\n");
+		return -ENODEV;
+	}
+
+	gti->vrr_enabled = of_property_read_bool(gti->vendor_dev->of_node,
+			"goog,vrr-enabled");
+	if (!gti->vrr_enabled)
+		return 0;
+
+	table_size = of_property_count_u32_elems(gti->vendor_dev->of_node,
+			"goog,vrr-display-rate");
+	if (table_size != of_property_count_u32_elems(gti->vendor_dev->of_node,
+			"goog,vrr-touch-rate")) {
+		GOOG_ERR(gti, "Table size mismatch!\n");
+		goto init_variable_report_rate_failed;
+	}
+
+	gti->report_rate_table_size = table_size;
+
+	gti->display_refresh_rate_table = devm_kzalloc(gti->vendor_dev,
+			sizeof(u32) * table_size, GFP_KERNEL);
+	if (!gti->display_refresh_rate_table) {
+		GOOG_ERR(gti, "display_refresh_rate_table alloc failed.\n");
+		goto init_variable_report_rate_failed;
+	}
+
+	gti->touch_report_rate_table = devm_kzalloc(gti->vendor_dev,
+			sizeof(u32) * table_size, GFP_KERNEL);
+	if (!gti->touch_report_rate_table) {
+		GOOG_ERR(gti, "touch_report_rate_table alloc failed.\n");
+		goto init_variable_report_rate_failed;
+	}
+
+	if (of_property_read_u32_array(gti->vendor_dev->of_node, "goog,vrr-display-rate",
+			gti->display_refresh_rate_table, table_size)) {
+		GOOG_ERR(gti, "Fail to parse goog,display-vrr-table.\n");
+		goto init_variable_report_rate_failed;
+	}
+
+	if (of_property_read_u32_array(gti->vendor_dev->of_node, "goog,vrr-touch-rate",
+			gti->touch_report_rate_table, table_size)) {
+		GOOG_ERR(gti, "Fail to parse goog,touch-vrr-table.\n");
+		goto init_variable_report_rate_failed;
+	}
+
+	if (of_property_read_u32(gti->vendor_dev->of_node, "goog,vrr-up-delay",
+			&gti->increase_report_rate_delay)) {
+		gti->increase_report_rate_delay = 0;
+	}
+
+	if (of_property_read_u32(gti->vendor_dev->of_node, "goog,vrr-down-delay",
+			&gti->decrease_report_rate_delay)) {
+		gti->decrease_report_rate_delay = 0;
+	}
+
+	GOOG_INFO(gti, "Default report rate: %uHz, report rate delay %u/%u)",
+			gti->touch_report_rate_table[0],
+			gti->increase_report_rate_delay,
+			gti->decrease_report_rate_delay);
+
+	gti->report_rate_setting = gti->touch_report_rate_table[0];
+	gti->report_rate_setting_next = gti->touch_report_rate_table[0];
+	INIT_DELAYED_WORK(&gti->set_report_rate_work, goog_set_report_rate_work);
+
+	return 0;
+
+init_variable_report_rate_failed:
+	gti->vrr_enabled = false;
+	devm_kfree(gti->vendor_dev, gti->display_refresh_rate_table);
+	devm_kfree(gti->vendor_dev, gti->touch_report_rate_table);
+
+	return 0;
+}
+
+int goog_get_lptw_triggered(struct goog_touch_interface *gti)
+{
+	if (gti == NULL)
+		return -ENODEV;
+
+	return gti->lptw_triggered;
+}
+EXPORT_SYMBOL_GPL(goog_get_lptw_triggered);
+
+static void goog_notify_lptw_triggered(struct TbnLptwEvent *lptw, void *data)
+{
+	struct goog_touch_interface *gti = (struct goog_touch_interface *)data;
+
+	GOOG_INFO(gti, "Notify lptw event down");
+
+	gti->lptw_x = lptw->x;
+	gti->lptw_y = lptw->y;
+	gti->lptw_major = lptw->major;
+	gti->lptw_minor = lptw->minor;
+	gti->lptw_angle = lptw->angle;
+	raw_notifier_call_chain(&lptw_notifier, 1, (void *) &gti->lptw_data[0]);
+	gti->lptw_down = true;
+}
+
+void goog_lptw_notifier_register(struct notifier_block *nb, bool reg)
+{
+	if (reg)
+		raw_notifier_chain_register(&lptw_notifier, nb);
+	else
+		raw_notifier_chain_unregister(&lptw_notifier, nb);
+}
+EXPORT_SYMBOL_GPL(goog_lptw_notifier_register);
+
+static int goog_notify_lptw_left(struct goog_touch_interface *gti)
+{
+	int ret = 0;
+
+	if (gti->lptw_down) {
+		GOOG_INFO(gti, "Notify lptw event up");
+		gti->lptw_down = false;
+		ret = raw_notifier_call_chain(&lptw_notifier, 0, (void *) &gti->lptw_data[0]);
+		if (ret != NOTIFY_OK)
+			GOOG_INFO(gti, "Notify lptw event up failed, ret=%d", ret);
+	} else {
+		GOOG_INFO(gti, "Lptw event already up");
+		ret = NOTIFY_OK;
+	}
+
+	return ret;
+}
+
+static void goog_track_lptw_slot(struct goog_touch_interface *gti, u16 x, u16 y, int slot_bit)
+{
+	gti->lptw_x = x;
+	gti->lptw_y = y;
+
+	if (!gti->lptw_down)
+		return;
+
+	if ((x < gti->lptw_track_min_x) || (x > gti->lptw_track_max_x) ||
+		(y < gti->lptw_track_min_y) || (y > gti->lptw_track_max_y)) {
+		GOOG_INFO(gti, "The tracking slot %#x moves out from the tracking area",
+				slot_bit);
+		goog_notify_lptw_left(gti);
+	}
+}
+
+static void gti_input_set_timestamp(struct goog_touch_interface *gti, ktime_t timestamp)
+{
+	if (gti) {
+		input_set_timestamp(gti->vendor_input_dev, timestamp);
+		gti->input_dev_mono_ktime = timestamp;
+	}
+}
+
+static irqreturn_t gti_irq_handler(int irq, void *data)
+{
+	irqreturn_t ret;
+	struct goog_touch_interface *gti = (struct goog_touch_interface *)data;
+
+	gti->irq_index++;
+	if (gti->vendor_irq_handler != NULL && gti->vendor_irq_cookie != NULL)
+		ret = gti->vendor_irq_handler(irq, gti->vendor_irq_cookie);
+	else
+		ret = IRQ_WAKE_THREAD;
+	gti_debug_healthcheck_update(gti, true);
+	return ret;
+}
+
+static irqreturn_t gti_irq_thread_fn(int irq, void *data)
+{
+	int pm_ret;
+	irqreturn_t ret = IRQ_NONE;
+	struct goog_touch_interface *gti = (struct goog_touch_interface *)data;
+
+	ATRACE_BEGIN(__func__);
+	/*
+	 * Allow vendor driver to handle wake-up gesture events by irq_thread_fn()
+	 * after pm_suspend() complete without requiring a prior request for an IRQ
+	 * wakelock. This is only for the tbn_enabled disabled case.
+	 */
+	pm_ret = goog_pm_wake_lock(gti, GTI_PM_WAKELOCK_TYPE_IRQ, true);
+	if (pm_ret < 0 && gti->tbn_enabled) {
+		GOOG_WARN(gti, "Skipping stray interrupt, pm state: (%d, %d)\n",
+				gti->pm.state, gti->pm.new_state);
+		ATRACE_END();
+		return IRQ_HANDLED;
+	}
+
+	cpu_latency_qos_update_request(&gti->pm_qos_req, 100 /* usec */);
+
+	/*
+	 * Some vendor drivers read sensor data inside vendor_irq_thread_fn and
+	 * some inside goog_input_process. Use input_heatmap_lock to avoid race that
+	 * heatmap reading between sysfs/procfs and drivers concurrently.
+	 */
+	mutex_lock(&gti->input_heatmap_lock);
+
+	if (gti->vendor_irq_thread_fn != NULL && gti->vendor_irq_cookie != NULL)
+		ret = gti->vendor_irq_thread_fn(irq, gti->vendor_irq_cookie);
+	else
+		ret = IRQ_HANDLED;
+
+	goog_input_process(gti, false);
+
+	mutex_unlock(&gti->input_heatmap_lock);
+
+	if (ret == IRQ_HANDLED && gti->vendor_irq_thread_fn != NULL &&
+			gti->options.post_irq_thread_fn != NULL &&
+			gti->vendor_irq_cookie != NULL) {
+		ret = gti->options.post_irq_thread_fn(irq, gti->vendor_irq_cookie);
+	}
+
+	gti_debug_healthcheck_update(gti, false);
+	cpu_latency_qos_update_request(&gti->pm_qos_req, PM_QOS_DEFAULT_VALUE);
+	if (pm_ret == 0)
+		goog_pm_wake_unlock_nosync(gti, GTI_PM_WAKELOCK_TYPE_IRQ);
+	ATRACE_END();
+
+	return ret;
+}
+
+int goog_devm_request_threaded_irq(struct goog_touch_interface *gti,
+		struct device *dev, unsigned int irq,
+		irq_handler_t handler, irq_handler_t thread_fn,
+		unsigned long irqflags, const char *devname,
+		void *dev_id)
+{
+	int ret;
+
+	if (gti) {
+		gti->vendor_irq_cookie = dev_id;
+		gti->vendor_irq_handler = handler;
+		gti->vendor_irq_thread_fn = thread_fn;
+		ret = devm_request_threaded_irq(dev, irq, gti_irq_handler, gti_irq_thread_fn,
+				irqflags, devname, gti);
+	} else {
+		ret = devm_request_threaded_irq(dev, irq, handler, thread_fn,
+				irqflags, devname, dev_id);
+	}
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_devm_request_threaded_irq);
+
+void goog_devm_free_irq(struct goog_touch_interface *gti,
+		struct device *dev, unsigned int irq)
+{
+	devm_free_irq(dev, irq, gti);
+}
+EXPORT_SYMBOL(goog_devm_free_irq);
+
+int goog_request_threaded_irq(struct goog_touch_interface *gti,
+		unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn,
+		unsigned long irqflags, const char *devname, void *dev_id)
+{
+	int ret;
+
+	if (gti) {
+		gti->vendor_irq_cookie = dev_id;
+		gti->vendor_irq_handler = handler;
+		gti->vendor_irq_thread_fn = thread_fn;
+		ret = request_threaded_irq(irq, gti_irq_handler, gti_irq_thread_fn,
+				irqflags, devname, gti);
+	} else {
+		ret = request_threaded_irq(irq, handler, thread_fn, irqflags, devname, dev_id);
+	}
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(goog_request_threaded_irq);
+
+struct goog_touch_interface *goog_touch_interface_probe(
+		void *private_data,
+		struct device *dev,
+		struct input_dev *input_dev,
+		int (*default_handler)(void *private_data,
+			u32 cmd_type, struct gti_union_cmd_data *cmd),
+		struct gti_optional_configuration *options)
+{
+	int ret;
+	struct goog_touch_interface *gti;
+
+	if (!dev || !input_dev || !default_handler) {
+		pr_err("%s: error: invalid dev/input_dev or default_handler!\n", __func__);
+		return NULL;
+	}
+
+	gti = devm_kzalloc(dev, sizeof(struct goog_touch_interface), GFP_KERNEL);
+	if (gti) {
+		gti->vendor_private_data = private_data;
+		gti->vendor_dev = dev;
+		gti->vendor_input_dev = input_dev;
+		gti->vendor_default_handler = default_handler;
+		mutex_init(&gti->input_lock);
+		mutex_init(&gti->input_process_lock);
+		mutex_init(&gti->input_heatmap_lock);
+
+		gti->event_wq = alloc_workqueue(
+			"gti_wq", WQ_UNBOUND | WQ_HIGHPRI | WQ_CPU_INTENSIVE, 1);
+		if (!gti->event_wq) {
+			GOOG_ERR(gti, "Fail to create work thread for gti!\n");
+			return NULL;
+		}
+	}
+
+	if (!gti_class)
+		gti_class = class_create(THIS_MODULE, GTI_NAME);
+
+	if (gti && gti_class) {
+		u32 dev_id = gti_dev_num;
+		char *name;
+
+		if (gti->vendor_dev) {
+			struct device_node *np = gti->vendor_dev->of_node;
+
+			of_property_read_u32(np, "goog,dev-id", &dev_id);
+		}
+		name = kasprintf(GFP_KERNEL, "gti.%d", dev_id);
+
+		if (name &&
+			!alloc_chrdev_region(&gti->dev_id, 0, 1, name)) {
+			gti->dev = device_create(gti_class, NULL,
+					gti->dev_id, gti, name);
+			if (gti->dev) {
+				gti_dev_num++;
+				GOOG_LOGI(gti, "device create \"%s\".\n", name);
+				if (gti->vendor_dev) {
+					ret = sysfs_create_link(&gti->dev->kobj,
+						&gti->vendor_dev->kobj, "vendor");
+					if (ret) {
+						GOOG_ERR(gti, "sysfs_create_link() failed for vendor, ret=%d!\n",
+							ret);
+					}
+				}
+				if (gti->vendor_input_dev) {
+					ret = sysfs_create_link(&gti->dev->kobj,
+						&gti->vendor_input_dev->dev.kobj, "vendor_input");
+					if (ret) {
+						GOOG_ERR(gti, "sysfs_create_link() failed for vendor_input, ret=%d!\n",
+							 ret);
+					}
+				}
+			}
+		}
+		kfree(name);
+	}
+
+	if (gti && gti->dev) {
+		goog_init_proc(gti);
+		goog_init_options(gti, options);
+		goog_offload_probe(gti);
+		/*
+		 * goog_init_input() needs the offload.cap initialization by goog_offload_probe().
+		 */
+		goog_init_input(gti);
+		goog_register_tbn(gti);
+		goog_pm_probe(gti);
+		register_panel_bridge(gti);
+		goog_init_variable_report_rate(gti);
+		goog_update_fw_settings(gti, true);
+
+		ret = sysfs_create_group(&gti->dev->kobj, &goog_attr_group);
+		if (ret)
+			GOOG_ERR(gti, "sysfs_create_group() failed, ret= %d!\n", ret);
+	}
+
+	return gti;
+}
+EXPORT_SYMBOL_GPL(goog_touch_interface_probe);
+
+int goog_touch_interface_remove(struct goog_touch_interface *gti)
+{
+	if (!gti)
+		return -ENODEV;
+
+	if (gti->event_wq) {
+		destroy_workqueue(gti->event_wq);
+		gti->event_wq = NULL;
+	}
+
+	unregister_panel_bridge(&gti->panel_bridge);
+	goog_pm_remove(gti);
+
+	if (gti->tbn_enabled && gti->tbn_register_mask)
+		unregister_tbn(&gti->tbn_register_mask);
+
+	goog_offload_remove(gti);
+
+	if (gti->dev) {
+		sysfs_remove_group(&gti->dev->kobj, &goog_attr_group);
+		if (gti->vendor_dev)
+			sysfs_remove_link(&gti->dev->kobj, "vendor");
+		if (gti->vendor_input_dev)
+			sysfs_remove_link(&gti->dev->kobj, "vendor_input");
+		device_destroy(gti_class, gti->dev_id);
+		gti->dev = NULL;
+		gti_dev_num--;
+	}
+
+	if (gti_class) {
+		unregister_chrdev_region(gti->dev_id, 1);
+		if (!gti_dev_num) {
+			proc_remove(gti_proc_dir_root);
+			gti_proc_dir_root = NULL;
+			class_destroy(gti_class);
+			gti_class = NULL;
+		}
+	}
+
+	devm_kfree(gti->vendor_dev, gti);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(goog_touch_interface_remove);
+
+MODULE_DESCRIPTION("Google Touch Interface");
+MODULE_AUTHOR("Super Liu<supercjliu@google.com>");
+MODULE_LICENSE("GPL v2");
diff --git a/goog_touch_interface.h b/goog_touch_interface.h
new file mode 100644
index 0000000..1d9cf89
--- /dev/null
+++ b/goog_touch_interface.h
@@ -0,0 +1,1103 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Google Touch Interface for Pixel devices.
+ *
+ * Copyright 2022 Google LLC.
+ */
+
+#ifndef _GOOG_TOUCH_INTERFACE_
+#define _GOOG_TOUCH_INTERFACE_
+
+#include <drm/drm_panel.h>
+#include <drm/drm_bridge.h>
+#include <drm/drm_connector.h>
+#include <linux/kfifo.h>
+#include <linux/pm_qos.h>
+
+#include "heatmap.h"
+#include "touch_offload.h"
+#include "uapi/input/touch_offload.h"
+
+#define GTI_NAME "goog_touch_interface"
+#define GOOG_LOG_NAME(gti) ((gti && gti->dev) ? dev_name(gti->dev) : "gti")
+#define GOOG_DBG(gti, fmt, args...)  pr_debug("%s: " fmt, GOOG_LOG_NAME(gti), ##args)
+#define GOOG_INFO(gti, fmt, args...) pr_info("%s: " fmt, GOOG_LOG_NAME(gti), ##args)
+#define GOOG_WARN(gti, fmt, args...) pr_warn("%s: " fmt, GOOG_LOG_NAME(gti), ##args)
+#define GOOG_ERR(gti, fmt, args...)  pr_err("%s: " fmt, GOOG_LOG_NAME(gti), ##args)
+#define GOOG_LOGD(gti, fmt, args...) GOOG_DBG(gti, "%s: "fmt, __func__, ##args)
+#define GOOG_LOGI(gti, fmt, args...) GOOG_INFO(gti, "%s: "fmt, __func__, ##args)
+#define GOOG_LOGW(gti, fmt, args...) GOOG_WARN(gti, "%s: "fmt, __func__, ##args)
+#define GOOG_LOGE(gti, fmt, args...) GOOG_ERR(gti, "%s: "fmt, __func__, ##args)
+#define MAX_SLOTS 10
+/*
+ * GTI_DEBUG_HEALTHCHECK_KFIFO_LEN
+ * Define the array length of struct gti_debug_healthcheck to track recent
+ * touch interrupts information for debug.
+ */
+#define GTI_DEBUG_HEALTHCHECK_KFIFO_LEN 32	/* must be power of 2. */
+#define GTI_DEBUG_HEALTHCHECK_LOGS_LEN 4
+/*
+ * GTI_DEBUG_INPUT_KFIFO_LEN
+ * Define the array length of struct gti_debug_input to track recent
+ * touch input report for debug.
+ */
+#define GTI_DEBUG_INPUT_KFIFO_LEN 16	/* must be power of 2. */
+#define GTI_DEBUG_INPUT_LOGS_LEN 4
+
+/*-----------------------------------------------------------------------------
+ * Interactive calibration minimum and maximum state times.
+ */
+
+#define S_IN_NS 1000000000ULL  /* 1s = 1e9ns */
+
+/* Must wait at least 5s before beginning any operation */
+#define MIN_DELAY_IDLE		(5 * S_IN_NS)
+
+/* Must wait at least 1s between screen-turning-off and calibration start, and
+ * cannot stay in this state longer than 15s.
+ */
+#define MIN_DELAY_INIT_CAL	(1 * S_IN_NS)
+#define MAX_DELAY_INIT_CAL	(15 * S_IN_NS)
+
+/* Must wait at least 3s for calibration to complete and cannot stay in this
+ * state longer than 15s.
+ */
+#define MIN_DELAY_RUN_CAL	(3 * S_IN_NS)
+#define MAX_DELAY_RUN_CAL	(15 * S_IN_NS)
+
+/* Must wait at least 1s before final return to idle and cannot stay in this
+ * state longer than 15s.
+ */
+#define MIN_DELAY_END_CAL	(1 * S_IN_NS)
+#define MAX_DELAY_END_CAL	(15 * S_IN_NS)
+
+/* Must wait at least 1s between screen-turning-off and self-test start, and
+ * cannot state in this state longer than 15s.
+ */
+#define MIN_DELAY_INIT_TEST	(1 * S_IN_NS)
+#define MAX_DELAY_INIT_TEST	(15 * S_IN_NS)
+
+/* Must wait at least 3s for self-test to complete and cannot stay in this state
+ * longer than 15s.
+ */
+#define MIN_DELAY_RUN_TEST	(3 * S_IN_NS)
+#define MAX_DELAY_RUN_TEST	(15 * S_IN_NS)
+
+/* Must wait at least 1s before final return to idle and cannot stay in this
+ * state longer than 15s.
+ */
+#define MIN_DELAY_END_TEST	(1 * S_IN_NS)
+#define MAX_DELAY_END_TEST	(15 * S_IN_NS)
+
+/* Must wait at least 1s before beginning reset operation and cannot stay in this state
+ * longer than 15s.
+ */
+#define MIN_DELAY_INIT_RESET	(1 * S_IN_NS)
+#define MAX_DELAY_INIT_RESET	(15 * S_IN_NS)
+#define MIN_DELAY_RUN_RESET	(1 * S_IN_NS)
+#define MAX_DELAY_RUN_RESET	(15 * S_IN_NS)
+#define MIN_DELAY_END_RESET	(1 * S_IN_NS)
+#define MAX_DELAY_END_RESET	(15 * S_IN_NS)
+
+/*-----------------------------------------------------------------------------
+ * enums.
+ */
+
+enum gti_cmd_type : u32 {
+	/* GTI_CMD operations. */
+	GTI_CMD_OPS_START = 0x100,
+	GTI_CMD_CALIBRATE,
+	GTI_CMD_PING,
+	GTI_CMD_RESET,
+	GTI_CMD_SELFTEST,
+
+	/* GTI_CMD_GET operations. */
+	GTI_CMD_GET_OPS_START = 0x200,
+	GTI_CMD_GET_CONTEXT_DRIVER,
+	GTI_CMD_GET_CONTEXT_STYLUS,
+	GTI_CMD_GET_COORD_FILTER_ENABLED,
+	GTI_CMD_GET_FW_VERSION,
+	GTI_CMD_GET_GRIP_MODE,
+	GTI_CMD_GET_IRQ_MODE,
+	GTI_CMD_GET_PALM_MODE,
+	GTI_CMD_GET_SCAN_MODE,
+	GTI_CMD_GET_SCREEN_PROTECTOR_MODE,
+	GTI_CMD_GET_SENSING_MODE,
+	GTI_CMD_GET_SENSOR_DATA,
+	GTI_CMD_GET_SENSOR_DATA_MANUAL,
+
+	/* GTI_CMD_NOTIFY operations. */
+	GTI_CMD_NOTIFY_OPS_START = 0x300,
+	GTI_CMD_NOTIFY_DISPLAY_STATE,
+	GTI_CMD_NOTIFY_DISPLAY_VREFRESH,
+
+	/* GTI_CMD_SET operations. */
+	GTI_CMD_SET_OPS_START = 0x400,
+	GTI_CMD_SET_CONTINUOUS_REPORT,
+	GTI_CMD_SET_COORD_FILTER_ENABLED,
+	GTI_CMD_SET_GESTURE_CONFIG,
+	GTI_CMD_SET_GRIP_MODE,
+	GTI_CMD_SET_HEATMAP_ENABLED,
+	GTI_CMD_SET_IRQ_MODE,
+	GTI_CMD_SET_PALM_MODE,
+	GTI_CMD_SET_PANEL_SPEED_MODE,
+	GTI_CMD_SET_REPORT_RATE,
+	GTI_CMD_SET_SCAN_MODE,
+	GTI_CMD_SET_SCREEN_PROTECTOR_MODE,
+	GTI_CMD_SET_SENSING_MODE,
+};
+
+enum gti_calibrate_result : u32 {
+	GTI_CALIBRATE_RESULT_DONE = 0,
+	GTI_CALIBRATE_RESULT_SHELL_CMDS_REDIRECT,
+	GTI_CALIBRATE_RESULT_FAIL,
+	GTI_CALIBRATE_RESULT_NA = 0xFFFFFFFF,
+};
+
+enum gti_continuous_report_setting : u32 {
+	GTI_CONTINUOUS_REPORT_DISABLE = 0,
+	GTI_CONTINUOUS_REPORT_ENABLE,
+	GTI_CONTINUOUS_REPORT_DRIVER_DEFAULT,
+};
+
+enum gti_coord_filter_setting : u32 {
+	GTI_COORD_FILTER_DISABLE = 0,
+	GTI_COORD_FILTER_ENABLE,
+};
+
+enum gti_display_state_setting : u32 {
+	GTI_DISPLAY_STATE_OFF = 0,
+	GTI_DISPLAY_STATE_ON,
+};
+
+enum gti_grip_setting : u32 {
+	GTI_GRIP_DISABLE = 0,
+	GTI_GRIP_ENABLE,
+};
+
+enum gti_heatmap_setting : u32 {
+	GTI_HEATMAP_DISABLE = 0,
+	GTI_HEATMAP_ENABLE,
+};
+
+enum gti_irq_mode : u32 {
+	GTI_IRQ_MODE_DISABLE = 0,
+	GTI_IRQ_MODE_ENABLE,
+	GTI_IRQ_MODE_NA = 0xFFFFFFFF,
+};
+
+/**
+ * Motion filter mode.
+ *   GTI_MF_MODE_UNFILTER: enable unfilter by continuous reporting.
+ *   GTI_MF_MODE_DYNAMIC: dynamic control for motion filter.
+ *   GTI_MF_MODE_FILTER: only report touch if coord report changed.
+ *   GTI_MF_MODE_AUTO: for development case.
+ */
+enum gti_mf_mode : u32 {
+	GTI_MF_MODE_UNFILTER = 0,
+	GTI_MF_MODE_DEFAULT = 1,
+	GTI_MF_MODE_DYNAMIC = GTI_MF_MODE_DEFAULT,
+	GTI_MF_MODE_FILTER = 2,
+	GTI_MF_MODE_AUTO_REPORT = 3,
+};
+
+/**
+ * Motion filter finite state machine (FSM) state.
+ *   GTI_MF_STATE_FILTERED: default coordinate filtering
+ *   GTI_MF_STATE_UNFILTERED: coordinate unfiltering for single-touch.
+ *   GTI_MF_STATE_FILTERED_LOCKED: filtered coordinates. Locked until
+ *                                 touch is lifted or timeout.
+ */
+enum gti_mf_state : u32 {
+	GTI_MF_STATE_FILTERED = 0,
+	GTI_MF_STATE_UNFILTERED,
+	GTI_MF_STATE_FILTERED_LOCKED,
+};
+
+enum gti_palm_setting : u32 {
+	GTI_PALM_DISABLE = 0,
+	GTI_PALM_ENABLE,
+};
+
+enum gti_panel_speed_mode_setting : u32 {
+	GTI_PANEL_SPEED_MODE_NS = 0,
+	GTI_PANEL_SPEED_MODE_HS,
+};
+
+enum gti_ping_mode : u32 {
+	GTI_PING_NOP = 0,
+	GTI_PING_ENABLE,
+	GTI_PING_NA = 0xFFFFFFFF,
+};
+
+enum gti_pm_state : u32 {
+	GTI_PM_SUSPEND = 0,
+	GTI_PM_RESUME,
+};
+
+#define GTI_PM_WAKELOCK_TYPE_LOCK_MASK 0xFFFF
+/**
+ * @brief: wakelock type.
+ */
+enum gti_pm_wakelock_type : u32 {
+	GTI_PM_WAKELOCK_TYPE_SCREEN_ON = (1 << 0),
+	GTI_PM_WAKELOCK_TYPE_IRQ = (1 << 1),
+	GTI_PM_WAKELOCK_TYPE_FW_UPDATE = (1 << 2),
+	GTI_PM_WAKELOCK_TYPE_SYSFS = (1 << 3),
+	GTI_PM_WAKELOCK_TYPE_FORCE_ACTIVE = (1 << 4),
+	GTI_PM_WAKELOCK_TYPE_BUGREPORT = (1 << 5),
+	GTI_PM_WAKELOCK_TYPE_OFFLOAD_REPORT = (1 << 6),
+	GTI_PM_WAKELOCK_TYPE_SENSOR_DATA = (1 << 7),
+	GTI_PM_WAKELOCK_TYPE_FW_SETTINGS = (1 << 8),
+	GTI_PM_WAKELOCK_TYPE_VENDOR_REQUEST = (1 << 9),
+};
+
+enum gti_proc_type : u32 {
+	GTI_PROC_DUMP,
+	GTI_PROC_MS_BASE,
+	GTI_PROC_MS_DIFF,
+	GTI_PROC_MS_RAW,
+	GTI_PROC_SS_BASE,
+	GTI_PROC_SS_DIFF,
+	GTI_PROC_SS_RAW,
+	GTI_PROC_NUM,
+};
+
+enum gti_reset_mode : u32 {
+	GTI_RESET_MODE_NOP = 0,
+	GTI_RESET_MODE_SW = (1 << 0),
+	GTI_RESET_MODE_HW = (1 << 1),
+	GTI_RESET_MODE_AUTO = GTI_RESET_MODE_HW | GTI_RESET_MODE_SW,
+	GTI_RESET_MODE_NA = 0xFFFFFFFF,
+};
+
+enum gti_scan_mode : u32 {
+	GTI_SCAN_MODE_AUTO = 0,
+	GTI_SCAN_MODE_NORMAL_ACTIVE,
+	GTI_SCAN_MODE_NORMAL_IDLE,
+	GTI_SCAN_MODE_LP_ACTIVE,
+	GTI_SCAN_MODE_LP_IDLE,
+	GTI_SCAN_MODE_NA = 0xFFFFFFFF,
+};
+
+enum gti_screen_protector_mode : u32 {
+	GTI_SCREEN_PROTECTOR_MODE_DISABLE = 0,
+	GTI_SCREEN_PROTECTOR_MODE_ENABLE,
+	GTI_SCREEN_PROTECTOR_MODE_NA = 0xFFFFFFFF,
+};
+
+enum gti_selftest_result : u32 {
+	GTI_SELFTEST_RESULT_DONE = 0,
+	GTI_SELFTEST_RESULT_PASS = GTI_SELFTEST_RESULT_DONE,
+	GTI_SELFTEST_RESULT_SHELL_CMDS_REDIRECT,
+	GTI_SELFTEST_RESULT_FAIL = 0x80000000,
+	GTI_SELFTEST_RESULT_NA = 0xFFFFFFFF,
+};
+
+enum gti_sensing_mode : u32 {
+	GTI_SENSING_MODE_DISABLE = 0,
+	GTI_SENSING_MODE_ENABLE,
+	GTI_SENSING_MODE_NA = 0xFFFFFFFF,
+};
+
+/* Touch read method for automatically reading data from interrupt */
+#define TOUCH_SENSOR_DATA_READ_METHOD_INT 0x10000
+/* Touch read method for manually reading data from command */
+#define TOUCH_SENSOR_DATA_READ_METHOD_COMMAND 0x20000
+
+enum gti_sensor_data_type : u32 {
+	GTI_SENSOR_DATA_TYPE_COORD = TOUCH_DATA_TYPE_COORD,
+	GTI_SENSOR_DATA_TYPE_MS = TOUCH_SENSOR_DATA_READ_METHOD_INT |
+			TOUCH_SCAN_TYPE_MUTUAL | TOUCH_DATA_TYPE_STRENGTH,
+	GTI_SENSOR_DATA_TYPE_MS_DIFF = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_MUTUAL | TOUCH_DATA_TYPE_STRENGTH,
+	GTI_SENSOR_DATA_TYPE_MS_RAW = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_MUTUAL | TOUCH_DATA_TYPE_RAW,
+	GTI_SENSOR_DATA_TYPE_MS_BASELINE = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_MUTUAL | TOUCH_DATA_TYPE_BASELINE,
+	GTI_SENSOR_DATA_TYPE_SS = TOUCH_SENSOR_DATA_READ_METHOD_INT |
+			TOUCH_SCAN_TYPE_SELF | TOUCH_DATA_TYPE_STRENGTH,
+	GTI_SENSOR_DATA_TYPE_SS_DIFF = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_SELF | TOUCH_DATA_TYPE_STRENGTH,
+	GTI_SENSOR_DATA_TYPE_SS_RAW = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_SELF | TOUCH_DATA_TYPE_RAW,
+	GTI_SENSOR_DATA_TYPE_SS_BASELINE = TOUCH_SENSOR_DATA_READ_METHOD_COMMAND |
+			TOUCH_SCAN_TYPE_SELF | TOUCH_DATA_TYPE_BASELINE,
+};
+
+enum gti_fw_status : u32 {
+	GTI_FW_STATUS_RESET = 0,
+	GTI_FW_STATUS_PALM_ENTER,
+	GTI_FW_STATUS_PALM_EXIT,
+	GTI_FW_STATUS_GRIP_ENTER,
+	GTI_FW_STATUS_GRIP_EXIT,
+	GTI_FW_STATUS_WATER_ENTER,
+	GTI_FW_STATUS_WATER_EXIT,
+	GTI_FW_STATUS_NOISE_MODE,
+	GTI_FW_STATUS_GESTURE_EVENT,
+};
+
+enum gti_gesture_params : u8 {
+	GTI_STTW_MIN_X = 0,
+	GTI_STTW_MAX_X,
+	GTI_STTW_MIN_Y,
+	GTI_STTW_MAX_Y,
+	GTI_STTW_MIN_FRAME,
+	GTI_STTW_MAX_FRAME,
+	GTI_STTW_JITTER,
+	GTI_STTW_MAX_TOUCH_SIZE,
+
+	GTI_LPTW_MIN_X,
+	GTI_LPTW_MAX_X,
+	GTI_LPTW_MIN_Y,
+	GTI_LPTW_MAX_Y,
+	GTI_LPTW_MIN_FRAME,
+	GTI_LPTW_JITTER,
+	GTI_LPTW_MAX_TOUCH_SIZE,
+	GTI_LPTW_MARGINAL_MIN_X,
+	GTI_LPTW_MARGINAL_MAX_X,
+	GTI_LPTW_MARGINAL_MIN_Y,
+	GTI_LPTW_MARGINAL_MAX_Y,
+	GTI_LPTW_MONITOR_CH_MIN_TX,
+	GTI_LPTW_MONITOR_CH_MAX_TX,
+	GTI_LPTW_MONITOR_CH_MIN_RX,
+	GTI_LPTW_MONITOR_CH_MAX_RX,
+	GTI_LPTW_NODE_COUNT_MIN,
+	GTI_LPTW_MOTION_BOUNDARY,
+
+	GTI_GESTURE_TYPE,
+
+	GTI_GESTURE_PARAMS_MAX,
+};
+
+enum gti_gesture_type : u8 {
+	GTI_GESTURE_DISABLE = 0,
+	GTI_GESTURE_STTW,
+	GTI_GESTURE_LPTW,
+	GTI_GESTURE_STTW_AND_LPTW,
+	GTI_GESTURE_TYPE_MAX,
+};
+
+enum gti_noise_mode_level : u8 {
+	GTI_NOISE_MODE_EXIT = 0,
+	GTI_NOISE_MODE_LEVEL1,
+	GTI_NOISE_MODE_LEVEL2,
+	GTI_NOISE_MODE_LEVEL3,
+};
+
+enum gti_ical_res : u32 {
+	ICAL_RES_SUCCESS = 0,
+	ICAL_RES_FAIL = 0x80000000,
+	ICAL_RES_FAIL_INVALID_BUS_ACCESS = 0x80000001,
+	ICAL_RES_NA = 0xFFFFFFFF,
+};
+
+enum gti_ical_state : u32 {
+	ICAL_STATE_IDLE = 0,
+	ICAL_STATE_INIT_CAL = 101,
+	ICAL_STATE_RUN_CAL = 102,
+	ICAL_STATE_END_CAL = 103,
+	ICAL_STATE_INIT_TEST = 201,
+	ICAL_STATE_RUN_TEST = 202,
+	ICAL_STATE_END_TEST = 203,
+	ICAL_STATE_INIT_RESET = 301,
+	ICAL_STATE_RUN_RESET = 302,
+	ICAL_STATE_END_RESET = 303,
+	ICAL_STATE_NA = 0xFFFFFFFF,
+};
+
+/*-----------------------------------------------------------------------------
+ * const char.
+ */
+
+const static char *gesture_params_list[GTI_GESTURE_PARAMS_MAX] = {
+	"sttw_min_x",
+	"sttw_max_x",
+	"sttw_min_y",
+	"sttw_max_y",
+	"sttw_min_frame",
+	"sttw_max_frame",
+	"sttw_jitter",
+	"sttw_max_touch_size",
+	"lptw_min_x",
+	"lptw_max_x",
+	"lptw_min_y",
+	"lptw_max_y",
+	"lptw_min_frame",
+	"lptw_jitter",
+	"lptw_max_touch_size",
+	"lptw_marginal_min_x",
+	"lptw_marginal_max_x",
+	"lptw_marginal_min_y",
+	"lptw_marginal_max_y",
+	"lptw_monitor_ch_min_tx",
+	"lptw_monitor_ch_max_tx",
+	"lptw_monitor_ch_min_rx",
+	"lptw_monitor_ch_max_rx",
+	"lptw_node_count_min",
+	"lptw_motion_boundary",
+	"gesture_type",
+};
+
+/*-----------------------------------------------------------------------------
+ * Structures.
+ */
+
+struct gti_calibrate_cmd {
+	enum gti_calibrate_result result;
+	char buffer[PAGE_SIZE];
+};
+
+struct gti_context_changed {
+	union {
+		struct {
+		u32 screen_state : 1;
+		u32 display_refresh_rate : 1;
+		u32 touch_report_rate : 1;
+		u32 noise_state : 1;
+		u32 water_mode : 1;
+		u32 charger_state : 1;
+		u32 hinge_angle : 1;
+		u32 offload_timestamp : 1;
+		};
+		u32 value;
+	};
+};
+
+struct gti_context_driver_cmd {
+	struct gti_context_changed context_changed;
+
+	u8 screen_state;
+	u8 display_refresh_rate;
+	u8 touch_report_rate;
+	u8 noise_state;
+	u8 water_mode;
+	u8 charger_state;
+	s16 hinge_angle;
+
+	ktime_t offload_timestamp;
+};
+
+struct gti_context_stylus_cmd {
+	struct {
+		u32 coords : 1;
+		u32 coords_timestamp : 1;
+		u32 pen_paired : 1;
+		u32 pen_active : 1;
+	} contents;
+	struct TouchOffloadCoord pen_offload_coord;
+	ktime_t pen_offload_coord_timestamp;
+	u8 pen_paired;
+	u8 pen_active;
+};
+
+struct gti_continuous_report_cmd {
+	enum gti_continuous_report_setting setting;
+};
+
+struct gti_debug_coord {
+	ktime_t time;
+	u64 irq_index;
+	struct TouchOffloadCoord coord;
+};
+
+struct gti_debug_healthcheck {
+	ktime_t irq_time;
+	u64 irq_index;
+	u64 input_index;
+	unsigned long slot_bit_active;
+};
+
+struct gti_debug_input {
+	int slot;
+	struct gti_debug_coord pressed;
+	struct gti_debug_coord released;
+};
+
+struct gti_coord_filter_cmd {
+	enum gti_coord_filter_setting setting;
+};
+
+struct gti_display_state_cmd {
+	enum gti_display_state_setting setting;
+};
+
+struct gti_display_vrefresh_cmd {
+	u32 setting;
+};
+
+struct gti_fw_version_cmd {
+	char buffer[0x200];
+};
+
+struct gti_gesture_config_cmd {
+	u8 updating_params[GTI_GESTURE_PARAMS_MAX];
+	u16 params[GTI_GESTURE_PARAMS_MAX];
+};
+
+struct gti_grip_cmd {
+	enum gti_grip_setting setting;
+};
+
+struct gti_heatmap_cmd {
+	enum gti_heatmap_setting setting;
+};
+
+struct gti_irq_cmd {
+	enum gti_irq_mode setting;
+};
+
+struct gti_palm_cmd {
+	enum gti_palm_setting setting;
+};
+
+struct gti_panel_speed_mode_cmd {
+	enum gti_panel_speed_mode_setting setting;
+};
+
+struct gti_ping_cmd {
+	enum gti_ping_mode setting;
+};
+
+struct gti_report_rate_cmd {
+	u32 setting;
+};
+
+struct gti_reset_cmd {
+	enum gti_reset_mode setting;
+};
+
+struct gti_scan_cmd {
+	enum gti_scan_mode setting;
+};
+
+struct gti_screen_protector_mode_cmd {
+	enum gti_screen_protector_mode setting;
+};
+
+struct gti_selftest_cmd {
+	enum gti_selftest_result result;
+	char buffer[PAGE_SIZE];
+	bool is_ical;
+};
+
+struct gti_sensing_cmd {
+	enum gti_sensing_mode setting;
+};
+
+struct gti_sensor_data_cmd {
+	enum gti_sensor_data_type type;
+	u8 *buffer;
+	u32 size;
+	/* Set by vendor driver and the default value is false */
+	bool is_unsigned;
+};
+
+/**
+ * struct gti_union_cmd_data - GTI commands to vendor driver.
+ * @calibrate_cmd: command to calibrate the touchscreen
+ * @context_driver_cmd: command to update touch offload driver context.
+ * @context_stylus_cmd: command to update touch offload stylus context.
+ * @continuous_report_cmd: command to set continuous reporting.
+ * @coord_filter_cmd: command to set/get coordinate filter enabled.
+ * @display_state_cmd: command to notify display state.
+ * @display_vrefresh_cmd: command to notify display vertical refresh rate.
+ * @fw_version_cmd: command to get fw version.
+ * @gesture_config_cmd: command to set gesture parameters and gesture types.
+ * @grip_cmd: command to set/get grip mode.
+ * @heatmap_cmd: command to set heatmap enabled.
+ * @irq_cmd: command to set/get irq mode.
+ * @palm_cmd: command to set/get palm mode.
+ * @panel_speed_mode_cmd: command to set panel speed mode.
+ * @ping_cmd: command to ping T-IC.
+ * @report_rate_cmd: command to change touch report rate.
+ * @reset_cmd: command to reset T-IC.
+ * @scan_cmd: command to set/get scan mode.
+ * @screen_protector_mode_cmd: command to set/get screen protector mode.
+ * @selftest_cmd: command to do self-test.
+ * @sensing_cmd: command to set/set sensing mode.
+ * @sensor_data_cmd: command to get sensor data.
+ * @manual_sensor_data_cmd: command to get sensor data manually.
+ */
+struct gti_union_cmd_data {
+	struct gti_calibrate_cmd calibrate_cmd;
+	struct gti_context_driver_cmd context_driver_cmd;
+	struct gti_context_stylus_cmd context_stylus_cmd;
+	struct gti_continuous_report_cmd continuous_report_cmd;
+	struct gti_coord_filter_cmd coord_filter_cmd;
+	struct gti_display_state_cmd display_state_cmd;
+	struct gti_display_vrefresh_cmd display_vrefresh_cmd;
+	struct gti_fw_version_cmd fw_version_cmd;
+	struct gti_gesture_config_cmd gesture_config_cmd;
+	struct gti_grip_cmd grip_cmd;
+	struct gti_heatmap_cmd heatmap_cmd;
+	struct gti_irq_cmd irq_cmd;
+	struct gti_palm_cmd palm_cmd;
+	struct gti_panel_speed_mode_cmd panel_speed_mode_cmd;
+	struct gti_ping_cmd ping_cmd;
+	struct gti_report_rate_cmd report_rate_cmd;
+	struct gti_reset_cmd reset_cmd;
+	struct gti_scan_cmd scan_cmd;
+	struct gti_screen_protector_mode_cmd screen_protector_mode_cmd;
+	struct gti_selftest_cmd selftest_cmd;
+	struct gti_sensing_cmd sensing_cmd;
+	struct gti_sensor_data_cmd sensor_data_cmd;
+	struct gti_sensor_data_cmd manual_sensor_data_cmd;
+};
+
+/**
+ * struct gti_gesture_event_data - GTI gesture event data for notifying changed.
+ * @gesture_type: triggered gesture type.
+ * @x: x coordinate for the finger.
+ * @y: x coordinate for the finger.
+ * @major: major of the finger in pixels.
+ * @minor: minor of the finger in pixels.
+ * @angle: finger angle from -4095 ~ 4096.
+ */
+struct gti_gesture_event_data {
+	enum gti_gesture_type type;
+	u16 x;
+	u16 y;
+	u16 major;
+	u16 minor;
+	s16 angle;
+};
+
+/**
+ * struct gti_fw_status_data - GTI fw status data for notifying changed.
+ * @noise_level: the noise level for noise mode.
+ */
+struct gti_fw_status_data {
+	enum gti_noise_mode_level noise_level;
+	u8 water_mode;
+	struct gti_gesture_event_data gesture_event;
+};
+
+/**
+ * struct gti_optional_configuration - optional configuration by vendor driver.
+ * @calibrate: vendor driver operation to exec calibration
+ * @get_context_driver: vendor driver operation to update touch offload driver context.
+ * @get_context_stylus: vendor driver operation to update touch offload stylus context.
+ * @get_coord_filter_enabled: vendor driver operation to get the coordinate filter enabled.
+ * @get_fw_version: vendor driver operation to get fw version info.
+ * @get_grip_mode: vendor driver operation to get the grip mode setting.
+ * @get_irq_mode: vendor driver operation to get irq mode setting.
+ * @get_mutual_sensor_data: vendor driver operation to get the mutual sensor data.
+ * @get_palm_mode: vendor driver operation to get the palm mode setting.
+ * @get_scan_mode: vendor driver operation to get scan mode.
+ * @get_screen_protector_mode: vendor driver operation to get screen protector mode.
+ * @get_self_sensor_data: vendor driver operation to get the self sensor data.
+ * @get_sensing_mode: vendor driver operation to get sensing mode.
+ * @notify_display_state: vendor driver operation to notify the display state.
+ * @notify_display_vrefresh: vendor driver operation to notify the display vertical refresh rate.
+ * @ping: vendor driver operation to ping T-IC.
+ * @reset: vendor driver operation to exec reset.
+ * @selftest: vendor driver operation to exec self-test.
+ * @set_continuous_report: vendor driver operation to apply the continuous reporting setting.
+ * @set_coord_filter_enabled: vendor driver operation to apply the coordinate filter enabled.
+ * @set_gesture_config: vendor driver operation to apply the gesture settings.
+ * @set_grip_mode: vendor driver operation to apply the grip setting.
+ * @set_heatmap_enabled: vendor driver operation to apply the heatmap setting.
+ * @set_irq_mode: vendor driver operation to apply the irq setting.
+ * @set_palm_mode: vendor driver operation to apply the palm setting.
+ * @set_panel_speed_mode: vendor driver operation to apply the panel speed mode setting.
+ * @set_report_rate: driver operation to set touch report rate.
+ * @set_scan_mode: vendor driver operation to set scan mode.
+ * @set_screen_protector_mode: vendor driver operation to set screen protector mode.
+ * @set_sensing_mode: vendor driver operation to set sensing mode.
+ * @post_irq_thread_fn: post irq thread function that register by vendor driver.
+ */
+struct gti_optional_configuration {
+	/*
+	 * Vendor command with GTI default NOP handler.
+	 * No need to check before use.
+	 */
+	int (*calibrate)(void *private_data, struct gti_calibrate_cmd *cmd);
+	int (*get_context_driver)(void *private_data, struct gti_context_driver_cmd *cmd);
+	int (*get_context_stylus)(void *private_data, struct gti_context_stylus_cmd *cmd);
+	int (*get_coord_filter_enabled)(void *private_data, struct gti_coord_filter_cmd *cmd);
+	int (*get_fw_version)(void *private_data, struct gti_fw_version_cmd *cmd);
+	int (*get_grip_mode)(void *private_data, struct gti_grip_cmd *cmd);
+	int (*get_irq_mode)(void *private_data, struct gti_irq_cmd *cmd);
+	int (*get_mutual_sensor_data)(void *private_data, struct gti_sensor_data_cmd *cmd);
+	int (*get_palm_mode)(void *private_data, struct gti_palm_cmd *cmd);
+	int (*get_scan_mode)(void *private_data, struct gti_scan_cmd *cmd);
+	int (*get_screen_protector_mode)(void *private_data,
+			struct gti_screen_protector_mode_cmd *cmd);
+	int (*get_self_sensor_data)(void *private_data, struct gti_sensor_data_cmd *cmd);
+	int (*get_sensing_mode)(void *private_data, struct gti_sensing_cmd *cmd);
+	int (*notify_display_state)(void *private_data, struct gti_display_state_cmd *cmd);
+	int (*notify_display_vrefresh)(void *private_data, struct gti_display_vrefresh_cmd *cmd);
+	int (*ping)(void *private_data, struct gti_ping_cmd *cmd);
+	int (*reset)(void *private_data, struct gti_reset_cmd *cmd);
+	int (*selftest)(void *private_data, struct gti_selftest_cmd *cmd);
+	int (*set_continuous_report)(void *private_data, struct gti_continuous_report_cmd *cmd);
+	int (*set_coord_filter_enabled)(void *private_data, struct gti_coord_filter_cmd *cmd);
+	int (*set_gesture_config)(void *private_data, struct gti_gesture_config_cmd *cmd);
+	int (*set_grip_mode)(void *private_data, struct gti_grip_cmd *cmd);
+	int (*set_heatmap_enabled)(void *private_data, struct gti_heatmap_cmd *cmd);
+	int (*set_irq_mode)(void *private_data, struct gti_irq_cmd *cmd);
+	int (*set_palm_mode)(void *private_data, struct gti_palm_cmd *cmd);
+	int (*set_panel_speed_mode)(void *private_data, struct gti_panel_speed_mode_cmd *cmd);
+	int (*set_report_rate)(void *private_data, struct gti_report_rate_cmd *cmd);
+	int (*set_scan_mode)(void *private_data, struct gti_scan_cmd *cmd);
+	int (*set_screen_protector_mode)(void *private_data,
+			struct gti_screen_protector_mode_cmd *cmd);
+	int (*set_sensing_mode)(void *private_data, struct gti_sensing_cmd *cmd);
+
+	/*
+	 * Vendor command without GTI default NOP handler.
+	 * Need to check before use.
+	 */
+	irq_handler_t post_irq_thread_fn;
+};
+
+/**
+ * struct gti_pm - power manager for GTI.
+ * @state_update_work: a work to update pm state.
+ * @locks: the lock state.
+ * @lock_mutex: protect the lock state.
+ * @state: GTI pm state.
+ * @new_state: New GTI pm state to be updated to.
+ * @enabled: Boolean value to represent if GTI PM is active.
+ * @update_state: Boolean value if state needs to be updated.
+ * @resume: callback for notifying resume.
+ * @suspend: callback for notifying suspend.
+ */
+struct gti_pm {
+	struct work_struct state_update_work;
+
+	u32 locks;
+	struct mutex lock_mutex;
+	enum gti_pm_state state;
+	enum gti_pm_state new_state;
+	bool enabled;
+	bool update_state;
+
+	int (*resume)(struct device *dev);
+	int (*suspend)(struct device *dev);
+};
+
+/**
+ * struct goog_touch_interface - Google touch interface data for Pixel.
+ * @vendor_private_data: the private data pointer that used by touch vendor driver.
+ * @vendor_dev: pointer to struct device that used by touch vendor driver.
+ * @vendor_input_dev: pointer to struct inpu_dev that used by touch vendor driver.
+ * @dev: pointer to struct device that used by google touch interface driver.
+ * @options: optional configuration that could apply by vendor driver.
+ * @input_lock: protect the input report between non-offload and offload.
+ * @input_process_lock: mutex for goog_input_process() function.
+ * @input_heatmap_lock: mutex for heatmap reading between vendor driver, GTI or sysfs/procfs.
+ * @offload: struct that used by touch offload.
+ * @offload_frame: reserved frame that used by touch offload.
+ * @v4l2: struct that used by v4l2.
+ * @panel_bridge: struct that used to register panel bridge notification.
+ * @connector: struct that used to get panel status.
+ * @cmd: struct that used by vendor default handler.
+ * @proc_dir: struct that used for procfs.
+ * @proc_heatmap: struct that used for heatmap procfs.
+ * @set_op_hz_work: a work to set op_hz.
+ * @event_wq: a work queue to run suspend/resume work.
+ * @input_dev_mono_ktime: input timestamp used by input dev and input subsystem.
+ * @input_timestamp: input timestamp from touch vendor driver.
+ * @mf_downtime: timestamp for motion filter control.
+ * @vrr_enabled: variable touch report rate is enabled or not.
+ * @report_rate_table_size: report rate table size from device tree.
+ * @touch_report_rate_table: touch report rate table parsed from device tree.
+ * @display_refresh_rate_table: display refresh rate table parsed from device tree.
+ * @report_rate_setting: current touch report rate.
+ * @report_rate_setting_next: next touch report rate going be set.
+ * @set_report_rate_work: delayed work for setting report rate.
+ * @increase_report_rate_delay: delayed work will be start after a delay in seconds.
+ * @decrease_report_rate_delay: delayed work will be start after a delay in seconds.
+ * @abs_x_min: minimum x of input resolution.
+ * @abs_x_max: maximum x of input resolution.
+ * @abs_y_min: minimum y of input resolution.
+ * @abs_y_max: maximum y of input resolution.
+ * @resolution_scale_factor: scale factor of input to display resolution.
+ * @display_vrefresh: display vrefresh in Hz.
+ * @display_state: current display state.
+ * @mf_mode: current motion filter mode.
+ * @mf_state: current motion filter state.
+ * @screen_protector_mode_setting: the setting of screen protector mode.
+ * @tbn_register_mask: the tbn_mask that used to request/release touch bus.
+ * @pm: struct that used by gti pm.
+ * @pm_qos_req: struct that used by pm qos.
+ * @fw_status: firmware status such as water_mode, noise_level, etc.
+ * @context_changed: flags that indicate driver status changing.
+ * @panel_is_lp_mode: display is in low power mode.
+ * @offload_enabled: touch offload is enabled or not.
+ * @v4l2_enabled: v4l2 is enabled or not.
+ * @tbn_enabled: tbn is enabled or not.
+ * @coord_filter_enabled: coordinate filter is enabled or not.
+ * @input_timestamp_changed: input timestamp changed from touch vendor driver.
+ * @ignore_grip_update: Ignore fw_grip status updates made on offload state change.
+ * @default_grip_enabled: the grip default setting.
+ * @ignore_palm_update: Ignore fw_palm status updates made on offload state change.
+ * @default_palm_enabled: the palm default setting.
+ * @ignore_coord_filter_update: Ignore fw_coordinate_filter status updates.
+ * @fw_coord_filter_enabled: the current setting of coordinate filter.
+ * @default_coord_filter_enabled: the default setting of coordinate filter.
+ * @panel_notifier_enabled: enable flag for receiving panel notifications.
+ * @reset_after_selftest: reset FW after running self-test.
+ * @lptw_triggered: LPTW is triggered or not.
+ * @lptw_suppress_coords_enabled: enable flag for suppressing the coords after lptw.
+ * @lptw_track_finger: flag for tracking the suppressed fingers.
+ * @lptw_track_min_x: minimum x of tracking area.
+ * @lptw_track_max_x: maximum x of tracking area.
+ * @lptw_track_min_y: minimum y of tracking area.
+ * @lptw_track_max_y: maximum y of tracking area.
+ * @lptw_cancel_delayed_work: delayed work for canceling finger.
+ * @lptw_cancel_time: record the time for lptw cancel timeout.
+ * @lptw_down: true if the finger is still on the screen.
+ * @lptw_data: x, y, major, minor, angle for the tracking finger.
+ * @ignore_force_active: Ignore the force_active sysfs request.
+ * @offload_id: id that used by touch offload.
+ * @heatmap_buf: heatmap buffer that used by v4l2.
+ * @heatmap_buf_size: heatmap buffer size that used by v4l2.
+ * @slot: slot id that current used by input report.
+ * @slot_bit_in_use: bitmap of slot in use for this input process cycle.
+ * @slot_bit_changed: bitmap of slot state changed for this input process cycle.
+ * @slot_bit_active: bitmap of active slot during GTI lifecycle.
+ * @slot_bit_lptw_track: bitmap of lptw suppressed fingers.
+ * @panel_op_hz: the operating rate of display panel.
+ * @dev_id: dev_t used for google interface driver.
+ * @panel_id: id of the display panel.
+ * @charger_state: indicates a USB charger is connected.
+ * @charger_notifier: notifier for power_supply updates.
+ * @panel_notifier: notifier for display panel updates.
+ * @ical_state: state of interactive calibration finite state machine.
+ * @ical_timestamp_ns: time of last interactive calibration state transition.
+ * @ical_result: interactive calibration FSM result.
+ * @ical_func_result: result returned from the requested interactive function.
+ * @frame_index: the count that handle by goog_input_process().
+ * @irq_index: irq count that handle by GTI.
+ * @input_index: the count of slot bit changed during goog_input_process().
+ * @vendor_irq_handler: irq handler that register by vendor driver.
+ * @vendor_irq_thread_fn: irq thread function that register by vendor driver.
+ * @vendor_irq_cookie: irq cookie that register by vendor driver.
+ * @vendor_default_handler: touch vendor driver default operation.
+ * @released_index: finger up count.
+ * @debug_warning_limit: limit number of warning logs.
+ * @debug_input: struct that used to debug input.
+ * @debug_fifo_input: kfifo struct to track input report.
+ * @debug_healthcheck: struct that used for the health check.
+ * @debug_fifo_healthcheck: kfifo struct to track touch interrupt information.
+ */
+
+struct goog_touch_interface {
+	void *vendor_private_data;
+	struct device *vendor_dev;
+	struct input_dev *vendor_input_dev;
+	struct device *dev;
+	struct gti_optional_configuration options;
+	struct mutex input_lock;
+	struct mutex input_process_lock;
+	struct mutex input_heatmap_lock;
+	struct touch_offload_context offload;
+	struct touch_offload_frame *offload_frame;
+	struct v4l2_heatmap v4l2;
+	struct drm_bridge panel_bridge;
+	struct drm_connector *connector;
+	struct gti_union_cmd_data cmd;
+	struct proc_dir_entry *proc_dir;
+	struct proc_dir_entry *proc_show[GTI_PROC_NUM];
+	struct work_struct set_op_hz_work;
+	struct workqueue_struct *event_wq;
+	ktime_t input_dev_mono_ktime;
+	ktime_t input_timestamp;
+	ktime_t mf_downtime;
+
+	bool vrr_enabled;
+	int report_rate_table_size;
+	u32 *display_refresh_rate_table;
+	u32 *touch_report_rate_table;
+	u32 report_rate_setting;
+	u32 report_rate_setting_next;
+	struct delayed_work set_report_rate_work;
+	u32 increase_report_rate_delay;
+	u32 decrease_report_rate_delay;
+	int abs_x_min;
+	int abs_x_max;
+	int abs_y_min;
+	int abs_y_max;
+	int resolution_scale_factor;
+
+	int display_vrefresh;
+	enum gti_display_state_setting display_state;
+	enum gti_mf_mode mf_mode;
+	enum gti_mf_state mf_state;
+	enum gti_screen_protector_mode screen_protector_mode_setting;
+	u32 tbn_register_mask;
+	struct gti_pm pm;
+	struct pm_qos_request pm_qos_req;
+
+	struct gti_fw_status_data fw_status;
+	struct gti_context_changed context_changed;
+
+	bool panel_is_lp_mode;
+	bool offload_enabled;
+	bool v4l2_enabled;
+	bool tbn_enabled;
+	bool coord_filter_enabled;
+	bool input_timestamp_changed;
+	bool ignore_grip_update;
+	bool default_grip_enabled;
+	bool ignore_palm_update;
+	bool default_palm_enabled;
+	bool ignore_coord_filter_update;
+	bool fw_coord_filter_enabled;
+	bool default_coord_filter_enabled;
+	bool panel_notifier_enabled;
+	bool reset_after_selftest;
+	bool lptw_triggered;
+	bool lptw_suppress_coords_enabled;
+	bool lptw_track_finger;
+	u32 lptw_track_min_x;
+	u32 lptw_track_max_x;
+	u32 lptw_track_min_y;
+	u32 lptw_track_max_y;
+	struct delayed_work lptw_cancel_delayed_work;
+	ktime_t lptw_cancel_time;
+
+	bool lptw_down;
+	union {
+		int lptw_data[5];
+		struct {
+			int lptw_x;
+			int lptw_y;
+			int lptw_major;
+			int lptw_minor;
+			int lptw_angle;
+		};
+	};
+
+	bool ignore_force_active;
+	bool gesture_config_enabled;
+	bool manual_heatmap_from_irq;
+	union {
+		u8 offload_id_byte[4];
+		u32 offload_id;
+	};
+	u8 *heatmap_buf;
+	u32 heatmap_buf_size;
+	int slot;
+	unsigned long slot_bit_in_use;
+	unsigned long slot_bit_changed;
+	unsigned long slot_bit_active;
+	unsigned long slot_bit_lptw_track;
+	unsigned int panel_op_hz;
+	dev_t dev_id;
+	int panel_id;
+	char fw_name[64];
+	char config_name[64];
+	char test_limits_name[64];
+	char usb_psy_name[64];
+
+	u8 charger_state;
+	struct notifier_block charger_notifier;
+	struct notifier_block panel_notifier;
+
+	u32 ical_state;
+	u64 ical_timestamp_ns;
+	s32 ical_result;
+	s32 ical_func_result;
+
+	u64 frame_index;
+	u64 irq_index;
+	u64 input_index;
+	irq_handler_t vendor_irq_handler;
+	irq_handler_t vendor_irq_thread_fn;
+	void *vendor_irq_cookie;
+
+	int (*vendor_default_handler)(void *private_data,
+		enum gti_cmd_type cmd_type, struct gti_union_cmd_data *cmd);
+
+	/* Debug used. */
+	u64 released_index;
+	int debug_warning_limit;
+	struct gti_debug_input debug_input[MAX_SLOTS];
+	struct gti_debug_input debug_input_history[GTI_DEBUG_INPUT_KFIFO_LEN];
+	DECLARE_KFIFO(debug_fifo_input, struct gti_debug_input, GTI_DEBUG_INPUT_KFIFO_LEN);
+	struct gti_debug_healthcheck debug_healthcheck;
+	struct gti_debug_healthcheck debug_healthcheck_history[GTI_DEBUG_HEALTHCHECK_KFIFO_LEN];
+	DECLARE_KFIFO(debug_fifo_healthcheck, struct gti_debug_healthcheck,
+		GTI_DEBUG_HEALTHCHECK_KFIFO_LEN);
+};
+
+/*-----------------------------------------------------------------------------
+ * Forward declarations.
+ */
+inline bool goog_check_spi_dma_enabled(struct spi_device *spi_dev);
+inline ktime_t *goog_input_get_timestamp(struct goog_touch_interface *gti);
+inline void goog_input_lock(struct goog_touch_interface *gti);
+inline void goog_input_unlock(struct goog_touch_interface *gti);
+inline void goog_input_set_timestamp(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, ktime_t timestamp);
+inline void goog_input_mt_slot(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, int slot);
+inline void goog_input_mt_report_slot_state(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int tool_type, bool active);
+inline void goog_input_report_abs(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int code, int value);
+inline void goog_input_report_key(
+		struct goog_touch_interface *gti,
+		struct input_dev *dev, unsigned int code, int value);
+inline void goog_input_sync(struct goog_touch_interface *gti, struct input_dev *dev);
+inline int goog_devm_request_threaded_irq(struct goog_touch_interface *gti,
+		struct device *dev, unsigned int irq,
+		irq_handler_t handler, irq_handler_t thread_fn,
+		unsigned long irqflags, const char *devname,
+		void *dev_id);
+void goog_devm_free_irq(struct goog_touch_interface *gti,
+		struct device *dev, unsigned int irq);
+inline int goog_request_threaded_irq(struct goog_touch_interface *gti,
+		unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn,
+		unsigned long irqflags, const char *devname, void *dev_id);
+
+int goog_process_vendor_cmd(struct goog_touch_interface *gti, enum gti_cmd_type cmd_type);
+int goog_input_process(struct goog_touch_interface *gti, bool reset_data);
+struct goog_touch_interface *goog_touch_interface_probe(
+		void *private_data,
+		struct device *dev,
+		struct input_dev *input_dev,
+		int (*default_handler)(void *private_data,
+			enum gti_cmd_type cmd_type, struct gti_union_cmd_data *cmd),
+		struct gti_optional_configuration *options);
+int goog_touch_interface_remove(struct goog_touch_interface *gti);
+
+int goog_pm_wake_lock_nosync(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type, bool skip_pm_resume);
+int goog_pm_wake_lock(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type, bool skip_pm_resume);
+int goog_pm_wake_unlock_nosync(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type);
+int goog_pm_wake_unlock(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type);
+bool goog_pm_wake_check_locked(struct goog_touch_interface *gti,
+		enum gti_pm_wakelock_type type);
+u32 goog_pm_wake_get_locks(struct goog_touch_interface *gti);
+int goog_pm_register_notification(struct goog_touch_interface *gti,
+		const struct dev_pm_ops* ops);
+int goog_pm_unregister_notification(struct goog_touch_interface *gti);
+
+void goog_notify_fw_status_changed(struct goog_touch_interface *gti,
+		enum gti_fw_status status, struct gti_fw_status_data* data);
+void gti_debug_healthcheck_dump(struct goog_touch_interface *gti);
+void gti_debug_input_dump(struct goog_touch_interface *gti);
+
+int goog_get_lptw_triggered(struct goog_touch_interface *gti);
+void goog_lptw_notifier_register(struct notifier_block *nb, bool reg);
+
+int goog_get_max_touch_report_rate(struct goog_touch_interface *gti);
+int goog_get_panel_id(struct device_node *node);
+int goog_get_firmware_name(struct device_node *node, int id, char *name, size_t size);
+int goog_get_config_name(struct device_node *node, int id, char *name, size_t size);
+int goog_get_test_limits_name(struct device_node *node, int id, char *name, size_t size);
+
+#endif // _GOOG_TOUCH_INTERFACE_
+
diff --git a/goog_touch_interface_nop.h b/goog_touch_interface_nop.h
new file mode 100644
index 0000000..0528e37
--- /dev/null
+++ b/goog_touch_interface_nop.h
@@ -0,0 +1,104 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Google Touch Interface NOP for Pixel devices.
+ *
+ * Copyright 2022 Google LLC.
+ */
+#ifndef _GOOG_TOUCH_INTERFACE_NOP_
+#define _GOOG_TOUCH_INTERFACE_NOP_
+
+#include <linux/input/mt.h>
+
+enum gti_cmd_type : u32{
+	GTI_CMD_NOP,
+};
+
+enum gti_vendor_dev_pm_state : u32 {
+	GTI_VENDOR_DEV_RESUME = 0,
+	GTI_VENDOR_DEV_SUSPEND,
+};
+
+struct gti_union_cmd_data {
+	u32 nop_cmd;
+};
+
+struct goog_touch_interface {
+	void *private_data;
+};
+
+static inline void goog_input_lock(struct goog_touch_interface *gti)
+{
+}
+
+static inline void goog_input_unlock(struct goog_touch_interface *gti)
+{
+}
+
+static inline void goog_input_set_timestamp(
+    struct goog_touch_interface *gti,
+    struct input_dev *dev, ktime_t timestamp)
+{
+	input_set_timestamp(dev, timestamp);
+}
+
+static inline void goog_input_mt_slot(
+    struct goog_touch_interface *gti,
+    struct input_dev *dev, int slot)
+{
+	input_mt_slot(dev, slot);
+}
+
+static inline void goog_input_mt_report_slot_state(
+    struct goog_touch_interface *gti,
+    struct input_dev *dev, unsigned int tool_type, bool active)
+{
+	input_mt_report_slot_state(dev, tool_type, active);
+}
+
+static inline void goog_input_report_abs(
+    struct goog_touch_interface *gti,
+    struct input_dev *dev, unsigned int code, int value)
+{
+	input_report_abs(dev, code, value);
+}
+
+static inline void goog_input_report_key(
+    struct goog_touch_interface *gti,
+    struct input_dev *dev, unsigned int code, int value)
+{
+	input_report_key(dev, code, value);
+}
+
+static inline void goog_input_sync(struct goog_touch_interface *gti, struct input_dev *dev)
+{
+	input_sync(dev);
+}
+
+static inline int goog_input_process(struct goog_touch_interface *gti)
+{
+	return 0;
+}
+
+struct gti_optional_configuration {
+	u32 reserve;
+};
+
+static inline struct goog_touch_interface *goog_touch_interface_probe(
+	void *private_data,
+	struct device *dev,
+	struct input_dev *input_dev,
+	int (*default_handler)(void *private_data,
+		enum gti_cmd_type cmd_type, struct gti_union_cmd_data *cmd),
+	struct gti_optional_configuration *options)
+{
+	static struct goog_touch_interface gti[1];
+
+	return gti;
+}
+
+static inline int goog_touch_interface_remove(struct goog_touch_interface *gti)
+{
+	return 0;
+}
+
+#endif // _GOOG_TOUCH_INTERFACE_NOP_
\ No newline at end of file
diff --git a/heatmap.c b/heatmap.c
new file mode 100644
index 0000000..333f72d
--- /dev/null
+++ b/heatmap.c
@@ -0,0 +1,426 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/module.h>
+#include <linux/input.h>
+#include <media/videobuf2-vmalloc.h>
+#include "heatmap.h"
+
+#undef dev_fmt
+#define dev_fmt(fmt) "gti: " fmt
+static const int FIRST_FREE_NODE = -1;
+
+/**
+ * Optimization: keep track of how many consecutive frames
+ * have been dropped due to not having any buffers available.
+ * If too many have been recently dropped, and still no free buffers
+ * are available, then skip the bus read.
+ * This situation could happen if an app have opened the video device,
+ * but went into paused state, and did not close the video device in
+ * onPause. With this optimization, we would avoid the wasteful bus reads
+ * when no one is likely to consume the buffers.
+ */
+static const unsigned int NUM_BUFFERS_BEFORE_DROP = 3;
+static unsigned int consecutive_frames_dropped;
+
+struct heatmap_vb2_buffer {
+	struct vb2_v4l2_buffer v4l2_vb;
+	struct list_head list;
+};
+
+static int heatmap_set_input(
+		struct v4l2_heatmap *v4l2, unsigned int input_index)
+{
+	struct v4l2_pix_format *fmt = &v4l2->format;
+
+	if (input_index != 0)
+		return -EINVAL;
+
+	/*
+	 * Changing the input implies a format change, which is not allowed
+	 * while buffers for use with streaming have already been allocated.
+	 */
+	if (vb2_is_busy(&v4l2->queue))
+		return -EBUSY;
+
+	v4l2->input_index = input_index;
+
+	fmt->width = v4l2->width;
+	fmt->height = v4l2->height;
+	fmt->pixelformat = V4L2_TCH_FMT_DELTA_TD16;
+	fmt->field = V4L2_FIELD_NONE;
+	fmt->colorspace = V4L2_COLORSPACE_RAW;
+	fmt->bytesperline = fmt->width * sizeof(strength_t);
+	fmt->sizeimage = fmt->width * fmt->height * sizeof(strength_t);
+
+	return 0;
+}
+
+static inline struct heatmap_vb2_buffer *to_heatmap_vb2_buffer(
+		struct vb2_buffer *vb2)
+{
+	return container_of(to_vb2_v4l2_buffer(vb2), struct heatmap_vb2_buffer,
+			    v4l2_vb);
+}
+
+static const struct v4l2_file_operations heatmap_video_fops = {
+	.owner = THIS_MODULE,
+	.open = v4l2_fh_open,
+	.release = vb2_fop_release,
+	.unlocked_ioctl = video_ioctl2,
+	.read = vb2_fop_read,
+	.mmap = vb2_fop_mmap,
+	.poll = vb2_fop_poll,
+};
+
+void heatmap_read(struct v4l2_heatmap *v4l2, uint64_t timestamp)
+{
+	struct heatmap_vb2_buffer *new_buf;
+	struct vb2_buffer *vb2_buf;
+	strength_t *data;
+	int total_bytes = v4l2->format.sizeimage;
+	bool read_success;
+	char index_tag[32] = {0};
+
+	if (v4l2->frame_index_enabled)
+		scnprintf(index_tag, sizeof(index_tag), "IDX=%llu", v4l2->frame_index);
+
+	if (!vb2_is_streaming(&v4l2->queue)) {
+		/* No need to read, no one is viewing the video */
+		return;
+	}
+
+	/* Optimization */
+	if (consecutive_frames_dropped >= NUM_BUFFERS_BEFORE_DROP) {
+		spin_lock(&v4l2->heatmap_lock);
+		if (list_empty(&v4l2->heatmap_buffer_list)) {
+			/*
+			 * Already dropped some frames, and still don't have
+			 * any free buffers. A buffer could become available
+			 * during read_frame(..), but given that we already
+			 * dropped some frames, this is unlikely.
+			 */
+			spin_unlock(&v4l2->heatmap_lock);
+			return; /* Drop the frame */
+		}
+		spin_unlock(&v4l2->heatmap_lock);
+	}
+
+	/* This is a potentially slow operation */
+	read_success = v4l2->read_frame(v4l2);
+	if (!read_success)
+		return;
+
+	/* Copy the data into the buffer */
+	spin_lock(&v4l2->heatmap_lock);
+	if (list_empty(&v4l2->heatmap_buffer_list)) {
+		/*
+		 * If streaming is off, then there would
+		 * be no queued buffers. This is expected.
+		 * On the other hand, if there is a consumer, but there
+		 * aren't any available buffers, then this indicates
+		 * slowness in the userspace for reading or
+		 * processing buffers.
+		 */
+		if (consecutive_frames_dropped == 0)
+			dev_warn(v4l2->parent_dev, "v4l2: No buffers available %s\n", index_tag);
+		consecutive_frames_dropped++;
+		spin_unlock(&v4l2->heatmap_lock);
+		return;
+	}
+	if (consecutive_frames_dropped > 1) {
+		dev_info(v4l2->parent_dev, "v4l2: unhandled frames=%u %s\n",
+				consecutive_frames_dropped, index_tag);
+	}
+	consecutive_frames_dropped = 0;
+	new_buf = list_entry(v4l2->heatmap_buffer_list.next,
+		struct heatmap_vb2_buffer, list);
+	list_del(&new_buf->list);
+
+	vb2_buf = &new_buf->v4l2_vb.vb2_buf;
+	data = vb2_plane_vaddr(vb2_buf, 0);
+	if (!data) {
+		dev_err(v4l2->parent_dev, "v4l2: Error acquiring frame pointer\n");
+		vb2_buffer_done(vb2_buf, VB2_BUF_STATE_ERROR);
+		spin_unlock(&v4l2->heatmap_lock);
+		return;
+	}
+
+	memcpy(data, v4l2->frame, total_bytes);
+	vb2_set_plane_payload(vb2_buf, /* plane number */ 0, total_bytes);
+	vb2_buf->timestamp = timestamp;
+	vb2_buffer_done(vb2_buf, VB2_BUF_STATE_DONE);
+	spin_unlock(&v4l2->heatmap_lock);
+}
+EXPORT_SYMBOL_GPL(heatmap_read);
+
+static void heatmap_buffer_queue(struct vb2_buffer *vb)
+{
+	struct v4l2_heatmap *v4l2 = vb2_get_drv_priv(vb->vb2_queue);
+	struct heatmap_vb2_buffer *heatmap_buffer = to_heatmap_vb2_buffer(vb);
+
+	spin_lock(&v4l2->heatmap_lock);
+	list_add_tail(&heatmap_buffer->list, &v4l2->heatmap_buffer_list);
+	spin_unlock(&v4l2->heatmap_lock);
+}
+
+static int heatmap_queue_setup(struct vb2_queue *vq,
+			unsigned int *num_buffers, unsigned int *num_planes,
+			unsigned int sizes[], struct device *alloc_devs[])
+{
+	struct v4l2_heatmap *v4l2 = vb2_get_drv_priv(vq);
+	size_t size = v4l2->format.sizeimage;
+
+	if (*num_planes != 0)
+		return sizes[0] < size ? -EINVAL : 0;
+
+	*num_planes = 1;
+	sizes[0] = size;
+
+	return 0;
+}
+
+static void return_all_buffers(struct v4l2_heatmap *v4l2,
+	enum vb2_buffer_state state)
+{
+	struct heatmap_vb2_buffer *buf, *node;
+
+	spin_lock(&v4l2->heatmap_lock);
+	list_for_each_entry_safe(buf, node, &v4l2->heatmap_buffer_list, list) {
+		vb2_buffer_done(&buf->v4l2_vb.vb2_buf, state);
+		list_del(&buf->list);
+	}
+	spin_unlock(&v4l2->heatmap_lock);
+}
+
+/*
+ * Stop the DMA engine. Any remaining buffers in the DMA queue are dequeued
+ * and passed on to the vb2 framework marked as STATE_ERROR.
+ */
+static void stop_streaming(struct vb2_queue *vq)
+{
+	struct v4l2_heatmap *v4l2 = vb2_get_drv_priv(vq);
+	/* Release all active buffers */
+	return_all_buffers(v4l2, VB2_BUF_STATE_ERROR);
+}
+
+/* V4L2 structures */
+static const struct vb2_ops heatmap_queue_ops = {
+	.queue_setup        = heatmap_queue_setup,
+	.buf_queue          = heatmap_buffer_queue,
+	.stop_streaming     = stop_streaming,
+	.wait_prepare       = vb2_ops_wait_prepare,
+	.wait_finish        = vb2_ops_wait_finish,
+};
+
+static const struct vb2_queue heatmap_queue = {
+	.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+	.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ,
+	.buf_struct_size = sizeof(struct heatmap_vb2_buffer),
+	.ops = &heatmap_queue_ops,
+	.mem_ops = &vb2_vmalloc_memops,
+	.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC,
+	.min_buffers_needed = 1,
+};
+
+static int heatmap_vidioc_querycap(struct file *file, void *priv,
+		struct v4l2_capability *cap)
+{
+	struct v4l2_heatmap *v4l2 = video_drvdata(file);
+	strlcpy(cap->driver, v4l2->parent_dev->driver->name,
+		sizeof(cap->driver));
+	if (v4l2->input_dev != NULL && v4l2->input_dev->name != NULL) {
+		strlcpy(cap->card, v4l2->input_dev->name, sizeof(cap->card));
+	} else {
+		strlcpy(cap->card, KBUILD_MODNAME, sizeof(cap->card));
+	}
+
+	strlcpy(cap->bus_info, dev_name(v4l2->parent_dev),
+		sizeof(cap->bus_info));
+	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH |
+		V4L2_CAP_READWRITE | V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
+	return 0;
+}
+
+static int heatmap_vidioc_enum_input(struct file *file, void *priv,
+		struct v4l2_input *video_input)
+{
+	if (video_input->index != 0)
+		return -EINVAL;
+
+	video_input->type = V4L2_INPUT_TYPE_TOUCH;
+	strlcpy(video_input->name, "strength", sizeof(video_input->name));
+	return 0;
+}
+
+static int heatmap_vidioc_s_input(
+		struct file *file, void *priv, unsigned int input_index)
+{
+	struct v4l2_heatmap *v4l2 = video_drvdata(file);
+	return heatmap_set_input(v4l2, input_index);
+}
+
+static int heatmap_vidioc_g_input(struct file *file, void *priv,
+		unsigned int *input_index)
+{
+	struct v4l2_heatmap *v4l2 = video_drvdata(file);
+	*input_index = v4l2->input_index;
+	return 0;
+}
+
+static int heatmap_vidioc_fmt(struct file *file, void *priv,
+		struct v4l2_format *fmt)
+{
+	struct v4l2_heatmap *v4l2 = video_drvdata(file);
+
+	fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+	fmt->fmt.pix = v4l2->format;
+
+	return 0;
+}
+
+static int heatmap_vidioc_enum_fmt(struct file *file, void *priv,
+		struct v4l2_fmtdesc *fmt)
+{
+	if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
+		return -EINVAL;
+
+	if (fmt->index != 0)
+		return -EINVAL;
+
+	fmt->pixelformat = V4L2_TCH_FMT_DELTA_TD16;
+	return 0;
+}
+
+static int heatmap_vidioc_g_parm(struct file *file, void *fh,
+		struct v4l2_streamparm *streamparm)
+{
+	struct v4l2_heatmap *v4l2 = video_drvdata(file);
+
+	if (streamparm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
+		return -EINVAL;
+
+	streamparm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
+	streamparm->parm.capture.readbuffers = 1;
+	streamparm->parm.capture.timeperframe.numerator =
+		v4l2->timeperframe.numerator;
+	streamparm->parm.capture.timeperframe.denominator =
+		v4l2->timeperframe.denominator;
+	return 0;
+}
+
+static const struct v4l2_ioctl_ops heatmap_video_ioctl_ops = {
+	.vidioc_querycap         = heatmap_vidioc_querycap,
+
+	.vidioc_enum_fmt_vid_cap = heatmap_vidioc_enum_fmt,
+	.vidioc_s_fmt_vid_cap    = heatmap_vidioc_fmt,
+	.vidioc_g_fmt_vid_cap    = heatmap_vidioc_fmt,
+	.vidioc_try_fmt_vid_cap  = heatmap_vidioc_fmt,
+	.vidioc_g_parm           = heatmap_vidioc_g_parm,
+
+	.vidioc_enum_input       = heatmap_vidioc_enum_input,
+	.vidioc_g_input          = heatmap_vidioc_g_input,
+	.vidioc_s_input          = heatmap_vidioc_s_input,
+
+	.vidioc_reqbufs          = vb2_ioctl_reqbufs,
+	.vidioc_create_bufs      = vb2_ioctl_create_bufs,
+	.vidioc_querybuf         = vb2_ioctl_querybuf,
+	.vidioc_qbuf             = vb2_ioctl_qbuf,
+	.vidioc_dqbuf            = vb2_ioctl_dqbuf,
+	.vidioc_expbuf           = vb2_ioctl_expbuf,
+
+	.vidioc_streamon         = vb2_ioctl_streamon,
+	.vidioc_streamoff        = vb2_ioctl_streamoff,
+};
+
+static const struct video_device heatmap_video_device = {
+	.name = "heatmap",
+	.fops = &heatmap_video_fops,
+	.ioctl_ops = &heatmap_video_ioctl_ops,
+	.release = video_device_release_empty,
+	.device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH |
+		V4L2_CAP_READWRITE | V4L2_CAP_STREAMING,
+};
+
+int heatmap_probe(struct v4l2_heatmap *v4l2)
+{
+	int error;
+
+	/* init channel to zero */
+	heatmap_set_input(v4l2, 0);
+
+	v4l2->frame = devm_kzalloc(v4l2->parent_dev,
+		v4l2->format.sizeimage, GFP_KERNEL);
+	if(!v4l2->frame) {
+		error = -ENOMEM;
+		goto err_probe;
+	}
+
+	/* register video device */
+	strlcpy(v4l2->device.name, dev_name(v4l2->parent_dev),
+		V4L2_DEVICE_NAME_SIZE);
+	error = v4l2_device_register(v4l2->parent_dev, &v4l2->device);
+	if (error)
+		goto err_free_frame_storage;
+
+	INIT_LIST_HEAD(&v4l2->heatmap_buffer_list);
+
+	/* initialize the queue */
+	spin_lock_init(&v4l2->heatmap_lock);
+	mutex_init(&v4l2->lock);
+
+	v4l2->queue = heatmap_queue;
+	v4l2->queue.drv_priv = v4l2;
+	v4l2->queue.lock = &v4l2->lock;
+
+	error = vb2_queue_init(&v4l2->queue);
+	if (error)
+		goto err_unreg_v4l2;
+
+	v4l2->vdev = heatmap_video_device;
+
+	v4l2->vdev.v4l2_dev = &v4l2->device;
+	v4l2->vdev.lock = &v4l2->lock;
+	v4l2->vdev.vfl_dir = VFL_DIR_RX;
+	v4l2->vdev.queue = &v4l2->queue;
+	video_set_drvdata(&v4l2->vdev, v4l2);
+
+	error = video_register_device(&v4l2->vdev, VFL_TYPE_TOUCH,
+		FIRST_FREE_NODE);
+	if (error)
+		goto err_video_device_release;
+	return 0;
+
+err_video_device_release:
+	mutex_lock(&v4l2->lock);
+	vb2_queue_release(&v4l2->queue);
+	mutex_unlock(&v4l2->lock);
+	video_device_release(&v4l2->vdev);
+
+err_unreg_v4l2:
+	v4l2_device_unregister(&v4l2->device);
+err_free_frame_storage:
+	kfree(v4l2->frame);
+err_probe:
+	return error;
+}
+EXPORT_SYMBOL_GPL(heatmap_probe);
+
+void heatmap_remove(struct v4l2_heatmap *v4l2)
+{
+	if (v4l2->frame) {
+		video_unregister_device(&v4l2->vdev);
+
+		mutex_lock(&v4l2->lock);
+		vb2_queue_release(&v4l2->queue);
+		mutex_unlock(&v4l2->lock);
+
+		v4l2_device_unregister(&v4l2->device);
+		devm_kfree(v4l2->parent_dev, v4l2->frame);
+		v4l2->frame = NULL;
+	}
+}
+EXPORT_SYMBOL_GPL(heatmap_remove);
+
+MODULE_DESCRIPTION("Touchscreen heatmap video device");
+MODULE_AUTHOR("Siarhei Vishniakou <svv@google.com>");
+MODULE_LICENSE("GPL v2");
diff --git a/heatmap.h b/heatmap.h
new file mode 100644
index 0000000..17a5a13
--- /dev/null
+++ b/heatmap.h
@@ -0,0 +1,62 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef _HEATMAP_H_
+#define _HEATMAP_H_
+
+#include <media/v4l2-device.h>
+#include <media/v4l2-ioctl.h>
+#include <media/videobuf2-v4l2.h>
+
+typedef int16_t strength_t;
+
+struct v4l2_heatmap {
+	struct device *parent_dev;
+	/* Can be NULL. Used to get the input device name */
+	struct input_dev *input_dev;
+	struct v4l2_device device;
+	struct v4l2_pix_format format;
+	struct video_device vdev;
+	struct vb2_queue queue;
+	struct mutex lock;
+	unsigned int input_index;
+	u64 frame_index;
+	bool frame_index_enabled;
+
+	size_t width;
+	size_t height;
+
+	/* The 'frame' storage is managed by the heatmap module.
+	 * The data inside frame is written inside read_frame(..)
+	 * and is read inside heatmap_read(..).
+	 */
+	strength_t *frame;
+
+	struct v4l2_fract timeperframe;
+
+	/* Used to protect access to the buffer queue */
+	spinlock_t heatmap_lock;
+	/* guarded by heatmap_lock */
+	struct list_head heatmap_buffer_list;
+
+	/*
+	 * Function read_frame must be provided by the driver.
+	 * This function should write the video frame into the
+	 * 'frame' field of struct v4l2_heatmap.
+	 * It should return 'true' on successful heatmap read
+	 * and 'false' on failure.
+	 */
+	bool (*read_frame)(struct v4l2_heatmap *v4l2);
+};
+
+int heatmap_probe(struct v4l2_heatmap *v4l2);
+void heatmap_remove(struct v4l2_heatmap *v4l2);
+/**
+ * Read the heatmap and populate an available buffer with data.
+ * The timestamp provided to this function will be used as the frame time.
+ * Designed to be called from interrupt context.
+ * This function should be called from the driver. Internally, it will call
+ * read_frame(..) provided by the driver to read the actual data.
+ */
+void heatmap_read(struct v4l2_heatmap *v4l2, uint64_t timestamp);
+
+#endif // _HEATMAP_H_
diff --git a/include/uapi/input/touch_offload.h b/include/uapi/input/touch_offload.h
new file mode 100644
index 0000000..01ef107
--- /dev/null
+++ b/include/uapi/input/touch_offload.h
@@ -0,0 +1,409 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+
+#ifndef _UAPI_TOUCH_OFFLOAD_H
+#define _UAPI_TOUCH_OFFLOAD_H
+
+#define TOUCH_OFFLOAD_INTERFACE_MAJOR_VERSION 2
+#define TOUCH_OFFLOAD_INTERFACE_MINOR_VERSION 1
+
+#define TOUCH_OFFLOAD_MAGIC '7'
+
+/* Bus interface type */
+#define BUS_TYPE_I2C 0
+#define BUS_TYPE_SPI 1
+#define BUS_TYPE_I3C 2
+
+/* Indicates full heatmap frame vs. partial */
+#define HEATMAP_SIZE_PARTIAL  0
+#define HEATMAP_SIZE_FULL     1
+
+/* Touch channel data types */
+#define TOUCH_DATA_TYPE_COORD	  0x0001
+#define TOUCH_DATA_TYPE_RAW	  0x0002
+#define TOUCH_DATA_TYPE_FILTERED  0x0004
+#define TOUCH_DATA_TYPE_BASELINE  0x0008
+#define TOUCH_DATA_TYPE_STRENGTH  0x0010
+
+/* Touch channel scan types */
+#define TOUCH_SCAN_TYPE_MUTUAL	  0x0040
+#define TOUCH_SCAN_TYPE_SELF	  0x0080
+
+/* "Context" channel types */
+#define CONTEXT_CHANNEL_TYPE_DRIVER_STATUS  0x0100
+#define CONTEXT_CHANNEL_TYPE_STYLUS_STATUS  0x0200
+/* Inclusive range of valid context channels */
+#define CONTEXT_CHANNEL_BIT_START 0x0100
+#define CONTEXT_CHANNEL_BIT_END   0x0200
+
+//////////////////////////////////////////////////////////////
+
+/* TouchOffloadCaps
+ *
+ * touch_offload_major_version - Major version for breaking changes
+ * touch_offload_minor_version - Minor version for small, compatible changes
+ * device_id - device-specific identifier
+ * touch_width - width of touch resolution
+ * touch_height - height of touch resolution
+ * heatmap_width - width of touch heatmap
+ * heatmap_height - height of touch heatmap
+ * bus_type - bus interface type
+ * bus_speed_hz - bus frequency
+ * heatmap_size - partial or full heatmap
+ * touch_data_scan_types - channel data types available
+ * touch_scan_types - channel scan types available
+ * context_channel_types - bitfield of additional supported channels
+ * continuous_reporting - driver supports continuous touch reports
+ * noise_reporting - driver supports noise status messages
+ * cancel_reporting - driver supports sending cancel events
+ * size_reporting - driver supports size information
+ * rotation_reporting - driver supports rotation information
+ * filter_grip - driver supports disabling underlying grip suppression
+ * filter_palm - driver supports disabling underlying palm rejection
+ * num_sensitivity_settings - number of sensitivity options provided
+ * auto_reporting - report heatmap when screen is not touched
+ * coord_filter - driver supports disabling underlying coordinate filter
+ */
+struct TouchOffloadCaps {
+	/* Version info */
+	__u32 touch_offload_major_version;
+	__u32 touch_offload_minor_version;
+	__u8 reserved1[8];
+
+	/* Device info */
+	__u32 device_id;
+	union {
+	__u16 display_width; /* obsolete */
+	__u16 touch_width;
+	};
+	union {
+	__u16 display_height; /* obsolete */
+	__u16 touch_height;
+	};
+	union {
+	__u16 tx_size; /* obsolete */
+	__u16 heatmap_width;
+	};
+	union {
+	__u16 rx_size; /* obsolete */
+	__u16 heatmap_height;
+	};
+	__u8 bus_type;
+	__u32 bus_speed_hz;
+	__u8 reserved2[16];
+
+	/* Algorithm info */
+	__u8 heatmap_size;
+	__u16 touch_data_types;
+	__u16 touch_scan_types;
+	__u16 context_channel_types;
+	__u8 reserved3[16];
+
+	/* Feature flags */
+	__u8 continuous_reporting;
+	__u8 noise_reporting;
+	__u8 cancel_reporting;
+	__u8 size_reporting;
+	__u8 rotation_reporting;
+	__u8 filter_grip;
+	__u8 filter_palm;
+	__u8 num_sensitivity_settings;
+	__u8 auto_reporting;
+	__u8 coord_filter;
+	__u8 reserved4[31];
+} __attribute__((packed));
+
+/* TouchOffloadConfig
+ *
+ * continuous_reporting - enable continuous touch reports
+ * noise_reporting - enable noise status messages
+ * cancel_reporting - enable cancel events
+ * filter_grip - enable underlying grip suppression
+ * filter_palm - enable underlying palm rejection
+ * sensitivity_setting - selected sensitivity
+ * auto_reporting - enable reporting when screen is not touched
+ * coord_filter - enable underlying coordinate filter
+ * read_coords - allocate a channel to coordinate data
+ * mutual_data_types - bitfield of mutual data types to collect
+ * self_data_types - bitfield of self data types to collect
+ * context_channel_types - bitfield of context channels to collect - overlays
+ *                         on channel type bit mask
+ */
+struct TouchOffloadConfig {
+	/* Feature flags */
+	__u8 continuous_reporting;
+	__u8 noise_reporting;
+	__u8 cancel_reporting;
+	__u8 filter_grip;
+	__u8 filter_palm;
+	__u8 sensitivity_setting;
+	__u8 auto_reporting;
+	__u8 coord_filter;
+	__u8 reserved1[15];
+
+	/* Data to read */
+	__u8 read_coords;
+	__u16 mutual_data_types;
+	__u16 self_data_types;
+	__u16 context_channel_types;
+	__u8 reserved2[16];
+} __attribute__((packed));
+
+/* TouchOffloadFrameHeader
+ *
+ * frame_size - number of bytes in the frame
+ * index - unique, sequential frame index
+ * timestamp - frame timestamp in nanoseconds
+ * num_channels - number of channels included in the frame
+ */
+struct TouchOffloadFrameHeader {
+	__u32 frame_size;
+	__u64 index;
+	__u64 timestamp;
+	__u8 num_channels;
+} __attribute__((packed));
+
+/* TouchOffloadChannelHeader
+ *
+ * channel_type - touch type stored in the channel
+ * channel_size - size in bytes of the channel sample
+ */
+struct TouchOffloadChannelHeader {
+	__u32 channel_type;
+	__u32 channel_size;
+} __attribute__((packed));
+
+/* CoordStatus
+ *
+ * COORD_STATUS_INACTIVE - slot is unused
+ * COORD_STATUS_FINGER - normal finger touch
+ * COORD_STATUS_EDGE - edge touch
+ * COORD_STATUS_PALM - palm touch
+ * COORD_STATUS_CANCEL - canceled touch
+ * COORD_STATUS_PEN - stylus pen touch
+ */
+enum CoordStatus {
+	COORD_STATUS_INACTIVE = 0x00,
+	COORD_STATUS_FINGER = 0x01,
+	COORD_STATUS_EDGE = 0x02,
+	COORD_STATUS_PALM = 0x03,
+	COORD_STATUS_CANCEL = 0x04,
+	COORD_STATUS_PEN = 0x05
+};
+
+/* Maximum number of touches that are tracked simultaneously */
+#define MAX_COORDS 10
+
+/* TouchOffloadCoord
+ *
+ * x - x component of touch location
+ * y - y component of touch location
+ * status - type of touch
+ * major - size of the larger axis of the touch blob
+ * minor - size of the smaller axis of the touch blob
+ * pressure - z-axis or force exerted on touch touch point
+ * rotation - signed rotation of major axis from y-axis, where -16384 is a
+ *            full rotation to the left and 16384 is a rotation to the right.
+ */
+struct TouchOffloadCoord {
+	__u16 x;
+	__u16 y;
+	enum CoordStatus status;
+	__u32 major;
+	__u32 minor;
+	__u32 pressure;
+	__s16 rotation;
+	__u8 reserved1[16];
+} __attribute__((packed));
+
+/* TouchOffloadDataCoord
+ *
+ * header - header shared by all channels in a frame
+ * coords - array of MAX_COORD coordinates
+ */
+struct TouchOffloadDataCoord {
+	struct TouchOffloadChannelHeader header;
+	struct TouchOffloadCoord coords[MAX_COORDS];
+	__u8 reserved1[16];
+} __attribute__((packed));
+#define TOUCH_OFFLOAD_FRAME_SIZE_COORD (sizeof(struct TouchOffloadDataCoord))
+
+/* TouchOffloadData2d
+ *
+ * header - header shared by all channels in a frame
+ * heatmap_width - width of touch heatmap
+ * heatmap_height - height of touch heatmap
+ * data - pointer to raw touch data buffer
+ */
+struct TouchOffloadData2d {
+	struct TouchOffloadChannelHeader header;
+	union {
+	__u16 tx_size; /* obsolete */
+	__u16 heatmap_width;
+	};
+	union {
+	__u16 rx_size; /* obsolete */
+	__u16 heatmap_height;
+	};
+	__u8 reserved1[16];
+	__u8 data[1];
+} __attribute__((packed));
+#define TOUCH_OFFLOAD_DATA_SIZE_2D(heatmap_height, heatmap_width) \
+	(sizeof(__u16)*(heatmap_height)*(heatmap_width))
+#define TOUCH_OFFLOAD_FRAME_SIZE_2D(heatmap_height, heatmap_width) \
+	(sizeof(struct TouchOffloadData2d) - 1 + \
+	TOUCH_OFFLOAD_DATA_SIZE_2D((heatmap_height), (heatmap_width)))
+
+/* TouchOffloadData1d
+ *
+ * header - header shared by all channels in a frame
+ * heatmap_width - width of touch heatmap
+ * heatmap_height - height of touch heatmap
+ * data - pointer to raw touch data buffer
+ */
+struct TouchOffloadData1d {
+	struct TouchOffloadChannelHeader header;
+	union {
+	__u16 tx_size; /* obsolete */
+	__u16 heatmap_width;
+	};
+	union {
+	__u16 rx_size; /* obsolete */
+	__u16 heatmap_height;
+	};
+	__u8 reserved1[16];
+	__u8 data[1];
+} __attribute__((packed));
+#define TOUCH_OFFLOAD_DATA_SIZE_1D(heatmap_height, heatmap_width) \
+	(sizeof(__u16)*((heatmap_height)+(heatmap_width)))
+#define TOUCH_OFFLOAD_FRAME_SIZE_1D(heatmap_height, heatmap_width) \
+	(sizeof(struct TouchOffloadData1d) - 1 + \
+	TOUCH_OFFLOAD_DATA_SIZE_1D((heatmap_height), (heatmap_width)))
+
+/* TouchOffloadDriverStatus
+ *
+ * header - header shared by all channels in a frame
+ * contents - bitfield indicating the corresponding data field is valid
+ * screen_state - 0 = off, 1 = on
+ * display_refresh_rate - display refresh rate in hz
+ * touch_report_rate - touch report rate in hz
+ * noise_state - 0 = no noise, 1 = noise present
+ * water_mode - 0 = normal mode, 1 = water mode
+ * charger_state - 0 = no charger, 1 = charger connected
+ * hinge_angle - angle in range [0=closed, 32767=open 360 degrees]
+ * offload_timestamp - recorded when touch offload frame was generated
+ */
+struct TouchOffloadDriverStatus {
+	struct TouchOffloadChannelHeader header;
+
+	struct DriverBitfieldContents {
+		__u32 screen_state : 1;
+		__u32 display_refresh_rate : 1;
+		__u32 touch_report_rate : 1;
+		__u32 noise_state : 1;
+		__u32 water_mode : 1;
+		__u32 charger_state : 1;
+		__u32 hinge_angle : 1;
+		__u32 offload_timestamp : 1;
+	} contents;
+	__u8 reserved1[8];
+
+	__u8 screen_state;
+	__u8 display_refresh_rate;
+	__u8 touch_report_rate;
+	__u8 noise_state;
+	__u8 water_mode;
+	__u8 charger_state;
+	__s16 hinge_angle;
+
+	__u64 offload_timestamp;
+
+	__u8 reserved2[32];
+} __attribute__((packed));
+#define TOUCH_OFFLOAD_FRAME_SIZE_DRIVER_STATUS \
+		(sizeof(struct TouchOffloadDriverStatus))
+
+/* TouchOffloadStylusStatus
+ *
+ * header - header shared by all channels in a frame
+ * contents - bitfield indicating the corresponding data field is valid
+ * coords - Up to MAX_COORDS active stylus touch points
+ * coords_timestamp - timestamp at which stylus coordinates were received
+ * pen_paired - 0 = no pen paired, 1 = a pen paired
+ * pen_active - 0 = no activity, 1 = a pen is actively communicating
+ */
+struct TouchOffloadStylusStatus {
+	struct TouchOffloadChannelHeader header;
+
+	struct StylusBitfieldContents {
+		__u32 coords : 1;
+		__u32 coords_timestamp : 1;
+		__u32 pen_paired : 1;
+		__u32 pen_active : 1;
+	} contents;
+	__u8 reserved1[8];
+
+	struct TouchOffloadCoord coords[MAX_COORDS];
+	__u64 coords_timestamp;
+	__u8 reserved2[16];
+
+	__u8 pen_paired;
+	__u8 pen_active;
+	__u8 reserved3[16];
+} __attribute__((packed));
+#define TOUCH_OFFLOAD_FRAME_SIZE_STYLUS_STATUS \
+		(sizeof(struct TouchOffloadStylusStatus))
+
+////////////////////////////////////////////////////////////
+
+/* TouchOffloadIocGetCaps
+ *
+ * caps - capabilities provided by the touch driver
+ */
+struct TouchOffloadIocGetCaps {
+	struct TouchOffloadCaps caps;
+	__u8 reserved1[16];
+} __attribute__((packed));
+
+/* TouchOffloadIocConfigure
+ *
+ * config - features to be used by the touch_offload client
+ */
+struct TouchOffloadIocConfigure {
+	struct TouchOffloadConfig config;
+	__u8 reserved1[16];
+} __attribute__((packed));
+
+/* TouchOffloadIocReport
+ *
+ * index - unique, sequential frame index
+ * timestamp - frame timestamp in nanoseconds
+ * num_coords - number of coordinates contained in "coords"
+ * coords - array of coordinates to be reported to the driver
+ */
+struct TouchOffloadIocReport {
+	__u64 index;
+	__u64 timestamp;
+	__u8 num_coords;
+	__u8 reserved1[16];
+	struct TouchOffloadCoord coords[MAX_COORDS];
+} __attribute__((packed));
+
+/* Ioctl to retrieve the capabilities of the touch driver */
+#define TOUCH_OFFLOAD_IOC_RD_GETCAPS \
+	_IOR(TOUCH_OFFLOAD_MAGIC, 0, struct TouchOffloadIocGetCaps)
+
+/* Ioctl to set the configuration of the touch driver */
+#define TOUCH_OFFLOAD_IOC_WR_CONFIGURE \
+	_IOW(TOUCH_OFFLOAD_MAGIC, 1, struct TouchOffloadIocConfigure)
+
+/* Ioctl to start the touch_offload pipeline */
+#define TOUCH_OFFLOAD_IOC_START _IOC(TOUCH_OFFLOAD_MAGIC, 2)
+
+/* Ioctl to report coordinates to the driver */
+#define TOUCH_OFFLOAD_IOC_WR_REPORT \
+	_IOW(TOUCH_OFFLOAD_MAGIC, 3, struct TouchOffloadIocReport)
+
+/* Ioctl to stop the touch_offload pipeline */
+#define TOUCH_OFFLOAD_IOC_STOP _IOC(TOUCH_OFFLOAD_MAGIC, 4)
+
+#endif /* _UAPI_TOUCH_OFFLOAD_H */
diff --git a/touch_bus_negotiator.c b/touch_bus_negotiator.c
new file mode 100644
index 0000000..e51b47a
--- /dev/null
+++ b/touch_bus_negotiator.c
@@ -0,0 +1,625 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Touch Bus Negotiator for Google Pixel devices.
+ *
+ * Copyright (C) 2021 Google, Inc.
+ */
+
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <linux/net.h>
+#include <linux/printk.h>
+#include <linux/slab.h>
+#include <linux/gpio.h>
+#include <linux/interrupt.h>
+#include <linux/irq.h>
+#include <linux/of_gpio.h>
+#include <linux/delay.h>
+#include "touch_bus_negotiator.h"
+
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+#include <uapi/linux/sched/types.h>
+#include "aoc_tbn_service_dev.h"
+#endif
+
+#define TBN_MODULE_NAME "touch_bus_negotiator"
+#define TBN_AOC_CHANNEL_THREAD_NAME "tbn_aoc_channel"
+#define TBN_DATA_BUFFER_MAX 64
+
+#undef pr_fmt
+#define pr_fmt(fmt) "gti: tbn: " fmt
+#undef dev_fmt
+#define dev_fmt(fmt) "gti: " fmt
+
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+static void handle_tbn_event_response(struct tbn_context *tbn,
+	struct TbnEventResponse *response);
+#endif
+static int tbn_handshaking(struct tbn_context *tbn, enum TbnOperation operation);
+static int tbn_remove(struct platform_device *pdev);
+
+static struct tbn_context *tbn_context;
+
+static irqreturn_t tbn_aoc2ap_irq_thread(int irq, void *ptr)
+{
+	struct tbn_context *tbn = ptr;
+
+	pr_info("%s: bus_released:%d bus_requested:%d.\n", __func__,
+		completion_done(&tbn->bus_released), completion_done(&tbn->bus_requested));
+
+	if (completion_done(&tbn->bus_released) && completion_done(&tbn->bus_requested))
+		return IRQ_HANDLED;
+
+	/*
+	 * For bus release, there two possibilities:
+	 * 1. aoc2ap gpio value already changed to AOC
+	 * 2. tbn_release_bus() with TBN_RELEASE_BUS_TIMEOUT_MS timeout
+	 *    for complete_all(&tbn->bus_released);
+	 */
+	while (!completion_done(&tbn->bus_released)) {
+		if (gpio_get_value(tbn->aoc2ap_gpio) == TBN_BUS_OWNER_AOC)
+			complete_all(&tbn->bus_released);
+		else
+			usleep_range(10000, 10000);	/* wait 10 ms for gpio stablized */
+	}
+
+	/*
+	 * For bus request, there two possibilities:
+	 * 1. aoc2ap gpio value already changed to AP
+	 * 2. tbn_request_bus() with TBN_REQUEST_BUS_TIMEOUT_MS timeout
+	 *    for complete_all(&tbn->bus_requested);
+	 */
+	while (!completion_done(&tbn->bus_requested)) {
+		if (gpio_get_value(tbn->aoc2ap_gpio) == TBN_BUS_OWNER_AP)
+			complete_all(&tbn->bus_requested);
+		else
+			usleep_range(10000, 10000);	/* wait 10 ms for gpio stablized */
+	}
+
+	return IRQ_HANDLED;
+}
+
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+static int aoc_channel_kthread(void *data)
+{
+	struct tbn_context *tbn = data;
+	struct TbnEventHeader header;
+	ssize_t len;
+	bool service_ready = false;
+
+	while (!kthread_should_stop()) {
+		if (service_ready != aoc_tbn_service_ready()) {
+			service_ready = !service_ready;
+			pr_info("%s: AOC TBN service is %s.\n",
+				__func__, service_ready ? "ready" : "not ready");
+		}
+
+		if (!service_ready) {
+			msleep(1000);
+			continue;
+		}
+
+		len = aoc_tbn_service_read(&header, sizeof(header));
+		if (len < 0) {
+			pr_err("%s: failed to read message, err: %ld\n",
+				__func__, len);
+			msleep(1000);
+			continue;
+		}
+
+		if (kthread_should_stop()) {
+			break;
+		}
+
+		if (header.operation == TBN_OPERATION_AOC_RESET) {
+			if (tbn->event_wq)
+				queue_work(tbn->event_wq, &tbn->aoc_reset_work);
+		} else if (header.operation == TBN_OPERATION_AOC_SEND_LPTW_EVENT) {
+			struct TbnLptwEvent* gesture;
+
+			if (len != sizeof(*gesture)) {
+				pr_err("%s: Abnormal gesture data length: %ld\n", __func__, len);
+				continue;
+			}
+			gesture = (struct TbnLptwEvent*)&header;
+			pr_info("%s: LPTW event, x=%u y=%u major=%u minor=%u angle=%d\n",
+				__func__, gesture->x, gesture->y, gesture->major,
+				gesture->minor, gesture->angle);
+			if (tbn->lptw_event_cb)
+				tbn->lptw_event_cb(gesture, tbn->lptw_event_cbdata);
+		} else {
+			struct TbnEventResponse* resp;
+
+			if (len != sizeof(*resp)) {
+				pr_err("%s: Abnormal resp data length: %ld\n", __func__, len);
+				continue;
+			}
+			resp = (struct TbnEventResponse*)&header;
+			handle_tbn_event_response(tbn, resp);
+		}
+	}
+
+	return 0;
+}
+
+static void handle_tbn_event_response(struct tbn_context *tbn,
+	struct TbnEventResponse *response)
+{
+	mutex_lock(&tbn->event_lock);
+
+	if (response->id != tbn->event.id) {
+		pr_err("%s: receive wrong response, id: %d, expected id: %d, "
+			"bus_released:%d bus_requested:%d.\n",
+			__func__, response->id, tbn->event.id,
+			completion_done(&tbn->bus_released),
+			completion_done(&tbn->bus_requested));
+		goto exit;
+	}
+
+	if (response->err != 0) {
+		pr_err("%s: send tbn event failed, err %d!\n",
+			__func__, response->err);
+		tbn->event_resp.err = response->err;
+	} else {
+		tbn->event_resp.lptw_triggered = response->lptw_triggered;
+	}
+
+	if (response->operation == TBN_OPERATION_AP_REQUEST_BUS) {
+		complete_all(&tbn->bus_requested);
+	} else if (response->operation == TBN_OPERATION_AP_RELEASE_BUS) {
+		complete_all(&tbn->bus_released);
+	} else {
+		pr_err("%s: response unknown operation, op: %d!\n",
+			__func__, response->operation);
+	}
+
+exit:
+	mutex_unlock(&tbn->event_lock);
+}
+
+static void send_tbn_event(struct tbn_context *tbn, enum TbnOperation operation)
+{
+	ssize_t len;
+	int retry = 3;
+
+	if (!aoc_tbn_service_ready()) {
+		pr_err("%s: AOC TBN service is not ready.\n",
+			__func__);
+		return;
+	}
+
+	mutex_lock(&tbn->event_lock);
+
+	tbn->event.operation = operation;
+	tbn->event.id++;
+
+	while (retry) {
+		len = aoc_tbn_service_write(&tbn->event, sizeof(tbn->event));
+		if (len == sizeof(tbn->event)) {
+			break;
+		}
+		pr_err("%s: failed to send TBN event, retry: %d.\n",
+			__func__, retry);
+		retry--;
+	}
+
+	mutex_unlock(&tbn->event_lock);
+}
+#endif
+
+static int tbn_handshaking(struct tbn_context *tbn, enum TbnOperation operation)
+{
+	struct completion *wait_for_completion;
+	enum tbn_bus_owner bus_owner;
+	unsigned int irq_type;
+	unsigned int timeout;
+	const char *msg;
+	int ret = 0;
+
+	if (!tbn || tbn->registered_mask == 0) {
+		pr_err("%s: tbn is not ready to serve.\n", __func__);
+		return -EINVAL;
+	}
+
+	if (operation == TBN_OPERATION_AP_REQUEST_BUS) {
+		wait_for_completion = &tbn->bus_requested;
+		bus_owner = TBN_BUS_OWNER_AP;
+		irq_type = IRQF_TRIGGER_FALLING;
+		timeout = TBN_REQUEST_BUS_TIMEOUT_MS;
+		msg = "request";
+	} else if (operation == TBN_OPERATION_AP_RELEASE_BUS) {
+		wait_for_completion = &tbn->bus_released;
+		bus_owner = TBN_BUS_OWNER_AOC;
+		irq_type = IRQF_TRIGGER_RISING;
+		timeout = TBN_RELEASE_BUS_TIMEOUT_MS;
+		msg = "release";
+	} else {
+		pr_err("%s: request unknown operation, op: %d.\n",
+			__func__, operation);
+		return -EINVAL;
+	}
+
+	if (tbn->mode == TBN_MODE_GPIO) {
+		int ap2aoc_val_org = gpio_get_value(tbn->ap2aoc_gpio);
+		int aoc2ap_val_org = gpio_get_value(tbn->aoc2ap_gpio);
+
+		reinit_completion(wait_for_completion);
+
+		irq_set_irq_type(tbn->aoc2ap_irq, irq_type);
+		enable_irq(tbn->aoc2ap_irq);
+		gpio_direction_output(tbn->ap2aoc_gpio, bus_owner);
+		if (wait_for_completion_timeout(wait_for_completion,
+			msecs_to_jiffies(timeout)) == 0) {
+			int ap2aoc_val = gpio_get_value(tbn->ap2aoc_gpio);
+			int aoc2ap_val = gpio_get_value(tbn->aoc2ap_gpio);
+
+			complete_all(wait_for_completion);
+			if (bus_owner == aoc2ap_val)
+				ret = 0;
+			else
+				ret = -ETIMEDOUT;
+			pr_err("AP %s bus ... timeout!, ap2aoc_gpio(B:%d,A:%d)"
+				" aoc2ap_gpio(B:%d,A:%d), ret=%d\n",
+				msg, ap2aoc_val_org, ap2aoc_val, aoc2ap_val_org,
+				aoc2ap_val, ret);
+		} else
+			pr_info("AP %s bus ... SUCCESS!\n", msg);
+		disable_irq_nosync(tbn->aoc2ap_irq);
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+	} else if (tbn->mode == TBN_MODE_AOC_CHANNEL) {
+		tbn->event_resp.lptw_triggered = false;
+		tbn->event_resp.err = 0;
+
+		reinit_completion(wait_for_completion);
+
+		send_tbn_event(tbn, operation);
+		if (wait_for_completion_timeout(wait_for_completion,
+			msecs_to_jiffies(timeout)) == 0) {
+			pr_err("AP %s bus ... timeout!\n", msg);
+			complete_all(wait_for_completion);
+			ret = -ETIMEDOUT;
+		} else {
+			if (tbn->event_resp.err == 0) {
+				pr_info("AP %s bus ... SUCCESS!\n", msg);
+			} else {
+				pr_info("AP %s bus ... failed!\n", msg);
+				ret = -EBUSY;
+			}
+		}
+#endif
+	} else if (tbn->mode == TBN_MODE_MOCK) {
+		pr_info("AP %s bus ... SUCCESS!\n", msg);
+	} else {
+		ret = -EINVAL;
+	}
+
+	return ret;
+}
+
+int tbn_request_bus_with_result(u32 dev_mask, bool *lptw_triggered)
+{
+	int ret = 0;
+
+	if (!tbn_context)
+		return -ENODEV;
+
+	mutex_lock(&tbn_context->dev_mask_mutex);
+
+	if ((dev_mask & tbn_context->registered_mask) == 0) {
+		mutex_unlock(&tbn_context->dev_mask_mutex);
+		pr_err("%s: dev_mask %#x is invalid.\n",
+			__func__, dev_mask);
+		return -EINVAL;
+	}
+
+	if (tbn_context->requested_dev_mask == 0) {
+		ret = tbn_handshaking(tbn_context, TBN_OPERATION_AP_REQUEST_BUS);
+		if ((ret == 0) && (lptw_triggered != NULL))
+			*lptw_triggered = tbn_context->event_resp.lptw_triggered;
+	} else {
+		dev_dbg(tbn_context->dev,
+			"%s: Bus already requested, requested_dev_mask %#x dev_mask %#x.\n",
+			__func__, tbn_context->requested_dev_mask, dev_mask);
+	}
+	tbn_context->requested_dev_mask |= dev_mask;
+
+	mutex_unlock(&tbn_context->dev_mask_mutex);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(tbn_request_bus_with_result);
+
+int tbn_request_bus(u32 dev_mask)
+{
+	return tbn_request_bus_with_result(dev_mask, NULL);
+}
+EXPORT_SYMBOL_GPL(tbn_request_bus);
+
+int tbn_release_bus(u32 dev_mask)
+{
+	int ret = 0;
+
+	if (!tbn_context)
+		return -ENODEV;
+
+	mutex_lock(&tbn_context->dev_mask_mutex);
+
+	if ((dev_mask & tbn_context->registered_mask) == 0) {
+		mutex_unlock(&tbn_context->dev_mask_mutex);
+		pr_err("%s: dev_mask %#x is invalid.\n",
+			__func__, dev_mask);
+		return -EINVAL;
+	}
+
+	if (tbn_context->requested_dev_mask == 0) {
+		pr_warn("%s: Bus already released, dev_mask %#x.\n",
+			 __func__, dev_mask);
+		mutex_unlock(&tbn_context->dev_mask_mutex);
+		return 0;
+	}
+
+	/* Release the bus when the last requested_dev_mask bit releases. */
+	if (tbn_context->requested_dev_mask == dev_mask) {
+		ret = tbn_handshaking(tbn_context, TBN_OPERATION_AP_RELEASE_BUS);
+	} else {
+		dev_dbg(tbn_context->dev,
+			 "%s: Bus is still in use, requested_dev_mask %#x dev_mask %#x.\n",
+			 __func__, tbn_context->requested_dev_mask, dev_mask);
+	}
+
+	tbn_context->requested_dev_mask &= ~dev_mask;
+
+	mutex_unlock(&tbn_context->dev_mask_mutex);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(tbn_release_bus);
+
+int register_tbn(u32 *output)
+{
+	u32 i = 0;
+
+	*output = 0;
+
+	if (!tbn_context) {
+		pr_warn("%s: tbn_context doesn't exist.", __func__);
+		return 0;
+	}
+
+	mutex_lock(&tbn_context->dev_mask_mutex);
+	for (i = 0; i < tbn_context->max_devices; i++) {
+		if (tbn_context->registered_mask & BIT_MASK(i))
+			continue;
+		tbn_context->registered_mask |= BIT_MASK(i);
+		/* Assume screen is on while registering tbn. */
+		tbn_context->requested_dev_mask |= BIT_MASK(i);
+		*output = BIT_MASK(i);
+		break;
+	}
+
+	mutex_unlock(&tbn_context->dev_mask_mutex);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(register_tbn);
+
+void register_tbn_lptw_callback(void* callback, void* cbdata)
+{
+	tbn_context->lptw_event_cb = callback;
+	tbn_context->lptw_event_cbdata = cbdata;
+}
+EXPORT_SYMBOL_GPL(register_tbn_lptw_callback);
+
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+void tbn_aoc_reset_work(struct work_struct *work) {
+	struct tbn_context *tbn = container_of(work, struct tbn_context, aoc_reset_work);
+
+	pr_warn("%s: AOC has been reset", __func__);
+	if (tbn->requested_dev_mask == 0)
+		tbn_handshaking(tbn, TBN_OPERATION_AP_RELEASE_BUS);
+	else
+		tbn_handshaking(tbn, TBN_OPERATION_AP_REQUEST_BUS);
+}
+#endif
+
+void unregister_tbn(u32 *output)
+{
+	if (!tbn_context)
+		return ;
+
+	mutex_lock(&tbn_context->dev_mask_mutex);
+	tbn_context->registered_mask &= ~(*output);
+	*output = 0;
+	mutex_unlock(&tbn_context->dev_mask_mutex);
+}
+EXPORT_SYMBOL_GPL(unregister_tbn);
+
+static int tbn_probe(struct platform_device *pdev)
+{
+	struct device *dev = &pdev->dev;
+	struct tbn_context *tbn = NULL;
+	struct device_node *np = dev->of_node;
+	int err = 0;
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+	struct sched_param param = {
+		.sched_priority = 10,
+	};
+#endif
+
+
+	tbn = devm_kzalloc(dev, sizeof(struct tbn_context), GFP_KERNEL);
+	if (!tbn) {
+		err = -ENOMEM;
+		goto failed;
+	}
+
+	tbn->dev = dev;
+	tbn->event_resp.lptw_triggered = false;
+	tbn_context = tbn;
+	dev_set_drvdata(tbn->dev, tbn);
+
+	if (of_property_read_u32(np, "tbn,max_devices", &tbn->max_devices))
+		tbn->max_devices = 1;
+
+	err = of_property_read_u32(np, "tbn,mode", &tbn->mode);
+	if (err)
+		tbn->mode = TBN_MODE_GPIO;
+
+	if (tbn->mode == TBN_MODE_GPIO) {
+		tbn->ap2aoc_gpio = of_get_named_gpio(np, "tbn,ap2aoc_gpio", 0);
+		if (gpio_is_valid(tbn->ap2aoc_gpio)) {
+			err = devm_gpio_request_one(tbn->dev, tbn->ap2aoc_gpio,
+				GPIOF_OUT_INIT_LOW, "tbn,ap2aoc_gpio");
+			if (err) {
+				pr_err("%s: Unable to request ap2aoc_gpio %d, err %d!\n",
+					__func__, tbn->ap2aoc_gpio, err);
+				goto failed;
+			}
+		} else {
+			pr_err("%s: invalid ap2aoc_gpio %d!\n",
+				__func__, tbn->ap2aoc_gpio);
+			err = -EPROBE_DEFER;
+			goto failed;
+		}
+
+		tbn->aoc2ap_gpio = of_get_named_gpio(np, "tbn,aoc2ap_gpio", 0);
+		if (gpio_is_valid(tbn->aoc2ap_gpio)) {
+			err = devm_gpio_request_one(tbn->dev, tbn->aoc2ap_gpio,
+				GPIOF_DIR_IN, "tbn,aoc2ap_gpio");
+			if (err) {
+				pr_err("%s: Unable to request aoc2ap_gpio %d, err %d!\n",
+					__func__, tbn->aoc2ap_gpio, err);
+				goto failed;
+			}
+			tbn->aoc2ap_irq = gpio_to_irq(tbn->aoc2ap_gpio);
+			err = devm_request_threaded_irq(tbn->dev,
+				tbn->aoc2ap_irq, NULL,
+				tbn_aoc2ap_irq_thread,
+				IRQF_TRIGGER_RISING |
+				IRQF_ONESHOT, "tbn", tbn);
+			if (err) {
+				pr_err("%s: Unable to request_threaded_irq, err %d!\n",
+					__func__, err);
+				goto failed;
+			}
+			disable_irq_nosync(tbn->aoc2ap_irq);
+		} else {
+			pr_err("%s: invalid aoc2ap_gpio %d!\n",
+				__func__, tbn->aoc2ap_gpio);
+			err = -EPROBE_DEFER;
+			goto failed;
+		}
+
+		pr_info("%s: gpios(aoc2ap: %d ap2aoc: %d)\n",
+			__func__, tbn->aoc2ap_gpio, tbn->ap2aoc_gpio);
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+	} else if (tbn->mode == TBN_MODE_AOC_CHANNEL) {
+		mutex_init(&tbn->event_lock);
+
+		tbn->aoc_channel_task = kthread_run(&aoc_channel_kthread, tbn,
+			TBN_AOC_CHANNEL_THREAD_NAME);
+		if (IS_ERR(tbn->aoc_channel_task)) {
+			err = PTR_ERR(tbn->aoc_channel_task);
+			goto failed;
+		}
+
+		err = sched_setscheduler(tbn->aoc_channel_task, SCHED_FIFO, &param);
+		if (err != 0) {
+			goto failed;
+		}
+
+		tbn->event_wq = alloc_workqueue(
+			"tbn_wq", WQ_UNBOUND | WQ_HIGHPRI | WQ_CPU_INTENSIVE, 1);
+		if (!tbn->event_wq) {
+			err = -ENOMEM;
+			pr_err("Failed to create work thread for tbn!\n");
+			goto failed;
+		}
+
+		INIT_WORK(&tbn->aoc_reset_work, tbn_aoc_reset_work);
+#endif
+	} else if (tbn->mode == TBN_MODE_MOCK) {
+		err = 0;
+	} else {
+		pr_err("bus negotiator: invalid mode: %d\n", tbn->mode);
+		err = -EINVAL;
+		goto failed;
+	}
+
+	mutex_init(&tbn->dev_mask_mutex);
+
+	init_completion(&tbn->bus_requested);
+	init_completion(&tbn->bus_released);
+	complete_all(&tbn->bus_requested);
+	complete_all(&tbn->bus_released);
+
+	pr_info("bus negotiator initialized: %pK, mode: %d\n", tbn, tbn->mode);
+
+failed:
+	if (err)
+		tbn_remove(pdev);
+
+	return err;
+}
+
+static int tbn_remove(struct platform_device *pdev)
+{
+	struct device *dev = &pdev->dev;
+	struct tbn_context *tbn = dev_get_drvdata(dev);
+
+	if (tbn == NULL)
+		return 0;
+
+	if (tbn->mode == TBN_MODE_GPIO) {
+		free_irq(tbn->aoc2ap_irq, tbn);
+		if (gpio_is_valid(tbn->ap2aoc_gpio))
+			gpio_free(tbn->ap2aoc_gpio);
+		if (gpio_is_valid(tbn->aoc2ap_gpio))
+			gpio_free(tbn->aoc2ap_gpio);
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+	} else if (tbn->mode == TBN_MODE_AOC_CHANNEL) {
+		if (!IS_ERR(tbn->aoc_channel_task))
+			kthread_stop(tbn->aoc_channel_task);
+		if (tbn->event_wq)
+			destroy_workqueue(tbn->event_wq);
+#endif
+	}
+
+	devm_kfree(dev, tbn);
+	tbn_context = NULL;
+	return 0;
+}
+
+static struct of_device_id tbn_of_match_table[] = {
+	{
+		.compatible = TBN_MODULE_NAME,
+	},
+	{},
+};
+MODULE_DEVICE_TABLE(of, tbn_of_match_table);
+
+static struct platform_driver tbn_driver = {
+	.driver = {
+		.name = TBN_MODULE_NAME,
+		.of_match_table = tbn_of_match_table,
+	},
+	.probe = tbn_probe,
+	.remove = tbn_remove,
+};
+
+static int __init tbn_init(void)
+{
+	return platform_driver_register(&tbn_driver);
+}
+
+static void __exit tbn_exit(void)
+{
+	platform_driver_unregister(&tbn_driver);
+}
+module_init(tbn_init);
+module_exit(tbn_exit);
+
+MODULE_SOFTDEP("pre: touch_offload");
+MODULE_LICENSE("GPL v2");
+MODULE_DESCRIPTION("Touch Bus Negotiator");
+MODULE_AUTHOR("Google, Inc.");
diff --git a/touch_bus_negotiator.h b/touch_bus_negotiator.h
new file mode 100644
index 0000000..4527fd7
--- /dev/null
+++ b/touch_bus_negotiator.h
@@ -0,0 +1,103 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef TOUCHSCREEN_BUS_NEGOTIATOR_H
+#define TOUCHSCREEN_BUS_NEGOTIATOR_H
+
+#include <linux/notifier.h>
+#include <linux/mutex.h>
+#include <linux/device.h>
+#include <linux/cdev.h>
+#include <linux/kthread.h>
+
+#define TBN_DEVICE_NAME "tbn"
+#define TBN_CLASS_NAME "tbn"
+
+#define TBN_REQUEST_BUS_TIMEOUT_MS 500
+#define TBN_RELEASE_BUS_TIMEOUT_MS 500
+
+enum tbn_mode {
+	TBN_MODE_DISABLED = 0,
+	TBN_MODE_GPIO,
+	TBN_MODE_AOC_CHANNEL,
+	TBN_MODE_MOCK,
+};
+
+enum tbn_bus_owner {
+	TBN_BUS_OWNER_AP = 0,
+	TBN_BUS_OWNER_AOC = 1,
+};
+
+enum TbnOperation : __u32 {
+	TBN_OPERATION_IDLE = 0,
+	TBN_OPERATION_AP_RELEASE_BUS,
+	TBN_OPERATION_AP_REQUEST_BUS,
+	TBN_OPERATION_AOC_RESET,
+	TBN_OPERATION_AOC_SEND_LPTW_EVENT,
+};
+
+struct TbnEvent {
+	__u32 id;
+	enum TbnOperation operation;
+} __packed;
+
+struct TbnEventHeader {
+    __u32 id;
+    __s32 err;
+    enum TbnOperation operation;
+    __u8 data[52];
+} __packed;
+
+struct TbnEventResponse {
+	__u32 id;
+	__s32 err;
+	enum TbnOperation operation;
+	bool lptw_triggered;
+} __packed;
+
+struct TbnLptwEvent {
+	__u32 id;
+	__s32 err;
+	enum TbnOperation operation;
+	u16 x;
+	u16 y;
+	u16 major;
+	u16 minor;
+	s16 angle;
+} __packed;
+
+struct tbn_context {
+	struct device *dev;
+	struct completion bus_requested;
+	struct completion bus_released;
+	struct mutex dev_mask_mutex;
+	u32 mode;
+	u32 max_devices;
+	u32 registered_mask;
+	u32 requested_dev_mask;
+	int aoc2ap_gpio;
+	int ap2aoc_gpio;
+	int aoc2ap_irq;
+	struct task_struct *aoc_channel_task;
+
+	/* event management */
+	struct TbnEventResponse event_resp;
+#if IS_ENABLED(CONFIG_TOUCHSCREEN_TBN_AOC_CHANNEL_MODE)
+	struct TbnEvent event;
+	struct mutex event_lock;
+	struct work_struct aoc_reset_work;
+	struct workqueue_struct *event_wq;
+#endif
+
+	void (*lptw_event_cb)(struct TbnLptwEvent* lptw, void* user_data);
+	void* lptw_event_cbdata;
+};
+
+int register_tbn(u32 *output);
+void register_tbn_lptw_callback(void* callback, void* cbdata);
+void unregister_tbn(u32 *output);
+int tbn_request_bus_with_result(u32 dev_mask, bool *lptw_triggered);
+int tbn_request_bus(u32 dev_mask);
+int tbn_release_bus(u32 dev_mask);
+
+
+#endif /* TOUCHSCREEN_BUS_NEGOTIATOR_H */
diff --git a/touch_offload.c b/touch_offload.c
new file mode 100644
index 0000000..9c64d47
--- /dev/null
+++ b/touch_offload.c
@@ -0,0 +1,744 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/module.h>
+#include <linux/fs.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+#include <linux/poll.h>
+
+#include "touch_offload.h"
+
+static int touch_offload_open(struct inode *inode, struct file *file)
+{
+	struct touch_offload_context *context =
+		container_of(inode->i_cdev, struct touch_offload_context, dev);
+
+	file->private_data = context;
+	pr_debug("%s\n", __func__);
+
+	mutex_lock(&context->file_lock);
+	if (context->file_in_use) {
+		mutex_unlock(&context->file_lock);
+		return -EBUSY;
+	}
+	context->file_in_use = true;
+	mutex_unlock(&context->file_lock);
+
+	/* Prepare context for consumer. E.g., event queue */
+	return 0;
+}
+
+static int touch_offload_release(struct inode *inode, struct file *file)
+{
+	struct touch_offload_context *context = file->private_data;
+
+	mutex_lock(&context->file_lock);
+	context->file_in_use = false;
+	mutex_unlock(&context->file_lock);
+
+	pr_debug("%s\n", __func__);
+	return 0;
+}
+
+static int pack_frame(struct touch_offload_context *context,
+		      struct touch_offload_frame *frame, u8 **packed)
+{
+	u8 *ptr = context->prealloc_packed_frame;
+	int channel_size;
+	int i = 0;
+
+	if (!ptr || !frame || frame->num_channels > MAX_CHANNELS)
+		return -EINVAL;
+
+	/* Copy the header */
+	memcpy(ptr, &frame->header, sizeof(frame->header));
+	ptr += sizeof(frame->header);
+
+	/* Copy frame data */
+	for (i = 0; i < frame->num_channels; i++) {
+		if (frame->channel_type[i] == TOUCH_DATA_TYPE_COORD)
+			channel_size = TOUCH_OFFLOAD_FRAME_SIZE_COORD;
+		else if ((frame->channel_type[i] & TOUCH_SCAN_TYPE_MUTUAL) != 0)
+			channel_size =
+			    TOUCH_OFFLOAD_FRAME_SIZE_2D(context->caps.heatmap_height,
+							context->caps.heatmap_width);
+		else if ((frame->channel_type[i] & TOUCH_SCAN_TYPE_SELF) != 0)
+			channel_size =
+			    TOUCH_OFFLOAD_FRAME_SIZE_1D(context->caps.heatmap_height,
+							context->caps.heatmap_width);
+		else if (frame->channel_type[i] ==
+				CONTEXT_CHANNEL_TYPE_DRIVER_STATUS)
+			channel_size = TOUCH_OFFLOAD_FRAME_SIZE_DRIVER_STATUS;
+		else if (frame->channel_type[i] ==
+				CONTEXT_CHANNEL_TYPE_STYLUS_STATUS)
+			channel_size = TOUCH_OFFLOAD_FRAME_SIZE_STYLUS_STATUS;
+		else {
+			pr_err("%s: Invalid channel_type = 0x%08X", __func__,
+			       frame->channel_type[i]);
+			return -EINVAL;
+		}
+		memcpy(ptr, frame->channel_data[i], channel_size);
+		ptr += channel_size;
+	}
+
+	*packed = context->prealloc_packed_frame;
+	return (ptr - *packed);
+}
+
+static ssize_t touch_offload_read(struct file *file, char __user *user_buffer,
+				  size_t size, loff_t *offset)
+{
+	struct touch_offload_context *context = file->private_data;
+	struct touch_offload_frame *frame;
+	size_t copy_size;
+	int result;
+	unsigned long remaining;
+
+	pr_debug("%s\n", __func__);
+
+	if (context->num_buffers == 0)
+		return -EINVAL;
+
+	/* Block until touch events occur */
+	/* Block (on completion?) until len >= 0. */
+	/* Lock the event buffer */
+	/* Copy contents of event buffer to service */
+	/* Reset completion since len=0 */
+	/* Unlock and return */
+
+	/* If the end of the data is reached, free the packed_frame and
+	 * return 0
+	 */
+
+	mutex_lock(&context->buffer_lock);
+
+	if (context->packed_frame != NULL &&
+	    *offset == context->packed_frame_size) {
+		pr_err("%s: [Unexpected!] The buffer should have been recycled after the previous read.\n",
+		       __func__);
+		context->packed_frame = NULL;
+		*offset = 0;
+		mutex_unlock(&context->buffer_lock);
+		return 0;
+	} else if (context->packed_frame == NULL) {
+		/* Process the next queued buffer */
+
+		while (list_empty(&context->frame_queue)) {
+			/* Presumably more buffers on the way, so block */
+			mutex_unlock(&context->buffer_lock);
+
+			/* Non-blocking read? */
+			if (file->f_flags & O_NONBLOCK)
+				return -EAGAIN;
+
+			/* Block until data is available */
+			if (wait_event_interruptible(context->read_queue,
+					!list_empty(&context->frame_queue)))
+				return -ERESTARTSYS;
+
+			/* Check that the pipeline is still running */
+			mutex_lock(&context->buffer_lock);
+		}
+
+		frame = list_entry(context->frame_queue.next,
+				   struct touch_offload_frame, entry);
+		list_del(&frame->entry);
+
+		result = pack_frame(context, frame, &context->packed_frame);
+		list_add_tail(&frame->entry, &context->free_pool);
+		if (result <= 0) {
+			pr_err("%s: Error packing frame! Result = %d.\n",
+			       __func__, result);
+			mutex_unlock(&context->buffer_lock);
+			return -EINVAL;
+		}
+		if (result != context->packed_frame_size) {
+			pr_err("%s: Packed frame size (%d) does not match size allocated per frame(%d)!\n",
+			       __func__, result, context->packed_frame_size);
+		}
+
+	}
+
+	/* Transfer the maximum amount of data */
+	copy_size = min((long long)size, context->packed_frame_size - *offset);
+	remaining = copy_to_user(user_buffer, context->packed_frame + *offset,
+			      copy_size);
+	if (remaining != 0)
+		pr_err("%s: copy_to_user unexpectedly failed to copy %lu bytes.\n",
+		       __func__, remaining);
+	*offset += copy_size - remaining;
+
+	/* Recycle the frame if transfer was complete */
+	if (*offset == context->packed_frame_size) {
+		context->packed_frame = NULL;
+		*offset = 0;
+	}
+
+	mutex_unlock(&context->buffer_lock);
+
+	return copy_size - remaining;
+}
+
+static unsigned int touch_offload_poll(struct file *file,
+				       struct poll_table_struct *wait)
+{
+	struct touch_offload_context *context = file->private_data;
+	unsigned int flags = 0;
+
+	pr_debug("%s\n", __func__);
+
+	poll_wait(file, &context->read_queue, wait);
+
+	mutex_lock(&context->buffer_lock);
+
+	if (context->packed_frame || !list_empty(&context->frame_queue))
+		flags |= POLLIN | POLLRDNORM;
+
+	mutex_unlock(&context->buffer_lock);
+	return flags;
+}
+
+static int touch_offload_allocate_buffers(struct touch_offload_context *context,
+					  int nb)
+{
+	struct touch_offload_frame *frame = NULL;
+	int i;
+	int num_channels;
+	__u32 mask;
+	__u32 size = 0;
+	int max_packed_frame_size =
+		sizeof(struct touch_offload_frame) +
+		TOUCH_OFFLOAD_DATA_SIZE_2D(context->caps.heatmap_height,
+					   context->caps.heatmap_width) *
+		MAX_CHANNELS;
+
+	pr_debug("%s\n", __func__);
+
+	num_channels = (context->config.read_coords ? 1 : 0) +
+		       hweight_long(context->config.mutual_data_types) +
+		       hweight_long(context->config.self_data_types) +
+		       hweight_long(context->config.context_channel_types);
+	if (num_channels == 0 || num_channels > MAX_CHANNELS) {
+		pr_err("%s: Configuration enables more (%d) than %d channels!\n",
+		       __func__, num_channels, MAX_CHANNELS);
+		return -EINVAL;
+	}
+
+
+	mutex_lock(&context->buffer_lock);
+	context->prealloc_packed_frame =
+		devm_kzalloc(context->device, max_packed_frame_size, GFP_KERNEL);
+	if (context->prealloc_packed_frame == NULL) {
+		mutex_unlock(&context->buffer_lock);
+		return -ENOMEM;
+	}
+	context->prealloc_packed_frame_size = max_packed_frame_size;
+
+	/* Add new buffers to the free_pool */
+	for (i = 0; i < nb; i++) {
+		int chan = 0;
+		struct touch_offload_frame *frame =
+		    kzalloc(sizeof(struct touch_offload_frame), GFP_KERNEL);
+
+		if (frame == NULL) {
+			mutex_unlock(&context->buffer_lock);
+			return -ENOMEM;
+		}
+
+		frame->header.frame_size = sizeof(frame->header);
+
+		/* Allocate component buffers */
+
+		if (context->config.read_coords) {
+			struct TouchOffloadDataCoord *coord;
+
+			frame->channel_type[chan] = TOUCH_DATA_TYPE_COORD;
+			size = TOUCH_OFFLOAD_FRAME_SIZE_COORD;
+			frame->channel_data[chan] = kzalloc(size,
+							       GFP_KERNEL);
+			if (frame->channel_data[chan] == NULL)
+				goto kzalloc_channel_fail;
+			coord = (struct TouchOffloadDataCoord *)
+					frame->channel_data[chan];
+			coord->header.channel_type = TOUCH_DATA_TYPE_COORD;
+			coord->header.channel_size = size;
+			frame->channel_data_size[chan] = size;
+			frame->header.frame_size += size;
+			chan++;
+		}
+		for (mask = 0x01; mask < 0x100; mask <<= 1) {
+			if ((context->config.mutual_data_types & mask) != 0) {
+				struct TouchOffloadData2d *data;
+
+				frame->channel_type[chan] =
+				    TOUCH_SCAN_TYPE_MUTUAL | mask;
+				size = TOUCH_OFFLOAD_FRAME_SIZE_2D(
+						context->caps.heatmap_height,
+						context->caps.heatmap_width);
+				frame->channel_data[chan] = kzalloc(size,
+								    GFP_KERNEL);
+				if (frame->channel_data[chan] == NULL)
+					goto kzalloc_channel_fail;
+				data = (struct TouchOffloadData2d *)
+						frame->channel_data[chan];
+				data->header.channel_type =
+				    TOUCH_SCAN_TYPE_MUTUAL | mask;
+				data->header.channel_size = size;
+				frame->channel_data_size[chan] = size;
+				frame->header.frame_size += size;
+				chan++;
+			}
+		}
+		for (mask = 0x01; mask < 0x100; mask <<= 1) {
+			if ((context->config.self_data_types & mask) != 0) {
+				struct TouchOffloadData1d *data;
+
+				frame->channel_type[chan] =
+					TOUCH_SCAN_TYPE_SELF | mask;
+				size = TOUCH_OFFLOAD_FRAME_SIZE_1D(
+						context->caps.heatmap_height,
+						context->caps.heatmap_width);
+				frame->channel_data[chan] = kzalloc(size,
+								GFP_KERNEL);
+				if (frame->channel_data[chan] == NULL)
+					goto kzalloc_channel_fail;
+				data = (struct TouchOffloadData1d *)
+						frame->channel_data[chan];
+				data->header.channel_type =
+				    TOUCH_SCAN_TYPE_SELF | mask;
+				data->header.channel_size = size;
+				frame->channel_data_size[chan] = size;
+				frame->header.frame_size += size;
+				chan++;
+			}
+		}
+		for (mask = CONTEXT_CHANNEL_BIT_START;
+		     mask <= CONTEXT_CHANNEL_BIT_END;
+		     mask <<= 1) {
+			struct TouchOffloadChannelHeader *chan_header;
+
+			if (!(context->config.context_channel_types & mask))
+				continue;
+
+			frame->channel_type[chan] = (__u32)mask;
+			size = 0;
+			switch (mask) {
+			case CONTEXT_CHANNEL_TYPE_DRIVER_STATUS:
+				size =
+				    TOUCH_OFFLOAD_FRAME_SIZE_DRIVER_STATUS;
+				break;
+			case CONTEXT_CHANNEL_TYPE_STYLUS_STATUS:
+				size =
+				    TOUCH_OFFLOAD_FRAME_SIZE_STYLUS_STATUS;
+				break;
+			default:
+				pr_err("%s: Invalid channel_type = 0x%08X\n",
+					__func__, mask);
+				goto invalid_context_channel;
+			}
+			frame->channel_data[chan] = kzalloc(size,
+							GFP_KERNEL);
+			if (frame->channel_data[chan] == NULL)
+				goto kzalloc_channel_fail;
+
+			chan_header =
+				(struct TouchOffloadChannelHeader *)
+					frame->channel_data[chan];
+			chan_header->channel_type = (__u32)mask;
+			chan_header->channel_size = size;
+			frame->channel_data_size[chan] = size;
+			frame->header.frame_size += size;
+			chan++;
+		}
+
+		frame->num_channels = chan;
+		frame->header.num_channels = chan;
+
+		if (context->packed_frame_size == 0)
+			context->packed_frame_size = frame->header.frame_size;
+		if (context->packed_frame_size != frame->header.frame_size)
+			pr_err("%s: Frame size mismatch! %d != %d.\n", __func__,
+			       context->packed_frame_size,
+			       frame->header.frame_size);
+
+		list_add_tail(&frame->entry, &context->free_pool);
+		context->num_buffers++;
+	}
+
+	mutex_unlock(&context->buffer_lock);
+	return 0;
+
+invalid_context_channel:
+kzalloc_channel_fail:
+	/* Free all channels of "frame" before returning */
+	if (frame)
+		for (i = 0; i < MAX_CHANNELS; i++)
+			kfree(frame->channel_data[i]);
+	kfree(frame);
+
+	mutex_unlock(&context->buffer_lock);
+	return -ENOMEM;
+}
+
+static int touch_offload_free_buffers(struct touch_offload_context *context)
+{
+	int freed = 0;
+	int chan = 0;
+
+	pr_debug("%s\n", __func__);
+
+	mutex_lock(&context->buffer_lock);
+
+	/* Ensure there is no outstanding reserved_frame before continuing */
+	while (context->reserved_frame != NULL) {
+		mutex_unlock(&context->buffer_lock);
+		wait_for_completion(&context->reserve_returned);
+		mutex_lock(&context->buffer_lock);
+	}
+
+	if (context->num_buffers > 0) {
+		while (!list_empty(&context->free_pool)) {
+			struct list_head *next = context->free_pool.next;
+			struct touch_offload_frame *frame =
+			    list_entry(next, struct touch_offload_frame, entry);
+
+			list_del(next);
+			for (chan = 0; chan < frame->num_channels; chan++)
+				kfree(frame->channel_data[chan]);
+			kfree(frame);
+			freed++;
+		}
+
+		while (!list_empty(&context->frame_queue)) {
+			struct list_head *next = context->frame_queue.next;
+			struct touch_offload_frame *frame =
+			    list_entry(next, struct touch_offload_frame, entry);
+
+			list_del(next);
+			for (chan = 0; chan < frame->num_channels; chan++)
+				kfree(frame->channel_data[chan]);
+			kfree(frame);
+			freed++;
+		}
+	}
+	if (freed != context->num_buffers)
+		pr_err("%s: mismatch between the number of buffers allocated(%d) and freed(%d)!",
+		       __func__, context->num_buffers, freed);
+
+	/* clean up */
+	context->num_buffers = 0;
+	context->reserved_frame = NULL;
+	INIT_LIST_HEAD(&context->free_pool);
+	INIT_LIST_HEAD(&context->frame_queue);
+	context->packed_frame_size = 0;
+
+	mutex_unlock(&context->buffer_lock);
+
+	return 0;
+}
+
+static long touch_offload_ioctl(struct file *file, unsigned int ioctl_num,
+				unsigned long ioctl_param)
+{
+	struct touch_offload_context *context = file->private_data;
+	unsigned long err = 0;
+
+	pr_debug("%s: ioctl_num=0x%08X, ioctl_param=0x%08lX\n", __func__,
+		 ioctl_num, ioctl_param);
+
+	switch (ioctl_num) {
+	case TOUCH_OFFLOAD_IOC_RD_GETCAPS:
+	{
+		struct TouchOffloadIocGetCaps getCaps;
+
+		/* Copy previously-populated caps */
+		memcpy(&getCaps.caps, &context->caps,
+		       sizeof(context->caps));
+
+		err = copy_to_user((void *)ioctl_param, &getCaps,
+				   sizeof(getCaps));
+		if (err != 0) {
+			pr_err("%s: copy_to_failed with err=0x%08lX",
+			       __func__, err);
+			return err;
+		}
+		break;
+	}
+
+	case TOUCH_OFFLOAD_IOC_WR_CONFIGURE:
+	{
+		struct TouchOffloadIocConfigure configure;
+		int num_channels;
+
+		err = copy_from_user(&configure, (void *)ioctl_param,
+				     sizeof(configure));
+		if (err != 0) {
+			pr_err("%s: copy_from_user failed with err=0x%08lX",
+			       __func__, err);
+			return err;
+		}
+
+		/* TODO: stop any active streaming */
+
+		/* Purge any previously-allocated buffers */
+		touch_offload_free_buffers(context);
+
+		memset(&context->config, 0, sizeof(context->config));
+		if ((configure.config.continuous_reporting &&
+		     !context->caps.continuous_reporting) ||
+		    (configure.config.noise_reporting &&
+		     !context->caps.noise_reporting) ||
+		    (configure.config.cancel_reporting &&
+		     !context->caps.cancel_reporting) ||
+		    (configure.config.filter_grip &&
+		     !context->caps.filter_grip) ||
+		    (configure.config.filter_palm &&
+		     !context->caps.filter_palm) ||
+		    (configure.config.auto_reporting &&
+		     !context->caps.auto_reporting) ||
+		    (configure.config.coord_filter &&
+		     !context->caps.coord_filter)) {
+			pr_err("%s: Invalid configuration enables unsupported features!\n",
+			       __func__);
+			err = -EINVAL;
+			return err;
+		} else if (configure.config.sensitivity_setting >=
+			   context->caps.num_sensitivity_settings) {
+			pr_err("%s: Invalid configuration enables unsupported sensitivity setting!\n",
+			       __func__);
+			err = -EINVAL;
+			return err;
+		} else if ((configure.config.mutual_data_types &
+			    ~context->caps.touch_data_types) != 0 ||
+			   (configure.config.self_data_types &
+			    ~context->caps.touch_data_types) != 0) {
+			pr_err("%s: Invalid configuration enables unsupported data types!\n",
+			       __func__);
+			err = -EINVAL;
+			return err;
+		} else if ((configure.config.context_channel_types &
+			    ~context->caps.context_channel_types) != 0) {
+			pr_err("%s: Invalid configuration enables unsupported context types!\n",
+			       __func__);
+			err = -EINVAL;
+			return err;
+		}
+
+		num_channels = (configure.config.read_coords ? 1 : 0) +
+			       hweight_long(
+				   configure.config.mutual_data_types) +
+			       hweight_long(
+				   configure.config.self_data_types) +
+			       hweight_long(
+				   configure.config.context_channel_types);
+		if (num_channels <= 0 || num_channels > MAX_CHANNELS) {
+			pr_err("%s: Invalid configuration enables more (%d) than %d channels!\n",
+			       __func__, num_channels, MAX_CHANNELS);
+			err = -EINVAL;
+			return err;
+		}
+
+		/* Copy sanitized config */
+		memcpy(&context->config, &configure.config,
+		       sizeof(context->config));
+
+		/* Allocate frames */
+		err = touch_offload_allocate_buffers(context, TOUCH_OFFLOAD_BUFFER_NUM);
+		if (err != 0) {
+			pr_err("%s: failed to allocate buffers. err = 0x%08X.\n",
+			       __func__, (unsigned int)err);
+			return err;
+		}
+
+		break;
+	}
+
+	case TOUCH_OFFLOAD_IOC_WR_REPORT:
+	{
+		struct TouchOffloadIocReport report;
+
+		err = copy_from_user(&report, (void *)ioctl_param,
+				     sizeof(report));
+		if (err != 0) {
+			pr_err("%s: copy_from_user failed with err=0x%08lx.\n",
+			       __func__, err);
+			return err;
+		}
+
+		context->report_cb(context->hcallback, &report);
+		break;
+	}
+
+	default:
+		return -EINVAL;
+	}
+
+	return err;
+}
+
+const struct file_operations touch_offload_fops = {
+	.owner	  = THIS_MODULE,
+	.open	  = touch_offload_open,
+	.release  = touch_offload_release,
+	.read	  = touch_offload_read,
+	.poll	  = touch_offload_poll,
+	.unlocked_ioctl	  = touch_offload_ioctl
+};
+
+int touch_offload_reserve_frame(struct touch_offload_context *context,
+				struct touch_offload_frame **frame)
+{
+	int ret = 0;
+
+	pr_debug("%s\n", __func__);
+
+	if (!context || !frame)
+		return -EINVAL;
+	*frame = NULL;
+
+	mutex_lock(&context->buffer_lock);
+
+	if (context->num_buffers == 0 || list_empty(&context->free_pool) ||
+	    context->reserved_frame != NULL) {
+		pr_debug("%s: buffer not available.\n", __func__);
+		ret = -EINVAL;
+	} else {
+		reinit_completion(&context->reserve_returned);
+		context->reserved_frame =
+			list_entry(context->free_pool.next,
+				   struct touch_offload_frame, entry);
+		list_del(&context->reserved_frame->entry);
+		*frame = context->reserved_frame;
+	}
+
+	mutex_unlock(&context->buffer_lock);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(touch_offload_reserve_frame);
+
+int touch_offload_queue_frame(struct touch_offload_context *context,
+			      struct touch_offload_frame *frame)
+{
+	int ret = 0;
+
+	pr_debug("%s\n", __func__);
+
+	if (!context || !frame)
+		return -EINVAL;
+
+	mutex_lock(&context->buffer_lock);
+
+	if (context->num_buffers == 0 || frame != context->reserved_frame) {
+		pr_err("%s: incorrect or NULL buffer submitted.\n", __func__);
+		ret = -EINVAL;
+	} else {
+		/* TODO: Restore important constant fields */
+
+		list_add_tail(&frame->entry, &context->frame_queue);
+		context->reserved_frame = NULL;
+		complete_all(&context->reserve_returned);
+
+		wake_up(&context->read_queue);
+	}
+
+	mutex_unlock(&context->buffer_lock);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(touch_offload_queue_frame);
+
+int touch_offload_init(struct touch_offload_context *context)
+{
+	int ret = 0;
+
+	/* Initialize ioctl interface */
+	context->file_in_use = false;
+	mutex_init(&context->file_lock);
+
+	/* Initialize the buffer pool */
+	context->num_buffers = 0;
+	context->reserved_frame = NULL;
+	INIT_LIST_HEAD(&context->free_pool);
+	INIT_LIST_HEAD(&context->frame_queue);
+	mutex_init(&context->buffer_lock);
+
+	init_waitqueue_head(&context->read_queue);
+
+	init_completion(&context->reserve_returned);
+	complete_all(&context->reserve_returned);
+
+	if (!strnlen(context->device_name, sizeof(context->device_name)))
+		scnprintf(context->device_name, sizeof(context->device_name), "%s", DEVICE_NAME);
+
+	pr_info("%s: %s.\n", __func__, context->device_name);
+
+	/* Initialize char device */
+	cdev_init(&context->dev, &touch_offload_fops);
+
+	ret = alloc_chrdev_region(&context->dev_num, 0, 1, context->device_name);
+	if (ret < 0) {
+		pr_err("%s: register_chrdev failed with error = %u\n",
+		       __func__, ret);
+		return ret;
+	}
+
+	ret = cdev_add(&context->dev, context->dev_num, 1);
+	if (ret < 0) {
+		pr_err("%s: cdev_add failed with error = %u\n",
+		        __func__, ret);
+		goto err_cdev_add;
+	}
+
+	context->cls = class_create(THIS_MODULE, context->device_name);
+	if (IS_ERR(context->cls)) {
+		pr_err("%s: class_create failed with error = %ld.\n",
+		       __func__, PTR_ERR(context->cls));
+		ret = PTR_ERR(context->cls);
+		goto err_class_create;
+	}
+
+	context->device = device_create(context->cls, NULL, context->dev_num,
+		NULL, context->device_name);
+	if (IS_ERR(context->device)) {
+		pr_err("%s: device_create failed with error = %ld.\n",
+		       __func__, PTR_ERR(context->device));
+		ret = PTR_ERR(context->device);
+		goto err_device_create;
+	}
+
+	return ret;
+
+err_device_create:
+	class_destroy(context->cls);
+err_class_create:
+	cdev_del(&context->dev);
+err_cdev_add:
+	unregister_chrdev_region(context->dev_num, 1);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(touch_offload_init);
+
+int touch_offload_cleanup(struct touch_offload_context *context)
+{
+	pr_debug("%s\n", __func__);
+
+	device_destroy(context->cls, context->dev_num);
+
+	class_destroy(context->cls);
+
+	cdev_del(&context->dev);
+
+	unregister_chrdev_region(context->dev_num, 1);
+
+	complete_all(&context->reserve_returned);
+
+	touch_offload_free_buffers(context);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(touch_offload_cleanup);
+
+MODULE_DESCRIPTION("Touch Offload to AP");
+MODULE_AUTHOR("Steve Pfetsch <spfetsch@google.com>");
+MODULE_LICENSE("GPL v2");
diff --git a/touch_offload.h b/touch_offload.h
new file mode 100644
index 0000000..bbd4f89
--- /dev/null
+++ b/touch_offload.h
@@ -0,0 +1,118 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef TOUCH_OFFLOAD_H
+#define TOUCH_OFFLOAD_H
+
+#include <linux/cdev.h>
+#include <linux/mutex.h>
+#include <linux/completion.h>
+
+#include "uapi/input/touch_offload.h"
+
+/* Maximum number of channels of touch data */
+#define MAX_CHANNELS 5
+#define TOUCH_OFFLOAD_BUFFER_NUM 6
+
+#define DEVICE_NAME "touch_offload"
+#define CLASS_NAME "touch_offload"
+
+/* Frame of touch data
+ *
+ * entry - list entry in either the free pool or the event queue
+ * header - frame header, including timestamp and index
+ * num_channels - number of channels in this frame
+ * channel_type - data type of each channel
+ * channel_data_size - size of the data in each channel
+ * channel_data - raw channel data
+ */
+struct touch_offload_frame {
+	struct list_head entry;
+	struct TouchOffloadFrameHeader header;
+	int num_channels;
+	int channel_type[MAX_CHANNELS];
+	__u32 channel_data_size[MAX_CHANNELS];
+	__u8 *channel_data[MAX_CHANNELS];
+};
+
+/* Touch Offload Context
+ *
+ * dev - char device
+ * dev_num - device number
+ * cls - pointer to class associated class
+ * device - pointer to associated device
+ * file - char device file for ioctl interface
+ * file_lock - mutex for the ioctl interface
+ * file_in_use - flag indicating the ioctl interface in use by one client
+ * caps - capabilities supported by the touch driver
+ * config - configuration in use by the touch driver
+ * coords - snapshot of the current coordinate state
+ * num_buffers - size of the pool of frame buffers
+ * free_pool - list of buffers available for use
+ * frame_queue - list of captured frames queued for the service
+ * reserved_frame - buffer ready to be filled with the next touch frame
+ * read_queue - waitqueue for blocked readers
+ * packed_frame - serialized frame being read by the char device client
+ * packed_frame_size - size of the array pointed to by packed_frame
+ * buffer_lock - mutex protecting buffer management
+ * reserve_returned - indicates that the reserved buffer was released
+ * hcallback - handle/pointer to driver's private callback context
+ * report_cb - driver callback used to report touch events
+ * offload_running - indicates whether the offload path is in use
+ */
+struct touch_offload_context {
+	/* ioctl interface */
+	struct cdev dev;
+	dev_t dev_num;
+	struct class *cls;
+	struct device *device;
+	struct file file;
+	struct mutex file_lock;
+	bool file_in_use;
+	bool multiple_panels;	/* TODO(b/201610482): remove this variable later! */
+	char device_name[32];
+
+	/* touch capabilities */
+	struct TouchOffloadCaps caps;
+
+	/* touch capture configuration */
+	struct TouchOffloadConfig config;
+
+	/* coordinate state */
+	struct TouchOffloadCoord coords[MAX_COORDS];
+
+	/* buffer management */
+	int num_buffers;
+	struct list_head free_pool;
+	struct list_head frame_queue;
+	struct touch_offload_frame *reserved_frame;
+	wait_queue_head_t read_queue;
+	u8 *prealloc_packed_frame;
+	__u32 prealloc_packed_frame_size;
+	u8 *packed_frame;
+	__u32 packed_frame_size;
+	struct mutex buffer_lock;
+	struct completion reserve_returned;
+
+	/* callbacks */
+	void *hcallback;
+	void (*report_cb)(void *hcallback,
+			  struct TouchOffloadIocReport *report);
+
+	int offload_running;
+};
+
+/* Initialize the touch_offload driver */
+int touch_offload_init(struct touch_offload_context *context);
+
+/* Clean-up the touch_offload driver */
+int touch_offload_cleanup(struct touch_offload_context *context);
+
+/* Allocate a new empty frame from the free pool */
+int touch_offload_reserve_frame(struct touch_offload_context *context,
+				struct touch_offload_frame **frame);
+
+/* Insert a populated frame into the queue */
+int touch_offload_queue_frame(struct touch_offload_context *context,
+			      struct touch_offload_frame *frame);
+
+#endif // TOUCH_OFFLOAD_H
diff --git a/usi/BUILD.bazel b/usi/BUILD.bazel
new file mode 100644
index 0000000..d77d847
--- /dev/null
+++ b/usi/BUILD.bazel
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+load("//build/kernel/kleaf:kernel.bzl", "kernel_module")
+
+filegroup(
+    name = "headers",
+    srcs = glob([
+        "**/*.h",
+    ]),
+    visibility = [
+        "//private/devices/google:__subpackages__",
+        "//private/google-modules/touch:__subpackages__",
+    ],
+)
+
+kernel_module(
+    name = "touch.common.usi",
+    srcs = glob([
+        "**/*.c",
+        "**/*.h",
+    ]) + [
+        "Kbuild",
+    ],
+    outs = [
+        "goog_usi_stylus.ko",
+    ],
+    kernel_build = "//private/devices/google/common:kernel",
+    visibility = [
+        "//private/devices/google:__subpackages__",
+        "//private/google-modules/touch:__subpackages__",
+    ],
+)
diff --git a/usi/Kbuild b/usi/Kbuild
new file mode 100644
index 0000000..37a381f
--- /dev/null
+++ b/usi/Kbuild
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0
+
+obj-$(CONFIG_GOOG_USI_STYLUS)		+= goog_usi_stylus.o
diff --git a/usi/Makefile b/usi/Makefile
new file mode 100644
index 0000000..2a6818a
--- /dev/null
+++ b/usi/Makefile
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+
+KERNEL_SRC ?= /lib/modules/$(shell uname -r)/build
+M ?= $(shell pwd)
+
+EXTRA_CFLAGS	+= -DDYNAMIC_DEBUG_MODULE
+
+modules modules_install clean:
+	$(MAKE) -C $(KERNEL_SRC) M=$(M) \
+	EXTRA_CFLAGS="$(EXTRA_CFLAGS)" $(@)
diff --git a/usi/goog_usi_stylus.c b/usi/goog_usi_stylus.c
new file mode 100644
index 0000000..7a6982f
--- /dev/null
+++ b/usi/goog_usi_stylus.c
@@ -0,0 +1,2728 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Google USI Stylus Support for Pixel devices.
+ *
+ * Copyright 2024 Google LLC.
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/hid.h>
+#include <linux/hidraw.h>
+#include <linux/input/mt.h>
+#include <linux/miscdevice.h>
+#include <linux/power_supply.h>
+#include <linux/slab.h>
+
+#include "goog_usi_stylus.h"
+
+#define G_USI_MAGIC				0x49535547 /* GUSI */
+
+#define G_USI_INPUT_NODE_NAME			"USI_Stylus"
+#define G_USI_INPUT_NODE_PHYS			"USI_Stylus/1" /* only one stylus is supported */
+#define G_USI_INPUT_NODE_VERSION		0x0100
+#define G_USI_BATTERY_NODE_NAME			"USI_Stylus_Battery"
+
+#define G_USI_SN_STR_LEN			17
+/* the length from USI spec */
+#define G_USI_GID_LEN				12
+#define G_USI_CAP_LEN				12
+#define G_USI_FW_VER_LEN			2
+#define G_USI_VENDOR_EXT_LEN			2
+#define G_USI_HASH_ID_LEN			2
+#define G_USI_SESSION_ID_LEN			2
+
+#undef pr_fmt
+#define pr_fmt(fmt)				"gtd: GUSI: " fmt
+#define G_USI_ERR(fmt, args...)			pr_err("%s: " fmt, __func__, ##args)
+#define G_USI_DBG(fmt, args...)			pr_debug("%s: " fmt, __func__, ##args)
+#define G_USI_LOG(fmt, args...)			pr_info("%s: " fmt, __func__, ##args)
+
+enum g_usi_op_status {
+	G_USI_OP_UNPAIRED	= 0,
+	G_USI_OP_PAIRED		= 1,
+
+	/*
+	 * The stylus is identified.
+	 *
+	 * HID Feature Reports can be supported only when the stylus is
+	 * identified
+	 */
+	G_USI_OP_IDENTIFIED	= 2
+};
+
+struct g_usi_header {
+	u32 magic;	/* magic number */
+	u32 version;	/* Google USI subsystem version */
+};
+
+struct g_usi_context {
+	struct g_usi_header hdr;
+
+	struct device *dev;			/* controller device */
+	struct g_usi_callbacks *cbs;
+	void *drvdata;
+
+	/* battery node */
+	char *battery_name;
+	struct power_supply_desc psy_desc;
+	struct power_supply_config psy_cfg;
+	struct power_supply *bat_psy;
+
+	/* input node */
+	struct input_dev *input_dev;
+	char *name;
+	char *phys;
+	struct input_id id;
+	int abs_x_max;
+	int abs_y_max;
+	int distance_max;       /* 0 means distance is not supported */
+	int tilt_min;
+	int tilt_max;           /* 0 means tilt is not supported */
+
+	/* USI Stylus Information */
+	u32 stylus_info_flags; /* bitmap for information availability */
+
+	/* Information collected from a paired stylus. */
+	u8 stylus_capability[G_USI_CAP_LEN];		/* C.GetCapability() */
+	u8 stylus_GID[G_USI_GID_LEN];			/* C.GetGID() */
+	u8 stylus_fw_ver[G_USI_FW_VER_LEN];		/* C.GetFirmwareVersion() */
+	u8 stylus_usi_ver;				/* C.GetUsiVersion() */
+	u8 stylus_vendor_ext[G_USI_VENDOR_EXT_LEN];	/* C.GetVendorExtension() */
+	u8 stylus_battery;				/* C.GetBattery() */
+
+	/* Pairing information which can be used to restore the controller during resume process */
+	struct g_usi_pairing_info pairing_info;
+
+	/* 64-bit serial number */
+	u32 stylus_sn_low;
+	u32 stylus_sn_high;
+
+	/*
+	 * When a user asks a diagnose, there should be both HID SET DIAGNOSE and HID GET DIAGNOSE.
+	 * During the HID SET DIAGNOSE, we don't actually send the beacon command. Instead,
+	 * we keep the command. Later, when there's HID GET DIAGNOSE request, we send the beacon
+	 * command and get the response
+	 */
+	bool is_diagnose_requested;	/* set true on SET request and set false on GET request */
+	u8 diagnose_uplink[5];
+
+	bool create_new_input_dev_flag; /*
+					 * If the vid/pid of the current stylus is different from
+					 * the previous one. We notify that by creating new input
+					 * event node with the new vid/pid.
+					 */
+	bool recreate_evdev_enabled;	/* recreate input event node is enabled ? */
+
+	bool is_flex_beacon;		/* true: flex beacon, false: standard beacon */
+	enum g_usi_op_status status;	/* pen operation status */
+	struct miscdevice g_usi_hidraw_dev; /* device for users to do HID SET/GET feature report */
+
+	struct mutex lock;		/* usi context lock */
+};
+
+#define handle_to_context(_handle)		((struct g_usi_context *)_handle)
+#define context_to_handle(_ctx)			((g_usi_handle_t)_ctx)
+
+/* check if the usi_ctx is valid or not */
+static inline bool g_usi_is_valid_context(struct g_usi_context *usi_ctx)
+{
+	if (!usi_ctx)
+		return false;
+
+	if (usi_ctx->hdr.magic != G_USI_MAGIC)
+		return false;
+
+	return true;
+}
+
+static inline void set_gid_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_GID_FLAG;
+}
+
+static inline bool is_gid_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_GID_FLAG;
+}
+
+static inline void set_battery_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_BATTERY_FLAG;
+}
+
+static inline bool is_battery_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_BATTERY_FLAG;
+}
+
+static inline void set_capability_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_CAPABILITY_FLAG;
+}
+
+static inline bool is_capability_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_CAPABILITY_FLAG;
+}
+
+static inline bool is_preferred_color_read_only(const struct g_usi_context *usi_ctx)
+{
+	return !!(usi_ctx->stylus_capability[0] & 0x20); /* preferred color is RO ? */
+}
+
+static inline bool is_preferred_width_read_only(const struct g_usi_context *usi_ctx)
+{
+	return !!(usi_ctx->stylus_capability[0] & 0x80); /* preferred width is RO ? */
+}
+
+static inline bool is_preferred_style_read_only(const struct g_usi_context *usi_ctx)
+{
+	return !!(usi_ctx->stylus_capability[0] & 0x40); /* preferred style is RO ? */
+}
+
+static inline bool is_true_color_supported(const struct g_usi_context *usi_ctx)
+{
+	return !!(usi_ctx->stylus_capability[5] & 0x04); /* support true color ? */
+}
+
+static inline void set_fw_version_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_FW_VERSION_FLAG;
+}
+
+static inline bool is_fw_version_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_FW_VERSION_FLAG;
+}
+
+static inline void set_usi_version_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_USI_VERSION_FLAG;
+}
+
+static inline bool is_usi_version_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_USI_VERSION_FLAG;
+}
+
+static inline void set_vendor_ext_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_VENDOR_EXT_FLAG;
+}
+
+static inline bool is_vendor_ext_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_VENDOR_EXT_FLAG;
+}
+
+static inline void set_pairing_info_available(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags |= G_USI_PAIRING_INFO_FLAG;
+}
+
+static inline bool is_pairing_info_available(const struct g_usi_context *usi_ctx)
+{
+	return usi_ctx->stylus_info_flags & G_USI_PAIRING_INFO_FLAG;
+}
+
+static inline void clear_stylus_info_flags(struct g_usi_context *usi_ctx)
+{
+	usi_ctx->stylus_info_flags = 0; /* clear stylus info for the new stylus */
+}
+
+/**
+ * goog_usi_report_gid() - reports GID to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @gid: 12 bytes GID from the stylus via C.GetGID()
+ *
+ * The USI controller must collect the GID of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the GID maintined in the subsystem.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_gid(g_usi_handle_t handle, const u8 *gid)
+{
+	u32 sn_high, sn_low;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+	u16 vid, pid;
+
+	if (!gid || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	memcpy(usi_ctx->stylus_GID, gid, sizeof(usi_ctx->stylus_GID));
+	sn_low = gid[0] | gid[1] << 8 | gid[2] << 16 | gid[3] << 24;
+	sn_high = gid[4] | gid[5] << 8 | gid[6] << 16 | gid[7] << 24;
+	if (usi_ctx->stylus_sn_low != sn_low || usi_ctx->stylus_sn_high != sn_high) {
+		usi_ctx->stylus_sn_low = sn_low;
+		usi_ctx->stylus_sn_high = sn_high;
+
+		/* notify serial number updated */
+		power_supply_changed(usi_ctx->bat_psy);
+	}
+
+	vid = gid[8] | gid[9] << 8;
+	pid = gid[10] | gid[11] << 8;
+	if (usi_ctx->id.vendor != vid || usi_ctx->id.product != pid) { /* is new stylus ? */
+		G_USI_LOG("Old(vid: 0x%04x, pid: 0x%04x) -> New(vid: 0x%04x, pid: 0x%04x)",
+			  usi_ctx->id.vendor, usi_ctx->id.product, vid, pid);
+
+		usi_ctx->id.vendor = vid;
+		usi_ctx->id.product = pid;
+
+		/* create new input node when the new stylus is unpaired */
+		if (usi_ctx->recreate_evdev_enabled)
+			usi_ctx->create_new_input_dev_flag = true;
+	}
+
+	usi_ctx->status = G_USI_OP_IDENTIFIED; /* Parsing GID is done. The stylus is identified */
+	set_gid_available(usi_ctx);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_gid);
+
+/**
+ * goog_usi_report_fw_version() - reports FW version to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @fw_ver: 2 bytes FW version from the stylus via C.GetFirmwareVersion()
+ *
+ * The USI controller must collect the FW version of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the FW version maintined in the subsystem.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_fw_version(g_usi_handle_t handle, const u8 *fw_ver)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!fw_ver || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	memcpy(usi_ctx->stylus_fw_ver, fw_ver, sizeof(usi_ctx->stylus_fw_ver));
+	set_fw_version_available(usi_ctx);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_fw_version);
+
+/**
+ * goog_usi_get_fw_version() - Get the FW version stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @fw_ver: 2 bytes FW version(Major, Minor)
+ *
+ * Return: 0 on success and @fw_ver has the major and minor version, non-zero on failure
+ */
+int goog_usi_get_fw_version(g_usi_handle_t handle, u8 *fw_ver)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!fw_ver || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_fw_version_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	memcpy(fw_ver, usi_ctx->stylus_fw_ver, sizeof(usi_ctx->stylus_fw_ver));
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_fw_version);
+
+/**
+ * goog_usi_report_usi_version() - report USI version to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @usi_ver: 8 bits USI version(4bits Major, 4bits Minor) from the stylus via C.GetUsiVersion()
+ *
+ * The USI controller may collect the USI version of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the USI version maintined in the subsystem.
+ *
+ * Note: The USI controller may not collect the USI version from the stylus. In that case,
+ * still the vendor driver should report the usi version which may be hard-coded.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_usi_version(g_usi_handle_t handle, const u8 *usi_ver)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!usi_ver || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameter");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	usi_ctx->stylus_usi_ver = *usi_ver;
+	set_usi_version_available(usi_ctx);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_usi_version);
+
+/**
+ * goog_usi_get_usi_version() - Get the USI version stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @usi_ver: 8 bits USI version(4bits Major, 4bits Minor)
+ *
+ * Return: 0 on success and @usi_ver has the USI version, non-zero on failure
+ */
+int goog_usi_get_usi_version(g_usi_handle_t handle, u8 *usi_ver)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!usi_ver || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_usi_version_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	*usi_ver = usi_ctx->stylus_usi_ver;
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_usi_version);
+
+/**
+ * goog_usi_report_vendor_extension() - reports vendor_extension to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @fw_version: 2 bytes vendor extension from the stylus via C.GetVendorExtension()
+ *
+ * The USI controller must retrieve the FW version of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the FW version maintined in the subsystem.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_vendor_extension(g_usi_handle_t handle, const u8 *vendor_ext)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!vendor_ext || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+	memcpy(usi_ctx->stylus_vendor_ext, vendor_ext, sizeof(usi_ctx->stylus_vendor_ext));
+	set_vendor_ext_available(usi_ctx);
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_vendor_extension);
+
+/**
+ * goog_usi_get_vendor_extension() - Get the vendor extension stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @vendor_ext: 2 bytes vendor extension
+ *
+ *
+ * Return: 0 on success and @vendor_Ext has the vendor extension, non-zero on failure
+ */
+int goog_usi_get_vendor_extension(g_usi_handle_t handle, u8 *vendor_ext)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!vendor_ext || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_vendor_ext_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	memcpy(vendor_ext, usi_ctx->stylus_vendor_ext, sizeof(usi_ctx->stylus_vendor_ext));
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_vendor_extension);
+
+/**
+ * goog_usi_report_capability() - reports capability to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @gid: 12 bytes capability from the stylus via C.GetCapability()
+ *
+ * The USI controller must collect the capability of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the capability maintined in the subsystem.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_capability(g_usi_handle_t handle, const u8 *cap)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!cap || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	memcpy(usi_ctx->stylus_capability, cap, sizeof(usi_ctx->stylus_capability));
+	set_capability_available(usi_ctx);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_capability);
+
+/**
+ * goog_usi_set_fw_version() - reports the battery level to the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @bat: 1 bytes battery level from the stylus via C.GetBattery()
+ *
+ * The USI controller must retrieve the battery level of the paired stylus and reports
+ * it to the host. The host(vendor driver) should call this function to update
+ * the battery level maintined in the subsystem.
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_report_battery(g_usi_handle_t handle, const u8 *bat)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!bat || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (usi_ctx->stylus_battery != bat[0]) {
+		usi_ctx->stylus_battery = bat[0];
+
+		/* notify new battery level received */
+		power_supply_changed(usi_ctx->bat_psy);
+	}
+	set_battery_available(usi_ctx);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_report_battery);
+
+/**
+ * goog_usi_get_battery() - Get the battery level stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @bat: 1 byte battery level
+ *
+ *
+ * Return: 0 on success and @bat has the battery level, non-zero on failure
+ */
+int goog_usi_get_battery(g_usi_handle_t handle, u8 *bat)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!bat || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_battery_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	*bat = usi_ctx->stylus_battery;
+
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_battery);
+
+/**
+ * goog_usi_get_serial_number() - Get the serial number stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @sn_high: upper 16 bits of the serial number
+ * @sn_low: lower 16 bits of the serial number
+ *
+ * Return: 0 on success and @sn_high and @sn_low has the 64 bits serial number, non-zero on failure
+ */
+int goog_usi_get_serial_number(g_usi_handle_t handle, u32 *sn_high, u32 *sn_low)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if ((!sn_high && !sn_low) || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_gid_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	if (sn_high)
+		*sn_high = usi_ctx->stylus_sn_high;
+	if (sn_low)
+		*sn_low = usi_ctx->stylus_sn_low;
+
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_serial_number);
+
+/**
+ * goog_usi_get_serial_number_str() - Get the serial number in string stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @sn_high: upper 16 bits of the serial number
+ * @sn_low: lower 16 bits of the serial number
+ *
+ * Return: 0 on success and @sn_high and @sn_low has the 64 bits serial number, non-zero on failure
+ */
+int goog_usi_get_serial_number_str(g_usi_handle_t handle, char *buf, int buf_size)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!buf || buf_size < G_USI_SN_STR_LEN || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_gid_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	sprintf(buf, "%08X%08X", usi_ctx->stylus_sn_high, usi_ctx->stylus_sn_low);
+
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_serial_number_str);
+
+/**
+ * goog_usi_get_vid_pid() - Get the vendor ID and product ID stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @vid: 16 bits vendor ID
+ * @pid: 16 bits product ID
+ *
+ * Return: 0 on success and @vid has a vendor ID and @pid has a product ID, non-zero on failure
+ */
+int goog_usi_get_vid_pid(g_usi_handle_t handle, u16 *vid, u16 *pid)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if ((!vid && !pid) || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_gid_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	if (vid)
+		*vid = usi_ctx->stylus_GID[8] | usi_ctx->stylus_GID[9] << 8;
+	if (pid)
+		*pid = usi_ctx->stylus_GID[10] | usi_ctx->stylus_GID[11] << 8;
+
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_vid_pid);
+
+/**
+ * goog_usi_update_status() - update the status of the stylus in use
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @type: &enum G_USI_STATUS
+ * @data: additional data to support the specified @type
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_update_status(g_usi_handle_t handle, int type, void *data)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+	struct g_usi_pairing_info *pairing_info = NULL;
+	int ret = 0;
+
+	if (!g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	switch (type) {
+	case G_USI_UPDATE_NORMAL_PAIRING_DONE:
+		if (!data) {
+			ret = -EINVAL;
+			break;
+		}
+
+		/*
+		 * Sometimes, even for the stylus recently paired, there can be normal pairing
+		 * instead of fast pairing. In this case, the driver needs to compare the HASH ID
+		 * to check if it's the recently paired stylus. If it is then
+		 * the driver re-use the existing information.
+		 */
+		pairing_info = (struct g_usi_pairing_info *)data;
+		if (usi_ctx->pairing_info.hash_id[0] != pairing_info->hash_id[0] ||
+		    usi_ctx->pairing_info.hash_id[1] != pairing_info->hash_id[1]) {
+			clear_stylus_info_flags(usi_ctx);/* clear stylus info for the new stylus */
+
+			/* save pairing information for the new stylus */
+			memcpy(&usi_ctx->pairing_info, pairing_info, sizeof(*pairing_info));
+
+			set_pairing_info_available(usi_ctx);
+			G_USI_LOG("Normal Pairing: new pen");
+		} else if (is_gid_available(usi_ctx)) {
+			G_USI_LOG("Normal Pairing: same pen");
+			usi_ctx->status = G_USI_OP_IDENTIFIED;
+		}
+
+		break;
+	case G_USI_UPDATE_FAST_PAIRING_DONE:
+		G_USI_LOG("Fast Pairing : 0x%08x", usi_ctx->stylus_info_flags);
+		if (is_gid_available(usi_ctx))
+			usi_ctx->status = G_USI_OP_IDENTIFIED;
+		break;
+	case G_USI_UPDATE_CRC_FAILURE:
+		break;
+	}
+
+	mutex_unlock(&usi_ctx->lock);
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_update_status);
+
+/**
+ * goog_usi_get_pairing_info() - get pairing information stored in the subsystem
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @pairing_info: &struct g_usi_pairing_info
+ *
+ * Return: 0 on success, non-zero on failure
+ */
+int goog_usi_get_pairing_info(g_usi_handle_t handle, struct g_usi_pairing_info *pairing_info)
+{
+	int ret = 0;
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!pairing_info || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	if (!is_pairing_info_available(usi_ctx)) {
+		ret = -ENODATA;
+		goto error_ret;
+	}
+
+	memcpy(pairing_info, &usi_ctx->pairing_info, sizeof(*pairing_info));
+
+error_ret:
+	mutex_unlock(&usi_ctx->lock);
+	return ret;
+}
+EXPORT_SYMBOL(goog_usi_get_pairing_info);
+
+/* USI Battery Information is exposed via Power Supply Subsystem */
+static enum power_supply_property stylus_battery_props[] = {
+	POWER_SUPPLY_PROP_PRESENT,
+	POWER_SUPPLY_PROP_CAPACITY,
+	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
+	POWER_SUPPLY_PROP_SERIAL_NUMBER,
+	POWER_SUPPLY_PROP_STATUS,
+	POWER_SUPPLY_PROP_SCOPE,
+};
+
+static int stylus_get_battery_property(struct power_supply *psy,
+				       enum power_supply_property prop,
+				       union power_supply_propval *val)
+{
+	int low_bat_flag, capacity;
+	struct g_usi_context *usi_ctx = (struct g_usi_context *)power_supply_get_drvdata(psy);
+	u8 battery = 0;
+	static u8 battery_sn_str[G_USI_SN_STR_LEN]; /* 64bit(16 nibbles) serial number */
+
+	if (goog_usi_get_battery(context_to_handle(usi_ctx), &battery))
+		return -EINVAL;
+
+	low_bat_flag = battery & 0x80;
+	capacity = battery & 0x7f;
+
+	switch (prop) {
+	case POWER_SUPPLY_PROP_PRESENT:
+		val->intval = 1;
+		break;
+
+	case POWER_SUPPLY_PROP_CAPACITY:
+		/* stylus doesn't support fuel gauge */
+		if (capacity == 127) {
+			if (low_bat_flag) /* low battery flag */
+				val->intval = 1;
+			else /* no low battery flag */
+				val->intval = 100;
+		} else { /* 1 ~ 100 */
+			val->intval = capacity;
+		}
+		break;
+
+	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
+		/* battery capacity is never updated */
+		if (capacity == 0) {
+			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
+			break;
+		}
+
+		if (low_bat_flag)
+			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
+		else if (capacity != 100) /* 127, 1 ~ 99 */
+			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
+		else /* 100 */
+			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
+
+		break;
+
+	case POWER_SUPPLY_PROP_SERIAL_NUMBER:
+		/* the latest serial number */
+		if (goog_usi_get_serial_number_str(context_to_handle(usi_ctx),
+						   battery_sn_str, sizeof(battery_sn_str))) {
+			return -ENODATA;
+		}
+		val->strval = battery_sn_str;
+		break;
+
+	case POWER_SUPPLY_PROP_STATUS:
+		val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
+		break;
+
+	case POWER_SUPPLY_PROP_SCOPE:
+		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
+		break;
+
+	default:
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+static struct input_dev *g_usi_register_input(struct g_usi_context *usi_ctx)
+{
+	struct input_dev *in_dev;
+	int ret = -1;
+
+	in_dev = input_allocate_device();
+	if (!in_dev)
+		return NULL;
+
+	in_dev->evbit[0] = BIT_MASK(EV_SYN) | BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
+	in_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
+	in_dev->keybit[BIT_WORD(BTN_TOOL_PEN)] |= BIT_MASK(BTN_TOOL_PEN);
+	in_dev->keybit[BIT_WORD(BTN_TOOL_RUBBER)] |= BIT_MASK(BTN_TOOL_RUBBER);
+	in_dev->keybit[BIT_WORD(BTN_STYLUS)] |= BIT_MASK(BTN_STYLUS);
+	in_dev->keybit[BIT_WORD(BTN_STYLUS2)] |= BIT_MASK(BTN_STYLUS2);
+	in_dev->propbit[0] = BIT(INPUT_PROP_DIRECT);
+
+	input_set_abs_params(in_dev, ABS_X, 0, usi_ctx->abs_x_max, 0, 0);
+	input_set_abs_params(in_dev, ABS_Y, 0, usi_ctx->abs_y_max, 0, 0);
+	input_set_abs_params(in_dev, ABS_PRESSURE, 0, 4095, 0, 0); /* USI spec */
+	if (usi_ctx->distance_max)	/* if the controller supports distance */
+		input_set_abs_params(in_dev, ABS_DISTANCE, 0, usi_ctx->distance_max, 0, 0);
+	if (usi_ctx->tilt_max) {	/* if the controller supports tilt */
+		input_set_abs_params(in_dev, ABS_TILT_X,
+				     usi_ctx->tilt_min, usi_ctx->tilt_max, 0, 0);
+		input_set_abs_params(in_dev, ABS_TILT_Y,
+				     usi_ctx->tilt_min, usi_ctx->tilt_max, 0, 0);
+	}
+
+	__set_bit(EV_MSC, in_dev->evbit);
+	__set_bit(MSC_SERIAL, in_dev->mscbit);
+
+	in_dev->name = usi_ctx->name;
+	in_dev->uniq = usi_ctx->name;
+	in_dev->phys = usi_ctx->phys;
+	in_dev->dev.parent = usi_ctx->dev;
+	memcpy(&in_dev->id, &usi_ctx->id, sizeof(in_dev->id));
+
+	ret = input_register_device(in_dev);
+	if (ret) {
+		goto input_register_device_error;
+		return NULL;
+	}
+
+	return in_dev;
+
+input_register_device_error:
+	input_free_device(in_dev);
+	return NULL;
+}
+
+static void g_usi_unregister_input(struct input_dev *in_dev)
+{
+	input_unregister_device(in_dev);
+}
+
+/**
+ * goog_usi_get_stylus_info_flags() - Get the bitmap of the available stylus information
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @info_flags: bitmap of &enum G_USI_STYLUS_INFO. each bit represents if the subsysetm
+ *            maintains the corresponding stylus information
+ *
+ * Return: 0 on success and @info_flags has the bitmap of available stylus information,
+ *         non-zero on failure
+ */
+int goog_usi_get_stylus_info_flags(g_usi_handle_t handle, u32 *info_flags)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!info_flags || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	*info_flags = usi_ctx->stylus_info_flags;
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_get_stylus_info_flags);
+
+/**
+ * goog_usi_send_event() - send a USI motion event
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @usi_event: the &struct g_usi_event contains a motion data
+ *
+ * Resturn: 0 on success, non-zero on error
+ */
+int goog_usi_send_event(g_usi_handle_t handle, struct g_usi_event *usi_event)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!usi_event || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	input_set_timestamp(usi_ctx->input_dev, usi_event->timestamp);
+	input_report_abs(usi_ctx->input_dev, ABS_X, usi_event->x);
+	input_report_abs(usi_ctx->input_dev, ABS_Y, usi_event->y);
+	input_report_abs(usi_ctx->input_dev, ABS_PRESSURE, usi_event->pressure);
+	input_report_key(usi_ctx->input_dev, BTN_TOUCH, !!usi_event->pressure);
+	if (usi_ctx->tilt_max) {
+		input_report_abs(usi_ctx->input_dev, ABS_TILT_X, usi_event->tilt_x);
+		input_report_abs(usi_ctx->input_dev, ABS_TILT_Y, usi_event->tilt_y);
+	}
+	if (usi_ctx->distance_max)
+		input_report_abs(usi_ctx->input_dev, ABS_DISTANCE, usi_event->distance);
+	input_report_key(usi_ctx->input_dev, BTN_TOOL_PEN, 1);
+	input_report_key(usi_ctx->input_dev, BTN_STYLUS, usi_event->buttons & 1);
+	input_report_key(usi_ctx->input_dev, BTN_STYLUS2, (usi_event->buttons >> 1) & 1);
+	input_report_key(usi_ctx->input_dev, BTN_TOOL_RUBBER, (usi_event->buttons >> 2) & 1);
+
+	/*
+	 * Input Subsystem doesn't support 64bits serial number.
+	 * So we only reports the lower 32bit.
+	 */
+	if (is_gid_available(usi_ctx))
+		input_event(usi_ctx->input_dev, EV_MSC, MSC_SERIAL, usi_ctx->stylus_sn_low);
+
+	if (usi_ctx->status == G_USI_OP_UNPAIRED) {
+		G_USI_LOG("USI Paired");
+		usi_ctx->status = G_USI_OP_PAIRED;
+	}
+
+	input_sync(usi_ctx->input_dev);
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_send_event);
+
+/**
+ * goog_usi_send_event_leave() - send a USI motion leave event
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @usi_event_leave: the &struct g_usi_event_leave contains a motion data
+ *
+ * The vendor driver calls when the controller reports stylus is unpaired
+ *
+ * Resturn: 0 on success, non-zero on error
+ */
+int goog_usi_send_event_leave(g_usi_handle_t handle, struct g_usi_event_leave *usi_event_leave)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+	struct input_dev *new_input_dev = NULL;
+
+	if (!usi_event_leave || !g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	input_set_timestamp(usi_ctx->input_dev, usi_event_leave->timestamp);
+	input_report_abs(usi_ctx->input_dev, ABS_PRESSURE, 0);
+	input_report_key(usi_ctx->input_dev, BTN_TOUCH, 0);
+	input_report_key(usi_ctx->input_dev, BTN_TOOL_PEN, 0);
+	input_report_key(usi_ctx->input_dev, BTN_STYLUS, 0);
+	input_report_key(usi_ctx->input_dev, BTN_STYLUS2, 0);
+	input_report_key(usi_ctx->input_dev, BTN_TOOL_RUBBER, 0);
+
+	/*
+	 * Input Subsystem doesn't support 64bits serial number.
+	 * So we only reports the lower 32bit.
+	 */
+	if (is_gid_available(usi_ctx))
+		input_event(usi_ctx->input_dev, EV_MSC, MSC_SERIAL, usi_ctx->stylus_sn_low);
+
+	usi_ctx->status = G_USI_OP_UNPAIRED;
+	G_USI_LOG("USI Unpaired");
+
+	input_sync(usi_ctx->input_dev);
+
+	/* we got GIDs with new VID/PID pair */
+	if (usi_ctx->create_new_input_dev_flag) {
+		/* create new input device with the new VID/PID pair */
+		new_input_dev = g_usi_register_input(usi_ctx);
+		if (new_input_dev) {
+			g_usi_unregister_input(usi_ctx->input_dev);
+			usi_ctx->input_dev = new_input_dev;
+		}
+
+		usi_ctx->create_new_input_dev_flag = false;
+	}
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_send_event_leave);
+
+/**
+ * goog_usi_set_drvdata() - set the vendor-specific data
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ * @data: pointer to vendor-specific data
+ *
+ * Return: 0 on success, non-zere on failure
+ */
+int goog_usi_set_drvdata(g_usi_handle_t handle, void *data)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	usi_ctx->drvdata = data;
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_set_drvdata);
+
+/**
+ * goog_usi_set_drvdata() - get the vendor-specific data
+ *
+ * @handle: handle(&typedef g_usi_handle_t) to the registered USI controller
+ *
+ * Return: Return 0 on success and @data contains the value, Non-zero on failure
+ */
+int goog_usi_get_drvdata(g_usi_handle_t handle, void **data)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return -EINVAL;
+	}
+
+	*data = usi_ctx->drvdata;
+
+	return 0;
+}
+EXPORT_SYMBOL(goog_usi_get_drvdata);
+
+/*
+ * Here, we only support HID GET/SET Feature Report via ioctl interface.
+ *
+ * We don't use HID core subsystem since the subsystem will automatically create
+ * input devices based on HID Input Descriptor.
+ */
+/*
+ * The following HID Report Descriptor is copied from
+ * USIv2-HID-Report-Descriptor.h from universalstylus.org.
+ *
+ * Only GET/SET Feature Report are used. Input Report is NOT used.
+ */
+#define PHYSICAL_WIDTH				23585
+#define LOGICAL_WIDTH				3200
+#define PHYSICAL_HEIGHT				14740
+#define LOGICAL_HEIGHT				5120
+
+#define MAX_SUPPORTED_STYLI			1
+
+/* Change these to your preferred values. */
+#define	HID_REPORTID_TABLET			8
+#define	HID_REPORTID_ERROR			10
+#define	HID_REPORTID_GETSET_COLOR8		11
+#define	HID_REPORTID_GETSET_WIDTH		12
+#define	HID_REPORTID_GETSET_STYLE		13
+#define	HID_REPORTID_DIAGNOSE			14
+#define	HID_REPORTID_GETSET_BUTTONS		15
+#define	HID_REPORTID_GET_FIRMWARE		16
+#define	HID_REPORTID_GET_PROTOCOL		17
+#define	HID_REPORTID_GETSET_VENDOR		18
+#define	HID_REPORTID_SET_TRANSDUCER		19
+#define	HID_REPORTID_GETSET_COLOR24		20
+
+/* Convenience defines */
+#define	TABLET_TIP				(1 << 0)
+#define	TABLET_BARREL				(1 << 1)
+#define	TABLET_SECONDARYBARREL			(1 << 2)
+#define	TABLET_INVERT				(1 << 3)
+#define	TABLET_ERASER				(1 << 4)
+#define	TABLET_INRANGE				(1 << 5)
+
+#define LOW_BYTE(x)				((x) & 0xFF)
+#define HIGH_BYTE(x)				(((x) >> 8) & 0xFF)
+
+/* 7.4 HID Descriptor for a Data Report */
+static u8 USI_report_descriptor_v2_0[] = {
+    0x05, 0x0d,                    // USAGE_PAGE (Digitizers)
+    0x09, 0x02,                    // USAGE (Pen)
+    0xa1, 0x01,                    // COLLECTION (Application)
+    0x09, 0x20,                    //   USAGE (Stylus)
+    0xa1, 0x00,                    //   COLLECTION (Physical)
+    0x85, HID_REPORTID_TABLET,     //     REPORT_ID (HID_REPORTID_TABLET)
+    0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
+    0xa4,                          //     PUSH
+    0x09, 0x30,                    //     USAGE (X)
+    0x35, 0x00,                    //     PHYSICAL_MINIMUM (0)
+    0x47, LOW_BYTE(PHYSICAL_WIDTH), HIGH_BYTE(PHYSICAL_WIDTH), 0x00, 0x00,  // PHYSICAL_MAXIMUM (PHYSICAL_WIDTH)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x27, LOW_BYTE(LOGICAL_WIDTH), HIGH_BYTE(LOGICAL_WIDTH), 0x00, 0x00,    // LOGICAL_MAXIMUM (LOGICAL_WIDTH)
+    0x55, 0x0d,                    //     UNIT_EXPONENT (-3)
+    0x65, 0x11,                    //     UNIT (Centimeter,SILinear)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x31,                    //     USAGE (Y)
+    0x47, LOW_BYTE(PHYSICAL_HEIGHT), HIGH_BYTE(PHYSICAL_HEIGHT), 0x00, 0x00, // PHYSICAL_MAXIMUM (PHYSICAL_HEIGT)
+    0x27, LOW_BYTE(LOGICAL_HEIGHT), HIGH_BYTE(LOGICAL_HEIGHT), 0x00, 0x00,   // LOGICAL_MAXIMUM (LOGICAL_HEIGT)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0xb4,                          //     POP
+    0x05, 0x0d,                    //     USAGE_PAGE (Digitizers)
+    0x09, 0x38,                    //     USAGE (Transducer Index)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //     LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x30,                    //     USAGE (Tip Pressure)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x26, 0xff, 0x0f,              //     LOGICAL_MAXIMUM (4095)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x31,                    //     USAGE (Barrel Pressure)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x42,                    //     USAGE (Tip Switch)
+    0x09, 0x44,                    //     USAGE (Barrel Switch)
+    0x09, 0x5a,                    //     USAGE (Secondary Barrel Switch)
+    0x09, 0x3c,                    //     USAGE (Invert)
+    0x09, 0x45,                    //     USAGE (Eraser)
+    0x09, 0x32,                    //     USAGE (In Range)
+    0x75, 0x01,                    //     REPORT_SIZE (1)
+    0x95, 0x06,                    //     REPORT_COUNT (6)
+    0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x95, 0x02,                    //     REPORT_COUNT (2)
+    0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)
+    0x09, 0x3d,                    //     USAGE (X Tilt)
+    0x55, 0x0e,                    //     UNIT_EXPONENT (-2)
+    0x65, 0x14,                    //     UNIT (Eng Rot:Angular Pos)
+    0x36, 0xd8, 0xdc,              //     PHYSICAL_MINIMUM (-9000)
+    0x46, 0x28, 0x23,              //     PHYSICAL_MAXIMUM (9000)
+    0x16, 0xd8, 0xdc,              //     LOGICAL_MINIMUM (-9000)
+    0x26, 0x28, 0x23,              //     LOGICAL_MAXIMUM (9000)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x3e,                    //     USAGE (Y Tilt)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x41,                    //     USAGE (Twist)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x27, 0xa0, 0x8c, 0x00, 0x00,  //     LOGICAL_MAXIMUM (36000)
+    0x35, 0x00,                    //     PHYSICAL_MINIMUM (0)
+    0x47, 0xa0, 0x8c, 0x00, 0x00,  //     PHYSICAL_MAXIMUM (36000)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x05, 0x20,                    //     USAGE_PAGE (Sensors)
+    0x0a, 0x53, 0x04,              //     USAGE (Data Field: Acceleration Axis X)
+    0x65, 0x00,                    //     UNIT (None)
+    0x16, 0x01, 0xf8,              //     LOGICAL_MINIMUM (-2047)
+    0x26, 0xff, 0x07,              //     LOGICAL_MAXIMUM (2047)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x54, 0x04,              //     USAGE (Data Field: Acceleration Axis Y)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x55, 0x04,              //     USAGE (Data Field: Acceleration Axis Z)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x57, 0x04,              //     USAGE (Data Field: Angular Velocity Axis X)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x58, 0x04,              //     USAGE (Data Field: Angular Velocity Axis Y)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x59, 0x04,              //     USAGE (Data Field: Angular Velocity Axis Z)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x72, 0x04,              //     USAGE (Data Field: Heading X Axis)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x73, 0x04,              //     USAGE (Data Field: Heading Y Axis)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x0a, 0x74, 0x04,              //     USAGE (Data Field: Heading Z Axis)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x05, 0x0d,                    //     USAGE_PAGE (Digitizers)
+    0x09, 0x3b,                    //     USAGE (Battery Strength)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x25, 0x64,                    //     LOGICAL_MAXIMUM (100)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x5b,                    //     USAGE (Transducer Serial Number)
+    0x17, 0x00, 0x00, 0x00, 0x80,  //     LOGICAL_MINIMUM(-2,147,483,648)
+    0x27, 0xFF, 0xFF, 0xFF, 0x7F,  //     LOGICAL_MAXIMUM(2,147,483,647)
+    0x75, 0x40,                    //     REPORT_SIZE (64)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x6E,                    //     USAGE(Transducer Serial Number Part 2[110])
+    0x75, 0x20,                    //     REPORT_SIZE (32)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x05, 0x0d,                    //     USAGE_PAGE (Digitizers)
+    0x09, 0x5c,                    //     USAGE (Preferred Color)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x26, 0xff, 0x00,              //     LOGICAL_MAXIMUM (255)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x5c,                    //     USAGE (Preferred Color)
+    0x27, 0xff, 0xff, 0xff, 0x00,  //     LOGICAL_MAXIMUM (0x00FFFFFF)
+    0x75, 0x18,                    //     REPORT_SIZE (24)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x6f,                    //     USAGE (No Preferred Color)
+    0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
+    0x75, 0x01,                    //     REPORT_SIZE (1)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x95, 0x07,                    //     REPORT_COUNT (7)
+    0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)
+    0x09, 0x5e,                    //     USAGE (Preferred Line Width)
+    0x26, 0xff, 0x00,              //     LOGICAL_MAXIMUM (255)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x09, 0x70,                    //     USAGE (Preferred Line Style)
+    0xa1, 0x02,                    //     COLLECTION (Logical)
+    0x15, 0x01,                    //       LOGICAL_MINIMUM (1)
+    0x25, 0x06,                    //       LOGICAL_MAXIMUM (6)
+    0x09, 0x72,                    //       USAGE (Ink)
+    0x09, 0x73,                    //       USAGE (Pencil)
+    0x09, 0x74,                    //       USAGE (Highlighter)
+    0x09, 0x75,                    //       USAGE (Chisel Marker)
+    0x09, 0x76,                    //       USAGE (Brush)
+    0x09, 0x77,                    //       USAGE (No Preferred Line Style)
+    0x81, 0x20,                    //       INPUT (Data,Ary,Abs,NPrf)
+    0xc0,                          //     END_COLLECTION
+    0x06, 0x00, 0xff,              //     USAGE_PAGE (Vendor Defined Page 1)
+    0x09, 0x01,                    //     USAGE (Vendor Usage 1)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x27, 0xff, 0xff, 0x00, 0x00,  //     LOGICAL_MAXIMUM (65535)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0x05, 0x0d,                    //     USAGE_PAGE (Digitizers)
+    0x55, 0x0c,                    //     UNIT_EXPONENT (-4)
+    0x66, 0x01, 0x10,              //     UNIT (SI Lin:Time)
+    0x47, 0xff, 0xff, 0x00, 0x00,  //     PHYSICAL_MAXIMUM (65535)
+    0x27, 0xff, 0xff, 0x00, 0x00,  //     LOGICAL_MAXIMUM (65535)
+    0x09, 0x56,                    //     USAGE (Scan Time)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
+    0xc0,                          //   END_COLLECTION
+
+// 7.5 HID Descriptor for Status Reports
+
+// The following is the portion of the HID descriptor for the status report that A USI
+// controller shall support for reporting status and error conditions.
+
+    0x05, 0x0d,                    //   USAGE_PAGE (Digitizers)
+    0x85, HID_REPORTID_ERROR,      //   REPORT_ID (HID_REPORTID_ERROR)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x81, 0x02,                    //   INPUT (Data,Var,Abs)
+    0x15, 0x01,                    //   LOGICAL_MINIMUM (1)
+    0x25, 0x04,                    //   LOGICAL_MAXIMUM (4)
+    0x09, 0x81,                    //   USAGE (Digitizer Error)
+    0xa1, 0x02,                    //   COLLECTION (Logical)
+    0x09, 0x82,                    //     USAGE (Err Normal Status)
+    0x09, 0x83,                    //     USAGE (Err Transducers Exceeded)
+    0x09, 0x84,                    //     USAGE (Err Full Trans Features Unavail)
+    0x09, 0x85,                    //     USAGE (Err Charge Low)
+    0x81, 0x20,                    //     INPUT (Data,Ary,Abs,NPrf)
+    0xc0,                          //   END_COLLECTION
+
+
+// 7.6 HID Descriptor for Feature Reports
+
+// Following is the portion of the HID descriptor for the Get/Set Feature Reports.
+
+    // Feature Get/Set - 8-Bit Line Color
+    0x85, HID_REPORTID_GETSET_COLOR8,    //   REPORT_ID (HID_REPORTID_GETSET_COLOR8)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5c,                    //   USAGE (Preferred Color)
+    0x26, 0xff, 0x00,              //   LOGICAL_MAXIMUM (255)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5d,                    //   USAGE (Preferred Color is Locked)
+    0x75, 0x01,                    //   REPORT_SIZE (1)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x95, 0x07,                    //   REPORT_COUNT (7)
+    0xb1, 0x03,                    //   FEATURE (Cnst,Var,Abs)
+
+    // Feature Get/Set - 24-Bit Line Color
+    0x85, HID_REPORTID_GETSET_COLOR24,// REPORT_ID (HID_REPORTID_GETSET_COLOR24)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5c,                    //   USAGE (Preferred Color)
+    0x27, 0xff, 0xff, 0xff, 0x00,  //   LOGICAL_MAXIMUM (0xFFFFFF)
+    0x75, 0x18,                    //   REPORT_SIZE (24)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x6f,                    //   USAGE (No Preferred Color)
+    0x75, 0x01,                    //   REPORT_SIZE (1)
+    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5d,                    //   USAGE (Preferred Color is Locked)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x95, 0x06,                    //   REPORT_COUNT (6)
+    0xb1, 0x03,                    //   FEATURE (Cnst,Var,Abs)
+
+    // Feature Get/Set - Line Width
+    0x85, HID_REPORTID_GETSET_WIDTH,    //   REPORT_ID (HID_REPORTID_GETSET_WIDTH)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5e,                    //   USAGE (Preferred Line Width)
+    0x26, 0xff, 0x00,              //   LOGICAL_MAXIMUM (255)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x09, 0x5f,                    //   USAGE (Preferred Line Width is Locked)
+    0x75, 0x01,                    //   REPORT_SIZE (1)
+    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x75, 0x07,                    //   REPORT_SIZE (7)
+    0xb1, 0x03,                    //   FEATURE (Cnst,Var,Abs)
+
+    // Feature Get/Set - Line Style
+    0x85, HID_REPORTID_GETSET_STYLE,    //   REPORT_ID (HID_REPORTID_GETSET_STYLE)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0xb1, 0x22,                    //   FEATURE (Data,Var,Abs,NPrf)
+    0x09, 0x70,                    //   USAGE (Preferred Line Style)
+    0x15, 0x01,                    //   LOGICAL_MINIMUM (1)
+    0x25, 0x06,                    //   LOGICAL_MAXIMUM (6)
+    0xa1, 0x02,                    //   COLLECTION (Logical)
+    0x09, 0x72,                    //     USAGE (Ink)
+    0x09, 0x73,                    //     USAGE (Pencil)
+    0x09, 0x74,                    //     USAGE (Highlighter)
+    0x09, 0x75,                    //     USAGE (Chisel Marker)
+    0x09, 0x76,                    //     USAGE (Brush)
+    0x09, 0x77,                    //     USAGE (No Preferred Line Style)
+    0xb1, 0x20,                    //     FEATURE (Data,Ary,Abs,NPrf)
+    0xc0,                          //   END_COLLECTION
+    0x09, 0x71,                    //   USAGE (Preferred Line Style is Locked)
+    0x75, 0x01,                    //   REPORT_SIZE (1)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x75, 0x07,                    //   REPORT_SIZE (7)
+    0xb1, 0x03,                    //   FEATURE (Cnst,Var,Abs)
+
+    // Feature Get/Set - Diagnostic
+    0x85, HID_REPORTID_DIAGNOSE,        //   REPORT_ID (HID_REPORTID_DIAGNOSE)
+    0x09, 0x80,                    //   USAGE (Digitizer Diagnostic)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x75, 0x40,                    //   REPORT_SIZE (64)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+
+    // Feature Get/Set - Buttons
+    0x85, HID_REPORTID_GETSET_BUTTONS,  //   REPORT_ID (HID_REPORTID_GETSET_BUTTONS)
+    0x09, 0xa5,                    //   USAGE (Transducer Switches)
+    0xa1, 0x02,                    //   COLLECTION (Logical)
+    0x09, 0x38,                    //     USAGE (Transducer Index)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x95, 0x01,                    //     REPORT_COUNT (1)
+    0x25, MAX_SUPPORTED_STYLI,     //     LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x15, 0x01,                    //     LOGICAL_MINIMUM (1)
+    0x25, 0x05,                    //     LOGICAL_MAXIMUM (5)
+    0x09, 0x44,                    //     USAGE (Barrel Switch)
+    0xa1, 0x02,                    //     COLLECTION (Logical)
+    0x09, 0xa4,                    //       USAGE (Switch Unimplemented)
+    0x09, 0x44,                    //       USAGE (Barrel Switch)
+    0x09, 0x5a,                    //       USAGE (Secondary Barrel Switch)
+    0x09, 0x45,                    //       USAGE (Eraser)
+    0x09, 0xa3,                    //       USAGE (Switch Disabled)
+    0xb1, 0x20,                    //       FEATURE (Data,Ary,Abs,NPrf)
+    0xc0,                          //     END_COLLECTION
+    0x09, 0x5a,                    //     USAGE (Secondary Barrel Switch)
+    0xa1, 0x02,                    //     COLLECTION (Logical)
+    0x09, 0xa4,                    //       USAGE (Switch Unimplemented)
+    0x09, 0x44,                    //       USAGE (Barrel Switch)
+    0x09, 0x5a,                    //       USAGE (Secondary Barrel Switch)
+    0x09, 0x45,                    //       USAGE (Eraser)
+    0x09, 0xa3,                    //       USAGE (Switch Disabled)
+    0xb1, 0x20,                    //       FEATURE (Data,Ary,Abs,NPrf)
+    0xc0,                          //     END_COLLECTION
+    0x09, 0x45,                    //     USAGE (Eraser)
+    0xa1, 0x02,                    //     COLLECTION (Logical)
+    0x09, 0xa4,                    //       USAGE (Switch Unimplemented)
+    0x09, 0x44,                    //       USAGE (Barrel Switch)
+    0x09, 0x5a,                    //       USAGE (Secondary Barrel Switch)
+    0x09, 0x45,                    //       USAGE (Eraser)
+    0x09, 0xa3,                    //       USAGE (Switch Disabled)
+    0xb1, 0x20,                    //       FEATURE (Data,Ary,Abs,NPrf)
+    0xc0,                          //     END_COLLECTION
+    0xc0,                          //   END_COLLECTION
+
+    // Feature Get - Firmware Version
+    0x85, HID_REPORTID_GET_FIRMWARE,    //   REPORT_ID (HID_REPORTID_GET_FIRMWARE)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x05, 0x0d,                    //   USAGE_PAGE (Digitizers)
+    0x09, 0x90,                    //   USAGE (Transducer Software Info.)
+    0xa1, 0x02,                    //   COLLECTION (Logical)
+    0x09, 0x38,                    //     USAGE (Transducer Index)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //     LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x09, 0x5b,                    //     USAGE (Transducer Serial Number)
+    0x17, 0x00, 0x00, 0x00, 0x80,  //     LOGICAL_MINIMUM(-2,147,483,648)
+    0x27, 0xFF, 0xFF, 0xFF, 0x7F,  //     LOGICAL_MAXIMUM(2,147,483,647)
+    0x75, 0x40,                    //     REPORT_SIZE (64)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x09, 0x6E,                    //     USAGE(Transducer Serial Number Part 2[110])
+    0x75, 0x20,                    //     REPORT_SIZE (32)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x09, 0x91,                    //     USAGE (Transducer Vendor ID)
+    0x75, 0x10,                    //     REPORT_SIZE (16)
+    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
+    0x26, 0xff, 0x0f,              //     LOGICAL_MAXIMUM (4095)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x09, 0x92,                    //     USAGE (Transducer Product ID)
+    0x27, 0xff, 0xff, 0x00, 0x00,  //     LOGICAL_MAXIMUM (65535)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x05, 0x06,                    //     USAGE_PAGE (Generic Device)
+    0x09, 0x2a,                    //     USAGE (Software Version)
+    0x75, 0x08,                    //     REPORT_SIZE (8)
+    0x26, 0xff, 0x00,              //     LOGICAL_MAXIMUM (255)
+    0xa1, 0x02,                    //     COLLECTION (Logical)
+    0x09, 0x2d,                    //       USAGE (Major)
+    0xb1, 0x02,                    //       FEATURE (Data,Var,Abs)
+    0x09, 0x2e,                    //       USAGE (Minor)
+    0xb1, 0x02,                    //       FEATURE (Data,Var,Abs)
+    0xc0,                          //     END_COLLECTION
+    0xc0,                          //   END_COLLECTION
+
+    // Feature Get - USI Version
+    0x85, HID_REPORTID_GET_PROTOCOL,    //   REPORT_ID (HID_REPORTID_GET_PROTOCOL)
+    0x05, 0x0d,                    //   USAGE_PAGE (Digitizers)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x05, 0x06,                    //   USAGE_PAGE (Generic Device)
+    0x09, 0x2b,                    //   USAGE (Protocol Version)
+    0xa1, 0x02,                    //   COLLECTION (Logical)
+    0x09, 0x2d,                    //     USAGE (Major)
+    0x26, 0xff, 0x00,              //     LOGICAL_MAXIMUM (255)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0x09, 0x2e,                    //     USAGE (Minor)
+    0xb1, 0x02,                    //     FEATURE (Data,Var,Abs)
+    0xc0,                          //   END_COLLECTION
+
+    // Feature Get/Set - Vendor Specific
+    0x85, HID_REPORTID_GETSET_VENDOR,   //   REPORT_ID (HID_REPORTID_GETSET_VENDOR)
+    0x05, 0x0d,                    //   USAGE_PAGE (Digitizers)
+    0x09, 0x38,                    //   USAGE (Transducer Index)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+    0x06, 0x00, 0xff,              //   USAGE_PAGE (Vendor Defined Page 1)
+    0x09, 0x01,                    //   USAGE (Vendor Usage 1)
+    0x75, 0x10,                    //   REPORT_SIZE (16)
+    0x27, 0xff, 0xff, 0x00, 0x00,  //   LOGICAL_MAXIMUM (65535)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+
+
+    // Feature Set - Select Transducer Index
+    0x85, HID_REPORTID_SET_TRANSDUCER,  //   REPORT_ID (HID_REPORTID_SET_TRANSDUCER)
+    0x05, 0x0d,                    //   USAGE_PAGE (Digitizers)
+    0x09, 0xa6,                    //   USAGE (Transducer Index Selector)
+    0x75, 0x08,                    //   REPORT_SIZE (8)
+    0x95, 0x01,                    //   REPORT_COUNT (1)
+    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
+    0x25, MAX_SUPPORTED_STYLI,     //   LOGICAL_MAXIMUM (MAX_SUPPORTED_STYLI)
+    0xb1, 0x02,                    //   FEATURE (Data,Var,Abs)
+
+    0xc0                           // END_COLLECTION
+};
+
+#define G_USI_DEFAULT_STYLUS_INDEX		1
+#define	G_USI_HID_SET_REPORT			0x01
+#define G_USI_HID_GET_REPORT			0x02
+#define G_USI_HID_SETGET_REPORT			(G_USI_HID_SET_REPORT | G_USI_HID_GET_REPORT)
+
+#define G_USI_GID_FW_VER_FLAG			(G_USI_GID_FLAG | G_USI_FW_VERSION_FLAG)
+static struct hid_feature_report_info {
+	u8 id;
+	u8 type;		/* Bit Flag - supported report type. 1: SET, 2: GET, 3: SET&GET */
+	u16 size;
+	u32 required_stylus_info;
+} hid_feature_report_infos[] = {
+	{HID_REPORTID_GETSET_COLOR8,	G_USI_HID_SETGET_REPORT,	4,  G_USI_CAPABILITY_FLAG},
+	{HID_REPORTID_GETSET_WIDTH,	G_USI_HID_SETGET_REPORT,	4,  G_USI_CAPABILITY_FLAG},
+	{HID_REPORTID_GETSET_STYLE,	G_USI_HID_SETGET_REPORT,	4,  G_USI_CAPABILITY_FLAG},
+	{HID_REPORTID_DIAGNOSE,		G_USI_HID_SETGET_REPORT,	9,  0},
+	{HID_REPORTID_GETSET_BUTTONS,	G_USI_HID_SETGET_REPORT,	5,  G_USI_CAPABILITY_FLAG},
+	{HID_REPORTID_GET_FIRMWARE,	G_USI_HID_GET_REPORT,		20, G_USI_GID_FW_VER_FLAG},
+	{HID_REPORTID_GET_PROTOCOL,	G_USI_HID_GET_REPORT,		4,  G_USI_USI_VERSION_FLAG},
+	{HID_REPORTID_GETSET_VENDOR,	G_USI_HID_SETGET_REPORT,	4,  G_USI_VENDOR_EXT_FLAG},
+	{HID_REPORTID_SET_TRANSDUCER,	0,				2,  0},
+	{HID_REPORTID_GETSET_COLOR24,	G_USI_HID_SETGET_REPORT,	6,  G_USI_CAPABILITY_FLAG},
+};
+
+enum {
+	PREAMBLE,
+	STYLUS_ID,
+	COMMAND_ID,
+	DATA,
+	CRC,
+	SUBCMD_ID,
+};
+
+/* main commands */
+enum {
+	G_USI_CONFIG_PHY,
+	G_USI_CONFIG_DOWNLINK,
+	G_USI_CONFIG_MENU_SELECT,
+	G_USI_CONFIG_PACKET,
+	G_USI_DISABLE_PACKET,
+	G_USI_SET_COLOR,
+	G_USI_SET_BUTTONS,
+	G_USI_SET_TYPE,
+	G_USI_VERIFY_HASH_LOW,
+	G_USI_UPDATE_PHY,
+	G_USI_CLEAR_INT_FLAGS,
+	G_USI_TRANSMIT_POSITION_TONE,
+	G_USI_SET_WIDTH,
+	G_USI_SEND_MY_VENDOR_ID,
+	G_USI_VERIFY_HASH_HIGH,
+	G_USI_SET_VENDOR_EXTENSION,
+	G_USI_UPDATE_PHY_TX2,
+	G_USI_CONFIG_PACKET_TX2,
+	G_USI_SEND_SESSION_ID,
+	G_USI_SLOT_CADENCE,
+	G_USI_CONFIG_PHY_FLEX,
+	G_USI_UPDATE_PHY_FLEX,
+	G_USI_SAVE_CONFIG_TO_MEM,
+	G_USI_CONFIG_FROM_MEM,
+	G_USI_WRITE_CMD_MAX,
+	G_USI_READ_CMD = 63,
+};
+
+/* sub commands for read command(G_USI_READ_CMD) */
+enum {
+	G_USI_GET_BATTERY,
+	G_USI_GET_CAPABILITY,
+	G_USI_GET_USI_VERSION,
+	G_USI_GET_GID,
+	G_USI_GET_DATA,
+	G_USI_GET_VENDOR_EXTENSION,
+	G_USI_GET_PHY,
+	G_USI_GET_TIMESLOT_SETUP0,
+	G_USI_GET_TIMESLOT_SETUP1,
+	G_USI_GET_INT_FLAGS,
+	G_USI_GET_HASH_ID,
+	G_USI_GET_FIRMWAR_EVERSION,
+	G_USI_GET_LAST_ERROR,
+	G_USI_GET_IMU,
+	G_USI_GET_TILT_TWIST,
+	G_USI_GET_TRANSMITTER_PARAMETERS,
+	G_USI_GET_TIMESLOT_SETUP2,
+	G_USI_GET_TIMESLOT_SETUP3,
+	G_USI_GET_SESSION_ID,
+	G_USI_RESERVED_FOR_USI = 19,
+	G_USI_GET_RX_STATISTICS = 50,
+	G_USI_GET_TX_STATISTICS = 51,
+	G_USI_GET_READ_SUBCMD_MAX,
+};
+
+enum {
+	G_USI_HID_STYLE_START			= 1,
+	G_USI_HID_STYLE_INK			= G_USI_HID_STYLE_START,
+	G_USI_HID_STYLE_PENCIL			= 2,
+	G_USI_HID_STYLE_HIGHLIGHTER		= 3,
+	G_USI_HID_STYLE_CHISEL_MARKER		= 4,
+	G_USI_HID_STYLE_BRUSH			= 5,
+	G_USI_HID_STYLE_NO_PREFERRED_STYLE	= 6,
+	G_USI_HID_STYLE_END			= G_USI_HID_STYLE_NO_PREFERRED_STYLE
+};
+
+#define G_USI_STYLE_NO_PREFERRED		255
+
+enum {
+	G_USI_BUTTON_SWITCH_UNPMPLEMENTED	= 1,
+	G_USI_BUTTON_BARREL_SWITCH		= 2,
+	G_USI_BUTTON_SECONDARY_BARREL_SWITCH	= 3,
+	G_USI_BUTTON_ERASER			= 4,
+	G_USI_BUTTON_SWITCH_DISABLED		= 5,
+};
+
+static const struct true_color {
+	u8 r;
+	u8 g;
+	u8 b;
+} true_colors[] = {
+	{0xF0, 0xF8, 0xFF},	// 0
+	{0xFA, 0xEB, 0xD7},	// 1
+	{0x00, 0xFF, 0xFF},	// 2
+	{0x7F, 0xFF, 0xD4},	// 3
+	{0xF0, 0xFF, 0xFF},	// 4
+	{0xF5, 0xF5, 0xDC},
+	{0xFF, 0xE4, 0xC4},
+	{0x00, 0x00, 0x00},
+	{0xFF, 0xEB, 0xCD},
+	{0x00, 0x00, 0xFF},
+	{0x8A, 0x2B, 0xE2},	// 10
+	{0xA5, 0x2A, 0x2A},
+	{0xDE, 0xB8, 0x87},
+	{0x5F, 0x9E, 0xA0},
+	{0x7F, 0xFF, 0x00},
+	{0xD2, 0x69, 0x1E},
+	{0xFF, 0x7F, 0x50},
+	{0x64, 0x95, 0xED},
+	{0xFF, 0xF8, 0xDC},
+	{0xDC, 0x14, 0x3C},
+	{0x00, 0xFF, 0xFF},	// 20
+	{0x00, 0x00, 0x8B},
+	{0x00, 0x8B, 0x8B},
+	{0xB8, 0x86, 0x0B},
+	{0xA9, 0xA9, 0xA9},
+	{0x00, 0x64, 0x00},
+	{0xBD, 0xB7, 0x6B},
+	{0x8B, 0x00, 0x8B},
+	{0x55, 0x6B, 0x2F},
+	{0xFF, 0x8C, 0x00},
+	{0x99, 0x32, 0xCC},	// 30
+	{0x8B, 0x00, 0x00},
+	{0xE9, 0x96, 0x7A},
+	{0x8F, 0xBC, 0x8F},
+	{0x48, 0x3D, 0x8B},
+	{0x2F, 0x4F, 0x4F},
+	{0x00, 0xCE, 0xD1},
+	{0x94, 0x00, 0xD3},
+	{0xFF, 0x14, 0x93},
+	{0x00, 0xBF, 0xFF},
+	{0x69, 0x69, 0x69},	// 40
+	{0x1E, 0x90, 0xFF},
+	{0xB2, 0x22, 0x22},
+	{0xFF, 0xFA, 0xF0},
+	{0x22, 0x8B, 0x22},
+	{0xFF, 0x00, 0xFF},
+	{0xDC, 0xDC, 0xDC},
+	{0xF8, 0xF8, 0xFF},
+	{0xFF, 0xD7, 0x00},
+	{0xDA, 0xA5, 0x20},
+	{0x80, 0x80, 0x80},	// 50
+	{0x00, 0x80, 0x00},
+	{0xAD, 0xFF, 0x2F},
+	{0xF0, 0xFF, 0xF0},
+	{0xFF, 0x69, 0xB4},
+	{0xCD, 0x5C, 0x5C},
+	{0x4B, 0x00, 0x82},
+	{0xFF, 0xFF, 0xF0},
+	{0xF0, 0xE6, 0x8C},
+	{0xE6, 0xE6, 0xFA},
+	{0xFF, 0xF0, 0xF5},	// 60
+	{0x7C, 0xFC, 0x00},
+	{0xFF, 0xFA, 0xCD},
+	{0xAD, 0xD8, 0xE6},
+	{0xF0, 0x80, 0x80},
+	{0xE0, 0xFF, 0xFF},
+	{0xFA, 0xFA, 0xD2},
+	{0xD3, 0xD3, 0xD3},
+	{0x90, 0xEE, 0x90},
+	{0xFF, 0xB6, 0xC1},
+	{0xFF, 0xA0, 0x7A},	// 70
+	{0x20, 0xB2, 0xAA},
+	{0x87, 0xCE, 0xFA},
+	{0x77, 0x88, 0x99},
+	{0xB0, 0xC4, 0xDE},
+	{0xFF, 0xFF, 0xE0},
+	{0x00, 0xFF, 0x00},
+	{0x32, 0xCD, 0x32},
+	{0xFA, 0xF0, 0xE6},
+	{0xFF, 0x00, 0xFF},
+	{0x80, 0x00, 0x00},	// 80
+	{0x66, 0xCD, 0xAA},
+	{0x00, 0x00, 0xCD},
+	{0xBA, 0x55, 0xD3},
+	{0x93, 0x70, 0xDB},
+	{0x3C, 0xB3, 0x71},
+	{0x7B, 0x68, 0xEE},
+	{0x00, 0xFA, 0x9A},
+	{0x48, 0xD1, 0xCC},
+	{0xC7, 0x15, 0x85},
+	{0x19, 0x19, 0x70},	// 90
+	{0xF5, 0xFF, 0xFA},
+	{0xFF, 0xE4, 0xE1},
+	{0xFF, 0xE4, 0xB5},
+	{0xFF, 0xDE, 0xAD},
+	{0x00, 0x00, 0x80},
+	{0xFD, 0xF5, 0xE6},
+	{0x80, 0x80, 0x00},
+	{0x6B, 0x8E, 0x23},
+	{0xFF, 0xA5, 0x00},
+	{0xFF, 0x45, 0x00},	// 100
+	{0xDA, 0x70, 0xD6},
+	{0xEE, 0xE8, 0xAA},
+	{0x98, 0xFB, 0x98},
+	{0xAF, 0xEE, 0xEE},
+	{0xDB, 0x70, 0x93},
+	{0xFF, 0xEF, 0xD5},
+	{0xFF, 0xDA, 0xB9},
+	{0xCD, 0x85, 0x3F},
+	{0xFF, 0xC0, 0xCB},
+	{0xDD, 0xA0, 0xDD},	// 110
+	{0xB0, 0xE0, 0xE6},
+	{0x80, 0x00, 0x80},
+	{0x66, 0x33, 0x99},
+	{0xFF, 0x00, 0x00},
+	{0xBC, 0x8F, 0x8F},
+	{0x41, 0x69, 0xE1},
+	{0x8B, 0x45, 0x13},
+	{0xFA, 0x80, 0x72},
+	{0xF4, 0xA4, 0x60},
+	{0x2E, 0x8B, 0x57},	// 120
+	{0xFF, 0xF5, 0xEE},
+	{0xA0, 0x52, 0x2D},
+	{0xC0, 0xC0, 0xC0},
+	{0x87, 0xCE, 0xEB},
+	{0x6A, 0x5A, 0xCD},
+	{0x70, 0x80, 0x90},
+	{0xFF, 0xFA, 0xFA},
+	{0x00, 0xFF, 0x7F},
+	{0x46, 0x82, 0xB4},
+	{0xD2, 0xB4, 0x8C},	// 130
+	{0x00, 0x80, 0x80},
+	{0xD8, 0xBF, 0xD8},
+	{0xFF, 0x63, 0x47},
+	{0x40, 0xE0, 0xD0},
+	{0xEE, 0x82, 0xEE},
+	{0xF5, 0xDE, 0xB3},
+	{0xFF, 0xFF, 0xFF},
+	{0xF5, 0xF5, 0xF5},
+	{0xFF, 0xFF, 0x00},
+	{0x9A, 0xCD, 0x32},	// 140
+};
+
+static const int beacon_bit_fields[] = {
+	[PREAMBLE]   = 3,
+	[STYLUS_ID]  = 3,
+	[COMMAND_ID] = 6,
+	[DATA]       = 16,
+	[CRC]        = 5,
+	[SUBCMD_ID]  = 7, /* subcommand + 'R'(reserved) */
+};
+
+#define DEFAULT_PREAMBLE_FLEX       0x1
+#define DEFAULT_PREAMBLE_STD        0x4
+#define CRC_POLYNOMIAL              0x39
+#define CRC_POLYNOMIAL_LENGTH       6
+
+/*
+ * CRC calculation from USI 2.0 spec
+ */
+static u8 calculate_crc(u32 data)
+{
+	int i;
+	int data_len = beacon_bit_fields[STYLUS_ID] +
+			beacon_bit_fields[COMMAND_ID] + beacon_bit_fields[DATA];
+
+	u32 crc_polynomial = CRC_POLYNOMIAL;
+	u32 msb_mask = 1 << (data_len - 1);
+
+	crc_polynomial = crc_polynomial << (data_len - CRC_POLYNOMIAL_LENGTH);
+
+	for (i = 0; i < data_len; i++) {
+		if (data & msb_mask)
+			data = data ^ crc_polynomial;
+		data = data << 1;
+	}
+
+	return data >> (data_len - (CRC_POLYNOMIAL_LENGTH - 1));
+}
+
+static u8 get_uplink_preamble(struct g_usi_context *usi_ctx)
+{
+	if (usi_ctx->is_flex_beacon)
+		return DEFAULT_PREAMBLE_FLEX;
+
+	return DEFAULT_PREAMBLE_STD;
+}
+
+static u16 create_uplink_data_to_read(u8 read_sub_cmd, int read_flag)
+{
+	u16 data;
+
+	data = 0x01 << read_flag;
+	data = (u16)read_sub_cmd | data << beacon_bit_fields[SUBCMD_ID];
+
+	return data;
+}
+
+static void create_uplink(u8 *buf, u8 preamble, u8 stylus_id, u8 cmd_id, u16 data)
+{
+	u64 beacon = 0;
+	u32 command = 0;
+	u8 crc;
+
+	command = (u32)data;
+	command = (u32)cmd_id | command << beacon_bit_fields[COMMAND_ID];
+	command = (u32)stylus_id | command << beacon_bit_fields[STYLUS_ID];
+
+	crc = calculate_crc(command);
+
+	beacon = (u64)crc;
+	beacon = (u64)command | beacon << (beacon_bit_fields[DATA] +
+				     beacon_bit_fields[COMMAND_ID] +
+				     beacon_bit_fields[STYLUS_ID]);
+	beacon = (u64)preamble | beacon << beacon_bit_fields[PREAMBLE];
+
+	buf[0] = (u8)beacon;
+	buf[1] = (u8)(beacon >> 8);
+	buf[2] = (u8)(beacon >> 16);
+	buf[3] = (u8)(beacon >> 24);
+	buf[4] = (u8)(beacon >> 32);
+}
+
+static struct hid_feature_report_info *get_feature_report_info(int rpt_id)
+{
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(hid_feature_report_infos); i++) {
+		if (hid_feature_report_infos[i].id == rpt_id)
+			return &hid_feature_report_infos[i];
+	}
+
+	return NULL;
+}
+
+static u8 g_usi_color24_to_color8(u8 r, u8 g, u8 b)
+{
+	int color8_idx = 0, r_diff, g_diff, b_diff;
+	u32 distance, closest = 0xFFFFFFFF;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(true_colors); i++) {
+		r_diff = r - true_colors[i].r;
+		g_diff = g - true_colors[i].g;
+		b_diff = b - true_colors[i].b;
+
+		distance = r_diff * r_diff + g_diff * g_diff + b_diff * b_diff;
+		if (distance < closest) {
+			closest = distance;
+			color8_idx = i;
+		}
+	}
+
+	return color8_idx;
+}
+
+static bool g_usi_color8_to_color24(int color8_idx, u8 *r, u8 *g, u8 *b)
+{
+	if (color8_idx < 0 || color8_idx >= ARRAY_SIZE(true_colors))
+		return false;
+
+	*r = true_colors[color8_idx].r;
+	*g = true_colors[color8_idx].g;
+	*b = true_colors[color8_idx].b;
+
+	return true;
+}
+
+/*
+ * convert button info: USI button value to HID button value
+ *
+ * Refer USI 2.0 spec
+ * 6.1.3.4 C.GetCapability()
+ * 7.3.3.1.9 Get/Set Button and Active Tail
+ */
+static u8 get_button_hid_value(struct g_usi_context *usi_ctx, int btn_no)
+{
+	u8 usi_btn_func_value = 0xFF;
+
+	/*
+	 * Check with the capability of the stylus to see which buttons are implemented and
+	 * get the designated function for the button if it's implemented.
+	 */
+	if (btn_no == 1 && usi_ctx->stylus_capability[1] & 0x08) /* Button1 implemented ? */
+		usi_btn_func_value = usi_ctx->stylus_capability[6] & 0x03;
+	else if (btn_no == 2 && (usi_ctx->stylus_capability[1] & 0x10)) /* Button2 implemented ? */
+		usi_btn_func_value = (usi_ctx->stylus_capability[6] & 0x0C) >> 2;
+	else if (btn_no == 3 && (usi_ctx->stylus_capability[1] & 0x20)) /* Eraser implemented ? */
+		usi_btn_func_value = (usi_ctx->stylus_capability[6] & 0x30) >> 4;
+	else
+		return G_USI_BUTTON_SWITCH_UNPMPLEMENTED;
+
+	if (usi_btn_func_value == 0) /* is the button disabled ? */
+		return G_USI_BUTTON_SWITCH_DISABLED;
+
+	/*
+	 * USI Primary(1) -> HID Barrel(2)
+	 * USI Secondary(2) -> HID Secondary Barrel(3)
+	 * USI Eraser(3) -> HID Eraser(4)
+	 */
+	return usi_btn_func_value + 1;
+}
+
+static int g_usi_send_diag_cmd(struct g_usi_context *usi_ctx, u8 stylus_id,
+			       u8 cmd_id, u16 cmd_data, u8 response[3])
+{
+	int ret;
+	u8 uplink[5];
+	u8 res[3];
+	u8 preamble;
+
+	memset(uplink, 0, sizeof(uplink));
+	memset(res, 0, sizeof(res));
+
+	preamble = get_uplink_preamble(usi_ctx);
+	create_uplink(uplink, preamble, 1, cmd_id, cmd_data);
+	mutex_unlock(&usi_ctx->lock);	/* This allow callback to call subsystem API functions */
+	ret = usi_ctx->cbs->g_usi_send_uplink(context_to_handle(usi_ctx), uplink, res);
+	mutex_lock(&usi_ctx->lock);
+	if (ret != 0)
+		return ret;
+
+	if (response[2] & 0x40)	{ /* EIA(Error Information Available) is set ? */
+		G_USI_ERR("EIA is set. Error Code : %d", response[2] & 0x3F);
+		return -EIO;
+	}
+
+	memcpy(response, res, sizeof(res));
+
+	return 0;
+}
+
+static int g_usi_send_write_cmd(struct g_usi_context *usi_ctx, u8 stylus_id,
+				u8 cmd_id, u16 cmd_data)
+{
+	int ret;
+	u8 response[3];
+
+	ret = g_usi_send_diag_cmd(usi_ctx, stylus_id, cmd_id, cmd_data, response);
+	if (ret != 0) {
+		G_USI_ERR("diag for write failed : cmd %d", cmd_id);
+		return ret;
+	}
+
+	/* response of a write command should be the same as the command data */
+	if ((cmd_data & 0x00FF) != response[0] || ((cmd_data & 0xFF00) >> 8) != response[1])
+		return false;
+
+	return 0;
+}
+
+static int g_usi_send_read_cmd(struct g_usi_context *usi_ctx, u8 stylus_id,
+			       u8 read_sub_cmd, int read_flag, u16 *read_data)
+{
+	int ret;
+	u16 cmd_data;
+	u8 response[3];
+
+	cmd_data = create_uplink_data_to_read(read_sub_cmd, read_flag);
+	ret = g_usi_send_diag_cmd(usi_ctx, stylus_id, G_USI_READ_CMD, cmd_data, response);
+	if (ret != 0) {
+		G_USI_ERR("diag for read failed: sub cmd %d", read_sub_cmd);
+		return ret;
+	}
+
+	*read_data = response[1] << 8 | response[0];
+
+	return 0;
+}
+
+static int g_usi_update_capability(struct g_usi_context *usi_ctx, int read_flag)
+{
+	int ret;
+	u16 read_data;
+
+	ret = g_usi_send_read_cmd(usi_ctx, 1, G_USI_GET_CAPABILITY, read_flag, &read_data);
+	if (ret != 0) {
+		G_USI_ERR("Read Capability failed: %d", ret);
+		return ret;
+	}
+
+	usi_ctx->stylus_capability[read_flag * 2] = (u8)(read_data & 0x00FF);
+	usi_ctx->stylus_capability[read_flag * 2 + 1] = (u8)((read_data >> 8) & 0x00FF);
+
+	return 0;
+}
+
+static int g_usi_update_colors(struct g_usi_context *usi_ctx)
+{
+	int ret;
+
+	/* refresh the part of capability for color information */
+	ret = g_usi_update_capability(usi_ctx, 2);
+	if (is_true_color_supported(usi_ctx)) {
+		ret |= g_usi_update_capability(usi_ctx, 4);
+		ret |= g_usi_update_capability(usi_ctx, 5);
+	}
+
+	return ret;
+}
+
+static int g_usi_hid_get_feature_report(struct g_usi_context *usi_ctx, u8 *buf, int buf_size,
+					struct hid_feature_report_info *rpt_info)
+{
+	int ret = 0;
+	u8 response[3];
+	u8 color8 = 0;
+	u8 usi_style = 0xFF;
+
+	if (rpt_info->id != HID_REPORTID_DIAGNOSE)
+		buf[1] = G_USI_DEFAULT_STYLUS_INDEX;
+
+	switch (rpt_info->id) {
+	case HID_REPORTID_GETSET_COLOR8:
+		if (!is_capability_available(usi_ctx))
+			return -ENODATA;
+
+		buf[2] = usi_ctx->stylus_capability[4];		/* preferred color */
+		buf[3] = is_preferred_color_read_only(usi_ctx); /* preferred color is RO ? */
+		break;
+	case HID_REPORTID_GETSET_WIDTH:
+		if (!is_capability_available(usi_ctx))
+			return -ENODATA;
+
+		buf[2] = usi_ctx->stylus_capability[3];		/* preferred width */
+		buf[3] = is_preferred_width_read_only(usi_ctx); /* preferred width is RO ? */
+		break;
+	case HID_REPORTID_GETSET_STYLE:
+		if (!is_capability_available(usi_ctx))
+			return -ENODATA;
+
+		usi_style = usi_ctx->stylus_capability[2];	/* preferred style */
+		/* USI to HID conversion for No Preference */
+		if (usi_style == G_USI_STYLE_NO_PREFERRED)
+			buf[2] = G_USI_HID_STYLE_NO_PREFERRED_STYLE;
+		else
+			buf[2] = usi_style;
+		buf[3] = is_preferred_style_read_only(usi_ctx); /* preferred style is RO ? */
+		break;
+	case HID_REPORTID_GETSET_BUTTONS:
+		if (!is_capability_available(usi_ctx))
+			return -ENODATA;
+
+		buf[2] = get_button_hid_value(usi_ctx, 1); /* get button 1 */
+		buf[3] = get_button_hid_value(usi_ctx, 2); /* get button 2 */
+		buf[4] = get_button_hid_value(usi_ctx, 3); /* get button 3 */
+		break;
+	case HID_REPORTID_GET_FIRMWARE:
+		if (!is_gid_available(usi_ctx) || !is_fw_version_available(usi_ctx))
+			return -ENODATA;
+
+		/* USI 2.0 spec. 7.3.3.1.3 Get Stylus Firmware Info */
+		/* 64bits Transducer Serial Number(GID0 ~ GID3) */
+		memcpy(buf + 2, usi_ctx->stylus_GID, 8);
+
+		/* 32bits Transducer Serial Number Part 2(GID2 ~ GID3) & VID/PID(GID4 ~ GID5) */
+		memcpy(buf + 10, usi_ctx->stylus_GID + 4, 8);
+
+		/* FW version major/minor */
+		buf[18] = usi_ctx->stylus_fw_ver[1];
+		buf[19] = usi_ctx->stylus_fw_ver[0];
+		break;
+	case HID_REPORTID_GETSET_COLOR24:
+		if (!is_capability_available(usi_ctx))
+			return -ENODATA;
+
+		buf[5] = 0;
+		if (is_preferred_color_read_only(usi_ctx))
+			buf[5] |= 0x02;				/* Preferred Color is RO */
+
+		if (usi_ctx->stylus_capability[4] == 0xFF) {	/* No Preferred Color */
+			buf[2] = 0; /* Blue Color Value */
+			buf[3] = 0; /* Green Color Value */
+			buf[4] = 0;  /* Red Color Value */
+			buf[5] |= 0x01; /* True for no Preferred Color */
+
+			break;
+		}
+
+		/* There's the preferred color */
+
+		if (is_true_color_supported(usi_ctx)) {
+			buf[2] = usi_ctx->stylus_capability[10]; /* Blue Value */
+			buf[3] = usi_ctx->stylus_capability[11]; /* Green Value */
+			buf[4] = usi_ctx->stylus_capability[8];  /* Red Value */
+		} else {
+			color8 = usi_ctx->stylus_capability[4];
+
+			/* convert color8 to color24 - buf[2]:blue, buf[3]:green, buf[4]:red */
+			if (g_usi_color8_to_color24(color8, buf + 4, buf + 3, buf + 2) == false)
+				return -ENODATA;
+		}
+
+		break;
+	case HID_REPORTID_GET_PROTOCOL:
+		if (!is_usi_version_available(usi_ctx))
+			return -ENODATA;
+
+		buf[2] = (usi_ctx->stylus_usi_ver & 0xF0) >> 4;
+		buf[3] = usi_ctx->stylus_usi_ver & 0x0F;
+		break;
+	case HID_REPORTID_GETSET_VENDOR:
+		if (!is_vendor_ext_available(usi_ctx))
+			return -ENODATA;
+
+		buf[2] = usi_ctx->stylus_vendor_ext[0];
+		buf[3] = usi_ctx->stylus_vendor_ext[1];
+		break;
+	case HID_REPORTID_DIAGNOSE:
+		if (!usi_ctx->cbs->g_usi_send_uplink) {
+			G_USI_ERR("Get Diagnostic Feature Request is not supported");
+			return -EINVAL;
+		}
+
+		if (!usi_ctx->is_diagnose_requested) {
+			G_USI_ERR("No HID SET DIAGNOSE is requested");
+			return -ENODATA;
+		}
+
+		mutex_unlock(&usi_ctx->lock);
+		ret = usi_ctx->cbs->g_usi_send_uplink(context_to_handle(usi_ctx),
+						      usi_ctx->diagnose_uplink, response);
+		mutex_lock(&usi_ctx->lock);
+		if (ret != 0) {
+			G_USI_ERR("Get Last Error failed : %d", ret);
+			break;
+		}
+
+		memcpy(&buf[1], response, sizeof(response));
+
+		usi_ctx->is_diagnose_requested = false;
+		break;
+	}
+
+	return ret;
+}
+
+static int g_usi_hid_set_feature_report(struct g_usi_context *usi_ctx, u8 *buf, int buf_size,
+					struct hid_feature_report_info *rpt_info)
+{
+	int ret = 0;
+	int i;
+	u16 cmd_data = 0;
+	u8 stylus_has_button = 0x20;		/* refer to C.GetCapability() in USI 2.0 spec */
+	u8 color8 = 0, r, g, b;
+
+	if (!usi_ctx->cbs->g_usi_send_uplink) {
+		G_USI_ERR("Set Feature Request is not supported");
+		return -EINVAL;
+	}
+
+	switch (rpt_info->id) {
+	case HID_REPORTID_GETSET_COLOR8:
+		if (!is_capability_available(usi_ctx))
+			return -EAGAIN;
+
+		if (is_preferred_color_read_only(usi_ctx))
+			return -EINVAL;
+
+		color8 = buf[2];
+		if (is_true_color_supported(usi_ctx) &&
+		    g_usi_color8_to_color24(color8, &r, &g, &b)) {
+			cmd_data = 0x0100 | b;
+			g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+
+			cmd_data = 0x0200 | g;
+			g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+
+			cmd_data = 0x0400 | r;
+			g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+		}
+
+		cmd_data = color8;
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set Color8 failed : %d", ret);
+
+		ret = g_usi_update_colors(usi_ctx);
+		if (ret != 0)
+			G_USI_ERR("Color Sync failed : %d", ret);
+
+		break;
+	case HID_REPORTID_GETSET_COLOR24:
+		if (!is_capability_available(usi_ctx))
+			return -EAGAIN;
+
+		if (is_preferred_color_read_only(usi_ctx))
+			return -EINVAL;
+
+		color8 = g_usi_color24_to_color8(buf[4], buf[3], buf[2]);
+
+		if (is_true_color_supported(usi_ctx)) {
+			for (i = 0; i < 3; i++) {
+				cmd_data = (0x0100 << i) | buf[i + 2];
+				ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+				if (ret != 0) {
+					G_USI_ERR("Set Color24 - %04X failed : %d", cmd_data, ret);
+					break;
+				}
+			}
+		}
+
+		cmd_data = color8;
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_COLOR, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set Color8 failed : %d", ret);
+
+		ret = g_usi_update_colors(usi_ctx);
+		if (ret != 0)
+			G_USI_ERR("Color Sync failed : %d", ret);
+
+		break;
+	case HID_REPORTID_GETSET_WIDTH:
+		if (!is_capability_available(usi_ctx))
+			return -EAGAIN;
+
+		if (is_preferred_width_read_only(usi_ctx))
+			return -EINVAL;
+
+		cmd_data = buf[2];
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_WIDTH, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set Width failed : %d", ret);
+
+		ret = g_usi_update_capability(usi_ctx, 1);
+		if (ret != 0)
+			G_USI_ERR("Width Sync failed : %d", ret);
+
+		break;
+	case HID_REPORTID_GETSET_STYLE:
+		if (!is_capability_available(usi_ctx))
+			return -EAGAIN;
+
+		if (is_preferred_style_read_only(usi_ctx))
+			return -EINVAL;
+
+		if (buf[2] < G_USI_HID_STYLE_START || buf[2] > G_USI_HID_STYLE_END) {
+			G_USI_ERR("Set Style - invalid style %d", buf[2]);
+			return -EINVAL;
+		}
+
+		if (buf[2] == G_USI_HID_STYLE_NO_PREFERRED_STYLE)
+			cmd_data = G_USI_STYLE_NO_PREFERRED;
+		else
+			cmd_data = buf[2];
+
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_TYPE, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set Type failed : %d", ret);
+
+		ret = g_usi_update_capability(usi_ctx, 1);
+		if (ret != 0)
+			G_USI_ERR("Type Sync failed : %d", ret);
+
+		break;
+	case HID_REPORTID_GETSET_BUTTONS:
+		if (!is_capability_available(usi_ctx))
+			return -EAGAIN;
+
+		cmd_data = 0;
+		for (i = 4; i >= 2; i--) {
+			cmd_data <<= 2;
+
+			if (buf[i] < G_USI_BUTTON_SWITCH_UNPMPLEMENTED ||
+			    buf[i] > G_USI_BUTTON_SWITCH_DISABLED) {
+				G_USI_ERR("Set Button[%d] - invalid function %d", i - 1, buf[i]);
+				return -EINVAL;
+			}
+
+			if (usi_ctx->stylus_capability[1] & stylus_has_button)
+				cmd_data |= buf[i] - 1;
+
+			stylus_has_button >>= 1;
+		}
+
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_BUTTONS, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set Buttons failed : %d", ret);
+
+		ret = g_usi_update_capability(usi_ctx, 3);
+		if (ret != 0)
+			G_USI_ERR("Type Sync failed : %d", ret);
+
+		break;
+	case HID_REPORTID_GETSET_VENDOR:
+		cmd_data = buf[3] << 8 | buf[2];
+		ret = g_usi_send_write_cmd(usi_ctx, 1, G_USI_SET_VENDOR_EXTENSION, cmd_data);
+		if (ret != 0)
+			G_USI_ERR("Set VendorExtension failed : %d", ret);
+
+		/* TODO: Get Vendor extension via diag */
+		break;
+	case HID_REPORTID_DIAGNOSE:
+		usi_ctx->is_diagnose_requested = false;
+
+		for (i = 0; i < 5; i++)
+			usi_ctx->diagnose_uplink[i] = buf[i + 1];
+
+		usi_ctx->is_diagnose_requested = true;
+		break;
+
+	default:
+		G_USI_ERR("Set Feature Report with report ID %d is not supported", rpt_info->id);
+		ret = -EINVAL;
+	}
+
+	return ret;
+}
+
+static int device_open(struct inode *inode, struct file *file)
+{
+	struct g_usi_context __maybe_unused *usi_ctx = container_of(file->private_data,
+								    struct g_usi_context,
+								    g_usi_hidraw_dev);
+	return 0;
+}
+
+static int device_release(struct inode *inode, struct file *file)
+{
+	return 0;
+}
+
+static long device_ioctl(struct file *file, u32 cmd, unsigned long arg)
+{
+	struct g_usi_context *usi_ctx = container_of(file->private_data,
+						     struct g_usi_context,
+						     g_usi_hidraw_dev);
+	struct hid_feature_report_info *rpt_info;
+	u8 *hid_buf;
+	void __user *user_arg = (void __user *)arg;
+	u32 hid_len;
+	u32 len_arg;
+	long ret = 0;
+	struct hidraw_devinfo dinfo;
+	u8 rpt_id;
+
+	if (!g_usi_is_valid_context(usi_ctx))
+		return -EFAULT;
+
+	mutex_lock(&usi_ctx->lock);
+
+	switch (cmd) {
+	case HIDIOCGRDESCSIZE:
+		if (put_user(sizeof(USI_report_descriptor_v2_0), (int __user *)arg))
+			ret = -EFAULT;
+		break;
+	case HIDIOCGRDESC:
+		if (get_user(len_arg, (int __user *)arg))
+			ret = -EFAULT;
+		else if (len_arg > HID_MAX_DESCRIPTOR_SIZE - 1)
+			ret = -EINVAL;
+		else if (copy_to_user(user_arg + offsetof(struct hidraw_report_descriptor,
+							  value[0]),
+				      USI_report_descriptor_v2_0,
+				      min((u32)sizeof(USI_report_descriptor_v2_0), len_arg)))
+			ret = -EFAULT;
+		break;
+	case HIDIOCGRAWINFO:
+		dinfo.bustype = usi_ctx->id.bustype;
+		dinfo.vendor = usi_ctx->id.vendor;
+		dinfo.product = usi_ctx->id.product;
+		if (copy_to_user(user_arg, &dinfo, sizeof(dinfo)))
+			ret = -EFAULT;
+		break;
+	default:
+		if (usi_ctx->status != G_USI_OP_IDENTIFIED) {
+			G_USI_LOG("pen is not in range or identified yet\n");
+			ret = 0;
+			break;
+		}
+
+		hid_len = _IOC_SIZE(cmd);
+		hid_buf = memdup_user(user_arg, hid_len);
+		if (IS_ERR(hid_buf)) {
+			ret = PTR_ERR(hid_buf);
+			break;
+		}
+
+		rpt_id = hid_buf[0];
+
+		rpt_info = get_feature_report_info(rpt_id);
+		if (!rpt_info) {
+			G_USI_ERR("Invalid Report ID : %d\n", rpt_id);
+			ret = -EINVAL;
+			goto setget_error;
+		}
+
+		if (rpt_info->size > hid_len) {
+			G_USI_ERR("too small input buffer for the report(ID:%d) %d > %d\n",
+				  rpt_id, rpt_info->size, hid_len);
+			ret = -EINVAL;
+			goto setget_error;
+		}
+
+		switch (_IOC_NR(cmd)) {
+		case _IOC_NR(HIDIOCSFEATURE(0)):
+			if (rpt_id == HID_REPORTID_SET_TRANSDUCER) {
+				/* we only support one stylus */
+				if (hid_buf[1] == 1) {
+					ret = hid_len;
+				} else {
+					G_USI_ERR("Invalid Transducer Index : %d\n", hid_buf[1]);
+					ret = -EINVAL;
+				}
+
+				break;
+			}
+
+			if (!(rpt_info->type & G_USI_HID_SET_REPORT)) {
+				G_USI_ERR("Invalid Report ID for SET FEATURE %d\n", rpt_id);
+				ret = -EINVAL;
+				break;
+			}
+
+			ret = g_usi_hid_set_feature_report(usi_ctx, hid_buf, hid_len, rpt_info);
+			if (ret == 0)
+				ret = hid_len;
+			else
+				G_USI_ERR("cannot handle set feaure report id %d", rpt_info->id);
+
+			break;
+		case _IOC_NR(HIDIOCGFEATURE(0)):
+			if (!(rpt_info->type & G_USI_HID_GET_REPORT)) {
+				G_USI_ERR("Invalid Report ID for GET FEATURE %d\n", rpt_id);
+				ret = -EINVAL;
+				break;
+			}
+
+			ret = g_usi_hid_get_feature_report(usi_ctx, hid_buf, hid_len, rpt_info);
+			if (ret == 0) {
+				ret = hid_len;
+			} else if (ret == -ENODATA) {
+				G_USI_LOG("data for report id %d is not ready\n", rpt_info->id);
+				ret = 0; /* ask retry */
+			} else {
+				G_USI_ERR("Error Get HID Feature Report %ld\n", ret);
+				break;
+			}
+
+			if (copy_to_user(user_arg, hid_buf, ret))
+				ret = -EFAULT;
+
+			break;
+		default:
+			G_USI_ERR("cmd %d is not supported\n", cmd);
+			ret = -EINVAL;
+			break;
+		}
+setget_error:
+		kfree(hid_buf);
+	}
+
+	mutex_unlock(&usi_ctx->lock);
+
+	return ret;
+}
+
+static ssize_t recreate_evdev_enabled_store(struct device *dev, struct device_attribute *attr,
+					    const char *buf, size_t count)
+{
+	struct g_usi_context *usi_ctx = container_of(dev_get_drvdata(dev), struct g_usi_context,
+						     g_usi_hidraw_dev);
+
+	if (kstrtobool(buf, &usi_ctx->recreate_evdev_enabled))
+		G_USI_ERR("error: invalid input!\n");
+
+	return count;
+}
+
+static ssize_t recreate_evdev_enabled_show(struct device *dev, struct device_attribute *attr,
+					   char *buf)
+{
+	struct g_usi_context *usi_ctx = container_of(dev_get_drvdata(dev), struct g_usi_context,
+						     g_usi_hidraw_dev);
+
+	return sysfs_emit(buf, "recreate_evdev_enabled : %d\n", usi_ctx->recreate_evdev_enabled);
+}
+
+static DEVICE_ATTR_RW(recreate_evdev_enabled);
+
+static struct attribute *g_usi_attrs[] = {
+	&dev_attr_recreate_evdev_enabled.attr,
+	NULL,
+};
+
+static const struct attribute_group g_usi_attrs_group = {
+	.attrs = g_usi_attrs,
+};
+
+static const struct file_operations g_usi_fops = {
+	.owner = THIS_MODULE,
+	.open = device_open,
+	.release = device_release,
+	.unlocked_ioctl = device_ioctl
+};
+
+static int g_usi_create_hidraw(struct g_usi_context *usi_ctx)
+{
+	int ret;
+
+	usi_ctx->g_usi_hidraw_dev.name = "g_usi_hidraw";
+	usi_ctx->g_usi_hidraw_dev.mode = 0600;
+	usi_ctx->g_usi_hidraw_dev.fops = &g_usi_fops;
+
+	ret = misc_register(&usi_ctx->g_usi_hidraw_dev);
+	if (ret < 0) {
+		G_USI_ERR("misc_register failed %s", usi_ctx->g_usi_hidraw_dev.name);
+		return ret;
+	}
+
+	ret = sysfs_create_group(&usi_ctx->g_usi_hidraw_dev.this_device->kobj, &g_usi_attrs_group);
+	if (ret) {
+		G_USI_ERR("failed to create attributes : %d\n", ret);
+		goto error_sysfs_create_group;
+	}
+
+	return 0;
+
+error_sysfs_create_group:
+	misc_deregister(&usi_ctx->g_usi_hidraw_dev);
+
+	return ret;
+}
+
+static void g_usi_remove_hidraw(struct g_usi_context *usi_ctx)
+{
+	sysfs_remove_group(&usi_ctx->g_usi_hidraw_dev.this_device->kobj, &g_usi_attrs_group);
+	misc_deregister(&usi_ctx->g_usi_hidraw_dev);
+}
+
+/**
+ * goog_usi_register() - register a USI device(controller)
+ *
+ * @usi - &struct g_usi has the information about the USI device
+ *
+ * Return: &typedef g_usi_handle_t if successful, G_USI_INVALID_HANDLE if not.
+ */
+g_usi_handle_t goog_usi_register(struct g_usi *usi)
+{
+	struct g_usi_context *usi_ctx;
+
+	if (!usi || !usi->dev || !usi->cbs) {
+		G_USI_ERR("Invalid arguments");
+		return G_USI_INVALID_HANDLE;
+	}
+
+	usi_ctx = kzalloc(sizeof(*usi_ctx), GFP_KERNEL);
+	if (!usi_ctx)
+		return G_USI_INVALID_HANDLE;
+
+	/* register power supply for stylus battery */
+	usi_ctx->psy_desc.name = G_USI_BATTERY_NODE_NAME;
+	usi_ctx->psy_desc.type = POWER_SUPPLY_TYPE_UNKNOWN;
+	usi_ctx->psy_desc.properties = stylus_battery_props;
+	usi_ctx->psy_desc.num_properties = ARRAY_SIZE(stylus_battery_props);
+	usi_ctx->psy_desc.get_property = stylus_get_battery_property;
+	usi_ctx->psy_cfg.drv_data = usi_ctx;
+
+	usi_ctx->bat_psy = power_supply_register(usi->dev, &usi_ctx->psy_desc, &usi_ctx->psy_cfg);
+	if (IS_ERR(usi_ctx->bat_psy)) {
+		G_USI_ERR("Can't register power supply, err = %ld\n", PTR_ERR(usi_ctx->bat_psy));
+		goto register_battery_error;
+	}
+
+	/* register input device for stylus */
+	usi_ctx->dev = usi->dev;
+	usi_ctx->name = G_USI_INPUT_NODE_NAME;
+	usi_ctx->phys = G_USI_INPUT_NODE_PHYS;
+	usi_ctx->abs_x_max = usi->abs_x_max;
+	usi_ctx->abs_y_max = usi->abs_y_max;
+	usi_ctx->distance_max = usi->distance_max;
+	usi_ctx->tilt_min = usi->tilt_min;
+	usi_ctx->tilt_max = usi->tilt_max;
+
+	usi_ctx->id.bustype = usi->bustype;
+	usi_ctx->id.version = G_USI_INPUT_NODE_VERSION;
+	/*
+	 * The default IDs are 0xFFFF/0xFFFF and later when a USI stylus is
+	 * paired. We will expose the vendor/product IDs from the USI stylus.
+	 */
+	usi_ctx->id.vendor = 0xFFFF;
+	usi_ctx->id.product = 0xFFFF;
+	usi_ctx->recreate_evdev_enabled = 1;
+	usi_ctx->input_dev = g_usi_register_input(usi_ctx);
+	if (!usi_ctx->input_dev) {
+		G_USI_ERR("Cannot create input device");
+		goto register_input_error;
+	}
+
+	usi_ctx->is_flex_beacon = usi->is_flex_beacon;
+	usi_ctx->cbs = usi->cbs;
+
+	if (g_usi_create_hidraw(usi_ctx)) {
+		G_USI_ERR("Cannot create usi_hidraw");
+		goto create_hidraw_error;
+	}
+
+	usi_ctx->hdr.version = 1;
+	usi_ctx->hdr.magic = G_USI_MAGIC;
+
+	mutex_init(&usi_ctx->lock);
+
+	return (g_usi_handle_t)usi_ctx;
+
+create_hidraw_error:
+	g_usi_unregister_input(usi_ctx->input_dev);
+
+register_input_error:
+	power_supply_unregister(usi_ctx->bat_psy);
+
+register_battery_error:
+	kfree(usi_ctx);
+
+	return G_USI_INVALID_HANDLE;
+}
+EXPORT_SYMBOL(goog_usi_register);
+
+/**
+ * goog_usi_unregister() - unregister the USI controller
+ *
+ * @handle: &typedef g_usi_handle_t of the registered USI controller
+ */
+void goog_usi_unregister(g_usi_handle_t handle)
+{
+	struct g_usi_context *usi_ctx = handle_to_context(handle);
+
+	if (!g_usi_is_valid_context(usi_ctx)) {
+		G_USI_ERR("Invalid Parameters");
+		return;
+	}
+
+	mutex_lock(&usi_ctx->lock);
+
+	usi_ctx->hdr.magic = 0;
+	usi_ctx->hdr.version = 0;
+	g_usi_remove_hidraw(usi_ctx);
+	g_usi_unregister_input(usi_ctx->input_dev);
+	power_supply_unregister(usi_ctx->bat_psy);
+	mutex_unlock(&usi_ctx->lock);
+
+	kfree(usi_ctx);
+}
+EXPORT_SYMBOL(goog_usi_unregister);
+
+MODULE_DESCRIPTION("Google USI Subsystem");
+MODULE_AUTHOR("Hyungwoo Yang <hyungwooyang@google.com>");
+MODULE_LICENSE("GPL v2");
diff --git a/usi/goog_usi_stylus.h b/usi/goog_usi_stylus.h
new file mode 100644
index 0000000..2709fd6
--- /dev/null
+++ b/usi/goog_usi_stylus.h
@@ -0,0 +1,209 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Google USI Stylus Support for Pixel devices.
+ *
+ * Copyright 2024 Google LLC.
+ */
+
+#ifndef _GOOG_USI_STYLUS_
+#define _GOOG_USI_STYLUS_
+
+#include <linux/input.h>
+
+/**
+ * typedef g_usi_handle_t - handle for a client to use Google USI subsystem API
+ *
+ * A client(e.g. vendor specific driver) registers itself as a client of
+ * the Google USI subsystem by calling goog_usi_register() and it gets new handle.
+ */
+typedef void *g_usi_handle_t;
+#define G_USI_INVALID_HANDLE		NULL
+
+/**
+ * enum G_USI_STYLUS_INFO - bitmap Flags indicate the specific stylus information available
+ *                          from the paired(or lastly paired) stylus.
+ *
+ * The flags can be retrieved by calling goog_usi_get_stylus_info_flags()
+ * The vendor driver can use the flags to see which stylus information is
+ * available in the Google USI subsystem.
+ *
+ * G_USI_GID_FLAG          - set when GID is collected by goog_usi_report_gid()
+ * G_USI_BATTERY_FLAG      - set when battery level is collected by goog_usi_report_battery()
+ * G_USI_CAPABILITY_FLAG   - set when capability is collected by goog_usi_report_capability()
+ * G_USI_FW_VERSION_FLAG   - set when FW version is collected by goog_usi_report_fw_version()
+ * G_USI_USI_VERSION_FLAG  - set when USI version is collected by goog_usi_report_usi_version()
+ * G_USI_VENDOR_EXT_FLAG   - set when VENDOR_EXT is collected by goog_usi_report_vendor_extension()
+ * G_USI_PAIRING_INFO_FLAG - set when pariring information is collected by goog_usi_update_state()
+ */
+enum G_USI_STYLUS_INFO {
+	G_USI_GID_FLAG          = 1U << 0, /* C.GetGID() */
+	G_USI_BATTERY_FLAG      = 1U << 1, /* C.GetBattery() */
+	G_USI_CAPABILITY_FLAG   = 1U << 2, /* C.GetCapability() */
+	G_USI_FW_VERSION_FLAG   = 1U << 3, /* C.GetFirmwareVersion() */
+	G_USI_USI_VERSION_FLAG	= 1U << 4, /* C.GetUsiVersion() */
+	G_USI_VENDOR_EXT_FLAG	= 1U << 5, /* C.GetVendorExtension() */
+	G_USI_PAIRING_INFO_FLAG	= 1U << 6
+};
+
+/**
+ * enum G_USI_STATUS - stylus status used by goog_usi_update_status()
+ *
+ * Let the subsystem know the current stylus status.
+ *
+ * G_USI_UPDATE_NORMAL_PAIRING_DONE should provide the pairing information using g_usi_pairing_info
+ * G_USI_UPDATE_FAST_PAIRING_DONE may provide the pairing information using g_usi_pairing_info
+ */
+enum G_USI_STATUS {
+	G_USI_UPDATE_NORMAL_PAIRING_DONE	= 1, /* mandatory parameter - g_usi_pairing_info */
+	G_USI_UPDATE_FAST_PAIRING_DONE		= 2,
+	G_USI_UPDATE_CRC_FAILURE		= 3
+};
+
+/**
+ * struct g_usi_pairing_info - pairing information
+ *
+ * @hash_id: stylus hash ID
+ * @session_id: session_id assigned to the stylus by USI controller
+ * @freq_sel: downlink frequency assigned to the stylus by USI controller
+ * @additional_data: vendor-specific additional data that helps stylus performance
+ */
+struct g_usi_pairing_info {
+	u8 hash_id[2];
+	u8 session_id[2];
+	u8 freq_sel;
+	void *additional_data;
+};
+
+/**
+ * struct g_usi_callbacks - callbacks to ask the vendor driver to do the vendor-specific action.
+ *
+ * @g_usi_send_uplink: It is called to send an uplink command to the paired stylus.
+ *                     The subsystem calls this to cover the host communication defined
+ *                     in chapter 7.3.3 in USI 2.0 spec.
+ *
+ *                     e.g.) HID Set Color/Width/Style/Button, HID Set/Get Diagnostic command
+ *
+ *                     It is not used for any HID GET except the Diagnostic command.
+ *
+ *                     For the details, please refer to chapter 7.3.3 Feature Reports in
+ *                     USI Stylus and Device Technical specification 2.0.
+ *
+ * @g_usi_invalidate_stylus_info: It is called to invalidate the stylus information
+ *                                maintained in the subsystem and ask the fresh one
+ *                                from the paired stylus.
+ */
+struct g_usi_callbacks {
+	/*
+	 * sends 33-bits uplink in "beacon" and fill "response" with the response from the stylus
+	 *
+	 * On return, response[0 ~ 1] contains the 16 bits of data from the
+	 * stylus and response[2] has EIA and error code, 0 if no error.
+	 */
+	int (*g_usi_send_uplink)(g_usi_handle_t handle, u8 beacon[5], u8 response[3]);
+};
+
+/**
+ * struct g_usi - USI device information to register
+ *
+ * @dev: USI controller device
+ * @bustype: USI controller bustype(BUS_SPI, BUS_I2C, ... refer to input.h for available bug types
+ * @abs_x_max: maximum of x axis
+ * @abs_y_max: maximum of y axis
+ * @distance_max: maximum distance. should be 0 if distance is not supported by the USI controller
+ * @tilt_min: minimum tilt(x and y)
+ * @tilt_max: maximum tilt(x and y). should be 0 if tilt is not supported by the USI controller
+ * @is_flex_beacon: 1(true) if the USI controller is using flex beacon, 0 for standard beacon
+ * @cbs: callback functions for the subsystem to ask vendor driver to do actions
+ */
+struct g_usi {
+	struct device *dev;
+	u16 bustype;	/* BUS_SPI, BUS_I2C, ... see input.h for available bus type */
+
+	/* H/W description */
+	int abs_x_max;
+	int abs_y_max;
+	int distance_max;	/* 0 means distance is not supported */
+	int tilt_min;
+	int tilt_max;		/* 0 means tilt is not supported */
+
+	bool is_flex_beacon;	/* true if the controller uses flex beacon */
+	struct g_usi_callbacks *cbs;
+};
+
+/**
+ * struct g_usi_event - USI motion event
+ *
+ * @timestamp: timestamp should be captured in a hard ISR context
+ * @x: ABS_X
+ * @y: ABS_Y
+ * @pressure: ABS_PRESSURE
+ * @tilt_X: ABS_TILT_X
+ * @tilt_y: ABA_TILT_Y
+ * @distance: ABS_DISTANCE
+ * @buttons: BIT0: BTN_STYLUS, BIT1:BTN_STYLUS2, BIT3: BTN_TOOL_RUBBER
+ *
+ * The vendor driver provides a stylus motion event via goog_usi_send_event()
+ */
+struct g_usi_event {
+	ktime_t timestamp; /* This should be captured in Hard ISR context */
+
+	u32 x;		/* ABS_X */
+	u32 y;		/* ABS_Y */
+	u32 pressure;	/* ABS_PRESSURE */
+	s32 tilt_x;	/* ABA_TILT_X */
+	s32 tilt_y;	/* ABA_TILT_Y */
+	u32 distance;	/* ABS_DISTANCE */
+	u32 buttons;	/* BIT0: BTN_STYLUS, BIT1:BTN_STYLUS2, BIT3: BTN_TOOL_RUBBER */
+};
+
+/**
+ * struct g_usi_event_leave - USI motion event leave
+ *
+ * @timestamp: timestamp should be captured in a hard ISR context
+ *
+ * The vendor driver provides a stylus leave event via goog_usi_send_event_leave()
+ */
+struct g_usi_event_leave {
+	ktime_t timestamp; /* This should be captured in hardware IRS context */
+};
+
+/* register/unregister a USI device */
+g_usi_handle_t goog_usi_register(struct g_usi *usi);
+void goog_usi_unregister(g_usi_handle_t handle);
+
+/* send motion event and leave event */
+int goog_usi_send_event(g_usi_handle_t handle, struct g_usi_event *usi_event);
+int goog_usi_send_event_leave(g_usi_handle_t handle, struct g_usi_event_leave *usi_event_leave);
+
+/* save/restore the vendor-specific data */
+int goog_usi_set_drvdata(g_usi_handle_t handle, void *data);
+int goog_usi_get_drvdata(g_usi_handle_t handle, void **data);
+
+/* save/restore stylus information to/from the driver */
+/* Set GID0-GID5 from C.GetGID() */
+int goog_usi_report_gid(g_usi_handle_t handle, const u8 *gid);
+/* Set firmware version from G.GetFirmwareVersion() */
+int goog_usi_report_fw_version(g_usi_handle_t handle, const u8 *fw_ver);
+int goog_usi_get_fw_version(g_usi_handle_t handle, u8 *fw_ver);
+/* Set USI version from C.GetUsiVersion() */
+int goog_usi_report_usi_version(g_usi_handle_t handle, const u8 *usi_ver);
+int goog_usi_get_usi_version(g_usi_handle_t handle, u8 *usi_ver);
+/* Set vendor extension from C.GetVendorExtension() */
+int goog_usi_report_vendor_extension(g_usi_handle_t handle, const u8 *vendor_ext);
+int goog_usi_get_vendor_extension(g_usi_handle_t handle, u8 *vendor_ext);
+/* Set capability from C.GetCapability() */
+int goog_usi_report_capability(g_usi_handle_t handle, const u8 *cap);
+/* Set battery capacity and low battery flag from C.GetBattery() */
+int goog_usi_report_battery(g_usi_handle_t handle, const u8 *bat);
+int goog_usi_get_battery(g_usi_handle_t handle, u8 *bat);
+/* Get serial number of the stylus from GID collected via goog_usi_report_gid() */
+int goog_usi_get_serial_number(g_usi_handle_t handle, u32 *sn_high, u32 *sn_low);
+int goog_usi_get_serial_number_str(g_usi_handle_t handle, char *buf, int buf_size);
+/* Get vendor ID&product ID of the stylus from GID collected via goog_usi_report_gid() */
+int goog_usi_get_vid_pid(g_usi_handle_t handle, u16 *vid, u16 *pid);
+/* Update current status */
+int goog_usi_update_status(g_usi_handle_t handle, int type, void *data);
+int goog_usi_get_pairing_info(g_usi_handle_t handle, struct g_usi_pairing_info *pairing_info);
+int goog_usi_get_stylus_info_flags(g_usi_handle_t handle, u32 *info_flags);
+
+#endif /* _GOOG_USI_STYLUS_ */