python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0 /* * Parade TrueTouch(TM) Standard Product V5 Module. * * Copyright (C) 2015 Parade Technologies * Copyright (C) 2012-2015 Cypress Semiconductor * Copyright (C) 2018 Bootlin * * Authors: Mylène Josserand <[email protected]> * Alistair Francis <[email protected]> */ #include <linux/crc-itu-t.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gpio/consumer.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/regmap.h> #include <asm/unaligned.h> #define CYTTSP5_NAME "cyttsp5" #define CY_I2C_DATA_SIZE (2 * 256) #define HID_VERSION 0x0100 #define CY_MAX_INPUT 512 #define CYTTSP5_PREALLOCATED_CMD_BUFFER 32 #define CY_BITS_PER_BTN 1 #define CY_NUM_BTN_EVENT_ID GENMASK(CY_BITS_PER_BTN - 1, 0) #define MAX_AREA 255 #define HID_OUTPUT_BL_SOP 0x1 #define HID_OUTPUT_BL_EOP 0x17 #define HID_OUTPUT_BL_LAUNCH_APP 0x3B #define HID_OUTPUT_BL_LAUNCH_APP_SIZE 11 #define HID_OUTPUT_GET_SYSINFO 0x2 #define HID_OUTPUT_GET_SYSINFO_SIZE 5 #define HID_OUTPUT_MAX_CMD_SIZE 12 #define HID_DESC_REG 0x1 #define HID_INPUT_REG 0x3 #define HID_OUTPUT_REG 0x4 #define HID_COMMAND_REG 0x5 #define REPORT_ID_TOUCH 0x1 #define REPORT_ID_BTN 0x3 #define REPORT_SIZE_5 5 #define REPORT_SIZE_8 8 #define REPORT_SIZE_16 16 /* Touch reports offsets */ /* Header offsets */ #define TOUCH_REPORT_DESC_HDR_CONTACTCOUNT 16 /* Record offsets */ #define TOUCH_REPORT_DESC_CONTACTID 8 #define TOUCH_REPORT_DESC_X 16 #define TOUCH_REPORT_DESC_Y 32 #define TOUCH_REPORT_DESC_P 48 #define TOUCH_REPORT_DESC_MAJ 56 #define TOUCH_REPORT_DESC_MIN 64 /* HID */ #define HID_TOUCH_REPORT_ID 0x1 #define HID_BTN_REPORT_ID 0x3 #define HID_APP_RESPONSE_REPORT_ID 0x1F #define HID_APP_OUTPUT_REPORT_ID 0x2F #define HID_BL_RESPONSE_REPORT_ID 0x30 #define HID_BL_OUTPUT_REPORT_ID 0x40 #define HID_RESPONSE_REPORT_ID 0xF0 #define HID_OUTPUT_RESPONSE_REPORT_OFFSET 2 #define HID_OUTPUT_RESPONSE_CMD_OFFSET 4 #define HID_OUTPUT_RESPONSE_CMD_MASK GENMASK(6, 0) #define HID_SYSINFO_SENSING_OFFSET 33 #define HID_SYSINFO_BTN_OFFSET 48 #define HID_SYSINFO_BTN_MASK GENMASK(7, 0) #define HID_SYSINFO_MAX_BTN 8 #define HID_CMD_SET_POWER 0x8 #define HID_POWER_ON 0x0 #define HID_POWER_SLEEP 0x1 #define CY_HID_OUTPUT_TIMEOUT_MS 200 #define CY_HID_OUTPUT_GET_SYSINFO_TIMEOUT_MS 3000 #define CY_HID_GET_HID_DESCRIPTOR_TIMEOUT_MS 4000 #define CY_HID_SET_POWER_TIMEOUT 500 /* maximum number of concurrent tracks */ #define TOUCH_REPORT_SIZE 10 #define TOUCH_INPUT_HEADER_SIZE 7 #define BTN_REPORT_SIZE 9 #define BTN_INPUT_HEADER_SIZE 5 #define MAX_CY_TCH_T_IDS 32 /* All usage pages for Touch Report */ #define TOUCH_REPORT_USAGE_PG_X 0x00010030 #define TOUCH_REPORT_USAGE_PG_Y 0x00010031 #define TOUCH_REPORT_USAGE_PG_P 0x000D0030 #define TOUCH_REPORT_USAGE_PG_CONTACTID 0x000D0051 #define TOUCH_REPORT_USAGE_PG_CONTACTCOUNT 0x000D0054 #define TOUCH_REPORT_USAGE_PG_MAJ 0xFF010062 #define TOUCH_REPORT_USAGE_PG_MIN 0xFF010063 #define TOUCH_COL_USAGE_PG 0x000D0022 #define SET_CMD_LOW(byte, bits) \ ((byte) = (((byte) & 0xF0) | ((bits) & 0x0F))) #define SET_CMD_HIGH(byte, bits)\ ((byte) = (((byte) & 0x0F) | ((bits) & 0xF0))) #define SET_CMD_OPCODE(byte, opcode) SET_CMD_LOW(byte, opcode) #define SET_CMD_REPORT_TYPE(byte, type) SET_CMD_HIGH(byte, ((type) << 4)) #define SET_CMD_REPORT_ID(byte, id) SET_CMD_LOW(byte, id) /* System Information interface definitions */ struct cyttsp5_sensing_conf_data_dev { u8 electrodes_x; u8 electrodes_y; __le16 len_x; __le16 len_y; __le16 res_x; __le16 res_y; __le16 max_z; u8 origin_x; u8 origin_y; u8 panel_id; u8 btn; u8 scan_mode; u8 max_num_of_tch_per_refresh_cycle; } __packed; struct cyttsp5_sensing_conf_data { u16 res_x; u16 res_y; u16 max_z; u16 len_x; u16 len_y; u8 origin_x; u8 origin_y; u8 max_tch; }; enum cyttsp5_tch_abs { /* for ordering within the extracted touch data array */ CY_TCH_X, /* X */ CY_TCH_Y, /* Y */ CY_TCH_P, /* P (Z) */ CY_TCH_T, /* TOUCH ID */ CY_TCH_MAJ, /* TOUCH_MAJOR */ CY_TCH_MIN, /* TOUCH_MINOR */ CY_TCH_NUM_ABS }; struct cyttsp5_tch_abs_params { size_t ofs; /* abs byte offset */ size_t size; /* size in bits */ size_t min; /* min value */ size_t max; /* max value */ size_t bofs; /* bit offset */ }; struct cyttsp5_touch { int abs[CY_TCH_NUM_ABS]; }; struct cyttsp5_sysinfo { struct cyttsp5_sensing_conf_data sensing_conf_data; int num_btns; struct cyttsp5_tch_abs_params tch_hdr; struct cyttsp5_tch_abs_params tch_abs[CY_TCH_NUM_ABS]; u32 key_code[HID_SYSINFO_MAX_BTN]; }; struct cyttsp5_hid_desc { __le16 hid_desc_len; u8 packet_id; u8 reserved_byte; __le16 bcd_version; __le16 report_desc_len; __le16 report_desc_register; __le16 input_register; __le16 max_input_len; __le16 output_register; __le16 max_output_len; __le16 command_register; __le16 data_register; __le16 vendor_id; __le16 product_id; __le16 version_id; u8 reserved[4]; } __packed; struct cyttsp5 { struct device *dev; struct completion cmd_done; struct cyttsp5_sysinfo sysinfo; struct cyttsp5_hid_desc hid_desc; u8 cmd_buf[CYTTSP5_PREALLOCATED_CMD_BUFFER]; u8 input_buf[CY_MAX_INPUT]; u8 response_buf[CY_MAX_INPUT]; struct gpio_desc *reset_gpio; struct input_dev *input; char phys[NAME_MAX]; int num_prv_rec; struct regmap *regmap; struct touchscreen_properties prop; struct regulator *vdd; }; /* * For what is understood in the datasheet, the register does not * matter. For consistency, use the Input Register address * but it does mean anything to the device. The important data * to send is the I2C address */ static int cyttsp5_read(struct cyttsp5 *ts, u8 *buf, u32 max) { int error; u32 size; u8 temp[2]; /* Read the frame to retrieve the size */ error = regmap_bulk_read(ts->regmap, HID_INPUT_REG, temp, sizeof(temp)); if (error) return error; size = get_unaligned_le16(temp); if (!size || size == 2) return 0; if (size > max) return -EINVAL; /* Get the real value */ return regmap_bulk_read(ts->regmap, HID_INPUT_REG, buf, size); } static int cyttsp5_write(struct cyttsp5 *ts, unsigned int reg, u8 *data, size_t size) { u8 cmd[HID_OUTPUT_MAX_CMD_SIZE]; if (size + 1 > HID_OUTPUT_MAX_CMD_SIZE) return -E2BIG; /* High bytes of register address needed as first byte of cmd */ cmd[0] = (reg >> 8) & 0xFF; /* Copy the rest of the data */ if (data) memcpy(&cmd[1], data, size); /* * The hardware wants to receive a frame with the address register * contained in the first two bytes. As the regmap_write function * add the register adresse in the frame, we use the low byte as * first frame byte for the address register and the first * data byte is the high register + left of the cmd to send */ return regmap_bulk_write(ts->regmap, reg & 0xFF, cmd, size + 1); } static void cyttsp5_get_touch_axis(int *axis, int size, int max, u8 *xy_data, int bofs) { int nbyte; for (nbyte = 0, *axis = 0; nbyte < size; nbyte++) *axis += ((xy_data[nbyte] >> bofs) << (nbyte * 8)); *axis &= max - 1; } static void cyttsp5_get_touch_record(struct cyttsp5 *ts, struct cyttsp5_touch *touch, u8 *xy_data) { struct cyttsp5_sysinfo *si = &ts->sysinfo; enum cyttsp5_tch_abs abs; for (abs = CY_TCH_X; abs < CY_TCH_NUM_ABS; abs++) cyttsp5_get_touch_axis(&touch->abs[abs], si->tch_abs[abs].size, si->tch_abs[abs].max, xy_data + si->tch_abs[abs].ofs, si->tch_abs[abs].bofs); } static void cyttsp5_get_mt_touches(struct cyttsp5 *ts, struct cyttsp5_touch *tch, int num_cur_tch) { struct cyttsp5_sysinfo *si = &ts->sysinfo; int i, t = 0, offset = 0; DECLARE_BITMAP(ids, MAX_CY_TCH_T_IDS); u8 *tch_addr; int tmp; bitmap_zero(ids, MAX_CY_TCH_T_IDS); memset(tch->abs, 0, sizeof(tch->abs)); switch (ts->input_buf[2]) { case HID_TOUCH_REPORT_ID: offset = TOUCH_INPUT_HEADER_SIZE; break; case HID_BTN_REPORT_ID: offset = BTN_INPUT_HEADER_SIZE; break; } for (i = 0; i < num_cur_tch; i++) { tch_addr = ts->input_buf + offset + (i * TOUCH_REPORT_SIZE); cyttsp5_get_touch_record(ts, tch, tch_addr); /* Convert MAJOR/MINOR from mm to resolution */ tmp = tch->abs[CY_TCH_MAJ] * 100 * si->sensing_conf_data.res_x; tch->abs[CY_TCH_MAJ] = tmp / si->sensing_conf_data.len_x; tmp = tch->abs[CY_TCH_MIN] * 100 * si->sensing_conf_data.res_x; tch->abs[CY_TCH_MIN] = tmp / si->sensing_conf_data.len_x; t = tch->abs[CY_TCH_T]; input_mt_slot(ts->input, t); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, true); __set_bit(t, ids); /* position and pressure fields */ touchscreen_report_pos(ts->input, &ts->prop, tch->abs[CY_TCH_X], tch->abs[CY_TCH_Y], true); input_report_abs(ts->input, ABS_MT_PRESSURE, tch->abs[CY_TCH_P]); /* Get the extended touch fields */ input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, tch->abs[CY_TCH_MAJ]); input_report_abs(ts->input, ABS_MT_TOUCH_MINOR, tch->abs[CY_TCH_MIN]); } ts->num_prv_rec = num_cur_tch; } static int cyttsp5_mt_attention(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); struct cyttsp5_sysinfo *si = &ts->sysinfo; int max_tch = si->sensing_conf_data.max_tch; struct cyttsp5_touch tch; int num_cur_tch; cyttsp5_get_touch_axis(&num_cur_tch, si->tch_hdr.size, si->tch_hdr.max, ts->input_buf + 3 + si->tch_hdr.ofs, si->tch_hdr.bofs); if (num_cur_tch > max_tch) { dev_err(dev, "Num touch err detected (n=%d)\n", num_cur_tch); num_cur_tch = max_tch; } if (num_cur_tch == 0 && ts->num_prv_rec == 0) return 0; /* extract xy_data for all currently reported touches */ if (num_cur_tch) cyttsp5_get_mt_touches(ts, &tch, num_cur_tch); input_mt_sync_frame(ts->input); input_sync(ts->input); return 0; } static int cyttsp5_setup_input_device(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); struct cyttsp5_sysinfo *si = &ts->sysinfo; int max_x, max_y, max_p; int max_x_tmp, max_y_tmp; int error; max_x_tmp = si->sensing_conf_data.res_x; max_y_tmp = si->sensing_conf_data.res_y; max_x = max_x_tmp - 1; max_y = max_y_tmp - 1; max_p = si->sensing_conf_data.max_z; input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, max_y, 0, 0); input_set_abs_params(ts->input, ABS_MT_PRESSURE, 0, max_p, 0, 0); input_set_abs_params(ts->input, ABS_MT_TOUCH_MAJOR, 0, MAX_AREA, 0, 0); input_set_abs_params(ts->input, ABS_MT_TOUCH_MINOR, 0, MAX_AREA, 0, 0); error = input_mt_init_slots(ts->input, si->tch_abs[CY_TCH_T].max, INPUT_MT_DROP_UNUSED | INPUT_MT_DIRECT); if (error) return error; error = input_register_device(ts->input); if (error) { dev_err(dev, "failed to register input device: %d\n", error); return error; } return error; } static int cyttsp5_parse_dt_key_code(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); struct cyttsp5_sysinfo *si = &ts->sysinfo; if (!si->num_btns) return 0; /* Initialize the button to RESERVED */ memset32(si->key_code, KEY_RESERVED, si->num_btns); return device_property_read_u32_array(dev, "linux,keycodes", si->key_code, si->num_btns); } static int cyttsp5_btn_attention(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); struct cyttsp5_sysinfo *si = &ts->sysinfo; int cur_btn, offset = 0; int cur_btn_state; switch (ts->input_buf[2]) { case HID_TOUCH_REPORT_ID: offset = TOUCH_INPUT_HEADER_SIZE; break; case HID_BTN_REPORT_ID: offset = BTN_INPUT_HEADER_SIZE; break; } if (ts->input_buf[2] != HID_BTN_REPORT_ID) return 0; /* extract button press/release touch information */ for (cur_btn = 0; cur_btn < si->num_btns; cur_btn++) { /* Get current button state */ cur_btn_state = (ts->input_buf[offset] >> (cur_btn * CY_BITS_PER_BTN)) & CY_NUM_BTN_EVENT_ID; input_report_key(ts->input, si->key_code[cur_btn], cur_btn_state); input_sync(ts->input); } return 0; } static int cyttsp5_validate_cmd_response(struct cyttsp5 *ts, u8 code) { u16 size, crc; u8 status, report_id; int command_code; size = get_unaligned_le16(&ts->response_buf[0]); if (!size) return 0; report_id = ts->response_buf[HID_OUTPUT_RESPONSE_REPORT_OFFSET]; switch (report_id) { case HID_BL_RESPONSE_REPORT_ID: if (ts->response_buf[4] != HID_OUTPUT_BL_SOP) { dev_err(ts->dev, "HID output response, wrong SOP\n"); return -EPROTO; } if (ts->response_buf[size - 1] != HID_OUTPUT_BL_EOP) { dev_err(ts->dev, "HID output response, wrong EOP\n"); return -EPROTO; } crc = crc_itu_t(0xFFFF, &ts->response_buf[4], size - 7); if (get_unaligned_le16(&ts->response_buf[size - 3]) != crc) { dev_err(ts->dev, "HID output response, wrong CRC 0x%X\n", crc); return -EPROTO; } status = ts->response_buf[5]; if (status) { dev_err(ts->dev, "HID output response, ERROR:%d\n", status); return -EPROTO; } break; case HID_APP_RESPONSE_REPORT_ID: command_code = ts->response_buf[HID_OUTPUT_RESPONSE_CMD_OFFSET] & HID_OUTPUT_RESPONSE_CMD_MASK; if (command_code != code) { dev_err(ts->dev, "HID output response, wrong command_code:%X\n", command_code); return -EPROTO; } break; } return 0; } static void cyttsp5_si_get_btn_data(struct cyttsp5 *ts) { struct cyttsp5_sysinfo *si = &ts->sysinfo; unsigned int btns = ts->response_buf[HID_SYSINFO_BTN_OFFSET] & HID_SYSINFO_BTN_MASK; si->num_btns = hweight8(btns); } static int cyttsp5_get_sysinfo_regs(struct cyttsp5 *ts) { struct cyttsp5_sensing_conf_data *scd = &ts->sysinfo.sensing_conf_data; struct cyttsp5_sensing_conf_data_dev *scd_dev = (struct cyttsp5_sensing_conf_data_dev *) &ts->response_buf[HID_SYSINFO_SENSING_OFFSET]; cyttsp5_si_get_btn_data(ts); scd->max_tch = scd_dev->max_num_of_tch_per_refresh_cycle; scd->res_x = get_unaligned_le16(&scd_dev->res_x); scd->res_y = get_unaligned_le16(&scd_dev->res_y); scd->max_z = get_unaligned_le16(&scd_dev->max_z); scd->len_x = get_unaligned_le16(&scd_dev->len_x); scd->len_y = get_unaligned_le16(&scd_dev->len_y); return 0; } static int cyttsp5_hid_output_get_sysinfo(struct cyttsp5 *ts) { int rc; u8 cmd[HID_OUTPUT_GET_SYSINFO_SIZE]; /* HI bytes of Output register address */ put_unaligned_le16(HID_OUTPUT_GET_SYSINFO_SIZE, cmd); cmd[2] = HID_APP_OUTPUT_REPORT_ID; cmd[3] = 0x0; /* Reserved */ cmd[4] = HID_OUTPUT_GET_SYSINFO; rc = cyttsp5_write(ts, HID_OUTPUT_REG, cmd, HID_OUTPUT_GET_SYSINFO_SIZE); if (rc) { dev_err(ts->dev, "Failed to write command %d", rc); return rc; } rc = wait_for_completion_interruptible_timeout(&ts->cmd_done, msecs_to_jiffies(CY_HID_OUTPUT_GET_SYSINFO_TIMEOUT_MS)); if (rc <= 0) { dev_err(ts->dev, "HID output cmd execution timed out\n"); rc = -ETIMEDOUT; return rc; } rc = cyttsp5_validate_cmd_response(ts, HID_OUTPUT_GET_SYSINFO); if (rc) { dev_err(ts->dev, "Validation of the response failed\n"); return rc; } return cyttsp5_get_sysinfo_regs(ts); } static int cyttsp5_power_control(struct cyttsp5 *ts, bool on) { u8 state = on ? HID_POWER_ON : HID_POWER_SLEEP; u8 cmd[2] = { 0 }; int rc; SET_CMD_REPORT_TYPE(cmd[0], 0); SET_CMD_REPORT_ID(cmd[0], HID_POWER_SLEEP); SET_CMD_OPCODE(cmd[1], HID_CMD_SET_POWER); rc = cyttsp5_write(ts, HID_COMMAND_REG, cmd, sizeof(cmd)); if (rc) { dev_err(ts->dev, "Failed to write power command %d", rc); return rc; } rc = wait_for_completion_interruptible_timeout(&ts->cmd_done, msecs_to_jiffies(CY_HID_SET_POWER_TIMEOUT)); if (rc <= 0) { dev_err(ts->dev, "HID power cmd execution timed out\n"); return -ETIMEDOUT; } if (ts->response_buf[2] != HID_RESPONSE_REPORT_ID || (ts->response_buf[3] & 0x03) != state || (ts->response_buf[4] & 0x0f) != HID_CMD_SET_POWER) { dev_err(ts->dev, "Validation of the %s response failed\n", on ? "wakeup" : "sleep"); return -EINVAL; } return 0; } static int cyttsp5_hid_output_bl_launch_app(struct cyttsp5 *ts) { int rc; u8 cmd[HID_OUTPUT_BL_LAUNCH_APP_SIZE]; u16 crc; put_unaligned_le16(HID_OUTPUT_BL_LAUNCH_APP_SIZE, cmd); cmd[2] = HID_BL_OUTPUT_REPORT_ID; cmd[3] = 0x0; /* Reserved */ cmd[4] = HID_OUTPUT_BL_SOP; cmd[5] = HID_OUTPUT_BL_LAUNCH_APP; put_unaligned_le16(0x00, &cmd[6]); crc = crc_itu_t(0xFFFF, &cmd[4], 4); put_unaligned_le16(crc, &cmd[8]); cmd[10] = HID_OUTPUT_BL_EOP; rc = cyttsp5_write(ts, HID_OUTPUT_REG, cmd, HID_OUTPUT_BL_LAUNCH_APP_SIZE); if (rc) { dev_err(ts->dev, "Failed to write command %d", rc); return rc; } rc = wait_for_completion_interruptible_timeout(&ts->cmd_done, msecs_to_jiffies(CY_HID_OUTPUT_TIMEOUT_MS)); if (rc <= 0) { dev_err(ts->dev, "HID output cmd execution timed out\n"); rc = -ETIMEDOUT; return rc; } rc = cyttsp5_validate_cmd_response(ts, HID_OUTPUT_BL_LAUNCH_APP); if (rc) { dev_err(ts->dev, "Validation of the response failed\n"); return rc; } return 0; } static int cyttsp5_get_hid_descriptor(struct cyttsp5 *ts, struct cyttsp5_hid_desc *desc) { struct device *dev = ts->dev; int rc; rc = cyttsp5_write(ts, HID_DESC_REG, NULL, 0); if (rc) { dev_err(dev, "Failed to get HID descriptor, rc=%d\n", rc); return rc; } rc = wait_for_completion_interruptible_timeout(&ts->cmd_done, msecs_to_jiffies(CY_HID_GET_HID_DESCRIPTOR_TIMEOUT_MS)); if (rc <= 0) { dev_err(ts->dev, "HID get descriptor timed out\n"); rc = -ETIMEDOUT; return rc; } memcpy(desc, ts->response_buf, sizeof(*desc)); /* Check HID descriptor length and version */ if (le16_to_cpu(desc->hid_desc_len) != sizeof(*desc) || le16_to_cpu(desc->bcd_version) != HID_VERSION) { dev_err(dev, "Unsupported HID version\n"); return -ENODEV; } return 0; } static int fill_tch_abs(struct cyttsp5_tch_abs_params *tch_abs, int report_size, int offset) { tch_abs->ofs = offset / 8; tch_abs->size = report_size / 8; if (report_size % 8) tch_abs->size += 1; tch_abs->min = 0; tch_abs->max = 1 << report_size; tch_abs->bofs = offset - (tch_abs->ofs << 3); return 0; } static irqreturn_t cyttsp5_handle_irq(int irq, void *handle) { struct cyttsp5 *ts = handle; int report_id; int size; int error; error = cyttsp5_read(ts, ts->input_buf, CY_MAX_INPUT); if (error) return IRQ_HANDLED; size = get_unaligned_le16(&ts->input_buf[0]); if (size == 0) { /* reset */ report_id = 0; size = 2; } else { report_id = ts->input_buf[2]; } switch (report_id) { case HID_TOUCH_REPORT_ID: cyttsp5_mt_attention(ts->dev); break; case HID_BTN_REPORT_ID: cyttsp5_btn_attention(ts->dev); break; case HID_RESPONSE_REPORT_ID: memcpy(ts->response_buf, ts->input_buf, size); complete(&ts->cmd_done); break; default: /* It is not an input but a command response */ memcpy(ts->response_buf, ts->input_buf, size); complete(&ts->cmd_done); } return IRQ_HANDLED; } static int cyttsp5_deassert_int(struct cyttsp5 *ts) { u16 size; u8 buf[2]; int error; error = regmap_bulk_read(ts->regmap, HID_INPUT_REG, buf, sizeof(buf)); if (error < 0) return error; size = get_unaligned_le16(&buf[0]); if (size == 2 || size == 0) return 0; return -EINVAL; } static int cyttsp5_fill_all_touch(struct cyttsp5 *ts) { struct cyttsp5_sysinfo *si = &ts->sysinfo; fill_tch_abs(&si->tch_abs[CY_TCH_X], REPORT_SIZE_16, TOUCH_REPORT_DESC_X); fill_tch_abs(&si->tch_abs[CY_TCH_Y], REPORT_SIZE_16, TOUCH_REPORT_DESC_Y); fill_tch_abs(&si->tch_abs[CY_TCH_P], REPORT_SIZE_8, TOUCH_REPORT_DESC_P); fill_tch_abs(&si->tch_abs[CY_TCH_T], REPORT_SIZE_5, TOUCH_REPORT_DESC_CONTACTID); fill_tch_abs(&si->tch_hdr, REPORT_SIZE_5, TOUCH_REPORT_DESC_HDR_CONTACTCOUNT); fill_tch_abs(&si->tch_abs[CY_TCH_MAJ], REPORT_SIZE_8, TOUCH_REPORT_DESC_MAJ); fill_tch_abs(&si->tch_abs[CY_TCH_MIN], REPORT_SIZE_8, TOUCH_REPORT_DESC_MIN); return 0; } static int cyttsp5_startup(struct cyttsp5 *ts) { int error; error = cyttsp5_deassert_int(ts); if (error) { dev_err(ts->dev, "Error on deassert int r=%d\n", error); return -ENODEV; } /* * Launch the application as the device starts in bootloader mode * because of a power-on-reset */ error = cyttsp5_hid_output_bl_launch_app(ts); if (error < 0) { dev_err(ts->dev, "Error on launch app r=%d\n", error); return error; } error = cyttsp5_get_hid_descriptor(ts, &ts->hid_desc); if (error < 0) { dev_err(ts->dev, "Error on getting HID descriptor r=%d\n", error); return error; } error = cyttsp5_fill_all_touch(ts); if (error < 0) { dev_err(ts->dev, "Error on report descriptor r=%d\n", error); return error; } error = cyttsp5_hid_output_get_sysinfo(ts); if (error) { dev_err(ts->dev, "Error on getting sysinfo r=%d\n", error); return error; } return error; } static void cyttsp5_cleanup(void *data) { struct cyttsp5 *ts = data; regulator_disable(ts->vdd); } static int cyttsp5_probe(struct device *dev, struct regmap *regmap, int irq, const char *name) { struct cyttsp5 *ts; struct cyttsp5_sysinfo *si; int error, i; ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; /* Initialize device info */ ts->regmap = regmap; ts->dev = dev; si = &ts->sysinfo; dev_set_drvdata(dev, ts); init_completion(&ts->cmd_done); /* Power up the device */ ts->vdd = devm_regulator_get(dev, "vdd"); if (IS_ERR(ts->vdd)) { error = PTR_ERR(ts->vdd); return error; } error = devm_add_action_or_reset(dev, cyttsp5_cleanup, ts); if (error) return error; error = regulator_enable(ts->vdd); if (error) return error; ts->input = devm_input_allocate_device(dev); if (!ts->input) { dev_err(dev, "Error, failed to allocate input device\n"); return -ENODEV; } ts->input->name = "cyttsp5"; scnprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(dev)); ts->input->phys = ts->phys; input_set_drvdata(ts->input, ts); /* Reset the gpio to be in a reset state */ ts->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ts->reset_gpio)) { error = PTR_ERR(ts->reset_gpio); dev_err(dev, "Failed to request reset gpio, error %d\n", error); return error; } gpiod_set_value_cansleep(ts->reset_gpio, 0); /* Need a delay to have device up */ msleep(20); error = devm_request_threaded_irq(dev, irq, NULL, cyttsp5_handle_irq, IRQF_ONESHOT, name, ts); if (error) { dev_err(dev, "unable to request IRQ\n"); return error; } error = cyttsp5_startup(ts); if (error) { dev_err(ts->dev, "Fail initial startup r=%d\n", error); return error; } error = cyttsp5_parse_dt_key_code(dev); if (error < 0) { dev_err(ts->dev, "Error while parsing dts %d\n", error); return error; } touchscreen_parse_properties(ts->input, true, &ts->prop); __set_bit(EV_KEY, ts->input->evbit); for (i = 0; i < si->num_btns; i++) __set_bit(si->key_code[i], ts->input->keybit); return cyttsp5_setup_input_device(dev); } static int cyttsp5_i2c_probe(struct i2c_client *client) { struct regmap *regmap; static const struct regmap_config config = { .reg_bits = 8, .val_bits = 8, }; regmap = devm_regmap_init_i2c(client, &config); if (IS_ERR(regmap)) { dev_err(&client->dev, "regmap allocation failed: %ld\n", PTR_ERR(regmap)); return PTR_ERR(regmap); } return cyttsp5_probe(&client->dev, regmap, client->irq, client->name); } static const struct of_device_id cyttsp5_of_match[] = { { .compatible = "cypress,tt21000", }, { } }; MODULE_DEVICE_TABLE(of, cyttsp5_of_match); static const struct i2c_device_id cyttsp5_i2c_id[] = { { CYTTSP5_NAME, 0, }, { } }; MODULE_DEVICE_TABLE(i2c, cyttsp5_i2c_id); static int __maybe_unused cyttsp5_suspend(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); if (!device_may_wakeup(dev)) cyttsp5_power_control(ts, false); return 0; } static int __maybe_unused cyttsp5_resume(struct device *dev) { struct cyttsp5 *ts = dev_get_drvdata(dev); if (!device_may_wakeup(dev)) cyttsp5_power_control(ts, true); return 0; } static SIMPLE_DEV_PM_OPS(cyttsp5_pm, cyttsp5_suspend, cyttsp5_resume); static struct i2c_driver cyttsp5_i2c_driver = { .driver = { .name = CYTTSP5_NAME, .of_match_table = cyttsp5_of_match, .pm = &cyttsp5_pm, }, .probe = cyttsp5_i2c_probe, .id_table = cyttsp5_i2c_id, }; module_i2c_driver(cyttsp5_i2c_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Touchscreen driver for Cypress TrueTouch Gen 5 Product"); MODULE_AUTHOR("Mylène Josserand <[email protected]>");
linux-master
drivers/input/touchscreen/cyttsp5.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Pixcir I2C touchscreen controllers. * * Copyright (C) 2010-2011 Pixcir, Inc. */ #include <asm/unaligned.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of.h> #include <linux/slab.h> #define PIXCIR_MAX_SLOTS 5 /* Max fingers supported by driver */ /* * Register map */ #define PIXCIR_REG_POWER_MODE 51 #define PIXCIR_REG_INT_MODE 52 /* * Power modes: * active: max scan speed * idle: lower scan speed with automatic transition to active on touch * halt: datasheet says sleep but this is more like halt as the chip * clocks are cut and it can only be brought out of this mode * using the RESET pin. */ enum pixcir_power_mode { PIXCIR_POWER_ACTIVE, PIXCIR_POWER_IDLE, PIXCIR_POWER_HALT, }; #define PIXCIR_POWER_MODE_MASK 0x03 #define PIXCIR_POWER_ALLOW_IDLE (1UL << 2) /* * Interrupt modes: * periodical: interrupt is asserted periodicaly * diff coordinates: interrupt is asserted when coordinates change * level on touch: interrupt level asserted during touch * pulse on touch: interrupt pulse asserted during touch * */ enum pixcir_int_mode { PIXCIR_INT_PERIODICAL, PIXCIR_INT_DIFF_COORD, PIXCIR_INT_LEVEL_TOUCH, PIXCIR_INT_PULSE_TOUCH, }; #define PIXCIR_INT_MODE_MASK 0x03 #define PIXCIR_INT_ENABLE (1UL << 3) #define PIXCIR_INT_POL_HIGH (1UL << 2) /** * struct pixcir_i2c_chip_data - chip related data * @max_fingers: Max number of fingers reported simultaneously by h/w * @has_hw_ids: Hardware supports finger tracking IDs * */ struct pixcir_i2c_chip_data { u8 max_fingers; bool has_hw_ids; }; struct pixcir_i2c_ts_data { struct i2c_client *client; struct input_dev *input; struct gpio_desc *gpio_attb; struct gpio_desc *gpio_reset; struct gpio_desc *gpio_enable; struct gpio_desc *gpio_wake; const struct pixcir_i2c_chip_data *chip; struct touchscreen_properties prop; bool running; }; struct pixcir_report_data { int num_touches; struct input_mt_pos pos[PIXCIR_MAX_SLOTS]; int ids[PIXCIR_MAX_SLOTS]; }; static void pixcir_ts_parse(struct pixcir_i2c_ts_data *tsdata, struct pixcir_report_data *report) { u8 rdbuf[2 + PIXCIR_MAX_SLOTS * 5]; u8 wrbuf[1] = { 0 }; u8 *bufptr; u8 touch; int ret, i; int readsize; const struct pixcir_i2c_chip_data *chip = tsdata->chip; memset(report, 0, sizeof(struct pixcir_report_data)); i = chip->has_hw_ids ? 1 : 0; readsize = 2 + tsdata->chip->max_fingers * (4 + i); if (readsize > sizeof(rdbuf)) readsize = sizeof(rdbuf); ret = i2c_master_send(tsdata->client, wrbuf, sizeof(wrbuf)); if (ret != sizeof(wrbuf)) { dev_err(&tsdata->client->dev, "%s: i2c_master_send failed(), ret=%d\n", __func__, ret); return; } ret = i2c_master_recv(tsdata->client, rdbuf, readsize); if (ret != readsize) { dev_err(&tsdata->client->dev, "%s: i2c_master_recv failed(), ret=%d\n", __func__, ret); return; } touch = rdbuf[0] & 0x7; if (touch > tsdata->chip->max_fingers) touch = tsdata->chip->max_fingers; report->num_touches = touch; bufptr = &rdbuf[2]; for (i = 0; i < touch; i++) { touchscreen_set_mt_pos(&report->pos[i], &tsdata->prop, get_unaligned_le16(bufptr), get_unaligned_le16(bufptr + 2)); if (chip->has_hw_ids) { report->ids[i] = bufptr[4]; bufptr = bufptr + 5; } else { bufptr = bufptr + 4; } } } static void pixcir_ts_report(struct pixcir_i2c_ts_data *ts, struct pixcir_report_data *report) { int slots[PIXCIR_MAX_SLOTS]; int n, i, slot; struct device *dev = &ts->client->dev; const struct pixcir_i2c_chip_data *chip = ts->chip; n = report->num_touches; if (n > PIXCIR_MAX_SLOTS) n = PIXCIR_MAX_SLOTS; if (!ts->chip->has_hw_ids) input_mt_assign_slots(ts->input, slots, report->pos, n, 0); for (i = 0; i < n; i++) { if (chip->has_hw_ids) { slot = input_mt_get_slot_by_key(ts->input, report->ids[i]); if (slot < 0) { dev_dbg(dev, "no free slot for id 0x%x\n", report->ids[i]); continue; } } else { slot = slots[i]; } input_mt_slot(ts->input, slot); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, true); input_report_abs(ts->input, ABS_MT_POSITION_X, report->pos[i].x); input_report_abs(ts->input, ABS_MT_POSITION_Y, report->pos[i].y); dev_dbg(dev, "%d: slot %d, x %d, y %d\n", i, slot, report->pos[i].x, report->pos[i].y); } input_mt_sync_frame(ts->input); input_sync(ts->input); } static irqreturn_t pixcir_ts_isr(int irq, void *dev_id) { struct pixcir_i2c_ts_data *tsdata = dev_id; struct pixcir_report_data report; while (tsdata->running) { /* parse packet */ pixcir_ts_parse(tsdata, &report); /* report it */ pixcir_ts_report(tsdata, &report); if (gpiod_get_value_cansleep(tsdata->gpio_attb)) { if (report.num_touches) { /* * Last report with no finger up? * Do it now then. */ input_mt_sync_frame(tsdata->input); input_sync(tsdata->input); } break; } msleep(20); } return IRQ_HANDLED; } static void pixcir_reset(struct pixcir_i2c_ts_data *tsdata) { if (!IS_ERR_OR_NULL(tsdata->gpio_reset)) { gpiod_set_value_cansleep(tsdata->gpio_reset, 1); ndelay(100); /* datasheet section 1.2.3 says 80ns min. */ gpiod_set_value_cansleep(tsdata->gpio_reset, 0); /* wait for controller ready. 100ms guess. */ msleep(100); } } static int pixcir_set_power_mode(struct pixcir_i2c_ts_data *ts, enum pixcir_power_mode mode) { struct device *dev = &ts->client->dev; int ret; if (mode == PIXCIR_POWER_ACTIVE || mode == PIXCIR_POWER_IDLE) { if (ts->gpio_wake) gpiod_set_value_cansleep(ts->gpio_wake, 1); } ret = i2c_smbus_read_byte_data(ts->client, PIXCIR_REG_POWER_MODE); if (ret < 0) { dev_err(dev, "%s: can't read reg %d : %d\n", __func__, PIXCIR_REG_POWER_MODE, ret); return ret; } ret &= ~PIXCIR_POWER_MODE_MASK; ret |= mode; /* Always AUTO_IDLE */ ret |= PIXCIR_POWER_ALLOW_IDLE; ret = i2c_smbus_write_byte_data(ts->client, PIXCIR_REG_POWER_MODE, ret); if (ret < 0) { dev_err(dev, "%s: can't write reg %d : %d\n", __func__, PIXCIR_REG_POWER_MODE, ret); return ret; } if (mode == PIXCIR_POWER_HALT) { if (ts->gpio_wake) gpiod_set_value_cansleep(ts->gpio_wake, 0); } return 0; } /* * Set the interrupt mode for the device i.e. ATTB line behaviour * * @polarity : 1 for active high, 0 for active low. */ static int pixcir_set_int_mode(struct pixcir_i2c_ts_data *ts, enum pixcir_int_mode mode, bool polarity) { struct device *dev = &ts->client->dev; int ret; ret = i2c_smbus_read_byte_data(ts->client, PIXCIR_REG_INT_MODE); if (ret < 0) { dev_err(dev, "%s: can't read reg %d : %d\n", __func__, PIXCIR_REG_INT_MODE, ret); return ret; } ret &= ~PIXCIR_INT_MODE_MASK; ret |= mode; if (polarity) ret |= PIXCIR_INT_POL_HIGH; else ret &= ~PIXCIR_INT_POL_HIGH; ret = i2c_smbus_write_byte_data(ts->client, PIXCIR_REG_INT_MODE, ret); if (ret < 0) { dev_err(dev, "%s: can't write reg %d : %d\n", __func__, PIXCIR_REG_INT_MODE, ret); return ret; } return 0; } /* * Enable/disable interrupt generation */ static int pixcir_int_enable(struct pixcir_i2c_ts_data *ts, bool enable) { struct device *dev = &ts->client->dev; int ret; ret = i2c_smbus_read_byte_data(ts->client, PIXCIR_REG_INT_MODE); if (ret < 0) { dev_err(dev, "%s: can't read reg %d : %d\n", __func__, PIXCIR_REG_INT_MODE, ret); return ret; } if (enable) ret |= PIXCIR_INT_ENABLE; else ret &= ~PIXCIR_INT_ENABLE; ret = i2c_smbus_write_byte_data(ts->client, PIXCIR_REG_INT_MODE, ret); if (ret < 0) { dev_err(dev, "%s: can't write reg %d : %d\n", __func__, PIXCIR_REG_INT_MODE, ret); return ret; } return 0; } static int pixcir_start(struct pixcir_i2c_ts_data *ts) { struct device *dev = &ts->client->dev; int error; if (ts->gpio_enable) { gpiod_set_value_cansleep(ts->gpio_enable, 1); msleep(100); } /* LEVEL_TOUCH interrupt with active low polarity */ error = pixcir_set_int_mode(ts, PIXCIR_INT_LEVEL_TOUCH, 0); if (error) { dev_err(dev, "Failed to set interrupt mode: %d\n", error); return error; } ts->running = true; mb(); /* Update status before IRQ can fire */ /* enable interrupt generation */ error = pixcir_int_enable(ts, true); if (error) { dev_err(dev, "Failed to enable interrupt generation: %d\n", error); return error; } return 0; } static int pixcir_stop(struct pixcir_i2c_ts_data *ts) { int error; /* Disable interrupt generation */ error = pixcir_int_enable(ts, false); if (error) { dev_err(&ts->client->dev, "Failed to disable interrupt generation: %d\n", error); return error; } /* Exit ISR if running, no more report parsing */ ts->running = false; mb(); /* update status before we synchronize irq */ /* Wait till running ISR is complete */ synchronize_irq(ts->client->irq); if (ts->gpio_enable) gpiod_set_value_cansleep(ts->gpio_enable, 0); return 0; } static int pixcir_input_open(struct input_dev *dev) { struct pixcir_i2c_ts_data *ts = input_get_drvdata(dev); return pixcir_start(ts); } static void pixcir_input_close(struct input_dev *dev) { struct pixcir_i2c_ts_data *ts = input_get_drvdata(dev); pixcir_stop(ts); } static int pixcir_i2c_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct pixcir_i2c_ts_data *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); if (device_may_wakeup(&client->dev)) { if (!input_device_enabled(input)) { ret = pixcir_start(ts); if (ret) { dev_err(dev, "Failed to start\n"); goto unlock; } } } else if (input_device_enabled(input)) { ret = pixcir_stop(ts); } unlock: mutex_unlock(&input->mutex); return ret; } static int pixcir_i2c_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct pixcir_i2c_ts_data *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); if (device_may_wakeup(&client->dev)) { if (!input_device_enabled(input)) { ret = pixcir_stop(ts); if (ret) { dev_err(dev, "Failed to stop\n"); goto unlock; } } } else if (input_device_enabled(input)) { ret = pixcir_start(ts); } unlock: mutex_unlock(&input->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(pixcir_dev_pm_ops, pixcir_i2c_ts_suspend, pixcir_i2c_ts_resume); static int pixcir_i2c_ts_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct device *dev = &client->dev; struct pixcir_i2c_ts_data *tsdata; struct input_dev *input; int error; tsdata = devm_kzalloc(dev, sizeof(*tsdata), GFP_KERNEL); if (!tsdata) return -ENOMEM; tsdata->chip = device_get_match_data(dev); if (!tsdata->chip && id) tsdata->chip = (const void *)id->driver_data; if (!tsdata->chip) { dev_err(dev, "can't locate chip data\n"); return -EINVAL; } input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } tsdata->client = client; tsdata->input = input; input->name = client->name; input->id.bustype = BUS_I2C; input->open = pixcir_input_open; input->close = pixcir_input_close; input_set_capability(input, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input, EV_ABS, ABS_MT_POSITION_Y); touchscreen_parse_properties(input, true, &tsdata->prop); if (!input_abs_get_max(input, ABS_MT_POSITION_X) || !input_abs_get_max(input, ABS_MT_POSITION_Y)) { dev_err(dev, "Touchscreen size is not specified\n"); return -EINVAL; } error = input_mt_init_slots(input, tsdata->chip->max_fingers, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(dev, "Error initializing Multi-Touch slots\n"); return error; } input_set_drvdata(input, tsdata); tsdata->gpio_attb = devm_gpiod_get(dev, "attb", GPIOD_IN); if (IS_ERR(tsdata->gpio_attb)) return dev_err_probe(dev, PTR_ERR(tsdata->gpio_attb), "Failed to request ATTB gpio\n"); tsdata->gpio_reset = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(tsdata->gpio_reset)) return dev_err_probe(dev, PTR_ERR(tsdata->gpio_reset), "Failed to request RESET gpio\n"); tsdata->gpio_wake = devm_gpiod_get_optional(dev, "wake", GPIOD_OUT_HIGH); if (IS_ERR(tsdata->gpio_wake)) return dev_err_probe(dev, PTR_ERR(tsdata->gpio_wake), "Failed to get wake gpio\n"); tsdata->gpio_enable = devm_gpiod_get_optional(dev, "enable", GPIOD_OUT_HIGH); if (IS_ERR(tsdata->gpio_enable)) return dev_err_probe(dev, PTR_ERR(tsdata->gpio_enable), "Failed to get enable gpio\n"); if (tsdata->gpio_enable) msleep(100); error = devm_request_threaded_irq(dev, client->irq, NULL, pixcir_ts_isr, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, client->name, tsdata); if (error) { dev_err(dev, "failed to request irq %d\n", client->irq); return error; } pixcir_reset(tsdata); /* Always be in IDLE mode to save power, device supports auto wake */ error = pixcir_set_power_mode(tsdata, PIXCIR_POWER_IDLE); if (error) { dev_err(dev, "Failed to set IDLE mode\n"); return error; } /* Stop device till opened */ error = pixcir_stop(tsdata); if (error) return error; error = input_register_device(input); if (error) return error; i2c_set_clientdata(client, tsdata); return 0; } static const struct pixcir_i2c_chip_data pixcir_ts_data = { .max_fingers = 2, /* no hw id support */ }; static const struct pixcir_i2c_chip_data pixcir_tangoc_data = { .max_fingers = 5, .has_hw_ids = true, }; static const struct i2c_device_id pixcir_i2c_ts_id[] = { { "pixcir_ts", (unsigned long) &pixcir_ts_data }, { "pixcir_tangoc", (unsigned long) &pixcir_tangoc_data }, { } }; MODULE_DEVICE_TABLE(i2c, pixcir_i2c_ts_id); #ifdef CONFIG_OF static const struct of_device_id pixcir_of_match[] = { { .compatible = "pixcir,pixcir_ts", .data = &pixcir_ts_data }, { .compatible = "pixcir,pixcir_tangoc", .data = &pixcir_tangoc_data }, { } }; MODULE_DEVICE_TABLE(of, pixcir_of_match); #endif static struct i2c_driver pixcir_i2c_ts_driver = { .driver = { .name = "pixcir_ts", .pm = pm_sleep_ptr(&pixcir_dev_pm_ops), .of_match_table = of_match_ptr(pixcir_of_match), }, .probe = pixcir_i2c_ts_probe, .id_table = pixcir_i2c_ts_id, }; module_i2c_driver(pixcir_i2c_ts_driver); MODULE_AUTHOR("Jianchun Bian <[email protected]>, Dequan Meng <[email protected]>"); MODULE_DESCRIPTION("Pixcir I2C Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/pixcir_i2c_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Fujitsu serial touchscreen driver * * Copyright (c) Dmitry Torokhov <[email protected]> */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #define DRIVER_DESC "Fujitsu serial touchscreen driver" MODULE_AUTHOR("Dmitry Torokhov <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); #define FUJITSU_LENGTH 5 /* * Per-touchscreen data. */ struct fujitsu { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[FUJITSU_LENGTH]; char phys[32]; }; /* * Decode serial data (5 bytes per packet) * First byte * 1 C 0 0 R S S S * Where C is 1 while in calibration mode (which we don't use) * R is 1 when no coordinate corection was done. * S are button state */ static irqreturn_t fujitsu_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct fujitsu *fujitsu = serio_get_drvdata(serio); struct input_dev *dev = fujitsu->dev; if (fujitsu->idx == 0) { /* resync skip until start of frame */ if ((data & 0xf0) != 0x80) return IRQ_HANDLED; } else { /* resync skip garbage */ if (data & 0x80) { fujitsu->idx = 0; return IRQ_HANDLED; } } fujitsu->data[fujitsu->idx++] = data; if (fujitsu->idx == FUJITSU_LENGTH) { input_report_abs(dev, ABS_X, (fujitsu->data[2] << 7) | fujitsu->data[1]); input_report_abs(dev, ABS_Y, (fujitsu->data[4] << 7) | fujitsu->data[3]); input_report_key(dev, BTN_TOUCH, (fujitsu->data[0] & 0x03) != 2); input_sync(dev); fujitsu->idx = 0; } return IRQ_HANDLED; } /* * fujitsu_disconnect() is the opposite of fujitsu_connect() */ static void fujitsu_disconnect(struct serio *serio) { struct fujitsu *fujitsu = serio_get_drvdata(serio); input_get_device(fujitsu->dev); input_unregister_device(fujitsu->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(fujitsu->dev); kfree(fujitsu); } /* * fujitsu_connect() is the routine that is called when someone adds a * new serio device that supports the Fujitsu protocol and registers it * as input device. */ static int fujitsu_connect(struct serio *serio, struct serio_driver *drv) { struct fujitsu *fujitsu; struct input_dev *input_dev; int err; fujitsu = kzalloc(sizeof(struct fujitsu), GFP_KERNEL); input_dev = input_allocate_device(); if (!fujitsu || !input_dev) { err = -ENOMEM; goto fail1; } fujitsu->serio = serio; fujitsu->dev = input_dev; snprintf(fujitsu->phys, sizeof(fujitsu->phys), "%s/input0", serio->phys); input_dev->name = "Fujitsu Serial Touchscreen"; input_dev->phys = fujitsu->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_FUJITSU; input_dev->id.product = 0; input_dev->id.version = 0x0100; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, 4096, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, 4096, 0, 0); serio_set_drvdata(serio, fujitsu); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(fujitsu->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(fujitsu); return err; } /* * The serio driver structure. */ static const struct serio_device_id fujitsu_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_FUJITSU, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, fujitsu_serio_ids); static struct serio_driver fujitsu_drv = { .driver = { .name = "fujitsu_ts", }, .description = DRIVER_DESC, .id_table = fujitsu_serio_ids, .interrupt = fujitsu_interrupt, .connect = fujitsu_connect, .disconnect = fujitsu_disconnect, }; module_serio_driver(fujitsu_drv);
linux-master
drivers/input/touchscreen/fujitsu_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/input/touchscreen/tsc2007.c * * Copyright (c) 2008 MtekVision Co., Ltd. * Kwangwoo Lee <[email protected]> * * Using code from: * - ads7846.c * Copyright (c) 2005 David Brownell * Copyright (c) 2006 Nokia Corporation * - corgi_ts.c * Copyright (C) 2004-2005 Richard Purdie * - omap_ts.[hc], ads7846.h, ts_osk.c * Copyright (C) 2002 MontaVista Software * Copyright (C) 2004 Texas Instruments * Copyright (C) 2005 Dirk Behme */ #include <linux/module.h> #include <linux/slab.h> #include <linux/gpio/consumer.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/mod_devicetable.h> #include <linux/property.h> #include <linux/platform_data/tsc2007.h> #include "tsc2007.h" int tsc2007_xfer(struct tsc2007 *tsc, u8 cmd) { s32 data; u16 val; data = i2c_smbus_read_word_data(tsc->client, cmd); if (data < 0) { dev_err(&tsc->client->dev, "i2c io error: %d\n", data); return data; } /* The protocol and raw data format from i2c interface: * S Addr Wr [A] Comm [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P * Where DataLow has [D11-D4], DataHigh has [D3-D0 << 4 | Dummy 4bit]. */ val = swab16(data) >> 4; dev_dbg(&tsc->client->dev, "data: 0x%x, val: 0x%x\n", data, val); return val; } static void tsc2007_read_values(struct tsc2007 *tsc, struct ts_event *tc) { /* y- still on; turn on only y+ (and ADC) */ tc->y = tsc2007_xfer(tsc, READ_Y); /* turn y- off, x+ on, then leave in lowpower */ tc->x = tsc2007_xfer(tsc, READ_X); /* turn y+ off, x- on; we'll use formula #1 */ tc->z1 = tsc2007_xfer(tsc, READ_Z1); tc->z2 = tsc2007_xfer(tsc, READ_Z2); /* Prepare for next touch reading - power down ADC, enable PENIRQ */ tsc2007_xfer(tsc, PWRDOWN); } u32 tsc2007_calculate_resistance(struct tsc2007 *tsc, struct ts_event *tc) { u32 rt = 0; /* range filtering */ if (tc->x == MAX_12BIT) tc->x = 0; if (likely(tc->x && tc->z1)) { /* compute touch resistance using equation #1 */ rt = tc->z2 - tc->z1; rt *= tc->x; rt *= tsc->x_plate_ohms; rt /= tc->z1; rt = (rt + 2047) >> 12; } return rt; } bool tsc2007_is_pen_down(struct tsc2007 *ts) { /* * NOTE: We can't rely on the pressure to determine the pen down * state, even though this controller has a pressure sensor. * The pressure value can fluctuate for quite a while after * lifting the pen and in some cases may not even settle at the * expected value. * * The only safe way to check for the pen up condition is in the * work function by reading the pen signal state (it's a GPIO * and IRQ). Unfortunately such callback is not always available, * in that case we assume that the pen is down and expect caller * to fall back on the pressure reading. */ if (!ts->get_pendown_state) return true; return ts->get_pendown_state(&ts->client->dev); } static irqreturn_t tsc2007_soft_irq(int irq, void *handle) { struct tsc2007 *ts = handle; struct input_dev *input = ts->input; struct ts_event tc; u32 rt; while (!ts->stopped && tsc2007_is_pen_down(ts)) { /* pen is down, continue with the measurement */ mutex_lock(&ts->mlock); tsc2007_read_values(ts, &tc); mutex_unlock(&ts->mlock); rt = tsc2007_calculate_resistance(ts, &tc); if (!rt && !ts->get_pendown_state) { /* * If pressure reported is 0 and we don't have * callback to check pendown state, we have to * assume that pen was lifted up. */ break; } if (rt <= ts->max_rt) { dev_dbg(&ts->client->dev, "DOWN point(%4d,%4d), resistance (%4u)\n", tc.x, tc.y, rt); rt = ts->max_rt - rt; input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, tc.x); input_report_abs(input, ABS_Y, tc.y); input_report_abs(input, ABS_PRESSURE, rt); input_sync(input); } else { /* * Sample found inconsistent by debouncing or pressure is * beyond the maximum. Don't report it to user space, * repeat at least once more the measurement. */ dev_dbg(&ts->client->dev, "ignored pressure %d\n", rt); } wait_event_timeout(ts->wait, ts->stopped, ts->poll_period); } dev_dbg(&ts->client->dev, "UP\n"); input_report_key(input, BTN_TOUCH, 0); input_report_abs(input, ABS_PRESSURE, 0); input_sync(input); if (ts->clear_penirq) ts->clear_penirq(); return IRQ_HANDLED; } static void tsc2007_stop(struct tsc2007 *ts) { ts->stopped = true; mb(); wake_up(&ts->wait); disable_irq(ts->irq); } static int tsc2007_open(struct input_dev *input_dev) { struct tsc2007 *ts = input_get_drvdata(input_dev); int err; ts->stopped = false; mb(); enable_irq(ts->irq); /* Prepare for touch readings - power down ADC and enable PENIRQ */ err = tsc2007_xfer(ts, PWRDOWN); if (err < 0) { tsc2007_stop(ts); return err; } return 0; } static void tsc2007_close(struct input_dev *input_dev) { struct tsc2007 *ts = input_get_drvdata(input_dev); tsc2007_stop(ts); } static int tsc2007_get_pendown_state_gpio(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct tsc2007 *ts = i2c_get_clientdata(client); return gpiod_get_value_cansleep(ts->gpiod); } static int tsc2007_probe_properties(struct device *dev, struct tsc2007 *ts) { u32 val32; u64 val64; if (!device_property_read_u32(dev, "ti,max-rt", &val32)) ts->max_rt = val32; else ts->max_rt = MAX_12BIT; if (!device_property_read_u32(dev, "ti,fuzzx", &val32)) ts->fuzzx = val32; if (!device_property_read_u32(dev, "ti,fuzzy", &val32)) ts->fuzzy = val32; if (!device_property_read_u32(dev, "ti,fuzzz", &val32)) ts->fuzzz = val32; if (!device_property_read_u64(dev, "ti,poll-period", &val64)) ts->poll_period = msecs_to_jiffies(val64); else ts->poll_period = msecs_to_jiffies(1); if (!device_property_read_u32(dev, "ti,x-plate-ohms", &val32)) { ts->x_plate_ohms = val32; } else { dev_err(dev, "Missing ti,x-plate-ohms device property\n"); return -EINVAL; } ts->gpiod = devm_gpiod_get_optional(dev, NULL, GPIOD_IN); if (IS_ERR(ts->gpiod)) return PTR_ERR(ts->gpiod); if (ts->gpiod) ts->get_pendown_state = tsc2007_get_pendown_state_gpio; else dev_warn(dev, "Pen down GPIO is not specified in properties\n"); return 0; } static int tsc2007_probe_pdev(struct device *dev, struct tsc2007 *ts, const struct tsc2007_platform_data *pdata, const struct i2c_device_id *id) { ts->model = pdata->model; ts->x_plate_ohms = pdata->x_plate_ohms; ts->max_rt = pdata->max_rt ? : MAX_12BIT; ts->poll_period = msecs_to_jiffies(pdata->poll_period ? : 1); ts->get_pendown_state = pdata->get_pendown_state; ts->clear_penirq = pdata->clear_penirq; ts->fuzzx = pdata->fuzzx; ts->fuzzy = pdata->fuzzy; ts->fuzzz = pdata->fuzzz; if (pdata->x_plate_ohms == 0) { dev_err(dev, "x_plate_ohms is not set up in platform data\n"); return -EINVAL; } return 0; } static void tsc2007_call_exit_platform_hw(void *data) { struct device *dev = data; const struct tsc2007_platform_data *pdata = dev_get_platdata(dev); pdata->exit_platform_hw(); } static int tsc2007_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); const struct tsc2007_platform_data *pdata = dev_get_platdata(&client->dev); struct tsc2007 *ts; struct input_dev *input_dev; int err; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) return -EIO; ts = devm_kzalloc(&client->dev, sizeof(struct tsc2007), GFP_KERNEL); if (!ts) return -ENOMEM; if (pdata) err = tsc2007_probe_pdev(&client->dev, ts, pdata, id); else err = tsc2007_probe_properties(&client->dev, ts); if (err) return err; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) return -ENOMEM; i2c_set_clientdata(client, ts); ts->client = client; ts->irq = client->irq; ts->input = input_dev; init_waitqueue_head(&ts->wait); mutex_init(&ts->mlock); snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); input_dev->name = "TSC2007 Touchscreen"; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_I2C; input_dev->open = tsc2007_open; input_dev->close = tsc2007_close; input_set_drvdata(input_dev, ts); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_12BIT, ts->fuzzx, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, ts->fuzzy, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, MAX_12BIT, ts->fuzzz, 0); if (pdata) { if (pdata->exit_platform_hw) { err = devm_add_action(&client->dev, tsc2007_call_exit_platform_hw, &client->dev); if (err) { dev_err(&client->dev, "Failed to register exit_platform_hw action, %d\n", err); return err; } } if (pdata->init_platform_hw) pdata->init_platform_hw(); } err = devm_request_threaded_irq(&client->dev, ts->irq, NULL, tsc2007_soft_irq, IRQF_ONESHOT, client->dev.driver->name, ts); if (err) { dev_err(&client->dev, "Failed to request irq %d: %d\n", ts->irq, err); return err; } tsc2007_stop(ts); /* power down the chip (TSC2007_SETUP does not ACK on I2C) */ err = tsc2007_xfer(ts, PWRDOWN); if (err < 0) { dev_err(&client->dev, "Failed to setup chip: %d\n", err); return err; /* chip does not respond */ } err = input_register_device(input_dev); if (err) { dev_err(&client->dev, "Failed to register input device: %d\n", err); return err; } err = tsc2007_iio_configure(ts); if (err) { dev_err(&client->dev, "Failed to register with IIO: %d\n", err); return err; } return 0; } static const struct i2c_device_id tsc2007_idtable[] = { { "tsc2007", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tsc2007_idtable); static const struct of_device_id tsc2007_of_match[] = { { .compatible = "ti,tsc2007" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, tsc2007_of_match); static struct i2c_driver tsc2007_driver = { .driver = { .name = "tsc2007", .of_match_table = tsc2007_of_match, }, .id_table = tsc2007_idtable, .probe = tsc2007_probe, }; module_i2c_driver(tsc2007_driver); MODULE_AUTHOR("Kwangwoo Lee <[email protected]>"); MODULE_DESCRIPTION("TSC2007 TouchScreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/tsc2007_core.c
/* * Touchscreen driver for the tps6507x chip. * * Copyright (c) 2009 RidgeRun ([email protected]) * * Credits: * * Using code from tsc2007, MtekVision Co., Ltd. * * For licencing details see kernel-base/COPYING * * TPS65070, TPS65073, TPS650731, and TPS650732 support * 10 bit touch screen interface. */ #include <linux/module.h> #include <linux/workqueue.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/platform_device.h> #include <linux/mfd/tps6507x.h> #include <linux/input/tps6507x-ts.h> #include <linux/delay.h> #define TSC_DEFAULT_POLL_PERIOD 30 /* ms */ #define TPS_DEFAULT_MIN_PRESSURE 0x30 #define MAX_10BIT ((1 << 10) - 1) #define TPS6507X_ADCONFIG_CONVERT_TS (TPS6507X_ADCONFIG_AD_ENABLE | \ TPS6507X_ADCONFIG_START_CONVERSION | \ TPS6507X_ADCONFIG_INPUT_REAL_TSC) #define TPS6507X_ADCONFIG_POWER_DOWN_TS (TPS6507X_ADCONFIG_INPUT_REAL_TSC) struct ts_event { u16 x; u16 y; u16 pressure; }; struct tps6507x_ts { struct device *dev; struct input_dev *input; struct tps6507x_dev *mfd; char phys[32]; struct ts_event tc; u16 min_pressure; bool pendown; }; static int tps6507x_read_u8(struct tps6507x_ts *tsc, u8 reg, u8 *data) { return tsc->mfd->read_dev(tsc->mfd, reg, 1, data); } static int tps6507x_write_u8(struct tps6507x_ts *tsc, u8 reg, u8 data) { return tsc->mfd->write_dev(tsc->mfd, reg, 1, &data); } static s32 tps6507x_adc_conversion(struct tps6507x_ts *tsc, u8 tsc_mode, u16 *value) { s32 ret; u8 adc_status; u8 result; /* Route input signal to A/D converter */ ret = tps6507x_write_u8(tsc, TPS6507X_REG_TSCMODE, tsc_mode); if (ret) { dev_err(tsc->dev, "TSC mode read failed\n"); goto err; } /* Start A/D conversion */ ret = tps6507x_write_u8(tsc, TPS6507X_REG_ADCONFIG, TPS6507X_ADCONFIG_CONVERT_TS); if (ret) { dev_err(tsc->dev, "ADC config write failed\n"); return ret; } do { ret = tps6507x_read_u8(tsc, TPS6507X_REG_ADCONFIG, &adc_status); if (ret) { dev_err(tsc->dev, "ADC config read failed\n"); goto err; } } while (adc_status & TPS6507X_ADCONFIG_START_CONVERSION); ret = tps6507x_read_u8(tsc, TPS6507X_REG_ADRESULT_2, &result); if (ret) { dev_err(tsc->dev, "ADC result 2 read failed\n"); goto err; } *value = (result & TPS6507X_REG_ADRESULT_2_MASK) << 8; ret = tps6507x_read_u8(tsc, TPS6507X_REG_ADRESULT_1, &result); if (ret) { dev_err(tsc->dev, "ADC result 1 read failed\n"); goto err; } *value |= result; dev_dbg(tsc->dev, "TSC channel %d = 0x%X\n", tsc_mode, *value); err: return ret; } /* Need to call tps6507x_adc_standby() after using A/D converter for the * touch screen interrupt to work properly. */ static s32 tps6507x_adc_standby(struct tps6507x_ts *tsc) { s32 ret; u8 val; ret = tps6507x_write_u8(tsc, TPS6507X_REG_ADCONFIG, TPS6507X_ADCONFIG_INPUT_TSC); if (ret) return ret; ret = tps6507x_write_u8(tsc, TPS6507X_REG_TSCMODE, TPS6507X_TSCMODE_STANDBY); if (ret) return ret; ret = tps6507x_read_u8(tsc, TPS6507X_REG_INT, &val); if (ret) return ret; while (val & TPS6507X_REG_TSC_INT) { mdelay(10); ret = tps6507x_read_u8(tsc, TPS6507X_REG_INT, &val); if (ret) return ret; } return ret; } static void tps6507x_ts_poll(struct input_dev *input_dev) { struct tps6507x_ts *tsc = input_get_drvdata(input_dev); bool pendown; s32 ret; ret = tps6507x_adc_conversion(tsc, TPS6507X_TSCMODE_PRESSURE, &tsc->tc.pressure); if (ret) goto done; pendown = tsc->tc.pressure > tsc->min_pressure; if (unlikely(!pendown && tsc->pendown)) { dev_dbg(tsc->dev, "UP\n"); input_report_key(input_dev, BTN_TOUCH, 0); input_report_abs(input_dev, ABS_PRESSURE, 0); input_sync(input_dev); tsc->pendown = false; } if (pendown) { if (!tsc->pendown) { dev_dbg(tsc->dev, "DOWN\n"); input_report_key(input_dev, BTN_TOUCH, 1); } else dev_dbg(tsc->dev, "still down\n"); ret = tps6507x_adc_conversion(tsc, TPS6507X_TSCMODE_X_POSITION, &tsc->tc.x); if (ret) goto done; ret = tps6507x_adc_conversion(tsc, TPS6507X_TSCMODE_Y_POSITION, &tsc->tc.y); if (ret) goto done; input_report_abs(input_dev, ABS_X, tsc->tc.x); input_report_abs(input_dev, ABS_Y, tsc->tc.y); input_report_abs(input_dev, ABS_PRESSURE, tsc->tc.pressure); input_sync(input_dev); tsc->pendown = true; } done: tps6507x_adc_standby(tsc); } static int tps6507x_ts_probe(struct platform_device *pdev) { struct tps6507x_dev *tps6507x_dev = dev_get_drvdata(pdev->dev.parent); const struct tps6507x_board *tps_board; const struct touchscreen_init_data *init_data; struct tps6507x_ts *tsc; struct input_dev *input_dev; int error; /* * tps_board points to pmic related constants * coming from the board-evm file. */ tps_board = dev_get_platdata(tps6507x_dev->dev); if (!tps_board) { dev_err(tps6507x_dev->dev, "Could not find tps6507x platform data\n"); return -ENODEV; } /* * init_data points to array of regulator_init structures * coming from the board-evm file. */ init_data = tps_board->tps6507x_ts_init_data; tsc = devm_kzalloc(&pdev->dev, sizeof(struct tps6507x_ts), GFP_KERNEL); if (!tsc) { dev_err(tps6507x_dev->dev, "failed to allocate driver data\n"); return -ENOMEM; } tsc->mfd = tps6507x_dev; tsc->dev = tps6507x_dev->dev; tsc->min_pressure = init_data ? init_data->min_pressure : TPS_DEFAULT_MIN_PRESSURE; snprintf(tsc->phys, sizeof(tsc->phys), "%s/input0", dev_name(tsc->dev)); input_dev = devm_input_allocate_device(&pdev->dev); if (!input_dev) { dev_err(tsc->dev, "Failed to allocate polled input device.\n"); return -ENOMEM; } tsc->input = input_dev; input_set_drvdata(input_dev, tsc); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_10BIT, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_10BIT, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, MAX_10BIT, 0, 0); input_dev->name = "TPS6507x Touchscreen"; input_dev->phys = tsc->phys; input_dev->dev.parent = tsc->dev; input_dev->id.bustype = BUS_I2C; if (init_data) { input_dev->id.vendor = init_data->vendor; input_dev->id.product = init_data->product; input_dev->id.version = init_data->version; } error = tps6507x_adc_standby(tsc); if (error) return error; error = input_setup_polling(input_dev, tps6507x_ts_poll); if (error) return error; input_set_poll_interval(input_dev, init_data ? init_data->poll_period : TSC_DEFAULT_POLL_PERIOD); error = input_register_device(input_dev); if (error) return error; return 0; } static struct platform_driver tps6507x_ts_driver = { .driver = { .name = "tps6507x-ts", }, .probe = tps6507x_ts_probe, }; module_platform_driver(tps6507x_ts_driver); MODULE_AUTHOR("Todd Fischer <[email protected]>"); MODULE_DESCRIPTION("TPS6507x - TouchScreen driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:tps6507x-ts");
linux-master
drivers/input/touchscreen/tps6507x-ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * usbtouchscreen.c * Driver for USB Touchscreens, supporting those devices: * - eGalax Touchkit * includes eTurboTouch CT-410/510/700 * - 3M/Microtouch EX II series * - ITM * - PanJit TouchSet * - eTurboTouch * - Gunze AHL61 * - DMC TSC-10/25 * - IRTOUCHSYSTEMS/UNITOP * - IdealTEK URTC1000 * - General Touch * - GoTop Super_Q2/GogoPen/PenPower tablets * - JASTEC USB touch controller/DigiTech DTR-02U * - Zytronic capacitive touchscreen * - NEXIO/iNexio * - Elo TouchSystems 2700 IntelliTouch * - EasyTouch USB Dual/Multi touch controller from Data Modul * * Copyright (C) 2004-2007 by Daniel Ritz <[email protected]> * Copyright (C) by Todd E. Johnson (mtouchusb.c) * * Driver is based on touchkitusb.c * - ITM parts are from itmtouch.c * - 3M parts are from mtouchusb.c * - PanJit parts are from an unmerged driver by Lanslott Gish * - DMC TSC 10/25 are from Holger Schurig, with ideas from an unmerged * driver from Marius Vollmer * *****************************************************************************/ //#define DEBUG #include <linux/kernel.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/module.h> #include <linux/usb.h> #include <linux/usb/input.h> #include <linux/hid.h> #include <linux/mutex.h> static bool swap_xy; module_param(swap_xy, bool, 0644); MODULE_PARM_DESC(swap_xy, "If set X and Y axes are swapped."); static bool hwcalib_xy; module_param(hwcalib_xy, bool, 0644); MODULE_PARM_DESC(hwcalib_xy, "If set hw-calibrated X/Y are used if available"); /* device specifc data/functions */ struct usbtouch_usb; struct usbtouch_device_info { int min_xc, max_xc; int min_yc, max_yc; int min_press, max_press; int rept_size; /* * Always service the USB devices irq not just when the input device is * open. This is useful when devices have a watchdog which prevents us * from periodically polling the device. Leave this unset unless your * touchscreen device requires it, as it does consume more of the USB * bandwidth. */ bool irq_always; void (*process_pkt) (struct usbtouch_usb *usbtouch, unsigned char *pkt, int len); /* * used to get the packet len. possible return values: * > 0: packet len * = 0: skip one byte * < 0: -return value more bytes needed */ int (*get_pkt_len) (unsigned char *pkt, int len); int (*read_data) (struct usbtouch_usb *usbtouch, unsigned char *pkt); int (*alloc) (struct usbtouch_usb *usbtouch); int (*init) (struct usbtouch_usb *usbtouch); void (*exit) (struct usbtouch_usb *usbtouch); }; /* a usbtouch device */ struct usbtouch_usb { unsigned char *data; dma_addr_t data_dma; int data_size; unsigned char *buffer; int buf_len; struct urb *irq; struct usb_interface *interface; struct input_dev *input; struct usbtouch_device_info *type; struct mutex pm_mutex; /* serialize access to open/suspend */ bool is_open; char name[128]; char phys[64]; void *priv; int x, y; int touch, press; }; /* device types */ enum { DEVTYPE_IGNORE = -1, DEVTYPE_EGALAX, DEVTYPE_PANJIT, DEVTYPE_3M, DEVTYPE_ITM, DEVTYPE_ETURBO, DEVTYPE_GUNZE, DEVTYPE_DMC_TSC10, DEVTYPE_IRTOUCH, DEVTYPE_IRTOUCH_HIRES, DEVTYPE_IDEALTEK, DEVTYPE_GENERAL_TOUCH, DEVTYPE_GOTOP, DEVTYPE_JASTEC, DEVTYPE_E2I, DEVTYPE_ZYTRONIC, DEVTYPE_TC45USB, DEVTYPE_NEXIO, DEVTYPE_ELO, DEVTYPE_ETOUCH, }; #define USB_DEVICE_HID_CLASS(vend, prod) \ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS \ | USB_DEVICE_ID_MATCH_DEVICE, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceClass = USB_INTERFACE_CLASS_HID static const struct usb_device_id usbtouch_devices[] = { #ifdef CONFIG_TOUCHSCREEN_USB_EGALAX /* ignore the HID capable devices, handled by usbhid */ {USB_DEVICE_HID_CLASS(0x0eef, 0x0001), .driver_info = DEVTYPE_IGNORE}, {USB_DEVICE_HID_CLASS(0x0eef, 0x0002), .driver_info = DEVTYPE_IGNORE}, /* normal device IDs */ {USB_DEVICE(0x3823, 0x0001), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x3823, 0x0002), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x0123, 0x0001), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x0eef, 0x0001), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x0eef, 0x0002), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x1234, 0x0001), .driver_info = DEVTYPE_EGALAX}, {USB_DEVICE(0x1234, 0x0002), .driver_info = DEVTYPE_EGALAX}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_PANJIT {USB_DEVICE(0x134c, 0x0001), .driver_info = DEVTYPE_PANJIT}, {USB_DEVICE(0x134c, 0x0002), .driver_info = DEVTYPE_PANJIT}, {USB_DEVICE(0x134c, 0x0003), .driver_info = DEVTYPE_PANJIT}, {USB_DEVICE(0x134c, 0x0004), .driver_info = DEVTYPE_PANJIT}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_3M {USB_DEVICE(0x0596, 0x0001), .driver_info = DEVTYPE_3M}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ITM {USB_DEVICE(0x0403, 0xf9e9), .driver_info = DEVTYPE_ITM}, {USB_DEVICE(0x16e3, 0xf9e9), .driver_info = DEVTYPE_ITM}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ETURBO {USB_DEVICE(0x1234, 0x5678), .driver_info = DEVTYPE_ETURBO}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GUNZE {USB_DEVICE(0x0637, 0x0001), .driver_info = DEVTYPE_GUNZE}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_DMC_TSC10 {USB_DEVICE(0x0afa, 0x03e8), .driver_info = DEVTYPE_DMC_TSC10}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_IRTOUCH {USB_DEVICE(0x255e, 0x0001), .driver_info = DEVTYPE_IRTOUCH}, {USB_DEVICE(0x595a, 0x0001), .driver_info = DEVTYPE_IRTOUCH}, {USB_DEVICE(0x6615, 0x0001), .driver_info = DEVTYPE_IRTOUCH}, {USB_DEVICE(0x6615, 0x0012), .driver_info = DEVTYPE_IRTOUCH_HIRES}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_IDEALTEK {USB_DEVICE(0x1391, 0x1000), .driver_info = DEVTYPE_IDEALTEK}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GENERAL_TOUCH {USB_DEVICE(0x0dfc, 0x0001), .driver_info = DEVTYPE_GENERAL_TOUCH}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GOTOP {USB_DEVICE(0x08f2, 0x007f), .driver_info = DEVTYPE_GOTOP}, {USB_DEVICE(0x08f2, 0x00ce), .driver_info = DEVTYPE_GOTOP}, {USB_DEVICE(0x08f2, 0x00f4), .driver_info = DEVTYPE_GOTOP}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_JASTEC {USB_DEVICE(0x0f92, 0x0001), .driver_info = DEVTYPE_JASTEC}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_E2I {USB_DEVICE(0x1ac7, 0x0001), .driver_info = DEVTYPE_E2I}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ZYTRONIC {USB_DEVICE(0x14c8, 0x0003), .driver_info = DEVTYPE_ZYTRONIC}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ETT_TC45USB /* TC5UH */ {USB_DEVICE(0x0664, 0x0309), .driver_info = DEVTYPE_TC45USB}, /* TC4UM */ {USB_DEVICE(0x0664, 0x0306), .driver_info = DEVTYPE_TC45USB}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_NEXIO /* data interface only */ {USB_DEVICE_AND_INTERFACE_INFO(0x10f0, 0x2002, 0x0a, 0x00, 0x00), .driver_info = DEVTYPE_NEXIO}, {USB_DEVICE_AND_INTERFACE_INFO(0x1870, 0x0001, 0x0a, 0x00, 0x00), .driver_info = DEVTYPE_NEXIO}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ELO {USB_DEVICE(0x04e7, 0x0020), .driver_info = DEVTYPE_ELO}, #endif #ifdef CONFIG_TOUCHSCREEN_USB_EASYTOUCH {USB_DEVICE(0x7374, 0x0001), .driver_info = DEVTYPE_ETOUCH}, #endif {} }; /***************************************************************************** * e2i Part */ #ifdef CONFIG_TOUCHSCREEN_USB_E2I static int e2i_init(struct usbtouch_usb *usbtouch) { int ret; struct usb_device *udev = interface_to_usbdev(usbtouch->interface); ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x01, 0x02, 0x0000, 0x0081, NULL, 0, USB_CTRL_SET_TIMEOUT); dev_dbg(&usbtouch->interface->dev, "%s - usb_control_msg - E2I_RESET - bytes|err: %d\n", __func__, ret); return ret; } static int e2i_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { int tmp = (pkt[0] << 8) | pkt[1]; dev->x = (pkt[2] << 8) | pkt[3]; dev->y = (pkt[4] << 8) | pkt[5]; tmp = tmp - 0xA000; dev->touch = (tmp > 0); dev->press = (tmp > 0 ? tmp : 0); return 1; } #endif /***************************************************************************** * eGalax part */ #ifdef CONFIG_TOUCHSCREEN_USB_EGALAX #ifndef MULTI_PACKET #define MULTI_PACKET #endif #define EGALAX_PKT_TYPE_MASK 0xFE #define EGALAX_PKT_TYPE_REPT 0x80 #define EGALAX_PKT_TYPE_DIAG 0x0A static int egalax_init(struct usbtouch_usb *usbtouch) { int ret, i; unsigned char *buf; struct usb_device *udev = interface_to_usbdev(usbtouch->interface); /* * An eGalax diagnostic packet kicks the device into using the right * protocol. We send a "check active" packet. The response will be * read later and ignored. */ buf = kmalloc(3, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = EGALAX_PKT_TYPE_DIAG; buf[1] = 1; /* length */ buf[2] = 'A'; /* command - check active */ for (i = 0; i < 3; i++) { ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, buf, 3, USB_CTRL_SET_TIMEOUT); if (ret >= 0) { ret = 0; break; } if (ret != -EPIPE) break; } kfree(buf); return ret; } static int egalax_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { if ((pkt[0] & EGALAX_PKT_TYPE_MASK) != EGALAX_PKT_TYPE_REPT) return 0; dev->x = ((pkt[3] & 0x0F) << 7) | (pkt[4] & 0x7F); dev->y = ((pkt[1] & 0x0F) << 7) | (pkt[2] & 0x7F); dev->touch = pkt[0] & 0x01; return 1; } static int egalax_get_pkt_len(unsigned char *buf, int len) { switch (buf[0] & EGALAX_PKT_TYPE_MASK) { case EGALAX_PKT_TYPE_REPT: return 5; case EGALAX_PKT_TYPE_DIAG: if (len < 2) return -1; return buf[1] + 2; } return 0; } #endif /***************************************************************************** * EasyTouch part */ #ifdef CONFIG_TOUCHSCREEN_USB_EASYTOUCH #ifndef MULTI_PACKET #define MULTI_PACKET #endif #define ETOUCH_PKT_TYPE_MASK 0xFE #define ETOUCH_PKT_TYPE_REPT 0x80 #define ETOUCH_PKT_TYPE_REPT2 0xB0 #define ETOUCH_PKT_TYPE_DIAG 0x0A static int etouch_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { if ((pkt[0] & ETOUCH_PKT_TYPE_MASK) != ETOUCH_PKT_TYPE_REPT && (pkt[0] & ETOUCH_PKT_TYPE_MASK) != ETOUCH_PKT_TYPE_REPT2) return 0; dev->x = ((pkt[1] & 0x1F) << 7) | (pkt[2] & 0x7F); dev->y = ((pkt[3] & 0x1F) << 7) | (pkt[4] & 0x7F); dev->touch = pkt[0] & 0x01; return 1; } static int etouch_get_pkt_len(unsigned char *buf, int len) { switch (buf[0] & ETOUCH_PKT_TYPE_MASK) { case ETOUCH_PKT_TYPE_REPT: case ETOUCH_PKT_TYPE_REPT2: return 5; case ETOUCH_PKT_TYPE_DIAG: if (len < 2) return -1; return buf[1] + 2; } return 0; } #endif /***************************************************************************** * PanJit Part */ #ifdef CONFIG_TOUCHSCREEN_USB_PANJIT static int panjit_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = ((pkt[2] & 0x0F) << 8) | pkt[1]; dev->y = ((pkt[4] & 0x0F) << 8) | pkt[3]; dev->touch = pkt[0] & 0x01; return 1; } #endif /***************************************************************************** * 3M/Microtouch Part */ #ifdef CONFIG_TOUCHSCREEN_USB_3M #define MTOUCHUSB_ASYNC_REPORT 1 #define MTOUCHUSB_RESET 7 #define MTOUCHUSB_REQ_CTRLLR_ID 10 #define MTOUCHUSB_REQ_CTRLLR_ID_LEN 16 static int mtouch_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { if (hwcalib_xy) { dev->x = (pkt[4] << 8) | pkt[3]; dev->y = 0xffff - ((pkt[6] << 8) | pkt[5]); } else { dev->x = (pkt[8] << 8) | pkt[7]; dev->y = (pkt[10] << 8) | pkt[9]; } dev->touch = (pkt[2] & 0x40) ? 1 : 0; return 1; } struct mtouch_priv { u8 fw_rev_major; u8 fw_rev_minor; }; static ssize_t mtouch_firmware_rev_show(struct device *dev, struct device_attribute *attr, char *output) { struct usb_interface *intf = to_usb_interface(dev); struct usbtouch_usb *usbtouch = usb_get_intfdata(intf); struct mtouch_priv *priv = usbtouch->priv; return scnprintf(output, PAGE_SIZE, "%1x.%1x\n", priv->fw_rev_major, priv->fw_rev_minor); } static DEVICE_ATTR(firmware_rev, 0444, mtouch_firmware_rev_show, NULL); static struct attribute *mtouch_attrs[] = { &dev_attr_firmware_rev.attr, NULL }; static const struct attribute_group mtouch_attr_group = { .attrs = mtouch_attrs, }; static int mtouch_get_fw_revision(struct usbtouch_usb *usbtouch) { struct usb_device *udev = interface_to_usbdev(usbtouch->interface); struct mtouch_priv *priv = usbtouch->priv; u8 *buf; int ret; buf = kzalloc(MTOUCHUSB_REQ_CTRLLR_ID_LEN, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), MTOUCHUSB_REQ_CTRLLR_ID, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, buf, MTOUCHUSB_REQ_CTRLLR_ID_LEN, USB_CTRL_SET_TIMEOUT); if (ret != MTOUCHUSB_REQ_CTRLLR_ID_LEN) { dev_warn(&usbtouch->interface->dev, "Failed to read FW rev: %d\n", ret); ret = ret < 0 ? ret : -EIO; goto free; } priv->fw_rev_major = buf[3]; priv->fw_rev_minor = buf[4]; ret = 0; free: kfree(buf); return ret; } static int mtouch_alloc(struct usbtouch_usb *usbtouch) { int ret; usbtouch->priv = kmalloc(sizeof(struct mtouch_priv), GFP_KERNEL); if (!usbtouch->priv) return -ENOMEM; ret = sysfs_create_group(&usbtouch->interface->dev.kobj, &mtouch_attr_group); if (ret) { kfree(usbtouch->priv); usbtouch->priv = NULL; return ret; } return 0; } static int mtouch_init(struct usbtouch_usb *usbtouch) { int ret, i; struct usb_device *udev = interface_to_usbdev(usbtouch->interface); ret = mtouch_get_fw_revision(usbtouch); if (ret) return ret; ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), MTOUCHUSB_RESET, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 1, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); dev_dbg(&usbtouch->interface->dev, "%s - usb_control_msg - MTOUCHUSB_RESET - bytes|err: %d\n", __func__, ret); if (ret < 0) return ret; msleep(150); for (i = 0; i < 3; i++) { ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), MTOUCHUSB_ASYNC_REPORT, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 1, 1, NULL, 0, USB_CTRL_SET_TIMEOUT); dev_dbg(&usbtouch->interface->dev, "%s - usb_control_msg - MTOUCHUSB_ASYNC_REPORT - bytes|err: %d\n", __func__, ret); if (ret >= 0) break; if (ret != -EPIPE) return ret; } /* Default min/max xy are the raw values, override if using hw-calib */ if (hwcalib_xy) { input_set_abs_params(usbtouch->input, ABS_X, 0, 0xffff, 0, 0); input_set_abs_params(usbtouch->input, ABS_Y, 0, 0xffff, 0, 0); } return 0; } static void mtouch_exit(struct usbtouch_usb *usbtouch) { struct mtouch_priv *priv = usbtouch->priv; sysfs_remove_group(&usbtouch->interface->dev.kobj, &mtouch_attr_group); kfree(priv); } #endif /***************************************************************************** * ITM Part */ #ifdef CONFIG_TOUCHSCREEN_USB_ITM static int itm_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { int touch; /* * ITM devices report invalid x/y data if not touched. * if the screen was touched before but is not touched any more * report touch as 0 with the last valid x/y data once. then stop * reporting data until touched again. */ dev->press = ((pkt[2] & 0x01) << 7) | (pkt[5] & 0x7F); touch = ~pkt[7] & 0x20; if (!touch) { if (dev->touch) { dev->touch = 0; return 1; } return 0; } dev->x = ((pkt[0] & 0x1F) << 7) | (pkt[3] & 0x7F); dev->y = ((pkt[1] & 0x1F) << 7) | (pkt[4] & 0x7F); dev->touch = touch; return 1; } #endif /***************************************************************************** * eTurboTouch part */ #ifdef CONFIG_TOUCHSCREEN_USB_ETURBO #ifndef MULTI_PACKET #define MULTI_PACKET #endif static int eturbo_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { unsigned int shift; /* packets should start with sync */ if (!(pkt[0] & 0x80)) return 0; shift = (6 - (pkt[0] & 0x03)); dev->x = ((pkt[3] << 7) | pkt[4]) >> shift; dev->y = ((pkt[1] << 7) | pkt[2]) >> shift; dev->touch = (pkt[0] & 0x10) ? 1 : 0; return 1; } static int eturbo_get_pkt_len(unsigned char *buf, int len) { if (buf[0] & 0x80) return 5; if (buf[0] == 0x01) return 3; return 0; } #endif /***************************************************************************** * Gunze part */ #ifdef CONFIG_TOUCHSCREEN_USB_GUNZE static int gunze_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { if (!(pkt[0] & 0x80) || ((pkt[1] | pkt[2] | pkt[3]) & 0x80)) return 0; dev->x = ((pkt[0] & 0x1F) << 7) | (pkt[2] & 0x7F); dev->y = ((pkt[1] & 0x1F) << 7) | (pkt[3] & 0x7F); dev->touch = pkt[0] & 0x20; return 1; } #endif /***************************************************************************** * DMC TSC-10/25 Part * * Documentation about the controller and it's protocol can be found at * http://www.dmccoltd.com/files/controler/tsc10usb_pi_e.pdf * http://www.dmccoltd.com/files/controler/tsc25_usb_e.pdf */ #ifdef CONFIG_TOUCHSCREEN_USB_DMC_TSC10 /* supported data rates. currently using 130 */ #define TSC10_RATE_POINT 0x50 #define TSC10_RATE_30 0x40 #define TSC10_RATE_50 0x41 #define TSC10_RATE_80 0x42 #define TSC10_RATE_100 0x43 #define TSC10_RATE_130 0x44 #define TSC10_RATE_150 0x45 /* commands */ #define TSC10_CMD_RESET 0x55 #define TSC10_CMD_RATE 0x05 #define TSC10_CMD_DATA1 0x01 static int dmc_tsc10_init(struct usbtouch_usb *usbtouch) { struct usb_device *dev = interface_to_usbdev(usbtouch->interface); int ret = -ENOMEM; unsigned char *buf; buf = kmalloc(2, GFP_NOIO); if (!buf) goto err_nobuf; /* reset */ buf[0] = buf[1] = 0xFF; ret = usb_control_msg(dev, usb_rcvctrlpipe (dev, 0), TSC10_CMD_RESET, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, buf, 2, USB_CTRL_SET_TIMEOUT); if (ret < 0) goto err_out; if (buf[0] != 0x06) { ret = -ENODEV; goto err_out; } /* TSC-25 data sheet specifies a delay after the RESET command */ msleep(150); /* set coordinate output rate */ buf[0] = buf[1] = 0xFF; ret = usb_control_msg(dev, usb_rcvctrlpipe (dev, 0), TSC10_CMD_RATE, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, TSC10_RATE_150, 0, buf, 2, USB_CTRL_SET_TIMEOUT); if (ret < 0) goto err_out; if ((buf[0] != 0x06) && (buf[0] != 0x15 || buf[1] != 0x01)) { ret = -ENODEV; goto err_out; } /* start sending data */ ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), TSC10_CMD_DATA1, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); err_out: kfree(buf); err_nobuf: return ret; } static int dmc_tsc10_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = ((pkt[2] & 0x03) << 8) | pkt[1]; dev->y = ((pkt[4] & 0x03) << 8) | pkt[3]; dev->touch = pkt[0] & 0x01; return 1; } #endif /***************************************************************************** * IRTOUCH Part */ #ifdef CONFIG_TOUCHSCREEN_USB_IRTOUCH static int irtouch_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = (pkt[3] << 8) | pkt[2]; dev->y = (pkt[5] << 8) | pkt[4]; dev->touch = (pkt[1] & 0x03) ? 1 : 0; return 1; } #endif /***************************************************************************** * ET&T TC5UH/TC4UM part */ #ifdef CONFIG_TOUCHSCREEN_USB_ETT_TC45USB static int tc45usb_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = ((pkt[2] & 0x0F) << 8) | pkt[1]; dev->y = ((pkt[4] & 0x0F) << 8) | pkt[3]; dev->touch = pkt[0] & 0x01; return 1; } #endif /***************************************************************************** * IdealTEK URTC1000 Part */ #ifdef CONFIG_TOUCHSCREEN_USB_IDEALTEK #ifndef MULTI_PACKET #define MULTI_PACKET #endif static int idealtek_get_pkt_len(unsigned char *buf, int len) { if (buf[0] & 0x80) return 5; if (buf[0] == 0x01) return len; return 0; } static int idealtek_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { switch (pkt[0] & 0x98) { case 0x88: /* touch data in IdealTEK mode */ dev->x = (pkt[1] << 5) | (pkt[2] >> 2); dev->y = (pkt[3] << 5) | (pkt[4] >> 2); dev->touch = (pkt[0] & 0x40) ? 1 : 0; return 1; case 0x98: /* touch data in MT emulation mode */ dev->x = (pkt[2] << 5) | (pkt[1] >> 2); dev->y = (pkt[4] << 5) | (pkt[3] >> 2); dev->touch = (pkt[0] & 0x40) ? 1 : 0; return 1; default: return 0; } } #endif /***************************************************************************** * General Touch Part */ #ifdef CONFIG_TOUCHSCREEN_USB_GENERAL_TOUCH static int general_touch_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = (pkt[2] << 8) | pkt[1]; dev->y = (pkt[4] << 8) | pkt[3]; dev->press = pkt[5] & 0xff; dev->touch = pkt[0] & 0x01; return 1; } #endif /***************************************************************************** * GoTop Part */ #ifdef CONFIG_TOUCHSCREEN_USB_GOTOP static int gotop_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = ((pkt[1] & 0x38) << 4) | pkt[2]; dev->y = ((pkt[1] & 0x07) << 7) | pkt[3]; dev->touch = pkt[0] & 0x01; return 1; } #endif /***************************************************************************** * JASTEC Part */ #ifdef CONFIG_TOUCHSCREEN_USB_JASTEC static int jastec_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = ((pkt[0] & 0x3f) << 6) | (pkt[2] & 0x3f); dev->y = ((pkt[1] & 0x3f) << 6) | (pkt[3] & 0x3f); dev->touch = (pkt[0] & 0x40) >> 6; return 1; } #endif /***************************************************************************** * Zytronic Part */ #ifdef CONFIG_TOUCHSCREEN_USB_ZYTRONIC static int zytronic_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { struct usb_interface *intf = dev->interface; switch (pkt[0]) { case 0x3A: /* command response */ dev_dbg(&intf->dev, "%s: Command response %d\n", __func__, pkt[1]); break; case 0xC0: /* down */ dev->x = (pkt[1] & 0x7f) | ((pkt[2] & 0x07) << 7); dev->y = (pkt[3] & 0x7f) | ((pkt[4] & 0x07) << 7); dev->touch = 1; dev_dbg(&intf->dev, "%s: down %d,%d\n", __func__, dev->x, dev->y); return 1; case 0x80: /* up */ dev->x = (pkt[1] & 0x7f) | ((pkt[2] & 0x07) << 7); dev->y = (pkt[3] & 0x7f) | ((pkt[4] & 0x07) << 7); dev->touch = 0; dev_dbg(&intf->dev, "%s: up %d,%d\n", __func__, dev->x, dev->y); return 1; default: dev_dbg(&intf->dev, "%s: Unknown return %d\n", __func__, pkt[0]); break; } return 0; } #endif /***************************************************************************** * NEXIO Part */ #ifdef CONFIG_TOUCHSCREEN_USB_NEXIO #define NEXIO_TIMEOUT 5000 #define NEXIO_BUFSIZE 1024 #define NEXIO_THRESHOLD 50 struct nexio_priv { struct urb *ack; unsigned char *ack_buf; }; struct nexio_touch_packet { u8 flags; /* 0xe1 = touch, 0xe1 = release */ __be16 data_len; /* total bytes of touch data */ __be16 x_len; /* bytes for X axis */ __be16 y_len; /* bytes for Y axis */ u8 data[]; } __attribute__ ((packed)); static unsigned char nexio_ack_pkt[2] = { 0xaa, 0x02 }; static unsigned char nexio_init_pkt[4] = { 0x82, 0x04, 0x0a, 0x0f }; static void nexio_ack_complete(struct urb *urb) { } static int nexio_alloc(struct usbtouch_usb *usbtouch) { struct nexio_priv *priv; int ret = -ENOMEM; usbtouch->priv = kmalloc(sizeof(struct nexio_priv), GFP_KERNEL); if (!usbtouch->priv) goto out_buf; priv = usbtouch->priv; priv->ack_buf = kmemdup(nexio_ack_pkt, sizeof(nexio_ack_pkt), GFP_KERNEL); if (!priv->ack_buf) goto err_priv; priv->ack = usb_alloc_urb(0, GFP_KERNEL); if (!priv->ack) { dev_dbg(&usbtouch->interface->dev, "%s - usb_alloc_urb failed: usbtouch->ack\n", __func__); goto err_ack_buf; } return 0; err_ack_buf: kfree(priv->ack_buf); err_priv: kfree(priv); out_buf: return ret; } static int nexio_init(struct usbtouch_usb *usbtouch) { struct usb_device *dev = interface_to_usbdev(usbtouch->interface); struct usb_host_interface *interface = usbtouch->interface->cur_altsetting; struct nexio_priv *priv = usbtouch->priv; int ret = -ENOMEM; int actual_len, i; unsigned char *buf; char *firmware_ver = NULL, *device_name = NULL; int input_ep = 0, output_ep = 0; /* find first input and output endpoint */ for (i = 0; i < interface->desc.bNumEndpoints; i++) { if (!input_ep && usb_endpoint_dir_in(&interface->endpoint[i].desc)) input_ep = interface->endpoint[i].desc.bEndpointAddress; if (!output_ep && usb_endpoint_dir_out(&interface->endpoint[i].desc)) output_ep = interface->endpoint[i].desc.bEndpointAddress; } if (!input_ep || !output_ep) return -ENXIO; buf = kmalloc(NEXIO_BUFSIZE, GFP_NOIO); if (!buf) goto out_buf; /* two empty reads */ for (i = 0; i < 2; i++) { ret = usb_bulk_msg(dev, usb_rcvbulkpipe(dev, input_ep), buf, NEXIO_BUFSIZE, &actual_len, NEXIO_TIMEOUT); if (ret < 0) goto out_buf; } /* send init command */ memcpy(buf, nexio_init_pkt, sizeof(nexio_init_pkt)); ret = usb_bulk_msg(dev, usb_sndbulkpipe(dev, output_ep), buf, sizeof(nexio_init_pkt), &actual_len, NEXIO_TIMEOUT); if (ret < 0) goto out_buf; /* read replies */ for (i = 0; i < 3; i++) { memset(buf, 0, NEXIO_BUFSIZE); ret = usb_bulk_msg(dev, usb_rcvbulkpipe(dev, input_ep), buf, NEXIO_BUFSIZE, &actual_len, NEXIO_TIMEOUT); if (ret < 0 || actual_len < 1 || buf[1] != actual_len) continue; switch (buf[0]) { case 0x83: /* firmware version */ if (!firmware_ver) firmware_ver = kstrdup(&buf[2], GFP_NOIO); break; case 0x84: /* device name */ if (!device_name) device_name = kstrdup(&buf[2], GFP_NOIO); break; } } printk(KERN_INFO "Nexio device: %s, firmware version: %s\n", device_name, firmware_ver); kfree(firmware_ver); kfree(device_name); usb_fill_bulk_urb(priv->ack, dev, usb_sndbulkpipe(dev, output_ep), priv->ack_buf, sizeof(nexio_ack_pkt), nexio_ack_complete, usbtouch); ret = 0; out_buf: kfree(buf); return ret; } static void nexio_exit(struct usbtouch_usb *usbtouch) { struct nexio_priv *priv = usbtouch->priv; usb_kill_urb(priv->ack); usb_free_urb(priv->ack); kfree(priv->ack_buf); kfree(priv); } static int nexio_read_data(struct usbtouch_usb *usbtouch, unsigned char *pkt) { struct device *dev = &usbtouch->interface->dev; struct nexio_touch_packet *packet = (void *) pkt; struct nexio_priv *priv = usbtouch->priv; unsigned int data_len = be16_to_cpu(packet->data_len); unsigned int x_len = be16_to_cpu(packet->x_len); unsigned int y_len = be16_to_cpu(packet->y_len); int x, y, begin_x, begin_y, end_x, end_y, w, h, ret; /* got touch data? */ if ((pkt[0] & 0xe0) != 0xe0) return 0; if (data_len > 0xff) data_len -= 0x100; if (x_len > 0xff) x_len -= 0x80; /* send ACK */ ret = usb_submit_urb(priv->ack, GFP_ATOMIC); if (ret) dev_warn(dev, "Failed to submit ACK URB: %d\n", ret); if (!usbtouch->type->max_xc) { usbtouch->type->max_xc = 2 * x_len; input_set_abs_params(usbtouch->input, ABS_X, 0, usbtouch->type->max_xc, 0, 0); usbtouch->type->max_yc = 2 * y_len; input_set_abs_params(usbtouch->input, ABS_Y, 0, usbtouch->type->max_yc, 0, 0); } /* * The device reports state of IR sensors on X and Y axes. * Each byte represents "darkness" percentage (0-100) of one element. * 17" touchscreen reports only 64 x 52 bytes so the resolution is low. * This also means that there's a limited multi-touch capability but * it's disabled (and untested) here as there's no X driver for that. */ begin_x = end_x = begin_y = end_y = -1; for (x = 0; x < x_len; x++) { if (begin_x == -1 && packet->data[x] > NEXIO_THRESHOLD) { begin_x = x; continue; } if (end_x == -1 && begin_x != -1 && packet->data[x] < NEXIO_THRESHOLD) { end_x = x - 1; for (y = x_len; y < data_len; y++) { if (begin_y == -1 && packet->data[y] > NEXIO_THRESHOLD) { begin_y = y - x_len; continue; } if (end_y == -1 && begin_y != -1 && packet->data[y] < NEXIO_THRESHOLD) { end_y = y - 1 - x_len; w = end_x - begin_x; h = end_y - begin_y; #if 0 /* multi-touch */ input_report_abs(usbtouch->input, ABS_MT_TOUCH_MAJOR, max(w,h)); input_report_abs(usbtouch->input, ABS_MT_TOUCH_MINOR, min(x,h)); input_report_abs(usbtouch->input, ABS_MT_POSITION_X, 2*begin_x+w); input_report_abs(usbtouch->input, ABS_MT_POSITION_Y, 2*begin_y+h); input_report_abs(usbtouch->input, ABS_MT_ORIENTATION, w > h); input_mt_sync(usbtouch->input); #endif /* single touch */ usbtouch->x = 2 * begin_x + w; usbtouch->y = 2 * begin_y + h; usbtouch->touch = packet->flags & 0x01; begin_y = end_y = -1; return 1; } } begin_x = end_x = -1; } } return 0; } #endif /***************************************************************************** * ELO part */ #ifdef CONFIG_TOUCHSCREEN_USB_ELO static int elo_read_data(struct usbtouch_usb *dev, unsigned char *pkt) { dev->x = (pkt[3] << 8) | pkt[2]; dev->y = (pkt[5] << 8) | pkt[4]; dev->touch = pkt[6] > 0; dev->press = pkt[6]; return 1; } #endif /***************************************************************************** * the different device descriptors */ #ifdef MULTI_PACKET static void usbtouch_process_multi(struct usbtouch_usb *usbtouch, unsigned char *pkt, int len); #endif static struct usbtouch_device_info usbtouch_dev_info[] = { #ifdef CONFIG_TOUCHSCREEN_USB_ELO [DEVTYPE_ELO] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .max_press = 0xff, .rept_size = 8, .read_data = elo_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_EGALAX [DEVTYPE_EGALAX] = { .min_xc = 0x0, .max_xc = 0x07ff, .min_yc = 0x0, .max_yc = 0x07ff, .rept_size = 16, .process_pkt = usbtouch_process_multi, .get_pkt_len = egalax_get_pkt_len, .read_data = egalax_read_data, .init = egalax_init, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_PANJIT [DEVTYPE_PANJIT] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 8, .read_data = panjit_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_3M [DEVTYPE_3M] = { .min_xc = 0x0, .max_xc = 0x4000, .min_yc = 0x0, .max_yc = 0x4000, .rept_size = 11, .read_data = mtouch_read_data, .alloc = mtouch_alloc, .init = mtouch_init, .exit = mtouch_exit, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ITM [DEVTYPE_ITM] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .max_press = 0xff, .rept_size = 8, .read_data = itm_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ETURBO [DEVTYPE_ETURBO] = { .min_xc = 0x0, .max_xc = 0x07ff, .min_yc = 0x0, .max_yc = 0x07ff, .rept_size = 8, .process_pkt = usbtouch_process_multi, .get_pkt_len = eturbo_get_pkt_len, .read_data = eturbo_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GUNZE [DEVTYPE_GUNZE] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 4, .read_data = gunze_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_DMC_TSC10 [DEVTYPE_DMC_TSC10] = { .min_xc = 0x0, .max_xc = 0x03ff, .min_yc = 0x0, .max_yc = 0x03ff, .rept_size = 5, .init = dmc_tsc10_init, .read_data = dmc_tsc10_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_IRTOUCH [DEVTYPE_IRTOUCH] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 8, .read_data = irtouch_read_data, }, [DEVTYPE_IRTOUCH_HIRES] = { .min_xc = 0x0, .max_xc = 0x7fff, .min_yc = 0x0, .max_yc = 0x7fff, .rept_size = 8, .read_data = irtouch_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_IDEALTEK [DEVTYPE_IDEALTEK] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 8, .process_pkt = usbtouch_process_multi, .get_pkt_len = idealtek_get_pkt_len, .read_data = idealtek_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GENERAL_TOUCH [DEVTYPE_GENERAL_TOUCH] = { .min_xc = 0x0, .max_xc = 0x7fff, .min_yc = 0x0, .max_yc = 0x7fff, .rept_size = 7, .read_data = general_touch_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_GOTOP [DEVTYPE_GOTOP] = { .min_xc = 0x0, .max_xc = 0x03ff, .min_yc = 0x0, .max_yc = 0x03ff, .rept_size = 4, .read_data = gotop_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_JASTEC [DEVTYPE_JASTEC] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 4, .read_data = jastec_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_E2I [DEVTYPE_E2I] = { .min_xc = 0x0, .max_xc = 0x7fff, .min_yc = 0x0, .max_yc = 0x7fff, .rept_size = 6, .init = e2i_init, .read_data = e2i_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ZYTRONIC [DEVTYPE_ZYTRONIC] = { .min_xc = 0x0, .max_xc = 0x03ff, .min_yc = 0x0, .max_yc = 0x03ff, .rept_size = 5, .read_data = zytronic_read_data, .irq_always = true, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_ETT_TC45USB [DEVTYPE_TC45USB] = { .min_xc = 0x0, .max_xc = 0x0fff, .min_yc = 0x0, .max_yc = 0x0fff, .rept_size = 5, .read_data = tc45usb_read_data, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_NEXIO [DEVTYPE_NEXIO] = { .rept_size = 1024, .irq_always = true, .read_data = nexio_read_data, .alloc = nexio_alloc, .init = nexio_init, .exit = nexio_exit, }, #endif #ifdef CONFIG_TOUCHSCREEN_USB_EASYTOUCH [DEVTYPE_ETOUCH] = { .min_xc = 0x0, .max_xc = 0x07ff, .min_yc = 0x0, .max_yc = 0x07ff, .rept_size = 16, .process_pkt = usbtouch_process_multi, .get_pkt_len = etouch_get_pkt_len, .read_data = etouch_read_data, }, #endif }; /***************************************************************************** * Generic Part */ static void usbtouch_process_pkt(struct usbtouch_usb *usbtouch, unsigned char *pkt, int len) { struct usbtouch_device_info *type = usbtouch->type; if (!type->read_data(usbtouch, pkt)) return; input_report_key(usbtouch->input, BTN_TOUCH, usbtouch->touch); if (swap_xy) { input_report_abs(usbtouch->input, ABS_X, usbtouch->y); input_report_abs(usbtouch->input, ABS_Y, usbtouch->x); } else { input_report_abs(usbtouch->input, ABS_X, usbtouch->x); input_report_abs(usbtouch->input, ABS_Y, usbtouch->y); } if (type->max_press) input_report_abs(usbtouch->input, ABS_PRESSURE, usbtouch->press); input_sync(usbtouch->input); } #ifdef MULTI_PACKET static void usbtouch_process_multi(struct usbtouch_usb *usbtouch, unsigned char *pkt, int len) { unsigned char *buffer; int pkt_len, pos, buf_len, tmp; /* process buffer */ if (unlikely(usbtouch->buf_len)) { /* try to get size */ pkt_len = usbtouch->type->get_pkt_len( usbtouch->buffer, usbtouch->buf_len); /* drop? */ if (unlikely(!pkt_len)) goto out_flush_buf; /* need to append -pkt_len bytes before able to get size */ if (unlikely(pkt_len < 0)) { int append = -pkt_len; if (unlikely(append > len)) append = len; if (usbtouch->buf_len + append >= usbtouch->type->rept_size) goto out_flush_buf; memcpy(usbtouch->buffer + usbtouch->buf_len, pkt, append); usbtouch->buf_len += append; pkt_len = usbtouch->type->get_pkt_len( usbtouch->buffer, usbtouch->buf_len); if (pkt_len < 0) return; } /* append */ tmp = pkt_len - usbtouch->buf_len; if (usbtouch->buf_len + tmp >= usbtouch->type->rept_size) goto out_flush_buf; memcpy(usbtouch->buffer + usbtouch->buf_len, pkt, tmp); usbtouch_process_pkt(usbtouch, usbtouch->buffer, pkt_len); buffer = pkt + tmp; buf_len = len - tmp; } else { buffer = pkt; buf_len = len; } /* loop over the received packet, process */ pos = 0; while (pos < buf_len) { /* get packet len */ pkt_len = usbtouch->type->get_pkt_len(buffer + pos, buf_len - pos); /* unknown packet: skip one byte */ if (unlikely(!pkt_len)) { pos++; continue; } /* full packet: process */ if (likely((pkt_len > 0) && (pkt_len <= buf_len - pos))) { usbtouch_process_pkt(usbtouch, buffer + pos, pkt_len); } else { /* incomplete packet: save in buffer */ memcpy(usbtouch->buffer, buffer + pos, buf_len - pos); usbtouch->buf_len = buf_len - pos; return; } pos += pkt_len; } out_flush_buf: usbtouch->buf_len = 0; return; } #endif static void usbtouch_irq(struct urb *urb) { struct usbtouch_usb *usbtouch = urb->context; struct device *dev = &usbtouch->interface->dev; int retval; switch (urb->status) { case 0: /* success */ break; case -ETIME: /* this urb is timing out */ dev_dbg(dev, "%s - urb timed out - was the device unplugged?\n", __func__); return; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: case -EPIPE: /* this urb is terminated, clean up */ dev_dbg(dev, "%s - urb shutting down with status: %d\n", __func__, urb->status); return; default: dev_dbg(dev, "%s - nonzero urb status received: %d\n", __func__, urb->status); goto exit; } usbtouch->type->process_pkt(usbtouch, usbtouch->data, urb->actual_length); exit: usb_mark_last_busy(interface_to_usbdev(usbtouch->interface)); retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result: %d\n", __func__, retval); } static int usbtouch_open(struct input_dev *input) { struct usbtouch_usb *usbtouch = input_get_drvdata(input); int r; usbtouch->irq->dev = interface_to_usbdev(usbtouch->interface); r = usb_autopm_get_interface(usbtouch->interface) ? -EIO : 0; if (r < 0) goto out; mutex_lock(&usbtouch->pm_mutex); if (!usbtouch->type->irq_always) { if (usb_submit_urb(usbtouch->irq, GFP_KERNEL)) { r = -EIO; goto out_put; } } usbtouch->interface->needs_remote_wakeup = 1; usbtouch->is_open = true; out_put: mutex_unlock(&usbtouch->pm_mutex); usb_autopm_put_interface(usbtouch->interface); out: return r; } static void usbtouch_close(struct input_dev *input) { struct usbtouch_usb *usbtouch = input_get_drvdata(input); int r; mutex_lock(&usbtouch->pm_mutex); if (!usbtouch->type->irq_always) usb_kill_urb(usbtouch->irq); usbtouch->is_open = false; mutex_unlock(&usbtouch->pm_mutex); r = usb_autopm_get_interface(usbtouch->interface); usbtouch->interface->needs_remote_wakeup = 0; if (!r) usb_autopm_put_interface(usbtouch->interface); } static int usbtouch_suspend (struct usb_interface *intf, pm_message_t message) { struct usbtouch_usb *usbtouch = usb_get_intfdata(intf); usb_kill_urb(usbtouch->irq); return 0; } static int usbtouch_resume(struct usb_interface *intf) { struct usbtouch_usb *usbtouch = usb_get_intfdata(intf); int result = 0; mutex_lock(&usbtouch->pm_mutex); if (usbtouch->is_open || usbtouch->type->irq_always) result = usb_submit_urb(usbtouch->irq, GFP_NOIO); mutex_unlock(&usbtouch->pm_mutex); return result; } static int usbtouch_reset_resume(struct usb_interface *intf) { struct usbtouch_usb *usbtouch = usb_get_intfdata(intf); int err = 0; /* reinit the device */ if (usbtouch->type->init) { err = usbtouch->type->init(usbtouch); if (err) { dev_dbg(&intf->dev, "%s - type->init() failed, err: %d\n", __func__, err); return err; } } /* restart IO if needed */ mutex_lock(&usbtouch->pm_mutex); if (usbtouch->is_open) err = usb_submit_urb(usbtouch->irq, GFP_NOIO); mutex_unlock(&usbtouch->pm_mutex); return err; } static void usbtouch_free_buffers(struct usb_device *udev, struct usbtouch_usb *usbtouch) { usb_free_coherent(udev, usbtouch->data_size, usbtouch->data, usbtouch->data_dma); kfree(usbtouch->buffer); } static struct usb_endpoint_descriptor * usbtouch_get_input_endpoint(struct usb_host_interface *interface) { int i; for (i = 0; i < interface->desc.bNumEndpoints; i++) if (usb_endpoint_dir_in(&interface->endpoint[i].desc)) return &interface->endpoint[i].desc; return NULL; } static int usbtouch_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usbtouch_usb *usbtouch; struct input_dev *input_dev; struct usb_endpoint_descriptor *endpoint; struct usb_device *udev = interface_to_usbdev(intf); struct usbtouch_device_info *type; int err = -ENOMEM; /* some devices are ignored */ if (id->driver_info == DEVTYPE_IGNORE) return -ENODEV; if (id->driver_info >= ARRAY_SIZE(usbtouch_dev_info)) return -ENODEV; endpoint = usbtouch_get_input_endpoint(intf->cur_altsetting); if (!endpoint) return -ENXIO; usbtouch = kzalloc(sizeof(struct usbtouch_usb), GFP_KERNEL); input_dev = input_allocate_device(); if (!usbtouch || !input_dev) goto out_free; mutex_init(&usbtouch->pm_mutex); type = &usbtouch_dev_info[id->driver_info]; usbtouch->type = type; if (!type->process_pkt) type->process_pkt = usbtouch_process_pkt; usbtouch->data_size = type->rept_size; if (type->get_pkt_len) { /* * When dealing with variable-length packets we should * not request more than wMaxPacketSize bytes at once * as we do not know if there is more data coming or * we filled exactly wMaxPacketSize bytes and there is * nothing else. */ usbtouch->data_size = min(usbtouch->data_size, usb_endpoint_maxp(endpoint)); } usbtouch->data = usb_alloc_coherent(udev, usbtouch->data_size, GFP_KERNEL, &usbtouch->data_dma); if (!usbtouch->data) goto out_free; if (type->get_pkt_len) { usbtouch->buffer = kmalloc(type->rept_size, GFP_KERNEL); if (!usbtouch->buffer) goto out_free_buffers; } usbtouch->irq = usb_alloc_urb(0, GFP_KERNEL); if (!usbtouch->irq) { dev_dbg(&intf->dev, "%s - usb_alloc_urb failed: usbtouch->irq\n", __func__); goto out_free_buffers; } usbtouch->interface = intf; usbtouch->input = input_dev; if (udev->manufacturer) strscpy(usbtouch->name, udev->manufacturer, sizeof(usbtouch->name)); if (udev->product) { if (udev->manufacturer) strlcat(usbtouch->name, " ", sizeof(usbtouch->name)); strlcat(usbtouch->name, udev->product, sizeof(usbtouch->name)); } if (!strlen(usbtouch->name)) snprintf(usbtouch->name, sizeof(usbtouch->name), "USB Touchscreen %04x:%04x", le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct)); usb_make_path(udev, usbtouch->phys, sizeof(usbtouch->phys)); strlcat(usbtouch->phys, "/input0", sizeof(usbtouch->phys)); input_dev->name = usbtouch->name; input_dev->phys = usbtouch->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, usbtouch); input_dev->open = usbtouch_open; input_dev->close = usbtouch_close; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, type->min_xc, type->max_xc, 0, 0); input_set_abs_params(input_dev, ABS_Y, type->min_yc, type->max_yc, 0, 0); if (type->max_press) input_set_abs_params(input_dev, ABS_PRESSURE, type->min_press, type->max_press, 0, 0); if (usb_endpoint_type(endpoint) == USB_ENDPOINT_XFER_INT) usb_fill_int_urb(usbtouch->irq, udev, usb_rcvintpipe(udev, endpoint->bEndpointAddress), usbtouch->data, usbtouch->data_size, usbtouch_irq, usbtouch, endpoint->bInterval); else usb_fill_bulk_urb(usbtouch->irq, udev, usb_rcvbulkpipe(udev, endpoint->bEndpointAddress), usbtouch->data, usbtouch->data_size, usbtouch_irq, usbtouch); usbtouch->irq->dev = udev; usbtouch->irq->transfer_dma = usbtouch->data_dma; usbtouch->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* device specific allocations */ if (type->alloc) { err = type->alloc(usbtouch); if (err) { dev_dbg(&intf->dev, "%s - type->alloc() failed, err: %d\n", __func__, err); goto out_free_urb; } } /* device specific initialisation*/ if (type->init) { err = type->init(usbtouch); if (err) { dev_dbg(&intf->dev, "%s - type->init() failed, err: %d\n", __func__, err); goto out_do_exit; } } err = input_register_device(usbtouch->input); if (err) { dev_dbg(&intf->dev, "%s - input_register_device failed, err: %d\n", __func__, err); goto out_do_exit; } usb_set_intfdata(intf, usbtouch); if (usbtouch->type->irq_always) { /* this can't fail */ usb_autopm_get_interface(intf); err = usb_submit_urb(usbtouch->irq, GFP_KERNEL); if (err) { usb_autopm_put_interface(intf); dev_err(&intf->dev, "%s - usb_submit_urb failed with result: %d\n", __func__, err); goto out_unregister_input; } } return 0; out_unregister_input: input_unregister_device(input_dev); input_dev = NULL; out_do_exit: if (type->exit) type->exit(usbtouch); out_free_urb: usb_free_urb(usbtouch->irq); out_free_buffers: usbtouch_free_buffers(udev, usbtouch); out_free: input_free_device(input_dev); kfree(usbtouch); return err; } static void usbtouch_disconnect(struct usb_interface *intf) { struct usbtouch_usb *usbtouch = usb_get_intfdata(intf); if (!usbtouch) return; dev_dbg(&intf->dev, "%s - usbtouch is initialized, cleaning up\n", __func__); usb_set_intfdata(intf, NULL); /* this will stop IO via close */ input_unregister_device(usbtouch->input); usb_free_urb(usbtouch->irq); if (usbtouch->type->exit) usbtouch->type->exit(usbtouch); usbtouch_free_buffers(interface_to_usbdev(intf), usbtouch); kfree(usbtouch); } MODULE_DEVICE_TABLE(usb, usbtouch_devices); static struct usb_driver usbtouch_driver = { .name = "usbtouchscreen", .probe = usbtouch_probe, .disconnect = usbtouch_disconnect, .suspend = usbtouch_suspend, .resume = usbtouch_resume, .reset_resume = usbtouch_reset_resume, .id_table = usbtouch_devices, .supports_autosuspend = 1, }; module_usb_driver(usbtouch_driver); MODULE_AUTHOR("Daniel Ritz <[email protected]>"); MODULE_DESCRIPTION("USB Touchscreen Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("touchkitusb"); MODULE_ALIAS("itmtouch"); MODULE_ALIAS("mtouchusb");
linux-master
drivers/input/touchscreen/usbtouchscreen.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2000-2001 Vojtech Pavlik */ /* * Gunze AHL-51S touchscreen driver for Linux */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #define DRIVER_DESC "Gunze AHL-51S touchscreen driver" MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define GUNZE_MAX_LENGTH 10 /* * Per-touchscreen data. */ struct gunze { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[GUNZE_MAX_LENGTH]; char phys[32]; }; static void gunze_process_packet(struct gunze *gunze) { struct input_dev *dev = gunze->dev; if (gunze->idx != GUNZE_MAX_LENGTH || gunze->data[5] != ',' || (gunze->data[0] != 'T' && gunze->data[0] != 'R')) { printk(KERN_WARNING "gunze.c: bad packet: >%.*s<\n", GUNZE_MAX_LENGTH, gunze->data); return; } input_report_abs(dev, ABS_X, simple_strtoul(gunze->data + 1, NULL, 10)); input_report_abs(dev, ABS_Y, 1024 - simple_strtoul(gunze->data + 6, NULL, 10)); input_report_key(dev, BTN_TOUCH, gunze->data[0] == 'T'); input_sync(dev); } static irqreturn_t gunze_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct gunze *gunze = serio_get_drvdata(serio); if (data == '\r') { gunze_process_packet(gunze); gunze->idx = 0; } else { if (gunze->idx < GUNZE_MAX_LENGTH) gunze->data[gunze->idx++] = data; } return IRQ_HANDLED; } /* * gunze_disconnect() is the opposite of gunze_connect() */ static void gunze_disconnect(struct serio *serio) { struct gunze *gunze = serio_get_drvdata(serio); input_get_device(gunze->dev); input_unregister_device(gunze->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(gunze->dev); kfree(gunze); } /* * gunze_connect() is the routine that is called when someone adds a * new serio device that supports Gunze protocol and registers it as * an input device. */ static int gunze_connect(struct serio *serio, struct serio_driver *drv) { struct gunze *gunze; struct input_dev *input_dev; int err; gunze = kzalloc(sizeof(struct gunze), GFP_KERNEL); input_dev = input_allocate_device(); if (!gunze || !input_dev) { err = -ENOMEM; goto fail1; } gunze->serio = serio; gunze->dev = input_dev; snprintf(gunze->phys, sizeof(serio->phys), "%s/input0", serio->phys); input_dev->name = "Gunze AHL-51S TouchScreen"; input_dev->phys = gunze->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_GUNZE; input_dev->id.product = 0x0051; input_dev->id.version = 0x0100; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 24, 1000, 0, 0); input_set_abs_params(input_dev, ABS_Y, 24, 1000, 0, 0); serio_set_drvdata(serio, gunze); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(gunze->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(gunze); return err; } /* * The serio driver structure. */ static const struct serio_device_id gunze_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_GUNZE, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, gunze_serio_ids); static struct serio_driver gunze_drv = { .driver = { .name = "gunze", }, .description = DRIVER_DESC, .id_table = gunze_serio_ids, .interrupt = gunze_interrupt, .connect = gunze_connect, .disconnect = gunze_disconnect, }; module_serio_driver(gunze_drv);
linux-master
drivers/input/touchscreen/gunze.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * mainstone-wm97xx.c -- Mainstone Continuous Touch screen driver for * Wolfson WM97xx AC97 Codecs. * * Copyright 2004, 2007 Wolfson Microelectronics PLC. * Author: Liam Girdwood <[email protected]> * Parts Copyright : Ian Molton <[email protected]> * Andrew Zabolotny <[email protected]> * * Notes: * This is a wm97xx extended touch driver to capture touch * data in a continuous manner on the Intel XScale architecture * * Features: * - codecs supported:- WM9705, WM9712, WM9713 * - processors supported:- Intel XScale PXA25x, PXA26x, PXA27x */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/soc/pxa/cpu.h> #include <linux/wm97xx.h> #include <sound/pxa2xx-lib.h> #include <asm/mach-types.h> struct continuous { u16 id; /* codec id */ u8 code; /* continuous code */ u8 reads; /* number of coord reads per read cycle */ u32 speed; /* number of coords per second */ }; #define WM_READS(sp) ((sp / HZ) + 1) static const struct continuous cinfo[] = { { WM9705_ID2, 0, WM_READS(94), 94 }, { WM9705_ID2, 1, WM_READS(188), 188 }, { WM9705_ID2, 2, WM_READS(375), 375 }, { WM9705_ID2, 3, WM_READS(750), 750 }, { WM9712_ID2, 0, WM_READS(94), 94 }, { WM9712_ID2, 1, WM_READS(188), 188 }, { WM9712_ID2, 2, WM_READS(375), 375 }, { WM9712_ID2, 3, WM_READS(750), 750 }, { WM9713_ID2, 0, WM_READS(94), 94 }, { WM9713_ID2, 1, WM_READS(120), 120 }, { WM9713_ID2, 2, WM_READS(154), 154 }, { WM9713_ID2, 3, WM_READS(188), 188 }, }; /* continuous speed index */ static int sp_idx; static struct gpio_desc *gpiod_irq; /* * Pen sampling frequency (Hz) in continuous mode. */ static int cont_rate = 200; module_param(cont_rate, int, 0); MODULE_PARM_DESC(cont_rate, "Sampling rate in continuous mode (Hz)"); /* * Pen down detection. * * This driver can either poll or use an interrupt to indicate a pen down * event. If the irq request fails then it will fall back to polling mode. */ static int pen_int; module_param(pen_int, int, 0); MODULE_PARM_DESC(pen_int, "Pen down detection (1 = interrupt, 0 = polling)"); /* * Pressure readback. * * Set to 1 to read back pen down pressure */ static int pressure; module_param(pressure, int, 0); MODULE_PARM_DESC(pressure, "Pressure readback (1 = pressure, 0 = no pressure)"); /* * AC97 touch data slot. * * Touch screen readback data ac97 slot */ static int ac97_touch_slot = 5; module_param(ac97_touch_slot, int, 0); MODULE_PARM_DESC(ac97_touch_slot, "Touch screen data slot AC97 number"); /* flush AC97 slot 5 FIFO on pxa machines */ static void wm97xx_acc_pen_up(struct wm97xx *wm) { unsigned int count; msleep(1); if (cpu_is_pxa27x()) { while (pxa2xx_ac97_read_misr() & (1 << 2)) pxa2xx_ac97_read_modr(); } else if (cpu_is_pxa3xx()) { for (count = 0; count < 16; count++) pxa2xx_ac97_read_modr(); } } static int wm97xx_acc_pen_down(struct wm97xx *wm) { u16 x, y, p = 0x100 | WM97XX_ADCSEL_PRES; int reads = 0; static u16 last, tries; /* When the AC97 queue has been drained we need to allow time * to buffer up samples otherwise we end up spinning polling * for samples. The controller can't have a suitably low * threshold set to use the notifications it gives. */ msleep(1); if (tries > 5) { tries = 0; return RC_PENUP; } x = pxa2xx_ac97_read_modr(); if (x == last) { tries++; return RC_AGAIN; } last = x; do { if (reads) x = pxa2xx_ac97_read_modr(); y = pxa2xx_ac97_read_modr(); if (pressure) p = pxa2xx_ac97_read_modr(); dev_dbg(wm->dev, "Raw coordinates: x=%x, y=%x, p=%x\n", x, y, p); /* are samples valid */ if ((x & WM97XX_ADCSEL_MASK) != WM97XX_ADCSEL_X || (y & WM97XX_ADCSEL_MASK) != WM97XX_ADCSEL_Y || (p & WM97XX_ADCSEL_MASK) != WM97XX_ADCSEL_PRES) goto up; /* coordinate is good */ tries = 0; input_report_abs(wm->input_dev, ABS_X, x & 0xfff); input_report_abs(wm->input_dev, ABS_Y, y & 0xfff); input_report_abs(wm->input_dev, ABS_PRESSURE, p & 0xfff); input_report_key(wm->input_dev, BTN_TOUCH, (p != 0)); input_sync(wm->input_dev); reads++; } while (reads < cinfo[sp_idx].reads); up: return RC_PENDOWN | RC_AGAIN; } static int wm97xx_acc_startup(struct wm97xx *wm) { int idx = 0, ret = 0; /* check we have a codec */ if (wm->ac97 == NULL) return -ENODEV; /* Go you big red fire engine */ for (idx = 0; idx < ARRAY_SIZE(cinfo); idx++) { if (wm->id != cinfo[idx].id) continue; sp_idx = idx; if (cont_rate <= cinfo[idx].speed) break; } wm->acc_rate = cinfo[sp_idx].code; wm->acc_slot = ac97_touch_slot; dev_info(wm->dev, "mainstone accelerated touchscreen driver, %d samples/sec\n", cinfo[sp_idx].speed); if (pen_int) { gpiod_irq = gpiod_get(wm->dev, "touch", GPIOD_IN); if (IS_ERR(gpiod_irq)) pen_int = 0; } if (pen_int) { wm->pen_irq = gpiod_to_irq(gpiod_irq); irq_set_irq_type(wm->pen_irq, IRQ_TYPE_EDGE_BOTH); } /* codec specific irq config */ if (pen_int) { switch (wm->id) { case WM9705_ID2: break; case WM9712_ID2: case WM9713_ID2: /* use PEN_DOWN GPIO 13 to assert IRQ on GPIO line 2 */ wm97xx_config_gpio(wm, WM97XX_GPIO_13, WM97XX_GPIO_IN, WM97XX_GPIO_POL_HIGH, WM97XX_GPIO_STICKY, WM97XX_GPIO_WAKE); wm97xx_config_gpio(wm, WM97XX_GPIO_2, WM97XX_GPIO_OUT, WM97XX_GPIO_POL_HIGH, WM97XX_GPIO_NOTSTICKY, WM97XX_GPIO_NOWAKE); break; default: dev_err(wm->dev, "pen down irq not supported on this device\n"); pen_int = 0; break; } } return ret; } static void wm97xx_acc_shutdown(struct wm97xx *wm) { /* codec specific deconfig */ if (pen_int) { if (gpiod_irq) gpiod_put(gpiod_irq); wm->pen_irq = 0; } } static struct wm97xx_mach_ops mainstone_mach_ops = { .acc_enabled = 1, .acc_pen_up = wm97xx_acc_pen_up, .acc_pen_down = wm97xx_acc_pen_down, .acc_startup = wm97xx_acc_startup, .acc_shutdown = wm97xx_acc_shutdown, .irq_gpio = WM97XX_GPIO_2, }; static int mainstone_wm97xx_probe(struct platform_device *pdev) { struct wm97xx *wm = platform_get_drvdata(pdev); return wm97xx_register_mach_ops(wm, &mainstone_mach_ops); } static int mainstone_wm97xx_remove(struct platform_device *pdev) { struct wm97xx *wm = platform_get_drvdata(pdev); wm97xx_unregister_mach_ops(wm); return 0; } static struct platform_driver mainstone_wm97xx_driver = { .probe = mainstone_wm97xx_probe, .remove = mainstone_wm97xx_remove, .driver = { .name = "wm97xx-touch", }, }; module_platform_driver(mainstone_wm97xx_driver); /* Module information */ MODULE_AUTHOR("Liam Girdwood <[email protected]>"); MODULE_DESCRIPTION("wm97xx continuous touch driver for mainstone"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/mainstone-wm97xx.c
// SPDX-License-Identifier: GPL-2.0-only /* * cyttsp_i2c.c * Cypress TrueTouch(TM) Standard Product (TTSP) I2C touchscreen driver. * For use with Cypress Txx3xx parts. * Supported parts include: * CY8CTST341 * CY8CTMA340 * * Copyright (C) 2009, 2010, 2011 Cypress Semiconductor, Inc. * Copyright (C) 2012 Javier Martinez Canillas <[email protected]> * * Contact Cypress Semiconductor at www.cypress.com <[email protected]> */ #include "cyttsp_core.h" #include <linux/i2c.h> #include <linux/input.h> #define CY_I2C_NAME "cyttsp-i2c" #define CY_I2C_DATA_SIZE 128 static const struct cyttsp_bus_ops cyttsp_i2c_bus_ops = { .bustype = BUS_I2C, .write = cyttsp_i2c_write_block_data, .read = cyttsp_i2c_read_block_data, }; static int cyttsp_i2c_probe(struct i2c_client *client) { struct cyttsp *ts; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C functionality not Supported\n"); return -EIO; } ts = cyttsp_probe(&cyttsp_i2c_bus_ops, &client->dev, client->irq, CY_I2C_DATA_SIZE); if (IS_ERR(ts)) return PTR_ERR(ts); i2c_set_clientdata(client, ts); return 0; } static const struct i2c_device_id cyttsp_i2c_id[] = { { CY_I2C_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, cyttsp_i2c_id); static const struct of_device_id cyttsp_of_i2c_match[] = { { .compatible = "cypress,cy8ctma340", }, { .compatible = "cypress,cy8ctst341", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, cyttsp_of_i2c_match); static struct i2c_driver cyttsp_i2c_driver = { .driver = { .name = CY_I2C_NAME, .pm = pm_sleep_ptr(&cyttsp_pm_ops), .of_match_table = cyttsp_of_i2c_match, }, .probe = cyttsp_i2c_probe, .id_table = cyttsp_i2c_id, }; module_i2c_driver(cyttsp_i2c_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard Product (TTSP) I2C driver"); MODULE_AUTHOR("Cypress");
linux-master
drivers/input/touchscreen/cyttsp_i2c.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * MELFAS MIP4 Touchscreen * * Copyright (C) 2016 MELFAS Inc. * * Author : Sangwon Jee <[email protected]> */ #include <linux/acpi.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of.h> #include <linux/slab.h> #include <asm/unaligned.h> #define MIP4_DEVICE_NAME "mip4_ts" /***************************************************************** * Protocol * Version : MIP 4.0 Rev 5.4 *****************************************************************/ /* Address */ #define MIP4_R0_BOOT 0x00 #define MIP4_R1_BOOT_MODE 0x01 #define MIP4_R1_BOOT_BUF_ADDR 0x10 #define MIP4_R1_BOOT_STATUS 0x20 #define MIP4_R1_BOOT_CMD 0x30 #define MIP4_R1_BOOT_TARGET_ADDR 0x40 #define MIP4_R1_BOOT_SIZE 0x44 #define MIP4_R0_INFO 0x01 #define MIP4_R1_INFO_PRODUCT_NAME 0x00 #define MIP4_R1_INFO_RESOLUTION_X 0x10 #define MIP4_R1_INFO_RESOLUTION_Y 0x12 #define MIP4_R1_INFO_NODE_NUM_X 0x14 #define MIP4_R1_INFO_NODE_NUM_Y 0x15 #define MIP4_R1_INFO_KEY_NUM 0x16 #define MIP4_R1_INFO_PRESSURE_NUM 0x17 #define MIP4_R1_INFO_LENGTH_X 0x18 #define MIP4_R1_INFO_LENGTH_Y 0x1A #define MIP4_R1_INFO_PPM_X 0x1C #define MIP4_R1_INFO_PPM_Y 0x1D #define MIP4_R1_INFO_VERSION_BOOT 0x20 #define MIP4_R1_INFO_VERSION_CORE 0x22 #define MIP4_R1_INFO_VERSION_APP 0x24 #define MIP4_R1_INFO_VERSION_PARAM 0x26 #define MIP4_R1_INFO_SECT_BOOT_START 0x30 #define MIP4_R1_INFO_SECT_BOOT_END 0x31 #define MIP4_R1_INFO_SECT_CORE_START 0x32 #define MIP4_R1_INFO_SECT_CORE_END 0x33 #define MIP4_R1_INFO_SECT_APP_START 0x34 #define MIP4_R1_INFO_SECT_APP_END 0x35 #define MIP4_R1_INFO_SECT_PARAM_START 0x36 #define MIP4_R1_INFO_SECT_PARAM_END 0x37 #define MIP4_R1_INFO_BUILD_DATE 0x40 #define MIP4_R1_INFO_BUILD_TIME 0x44 #define MIP4_R1_INFO_CHECKSUM_PRECALC 0x48 #define MIP4_R1_INFO_CHECKSUM_REALTIME 0x4A #define MIP4_R1_INFO_PROTOCOL_NAME 0x50 #define MIP4_R1_INFO_PROTOCOL_VERSION 0x58 #define MIP4_R1_INFO_IC_ID 0x70 #define MIP4_R1_INFO_IC_NAME 0x71 #define MIP4_R1_INFO_IC_VENDOR_ID 0x75 #define MIP4_R1_INFO_IC_HW_CATEGORY 0x77 #define MIP4_R1_INFO_CONTACT_THD_SCR 0x78 #define MIP4_R1_INFO_CONTACT_THD_KEY 0x7A #define MIP4_R1_INFO_PID 0x7C #define MIP4_R1_INFO_VID 0x7E #define MIP4_R1_INFO_SLAVE_ADDR 0x80 #define MIP4_R0_EVENT 0x02 #define MIP4_R1_EVENT_SUPPORTED_FUNC 0x00 #define MIP4_R1_EVENT_FORMAT 0x04 #define MIP4_R1_EVENT_SIZE 0x06 #define MIP4_R1_EVENT_PACKET_INFO 0x10 #define MIP4_R1_EVENT_PACKET_DATA 0x11 #define MIP4_R0_CTRL 0x06 #define MIP4_R1_CTRL_READY_STATUS 0x00 #define MIP4_R1_CTRL_EVENT_READY 0x01 #define MIP4_R1_CTRL_MODE 0x10 #define MIP4_R1_CTRL_EVENT_TRIGGER_TYPE 0x11 #define MIP4_R1_CTRL_RECALIBRATE 0x12 #define MIP4_R1_CTRL_POWER_STATE 0x13 #define MIP4_R1_CTRL_GESTURE_TYPE 0x14 #define MIP4_R1_CTRL_DISABLE_ESD_ALERT 0x18 #define MIP4_R1_CTRL_CHARGER_MODE 0x19 #define MIP4_R1_CTRL_HIGH_SENS_MODE 0x1A #define MIP4_R1_CTRL_WINDOW_MODE 0x1B #define MIP4_R1_CTRL_PALM_REJECTION 0x1C #define MIP4_R1_CTRL_EDGE_CORRECTION 0x1D #define MIP4_R1_CTRL_ENTER_GLOVE_MODE 0x1E #define MIP4_R1_CTRL_I2C_ON_LPM 0x1F #define MIP4_R1_CTRL_GESTURE_DEBUG 0x20 #define MIP4_R1_CTRL_PALM_EVENT 0x22 #define MIP4_R1_CTRL_PROXIMITY_SENSING 0x23 /* Value */ #define MIP4_BOOT_MODE_BOOT 0x01 #define MIP4_BOOT_MODE_APP 0x02 #define MIP4_BOOT_STATUS_BUSY 0x05 #define MIP4_BOOT_STATUS_ERROR 0x0E #define MIP4_BOOT_STATUS_DONE 0xA0 #define MIP4_BOOT_CMD_MASS_ERASE 0x15 #define MIP4_BOOT_CMD_PROGRAM 0x54 #define MIP4_BOOT_CMD_ERASE 0x8F #define MIP4_BOOT_CMD_WRITE 0xA5 #define MIP4_BOOT_CMD_READ 0xC2 #define MIP4_EVENT_INPUT_TYPE_KEY 0 #define MIP4_EVENT_INPUT_TYPE_SCREEN 1 #define MIP4_EVENT_INPUT_TYPE_PROXIMITY 2 #define I2C_RETRY_COUNT 3 /* 2~ */ #define MIP4_BUF_SIZE 128 #define MIP4_MAX_FINGERS 10 #define MIP4_MAX_KEYS 4 #define MIP4_TOUCH_MAJOR_MIN 0 #define MIP4_TOUCH_MAJOR_MAX 255 #define MIP4_TOUCH_MINOR_MIN 0 #define MIP4_TOUCH_MINOR_MAX 255 #define MIP4_PRESSURE_MIN 0 #define MIP4_PRESSURE_MAX 255 #define MIP4_FW_NAME "melfas_mip4.fw" #define MIP4_FW_UPDATE_DEBUG 0 /* 0 (default) or 1 */ struct mip4_fw_version { u16 boot; u16 core; u16 app; u16 param; }; struct mip4_ts { struct i2c_client *client; struct input_dev *input; struct gpio_desc *gpio_ce; char phys[32]; char product_name[16]; u16 product_id; char ic_name[4]; char fw_name[32]; unsigned int max_x; unsigned int max_y; u8 node_x; u8 node_y; u8 node_key; unsigned int ppm_x; unsigned int ppm_y; struct mip4_fw_version fw_version; unsigned int event_size; unsigned int event_format; unsigned int key_num; unsigned short key_code[MIP4_MAX_KEYS]; bool wake_irq_enabled; u8 buf[MIP4_BUF_SIZE]; }; static int mip4_i2c_xfer(struct mip4_ts *ts, char *write_buf, unsigned int write_len, char *read_buf, unsigned int read_len) { struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = write_buf, .len = write_len, }, { .addr = ts->client->addr, .flags = I2C_M_RD, .buf = read_buf, .len = read_len, }, }; int retry = I2C_RETRY_COUNT; int res; int error; do { res = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (res == ARRAY_SIZE(msg)) return 0; error = res < 0 ? res : -EIO; dev_err(&ts->client->dev, "%s - i2c_transfer failed: %d (%d)\n", __func__, error, res); } while (--retry); return error; } static void mip4_parse_fw_version(const u8 *buf, struct mip4_fw_version *v) { v->boot = get_unaligned_le16(buf + 0); v->core = get_unaligned_le16(buf + 2); v->app = get_unaligned_le16(buf + 4); v->param = get_unaligned_le16(buf + 6); } /* * Read chip firmware version */ static int mip4_get_fw_version(struct mip4_ts *ts) { u8 cmd[] = { MIP4_R0_INFO, MIP4_R1_INFO_VERSION_BOOT }; u8 buf[sizeof(ts->fw_version)]; int error; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), buf, sizeof(buf)); if (error) { memset(&ts->fw_version, 0xff, sizeof(ts->fw_version)); return error; } mip4_parse_fw_version(buf, &ts->fw_version); return 0; } /* * Fetch device characteristics */ static int mip4_query_device(struct mip4_ts *ts) { union i2c_smbus_data dummy; int error; u8 cmd[2]; u8 buf[14]; /* * Make sure there is something at this address as we do not * consider subsequent failures as fatal. */ if (i2c_smbus_xfer(ts->client->adapter, ts->client->addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0) { dev_err(&ts->client->dev, "nothing at this address\n"); return -ENXIO; } /* Product name */ cmd[0] = MIP4_R0_INFO; cmd[1] = MIP4_R1_INFO_PRODUCT_NAME; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), ts->product_name, sizeof(ts->product_name)); if (error) dev_warn(&ts->client->dev, "Failed to retrieve product name: %d\n", error); else dev_dbg(&ts->client->dev, "product name: %.*s\n", (int)sizeof(ts->product_name), ts->product_name); /* Product ID */ cmd[0] = MIP4_R0_INFO; cmd[1] = MIP4_R1_INFO_PID; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), buf, 2); if (error) { dev_warn(&ts->client->dev, "Failed to retrieve product id: %d\n", error); } else { ts->product_id = get_unaligned_le16(&buf[0]); dev_dbg(&ts->client->dev, "product id: %04X\n", ts->product_id); } /* Firmware name */ snprintf(ts->fw_name, sizeof(ts->fw_name), "melfas_mip4_%04X.fw", ts->product_id); dev_dbg(&ts->client->dev, "firmware name: %s\n", ts->fw_name); /* IC name */ cmd[0] = MIP4_R0_INFO; cmd[1] = MIP4_R1_INFO_IC_NAME; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), ts->ic_name, sizeof(ts->ic_name)); if (error) dev_warn(&ts->client->dev, "Failed to retrieve IC name: %d\n", error); else dev_dbg(&ts->client->dev, "IC name: %.*s\n", (int)sizeof(ts->ic_name), ts->ic_name); /* Firmware version */ error = mip4_get_fw_version(ts); if (error) dev_warn(&ts->client->dev, "Failed to retrieve FW version: %d\n", error); else dev_dbg(&ts->client->dev, "F/W Version: %04X %04X %04X %04X\n", ts->fw_version.boot, ts->fw_version.core, ts->fw_version.app, ts->fw_version.param); /* Resolution */ cmd[0] = MIP4_R0_INFO; cmd[1] = MIP4_R1_INFO_RESOLUTION_X; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), buf, 14); if (error) { dev_warn(&ts->client->dev, "Failed to retrieve touchscreen parameters: %d\n", error); } else { ts->max_x = get_unaligned_le16(&buf[0]); ts->max_y = get_unaligned_le16(&buf[2]); dev_dbg(&ts->client->dev, "max_x: %d, max_y: %d\n", ts->max_x, ts->max_y); ts->node_x = buf[4]; ts->node_y = buf[5]; ts->node_key = buf[6]; dev_dbg(&ts->client->dev, "node_x: %d, node_y: %d, node_key: %d\n", ts->node_x, ts->node_y, ts->node_key); ts->ppm_x = buf[12]; ts->ppm_y = buf[13]; dev_dbg(&ts->client->dev, "ppm_x: %d, ppm_y: %d\n", ts->ppm_x, ts->ppm_y); /* Key ts */ if (ts->node_key > 0) ts->key_num = ts->node_key; } /* Protocol */ cmd[0] = MIP4_R0_EVENT; cmd[1] = MIP4_R1_EVENT_SUPPORTED_FUNC; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), buf, 7); if (error) { dev_warn(&ts->client->dev, "Failed to retrieve device type: %d\n", error); ts->event_format = 0xff; } else { ts->event_format = get_unaligned_le16(&buf[4]); ts->event_size = buf[6]; dev_dbg(&ts->client->dev, "event_format: %d, event_size: %d\n", ts->event_format, ts->event_size); if (ts->event_format == 2 || ts->event_format > 3) dev_warn(&ts->client->dev, "Unknown event format %d\n", ts->event_format); } return 0; } static int mip4_power_on(struct mip4_ts *ts) { if (ts->gpio_ce) { gpiod_set_value_cansleep(ts->gpio_ce, 1); /* Booting delay : 200~300ms */ usleep_range(200 * 1000, 300 * 1000); } return 0; } static void mip4_power_off(struct mip4_ts *ts) { if (ts->gpio_ce) gpiod_set_value_cansleep(ts->gpio_ce, 0); } /* * Clear touch input event status */ static void mip4_clear_input(struct mip4_ts *ts) { int i; /* Screen */ for (i = 0; i < MIP4_MAX_FINGERS; i++) { input_mt_slot(ts->input, i); input_mt_report_slot_inactive(ts->input); } /* Keys */ for (i = 0; i < ts->key_num; i++) input_report_key(ts->input, ts->key_code[i], 0); input_sync(ts->input); } static int mip4_enable(struct mip4_ts *ts) { int error; error = mip4_power_on(ts); if (error) return error; enable_irq(ts->client->irq); return 0; } static void mip4_disable(struct mip4_ts *ts) { disable_irq(ts->client->irq); mip4_power_off(ts); mip4_clear_input(ts); } /***************************************************************** * Input handling *****************************************************************/ static void mip4_report_keys(struct mip4_ts *ts, u8 *packet) { u8 key; bool down; switch (ts->event_format) { case 0: case 1: key = packet[0] & 0x0F; down = packet[0] & 0x80; break; case 3: default: key = packet[0] & 0x0F; down = packet[1] & 0x01; break; } /* Report key event */ if (key >= 1 && key <= ts->key_num) { unsigned short keycode = ts->key_code[key - 1]; dev_dbg(&ts->client->dev, "Key - ID: %d, keycode: %d, state: %d\n", key, keycode, down); input_event(ts->input, EV_MSC, MSC_SCAN, keycode); input_report_key(ts->input, keycode, down); } else { dev_err(&ts->client->dev, "Unknown key: %d\n", key); } } static void mip4_report_touch(struct mip4_ts *ts, u8 *packet) { int id; bool __always_unused hover; bool palm; bool state; u16 x, y; u8 __always_unused pressure_stage = 0; u8 pressure; u8 __always_unused size; u8 touch_major; u8 touch_minor; switch (ts->event_format) { case 0: case 1: /* Touch only */ state = packet[0] & BIT(7); hover = packet[0] & BIT(5); palm = packet[0] & BIT(4); id = (packet[0] & 0x0F) - 1; x = ((packet[1] & 0x0F) << 8) | packet[2]; y = (((packet[1] >> 4) & 0x0F) << 8) | packet[3]; pressure = packet[4]; size = packet[5]; if (ts->event_format == 0) { touch_major = packet[5]; touch_minor = packet[5]; } else { touch_major = packet[6]; touch_minor = packet[7]; } break; case 3: default: /* Touch + Force(Pressure) */ id = (packet[0] & 0x0F) - 1; hover = packet[1] & BIT(2); palm = packet[1] & BIT(1); state = packet[1] & BIT(0); x = ((packet[2] & 0x0F) << 8) | packet[3]; y = (((packet[2] >> 4) & 0x0F) << 8) | packet[4]; size = packet[6]; pressure_stage = (packet[7] & 0xF0) >> 4; pressure = ((packet[7] & 0x0F) << 8) | packet[8]; touch_major = packet[9]; touch_minor = packet[10]; break; } dev_dbg(&ts->client->dev, "Screen - Slot: %d State: %d X: %04d Y: %04d Z: %d\n", id, state, x, y, pressure); if (unlikely(id < 0 || id >= MIP4_MAX_FINGERS)) { dev_err(&ts->client->dev, "Screen - invalid slot ID: %d\n", id); goto out; } input_mt_slot(ts->input, id); if (input_mt_report_slot_state(ts->input, palm ? MT_TOOL_PALM : MT_TOOL_FINGER, state)) { input_report_abs(ts->input, ABS_MT_POSITION_X, x); input_report_abs(ts->input, ABS_MT_POSITION_Y, y); input_report_abs(ts->input, ABS_MT_PRESSURE, pressure); input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, touch_major); input_report_abs(ts->input, ABS_MT_TOUCH_MINOR, touch_minor); } out: input_mt_sync_frame(ts->input); } static int mip4_handle_packet(struct mip4_ts *ts, u8 *packet) { u8 type; switch (ts->event_format) { case 0: case 1: type = (packet[0] & 0x40) >> 6; break; case 3: type = (packet[0] & 0xF0) >> 4; break; default: /* Should not happen unless we have corrupted firmware */ return -EINVAL; } dev_dbg(&ts->client->dev, "Type: %d\n", type); /* Report input event */ switch (type) { case MIP4_EVENT_INPUT_TYPE_KEY: mip4_report_keys(ts, packet); break; case MIP4_EVENT_INPUT_TYPE_SCREEN: mip4_report_touch(ts, packet); break; default: dev_err(&ts->client->dev, "Unknown event type: %d\n", type); break; } return 0; } static irqreturn_t mip4_interrupt(int irq, void *dev_id) { struct mip4_ts *ts = dev_id; struct i2c_client *client = ts->client; unsigned int i; int error; u8 cmd[2]; u8 size; bool alert; /* Read packet info */ cmd[0] = MIP4_R0_EVENT; cmd[1] = MIP4_R1_EVENT_PACKET_INFO; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), ts->buf, 1); if (error) { dev_err(&client->dev, "Failed to read packet info: %d\n", error); goto out; } size = ts->buf[0] & 0x7F; alert = ts->buf[0] & BIT(7); dev_dbg(&client->dev, "packet size: %d, alert: %d\n", size, alert); /* Check size */ if (!size) { dev_err(&client->dev, "Empty packet\n"); goto out; } /* Read packet data */ cmd[0] = MIP4_R0_EVENT; cmd[1] = MIP4_R1_EVENT_PACKET_DATA; error = mip4_i2c_xfer(ts, cmd, sizeof(cmd), ts->buf, size); if (error) { dev_err(&client->dev, "Failed to read packet data: %d\n", error); goto out; } if (alert) { dev_dbg(&client->dev, "Alert: %d\n", ts->buf[0]); } else { for (i = 0; i < size; i += ts->event_size) { error = mip4_handle_packet(ts, &ts->buf[i]); if (error) break; } input_sync(ts->input); } out: return IRQ_HANDLED; } static int mip4_input_open(struct input_dev *dev) { struct mip4_ts *ts = input_get_drvdata(dev); return mip4_enable(ts); } static void mip4_input_close(struct input_dev *dev) { struct mip4_ts *ts = input_get_drvdata(dev); mip4_disable(ts); } /***************************************************************** * Firmware update *****************************************************************/ /* Firmware Info */ #define MIP4_BL_PAGE_SIZE 512 /* 512 */ #define MIP4_BL_PACKET_SIZE 512 /* 512, 256, 128, 64, ... */ /* * Firmware binary tail info */ struct mip4_bin_tail { u8 tail_mark[4]; u8 chip_name[4]; __le32 bin_start_addr; __le32 bin_length; __le16 ver_boot; __le16 ver_core; __le16 ver_app; __le16 ver_param; u8 boot_start; u8 boot_end; u8 core_start; u8 core_end; u8 app_start; u8 app_end; u8 param_start; u8 param_end; u8 checksum_type; u8 hw_category; __le16 param_id; __le32 param_length; __le32 build_date; __le32 build_time; __le32 reserved1; __le32 reserved2; __le16 reserved3; __le16 tail_size; __le32 crc; } __packed; #define MIP4_BIN_TAIL_MARK "MBT\001" #define MIP4_BIN_TAIL_SIZE (sizeof(struct mip4_bin_tail)) /* * Bootloader - Read status */ static int mip4_bl_read_status(struct mip4_ts *ts) { u8 cmd[] = { MIP4_R0_BOOT, MIP4_R1_BOOT_STATUS }; u8 result; struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = cmd, .len = sizeof(cmd), }, { .addr = ts->client->addr, .flags = I2C_M_RD, .buf = &result, .len = sizeof(result), }, }; int ret; int error; int retry = 1000; do { ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to read bootloader status: %d\n", error); return error; } switch (result) { case MIP4_BOOT_STATUS_DONE: dev_dbg(&ts->client->dev, "%s - done\n", __func__); return 0; case MIP4_BOOT_STATUS_ERROR: dev_err(&ts->client->dev, "Bootloader failure\n"); return -EIO; case MIP4_BOOT_STATUS_BUSY: dev_dbg(&ts->client->dev, "%s - Busy\n", __func__); error = -EBUSY; break; default: dev_err(&ts->client->dev, "Unexpected bootloader status: %#02x\n", result); error = -EINVAL; break; } usleep_range(1000, 2000); } while (--retry); return error; } /* * Bootloader - Change mode */ static int mip4_bl_change_mode(struct mip4_ts *ts, u8 mode) { u8 mode_chg_cmd[] = { MIP4_R0_BOOT, MIP4_R1_BOOT_MODE, mode }; u8 mode_read_cmd[] = { MIP4_R0_BOOT, MIP4_R1_BOOT_MODE }; u8 result; struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = mode_read_cmd, .len = sizeof(mode_read_cmd), }, { .addr = ts->client->addr, .flags = I2C_M_RD, .buf = &result, .len = sizeof(result), }, }; int retry = 10; int ret; int error; do { /* Send mode change command */ ret = i2c_master_send(ts->client, mode_chg_cmd, sizeof(mode_chg_cmd)); if (ret != sizeof(mode_chg_cmd)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send %d mode change: %d (%d)\n", mode, error, ret); return error; } dev_dbg(&ts->client->dev, "Sent mode change request (mode: %d)\n", mode); /* Wait */ msleep(1000); /* Verify target mode */ ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to read device mode: %d\n", error); return error; } dev_dbg(&ts->client->dev, "Current device mode: %d, want: %d\n", result, mode); if (result == mode) return 0; } while (--retry); return -EIO; } /* * Bootloader - Start bootloader mode */ static int mip4_bl_enter(struct mip4_ts *ts) { return mip4_bl_change_mode(ts, MIP4_BOOT_MODE_BOOT); } /* * Bootloader - Exit bootloader mode */ static int mip4_bl_exit(struct mip4_ts *ts) { return mip4_bl_change_mode(ts, MIP4_BOOT_MODE_APP); } static int mip4_bl_get_address(struct mip4_ts *ts, u16 *buf_addr) { u8 cmd[] = { MIP4_R0_BOOT, MIP4_R1_BOOT_BUF_ADDR }; u8 result[sizeof(u16)]; struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = cmd, .len = sizeof(cmd), }, { .addr = ts->client->addr, .flags = I2C_M_RD, .buf = result, .len = sizeof(result), }, }; int ret; int error; ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to retrieve bootloader buffer address: %d\n", error); return error; } *buf_addr = get_unaligned_le16(result); dev_dbg(&ts->client->dev, "Bootloader buffer address %#04x\n", *buf_addr); return 0; } static int mip4_bl_program_page(struct mip4_ts *ts, int offset, const u8 *data, int length, u16 buf_addr) { u8 cmd[6]; u8 *data_buf; u16 buf_offset; int ret; int error; dev_dbg(&ts->client->dev, "Writing page @%#06x (%d)\n", offset, length); if (length > MIP4_BL_PAGE_SIZE || length % MIP4_BL_PACKET_SIZE) { dev_err(&ts->client->dev, "Invalid page length: %d\n", length); return -EINVAL; } data_buf = kmalloc(2 + MIP4_BL_PACKET_SIZE, GFP_KERNEL); if (!data_buf) return -ENOMEM; /* Addr */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_TARGET_ADDR; put_unaligned_le32(offset, &cmd[2]); ret = i2c_master_send(ts->client, cmd, 6); if (ret != 6) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send write page address: %d\n", error); goto out; } /* Size */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_SIZE; put_unaligned_le32(length, &cmd[2]); ret = i2c_master_send(ts->client, cmd, 6); if (ret != 6) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send write page size: %d\n", error); goto out; } /* Data */ for (buf_offset = 0; buf_offset < length; buf_offset += MIP4_BL_PACKET_SIZE) { dev_dbg(&ts->client->dev, "writing chunk at %#04x (size %d)\n", buf_offset, MIP4_BL_PACKET_SIZE); put_unaligned_be16(buf_addr + buf_offset, data_buf); memcpy(&data_buf[2], &data[buf_offset], MIP4_BL_PACKET_SIZE); ret = i2c_master_send(ts->client, data_buf, 2 + MIP4_BL_PACKET_SIZE); if (ret != 2 + MIP4_BL_PACKET_SIZE) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to read chunk at %#04x (size %d): %d\n", buf_offset, MIP4_BL_PACKET_SIZE, error); goto out; } } /* Command */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_CMD; cmd[2] = MIP4_BOOT_CMD_PROGRAM; ret = i2c_master_send(ts->client, cmd, 3); if (ret != 3) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send 'write' command: %d\n", error); goto out; } /* Status */ error = mip4_bl_read_status(ts); out: kfree(data_buf); return error ? error : 0; } static int mip4_bl_verify_page(struct mip4_ts *ts, int offset, const u8 *data, int length, int buf_addr) { u8 cmd[8]; u8 *read_buf; int buf_offset; struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = cmd, .len = 2, }, { .addr = ts->client->addr, .flags = I2C_M_RD, .len = MIP4_BL_PACKET_SIZE, }, }; int ret; int error; dev_dbg(&ts->client->dev, "Validating page @%#06x (%d)\n", offset, length); /* Addr */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_TARGET_ADDR; put_unaligned_le32(offset, &cmd[2]); ret = i2c_master_send(ts->client, cmd, 6); if (ret != 6) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send read page address: %d\n", error); return error; } /* Size */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_SIZE; put_unaligned_le32(length, &cmd[2]); ret = i2c_master_send(ts->client, cmd, 6); if (ret != 6) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send read page size: %d\n", error); return error; } /* Command */ cmd[0] = MIP4_R0_BOOT; cmd[1] = MIP4_R1_BOOT_CMD; cmd[2] = MIP4_BOOT_CMD_READ; ret = i2c_master_send(ts->client, cmd, 3); if (ret != 3) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to send 'read' command: %d\n", error); return error; } /* Status */ error = mip4_bl_read_status(ts); if (error) return error; /* Read */ msg[1].buf = read_buf = kmalloc(MIP4_BL_PACKET_SIZE, GFP_KERNEL); if (!read_buf) return -ENOMEM; for (buf_offset = 0; buf_offset < length; buf_offset += MIP4_BL_PACKET_SIZE) { dev_dbg(&ts->client->dev, "reading chunk at %#04x (size %d)\n", buf_offset, MIP4_BL_PACKET_SIZE); put_unaligned_be16(buf_addr + buf_offset, cmd); ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "Failed to read chunk at %#04x (size %d): %d\n", buf_offset, MIP4_BL_PACKET_SIZE, error); break; } if (memcmp(&data[buf_offset], read_buf, MIP4_BL_PACKET_SIZE)) { dev_err(&ts->client->dev, "Failed to validate chunk at %#04x (size %d)\n", buf_offset, MIP4_BL_PACKET_SIZE); #if MIP4_FW_UPDATE_DEBUG print_hex_dump(KERN_DEBUG, MIP4_DEVICE_NAME " F/W File: ", DUMP_PREFIX_OFFSET, 16, 1, data + offset, MIP4_BL_PACKET_SIZE, false); print_hex_dump(KERN_DEBUG, MIP4_DEVICE_NAME " F/W Chip: ", DUMP_PREFIX_OFFSET, 16, 1, read_buf, MIP4_BL_PAGE_SIZE, false); #endif error = -EINVAL; break; } } kfree(read_buf); return error ? error : 0; } /* * Flash chip firmware */ static int mip4_flash_fw(struct mip4_ts *ts, const u8 *fw_data, u32 fw_size, u32 fw_offset) { struct i2c_client *client = ts->client; int offset; u16 buf_addr; int error, error2; /* Enter bootloader mode */ dev_dbg(&client->dev, "Entering bootloader mode\n"); error = mip4_bl_enter(ts); if (error) { dev_err(&client->dev, "Failed to enter bootloader mode: %d\n", error); return error; } /* Read info */ error = mip4_bl_get_address(ts, &buf_addr); if (error) goto exit_bl; /* Program & Verify */ dev_dbg(&client->dev, "Program & Verify, page size: %d, packet size: %d\n", MIP4_BL_PAGE_SIZE, MIP4_BL_PACKET_SIZE); for (offset = fw_offset; offset < fw_offset + fw_size; offset += MIP4_BL_PAGE_SIZE) { /* Program */ error = mip4_bl_program_page(ts, offset, fw_data + offset, MIP4_BL_PAGE_SIZE, buf_addr); if (error) break; /* Verify */ error = mip4_bl_verify_page(ts, offset, fw_data + offset, MIP4_BL_PAGE_SIZE, buf_addr); if (error) break; } exit_bl: /* Exit bootloader mode */ dev_dbg(&client->dev, "Exiting bootloader mode\n"); error2 = mip4_bl_exit(ts); if (error2) { dev_err(&client->dev, "Failed to exit bootloader mode: %d\n", error2); if (!error) error = error2; } /* Reset chip */ mip4_power_off(ts); mip4_power_on(ts); mip4_query_device(ts); /* Refresh device parameters */ input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, ts->max_x, 0, 0); input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, ts->max_y, 0, 0); input_set_abs_params(ts->input, ABS_X, 0, ts->max_x, 0, 0); input_set_abs_params(ts->input, ABS_Y, 0, ts->max_y, 0, 0); input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->ppm_x); input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->ppm_y); input_abs_set_res(ts->input, ABS_X, ts->ppm_x); input_abs_set_res(ts->input, ABS_Y, ts->ppm_y); return error ? error : 0; } static int mip4_parse_firmware(struct mip4_ts *ts, const struct firmware *fw, u32 *fw_offset_start, u32 *fw_size, const struct mip4_bin_tail **pfw_info) { const struct mip4_bin_tail *fw_info; struct mip4_fw_version fw_version; u16 tail_size; if (fw->size < MIP4_BIN_TAIL_SIZE) { dev_err(&ts->client->dev, "Invalid firmware, size mismatch (tail %zd vs %zd)\n", MIP4_BIN_TAIL_SIZE, fw->size); return -EINVAL; } fw_info = (const void *)&fw->data[fw->size - MIP4_BIN_TAIL_SIZE]; #if MIP4_FW_UPDATE_DEBUG print_hex_dump(KERN_ERR, MIP4_DEVICE_NAME " Bin Info: ", DUMP_PREFIX_OFFSET, 16, 1, *fw_info, tail_size, false); #endif tail_size = get_unaligned_le16(&fw_info->tail_size); if (tail_size != MIP4_BIN_TAIL_SIZE) { dev_err(&ts->client->dev, "wrong tail size: %d (expected %zd)\n", tail_size, MIP4_BIN_TAIL_SIZE); return -EINVAL; } /* Check bin format */ if (memcmp(fw_info->tail_mark, MIP4_BIN_TAIL_MARK, sizeof(fw_info->tail_mark))) { dev_err(&ts->client->dev, "unable to locate tail marker (%*ph vs %*ph)\n", (int)sizeof(fw_info->tail_mark), fw_info->tail_mark, (int)sizeof(fw_info->tail_mark), MIP4_BIN_TAIL_MARK); return -EINVAL; } *fw_offset_start = get_unaligned_le32(&fw_info->bin_start_addr); *fw_size = get_unaligned_le32(&fw_info->bin_length); dev_dbg(&ts->client->dev, "F/W Data offset: %#08x, size: %d\n", *fw_offset_start, *fw_size); if (*fw_size % MIP4_BL_PAGE_SIZE) { dev_err(&ts->client->dev, "encoded fw length %d is not multiple of pages (%d)\n", *fw_size, MIP4_BL_PAGE_SIZE); return -EINVAL; } if (fw->size != *fw_offset_start + *fw_size) { dev_err(&ts->client->dev, "Wrong firmware size, expected %d bytes, got %zd\n", *fw_offset_start + *fw_size, fw->size); return -EINVAL; } mip4_parse_fw_version((const u8 *)&fw_info->ver_boot, &fw_version); dev_dbg(&ts->client->dev, "F/W file version %04X %04X %04X %04X\n", fw_version.boot, fw_version.core, fw_version.app, fw_version.param); dev_dbg(&ts->client->dev, "F/W chip version: %04X %04X %04X %04X\n", ts->fw_version.boot, ts->fw_version.core, ts->fw_version.app, ts->fw_version.param); /* Check F/W type */ if (fw_version.boot != 0xEEEE && fw_version.boot != 0xFFFF && fw_version.core == 0xEEEE && fw_version.app == 0xEEEE && fw_version.param == 0xEEEE) { dev_dbg(&ts->client->dev, "F/W type: Bootloader\n"); } else if (fw_version.boot == 0xEEEE && fw_version.core != 0xEEEE && fw_version.core != 0xFFFF && fw_version.app != 0xEEEE && fw_version.app != 0xFFFF && fw_version.param != 0xEEEE && fw_version.param != 0xFFFF) { dev_dbg(&ts->client->dev, "F/W type: Main\n"); } else { dev_err(&ts->client->dev, "Wrong firmware type\n"); return -EINVAL; } return 0; } static int mip4_execute_fw_update(struct mip4_ts *ts, const struct firmware *fw) { const struct mip4_bin_tail *fw_info; u32 fw_start_offset; u32 fw_size; int retires = 3; int error; error = mip4_parse_firmware(ts, fw, &fw_start_offset, &fw_size, &fw_info); if (error) return error; if (input_device_enabled(ts->input)) { disable_irq(ts->client->irq); } else { error = mip4_power_on(ts); if (error) return error; } /* Update firmware */ do { error = mip4_flash_fw(ts, fw->data, fw_size, fw_start_offset); if (!error) break; } while (--retires); if (error) dev_err(&ts->client->dev, "Failed to flash firmware: %d\n", error); /* Enable IRQ */ if (input_device_enabled(ts->input)) enable_irq(ts->client->irq); else mip4_power_off(ts); return error ? error : 0; } static ssize_t mip4_sysfs_fw_update(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); const struct firmware *fw; int error; error = request_firmware(&fw, ts->fw_name, dev); if (error) { dev_err(&ts->client->dev, "Failed to retrieve firmware %s: %d\n", ts->fw_name, error); return error; } /* * Take input mutex to prevent racing with itself and also with * userspace opening and closing the device and also suspend/resume * transitions. */ mutex_lock(&ts->input->mutex); error = mip4_execute_fw_update(ts, fw); mutex_unlock(&ts->input->mutex); release_firmware(fw); if (error) { dev_err(&ts->client->dev, "Firmware update failed: %d\n", error); return error; } return count; } static DEVICE_ATTR(update_fw, S_IWUSR, NULL, mip4_sysfs_fw_update); static ssize_t mip4_sysfs_read_fw_version(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); size_t count; /* Take lock to prevent racing with firmware update */ mutex_lock(&ts->input->mutex); count = snprintf(buf, PAGE_SIZE, "%04X %04X %04X %04X\n", ts->fw_version.boot, ts->fw_version.core, ts->fw_version.app, ts->fw_version.param); mutex_unlock(&ts->input->mutex); return count; } static DEVICE_ATTR(fw_version, S_IRUGO, mip4_sysfs_read_fw_version, NULL); static ssize_t mip4_sysfs_read_hw_version(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); size_t count; /* Take lock to prevent racing with firmware update */ mutex_lock(&ts->input->mutex); /* * product_name shows the name or version of the hardware * paired with current firmware in the chip. */ count = snprintf(buf, PAGE_SIZE, "%.*s\n", (int)sizeof(ts->product_name), ts->product_name); mutex_unlock(&ts->input->mutex); return count; } static DEVICE_ATTR(hw_version, S_IRUGO, mip4_sysfs_read_hw_version, NULL); static ssize_t mip4_sysfs_read_product_id(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); size_t count; mutex_lock(&ts->input->mutex); count = snprintf(buf, PAGE_SIZE, "%04X\n", ts->product_id); mutex_unlock(&ts->input->mutex); return count; } static DEVICE_ATTR(product_id, S_IRUGO, mip4_sysfs_read_product_id, NULL); static ssize_t mip4_sysfs_read_ic_name(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); size_t count; mutex_lock(&ts->input->mutex); count = snprintf(buf, PAGE_SIZE, "%.*s\n", (int)sizeof(ts->ic_name), ts->ic_name); mutex_unlock(&ts->input->mutex); return count; } static DEVICE_ATTR(ic_name, S_IRUGO, mip4_sysfs_read_ic_name, NULL); static struct attribute *mip4_attrs[] = { &dev_attr_fw_version.attr, &dev_attr_hw_version.attr, &dev_attr_product_id.attr, &dev_attr_ic_name.attr, &dev_attr_update_fw.attr, NULL, }; static const struct attribute_group mip4_attr_group = { .attrs = mip4_attrs, }; static int mip4_probe(struct i2c_client *client) { struct mip4_ts *ts; struct input_dev *input; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "Not supported I2C adapter\n"); return -ENXIO; } ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; input = devm_input_allocate_device(&client->dev); if (!input) return -ENOMEM; ts->client = client; ts->input = input; snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); ts->gpio_ce = devm_gpiod_get_optional(&client->dev, "ce", GPIOD_OUT_LOW); if (IS_ERR(ts->gpio_ce)) return dev_err_probe(&client->dev, PTR_ERR(ts->gpio_ce), "Failed to get gpio\n"); error = mip4_power_on(ts); if (error) return error; error = mip4_query_device(ts); mip4_power_off(ts); if (error) return error; input->name = "MELFAS MIP4 Touchscreen"; input->phys = ts->phys; input->id.bustype = BUS_I2C; input->id.vendor = 0x13c5; input->id.product = ts->product_id; input->open = mip4_input_open; input->close = mip4_input_close; input_set_drvdata(input, ts); input->keycode = ts->key_code; input->keycodesize = sizeof(*ts->key_code); input->keycodemax = ts->key_num; input_set_abs_params(input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_PALM, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_X, 0, ts->max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, ts->max_y, 0, 0); input_set_abs_params(input, ABS_MT_PRESSURE, MIP4_PRESSURE_MIN, MIP4_PRESSURE_MAX, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, MIP4_TOUCH_MAJOR_MIN, MIP4_TOUCH_MAJOR_MAX, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MINOR, MIP4_TOUCH_MINOR_MIN, MIP4_TOUCH_MINOR_MAX, 0, 0); input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->ppm_x); input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->ppm_y); error = input_mt_init_slots(input, MIP4_MAX_FINGERS, INPUT_MT_DIRECT); if (error) return error; i2c_set_clientdata(client, ts); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, mip4_interrupt, IRQF_ONESHOT | IRQF_NO_AUTOEN, MIP4_DEVICE_NAME, ts); if (error) { dev_err(&client->dev, "Failed to request interrupt %d: %d\n", client->irq, error); return error; } error = input_register_device(input); if (error) { dev_err(&client->dev, "Failed to register input device: %d\n", error); return error; } error = devm_device_add_group(&client->dev, &mip4_attr_group); if (error) { dev_err(&client->dev, "Failed to create sysfs attribute group: %d\n", error); return error; } return 0; } static int mip4_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; mutex_lock(&input->mutex); if (device_may_wakeup(dev)) ts->wake_irq_enabled = enable_irq_wake(client->irq) == 0; else if (input_device_enabled(input)) mip4_disable(ts); mutex_unlock(&input->mutex); return 0; } static int mip4_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mip4_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; mutex_lock(&input->mutex); if (ts->wake_irq_enabled) disable_irq_wake(client->irq); else if (input_device_enabled(input)) mip4_enable(ts); mutex_unlock(&input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(mip4_pm_ops, mip4_suspend, mip4_resume); #ifdef CONFIG_OF static const struct of_device_id mip4_of_match[] = { { .compatible = "melfas,"MIP4_DEVICE_NAME, }, { }, }; MODULE_DEVICE_TABLE(of, mip4_of_match); #endif #ifdef CONFIG_ACPI static const struct acpi_device_id mip4_acpi_match[] = { { "MLFS0000", 0}, { }, }; MODULE_DEVICE_TABLE(acpi, mip4_acpi_match); #endif static const struct i2c_device_id mip4_i2c_ids[] = { { MIP4_DEVICE_NAME, 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, mip4_i2c_ids); static struct i2c_driver mip4_driver = { .id_table = mip4_i2c_ids, .probe = mip4_probe, .driver = { .name = MIP4_DEVICE_NAME, .of_match_table = of_match_ptr(mip4_of_match), .acpi_match_table = ACPI_PTR(mip4_acpi_match), .pm = pm_sleep_ptr(&mip4_pm_ops), }, }; module_i2c_driver(mip4_driver); MODULE_DESCRIPTION("MELFAS MIP4 Touchscreen"); MODULE_AUTHOR("Sangwon Jee <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/melfas_mip4.c
// SPDX-License-Identifier: GPL-2.0-only /* * Microchip AR1020 and AR1021 driver for I2C * * Author: Christian Gmeiner <[email protected]> */ #include <linux/bitops.h> #include <linux/module.h> #include <linux/input.h> #include <linux/of.h> #include <linux/i2c.h> #include <linux/irq.h> #include <linux/interrupt.h> #define AR1021_TOUCH_PKG_SIZE 5 #define AR1021_MAX_X 4095 #define AR1021_MAX_Y 4095 #define AR1021_CMD 0x55 #define AR1021_CMD_ENABLE_TOUCH 0x12 struct ar1021_i2c { struct i2c_client *client; struct input_dev *input; u8 data[AR1021_TOUCH_PKG_SIZE]; }; static irqreturn_t ar1021_i2c_irq(int irq, void *dev_id) { struct ar1021_i2c *ar1021 = dev_id; struct input_dev *input = ar1021->input; u8 *data = ar1021->data; unsigned int x, y, button; int retval; retval = i2c_master_recv(ar1021->client, ar1021->data, sizeof(ar1021->data)); if (retval != sizeof(ar1021->data)) goto out; /* sync bit set ? */ if (!(data[0] & BIT(7))) goto out; button = data[0] & BIT(0); x = ((data[2] & 0x1f) << 7) | (data[1] & 0x7f); y = ((data[4] & 0x1f) << 7) | (data[3] & 0x7f); input_report_abs(input, ABS_X, x); input_report_abs(input, ABS_Y, y); input_report_key(input, BTN_TOUCH, button); input_sync(input); out: return IRQ_HANDLED; } static int ar1021_i2c_open(struct input_dev *dev) { static const u8 cmd_enable_touch[] = { AR1021_CMD, 0x01, /* number of bytes after this */ AR1021_CMD_ENABLE_TOUCH }; struct ar1021_i2c *ar1021 = input_get_drvdata(dev); struct i2c_client *client = ar1021->client; int error; error = i2c_master_send(ar1021->client, cmd_enable_touch, sizeof(cmd_enable_touch)); if (error < 0) return error; enable_irq(client->irq); return 0; } static void ar1021_i2c_close(struct input_dev *dev) { struct ar1021_i2c *ar1021 = input_get_drvdata(dev); struct i2c_client *client = ar1021->client; disable_irq(client->irq); } static int ar1021_i2c_probe(struct i2c_client *client) { struct ar1021_i2c *ar1021; struct input_dev *input; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "i2c_check_functionality error\n"); return -ENXIO; } ar1021 = devm_kzalloc(&client->dev, sizeof(*ar1021), GFP_KERNEL); if (!ar1021) return -ENOMEM; input = devm_input_allocate_device(&client->dev); if (!input) return -ENOMEM; ar1021->client = client; ar1021->input = input; input->name = "ar1021 I2C Touchscreen"; input->id.bustype = BUS_I2C; input->dev.parent = &client->dev; input->open = ar1021_i2c_open; input->close = ar1021_i2c_close; __set_bit(INPUT_PROP_DIRECT, input->propbit); input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, 0, AR1021_MAX_X, 0, 0); input_set_abs_params(input, ABS_Y, 0, AR1021_MAX_Y, 0, 0); input_set_drvdata(input, ar1021); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, ar1021_i2c_irq, IRQF_ONESHOT | IRQF_NO_AUTOEN, "ar1021_i2c", ar1021); if (error) { dev_err(&client->dev, "Failed to enable IRQ, error: %d\n", error); return error; } error = input_register_device(ar1021->input); if (error) { dev_err(&client->dev, "Failed to register input device, error: %d\n", error); return error; } return 0; } static int ar1021_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); disable_irq(client->irq); return 0; } static int ar1021_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(ar1021_i2c_pm, ar1021_i2c_suspend, ar1021_i2c_resume); static const struct i2c_device_id ar1021_i2c_id[] = { { "ar1021", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, ar1021_i2c_id); static const struct of_device_id ar1021_i2c_of_match[] = { { .compatible = "microchip,ar1021-i2c", }, { } }; MODULE_DEVICE_TABLE(of, ar1021_i2c_of_match); static struct i2c_driver ar1021_i2c_driver = { .driver = { .name = "ar1021_i2c", .pm = pm_sleep_ptr(&ar1021_i2c_pm), .of_match_table = ar1021_i2c_of_match, }, .probe = ar1021_i2c_probe, .id_table = ar1021_i2c_id, }; module_i2c_driver(ar1021_i2c_driver); MODULE_AUTHOR("Christian Gmeiner <[email protected]>"); MODULE_DESCRIPTION("Microchip AR1020 and AR1021 I2C Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ar1021_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Touchscreen driver for Marvell 88PM860x * * Copyright (C) 2009 Marvell International Ltd. * Haojian Zhuang <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/mfd/88pm860x.h> #include <linux/slab.h> #include <linux/device.h> #define MEAS_LEN (8) #define ACCURATE_BIT (12) /* touch register */ #define MEAS_EN3 (0x52) #define MEAS_TSIX_1 (0x8D) #define MEAS_TSIX_2 (0x8E) #define MEAS_TSIY_1 (0x8F) #define MEAS_TSIY_2 (0x90) #define MEAS_TSIZ1_1 (0x91) #define MEAS_TSIZ1_2 (0x92) #define MEAS_TSIZ2_1 (0x93) #define MEAS_TSIZ2_2 (0x94) /* bit definitions of touch */ #define MEAS_PD_EN (1 << 3) #define MEAS_TSIX_EN (1 << 4) #define MEAS_TSIY_EN (1 << 5) #define MEAS_TSIZ1_EN (1 << 6) #define MEAS_TSIZ2_EN (1 << 7) struct pm860x_touch { struct input_dev *idev; struct i2c_client *i2c; struct pm860x_chip *chip; int irq; int res_x; /* resistor of Xplate */ }; static irqreturn_t pm860x_touch_handler(int irq, void *data) { struct pm860x_touch *touch = data; struct pm860x_chip *chip = touch->chip; unsigned char buf[MEAS_LEN]; int x, y, pen_down; int z1, z2, rt = 0; int ret; ret = pm860x_bulk_read(touch->i2c, MEAS_TSIX_1, MEAS_LEN, buf); if (ret < 0) goto out; pen_down = buf[1] & (1 << 6); x = ((buf[0] & 0xFF) << 4) | (buf[1] & 0x0F); y = ((buf[2] & 0xFF) << 4) | (buf[3] & 0x0F); z1 = ((buf[4] & 0xFF) << 4) | (buf[5] & 0x0F); z2 = ((buf[6] & 0xFF) << 4) | (buf[7] & 0x0F); if (pen_down) { if ((x != 0) && (z1 != 0) && (touch->res_x != 0)) { rt = z2 / z1 - 1; rt = (rt * touch->res_x * x) >> ACCURATE_BIT; dev_dbg(chip->dev, "z1:%d, z2:%d, rt:%d\n", z1, z2, rt); } input_report_abs(touch->idev, ABS_X, x); input_report_abs(touch->idev, ABS_Y, y); input_report_abs(touch->idev, ABS_PRESSURE, rt); input_report_key(touch->idev, BTN_TOUCH, 1); dev_dbg(chip->dev, "pen down at [%d, %d].\n", x, y); } else { input_report_abs(touch->idev, ABS_PRESSURE, 0); input_report_key(touch->idev, BTN_TOUCH, 0); dev_dbg(chip->dev, "pen release\n"); } input_sync(touch->idev); out: return IRQ_HANDLED; } static int pm860x_touch_open(struct input_dev *dev) { struct pm860x_touch *touch = input_get_drvdata(dev); int data, ret; data = MEAS_PD_EN | MEAS_TSIX_EN | MEAS_TSIY_EN | MEAS_TSIZ1_EN | MEAS_TSIZ2_EN; ret = pm860x_set_bits(touch->i2c, MEAS_EN3, data, data); if (ret < 0) goto out; return 0; out: return ret; } static void pm860x_touch_close(struct input_dev *dev) { struct pm860x_touch *touch = input_get_drvdata(dev); int data; data = MEAS_PD_EN | MEAS_TSIX_EN | MEAS_TSIY_EN | MEAS_TSIZ1_EN | MEAS_TSIZ2_EN; pm860x_set_bits(touch->i2c, MEAS_EN3, data, 0); } #ifdef CONFIG_OF static int pm860x_touch_dt_init(struct platform_device *pdev, struct pm860x_chip *chip, int *res_x) { struct device_node *np = pdev->dev.parent->of_node; struct i2c_client *i2c = (chip->id == CHIP_PM8607) ? chip->client \ : chip->companion; int data, n, ret; if (!np) return -ENODEV; np = of_get_child_by_name(np, "touch"); if (!np) { dev_err(&pdev->dev, "Can't find touch node\n"); return -EINVAL; } /* set GPADC MISC1 register */ data = 0; if (!of_property_read_u32(np, "marvell,88pm860x-gpadc-prebias", &n)) data |= (n << 1) & PM8607_GPADC_PREBIAS_MASK; if (!of_property_read_u32(np, "marvell,88pm860x-gpadc-slot-cycle", &n)) data |= (n << 3) & PM8607_GPADC_SLOT_CYCLE_MASK; if (!of_property_read_u32(np, "marvell,88pm860x-gpadc-off-scale", &n)) data |= (n << 5) & PM8607_GPADC_OFF_SCALE_MASK; if (!of_property_read_u32(np, "marvell,88pm860x-gpadc-sw-cal", &n)) data |= (n << 7) & PM8607_GPADC_SW_CAL_MASK; if (data) { ret = pm860x_reg_write(i2c, PM8607_GPADC_MISC1, data); if (ret < 0) goto err_put_node; } /* set tsi prebias time */ if (!of_property_read_u32(np, "marvell,88pm860x-tsi-prebias", &data)) { ret = pm860x_reg_write(i2c, PM8607_TSI_PREBIAS, data); if (ret < 0) goto err_put_node; } /* set prebias & prechg time of pen detect */ data = 0; if (!of_property_read_u32(np, "marvell,88pm860x-pen-prebias", &n)) data |= n & PM8607_PD_PREBIAS_MASK; if (!of_property_read_u32(np, "marvell,88pm860x-pen-prechg", &n)) data |= n & PM8607_PD_PRECHG_MASK; if (data) { ret = pm860x_reg_write(i2c, PM8607_PD_PREBIAS, data); if (ret < 0) goto err_put_node; } of_property_read_u32(np, "marvell,88pm860x-resistor-X", res_x); of_node_put(np); return 0; err_put_node: of_node_put(np); return -EINVAL; } #else #define pm860x_touch_dt_init(x, y, z) (-1) #endif static int pm860x_touch_probe(struct platform_device *pdev) { struct pm860x_chip *chip = dev_get_drvdata(pdev->dev.parent); struct pm860x_touch_pdata *pdata = dev_get_platdata(&pdev->dev); struct pm860x_touch *touch; struct i2c_client *i2c = (chip->id == CHIP_PM8607) ? chip->client \ : chip->companion; int irq, ret, res_x = 0, data = 0; irq = platform_get_irq(pdev, 0); if (irq < 0) return -EINVAL; if (pm860x_touch_dt_init(pdev, chip, &res_x)) { if (pdata) { /* set GPADC MISC1 register */ data = 0; data |= (pdata->gpadc_prebias << 1) & PM8607_GPADC_PREBIAS_MASK; data |= (pdata->slot_cycle << 3) & PM8607_GPADC_SLOT_CYCLE_MASK; data |= (pdata->off_scale << 5) & PM8607_GPADC_OFF_SCALE_MASK; data |= (pdata->sw_cal << 7) & PM8607_GPADC_SW_CAL_MASK; if (data) { ret = pm860x_reg_write(i2c, PM8607_GPADC_MISC1, data); if (ret < 0) return -EINVAL; } /* set tsi prebias time */ if (pdata->tsi_prebias) { data = pdata->tsi_prebias; ret = pm860x_reg_write(i2c, PM8607_TSI_PREBIAS, data); if (ret < 0) return -EINVAL; } /* set prebias & prechg time of pen detect */ data = 0; data |= pdata->pen_prebias & PM8607_PD_PREBIAS_MASK; data |= (pdata->pen_prechg << 5) & PM8607_PD_PRECHG_MASK; if (data) { ret = pm860x_reg_write(i2c, PM8607_PD_PREBIAS, data); if (ret < 0) return -EINVAL; } res_x = pdata->res_x; } else { dev_err(&pdev->dev, "failed to get platform data\n"); return -EINVAL; } } /* enable GPADC */ ret = pm860x_set_bits(i2c, PM8607_GPADC_MISC1, PM8607_GPADC_EN, PM8607_GPADC_EN); if (ret) return ret; touch = devm_kzalloc(&pdev->dev, sizeof(struct pm860x_touch), GFP_KERNEL); if (!touch) return -ENOMEM; touch->idev = devm_input_allocate_device(&pdev->dev); if (!touch->idev) { dev_err(&pdev->dev, "Failed to allocate input device!\n"); return -ENOMEM; } touch->idev->name = "88pm860x-touch"; touch->idev->phys = "88pm860x/input0"; touch->idev->id.bustype = BUS_I2C; touch->idev->dev.parent = &pdev->dev; touch->idev->open = pm860x_touch_open; touch->idev->close = pm860x_touch_close; touch->chip = chip; touch->i2c = i2c; touch->irq = irq; touch->res_x = res_x; input_set_drvdata(touch->idev, touch); ret = devm_request_threaded_irq(&pdev->dev, touch->irq, NULL, pm860x_touch_handler, IRQF_ONESHOT, "touch", touch); if (ret < 0) return ret; __set_bit(EV_ABS, touch->idev->evbit); __set_bit(ABS_X, touch->idev->absbit); __set_bit(ABS_Y, touch->idev->absbit); __set_bit(ABS_PRESSURE, touch->idev->absbit); __set_bit(EV_SYN, touch->idev->evbit); __set_bit(EV_KEY, touch->idev->evbit); __set_bit(BTN_TOUCH, touch->idev->keybit); input_set_abs_params(touch->idev, ABS_X, 0, 1 << ACCURATE_BIT, 0, 0); input_set_abs_params(touch->idev, ABS_Y, 0, 1 << ACCURATE_BIT, 0, 0); input_set_abs_params(touch->idev, ABS_PRESSURE, 0, 1 << ACCURATE_BIT, 0, 0); ret = input_register_device(touch->idev); if (ret < 0) { dev_err(chip->dev, "Failed to register touch!\n"); return ret; } return 0; } static struct platform_driver pm860x_touch_driver = { .driver = { .name = "88pm860x-touch", }, .probe = pm860x_touch_probe, }; module_platform_driver(pm860x_touch_driver); MODULE_DESCRIPTION("Touchscreen driver for Marvell Semiconductor 88PM860x"); MODULE_AUTHOR("Haojian Zhuang <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:88pm860x-touch");
linux-master
drivers/input/touchscreen/88pm860x-ts.c
/* * Touchscreen driver for the TS-4800 board * * Copyright (c) 2015 - Savoir-faire Linux * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/bitops.h> #include <linux/input.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/regmap.h> /* polling interval in ms */ #define POLL_INTERVAL 3 #define DEBOUNCE_COUNT 1 /* sensor values are 12-bit wide */ #define MAX_12BIT ((1 << 12) - 1) #define PENDOWN_MASK 0x1 #define X_OFFSET 0x0 #define Y_OFFSET 0x2 struct ts4800_ts { struct input_dev *input; struct device *dev; char phys[32]; void __iomem *base; struct regmap *regmap; unsigned int reg; unsigned int bit; bool pendown; int debounce; }; static int ts4800_ts_open(struct input_dev *input_dev) { struct ts4800_ts *ts = input_get_drvdata(input_dev); int error; ts->pendown = false; ts->debounce = DEBOUNCE_COUNT; error = regmap_update_bits(ts->regmap, ts->reg, ts->bit, ts->bit); if (error) { dev_warn(ts->dev, "Failed to enable touchscreen: %d\n", error); return error; } return 0; } static void ts4800_ts_close(struct input_dev *input_dev) { struct ts4800_ts *ts = input_get_drvdata(input_dev); int ret; ret = regmap_update_bits(ts->regmap, ts->reg, ts->bit, 0); if (ret) dev_warn(ts->dev, "Failed to disable touchscreen\n"); } static void ts4800_ts_poll(struct input_dev *input_dev) { struct ts4800_ts *ts = input_get_drvdata(input_dev); u16 last_x = readw(ts->base + X_OFFSET); u16 last_y = readw(ts->base + Y_OFFSET); bool pendown = last_x & PENDOWN_MASK; if (pendown) { if (ts->debounce) { ts->debounce--; return; } if (!ts->pendown) { input_report_key(input_dev, BTN_TOUCH, 1); ts->pendown = true; } last_x = ((~last_x) >> 4) & MAX_12BIT; last_y = ((~last_y) >> 4) & MAX_12BIT; input_report_abs(input_dev, ABS_X, last_x); input_report_abs(input_dev, ABS_Y, last_y); input_sync(input_dev); } else if (ts->pendown) { ts->pendown = false; ts->debounce = DEBOUNCE_COUNT; input_report_key(input_dev, BTN_TOUCH, 0); input_sync(input_dev); } } static int ts4800_parse_dt(struct platform_device *pdev, struct ts4800_ts *ts) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct device_node *syscon_np; u32 reg, bit; int error; syscon_np = of_parse_phandle(np, "syscon", 0); if (!syscon_np) { dev_err(dev, "no syscon property\n"); return -ENODEV; } ts->regmap = syscon_node_to_regmap(syscon_np); of_node_put(syscon_np); if (IS_ERR(ts->regmap)) { dev_err(dev, "cannot get parent's regmap\n"); return PTR_ERR(ts->regmap); } error = of_property_read_u32_index(np, "syscon", 1, &reg); if (error < 0) { dev_err(dev, "no offset in syscon\n"); return error; } ts->reg = reg; error = of_property_read_u32_index(np, "syscon", 2, &bit); if (error < 0) { dev_err(dev, "no bit in syscon\n"); return error; } ts->bit = BIT(bit); return 0; } static int ts4800_ts_probe(struct platform_device *pdev) { struct input_dev *input_dev; struct ts4800_ts *ts; int error; ts = devm_kzalloc(&pdev->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; error = ts4800_parse_dt(pdev, ts); if (error) return error; ts->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(ts->base)) return PTR_ERR(ts->base); input_dev = devm_input_allocate_device(&pdev->dev); if (!input_dev) return -ENOMEM; snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&pdev->dev)); ts->input = input_dev; ts->dev = &pdev->dev; input_set_drvdata(input_dev, ts); input_dev->name = "TS-4800 Touchscreen"; input_dev->phys = ts->phys; input_dev->open = ts4800_ts_open; input_dev->close = ts4800_ts_close; input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, 0, 0); error = input_setup_polling(input_dev, ts4800_ts_poll); if (error) { dev_err(&pdev->dev, "Unable to set up polling: %d\n", error); return error; } input_set_poll_interval(input_dev, POLL_INTERVAL); error = input_register_device(input_dev); if (error) { dev_err(&pdev->dev, "Unable to register input device: %d\n", error); return error; } return 0; } static const struct of_device_id ts4800_ts_of_match[] = { { .compatible = "technologic,ts4800-ts", }, { }, }; MODULE_DEVICE_TABLE(of, ts4800_ts_of_match); static struct platform_driver ts4800_ts_driver = { .driver = { .name = "ts4800-ts", .of_match_table = ts4800_ts_of_match, }, .probe = ts4800_ts_probe, }; module_platform_driver(ts4800_ts_driver); MODULE_AUTHOR("Damien Riegel <[email protected]>"); MODULE_DESCRIPTION("TS-4800 Touchscreen Driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:ts4800_ts");
linux-master
drivers/input/touchscreen/ts4800-ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2006-2008 Michael Hennerich, Analog Devices Inc. * * Description: AD7877 based touchscreen, sensor (ADCs), DAC and GPIO driver * Based on: ads7846.c * * Bugs: Enter bugs at http://blackfin.uclinux.org/ * * History: * Copyright (c) 2005 David Brownell * Copyright (c) 2006 Nokia Corporation * Various changes: Imre Deak <[email protected]> * * Using code from: * - corgi_ts.c * Copyright (C) 2004-2005 Richard Purdie * - omap_ts.[hc], ads7846.h, ts_osk.c * Copyright (C) 2002 MontaVista Software * Copyright (C) 2004 Texas Instruments * Copyright (C) 2005 Dirk Behme */ #include <linux/device.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/pm.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/spi/ad7877.h> #include <linux/module.h> #include <asm/irq.h> #define TS_PEN_UP_TIMEOUT msecs_to_jiffies(100) #define MAX_SPI_FREQ_HZ 20000000 #define MAX_12BIT ((1<<12)-1) #define AD7877_REG_ZEROS 0 #define AD7877_REG_CTRL1 1 #define AD7877_REG_CTRL2 2 #define AD7877_REG_ALERT 3 #define AD7877_REG_AUX1HIGH 4 #define AD7877_REG_AUX1LOW 5 #define AD7877_REG_BAT1HIGH 6 #define AD7877_REG_BAT1LOW 7 #define AD7877_REG_BAT2HIGH 8 #define AD7877_REG_BAT2LOW 9 #define AD7877_REG_TEMP1HIGH 10 #define AD7877_REG_TEMP1LOW 11 #define AD7877_REG_SEQ0 12 #define AD7877_REG_SEQ1 13 #define AD7877_REG_DAC 14 #define AD7877_REG_NONE1 15 #define AD7877_REG_EXTWRITE 15 #define AD7877_REG_XPLUS 16 #define AD7877_REG_YPLUS 17 #define AD7877_REG_Z2 18 #define AD7877_REG_aux1 19 #define AD7877_REG_aux2 20 #define AD7877_REG_aux3 21 #define AD7877_REG_bat1 22 #define AD7877_REG_bat2 23 #define AD7877_REG_temp1 24 #define AD7877_REG_temp2 25 #define AD7877_REG_Z1 26 #define AD7877_REG_GPIOCTRL1 27 #define AD7877_REG_GPIOCTRL2 28 #define AD7877_REG_GPIODATA 29 #define AD7877_REG_NONE2 30 #define AD7877_REG_NONE3 31 #define AD7877_SEQ_YPLUS_BIT (1<<11) #define AD7877_SEQ_XPLUS_BIT (1<<10) #define AD7877_SEQ_Z2_BIT (1<<9) #define AD7877_SEQ_AUX1_BIT (1<<8) #define AD7877_SEQ_AUX2_BIT (1<<7) #define AD7877_SEQ_AUX3_BIT (1<<6) #define AD7877_SEQ_BAT1_BIT (1<<5) #define AD7877_SEQ_BAT2_BIT (1<<4) #define AD7877_SEQ_TEMP1_BIT (1<<3) #define AD7877_SEQ_TEMP2_BIT (1<<2) #define AD7877_SEQ_Z1_BIT (1<<1) enum { AD7877_SEQ_YPOS = 0, AD7877_SEQ_XPOS = 1, AD7877_SEQ_Z2 = 2, AD7877_SEQ_AUX1 = 3, AD7877_SEQ_AUX2 = 4, AD7877_SEQ_AUX3 = 5, AD7877_SEQ_BAT1 = 6, AD7877_SEQ_BAT2 = 7, AD7877_SEQ_TEMP1 = 8, AD7877_SEQ_TEMP2 = 9, AD7877_SEQ_Z1 = 10, AD7877_NR_SENSE = 11, }; /* DAC Register Default RANGE 0 to Vcc, Volatge Mode, DAC On */ #define AD7877_DAC_CONF 0x1 /* If gpio3 is set AUX3/GPIO3 acts as GPIO Output */ #define AD7877_EXTW_GPIO_3_CONF 0x1C4 #define AD7877_EXTW_GPIO_DATA 0x200 /* Control REG 2 */ #define AD7877_TMR(x) ((x & 0x3) << 0) #define AD7877_REF(x) ((x & 0x1) << 2) #define AD7877_POL(x) ((x & 0x1) << 3) #define AD7877_FCD(x) ((x & 0x3) << 4) #define AD7877_PM(x) ((x & 0x3) << 6) #define AD7877_ACQ(x) ((x & 0x3) << 8) #define AD7877_AVG(x) ((x & 0x3) << 10) /* Control REG 1 */ #define AD7877_SER (1 << 11) /* non-differential */ #define AD7877_DFR (0 << 11) /* differential */ #define AD7877_MODE_NOC (0) /* Do not convert */ #define AD7877_MODE_SCC (1) /* Single channel conversion */ #define AD7877_MODE_SEQ0 (2) /* Sequence 0 in Slave Mode */ #define AD7877_MODE_SEQ1 (3) /* Sequence 1 in Master Mode */ #define AD7877_CHANADD(x) ((x&0xF)<<7) #define AD7877_READADD(x) ((x)<<2) #define AD7877_WRITEADD(x) ((x)<<12) #define AD7877_READ_CHAN(x) (AD7877_WRITEADD(AD7877_REG_CTRL1) | AD7877_SER | \ AD7877_MODE_SCC | AD7877_CHANADD(AD7877_REG_ ## x) | \ AD7877_READADD(AD7877_REG_ ## x)) #define AD7877_MM_SEQUENCE (AD7877_SEQ_YPLUS_BIT | AD7877_SEQ_XPLUS_BIT | \ AD7877_SEQ_Z2_BIT | AD7877_SEQ_Z1_BIT) /* * Non-touchscreen sensors only use single-ended conversions. */ struct ser_req { u16 reset; u16 ref_on; u16 command; struct spi_message msg; struct spi_transfer xfer[6]; /* * DMA (thus cache coherency maintenance) requires the * transfer buffers to live in their own cache lines. */ u16 sample ____cacheline_aligned; }; struct ad7877 { struct input_dev *input; char phys[32]; struct spi_device *spi; u16 model; u16 vref_delay_usecs; u16 x_plate_ohms; u16 pressure_max; u16 cmd_crtl1; u16 cmd_crtl2; u16 cmd_dummy; u16 dac; u8 stopacq_polarity; u8 first_conversion_delay; u8 acquisition_time; u8 averaging; u8 pen_down_acc_interval; struct spi_transfer xfer[AD7877_NR_SENSE + 2]; struct spi_message msg; struct mutex mutex; bool disabled; /* P: mutex */ bool gpio3; /* P: mutex */ bool gpio4; /* P: mutex */ spinlock_t lock; struct timer_list timer; /* P: lock */ /* * DMA (thus cache coherency maintenance) requires the * transfer buffers to live in their own cache lines. */ u16 conversion_data[AD7877_NR_SENSE] ____cacheline_aligned; }; static bool gpio3; module_param(gpio3, bool, 0); MODULE_PARM_DESC(gpio3, "If gpio3 is set to 1 AUX3 acts as GPIO3"); static int ad7877_read(struct spi_device *spi, u16 reg) { struct ser_req *req; int status, ret; req = kzalloc(sizeof *req, GFP_KERNEL); if (!req) return -ENOMEM; spi_message_init(&req->msg); req->command = (u16) (AD7877_WRITEADD(AD7877_REG_CTRL1) | AD7877_READADD(reg)); req->xfer[0].tx_buf = &req->command; req->xfer[0].len = 2; req->xfer[0].cs_change = 1; req->xfer[1].rx_buf = &req->sample; req->xfer[1].len = 2; spi_message_add_tail(&req->xfer[0], &req->msg); spi_message_add_tail(&req->xfer[1], &req->msg); status = spi_sync(spi, &req->msg); ret = status ? : req->sample; kfree(req); return ret; } static int ad7877_write(struct spi_device *spi, u16 reg, u16 val) { struct ser_req *req; int status; req = kzalloc(sizeof *req, GFP_KERNEL); if (!req) return -ENOMEM; spi_message_init(&req->msg); req->command = (u16) (AD7877_WRITEADD(reg) | (val & MAX_12BIT)); req->xfer[0].tx_buf = &req->command; req->xfer[0].len = 2; spi_message_add_tail(&req->xfer[0], &req->msg); status = spi_sync(spi, &req->msg); kfree(req); return status; } static int ad7877_read_adc(struct spi_device *spi, unsigned command) { struct ad7877 *ts = spi_get_drvdata(spi); struct ser_req *req; int status; int sample; int i; req = kzalloc(sizeof *req, GFP_KERNEL); if (!req) return -ENOMEM; spi_message_init(&req->msg); /* activate reference, so it has time to settle; */ req->ref_on = AD7877_WRITEADD(AD7877_REG_CTRL2) | AD7877_POL(ts->stopacq_polarity) | AD7877_AVG(0) | AD7877_PM(2) | AD7877_TMR(0) | AD7877_ACQ(ts->acquisition_time) | AD7877_FCD(0); req->reset = AD7877_WRITEADD(AD7877_REG_CTRL1) | AD7877_MODE_NOC; req->command = (u16) command; req->xfer[0].tx_buf = &req->reset; req->xfer[0].len = 2; req->xfer[0].cs_change = 1; req->xfer[1].tx_buf = &req->ref_on; req->xfer[1].len = 2; req->xfer[1].delay.value = ts->vref_delay_usecs; req->xfer[1].delay.unit = SPI_DELAY_UNIT_USECS; req->xfer[1].cs_change = 1; req->xfer[2].tx_buf = &req->command; req->xfer[2].len = 2; req->xfer[2].delay.value = ts->vref_delay_usecs; req->xfer[2].delay.unit = SPI_DELAY_UNIT_USECS; req->xfer[2].cs_change = 1; req->xfer[3].rx_buf = &req->sample; req->xfer[3].len = 2; req->xfer[3].cs_change = 1; req->xfer[4].tx_buf = &ts->cmd_crtl2; /*REF OFF*/ req->xfer[4].len = 2; req->xfer[4].cs_change = 1; req->xfer[5].tx_buf = &ts->cmd_crtl1; /*DEFAULT*/ req->xfer[5].len = 2; /* group all the transfers together, so we can't interfere with * reading touchscreen state; disable penirq while sampling */ for (i = 0; i < 6; i++) spi_message_add_tail(&req->xfer[i], &req->msg); status = spi_sync(spi, &req->msg); sample = req->sample; kfree(req); return status ? : sample; } static int ad7877_process_data(struct ad7877 *ts) { struct input_dev *input_dev = ts->input; unsigned Rt; u16 x, y, z1, z2; x = ts->conversion_data[AD7877_SEQ_XPOS] & MAX_12BIT; y = ts->conversion_data[AD7877_SEQ_YPOS] & MAX_12BIT; z1 = ts->conversion_data[AD7877_SEQ_Z1] & MAX_12BIT; z2 = ts->conversion_data[AD7877_SEQ_Z2] & MAX_12BIT; /* * The samples processed here are already preprocessed by the AD7877. * The preprocessing function consists of an averaging filter. * The combination of 'first conversion delay' and averaging provides a robust solution, * discarding the spurious noise in the signal and keeping only the data of interest. * The size of the averaging filter is programmable. (dev.platform_data, see linux/spi/ad7877.h) * Other user-programmable conversion controls include variable acquisition time, * and first conversion delay. Up to 16 averages can be taken per conversion. */ if (likely(x && z1)) { /* compute touch pressure resistance using equation #1 */ Rt = (z2 - z1) * x * ts->x_plate_ohms; Rt /= z1; Rt = (Rt + 2047) >> 12; /* * Sample found inconsistent, pressure is beyond * the maximum. Don't report it to user space. */ if (Rt > ts->pressure_max) return -EINVAL; if (!timer_pending(&ts->timer)) input_report_key(input_dev, BTN_TOUCH, 1); input_report_abs(input_dev, ABS_X, x); input_report_abs(input_dev, ABS_Y, y); input_report_abs(input_dev, ABS_PRESSURE, Rt); input_sync(input_dev); return 0; } return -EINVAL; } static inline void ad7877_ts_event_release(struct ad7877 *ts) { struct input_dev *input_dev = ts->input; input_report_abs(input_dev, ABS_PRESSURE, 0); input_report_key(input_dev, BTN_TOUCH, 0); input_sync(input_dev); } static void ad7877_timer(struct timer_list *t) { struct ad7877 *ts = from_timer(ts, t, timer); unsigned long flags; spin_lock_irqsave(&ts->lock, flags); ad7877_ts_event_release(ts); spin_unlock_irqrestore(&ts->lock, flags); } static irqreturn_t ad7877_irq(int irq, void *handle) { struct ad7877 *ts = handle; unsigned long flags; int error; error = spi_sync(ts->spi, &ts->msg); if (error) { dev_err(&ts->spi->dev, "spi_sync --> %d\n", error); goto out; } spin_lock_irqsave(&ts->lock, flags); error = ad7877_process_data(ts); if (!error) mod_timer(&ts->timer, jiffies + TS_PEN_UP_TIMEOUT); spin_unlock_irqrestore(&ts->lock, flags); out: return IRQ_HANDLED; } static void ad7877_disable(void *data) { struct ad7877 *ts = data; mutex_lock(&ts->mutex); if (!ts->disabled) { ts->disabled = true; disable_irq(ts->spi->irq); if (del_timer_sync(&ts->timer)) ad7877_ts_event_release(ts); } /* * We know the chip's in lowpower mode since we always * leave it that way after every request */ mutex_unlock(&ts->mutex); } static void ad7877_enable(struct ad7877 *ts) { mutex_lock(&ts->mutex); if (ts->disabled) { ts->disabled = false; enable_irq(ts->spi->irq); } mutex_unlock(&ts->mutex); } #define SHOW(name) static ssize_t \ name ## _show(struct device *dev, struct device_attribute *attr, char *buf) \ { \ struct ad7877 *ts = dev_get_drvdata(dev); \ ssize_t v = ad7877_read_adc(ts->spi, \ AD7877_READ_CHAN(name)); \ if (v < 0) \ return v; \ return sprintf(buf, "%u\n", (unsigned) v); \ } \ static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL); SHOW(aux1) SHOW(aux2) SHOW(aux3) SHOW(bat1) SHOW(bat2) SHOW(temp1) SHOW(temp2) static ssize_t ad7877_disable_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ad7877 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->disabled); } static ssize_t ad7877_disable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ad7877 *ts = dev_get_drvdata(dev); unsigned int val; int error; error = kstrtouint(buf, 10, &val); if (error) return error; if (val) ad7877_disable(ts); else ad7877_enable(ts); return count; } static DEVICE_ATTR(disable, 0664, ad7877_disable_show, ad7877_disable_store); static ssize_t ad7877_dac_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ad7877 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->dac); } static ssize_t ad7877_dac_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ad7877 *ts = dev_get_drvdata(dev); unsigned int val; int error; error = kstrtouint(buf, 10, &val); if (error) return error; mutex_lock(&ts->mutex); ts->dac = val & 0xFF; ad7877_write(ts->spi, AD7877_REG_DAC, (ts->dac << 4) | AD7877_DAC_CONF); mutex_unlock(&ts->mutex); return count; } static DEVICE_ATTR(dac, 0664, ad7877_dac_show, ad7877_dac_store); static ssize_t ad7877_gpio3_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ad7877 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->gpio3); } static ssize_t ad7877_gpio3_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ad7877 *ts = dev_get_drvdata(dev); unsigned int val; int error; error = kstrtouint(buf, 10, &val); if (error) return error; mutex_lock(&ts->mutex); ts->gpio3 = !!val; ad7877_write(ts->spi, AD7877_REG_EXTWRITE, AD7877_EXTW_GPIO_DATA | (ts->gpio4 << 4) | (ts->gpio3 << 5)); mutex_unlock(&ts->mutex); return count; } static DEVICE_ATTR(gpio3, 0664, ad7877_gpio3_show, ad7877_gpio3_store); static ssize_t ad7877_gpio4_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ad7877 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->gpio4); } static ssize_t ad7877_gpio4_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ad7877 *ts = dev_get_drvdata(dev); unsigned int val; int error; error = kstrtouint(buf, 10, &val); if (error) return error; mutex_lock(&ts->mutex); ts->gpio4 = !!val; ad7877_write(ts->spi, AD7877_REG_EXTWRITE, AD7877_EXTW_GPIO_DATA | (ts->gpio4 << 4) | (ts->gpio3 << 5)); mutex_unlock(&ts->mutex); return count; } static DEVICE_ATTR(gpio4, 0664, ad7877_gpio4_show, ad7877_gpio4_store); static struct attribute *ad7877_attributes[] = { &dev_attr_temp1.attr, &dev_attr_temp2.attr, &dev_attr_aux1.attr, &dev_attr_aux2.attr, &dev_attr_aux3.attr, &dev_attr_bat1.attr, &dev_attr_bat2.attr, &dev_attr_disable.attr, &dev_attr_dac.attr, &dev_attr_gpio3.attr, &dev_attr_gpio4.attr, NULL }; static umode_t ad7877_attr_is_visible(struct kobject *kobj, struct attribute *attr, int n) { umode_t mode = attr->mode; if (attr == &dev_attr_aux3.attr) { if (gpio3) mode = 0; } else if (attr == &dev_attr_gpio3.attr) { if (!gpio3) mode = 0; } return mode; } static const struct attribute_group ad7877_attr_group = { .is_visible = ad7877_attr_is_visible, .attrs = ad7877_attributes, }; static void ad7877_setup_ts_def_msg(struct spi_device *spi, struct ad7877 *ts) { struct spi_message *m; int i; ts->cmd_crtl2 = AD7877_WRITEADD(AD7877_REG_CTRL2) | AD7877_POL(ts->stopacq_polarity) | AD7877_AVG(ts->averaging) | AD7877_PM(1) | AD7877_TMR(ts->pen_down_acc_interval) | AD7877_ACQ(ts->acquisition_time) | AD7877_FCD(ts->first_conversion_delay); ad7877_write(spi, AD7877_REG_CTRL2, ts->cmd_crtl2); ts->cmd_crtl1 = AD7877_WRITEADD(AD7877_REG_CTRL1) | AD7877_READADD(AD7877_REG_XPLUS-1) | AD7877_MODE_SEQ1 | AD7877_DFR; ad7877_write(spi, AD7877_REG_CTRL1, ts->cmd_crtl1); ts->cmd_dummy = 0; m = &ts->msg; spi_message_init(m); m->context = ts; ts->xfer[0].tx_buf = &ts->cmd_crtl1; ts->xfer[0].len = 2; ts->xfer[0].cs_change = 1; spi_message_add_tail(&ts->xfer[0], m); ts->xfer[1].tx_buf = &ts->cmd_dummy; /* Send ZERO */ ts->xfer[1].len = 2; ts->xfer[1].cs_change = 1; spi_message_add_tail(&ts->xfer[1], m); for (i = 0; i < AD7877_NR_SENSE; i++) { ts->xfer[i + 2].rx_buf = &ts->conversion_data[AD7877_SEQ_YPOS + i]; ts->xfer[i + 2].len = 2; if (i < (AD7877_NR_SENSE - 1)) ts->xfer[i + 2].cs_change = 1; spi_message_add_tail(&ts->xfer[i + 2], m); } } static int ad7877_probe(struct spi_device *spi) { struct ad7877 *ts; struct input_dev *input_dev; struct ad7877_platform_data *pdata = dev_get_platdata(&spi->dev); int err; u16 verify; if (!spi->irq) { dev_dbg(&spi->dev, "no IRQ?\n"); return -ENODEV; } if (!pdata) { dev_dbg(&spi->dev, "no platform data?\n"); return -ENODEV; } /* don't exceed max specified SPI CLK frequency */ if (spi->max_speed_hz > MAX_SPI_FREQ_HZ) { dev_dbg(&spi->dev, "SPI CLK %d Hz?\n",spi->max_speed_hz); return -EINVAL; } spi->bits_per_word = 16; err = spi_setup(spi); if (err) { dev_dbg(&spi->dev, "spi master doesn't support 16 bits/word\n"); return err; } ts = devm_kzalloc(&spi->dev, sizeof(struct ad7877), GFP_KERNEL); if (!ts) return -ENOMEM; input_dev = devm_input_allocate_device(&spi->dev); if (!input_dev) return -ENOMEM; err = devm_add_action_or_reset(&spi->dev, ad7877_disable, ts); if (err) return err; spi_set_drvdata(spi, ts); ts->spi = spi; ts->input = input_dev; timer_setup(&ts->timer, ad7877_timer, 0); mutex_init(&ts->mutex); spin_lock_init(&ts->lock); ts->model = pdata->model ? : 7877; ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100; ts->x_plate_ohms = pdata->x_plate_ohms ? : 400; ts->pressure_max = pdata->pressure_max ? : ~0; ts->stopacq_polarity = pdata->stopacq_polarity; ts->first_conversion_delay = pdata->first_conversion_delay; ts->acquisition_time = pdata->acquisition_time; ts->averaging = pdata->averaging; ts->pen_down_acc_interval = pdata->pen_down_acc_interval; snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&spi->dev)); input_dev->name = "AD7877 Touchscreen"; input_dev->phys = ts->phys; input_dev->dev.parent = &spi->dev; __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); __set_bit(EV_ABS, input_dev->evbit); __set_bit(ABS_X, input_dev->absbit); __set_bit(ABS_Y, input_dev->absbit); __set_bit(ABS_PRESSURE, input_dev->absbit); input_set_abs_params(input_dev, ABS_X, pdata->x_min ? : 0, pdata->x_max ? : MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_Y, pdata->y_min ? : 0, pdata->y_max ? : MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, pdata->pressure_min, pdata->pressure_max, 0, 0); ad7877_write(spi, AD7877_REG_SEQ1, AD7877_MM_SEQUENCE); verify = ad7877_read(spi, AD7877_REG_SEQ1); if (verify != AD7877_MM_SEQUENCE) { dev_err(&spi->dev, "%s: Failed to probe %s\n", dev_name(&spi->dev), input_dev->name); return -ENODEV; } if (gpio3) ad7877_write(spi, AD7877_REG_EXTWRITE, AD7877_EXTW_GPIO_3_CONF); ad7877_setup_ts_def_msg(spi, ts); /* Request AD7877 /DAV GPIO interrupt */ err = devm_request_threaded_irq(&spi->dev, spi->irq, NULL, ad7877_irq, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, spi->dev.driver->name, ts); if (err) { dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq); return err; } err = devm_device_add_group(&spi->dev, &ad7877_attr_group); if (err) return err; err = input_register_device(input_dev); if (err) return err; return 0; } static int ad7877_suspend(struct device *dev) { struct ad7877 *ts = dev_get_drvdata(dev); ad7877_disable(ts); return 0; } static int ad7877_resume(struct device *dev) { struct ad7877 *ts = dev_get_drvdata(dev); ad7877_enable(ts); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(ad7877_pm, ad7877_suspend, ad7877_resume); static struct spi_driver ad7877_driver = { .driver = { .name = "ad7877", .pm = pm_sleep_ptr(&ad7877_pm), }, .probe = ad7877_probe, }; module_spi_driver(ad7877_driver); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("AD7877 touchscreen Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:ad7877");
linux-master
drivers/input/touchscreen/ad7877.c
// SPDX-License-Identifier: GPL-2.0-only /* * HTC Shift touchscreen driver * * Copyright (C) 2008 Pau Oliva Fora <[email protected]> */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/init.h> #include <linux/irq.h> #include <linux/isa.h> #include <linux/ioport.h> #include <linux/dmi.h> MODULE_AUTHOR("Pau Oliva Fora <[email protected]>"); MODULE_DESCRIPTION("HTC Shift touchscreen driver"); MODULE_LICENSE("GPL"); #define HTCPEN_PORT_IRQ_CLEAR 0x068 #define HTCPEN_PORT_INIT 0x06c #define HTCPEN_PORT_INDEX 0x0250 #define HTCPEN_PORT_DATA 0x0251 #define HTCPEN_IRQ 3 #define DEVICE_ENABLE 0xa2 #define DEVICE_DISABLE 0xa3 #define X_INDEX 3 #define Y_INDEX 5 #define TOUCH_INDEX 0xb #define LSB_XY_INDEX 0xc #define X_AXIS_MAX 2040 #define Y_AXIS_MAX 2040 static bool invert_x; module_param(invert_x, bool, 0644); MODULE_PARM_DESC(invert_x, "If set, X axis is inverted"); static bool invert_y; module_param(invert_y, bool, 0644); MODULE_PARM_DESC(invert_y, "If set, Y axis is inverted"); static irqreturn_t htcpen_interrupt(int irq, void *handle) { struct input_dev *htcpen_dev = handle; unsigned short x, y, xy; /* 0 = press; 1 = release */ outb_p(TOUCH_INDEX, HTCPEN_PORT_INDEX); if (inb_p(HTCPEN_PORT_DATA)) { input_report_key(htcpen_dev, BTN_TOUCH, 0); } else { outb_p(X_INDEX, HTCPEN_PORT_INDEX); x = inb_p(HTCPEN_PORT_DATA); outb_p(Y_INDEX, HTCPEN_PORT_INDEX); y = inb_p(HTCPEN_PORT_DATA); outb_p(LSB_XY_INDEX, HTCPEN_PORT_INDEX); xy = inb_p(HTCPEN_PORT_DATA); /* get high resolution value of X and Y using LSB */ x = X_AXIS_MAX - ((x * 8) + ((xy >> 4) & 0xf)); y = (y * 8) + (xy & 0xf); if (invert_x) x = X_AXIS_MAX - x; if (invert_y) y = Y_AXIS_MAX - y; if (x != X_AXIS_MAX && x != 0) { input_report_key(htcpen_dev, BTN_TOUCH, 1); input_report_abs(htcpen_dev, ABS_X, x); input_report_abs(htcpen_dev, ABS_Y, y); } } input_sync(htcpen_dev); inb_p(HTCPEN_PORT_IRQ_CLEAR); return IRQ_HANDLED; } static int htcpen_open(struct input_dev *dev) { outb_p(DEVICE_ENABLE, HTCPEN_PORT_INIT); return 0; } static void htcpen_close(struct input_dev *dev) { outb_p(DEVICE_DISABLE, HTCPEN_PORT_INIT); synchronize_irq(HTCPEN_IRQ); } static int htcpen_isa_probe(struct device *dev, unsigned int id) { struct input_dev *htcpen_dev; int err = -EBUSY; if (!request_region(HTCPEN_PORT_IRQ_CLEAR, 1, "htcpen")) { printk(KERN_ERR "htcpen: unable to get IO region 0x%x\n", HTCPEN_PORT_IRQ_CLEAR); goto request_region1_failed; } if (!request_region(HTCPEN_PORT_INIT, 1, "htcpen")) { printk(KERN_ERR "htcpen: unable to get IO region 0x%x\n", HTCPEN_PORT_INIT); goto request_region2_failed; } if (!request_region(HTCPEN_PORT_INDEX, 2, "htcpen")) { printk(KERN_ERR "htcpen: unable to get IO region 0x%x\n", HTCPEN_PORT_INDEX); goto request_region3_failed; } htcpen_dev = input_allocate_device(); if (!htcpen_dev) { printk(KERN_ERR "htcpen: can't allocate device\n"); err = -ENOMEM; goto input_alloc_failed; } htcpen_dev->name = "HTC Shift EC TouchScreen"; htcpen_dev->id.bustype = BUS_ISA; htcpen_dev->evbit[0] = BIT_MASK(EV_ABS) | BIT_MASK(EV_KEY); htcpen_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(htcpen_dev, ABS_X, 0, X_AXIS_MAX, 0, 0); input_set_abs_params(htcpen_dev, ABS_Y, 0, Y_AXIS_MAX, 0, 0); htcpen_dev->open = htcpen_open; htcpen_dev->close = htcpen_close; err = request_irq(HTCPEN_IRQ, htcpen_interrupt, 0, "htcpen", htcpen_dev); if (err) { printk(KERN_ERR "htcpen: irq busy\n"); goto request_irq_failed; } inb_p(HTCPEN_PORT_IRQ_CLEAR); err = input_register_device(htcpen_dev); if (err) goto input_register_failed; dev_set_drvdata(dev, htcpen_dev); return 0; input_register_failed: free_irq(HTCPEN_IRQ, htcpen_dev); request_irq_failed: input_free_device(htcpen_dev); input_alloc_failed: release_region(HTCPEN_PORT_INDEX, 2); request_region3_failed: release_region(HTCPEN_PORT_INIT, 1); request_region2_failed: release_region(HTCPEN_PORT_IRQ_CLEAR, 1); request_region1_failed: return err; } static void htcpen_isa_remove(struct device *dev, unsigned int id) { struct input_dev *htcpen_dev = dev_get_drvdata(dev); input_unregister_device(htcpen_dev); free_irq(HTCPEN_IRQ, htcpen_dev); release_region(HTCPEN_PORT_INDEX, 2); release_region(HTCPEN_PORT_INIT, 1); release_region(HTCPEN_PORT_IRQ_CLEAR, 1); } #ifdef CONFIG_PM static int htcpen_isa_suspend(struct device *dev, unsigned int n, pm_message_t state) { outb_p(DEVICE_DISABLE, HTCPEN_PORT_INIT); return 0; } static int htcpen_isa_resume(struct device *dev, unsigned int n) { outb_p(DEVICE_ENABLE, HTCPEN_PORT_INIT); return 0; } #endif static struct isa_driver htcpen_isa_driver = { .probe = htcpen_isa_probe, .remove = htcpen_isa_remove, #ifdef CONFIG_PM .suspend = htcpen_isa_suspend, .resume = htcpen_isa_resume, #endif .driver = { .owner = THIS_MODULE, .name = "htcpen", } }; static const struct dmi_system_id htcshift_dmi_table[] __initconst = { { .ident = "Shift", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "High Tech Computer Corp"), DMI_MATCH(DMI_PRODUCT_NAME, "Shift"), }, }, { } }; MODULE_DEVICE_TABLE(dmi, htcshift_dmi_table); static int __init htcpen_isa_init(void) { if (!dmi_check_system(htcshift_dmi_table)) return -ENODEV; return isa_register_driver(&htcpen_isa_driver, 1); } static void __exit htcpen_isa_exit(void) { isa_unregister_driver(&htcpen_isa_driver); } module_init(htcpen_isa_init); module_exit(htcpen_isa_exit);
linux-master
drivers/input/touchscreen/htcpen.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2012 Simon Budig, <[email protected]> * Daniel Wagener <[email protected]> (M09 firmware support) * Lothar Waßmann <[email protected]> (DT support) * Dario Binacchi <[email protected]> (regmap support) */ /* * This is a driver for the EDT "Polytouch" family of touch controllers * based on the FocalTech FT5x06 line of chips. * * Development of this driver has been sponsored by Glyn: * http://www.glyn.com/Products/Displays */ #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/property.h> #include <linux/ratelimit.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #define WORK_REGISTER_THRESHOLD 0x00 #define WORK_REGISTER_REPORT_RATE 0x08 #define WORK_REGISTER_GAIN 0x30 #define WORK_REGISTER_OFFSET 0x31 #define WORK_REGISTER_NUM_X 0x33 #define WORK_REGISTER_NUM_Y 0x34 #define PMOD_REGISTER_ACTIVE 0x00 #define PMOD_REGISTER_HIBERNATE 0x03 #define M09_REGISTER_THRESHOLD 0x80 #define M09_REGISTER_GAIN 0x92 #define M09_REGISTER_OFFSET 0x93 #define M09_REGISTER_NUM_X 0x94 #define M09_REGISTER_NUM_Y 0x95 #define M12_REGISTER_REPORT_RATE 0x88 #define EV_REGISTER_THRESHOLD 0x40 #define EV_REGISTER_GAIN 0x41 #define EV_REGISTER_OFFSET_Y 0x45 #define EV_REGISTER_OFFSET_X 0x46 #define NO_REGISTER 0xff #define WORK_REGISTER_OPMODE 0x3c #define FACTORY_REGISTER_OPMODE 0x01 #define PMOD_REGISTER_OPMODE 0xa5 #define TOUCH_EVENT_DOWN 0x00 #define TOUCH_EVENT_UP 0x01 #define TOUCH_EVENT_ON 0x02 #define TOUCH_EVENT_RESERVED 0x03 #define EDT_NAME_LEN 23 #define EDT_SWITCH_MODE_RETRIES 10 #define EDT_SWITCH_MODE_DELAY 5 /* msec */ #define EDT_RAW_DATA_RETRIES 100 #define EDT_RAW_DATA_DELAY 1000 /* usec */ #define EDT_DEFAULT_NUM_X 1024 #define EDT_DEFAULT_NUM_Y 1024 #define M06_REG_CMD(factory) ((factory) ? 0xf3 : 0xfc) #define M06_REG_ADDR(factory, addr) ((factory) ? (addr) & 0x7f : (addr) & 0x3f) enum edt_pmode { EDT_PMODE_NOT_SUPPORTED, EDT_PMODE_HIBERNATE, EDT_PMODE_POWEROFF, }; enum edt_ver { EDT_M06, EDT_M09, EDT_M12, EV_FT, GENERIC_FT, }; struct edt_reg_addr { int reg_threshold; int reg_report_rate; int reg_gain; int reg_offset; int reg_offset_x; int reg_offset_y; int reg_num_x; int reg_num_y; }; struct edt_ft5x06_ts_data { struct i2c_client *client; struct input_dev *input; struct touchscreen_properties prop; u16 num_x; u16 num_y; struct regulator *vcc; struct regulator *iovcc; struct gpio_desc *reset_gpio; struct gpio_desc *wake_gpio; struct regmap *regmap; #if defined(CONFIG_DEBUG_FS) struct dentry *debug_dir; u8 *raw_buffer; size_t raw_bufsize; #endif struct mutex mutex; bool factory_mode; enum edt_pmode suspend_mode; int threshold; int gain; int offset; int offset_x; int offset_y; int report_rate; int max_support_points; int point_len; u8 tdata_cmd; int tdata_len; int tdata_offset; char name[EDT_NAME_LEN]; char fw_version[EDT_NAME_LEN]; struct edt_reg_addr reg_addr; enum edt_ver version; unsigned int crc_errors; unsigned int header_errors; }; struct edt_i2c_chip_data { int max_support_points; }; static const struct regmap_config edt_ft5x06_i2c_regmap_config = { .reg_bits = 8, .val_bits = 8, }; static bool edt_ft5x06_ts_check_crc(struct edt_ft5x06_ts_data *tsdata, u8 *buf, int buflen) { int i; u8 crc = 0; for (i = 0; i < buflen - 1; i++) crc ^= buf[i]; if (crc != buf[buflen - 1]) { tsdata->crc_errors++; dev_err_ratelimited(&tsdata->client->dev, "crc error: 0x%02x expected, got 0x%02x\n", crc, buf[buflen - 1]); return false; } return true; } static int edt_M06_i2c_read(void *context, const void *reg_buf, size_t reg_size, void *val_buf, size_t val_size) { struct device *dev = context; struct i2c_client *i2c = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(i2c); struct i2c_msg xfer[2]; bool reg_read = false; u8 addr; u8 wlen; u8 wbuf[4], rbuf[3]; int ret; addr = *((u8 *)reg_buf); wbuf[0] = addr; switch (addr) { case 0xf5: wlen = 3; wbuf[0] = 0xf5; wbuf[1] = 0xe; wbuf[2] = *((u8 *)val_buf); break; case 0xf9: wlen = 1; break; default: wlen = 2; reg_read = true; wbuf[0] = M06_REG_CMD(tsdata->factory_mode); wbuf[1] = M06_REG_ADDR(tsdata->factory_mode, addr); wbuf[1] |= tsdata->factory_mode ? 0x80 : 0x40; } xfer[0].addr = i2c->addr; xfer[0].flags = 0; xfer[0].len = wlen; xfer[0].buf = wbuf; xfer[1].addr = i2c->addr; xfer[1].flags = I2C_M_RD; xfer[1].len = reg_read ? 2 : val_size; xfer[1].buf = reg_read ? rbuf : val_buf; ret = i2c_transfer(i2c->adapter, xfer, 2); if (ret != 2) { if (ret < 0) return ret; return -EIO; } if (addr == 0xf9) { u8 *buf = (u8 *)val_buf; if (buf[0] != 0xaa || buf[1] != 0xaa || buf[2] != val_size) { tsdata->header_errors++; dev_err_ratelimited(dev, "Unexpected header: %02x%02x%02x\n", buf[0], buf[1], buf[2]); return -EIO; } if (!edt_ft5x06_ts_check_crc(tsdata, val_buf, val_size)) return -EIO; } else if (reg_read) { wbuf[2] = rbuf[0]; wbuf[3] = rbuf[1]; if (!edt_ft5x06_ts_check_crc(tsdata, wbuf, 4)) return -EIO; *((u8 *)val_buf) = rbuf[0]; } return 0; } static int edt_M06_i2c_write(void *context, const void *data, size_t count) { struct device *dev = context; struct i2c_client *i2c = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(i2c); u8 addr, val; u8 wbuf[4]; struct i2c_msg xfer; int ret; addr = *((u8 *)data); val = *((u8 *)data + 1); wbuf[0] = M06_REG_CMD(tsdata->factory_mode); wbuf[1] = M06_REG_ADDR(tsdata->factory_mode, addr); wbuf[2] = val; wbuf[3] = wbuf[0] ^ wbuf[1] ^ wbuf[2]; xfer.addr = i2c->addr; xfer.flags = 0; xfer.len = 4; xfer.buf = wbuf; ret = i2c_transfer(i2c->adapter, &xfer, 1); if (ret != 1) { if (ret < 0) return ret; return -EIO; } return 0; } static const struct regmap_config edt_M06_i2c_regmap_config = { .reg_bits = 8, .val_bits = 8, .read = edt_M06_i2c_read, .write = edt_M06_i2c_write, }; static irqreturn_t edt_ft5x06_ts_isr(int irq, void *dev_id) { struct edt_ft5x06_ts_data *tsdata = dev_id; struct device *dev = &tsdata->client->dev; u8 rdbuf[63]; int i, type, x, y, id; int error; memset(rdbuf, 0, sizeof(rdbuf)); error = regmap_bulk_read(tsdata->regmap, tsdata->tdata_cmd, rdbuf, tsdata->tdata_len); if (error) { dev_err_ratelimited(dev, "Unable to fetch data, error: %d\n", error); goto out; } for (i = 0; i < tsdata->max_support_points; i++) { u8 *buf = &rdbuf[i * tsdata->point_len + tsdata->tdata_offset]; type = buf[0] >> 6; /* ignore Reserved events */ if (type == TOUCH_EVENT_RESERVED) continue; /* M06 sometimes sends bogus coordinates in TOUCH_DOWN */ if (tsdata->version == EDT_M06 && type == TOUCH_EVENT_DOWN) continue; x = get_unaligned_be16(buf) & 0x0fff; y = get_unaligned_be16(buf + 2) & 0x0fff; /* The FT5x26 send the y coordinate first */ if (tsdata->version == EV_FT) swap(x, y); id = (buf[2] >> 4) & 0x0f; input_mt_slot(tsdata->input, id); if (input_mt_report_slot_state(tsdata->input, MT_TOOL_FINGER, type != TOUCH_EVENT_UP)) touchscreen_report_pos(tsdata->input, &tsdata->prop, x, y, true); } input_mt_report_pointer_emulation(tsdata->input, true); input_sync(tsdata->input); out: return IRQ_HANDLED; } struct edt_ft5x06_attribute { struct device_attribute dattr; size_t field_offset; u8 limit_low; u8 limit_high; u8 addr_m06; u8 addr_m09; u8 addr_ev; }; #define EDT_ATTR(_field, _mode, _addr_m06, _addr_m09, _addr_ev, \ _limit_low, _limit_high) \ struct edt_ft5x06_attribute edt_ft5x06_attr_##_field = { \ .dattr = __ATTR(_field, _mode, \ edt_ft5x06_setting_show, \ edt_ft5x06_setting_store), \ .field_offset = offsetof(struct edt_ft5x06_ts_data, _field), \ .addr_m06 = _addr_m06, \ .addr_m09 = _addr_m09, \ .addr_ev = _addr_ev, \ .limit_low = _limit_low, \ .limit_high = _limit_high, \ } static ssize_t edt_ft5x06_setting_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); struct edt_ft5x06_attribute *attr = container_of(dattr, struct edt_ft5x06_attribute, dattr); u8 *field = (u8 *)tsdata + attr->field_offset; unsigned int val; size_t count = 0; int error = 0; u8 addr; mutex_lock(&tsdata->mutex); if (tsdata->factory_mode) { error = -EIO; goto out; } switch (tsdata->version) { case EDT_M06: addr = attr->addr_m06; break; case EDT_M09: case EDT_M12: case GENERIC_FT: addr = attr->addr_m09; break; case EV_FT: addr = attr->addr_ev; break; default: error = -ENODEV; goto out; } if (addr != NO_REGISTER) { error = regmap_read(tsdata->regmap, addr, &val); if (error) { dev_err(&tsdata->client->dev, "Failed to fetch attribute %s, error %d\n", dattr->attr.name, error); goto out; } } else { val = *field; } if (val != *field) { dev_warn(&tsdata->client->dev, "%s: read (%d) and stored value (%d) differ\n", dattr->attr.name, val, *field); *field = val; } count = scnprintf(buf, PAGE_SIZE, "%d\n", val); out: mutex_unlock(&tsdata->mutex); return error ?: count; } static ssize_t edt_ft5x06_setting_store(struct device *dev, struct device_attribute *dattr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); struct edt_ft5x06_attribute *attr = container_of(dattr, struct edt_ft5x06_attribute, dattr); u8 *field = (u8 *)tsdata + attr->field_offset; unsigned int val; int error; u8 addr; mutex_lock(&tsdata->mutex); if (tsdata->factory_mode) { error = -EIO; goto out; } error = kstrtouint(buf, 0, &val); if (error) goto out; if (val < attr->limit_low || val > attr->limit_high) { error = -ERANGE; goto out; } switch (tsdata->version) { case EDT_M06: addr = attr->addr_m06; break; case EDT_M09: case EDT_M12: case GENERIC_FT: addr = attr->addr_m09; break; case EV_FT: addr = attr->addr_ev; break; default: error = -ENODEV; goto out; } if (addr != NO_REGISTER) { error = regmap_write(tsdata->regmap, addr, val); if (error) { dev_err(&tsdata->client->dev, "Failed to update attribute %s, error: %d\n", dattr->attr.name, error); goto out; } } *field = val; out: mutex_unlock(&tsdata->mutex); return error ?: count; } /* m06, m09: range 0-31, m12: range 0-5 */ static EDT_ATTR(gain, S_IWUSR | S_IRUGO, WORK_REGISTER_GAIN, M09_REGISTER_GAIN, EV_REGISTER_GAIN, 0, 31); /* m06, m09: range 0-31, m12: range 0-16 */ static EDT_ATTR(offset, S_IWUSR | S_IRUGO, WORK_REGISTER_OFFSET, M09_REGISTER_OFFSET, NO_REGISTER, 0, 31); /* m06, m09, m12: no supported, ev_ft: range 0-80 */ static EDT_ATTR(offset_x, S_IWUSR | S_IRUGO, NO_REGISTER, NO_REGISTER, EV_REGISTER_OFFSET_X, 0, 80); /* m06, m09, m12: no supported, ev_ft: range 0-80 */ static EDT_ATTR(offset_y, S_IWUSR | S_IRUGO, NO_REGISTER, NO_REGISTER, EV_REGISTER_OFFSET_Y, 0, 80); /* m06: range 20 to 80, m09: range 0 to 30, m12: range 1 to 255... */ static EDT_ATTR(threshold, S_IWUSR | S_IRUGO, WORK_REGISTER_THRESHOLD, M09_REGISTER_THRESHOLD, EV_REGISTER_THRESHOLD, 0, 255); /* m06: range 3 to 14, m12: range 1 to 255 */ static EDT_ATTR(report_rate, S_IWUSR | S_IRUGO, WORK_REGISTER_REPORT_RATE, M12_REGISTER_REPORT_RATE, NO_REGISTER, 0, 255); static ssize_t model_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); return sysfs_emit(buf, "%s\n", tsdata->name); } static DEVICE_ATTR_RO(model); static ssize_t fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); return sysfs_emit(buf, "%s\n", tsdata->fw_version); } static DEVICE_ATTR_RO(fw_version); /* m06 only */ static ssize_t header_errors_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); return sysfs_emit(buf, "%d\n", tsdata->header_errors); } static DEVICE_ATTR_RO(header_errors); /* m06 only */ static ssize_t crc_errors_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); return sysfs_emit(buf, "%d\n", tsdata->crc_errors); } static DEVICE_ATTR_RO(crc_errors); static struct attribute *edt_ft5x06_attrs[] = { &edt_ft5x06_attr_gain.dattr.attr, &edt_ft5x06_attr_offset.dattr.attr, &edt_ft5x06_attr_offset_x.dattr.attr, &edt_ft5x06_attr_offset_y.dattr.attr, &edt_ft5x06_attr_threshold.dattr.attr, &edt_ft5x06_attr_report_rate.dattr.attr, &dev_attr_model.attr, &dev_attr_fw_version.attr, &dev_attr_header_errors.attr, &dev_attr_crc_errors.attr, NULL }; static const struct attribute_group edt_ft5x06_attr_group = { .attrs = edt_ft5x06_attrs, }; static void edt_ft5x06_restore_reg_parameters(struct edt_ft5x06_ts_data *tsdata) { struct edt_reg_addr *reg_addr = &tsdata->reg_addr; struct regmap *regmap = tsdata->regmap; regmap_write(regmap, reg_addr->reg_threshold, tsdata->threshold); regmap_write(regmap, reg_addr->reg_gain, tsdata->gain); if (reg_addr->reg_offset != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset, tsdata->offset); if (reg_addr->reg_offset_x != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset_x, tsdata->offset_x); if (reg_addr->reg_offset_y != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset_y, tsdata->offset_y); if (reg_addr->reg_report_rate != NO_REGISTER) regmap_write(regmap, reg_addr->reg_report_rate, tsdata->report_rate); } #ifdef CONFIG_DEBUG_FS static int edt_ft5x06_factory_mode(struct edt_ft5x06_ts_data *tsdata) { struct i2c_client *client = tsdata->client; int retries = EDT_SWITCH_MODE_RETRIES; unsigned int val; int error; if (tsdata->version != EDT_M06) { dev_err(&client->dev, "No factory mode support for non-M06 devices\n"); return -EINVAL; } disable_irq(client->irq); if (!tsdata->raw_buffer) { tsdata->raw_bufsize = tsdata->num_x * tsdata->num_y * sizeof(u16); tsdata->raw_buffer = kzalloc(tsdata->raw_bufsize, GFP_KERNEL); if (!tsdata->raw_buffer) { error = -ENOMEM; goto err_out; } } /* mode register is 0x3c when in the work mode */ error = regmap_write(tsdata->regmap, WORK_REGISTER_OPMODE, 0x03); if (error) { dev_err(&client->dev, "failed to switch to factory mode, error %d\n", error); goto err_out; } tsdata->factory_mode = true; do { mdelay(EDT_SWITCH_MODE_DELAY); /* mode register is 0x01 when in factory mode */ error = regmap_read(tsdata->regmap, FACTORY_REGISTER_OPMODE, &val); if (!error && val == 0x03) break; } while (--retries > 0); if (retries == 0) { dev_err(&client->dev, "not in factory mode after %dms.\n", EDT_SWITCH_MODE_RETRIES * EDT_SWITCH_MODE_DELAY); error = -EIO; goto err_out; } return 0; err_out: kfree(tsdata->raw_buffer); tsdata->raw_buffer = NULL; tsdata->factory_mode = false; enable_irq(client->irq); return error; } static int edt_ft5x06_work_mode(struct edt_ft5x06_ts_data *tsdata) { struct i2c_client *client = tsdata->client; int retries = EDT_SWITCH_MODE_RETRIES; unsigned int val; int error; /* mode register is 0x01 when in the factory mode */ error = regmap_write(tsdata->regmap, FACTORY_REGISTER_OPMODE, 0x1); if (error) { dev_err(&client->dev, "failed to switch to work mode, error: %d\n", error); return error; } tsdata->factory_mode = false; do { mdelay(EDT_SWITCH_MODE_DELAY); /* mode register is 0x01 when in factory mode */ error = regmap_read(tsdata->regmap, WORK_REGISTER_OPMODE, &val); if (!error && val == 0x01) break; } while (--retries > 0); if (retries == 0) { dev_err(&client->dev, "not in work mode after %dms.\n", EDT_SWITCH_MODE_RETRIES * EDT_SWITCH_MODE_DELAY); tsdata->factory_mode = true; return -EIO; } kfree(tsdata->raw_buffer); tsdata->raw_buffer = NULL; edt_ft5x06_restore_reg_parameters(tsdata); enable_irq(client->irq); return 0; } static int edt_ft5x06_debugfs_mode_get(void *data, u64 *mode) { struct edt_ft5x06_ts_data *tsdata = data; *mode = tsdata->factory_mode; return 0; }; static int edt_ft5x06_debugfs_mode_set(void *data, u64 mode) { struct edt_ft5x06_ts_data *tsdata = data; int retval = 0; if (mode > 1) return -ERANGE; mutex_lock(&tsdata->mutex); if (mode != tsdata->factory_mode) { retval = mode ? edt_ft5x06_factory_mode(tsdata) : edt_ft5x06_work_mode(tsdata); } mutex_unlock(&tsdata->mutex); return retval; }; DEFINE_SIMPLE_ATTRIBUTE(debugfs_mode_fops, edt_ft5x06_debugfs_mode_get, edt_ft5x06_debugfs_mode_set, "%llu\n"); static ssize_t edt_ft5x06_debugfs_raw_data_read(struct file *file, char __user *buf, size_t count, loff_t *off) { struct edt_ft5x06_ts_data *tsdata = file->private_data; struct i2c_client *client = tsdata->client; int retries = EDT_RAW_DATA_RETRIES; unsigned int val; int i, error; size_t read = 0; int colbytes; u8 *rdbuf; if (*off < 0 || *off >= tsdata->raw_bufsize) return 0; mutex_lock(&tsdata->mutex); if (!tsdata->factory_mode || !tsdata->raw_buffer) { error = -EIO; goto out; } error = regmap_write(tsdata->regmap, 0x08, 0x01); if (error) { dev_err(&client->dev, "failed to write 0x08 register, error %d\n", error); goto out; } do { usleep_range(EDT_RAW_DATA_DELAY, EDT_RAW_DATA_DELAY + 100); error = regmap_read(tsdata->regmap, 0x08, &val); if (error) { dev_err(&client->dev, "failed to read 0x08 register, error %d\n", error); goto out; } if (val == 1) break; } while (--retries > 0); if (retries == 0) { dev_err(&client->dev, "timed out waiting for register to settle\n"); error = -ETIMEDOUT; goto out; } rdbuf = tsdata->raw_buffer; colbytes = tsdata->num_y * sizeof(u16); for (i = 0; i < tsdata->num_x; i++) { rdbuf[0] = i; /* column index */ error = regmap_bulk_read(tsdata->regmap, 0xf5, rdbuf, colbytes); if (error) goto out; rdbuf += colbytes; } read = min_t(size_t, count, tsdata->raw_bufsize - *off); if (copy_to_user(buf, tsdata->raw_buffer + *off, read)) { error = -EFAULT; goto out; } *off += read; out: mutex_unlock(&tsdata->mutex); return error ?: read; }; static const struct file_operations debugfs_raw_data_fops = { .open = simple_open, .read = edt_ft5x06_debugfs_raw_data_read, }; static void edt_ft5x06_ts_prepare_debugfs(struct edt_ft5x06_ts_data *tsdata, const char *debugfs_name) { tsdata->debug_dir = debugfs_create_dir(debugfs_name, NULL); debugfs_create_u16("num_x", S_IRUSR, tsdata->debug_dir, &tsdata->num_x); debugfs_create_u16("num_y", S_IRUSR, tsdata->debug_dir, &tsdata->num_y); debugfs_create_file("mode", S_IRUSR | S_IWUSR, tsdata->debug_dir, tsdata, &debugfs_mode_fops); debugfs_create_file("raw_data", S_IRUSR, tsdata->debug_dir, tsdata, &debugfs_raw_data_fops); } static void edt_ft5x06_ts_teardown_debugfs(struct edt_ft5x06_ts_data *tsdata) { debugfs_remove_recursive(tsdata->debug_dir); kfree(tsdata->raw_buffer); } #else static int edt_ft5x06_factory_mode(struct edt_ft5x06_ts_data *tsdata) { return -ENOSYS; } static void edt_ft5x06_ts_prepare_debugfs(struct edt_ft5x06_ts_data *tsdata, const char *debugfs_name) { } static void edt_ft5x06_ts_teardown_debugfs(struct edt_ft5x06_ts_data *tsdata) { } #endif /* CONFIG_DEBUGFS */ static int edt_ft5x06_ts_identify(struct i2c_client *client, struct edt_ft5x06_ts_data *tsdata) { u8 rdbuf[EDT_NAME_LEN]; char *p; int error; char *model_name = tsdata->name; char *fw_version = tsdata->fw_version; /* see what we find if we assume it is a M06 * * if we get less than EDT_NAME_LEN, we don't want * to have garbage in there */ memset(rdbuf, 0, sizeof(rdbuf)); error = regmap_bulk_read(tsdata->regmap, 0xBB, rdbuf, EDT_NAME_LEN - 1); if (error) return error; /* Probe content for something consistent. * M06 starts with a response byte, M12 gives the data directly. * M09/Generic does not provide model number information. */ if (!strncasecmp(rdbuf + 1, "EP0", 3)) { tsdata->version = EDT_M06; /* remove last '$' end marker */ rdbuf[EDT_NAME_LEN - 1] = '\0'; if (rdbuf[EDT_NAME_LEN - 2] == '$') rdbuf[EDT_NAME_LEN - 2] = '\0'; /* look for Model/Version separator */ p = strchr(rdbuf, '*'); if (p) *p++ = '\0'; strscpy(model_name, rdbuf + 1, EDT_NAME_LEN); strscpy(fw_version, p ? p : "", EDT_NAME_LEN); regmap_exit(tsdata->regmap); tsdata->regmap = regmap_init_i2c(client, &edt_M06_i2c_regmap_config); if (IS_ERR(tsdata->regmap)) { dev_err(&client->dev, "regmap allocation failed\n"); return PTR_ERR(tsdata->regmap); } } else if (!strncasecmp(rdbuf, "EP0", 3)) { tsdata->version = EDT_M12; /* remove last '$' end marker */ rdbuf[EDT_NAME_LEN - 2] = '\0'; if (rdbuf[EDT_NAME_LEN - 3] == '$') rdbuf[EDT_NAME_LEN - 3] = '\0'; /* look for Model/Version separator */ p = strchr(rdbuf, '*'); if (p) *p++ = '\0'; strscpy(model_name, rdbuf, EDT_NAME_LEN); strscpy(fw_version, p ? p : "", EDT_NAME_LEN); } else { /* If it is not an EDT M06/M12 touchscreen, then the model * detection is a bit hairy. The different ft5x06 * firmwares around don't reliably implement the * identification registers. Well, we'll take a shot. * * The main difference between generic focaltec based * touches and EDT M09 is that we know how to retrieve * the max coordinates for the latter. */ tsdata->version = GENERIC_FT; error = regmap_bulk_read(tsdata->regmap, 0xA6, rdbuf, 2); if (error) return error; strscpy(fw_version, rdbuf, 2); error = regmap_bulk_read(tsdata->regmap, 0xA8, rdbuf, 1); if (error) return error; /* This "model identification" is not exact. Unfortunately * not all firmwares for the ft5x06 put useful values in * the identification registers. */ switch (rdbuf[0]) { case 0x11: /* EDT EP0110M09 */ case 0x35: /* EDT EP0350M09 */ case 0x43: /* EDT EP0430M09 */ case 0x50: /* EDT EP0500M09 */ case 0x57: /* EDT EP0570M09 */ case 0x70: /* EDT EP0700M09 */ tsdata->version = EDT_M09; snprintf(model_name, EDT_NAME_LEN, "EP0%i%i0M09", rdbuf[0] >> 4, rdbuf[0] & 0x0F); break; case 0xa1: /* EDT EP1010ML00 */ tsdata->version = EDT_M09; snprintf(model_name, EDT_NAME_LEN, "EP%i%i0ML00", rdbuf[0] >> 4, rdbuf[0] & 0x0F); break; case 0x5a: /* Solomon Goldentek Display */ snprintf(model_name, EDT_NAME_LEN, "GKTW50SCED1R0"); break; case 0x59: /* Evervision Display with FT5xx6 TS */ tsdata->version = EV_FT; error = regmap_bulk_read(tsdata->regmap, 0x53, rdbuf, 1); if (error) return error; strscpy(fw_version, rdbuf, 1); snprintf(model_name, EDT_NAME_LEN, "EVERVISION-FT5726NEi"); break; default: snprintf(model_name, EDT_NAME_LEN, "generic ft5x06 (%02x)", rdbuf[0]); break; } } return 0; } static void edt_ft5x06_ts_get_defaults(struct device *dev, struct edt_ft5x06_ts_data *tsdata) { struct edt_reg_addr *reg_addr = &tsdata->reg_addr; struct regmap *regmap = tsdata->regmap; u32 val; int error; error = device_property_read_u32(dev, "threshold", &val); if (!error) { regmap_write(regmap, reg_addr->reg_threshold, val); tsdata->threshold = val; } error = device_property_read_u32(dev, "gain", &val); if (!error) { regmap_write(regmap, reg_addr->reg_gain, val); tsdata->gain = val; } error = device_property_read_u32(dev, "offset", &val); if (!error) { if (reg_addr->reg_offset != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset, val); tsdata->offset = val; } error = device_property_read_u32(dev, "offset-x", &val); if (!error) { if (reg_addr->reg_offset_x != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset_x, val); tsdata->offset_x = val; } error = device_property_read_u32(dev, "offset-y", &val); if (!error) { if (reg_addr->reg_offset_y != NO_REGISTER) regmap_write(regmap, reg_addr->reg_offset_y, val); tsdata->offset_y = val; } } static void edt_ft5x06_ts_get_parameters(struct edt_ft5x06_ts_data *tsdata) { struct edt_reg_addr *reg_addr = &tsdata->reg_addr; struct regmap *regmap = tsdata->regmap; unsigned int val; regmap_read(regmap, reg_addr->reg_threshold, &tsdata->threshold); regmap_read(regmap, reg_addr->reg_gain, &tsdata->gain); if (reg_addr->reg_offset != NO_REGISTER) regmap_read(regmap, reg_addr->reg_offset, &tsdata->offset); if (reg_addr->reg_offset_x != NO_REGISTER) regmap_read(regmap, reg_addr->reg_offset_x, &tsdata->offset_x); if (reg_addr->reg_offset_y != NO_REGISTER) regmap_read(regmap, reg_addr->reg_offset_y, &tsdata->offset_y); if (reg_addr->reg_report_rate != NO_REGISTER) regmap_read(regmap, reg_addr->reg_report_rate, &tsdata->report_rate); tsdata->num_x = EDT_DEFAULT_NUM_X; if (reg_addr->reg_num_x != NO_REGISTER) { if (!regmap_read(regmap, reg_addr->reg_num_x, &val)) tsdata->num_x = val; } tsdata->num_y = EDT_DEFAULT_NUM_Y; if (reg_addr->reg_num_y != NO_REGISTER) { if (!regmap_read(regmap, reg_addr->reg_num_y, &val)) tsdata->num_y = val; } } static void edt_ft5x06_ts_set_tdata_parameters(struct edt_ft5x06_ts_data *tsdata) { int crclen; if (tsdata->version == EDT_M06) { tsdata->tdata_cmd = 0xf9; tsdata->tdata_offset = 5; tsdata->point_len = 4; crclen = 1; } else { tsdata->tdata_cmd = 0x0; tsdata->tdata_offset = 3; tsdata->point_len = 6; crclen = 0; } tsdata->tdata_len = tsdata->point_len * tsdata->max_support_points + tsdata->tdata_offset + crclen; } static void edt_ft5x06_ts_set_regs(struct edt_ft5x06_ts_data *tsdata) { struct edt_reg_addr *reg_addr = &tsdata->reg_addr; switch (tsdata->version) { case EDT_M06: reg_addr->reg_threshold = WORK_REGISTER_THRESHOLD; reg_addr->reg_report_rate = WORK_REGISTER_REPORT_RATE; reg_addr->reg_gain = WORK_REGISTER_GAIN; reg_addr->reg_offset = WORK_REGISTER_OFFSET; reg_addr->reg_offset_x = NO_REGISTER; reg_addr->reg_offset_y = NO_REGISTER; reg_addr->reg_num_x = WORK_REGISTER_NUM_X; reg_addr->reg_num_y = WORK_REGISTER_NUM_Y; break; case EDT_M09: case EDT_M12: reg_addr->reg_threshold = M09_REGISTER_THRESHOLD; reg_addr->reg_report_rate = tsdata->version == EDT_M12 ? M12_REGISTER_REPORT_RATE : NO_REGISTER; reg_addr->reg_gain = M09_REGISTER_GAIN; reg_addr->reg_offset = M09_REGISTER_OFFSET; reg_addr->reg_offset_x = NO_REGISTER; reg_addr->reg_offset_y = NO_REGISTER; reg_addr->reg_num_x = M09_REGISTER_NUM_X; reg_addr->reg_num_y = M09_REGISTER_NUM_Y; break; case EV_FT: reg_addr->reg_threshold = EV_REGISTER_THRESHOLD; reg_addr->reg_report_rate = NO_REGISTER; reg_addr->reg_gain = EV_REGISTER_GAIN; reg_addr->reg_offset = NO_REGISTER; reg_addr->reg_offset_x = EV_REGISTER_OFFSET_X; reg_addr->reg_offset_y = EV_REGISTER_OFFSET_Y; reg_addr->reg_num_x = NO_REGISTER; reg_addr->reg_num_y = NO_REGISTER; break; case GENERIC_FT: /* this is a guesswork */ reg_addr->reg_threshold = M09_REGISTER_THRESHOLD; reg_addr->reg_report_rate = NO_REGISTER; reg_addr->reg_gain = M09_REGISTER_GAIN; reg_addr->reg_offset = M09_REGISTER_OFFSET; reg_addr->reg_offset_x = NO_REGISTER; reg_addr->reg_offset_y = NO_REGISTER; reg_addr->reg_num_x = NO_REGISTER; reg_addr->reg_num_y = NO_REGISTER; break; } } static void edt_ft5x06_disable_regulators(void *arg) { struct edt_ft5x06_ts_data *data = arg; regulator_disable(data->vcc); regulator_disable(data->iovcc); } static int edt_ft5x06_ts_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); const struct edt_i2c_chip_data *chip_data; struct edt_ft5x06_ts_data *tsdata; unsigned int val; struct input_dev *input; unsigned long irq_flags; int error; u32 report_rate; dev_dbg(&client->dev, "probing for EDT FT5x06 I2C\n"); tsdata = devm_kzalloc(&client->dev, sizeof(*tsdata), GFP_KERNEL); if (!tsdata) { dev_err(&client->dev, "failed to allocate driver data.\n"); return -ENOMEM; } tsdata->regmap = regmap_init_i2c(client, &edt_ft5x06_i2c_regmap_config); if (IS_ERR(tsdata->regmap)) { dev_err(&client->dev, "regmap allocation failed\n"); return PTR_ERR(tsdata->regmap); } chip_data = device_get_match_data(&client->dev); if (!chip_data) chip_data = (const struct edt_i2c_chip_data *)id->driver_data; if (!chip_data || !chip_data->max_support_points) { dev_err(&client->dev, "invalid or missing chip data\n"); return -EINVAL; } tsdata->max_support_points = chip_data->max_support_points; tsdata->vcc = devm_regulator_get(&client->dev, "vcc"); if (IS_ERR(tsdata->vcc)) return dev_err_probe(&client->dev, PTR_ERR(tsdata->vcc), "failed to request regulator\n"); tsdata->iovcc = devm_regulator_get(&client->dev, "iovcc"); if (IS_ERR(tsdata->iovcc)) { error = PTR_ERR(tsdata->iovcc); if (error != -EPROBE_DEFER) dev_err(&client->dev, "failed to request iovcc regulator: %d\n", error); return error; } error = regulator_enable(tsdata->iovcc); if (error < 0) { dev_err(&client->dev, "failed to enable iovcc: %d\n", error); return error; } /* Delay enabling VCC for > 10us (T_ivd) after IOVCC */ usleep_range(10, 100); error = regulator_enable(tsdata->vcc); if (error < 0) { dev_err(&client->dev, "failed to enable vcc: %d\n", error); regulator_disable(tsdata->iovcc); return error; } error = devm_add_action_or_reset(&client->dev, edt_ft5x06_disable_regulators, tsdata); if (error) return error; tsdata->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(tsdata->reset_gpio)) { error = PTR_ERR(tsdata->reset_gpio); dev_err(&client->dev, "Failed to request GPIO reset pin, error %d\n", error); return error; } tsdata->wake_gpio = devm_gpiod_get_optional(&client->dev, "wake", GPIOD_OUT_LOW); if (IS_ERR(tsdata->wake_gpio)) { error = PTR_ERR(tsdata->wake_gpio); dev_err(&client->dev, "Failed to request GPIO wake pin, error %d\n", error); return error; } /* * Check which sleep modes we can support. Power-off requieres the * reset-pin to ensure correct power-down/power-up behaviour. Start with * the EDT_PMODE_POWEROFF test since this is the deepest possible sleep * mode. */ if (tsdata->reset_gpio) tsdata->suspend_mode = EDT_PMODE_POWEROFF; else if (tsdata->wake_gpio) tsdata->suspend_mode = EDT_PMODE_HIBERNATE; else tsdata->suspend_mode = EDT_PMODE_NOT_SUPPORTED; if (tsdata->wake_gpio) { usleep_range(5000, 6000); gpiod_set_value_cansleep(tsdata->wake_gpio, 1); usleep_range(5000, 6000); } if (tsdata->reset_gpio) { usleep_range(5000, 6000); gpiod_set_value_cansleep(tsdata->reset_gpio, 0); msleep(300); } input = devm_input_allocate_device(&client->dev); if (!input) { dev_err(&client->dev, "failed to allocate input device.\n"); return -ENOMEM; } mutex_init(&tsdata->mutex); tsdata->client = client; tsdata->input = input; tsdata->factory_mode = false; i2c_set_clientdata(client, tsdata); error = edt_ft5x06_ts_identify(client, tsdata); if (error) { dev_err(&client->dev, "touchscreen probe failed\n"); return error; } /* * Dummy read access. EP0700MLP1 returns bogus data on the first * register read access and ignores writes. */ regmap_read(tsdata->regmap, 0x00, &val); edt_ft5x06_ts_set_tdata_parameters(tsdata); edt_ft5x06_ts_set_regs(tsdata); edt_ft5x06_ts_get_defaults(&client->dev, tsdata); edt_ft5x06_ts_get_parameters(tsdata); if (tsdata->reg_addr.reg_report_rate != NO_REGISTER && !device_property_read_u32(&client->dev, "report-rate-hz", &report_rate)) { if (tsdata->version == EDT_M06) tsdata->report_rate = clamp_val(report_rate, 30, 140); else tsdata->report_rate = clamp_val(report_rate, 1, 255); if (report_rate != tsdata->report_rate) dev_warn(&client->dev, "report-rate %dHz is unsupported, use %dHz\n", report_rate, tsdata->report_rate); if (tsdata->version == EDT_M06) tsdata->report_rate /= 10; regmap_write(tsdata->regmap, tsdata->reg_addr.reg_report_rate, tsdata->report_rate); } dev_dbg(&client->dev, "Model \"%s\", Rev. \"%s\", %dx%d sensors\n", tsdata->name, tsdata->fw_version, tsdata->num_x, tsdata->num_y); input->name = tsdata->name; input->id.bustype = BUS_I2C; input->dev.parent = &client->dev; input_set_abs_params(input, ABS_MT_POSITION_X, 0, tsdata->num_x * 64 - 1, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, tsdata->num_y * 64 - 1, 0, 0); touchscreen_parse_properties(input, true, &tsdata->prop); error = input_mt_init_slots(input, tsdata->max_support_points, INPUT_MT_DIRECT); if (error) { dev_err(&client->dev, "Unable to init MT slots.\n"); return error; } irq_flags = irq_get_trigger_type(client->irq); if (irq_flags == IRQF_TRIGGER_NONE) irq_flags = IRQF_TRIGGER_FALLING; irq_flags |= IRQF_ONESHOT; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, edt_ft5x06_ts_isr, irq_flags, client->name, tsdata); if (error) { dev_err(&client->dev, "Unable to request touchscreen IRQ.\n"); return error; } error = devm_device_add_group(&client->dev, &edt_ft5x06_attr_group); if (error) return error; error = input_register_device(input); if (error) return error; edt_ft5x06_ts_prepare_debugfs(tsdata, dev_driver_string(&client->dev)); dev_dbg(&client->dev, "EDT FT5x06 initialized: IRQ %d, WAKE pin %d, Reset pin %d.\n", client->irq, tsdata->wake_gpio ? desc_to_gpio(tsdata->wake_gpio) : -1, tsdata->reset_gpio ? desc_to_gpio(tsdata->reset_gpio) : -1); return 0; } static void edt_ft5x06_ts_remove(struct i2c_client *client) { struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); edt_ft5x06_ts_teardown_debugfs(tsdata); regmap_exit(tsdata->regmap); } static int edt_ft5x06_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); struct gpio_desc *reset_gpio = tsdata->reset_gpio; int ret; if (device_may_wakeup(dev)) return 0; if (tsdata->suspend_mode == EDT_PMODE_NOT_SUPPORTED) return 0; /* Enter hibernate mode. */ ret = regmap_write(tsdata->regmap, PMOD_REGISTER_OPMODE, PMOD_REGISTER_HIBERNATE); if (ret) dev_warn(dev, "Failed to set hibernate mode\n"); if (tsdata->suspend_mode == EDT_PMODE_HIBERNATE) return 0; /* * Power-off according the datasheet. Cut the power may leaf the irq * line in an undefined state depending on the host pull resistor * settings. Disable the irq to avoid adjusting each host till the * device is back in a full functional state. */ disable_irq(tsdata->client->irq); gpiod_set_value_cansleep(reset_gpio, 1); usleep_range(1000, 2000); ret = regulator_disable(tsdata->vcc); if (ret) dev_warn(dev, "Failed to disable vcc\n"); ret = regulator_disable(tsdata->iovcc); if (ret) dev_warn(dev, "Failed to disable iovcc\n"); return 0; } static int edt_ft5x06_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct edt_ft5x06_ts_data *tsdata = i2c_get_clientdata(client); int ret = 0; if (device_may_wakeup(dev)) return 0; if (tsdata->suspend_mode == EDT_PMODE_NOT_SUPPORTED) return 0; if (tsdata->suspend_mode == EDT_PMODE_POWEROFF) { struct gpio_desc *reset_gpio = tsdata->reset_gpio; /* * We can't check if the regulator is a dummy or a real * regulator. So we need to specify the 5ms reset time (T_rst) * here instead of the 100us T_rtp time. We also need to wait * 300ms in case it was a real supply and the power was cutted * of. Toggle the reset pin is also a way to exit the hibernate * mode. */ gpiod_set_value_cansleep(reset_gpio, 1); usleep_range(5000, 6000); ret = regulator_enable(tsdata->iovcc); if (ret) { dev_err(dev, "Failed to enable iovcc\n"); return ret; } /* Delay enabling VCC for > 10us (T_ivd) after IOVCC */ usleep_range(10, 100); ret = regulator_enable(tsdata->vcc); if (ret) { dev_err(dev, "Failed to enable vcc\n"); regulator_disable(tsdata->iovcc); return ret; } usleep_range(1000, 2000); gpiod_set_value_cansleep(reset_gpio, 0); msleep(300); edt_ft5x06_restore_reg_parameters(tsdata); enable_irq(tsdata->client->irq); if (tsdata->factory_mode) ret = edt_ft5x06_factory_mode(tsdata); } else { struct gpio_desc *wake_gpio = tsdata->wake_gpio; gpiod_set_value_cansleep(wake_gpio, 0); usleep_range(5000, 6000); gpiod_set_value_cansleep(wake_gpio, 1); } return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(edt_ft5x06_ts_pm_ops, edt_ft5x06_ts_suspend, edt_ft5x06_ts_resume); static const struct edt_i2c_chip_data edt_ft5x06_data = { .max_support_points = 5, }; static const struct edt_i2c_chip_data edt_ft5506_data = { .max_support_points = 10, }; static const struct edt_i2c_chip_data edt_ft6236_data = { .max_support_points = 2, }; static const struct i2c_device_id edt_ft5x06_ts_id[] = { { .name = "edt-ft5x06", .driver_data = (long)&edt_ft5x06_data }, { .name = "edt-ft5506", .driver_data = (long)&edt_ft5506_data }, { .name = "ev-ft5726", .driver_data = (long)&edt_ft5506_data }, /* Note no edt- prefix for compatibility with the ft6236.c driver */ { .name = "ft6236", .driver_data = (long)&edt_ft6236_data }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, edt_ft5x06_ts_id); static const struct of_device_id edt_ft5x06_of_match[] = { { .compatible = "edt,edt-ft5206", .data = &edt_ft5x06_data }, { .compatible = "edt,edt-ft5306", .data = &edt_ft5x06_data }, { .compatible = "edt,edt-ft5406", .data = &edt_ft5x06_data }, { .compatible = "edt,edt-ft5506", .data = &edt_ft5506_data }, { .compatible = "evervision,ev-ft5726", .data = &edt_ft5506_data }, /* Note focaltech vendor prefix for compatibility with ft6236.c */ { .compatible = "focaltech,ft6236", .data = &edt_ft6236_data }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, edt_ft5x06_of_match); static struct i2c_driver edt_ft5x06_ts_driver = { .driver = { .name = "edt_ft5x06", .of_match_table = edt_ft5x06_of_match, .pm = pm_sleep_ptr(&edt_ft5x06_ts_pm_ops), .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, .id_table = edt_ft5x06_ts_id, .probe = edt_ft5x06_ts_probe, .remove = edt_ft5x06_ts_remove, }; module_i2c_driver(edt_ft5x06_ts_driver); MODULE_AUTHOR("Simon Budig <[email protected]>"); MODULE_DESCRIPTION("EDT FT5x06 I2C Touchscreen Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/edt-ft5x06.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Wacom Penabled Driver for I2C * * Copyright (c) 2011 - 2013 Tatsunosuke Tobita, Wacom. * <[email protected]> */ #include <linux/bits.h> #include <linux/module.h> #include <linux/input.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <asm/unaligned.h> /* Bitmasks (for data[3]) */ #define WACOM_TIP_SWITCH BIT(0) #define WACOM_BARREL_SWITCH BIT(1) #define WACOM_ERASER BIT(2) #define WACOM_INVERT BIT(3) #define WACOM_BARREL_SWITCH_2 BIT(4) #define WACOM_IN_PROXIMITY BIT(5) /* Registers */ #define WACOM_COMMAND_LSB 0x04 #define WACOM_COMMAND_MSB 0x00 #define WACOM_DATA_LSB 0x05 #define WACOM_DATA_MSB 0x00 /* Report types */ #define REPORT_FEATURE 0x30 /* Requests / operations */ #define OPCODE_GET_REPORT 0x02 #define WACOM_QUERY_REPORT 3 #define WACOM_QUERY_SIZE 19 struct wacom_features { int x_max; int y_max; int pressure_max; char fw_version; }; struct wacom_i2c { struct i2c_client *client; struct input_dev *input; u8 data[WACOM_QUERY_SIZE]; bool prox; int tool; }; static int wacom_query_device(struct i2c_client *client, struct wacom_features *features) { u8 get_query_data_cmd[] = { WACOM_COMMAND_LSB, WACOM_COMMAND_MSB, REPORT_FEATURE | WACOM_QUERY_REPORT, OPCODE_GET_REPORT, WACOM_DATA_LSB, WACOM_DATA_MSB, }; u8 data[WACOM_QUERY_SIZE]; int ret; struct i2c_msg msgs[] = { /* Request reading of feature ReportID: 3 (Pen Query Data) */ { .addr = client->addr, .flags = 0, .len = sizeof(get_query_data_cmd), .buf = get_query_data_cmd, }, { .addr = client->addr, .flags = I2C_M_RD, .len = sizeof(data), .buf = data, }, }; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) return ret; if (ret != ARRAY_SIZE(msgs)) return -EIO; features->x_max = get_unaligned_le16(&data[3]); features->y_max = get_unaligned_le16(&data[5]); features->pressure_max = get_unaligned_le16(&data[11]); features->fw_version = get_unaligned_le16(&data[13]); dev_dbg(&client->dev, "x_max:%d, y_max:%d, pressure:%d, fw:%d\n", features->x_max, features->y_max, features->pressure_max, features->fw_version); return 0; } static irqreturn_t wacom_i2c_irq(int irq, void *dev_id) { struct wacom_i2c *wac_i2c = dev_id; struct input_dev *input = wac_i2c->input; u8 *data = wac_i2c->data; unsigned int x, y, pressure; unsigned char tsw, f1, f2, ers; int error; error = i2c_master_recv(wac_i2c->client, wac_i2c->data, sizeof(wac_i2c->data)); if (error < 0) goto out; tsw = data[3] & WACOM_TIP_SWITCH; ers = data[3] & WACOM_ERASER; f1 = data[3] & WACOM_BARREL_SWITCH; f2 = data[3] & WACOM_BARREL_SWITCH_2; x = le16_to_cpup((__le16 *)&data[4]); y = le16_to_cpup((__le16 *)&data[6]); pressure = le16_to_cpup((__le16 *)&data[8]); if (!wac_i2c->prox) wac_i2c->tool = (data[3] & (WACOM_ERASER | WACOM_INVERT)) ? BTN_TOOL_RUBBER : BTN_TOOL_PEN; wac_i2c->prox = data[3] & WACOM_IN_PROXIMITY; input_report_key(input, BTN_TOUCH, tsw || ers); input_report_key(input, wac_i2c->tool, wac_i2c->prox); input_report_key(input, BTN_STYLUS, f1); input_report_key(input, BTN_STYLUS2, f2); input_report_abs(input, ABS_X, x); input_report_abs(input, ABS_Y, y); input_report_abs(input, ABS_PRESSURE, pressure); input_sync(input); out: return IRQ_HANDLED; } static int wacom_i2c_open(struct input_dev *dev) { struct wacom_i2c *wac_i2c = input_get_drvdata(dev); struct i2c_client *client = wac_i2c->client; enable_irq(client->irq); return 0; } static void wacom_i2c_close(struct input_dev *dev) { struct wacom_i2c *wac_i2c = input_get_drvdata(dev); struct i2c_client *client = wac_i2c->client; disable_irq(client->irq); } static int wacom_i2c_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct wacom_i2c *wac_i2c; struct input_dev *input; struct wacom_features features = { 0 }; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(dev, "i2c_check_functionality error\n"); return -EIO; } error = wacom_query_device(client, &features); if (error) return error; wac_i2c = devm_kzalloc(dev, sizeof(*wac_i2c), GFP_KERNEL); if (!wac_i2c) return -ENOMEM; wac_i2c->client = client; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; wac_i2c->input = input; input->name = "Wacom I2C Digitizer"; input->id.bustype = BUS_I2C; input->id.vendor = 0x56a; input->id.version = features.fw_version; input->open = wacom_i2c_open; input->close = wacom_i2c_close; input->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); __set_bit(BTN_TOOL_PEN, input->keybit); __set_bit(BTN_TOOL_RUBBER, input->keybit); __set_bit(BTN_STYLUS, input->keybit); __set_bit(BTN_STYLUS2, input->keybit); __set_bit(BTN_TOUCH, input->keybit); input_set_abs_params(input, ABS_X, 0, features.x_max, 0, 0); input_set_abs_params(input, ABS_Y, 0, features.y_max, 0, 0); input_set_abs_params(input, ABS_PRESSURE, 0, features.pressure_max, 0, 0); input_set_drvdata(input, wac_i2c); error = devm_request_threaded_irq(dev, client->irq, NULL, wacom_i2c_irq, IRQF_ONESHOT, "wacom_i2c", wac_i2c); if (error) { dev_err(dev, "Failed to request IRQ: %d\n", error); return error; } /* Disable the IRQ, we'll enable it in wac_i2c_open() */ disable_irq(client->irq); error = input_register_device(wac_i2c->input); if (error) { dev_err(dev, "Failed to register input device: %d\n", error); return error; } return 0; } static int wacom_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); disable_irq(client->irq); return 0; } static int wacom_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(wacom_i2c_pm, wacom_i2c_suspend, wacom_i2c_resume); static const struct i2c_device_id wacom_i2c_id[] = { { "WAC_I2C_EMR", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, wacom_i2c_id); static struct i2c_driver wacom_i2c_driver = { .driver = { .name = "wacom_i2c", .pm = pm_sleep_ptr(&wacom_i2c_pm), }, .probe = wacom_i2c_probe, .id_table = wacom_i2c_id, }; module_i2c_driver(wacom_i2c_driver); MODULE_AUTHOR("Tatsunosuke Tobita <[email protected]>"); MODULE_DESCRIPTION("WACOM EMR I2C Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wacom_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * * h3600 atmel micro companion support, touchscreen subdevice * Author : Alessandro Gardich <[email protected]> * Author : Dmitry Artamonow <[email protected]> * Author : Linus Walleij <[email protected]> */ #include <asm/byteorder.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/pm.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/input.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/mfd/ipaq-micro.h> struct touchscreen_data { struct input_dev *input; struct ipaq_micro *micro; }; static void micro_ts_receive(void *data, int len, unsigned char *msg) { struct touchscreen_data *ts = data; if (len == 4) { input_report_abs(ts->input, ABS_X, be16_to_cpup((__be16 *) &msg[2])); input_report_abs(ts->input, ABS_Y, be16_to_cpup((__be16 *) &msg[0])); input_report_key(ts->input, BTN_TOUCH, 1); input_sync(ts->input); } else if (len == 0) { input_report_abs(ts->input, ABS_X, 0); input_report_abs(ts->input, ABS_Y, 0); input_report_key(ts->input, BTN_TOUCH, 0); input_sync(ts->input); } } static void micro_ts_toggle_receive(struct touchscreen_data *ts, bool enable) { struct ipaq_micro *micro = ts->micro; spin_lock_irq(&micro->lock); if (enable) { micro->ts = micro_ts_receive; micro->ts_data = ts; } else { micro->ts = NULL; micro->ts_data = NULL; } spin_unlock_irq(&ts->micro->lock); } static int micro_ts_open(struct input_dev *input) { struct touchscreen_data *ts = input_get_drvdata(input); micro_ts_toggle_receive(ts, true); return 0; } static void micro_ts_close(struct input_dev *input) { struct touchscreen_data *ts = input_get_drvdata(input); micro_ts_toggle_receive(ts, false); } static int micro_ts_probe(struct platform_device *pdev) { struct ipaq_micro *micro = dev_get_drvdata(pdev->dev.parent); struct touchscreen_data *ts; int error; ts = devm_kzalloc(&pdev->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->micro = micro; ts->input = devm_input_allocate_device(&pdev->dev); if (!ts->input) { dev_err(&pdev->dev, "failed to allocate input device\n"); return -ENOMEM; } ts->input->name = "ipaq micro ts"; ts->input->open = micro_ts_open; ts->input->close = micro_ts_close; input_set_drvdata(ts->input, ts); input_set_capability(ts->input, EV_KEY, BTN_TOUCH); input_set_capability(ts->input, EV_ABS, ABS_X); input_set_capability(ts->input, EV_ABS, ABS_Y); input_set_abs_params(ts->input, ABS_X, 0, 1023, 0, 0); input_set_abs_params(ts->input, ABS_Y, 0, 1023, 0, 0); error = input_register_device(ts->input); if (error) { dev_err(&pdev->dev, "error registering touch input\n"); return error; } platform_set_drvdata(pdev, ts); dev_info(&pdev->dev, "iPAQ micro touchscreen\n"); return 0; } static int micro_ts_suspend(struct device *dev) { struct touchscreen_data *ts = dev_get_drvdata(dev); micro_ts_toggle_receive(ts, false); return 0; } static int micro_ts_resume(struct device *dev) { struct touchscreen_data *ts = dev_get_drvdata(dev); struct input_dev *input = ts->input; mutex_lock(&input->mutex); if (input_device_enabled(input)) micro_ts_toggle_receive(ts, true); mutex_unlock(&input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(micro_ts_dev_pm_ops, micro_ts_suspend, micro_ts_resume); static struct platform_driver micro_ts_device_driver = { .driver = { .name = "ipaq-micro-ts", .pm = pm_sleep_ptr(&micro_ts_dev_pm_ops), }, .probe = micro_ts_probe, }; module_platform_driver(micro_ts_device_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("driver for iPAQ Atmel micro touchscreen"); MODULE_ALIAS("platform:ipaq-micro-ts");
linux-master
drivers/input/touchscreen/ipaq-micro-ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Touch Screen driver for EETI's I2C connected touch screen panels * Copyright (c) 2009,2018 Daniel Mack <[email protected]> * * See EETI's software guide for the protocol specification: * http://home.eeti.com.tw/documentation.html * * Based on migor_ts.c * Copyright (c) 2008 Magnus Damm * Copyright (c) 2007 Ujjwal Pande <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/timer.h> #include <linux/gpio/consumer.h> #include <linux/of.h> #include <linux/slab.h> #include <asm/unaligned.h> struct eeti_ts { struct i2c_client *client; struct input_dev *input; struct gpio_desc *attn_gpio; struct touchscreen_properties props; struct mutex mutex; bool running; }; #define EETI_TS_BITDEPTH (11) #define EETI_MAXVAL ((1 << (EETI_TS_BITDEPTH + 1)) - 1) #define REPORT_BIT_PRESSED BIT(0) #define REPORT_BIT_AD0 BIT(1) #define REPORT_BIT_AD1 BIT(2) #define REPORT_BIT_HAS_PRESSURE BIT(6) #define REPORT_RES_BITS(v) (((v) >> 1) + EETI_TS_BITDEPTH) static void eeti_ts_report_event(struct eeti_ts *eeti, u8 *buf) { unsigned int res; u16 x, y; res = REPORT_RES_BITS(buf[0] & (REPORT_BIT_AD0 | REPORT_BIT_AD1)); x = get_unaligned_be16(&buf[1]); y = get_unaligned_be16(&buf[3]); /* fix the range to 11 bits */ x >>= res - EETI_TS_BITDEPTH; y >>= res - EETI_TS_BITDEPTH; if (buf[0] & REPORT_BIT_HAS_PRESSURE) input_report_abs(eeti->input, ABS_PRESSURE, buf[5]); touchscreen_report_pos(eeti->input, &eeti->props, x, y, false); input_report_key(eeti->input, BTN_TOUCH, buf[0] & REPORT_BIT_PRESSED); input_sync(eeti->input); } static int eeti_ts_read(struct eeti_ts *eeti) { int len, error; char buf[6]; len = i2c_master_recv(eeti->client, buf, sizeof(buf)); if (len != sizeof(buf)) { error = len < 0 ? len : -EIO; dev_err(&eeti->client->dev, "failed to read touchscreen data: %d\n", error); return error; } /* Motion packet */ if (buf[0] & 0x80) eeti_ts_report_event(eeti, buf); return 0; } static irqreturn_t eeti_ts_isr(int irq, void *dev_id) { struct eeti_ts *eeti = dev_id; int error; mutex_lock(&eeti->mutex); do { /* * If we have attention GPIO, trust it. Otherwise we'll read * once and exit. We assume that in this case we are using * level triggered interrupt and it will get raised again * if/when there is more data. */ if (eeti->attn_gpio && !gpiod_get_value_cansleep(eeti->attn_gpio)) { break; } error = eeti_ts_read(eeti); if (error) break; } while (eeti->running && eeti->attn_gpio); mutex_unlock(&eeti->mutex); return IRQ_HANDLED; } static void eeti_ts_start(struct eeti_ts *eeti) { mutex_lock(&eeti->mutex); eeti->running = true; enable_irq(eeti->client->irq); /* * Kick the controller in case we are using edge interrupt and * we missed our edge while interrupt was disabled. We expect * the attention GPIO to be wired in this case. */ if (eeti->attn_gpio && gpiod_get_value_cansleep(eeti->attn_gpio)) eeti_ts_read(eeti); mutex_unlock(&eeti->mutex); } static void eeti_ts_stop(struct eeti_ts *eeti) { /* * Not locking here, just setting a flag and expect that the * interrupt thread will notice the flag eventually. */ eeti->running = false; wmb(); disable_irq(eeti->client->irq); } static int eeti_ts_open(struct input_dev *dev) { struct eeti_ts *eeti = input_get_drvdata(dev); eeti_ts_start(eeti); return 0; } static void eeti_ts_close(struct input_dev *dev) { struct eeti_ts *eeti = input_get_drvdata(dev); eeti_ts_stop(eeti); } static int eeti_ts_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct eeti_ts *eeti; struct input_dev *input; int error; /* * In contrast to what's described in the datasheet, there seems * to be no way of probing the presence of that device using I2C * commands. So we need to blindly believe it is there, and wait * for interrupts to occur. */ eeti = devm_kzalloc(dev, sizeof(*eeti), GFP_KERNEL); if (!eeti) { dev_err(dev, "failed to allocate driver data\n"); return -ENOMEM; } mutex_init(&eeti->mutex); input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "Failed to allocate input device.\n"); return -ENOMEM; } input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, 0, EETI_MAXVAL, 0, 0); input_set_abs_params(input, ABS_Y, 0, EETI_MAXVAL, 0, 0); input_set_abs_params(input, ABS_PRESSURE, 0, 0xff, 0, 0); touchscreen_parse_properties(input, false, &eeti->props); input->name = client->name; input->id.bustype = BUS_I2C; input->open = eeti_ts_open; input->close = eeti_ts_close; eeti->client = client; eeti->input = input; eeti->attn_gpio = devm_gpiod_get_optional(dev, "attn", GPIOD_IN); if (IS_ERR(eeti->attn_gpio)) return PTR_ERR(eeti->attn_gpio); i2c_set_clientdata(client, eeti); input_set_drvdata(input, eeti); error = devm_request_threaded_irq(dev, client->irq, NULL, eeti_ts_isr, IRQF_ONESHOT, client->name, eeti); if (error) { dev_err(dev, "Unable to request touchscreen IRQ: %d\n", error); return error; } /* * Disable the device for now. It will be enabled once the * input device is opened. */ eeti_ts_stop(eeti); error = input_register_device(input); if (error) return error; return 0; } static int eeti_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct eeti_ts *eeti = i2c_get_clientdata(client); struct input_dev *input_dev = eeti->input; mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) eeti_ts_stop(eeti); mutex_unlock(&input_dev->mutex); if (device_may_wakeup(&client->dev)) enable_irq_wake(client->irq); return 0; } static int eeti_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct eeti_ts *eeti = i2c_get_clientdata(client); struct input_dev *input_dev = eeti->input; if (device_may_wakeup(&client->dev)) disable_irq_wake(client->irq); mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) eeti_ts_start(eeti); mutex_unlock(&input_dev->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(eeti_ts_pm, eeti_ts_suspend, eeti_ts_resume); static const struct i2c_device_id eeti_ts_id[] = { { "eeti_ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, eeti_ts_id); #ifdef CONFIG_OF static const struct of_device_id of_eeti_ts_match[] = { { .compatible = "eeti,exc3000-i2c", }, { } }; #endif static struct i2c_driver eeti_ts_driver = { .driver = { .name = "eeti_ts", .pm = pm_sleep_ptr(&eeti_ts_pm), .of_match_table = of_match_ptr(of_eeti_ts_match), }, .probe = eeti_ts_probe, .id_table = eeti_ts_id, }; module_i2c_driver(eeti_ts_driver); MODULE_DESCRIPTION("EETI Touchscreen driver"); MODULE_AUTHOR("Daniel Mack <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/eeti_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * iNexio serial touchscreen driver * * Copyright (c) 2008 Richard Lemon * Based on the mtouch driver (c) Vojtech Pavlik and Dan Streetman */ /* * 2008/06/19 Richard Lemon <[email protected]> * Copied mtouch.c and edited for iNexio protocol */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #define DRIVER_DESC "iNexio serial touchscreen driver" MODULE_AUTHOR("Richard Lemon <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define INEXIO_FORMAT_TOUCH_BIT 0x01 #define INEXIO_FORMAT_LENGTH 5 #define INEXIO_RESPONSE_BEGIN_BYTE 0x80 /* todo: check specs for max length of all responses */ #define INEXIO_MAX_LENGTH 16 #define INEXIO_MIN_XC 0 #define INEXIO_MAX_XC 0x3fff #define INEXIO_MIN_YC 0 #define INEXIO_MAX_YC 0x3fff #define INEXIO_GET_XC(data) (((data[1])<<7) | data[2]) #define INEXIO_GET_YC(data) (((data[3])<<7) | data[4]) #define INEXIO_GET_TOUCHED(data) (INEXIO_FORMAT_TOUCH_BIT & data[0]) /* * Per-touchscreen data. */ struct inexio { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[INEXIO_MAX_LENGTH]; char phys[32]; }; static void inexio_process_data(struct inexio *pinexio) { struct input_dev *dev = pinexio->dev; if (INEXIO_FORMAT_LENGTH == ++pinexio->idx) { input_report_abs(dev, ABS_X, INEXIO_GET_XC(pinexio->data)); input_report_abs(dev, ABS_Y, INEXIO_GET_YC(pinexio->data)); input_report_key(dev, BTN_TOUCH, INEXIO_GET_TOUCHED(pinexio->data)); input_sync(dev); pinexio->idx = 0; } } static irqreturn_t inexio_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct inexio *pinexio = serio_get_drvdata(serio); pinexio->data[pinexio->idx] = data; if (INEXIO_RESPONSE_BEGIN_BYTE&pinexio->data[0]) inexio_process_data(pinexio); else printk(KERN_DEBUG "inexio.c: unknown/unsynchronized data from device, byte %x\n",pinexio->data[0]); return IRQ_HANDLED; } /* * inexio_disconnect() is the opposite of inexio_connect() */ static void inexio_disconnect(struct serio *serio) { struct inexio *pinexio = serio_get_drvdata(serio); input_get_device(pinexio->dev); input_unregister_device(pinexio->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(pinexio->dev); kfree(pinexio); } /* * inexio_connect() is the routine that is called when someone adds a * new serio device that supports iNexio protocol and registers it as * an input device. This is usually accomplished using inputattach. */ static int inexio_connect(struct serio *serio, struct serio_driver *drv) { struct inexio *pinexio; struct input_dev *input_dev; int err; pinexio = kzalloc(sizeof(struct inexio), GFP_KERNEL); input_dev = input_allocate_device(); if (!pinexio || !input_dev) { err = -ENOMEM; goto fail1; } pinexio->serio = serio; pinexio->dev = input_dev; snprintf(pinexio->phys, sizeof(pinexio->phys), "%s/input0", serio->phys); input_dev->name = "iNexio Serial TouchScreen"; input_dev->phys = pinexio->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_INEXIO; input_dev->id.product = 0; input_dev->id.version = 0x0001; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(pinexio->dev, ABS_X, INEXIO_MIN_XC, INEXIO_MAX_XC, 0, 0); input_set_abs_params(pinexio->dev, ABS_Y, INEXIO_MIN_YC, INEXIO_MAX_YC, 0, 0); serio_set_drvdata(serio, pinexio); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(pinexio->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(pinexio); return err; } /* * The serio driver structure. */ static const struct serio_device_id inexio_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_INEXIO, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, inexio_serio_ids); static struct serio_driver inexio_drv = { .driver = { .name = "inexio", }, .description = DRIVER_DESC, .id_table = inexio_serio_ids, .interrupt = inexio_interrupt, .connect = inexio_connect, .disconnect = inexio_disconnect, }; module_serio_driver(inexio_drv);
linux-master
drivers/input/touchscreen/inexio.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * TSC2004 touchscreen driver * * Copyright (C) 2015 QWERTY Embedded Design * Copyright (C) 2015 EMAC Inc. */ #include <linux/module.h> #include <linux/input.h> #include <linux/of.h> #include <linux/i2c.h> #include <linux/regmap.h> #include "tsc200x-core.h" static const struct input_id tsc2004_input_id = { .bustype = BUS_I2C, .product = 2004, }; static int tsc2004_cmd(struct device *dev, u8 cmd) { u8 tx = TSC200X_CMD | TSC200X_CMD_12BIT | cmd; s32 data; struct i2c_client *i2c = to_i2c_client(dev); data = i2c_smbus_write_byte(i2c, tx); if (data < 0) { dev_err(dev, "%s: failed, command: %x i2c error: %d\n", __func__, cmd, data); return data; } return 0; } static int tsc2004_probe(struct i2c_client *i2c) { return tsc200x_probe(&i2c->dev, i2c->irq, &tsc2004_input_id, devm_regmap_init_i2c(i2c, &tsc200x_regmap_config), tsc2004_cmd); } static void tsc2004_remove(struct i2c_client *i2c) { tsc200x_remove(&i2c->dev); } static const struct i2c_device_id tsc2004_idtable[] = { { "tsc2004", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tsc2004_idtable); #ifdef CONFIG_OF static const struct of_device_id tsc2004_of_match[] = { { .compatible = "ti,tsc2004" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, tsc2004_of_match); #endif static struct i2c_driver tsc2004_driver = { .driver = { .name = "tsc2004", .of_match_table = of_match_ptr(tsc2004_of_match), .pm = pm_sleep_ptr(&tsc200x_pm_ops), }, .id_table = tsc2004_idtable, .probe = tsc2004_probe, .remove = tsc2004_remove, }; module_i2c_driver(tsc2004_driver); MODULE_AUTHOR("Michael Welling <[email protected]>"); MODULE_DESCRIPTION("TSC2004 Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/tsc2004.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AD7879-1/AD7889-1 touchscreen (I2C bus) * * Copyright (C) 2008-2010 Michael Hennerich, Analog Devices Inc. */ #include <linux/input.h> /* BUS_I2C */ #include <linux/i2c.h> #include <linux/module.h> #include <linux/types.h> #include <linux/of.h> #include <linux/pm.h> #include <linux/regmap.h> #include "ad7879.h" #define AD7879_DEVID 0x79 /* AD7879-1/AD7889-1 */ static const struct regmap_config ad7879_i2c_regmap_config = { .reg_bits = 8, .val_bits = 16, .max_register = 15, }; static int ad7879_i2c_probe(struct i2c_client *client) { struct regmap *regmap; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WORD_DATA)) { dev_err(&client->dev, "SMBUS Word Data not Supported\n"); return -EIO; } regmap = devm_regmap_init_i2c(client, &ad7879_i2c_regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); return ad7879_probe(&client->dev, regmap, client->irq, BUS_I2C, AD7879_DEVID); } static const struct i2c_device_id ad7879_id[] = { { "ad7879", 0 }, { "ad7889", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ad7879_id); #ifdef CONFIG_OF static const struct of_device_id ad7879_i2c_dt_ids[] = { { .compatible = "adi,ad7879-1", }, { } }; MODULE_DEVICE_TABLE(of, ad7879_i2c_dt_ids); #endif static struct i2c_driver ad7879_i2c_driver = { .driver = { .name = "ad7879", .pm = &ad7879_pm_ops, .of_match_table = of_match_ptr(ad7879_i2c_dt_ids), }, .probe = ad7879_i2c_probe, .id_table = ad7879_id, }; module_i2c_driver(ad7879_i2c_driver); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("AD7879(-1) touchscreen I2C bus driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ad7879-i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Touchwindow serial touchscreen driver * * Copyright (c) 2006 Rick Koch <[email protected]> * * Based on MicroTouch driver (drivers/input/touchscreen/mtouch.c) * Copyright (c) 2004 Vojtech Pavlik * and Dan Streetman <[email protected]> */ /* * 2005/02/19 Rick Koch: * The Touchwindow I used is made by Edmark Corp. and * constantly outputs a stream of 0's unless it is touched. * It then outputs 3 bytes: X, Y, and a copy of Y. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #define DRIVER_DESC "Touchwindow serial touchscreen driver" MODULE_AUTHOR("Rick Koch <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define TW_LENGTH 3 #define TW_MIN_XC 0 #define TW_MAX_XC 0xff #define TW_MIN_YC 0 #define TW_MAX_YC 0xff /* * Per-touchscreen data. */ struct tw { struct input_dev *dev; struct serio *serio; int idx; int touched; unsigned char data[TW_LENGTH]; char phys[32]; }; static irqreturn_t tw_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct tw *tw = serio_get_drvdata(serio); struct input_dev *dev = tw->dev; if (data) { /* touch */ tw->touched = 1; tw->data[tw->idx++] = data; /* verify length and that the two Y's are the same */ if (tw->idx == TW_LENGTH && tw->data[1] == tw->data[2]) { input_report_abs(dev, ABS_X, tw->data[0]); input_report_abs(dev, ABS_Y, tw->data[1]); input_report_key(dev, BTN_TOUCH, 1); input_sync(dev); tw->idx = 0; } } else if (tw->touched) { /* untouch */ input_report_key(dev, BTN_TOUCH, 0); input_sync(dev); tw->idx = 0; tw->touched = 0; } return IRQ_HANDLED; } /* * tw_disconnect() is the opposite of tw_connect() */ static void tw_disconnect(struct serio *serio) { struct tw *tw = serio_get_drvdata(serio); input_get_device(tw->dev); input_unregister_device(tw->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(tw->dev); kfree(tw); } /* * tw_connect() is the routine that is called when someone adds a * new serio device that supports the Touchwin protocol and registers it as * an input device. */ static int tw_connect(struct serio *serio, struct serio_driver *drv) { struct tw *tw; struct input_dev *input_dev; int err; tw = kzalloc(sizeof(struct tw), GFP_KERNEL); input_dev = input_allocate_device(); if (!tw || !input_dev) { err = -ENOMEM; goto fail1; } tw->serio = serio; tw->dev = input_dev; snprintf(tw->phys, sizeof(tw->phys), "%s/input0", serio->phys); input_dev->name = "Touchwindow Serial TouchScreen"; input_dev->phys = tw->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_TOUCHWIN; input_dev->id.product = 0; input_dev->id.version = 0x0100; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(tw->dev, ABS_X, TW_MIN_XC, TW_MAX_XC, 0, 0); input_set_abs_params(tw->dev, ABS_Y, TW_MIN_YC, TW_MAX_YC, 0, 0); serio_set_drvdata(serio, tw); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(tw->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(tw); return err; } /* * The serio driver structure. */ static const struct serio_device_id tw_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_TOUCHWIN, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, tw_serio_ids); static struct serio_driver tw_drv = { .driver = { .name = "touchwin", }, .description = DRIVER_DESC, .id_table = tw_serio_ids, .interrupt = tw_interrupt, .connect = tw_connect, .disconnect = tw_disconnect, }; module_serio_driver(tw_drv);
linux-master
drivers/input/touchscreen/touchwin.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Goodix Touchscreens * * Copyright (c) 2014 Red Hat Inc. * Copyright (c) 2015 K. Merker <[email protected]> * * This code is based on gt9xx.c authored by [email protected]: * * 2010 - 2012 Goodix Technology. */ #include <linux/kernel.h> #include <linux/dmi.h> #include <linux/firmware.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/platform_data/x86/soc.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/of.h> #include <asm/unaligned.h> #include "goodix.h" #define GOODIX_GPIO_INT_NAME "irq" #define GOODIX_GPIO_RST_NAME "reset" #define GOODIX_MAX_HEIGHT 4096 #define GOODIX_MAX_WIDTH 4096 #define GOODIX_INT_TRIGGER 1 #define GOODIX_CONTACT_SIZE 8 #define GOODIX_MAX_CONTACT_SIZE 9 #define GOODIX_MAX_CONTACTS 10 #define GOODIX_CONFIG_MIN_LENGTH 186 #define GOODIX_CONFIG_911_LENGTH 186 #define GOODIX_CONFIG_967_LENGTH 228 #define GOODIX_CONFIG_GT9X_LENGTH 240 #define GOODIX_BUFFER_STATUS_READY BIT(7) #define GOODIX_HAVE_KEY BIT(4) #define GOODIX_BUFFER_STATUS_TIMEOUT 20 #define RESOLUTION_LOC 1 #define MAX_CONTACTS_LOC 5 #define TRIGGER_LOC 6 /* Our special handling for GPIO accesses through ACPI is x86 specific */ #if defined CONFIG_X86 && defined CONFIG_ACPI #define ACPI_GPIO_SUPPORT #endif struct goodix_chip_id { const char *id; const struct goodix_chip_data *data; }; static int goodix_check_cfg_8(struct goodix_ts_data *ts, const u8 *cfg, int len); static int goodix_check_cfg_16(struct goodix_ts_data *ts, const u8 *cfg, int len); static void goodix_calc_cfg_checksum_8(struct goodix_ts_data *ts); static void goodix_calc_cfg_checksum_16(struct goodix_ts_data *ts); static const struct goodix_chip_data gt1x_chip_data = { .config_addr = GOODIX_GT1X_REG_CONFIG_DATA, .config_len = GOODIX_CONFIG_GT9X_LENGTH, .check_config = goodix_check_cfg_16, .calc_config_checksum = goodix_calc_cfg_checksum_16, }; static const struct goodix_chip_data gt911_chip_data = { .config_addr = GOODIX_GT9X_REG_CONFIG_DATA, .config_len = GOODIX_CONFIG_911_LENGTH, .check_config = goodix_check_cfg_8, .calc_config_checksum = goodix_calc_cfg_checksum_8, }; static const struct goodix_chip_data gt967_chip_data = { .config_addr = GOODIX_GT9X_REG_CONFIG_DATA, .config_len = GOODIX_CONFIG_967_LENGTH, .check_config = goodix_check_cfg_8, .calc_config_checksum = goodix_calc_cfg_checksum_8, }; static const struct goodix_chip_data gt9x_chip_data = { .config_addr = GOODIX_GT9X_REG_CONFIG_DATA, .config_len = GOODIX_CONFIG_GT9X_LENGTH, .check_config = goodix_check_cfg_8, .calc_config_checksum = goodix_calc_cfg_checksum_8, }; static const struct goodix_chip_id goodix_chip_ids[] = { { .id = "1151", .data = &gt1x_chip_data }, { .id = "1158", .data = &gt1x_chip_data }, { .id = "5663", .data = &gt1x_chip_data }, { .id = "5688", .data = &gt1x_chip_data }, { .id = "917S", .data = &gt1x_chip_data }, { .id = "9286", .data = &gt1x_chip_data }, { .id = "911", .data = &gt911_chip_data }, { .id = "9271", .data = &gt911_chip_data }, { .id = "9110", .data = &gt911_chip_data }, { .id = "9111", .data = &gt911_chip_data }, { .id = "927", .data = &gt911_chip_data }, { .id = "928", .data = &gt911_chip_data }, { .id = "912", .data = &gt967_chip_data }, { .id = "9147", .data = &gt967_chip_data }, { .id = "967", .data = &gt967_chip_data }, { } }; static const unsigned long goodix_irq_flags[] = { IRQ_TYPE_EDGE_RISING, IRQ_TYPE_EDGE_FALLING, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, }; static const struct dmi_system_id nine_bytes_report[] = { #if defined(CONFIG_DMI) && defined(CONFIG_X86) { /* Lenovo Yoga Book X90F / X90L */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Intel Corporation"), DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "CHERRYVIEW D1 PLATFORM"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "YETI-11"), } }, { /* Lenovo Yoga Book X91F / X91L */ .matches = { /* Non exact match to match F + L versions */ DMI_MATCH(DMI_PRODUCT_NAME, "Lenovo YB1-X91"), } }, #endif {} }; /* * Those tablets have their x coordinate inverted */ static const struct dmi_system_id inverted_x_screen[] = { #if defined(CONFIG_DMI) && defined(CONFIG_X86) { .ident = "Cube I15-TC", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Cube"), DMI_MATCH(DMI_PRODUCT_NAME, "I15-TC") }, }, #endif {} }; /** * goodix_i2c_read - read data from a register of the i2c slave device. * * @client: i2c device. * @reg: the register to read from. * @buf: raw write data buffer. * @len: length of the buffer to write */ int goodix_i2c_read(struct i2c_client *client, u16 reg, u8 *buf, int len) { struct i2c_msg msgs[2]; __be16 wbuf = cpu_to_be16(reg); int ret; msgs[0].flags = 0; msgs[0].addr = client->addr; msgs[0].len = 2; msgs[0].buf = (u8 *)&wbuf; msgs[1].flags = I2C_M_RD; msgs[1].addr = client->addr; msgs[1].len = len; msgs[1].buf = buf; ret = i2c_transfer(client->adapter, msgs, 2); if (ret >= 0) ret = (ret == ARRAY_SIZE(msgs) ? 0 : -EIO); if (ret) dev_err(&client->dev, "Error reading %d bytes from 0x%04x: %d\n", len, reg, ret); return ret; } /** * goodix_i2c_write - write data to a register of the i2c slave device. * * @client: i2c device. * @reg: the register to write to. * @buf: raw data buffer to write. * @len: length of the buffer to write */ int goodix_i2c_write(struct i2c_client *client, u16 reg, const u8 *buf, int len) { u8 *addr_buf; struct i2c_msg msg; int ret; addr_buf = kmalloc(len + 2, GFP_KERNEL); if (!addr_buf) return -ENOMEM; addr_buf[0] = reg >> 8; addr_buf[1] = reg & 0xFF; memcpy(&addr_buf[2], buf, len); msg.flags = 0; msg.addr = client->addr; msg.buf = addr_buf; msg.len = len + 2; ret = i2c_transfer(client->adapter, &msg, 1); if (ret >= 0) ret = (ret == 1 ? 0 : -EIO); kfree(addr_buf); if (ret) dev_err(&client->dev, "Error writing %d bytes to 0x%04x: %d\n", len, reg, ret); return ret; } int goodix_i2c_write_u8(struct i2c_client *client, u16 reg, u8 value) { return goodix_i2c_write(client, reg, &value, sizeof(value)); } static const struct goodix_chip_data *goodix_get_chip_data(const char *id) { unsigned int i; for (i = 0; goodix_chip_ids[i].id; i++) { if (!strcmp(goodix_chip_ids[i].id, id)) return goodix_chip_ids[i].data; } return &gt9x_chip_data; } static int goodix_ts_read_input_report(struct goodix_ts_data *ts, u8 *data) { unsigned long max_timeout; int touch_num; int error; u16 addr = GOODIX_READ_COOR_ADDR; /* * We are going to read 1-byte header, * ts->contact_size * max(1, touch_num) bytes of coordinates * and 1-byte footer which contains the touch-key code. */ const int header_contact_keycode_size = 1 + ts->contact_size + 1; /* * The 'buffer status' bit, which indicates that the data is valid, is * not set as soon as the interrupt is raised, but slightly after. * This takes around 10 ms to happen, so we poll for 20 ms. */ max_timeout = jiffies + msecs_to_jiffies(GOODIX_BUFFER_STATUS_TIMEOUT); do { error = goodix_i2c_read(ts->client, addr, data, header_contact_keycode_size); if (error) return error; if (data[0] & GOODIX_BUFFER_STATUS_READY) { touch_num = data[0] & 0x0f; if (touch_num > ts->max_touch_num) return -EPROTO; if (touch_num > 1) { addr += header_contact_keycode_size; data += header_contact_keycode_size; error = goodix_i2c_read(ts->client, addr, data, ts->contact_size * (touch_num - 1)); if (error) return error; } return touch_num; } if (data[0] == 0 && ts->firmware_name) { if (goodix_handle_fw_request(ts)) return 0; } usleep_range(1000, 2000); /* Poll every 1 - 2 ms */ } while (time_before(jiffies, max_timeout)); /* * The Goodix panel will send spurious interrupts after a * 'finger up' event, which will always cause a timeout. */ return -ENOMSG; } static int goodix_create_pen_input(struct goodix_ts_data *ts) { struct device *dev = &ts->client->dev; struct input_dev *input; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input_copy_abs(input, ABS_X, ts->input_dev, ABS_MT_POSITION_X); input_copy_abs(input, ABS_Y, ts->input_dev, ABS_MT_POSITION_Y); /* * The resolution of these touchscreens is about 10 units/mm, the actual * resolution does not matter much since we set INPUT_PROP_DIRECT. * Userspace wants something here though, so just set it to 10 units/mm. */ input_abs_set_res(input, ABS_X, 10); input_abs_set_res(input, ABS_Y, 10); input_set_abs_params(input, ABS_PRESSURE, 0, 255, 0, 0); input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_capability(input, EV_KEY, BTN_TOOL_PEN); input_set_capability(input, EV_KEY, BTN_STYLUS); input_set_capability(input, EV_KEY, BTN_STYLUS2); __set_bit(INPUT_PROP_DIRECT, input->propbit); input->name = "Goodix Active Pen"; input->phys = "input/pen"; input->id.bustype = BUS_I2C; input->id.vendor = 0x0416; if (kstrtou16(ts->id, 10, &input->id.product)) input->id.product = 0x1001; input->id.version = ts->version; ts->input_pen = input; return 0; } static void goodix_ts_report_pen_down(struct goodix_ts_data *ts, u8 *data) { int input_x, input_y, input_w, error; u8 key_value; if (!ts->pen_input_registered) { error = input_register_device(ts->input_pen); ts->pen_input_registered = (error == 0) ? 1 : error; } if (ts->pen_input_registered < 0) return; if (ts->contact_size == 9) { input_x = get_unaligned_le16(&data[4]); input_y = get_unaligned_le16(&data[6]); input_w = get_unaligned_le16(&data[8]); } else { input_x = get_unaligned_le16(&data[2]); input_y = get_unaligned_le16(&data[4]); input_w = get_unaligned_le16(&data[6]); } touchscreen_report_pos(ts->input_pen, &ts->prop, input_x, input_y, false); input_report_abs(ts->input_pen, ABS_PRESSURE, input_w); input_report_key(ts->input_pen, BTN_TOUCH, 1); input_report_key(ts->input_pen, BTN_TOOL_PEN, 1); if (data[0] & GOODIX_HAVE_KEY) { key_value = data[1 + ts->contact_size]; input_report_key(ts->input_pen, BTN_STYLUS, key_value & 0x10); input_report_key(ts->input_pen, BTN_STYLUS2, key_value & 0x20); } else { input_report_key(ts->input_pen, BTN_STYLUS, 0); input_report_key(ts->input_pen, BTN_STYLUS2, 0); } input_sync(ts->input_pen); } static void goodix_ts_report_pen_up(struct goodix_ts_data *ts) { if (!ts->input_pen) return; input_report_key(ts->input_pen, BTN_TOUCH, 0); input_report_key(ts->input_pen, BTN_TOOL_PEN, 0); input_report_key(ts->input_pen, BTN_STYLUS, 0); input_report_key(ts->input_pen, BTN_STYLUS2, 0); input_sync(ts->input_pen); } static void goodix_ts_report_touch_8b(struct goodix_ts_data *ts, u8 *coor_data) { int id = coor_data[0] & 0x0F; int input_x = get_unaligned_le16(&coor_data[1]); int input_y = get_unaligned_le16(&coor_data[3]); int input_w = get_unaligned_le16(&coor_data[5]); input_mt_slot(ts->input_dev, id); input_mt_report_slot_state(ts->input_dev, MT_TOOL_FINGER, true); touchscreen_report_pos(ts->input_dev, &ts->prop, input_x, input_y, true); input_report_abs(ts->input_dev, ABS_MT_TOUCH_MAJOR, input_w); input_report_abs(ts->input_dev, ABS_MT_WIDTH_MAJOR, input_w); } static void goodix_ts_report_touch_9b(struct goodix_ts_data *ts, u8 *coor_data) { int id = coor_data[1] & 0x0F; int input_x = get_unaligned_le16(&coor_data[3]); int input_y = get_unaligned_le16(&coor_data[5]); int input_w = get_unaligned_le16(&coor_data[7]); input_mt_slot(ts->input_dev, id); input_mt_report_slot_state(ts->input_dev, MT_TOOL_FINGER, true); touchscreen_report_pos(ts->input_dev, &ts->prop, input_x, input_y, true); input_report_abs(ts->input_dev, ABS_MT_TOUCH_MAJOR, input_w); input_report_abs(ts->input_dev, ABS_MT_WIDTH_MAJOR, input_w); } static void goodix_ts_release_keys(struct goodix_ts_data *ts) { int i; for (i = 0; i < GOODIX_MAX_KEYS; i++) input_report_key(ts->input_dev, ts->keymap[i], 0); } static void goodix_ts_report_key(struct goodix_ts_data *ts, u8 *data) { int touch_num; u8 key_value; int i; if (data[0] & GOODIX_HAVE_KEY) { touch_num = data[0] & 0x0f; key_value = data[1 + ts->contact_size * touch_num]; for (i = 0; i < GOODIX_MAX_KEYS; i++) if (key_value & BIT(i)) input_report_key(ts->input_dev, ts->keymap[i], 1); } else { goodix_ts_release_keys(ts); } } /** * goodix_process_events - Process incoming events * * @ts: our goodix_ts_data pointer * * Called when the IRQ is triggered. Read the current device state, and push * the input events to the user space. */ static void goodix_process_events(struct goodix_ts_data *ts) { u8 point_data[2 + GOODIX_MAX_CONTACT_SIZE * GOODIX_MAX_CONTACTS]; int touch_num; int i; touch_num = goodix_ts_read_input_report(ts, point_data); if (touch_num < 0) return; /* The pen being down is always reported as a single touch */ if (touch_num == 1 && (point_data[1] & 0x80)) { goodix_ts_report_pen_down(ts, point_data); goodix_ts_release_keys(ts); goto sync; /* Release any previously registered touches */ } else { goodix_ts_report_pen_up(ts); } goodix_ts_report_key(ts, point_data); for (i = 0; i < touch_num; i++) if (ts->contact_size == 9) goodix_ts_report_touch_9b(ts, &point_data[1 + ts->contact_size * i]); else goodix_ts_report_touch_8b(ts, &point_data[1 + ts->contact_size * i]); sync: input_mt_sync_frame(ts->input_dev); input_sync(ts->input_dev); } /** * goodix_ts_irq_handler - The IRQ handler * * @irq: interrupt number. * @dev_id: private data pointer. */ static irqreturn_t goodix_ts_irq_handler(int irq, void *dev_id) { struct goodix_ts_data *ts = dev_id; goodix_process_events(ts); goodix_i2c_write_u8(ts->client, GOODIX_READ_COOR_ADDR, 0); return IRQ_HANDLED; } static void goodix_free_irq(struct goodix_ts_data *ts) { devm_free_irq(&ts->client->dev, ts->client->irq, ts); } static int goodix_request_irq(struct goodix_ts_data *ts) { return devm_request_threaded_irq(&ts->client->dev, ts->client->irq, NULL, goodix_ts_irq_handler, ts->irq_flags, ts->client->name, ts); } static int goodix_check_cfg_8(struct goodix_ts_data *ts, const u8 *cfg, int len) { int i, raw_cfg_len = len - 2; u8 check_sum = 0; for (i = 0; i < raw_cfg_len; i++) check_sum += cfg[i]; check_sum = (~check_sum) + 1; if (check_sum != cfg[raw_cfg_len]) { dev_err(&ts->client->dev, "The checksum of the config fw is not correct"); return -EINVAL; } if (cfg[raw_cfg_len + 1] != 1) { dev_err(&ts->client->dev, "Config fw must have Config_Fresh register set"); return -EINVAL; } return 0; } static void goodix_calc_cfg_checksum_8(struct goodix_ts_data *ts) { int i, raw_cfg_len = ts->chip->config_len - 2; u8 check_sum = 0; for (i = 0; i < raw_cfg_len; i++) check_sum += ts->config[i]; check_sum = (~check_sum) + 1; ts->config[raw_cfg_len] = check_sum; ts->config[raw_cfg_len + 1] = 1; /* Set "config_fresh" bit */ } static int goodix_check_cfg_16(struct goodix_ts_data *ts, const u8 *cfg, int len) { int i, raw_cfg_len = len - 3; u16 check_sum = 0; for (i = 0; i < raw_cfg_len; i += 2) check_sum += get_unaligned_be16(&cfg[i]); check_sum = (~check_sum) + 1; if (check_sum != get_unaligned_be16(&cfg[raw_cfg_len])) { dev_err(&ts->client->dev, "The checksum of the config fw is not correct"); return -EINVAL; } if (cfg[raw_cfg_len + 2] != 1) { dev_err(&ts->client->dev, "Config fw must have Config_Fresh register set"); return -EINVAL; } return 0; } static void goodix_calc_cfg_checksum_16(struct goodix_ts_data *ts) { int i, raw_cfg_len = ts->chip->config_len - 3; u16 check_sum = 0; for (i = 0; i < raw_cfg_len; i += 2) check_sum += get_unaligned_be16(&ts->config[i]); check_sum = (~check_sum) + 1; put_unaligned_be16(check_sum, &ts->config[raw_cfg_len]); ts->config[raw_cfg_len + 2] = 1; /* Set "config_fresh" bit */ } /** * goodix_check_cfg - Checks if config fw is valid * * @ts: goodix_ts_data pointer * @cfg: firmware config data * @len: config data length */ static int goodix_check_cfg(struct goodix_ts_data *ts, const u8 *cfg, int len) { if (len < GOODIX_CONFIG_MIN_LENGTH || len > GOODIX_CONFIG_MAX_LENGTH) { dev_err(&ts->client->dev, "The length of the config fw is not correct"); return -EINVAL; } return ts->chip->check_config(ts, cfg, len); } /** * goodix_send_cfg - Write fw config to device * * @ts: goodix_ts_data pointer * @cfg: config firmware to write to device * @len: config data length */ int goodix_send_cfg(struct goodix_ts_data *ts, const u8 *cfg, int len) { int error; error = goodix_check_cfg(ts, cfg, len); if (error) return error; error = goodix_i2c_write(ts->client, ts->chip->config_addr, cfg, len); if (error) return error; dev_dbg(&ts->client->dev, "Config sent successfully."); /* Let the firmware reconfigure itself, so sleep for 10ms */ usleep_range(10000, 11000); return 0; } #ifdef ACPI_GPIO_SUPPORT static int goodix_pin_acpi_direction_input(struct goodix_ts_data *ts) { acpi_handle handle = ACPI_HANDLE(&ts->client->dev); acpi_status status; status = acpi_evaluate_object(handle, "INTI", NULL, NULL); return ACPI_SUCCESS(status) ? 0 : -EIO; } static int goodix_pin_acpi_output_method(struct goodix_ts_data *ts, int value) { acpi_handle handle = ACPI_HANDLE(&ts->client->dev); acpi_status status; status = acpi_execute_simple_method(handle, "INTO", value); return ACPI_SUCCESS(status) ? 0 : -EIO; } #else static int goodix_pin_acpi_direction_input(struct goodix_ts_data *ts) { dev_err(&ts->client->dev, "%s called on device without ACPI support\n", __func__); return -EINVAL; } static int goodix_pin_acpi_output_method(struct goodix_ts_data *ts, int value) { dev_err(&ts->client->dev, "%s called on device without ACPI support\n", __func__); return -EINVAL; } #endif static int goodix_irq_direction_output(struct goodix_ts_data *ts, int value) { switch (ts->irq_pin_access_method) { case IRQ_PIN_ACCESS_NONE: dev_err(&ts->client->dev, "%s called without an irq_pin_access_method set\n", __func__); return -EINVAL; case IRQ_PIN_ACCESS_GPIO: return gpiod_direction_output(ts->gpiod_int, value); case IRQ_PIN_ACCESS_ACPI_GPIO: /* * The IRQ pin triggers on a falling edge, so its gets marked * as active-low, use output_raw to avoid the value inversion. */ return gpiod_direction_output_raw(ts->gpiod_int, value); case IRQ_PIN_ACCESS_ACPI_METHOD: return goodix_pin_acpi_output_method(ts, value); } return -EINVAL; /* Never reached */ } static int goodix_irq_direction_input(struct goodix_ts_data *ts) { switch (ts->irq_pin_access_method) { case IRQ_PIN_ACCESS_NONE: dev_err(&ts->client->dev, "%s called without an irq_pin_access_method set\n", __func__); return -EINVAL; case IRQ_PIN_ACCESS_GPIO: return gpiod_direction_input(ts->gpiod_int); case IRQ_PIN_ACCESS_ACPI_GPIO: return gpiod_direction_input(ts->gpiod_int); case IRQ_PIN_ACCESS_ACPI_METHOD: return goodix_pin_acpi_direction_input(ts); } return -EINVAL; /* Never reached */ } int goodix_int_sync(struct goodix_ts_data *ts) { int error; error = goodix_irq_direction_output(ts, 0); if (error) goto error; msleep(50); /* T5: 50ms */ error = goodix_irq_direction_input(ts); if (error) goto error; return 0; error: dev_err(&ts->client->dev, "Controller irq sync failed.\n"); return error; } /** * goodix_reset_no_int_sync - Reset device, leaving interrupt line in output mode * * @ts: goodix_ts_data pointer */ int goodix_reset_no_int_sync(struct goodix_ts_data *ts) { int error; /* begin select I2C slave addr */ error = gpiod_direction_output(ts->gpiod_rst, 0); if (error) goto error; msleep(20); /* T2: > 10ms */ /* HIGH: 0x28/0x29, LOW: 0xBA/0xBB */ error = goodix_irq_direction_output(ts, ts->client->addr == 0x14); if (error) goto error; usleep_range(100, 2000); /* T3: > 100us */ error = gpiod_direction_output(ts->gpiod_rst, 1); if (error) goto error; usleep_range(6000, 10000); /* T4: > 5ms */ /* * Put the reset pin back in to input / high-impedance mode to save * power. Only do this in the non ACPI case since some ACPI boards * don't have a pull-up, so there the reset pin must stay active-high. */ if (ts->irq_pin_access_method == IRQ_PIN_ACCESS_GPIO) { error = gpiod_direction_input(ts->gpiod_rst); if (error) goto error; } return 0; error: dev_err(&ts->client->dev, "Controller reset failed.\n"); return error; } /** * goodix_reset - Reset device during power on * * @ts: goodix_ts_data pointer */ static int goodix_reset(struct goodix_ts_data *ts) { int error; error = goodix_reset_no_int_sync(ts); if (error) return error; return goodix_int_sync(ts); } #ifdef ACPI_GPIO_SUPPORT static const struct acpi_gpio_params first_gpio = { 0, 0, false }; static const struct acpi_gpio_params second_gpio = { 1, 0, false }; static const struct acpi_gpio_mapping acpi_goodix_int_first_gpios[] = { { GOODIX_GPIO_INT_NAME "-gpios", &first_gpio, 1 }, { GOODIX_GPIO_RST_NAME "-gpios", &second_gpio, 1 }, { }, }; static const struct acpi_gpio_mapping acpi_goodix_int_last_gpios[] = { { GOODIX_GPIO_RST_NAME "-gpios", &first_gpio, 1 }, { GOODIX_GPIO_INT_NAME "-gpios", &second_gpio, 1 }, { }, }; static const struct acpi_gpio_mapping acpi_goodix_reset_only_gpios[] = { { GOODIX_GPIO_RST_NAME "-gpios", &first_gpio, 1 }, { }, }; static int goodix_resource(struct acpi_resource *ares, void *data) { struct goodix_ts_data *ts = data; struct device *dev = &ts->client->dev; struct acpi_resource_gpio *gpio; if (acpi_gpio_get_irq_resource(ares, &gpio)) { if (ts->gpio_int_idx == -1) { ts->gpio_int_idx = ts->gpio_count; } else { dev_err(dev, "More then one GpioInt resource, ignoring ACPI GPIO resources\n"); ts->gpio_int_idx = -2; } ts->gpio_count++; } else if (acpi_gpio_get_io_resource(ares, &gpio)) ts->gpio_count++; return 0; } /* * This function gets called in case we fail to get the irq GPIO directly * because the ACPI tables lack GPIO-name to APCI _CRS index mappings * (no _DSD UUID daffd814-6eba-4d8c-8a91-bc9bbf4aa301 data). * In that case we add our own mapping and then goodix_get_gpio_config() * retries to get the GPIOs based on the added mapping. */ static int goodix_add_acpi_gpio_mappings(struct goodix_ts_data *ts) { const struct acpi_gpio_mapping *gpio_mapping = NULL; struct device *dev = &ts->client->dev; LIST_HEAD(resources); int irq, ret; ts->gpio_count = 0; ts->gpio_int_idx = -1; ret = acpi_dev_get_resources(ACPI_COMPANION(dev), &resources, goodix_resource, ts); if (ret < 0) { dev_err(dev, "Error getting ACPI resources: %d\n", ret); return ret; } acpi_dev_free_resource_list(&resources); /* * CHT devices should have a GpioInt + a regular GPIO ACPI resource. * Some CHT devices have a bug (where the also is bogus Interrupt * resource copied from a previous BYT based generation). i2c-core-acpi * will use the non-working Interrupt resource, fix this up. */ if (soc_intel_is_cht() && ts->gpio_count == 2 && ts->gpio_int_idx != -1) { irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0); if (irq > 0 && irq != ts->client->irq) { dev_warn(dev, "Overriding IRQ %d -> %d\n", ts->client->irq, irq); ts->client->irq = irq; } } if (ts->gpio_count == 2 && ts->gpio_int_idx == 0) { ts->irq_pin_access_method = IRQ_PIN_ACCESS_ACPI_GPIO; gpio_mapping = acpi_goodix_int_first_gpios; } else if (ts->gpio_count == 2 && ts->gpio_int_idx == 1) { ts->irq_pin_access_method = IRQ_PIN_ACCESS_ACPI_GPIO; gpio_mapping = acpi_goodix_int_last_gpios; } else if (ts->gpio_count == 1 && ts->gpio_int_idx == -1 && acpi_has_method(ACPI_HANDLE(dev), "INTI") && acpi_has_method(ACPI_HANDLE(dev), "INTO")) { dev_info(dev, "Using ACPI INTI and INTO methods for IRQ pin access\n"); ts->irq_pin_access_method = IRQ_PIN_ACCESS_ACPI_METHOD; gpio_mapping = acpi_goodix_reset_only_gpios; } else if (soc_intel_is_byt() && ts->gpio_count == 2 && ts->gpio_int_idx == -1) { dev_info(dev, "No ACPI GpioInt resource, assuming that the GPIO order is reset, int\n"); ts->irq_pin_access_method = IRQ_PIN_ACCESS_ACPI_GPIO; gpio_mapping = acpi_goodix_int_last_gpios; } else { dev_warn(dev, "Unexpected ACPI resources: gpio_count %d, gpio_int_idx %d\n", ts->gpio_count, ts->gpio_int_idx); /* * On some devices _PS0 does a reset for us and * sometimes this is necessary for things to work. */ acpi_device_fix_up_power(ACPI_COMPANION(dev)); return -EINVAL; } /* * Normally we put the reset pin in input / high-impedance mode to save * power. But some x86/ACPI boards don't have a pull-up, so for the ACPI * case, leave the pin as is. This results in the pin not being touched * at all on x86/ACPI boards, except when needed for error-recover. */ ts->gpiod_rst_flags = GPIOD_ASIS; return devm_acpi_dev_add_driver_gpios(dev, gpio_mapping); } #else static int goodix_add_acpi_gpio_mappings(struct goodix_ts_data *ts) { return -EINVAL; } #endif /* CONFIG_X86 && CONFIG_ACPI */ /** * goodix_get_gpio_config - Get GPIO config from ACPI/DT * * @ts: goodix_ts_data pointer */ static int goodix_get_gpio_config(struct goodix_ts_data *ts) { struct device *dev; struct gpio_desc *gpiod; bool added_acpi_mappings = false; if (!ts->client) return -EINVAL; dev = &ts->client->dev; /* * By default we request the reset pin as input, leaving it in * high-impedance when not resetting the controller to save power. */ ts->gpiod_rst_flags = GPIOD_IN; ts->avdd28 = devm_regulator_get(dev, "AVDD28"); if (IS_ERR(ts->avdd28)) return dev_err_probe(dev, PTR_ERR(ts->avdd28), "Failed to get AVDD28 regulator\n"); ts->vddio = devm_regulator_get(dev, "VDDIO"); if (IS_ERR(ts->vddio)) return dev_err_probe(dev, PTR_ERR(ts->vddio), "Failed to get VDDIO regulator\n"); retry_get_irq_gpio: /* Get the interrupt GPIO pin number */ gpiod = devm_gpiod_get_optional(dev, GOODIX_GPIO_INT_NAME, GPIOD_IN); if (IS_ERR(gpiod)) return dev_err_probe(dev, PTR_ERR(gpiod), "Failed to get %s GPIO\n", GOODIX_GPIO_INT_NAME); if (!gpiod && has_acpi_companion(dev) && !added_acpi_mappings) { added_acpi_mappings = true; if (goodix_add_acpi_gpio_mappings(ts) == 0) goto retry_get_irq_gpio; } ts->gpiod_int = gpiod; /* Get the reset line GPIO pin number */ gpiod = devm_gpiod_get_optional(dev, GOODIX_GPIO_RST_NAME, ts->gpiod_rst_flags); if (IS_ERR(gpiod)) return dev_err_probe(dev, PTR_ERR(gpiod), "Failed to get %s GPIO\n", GOODIX_GPIO_RST_NAME); ts->gpiod_rst = gpiod; switch (ts->irq_pin_access_method) { case IRQ_PIN_ACCESS_ACPI_GPIO: /* * We end up here if goodix_add_acpi_gpio_mappings() has * called devm_acpi_dev_add_driver_gpios() because the ACPI * tables did not contain name to index mappings. * Check that we successfully got both GPIOs after we've * added our own acpi_gpio_mapping and if we did not get both * GPIOs reset irq_pin_access_method to IRQ_PIN_ACCESS_NONE. */ if (!ts->gpiod_int || !ts->gpiod_rst) ts->irq_pin_access_method = IRQ_PIN_ACCESS_NONE; break; case IRQ_PIN_ACCESS_ACPI_METHOD: if (!ts->gpiod_rst) ts->irq_pin_access_method = IRQ_PIN_ACCESS_NONE; break; default: if (ts->gpiod_int && ts->gpiod_rst) { ts->reset_controller_at_probe = true; ts->load_cfg_from_disk = true; ts->irq_pin_access_method = IRQ_PIN_ACCESS_GPIO; } } return 0; } /** * goodix_read_config - Read the embedded configuration of the panel * * @ts: our goodix_ts_data pointer * * Must be called during probe */ static void goodix_read_config(struct goodix_ts_data *ts) { int x_max, y_max; int error; /* * On controllers where we need to upload the firmware * (controllers without flash) ts->config already has the config * at this point and the controller itself does not have it yet! */ if (!ts->firmware_name) { error = goodix_i2c_read(ts->client, ts->chip->config_addr, ts->config, ts->chip->config_len); if (error) { ts->int_trigger_type = GOODIX_INT_TRIGGER; ts->max_touch_num = GOODIX_MAX_CONTACTS; return; } } ts->int_trigger_type = ts->config[TRIGGER_LOC] & 0x03; ts->max_touch_num = ts->config[MAX_CONTACTS_LOC] & 0x0f; x_max = get_unaligned_le16(&ts->config[RESOLUTION_LOC]); y_max = get_unaligned_le16(&ts->config[RESOLUTION_LOC + 2]); if (x_max && y_max) { input_abs_set_max(ts->input_dev, ABS_MT_POSITION_X, x_max - 1); input_abs_set_max(ts->input_dev, ABS_MT_POSITION_Y, y_max - 1); } ts->chip->calc_config_checksum(ts); } /** * goodix_read_version - Read goodix touchscreen version * * @ts: our goodix_ts_data pointer */ static int goodix_read_version(struct goodix_ts_data *ts) { int error; u8 buf[6]; char id_str[GOODIX_ID_MAX_LEN + 1]; error = goodix_i2c_read(ts->client, GOODIX_REG_ID, buf, sizeof(buf)); if (error) return error; memcpy(id_str, buf, GOODIX_ID_MAX_LEN); id_str[GOODIX_ID_MAX_LEN] = 0; strscpy(ts->id, id_str, GOODIX_ID_MAX_LEN + 1); ts->version = get_unaligned_le16(&buf[4]); dev_info(&ts->client->dev, "ID %s, version: %04x\n", ts->id, ts->version); return 0; } /** * goodix_i2c_test - I2C test function to check if the device answers. * * @client: the i2c client */ static int goodix_i2c_test(struct i2c_client *client) { int retry = 0; int error; u8 test; while (retry++ < 2) { error = goodix_i2c_read(client, GOODIX_REG_ID, &test, 1); if (!error) return 0; msleep(20); } return error; } /** * goodix_configure_dev - Finish device initialization * * @ts: our goodix_ts_data pointer * * Must be called from probe to finish initialization of the device. * Contains the common initialization code for both devices that * declare gpio pins and devices that do not. It is either called * directly from probe or from request_firmware_wait callback. */ static int goodix_configure_dev(struct goodix_ts_data *ts) { int error; int i; ts->int_trigger_type = GOODIX_INT_TRIGGER; ts->max_touch_num = GOODIX_MAX_CONTACTS; ts->input_dev = devm_input_allocate_device(&ts->client->dev); if (!ts->input_dev) { dev_err(&ts->client->dev, "Failed to allocate input device."); return -ENOMEM; } ts->input_dev->name = "Goodix Capacitive TouchScreen"; ts->input_dev->phys = "input/ts"; ts->input_dev->id.bustype = BUS_I2C; ts->input_dev->id.vendor = 0x0416; if (kstrtou16(ts->id, 10, &ts->input_dev->id.product)) ts->input_dev->id.product = 0x1001; ts->input_dev->id.version = ts->version; ts->input_dev->keycode = ts->keymap; ts->input_dev->keycodesize = sizeof(ts->keymap[0]); ts->input_dev->keycodemax = GOODIX_MAX_KEYS; /* Capacitive Windows/Home button on some devices */ for (i = 0; i < GOODIX_MAX_KEYS; ++i) { if (i == 0) ts->keymap[i] = KEY_LEFTMETA; else ts->keymap[i] = KEY_F1 + (i - 1); input_set_capability(ts->input_dev, EV_KEY, ts->keymap[i]); } input_set_capability(ts->input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(ts->input_dev, EV_ABS, ABS_MT_POSITION_Y); input_set_abs_params(ts->input_dev, ABS_MT_WIDTH_MAJOR, 0, 255, 0, 0); input_set_abs_params(ts->input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); retry_read_config: /* Read configuration and apply touchscreen parameters */ goodix_read_config(ts); /* Try overriding touchscreen parameters via device properties */ touchscreen_parse_properties(ts->input_dev, true, &ts->prop); if (!ts->prop.max_x || !ts->prop.max_y || !ts->max_touch_num) { if (!ts->reset_controller_at_probe && ts->irq_pin_access_method != IRQ_PIN_ACCESS_NONE) { dev_info(&ts->client->dev, "Config not set, resetting controller\n"); /* Retry after a controller reset */ ts->reset_controller_at_probe = true; error = goodix_reset(ts); if (error) return error; goto retry_read_config; } dev_err(&ts->client->dev, "Invalid config (%d, %d, %d), using defaults\n", ts->prop.max_x, ts->prop.max_y, ts->max_touch_num); ts->prop.max_x = GOODIX_MAX_WIDTH - 1; ts->prop.max_y = GOODIX_MAX_HEIGHT - 1; ts->max_touch_num = GOODIX_MAX_CONTACTS; input_abs_set_max(ts->input_dev, ABS_MT_POSITION_X, ts->prop.max_x); input_abs_set_max(ts->input_dev, ABS_MT_POSITION_Y, ts->prop.max_y); } if (dmi_check_system(nine_bytes_report)) { ts->contact_size = 9; dev_dbg(&ts->client->dev, "Non-standard 9-bytes report format quirk\n"); } if (dmi_check_system(inverted_x_screen)) { ts->prop.invert_x = true; dev_dbg(&ts->client->dev, "Applying 'inverted x screen' quirk\n"); } error = input_mt_init_slots(ts->input_dev, ts->max_touch_num, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&ts->client->dev, "Failed to initialize MT slots: %d", error); return error; } error = input_register_device(ts->input_dev); if (error) { dev_err(&ts->client->dev, "Failed to register input device: %d", error); return error; } /* * Create the input_pen device before goodix_request_irq() calls * devm_request_threaded_irq() so that the devm framework frees * it after disabling the irq. * Unfortunately there is no way to detect if the touchscreen has pen * support, so registering the dev is delayed till the first pen event. */ error = goodix_create_pen_input(ts); if (error) return error; ts->irq_flags = goodix_irq_flags[ts->int_trigger_type] | IRQF_ONESHOT; error = goodix_request_irq(ts); if (error) { dev_err(&ts->client->dev, "request IRQ failed: %d\n", error); return error; } return 0; } /** * goodix_config_cb - Callback to finish device init * * @cfg: firmware config * @ctx: our goodix_ts_data pointer * * request_firmware_wait callback that finishes * initialization of the device. */ static void goodix_config_cb(const struct firmware *cfg, void *ctx) { struct goodix_ts_data *ts = ctx; int error; if (ts->firmware_name) { if (!cfg) goto err_release_cfg; error = goodix_check_cfg(ts, cfg->data, cfg->size); if (error) goto err_release_cfg; memcpy(ts->config, cfg->data, cfg->size); } else if (cfg) { /* send device configuration to the firmware */ error = goodix_send_cfg(ts, cfg->data, cfg->size); if (error) goto err_release_cfg; } goodix_configure_dev(ts); err_release_cfg: release_firmware(cfg); complete_all(&ts->firmware_loading_complete); } static void goodix_disable_regulators(void *arg) { struct goodix_ts_data *ts = arg; regulator_disable(ts->vddio); regulator_disable(ts->avdd28); } static int goodix_ts_probe(struct i2c_client *client) { struct goodix_ts_data *ts; const char *cfg_name; int error; dev_dbg(&client->dev, "I2C Address: 0x%02x\n", client->addr); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C check functionality failed.\n"); return -ENXIO; } ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; i2c_set_clientdata(client, ts); init_completion(&ts->firmware_loading_complete); ts->contact_size = GOODIX_CONTACT_SIZE; error = goodix_get_gpio_config(ts); if (error) return error; /* power up the controller */ error = regulator_enable(ts->avdd28); if (error) { dev_err(&client->dev, "Failed to enable AVDD28 regulator: %d\n", error); return error; } error = regulator_enable(ts->vddio); if (error) { dev_err(&client->dev, "Failed to enable VDDIO regulator: %d\n", error); regulator_disable(ts->avdd28); return error; } error = devm_add_action_or_reset(&client->dev, goodix_disable_regulators, ts); if (error) return error; reset: if (ts->reset_controller_at_probe) { /* reset the controller */ error = goodix_reset(ts); if (error) return error; } error = goodix_i2c_test(client); if (error) { if (!ts->reset_controller_at_probe && ts->irq_pin_access_method != IRQ_PIN_ACCESS_NONE) { /* Retry after a controller reset */ ts->reset_controller_at_probe = true; goto reset; } dev_err(&client->dev, "I2C communication failure: %d\n", error); return error; } error = goodix_firmware_check(ts); if (error) return error; error = goodix_read_version(ts); if (error) return error; ts->chip = goodix_get_chip_data(ts->id); if (ts->load_cfg_from_disk) { /* update device config */ error = device_property_read_string(&client->dev, "goodix,config-name", &cfg_name); if (!error) snprintf(ts->cfg_name, sizeof(ts->cfg_name), "goodix/%s", cfg_name); else snprintf(ts->cfg_name, sizeof(ts->cfg_name), "goodix_%s_cfg.bin", ts->id); error = request_firmware_nowait(THIS_MODULE, true, ts->cfg_name, &client->dev, GFP_KERNEL, ts, goodix_config_cb); if (error) { dev_err(&client->dev, "Failed to invoke firmware loader: %d\n", error); return error; } return 0; } else { error = goodix_configure_dev(ts); if (error) return error; } return 0; } static void goodix_ts_remove(struct i2c_client *client) { struct goodix_ts_data *ts = i2c_get_clientdata(client); if (ts->load_cfg_from_disk) wait_for_completion(&ts->firmware_loading_complete); } static int goodix_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct goodix_ts_data *ts = i2c_get_clientdata(client); int error; if (ts->load_cfg_from_disk) wait_for_completion(&ts->firmware_loading_complete); /* We need gpio pins to suspend/resume */ if (ts->irq_pin_access_method == IRQ_PIN_ACCESS_NONE) { disable_irq(client->irq); return 0; } /* Free IRQ as IRQ pin is used as output in the suspend sequence */ goodix_free_irq(ts); /* Save reference (calibration) info if necessary */ goodix_save_bak_ref(ts); /* Output LOW on the INT pin for 5 ms */ error = goodix_irq_direction_output(ts, 0); if (error) { goodix_request_irq(ts); return error; } usleep_range(5000, 6000); error = goodix_i2c_write_u8(ts->client, GOODIX_REG_COMMAND, GOODIX_CMD_SCREEN_OFF); if (error) { goodix_irq_direction_input(ts); goodix_request_irq(ts); return -EAGAIN; } /* * The datasheet specifies that the interval between sending screen-off * command and wake-up should be longer than 58 ms. To avoid waking up * sooner, delay 58ms here. */ msleep(58); return 0; } static int goodix_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct goodix_ts_data *ts = i2c_get_clientdata(client); u8 config_ver; int error; if (ts->irq_pin_access_method == IRQ_PIN_ACCESS_NONE) { enable_irq(client->irq); return 0; } /* * Exit sleep mode by outputting HIGH level to INT pin * for 2ms~5ms. */ error = goodix_irq_direction_output(ts, 1); if (error) return error; usleep_range(2000, 5000); error = goodix_int_sync(ts); if (error) return error; error = goodix_i2c_read(ts->client, ts->chip->config_addr, &config_ver, 1); if (!error && config_ver != ts->config[0]) dev_info(dev, "Config version mismatch %d != %d, resetting controller\n", config_ver, ts->config[0]); if (error != 0 || config_ver != ts->config[0]) { error = goodix_reset(ts); if (error) return error; error = goodix_send_cfg(ts, ts->config, ts->chip->config_len); if (error) return error; } error = goodix_request_irq(ts); if (error) return error; return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(goodix_pm_ops, goodix_suspend, goodix_resume); static const struct i2c_device_id goodix_ts_id[] = { { "GDIX1001:00", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, goodix_ts_id); #ifdef CONFIG_ACPI static const struct acpi_device_id goodix_acpi_match[] = { { "GDIX1001", 0 }, { "GDIX1002", 0 }, { "GDX9110", 0 }, { } }; MODULE_DEVICE_TABLE(acpi, goodix_acpi_match); #endif #ifdef CONFIG_OF static const struct of_device_id goodix_of_match[] = { { .compatible = "goodix,gt1151" }, { .compatible = "goodix,gt1158" }, { .compatible = "goodix,gt5663" }, { .compatible = "goodix,gt5688" }, { .compatible = "goodix,gt911" }, { .compatible = "goodix,gt9110" }, { .compatible = "goodix,gt912" }, { .compatible = "goodix,gt9147" }, { .compatible = "goodix,gt917s" }, { .compatible = "goodix,gt927" }, { .compatible = "goodix,gt9271" }, { .compatible = "goodix,gt928" }, { .compatible = "goodix,gt9286" }, { .compatible = "goodix,gt967" }, { } }; MODULE_DEVICE_TABLE(of, goodix_of_match); #endif static struct i2c_driver goodix_ts_driver = { .probe = goodix_ts_probe, .remove = goodix_ts_remove, .id_table = goodix_ts_id, .driver = { .name = "Goodix-TS", .acpi_match_table = ACPI_PTR(goodix_acpi_match), .of_match_table = of_match_ptr(goodix_of_match), .pm = pm_sleep_ptr(&goodix_pm_ops), }, }; module_i2c_driver(goodix_ts_driver); MODULE_AUTHOR("Benjamin Tissoires <[email protected]>"); MODULE_AUTHOR("Bastien Nocera <[email protected]>"); MODULE_DESCRIPTION("Goodix touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/goodix.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Himax hx83112b touchscreens * * Copyright (C) 2022 Job Noorman <[email protected]> * * This code is based on "Himax Android Driver Sample Code for QCT platform": * * Copyright (C) 2017 Himax Corporation. */ #include <linux/delay.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/regmap.h> #define HIMAX_ID_83112B 0x83112b #define HIMAX_MAX_POINTS 10 #define HIMAX_REG_CFG_SET_ADDR 0x00 #define HIMAX_REG_CFG_INIT_READ 0x0c #define HIMAX_REG_CFG_READ_VALUE 0x08 #define HIMAX_REG_READ_EVENT 0x30 #define HIMAX_CFG_PRODUCT_ID 0x900000d0 #define HIMAX_INVALID_COORD 0xffff struct himax_event_point { __be16 x; __be16 y; } __packed; struct himax_event { struct himax_event_point points[HIMAX_MAX_POINTS]; u8 majors[HIMAX_MAX_POINTS]; u8 pad0[2]; u8 num_points; u8 pad1[2]; u8 checksum_fix; } __packed; static_assert(sizeof(struct himax_event) == 56); struct himax_ts_data { struct gpio_desc *gpiod_rst; struct input_dev *input_dev; struct i2c_client *client; struct regmap *regmap; struct touchscreen_properties props; }; static const struct regmap_config himax_regmap_config = { .reg_bits = 8, .val_bits = 32, .val_format_endian = REGMAP_ENDIAN_LITTLE, }; static int himax_read_config(struct himax_ts_data *ts, u32 address, u32 *dst) { int error; error = regmap_write(ts->regmap, HIMAX_REG_CFG_SET_ADDR, address); if (error) return error; error = regmap_write(ts->regmap, HIMAX_REG_CFG_INIT_READ, 0x0); if (error) return error; error = regmap_read(ts->regmap, HIMAX_REG_CFG_READ_VALUE, dst); if (error) return error; return 0; } static void himax_reset(struct himax_ts_data *ts) { gpiod_set_value_cansleep(ts->gpiod_rst, 1); /* Delay copied from downstream driver */ msleep(20); gpiod_set_value_cansleep(ts->gpiod_rst, 0); /* * The downstream driver doesn't contain this delay but is seems safer * to include it. The range is just a guess that seems to work well. */ usleep_range(1000, 1100); } static int himax_read_product_id(struct himax_ts_data *ts, u32 *product_id) { int error; error = himax_read_config(ts, HIMAX_CFG_PRODUCT_ID, product_id); if (error) return error; *product_id >>= 8; return 0; } static int himax_check_product_id(struct himax_ts_data *ts) { int error; u32 product_id; error = himax_read_product_id(ts, &product_id); if (error) return error; dev_dbg(&ts->client->dev, "Product id: %x\n", product_id); switch (product_id) { case HIMAX_ID_83112B: return 0; default: dev_err(&ts->client->dev, "Unknown product id: %x\n", product_id); return -EINVAL; } } static int himax_input_register(struct himax_ts_data *ts) { int error; ts->input_dev = devm_input_allocate_device(&ts->client->dev); if (!ts->input_dev) { dev_err(&ts->client->dev, "Failed to allocate input device\n"); return -ENOMEM; } ts->input_dev->name = "Himax Touchscreen"; input_set_capability(ts->input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(ts->input_dev, EV_ABS, ABS_MT_POSITION_Y); input_set_abs_params(ts->input_dev, ABS_MT_WIDTH_MAJOR, 0, 200, 0, 0); input_set_abs_params(ts->input_dev, ABS_MT_TOUCH_MAJOR, 0, 200, 0, 0); touchscreen_parse_properties(ts->input_dev, true, &ts->props); error = input_mt_init_slots(ts->input_dev, HIMAX_MAX_POINTS, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&ts->client->dev, "Failed to initialize MT slots: %d\n", error); return error; } error = input_register_device(ts->input_dev); if (error) { dev_err(&ts->client->dev, "Failed to register input device: %d\n", error); return error; } return 0; } static u8 himax_event_get_num_points(const struct himax_event *event) { if (event->num_points == 0xff) return 0; else return event->num_points & 0x0f; } static bool himax_process_event_point(struct himax_ts_data *ts, const struct himax_event *event, int point_index) { const struct himax_event_point *point = &event->points[point_index]; u16 x = be16_to_cpu(point->x); u16 y = be16_to_cpu(point->y); u8 w = event->majors[point_index]; if (x == HIMAX_INVALID_COORD || y == HIMAX_INVALID_COORD) return false; input_mt_slot(ts->input_dev, point_index); input_mt_report_slot_state(ts->input_dev, MT_TOOL_FINGER, true); touchscreen_report_pos(ts->input_dev, &ts->props, x, y, true); input_report_abs(ts->input_dev, ABS_MT_TOUCH_MAJOR, w); input_report_abs(ts->input_dev, ABS_MT_WIDTH_MAJOR, w); return true; } static void himax_process_event(struct himax_ts_data *ts, const struct himax_event *event) { int i; int num_points_left = himax_event_get_num_points(event); for (i = 0; i < HIMAX_MAX_POINTS && num_points_left > 0; i++) { if (himax_process_event_point(ts, event, i)) num_points_left--; } input_mt_sync_frame(ts->input_dev); input_sync(ts->input_dev); } static bool himax_verify_checksum(struct himax_ts_data *ts, const struct himax_event *event) { u8 *data = (u8 *)event; int i; u16 checksum = 0; for (i = 0; i < sizeof(*event); i++) checksum += data[i]; if ((checksum & 0x00ff) != 0) { dev_err(&ts->client->dev, "Wrong event checksum: %04x\n", checksum); return false; } return true; } static int himax_handle_input(struct himax_ts_data *ts) { int error; struct himax_event event; error = regmap_raw_read(ts->regmap, HIMAX_REG_READ_EVENT, &event, sizeof(event)); if (error) { dev_err(&ts->client->dev, "Failed to read input event: %d\n", error); return error; } /* * Only process the current event when it has a valid checksum but * don't consider it a fatal error when it doesn't. */ if (himax_verify_checksum(ts, &event)) himax_process_event(ts, &event); return 0; } static irqreturn_t himax_irq_handler(int irq, void *dev_id) { int error; struct himax_ts_data *ts = dev_id; error = himax_handle_input(ts); if (error) return IRQ_NONE; return IRQ_HANDLED; } static int himax_probe(struct i2c_client *client) { int error; struct device *dev = &client->dev; struct himax_ts_data *ts; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(dev, "I2C check functionality failed\n"); return -ENXIO; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; i2c_set_clientdata(client, ts); ts->client = client; ts->regmap = devm_regmap_init_i2c(client, &himax_regmap_config); error = PTR_ERR_OR_ZERO(ts->regmap); if (error) { dev_err(dev, "Failed to initialize regmap: %d\n", error); return error; } ts->gpiod_rst = devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH); error = PTR_ERR_OR_ZERO(ts->gpiod_rst); if (error) { dev_err(dev, "Failed to get reset GPIO: %d\n", error); return error; } himax_reset(ts); error = himax_check_product_id(ts); if (error) return error; error = himax_input_register(ts); if (error) return error; error = devm_request_threaded_irq(dev, client->irq, NULL, himax_irq_handler, IRQF_ONESHOT, client->name, ts); if (error) return error; return 0; } static int himax_suspend(struct device *dev) { struct himax_ts_data *ts = dev_get_drvdata(dev); disable_irq(ts->client->irq); return 0; } static int himax_resume(struct device *dev) { struct himax_ts_data *ts = dev_get_drvdata(dev); enable_irq(ts->client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(himax_pm_ops, himax_suspend, himax_resume); static const struct i2c_device_id himax_ts_id[] = { { "hx83112b", 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, himax_ts_id); #ifdef CONFIG_OF static const struct of_device_id himax_of_match[] = { { .compatible = "himax,hx83112b" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, himax_of_match); #endif static struct i2c_driver himax_ts_driver = { .probe = himax_probe, .id_table = himax_ts_id, .driver = { .name = "Himax-hx83112b-TS", .of_match_table = of_match_ptr(himax_of_match), .pm = pm_sleep_ptr(&himax_pm_ops), }, }; module_i2c_driver(himax_ts_driver); MODULE_AUTHOR("Job Noorman <[email protected]>"); MODULE_DESCRIPTION("Himax hx83112b touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/himax_hx83112b.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AD7879/AD7889 based touchscreen and GPIO driver * * Copyright (C) 2008-2010 Michael Hennerich, Analog Devices Inc. * * History: * Copyright (c) 2005 David Brownell * Copyright (c) 2006 Nokia Corporation * Various changes: Imre Deak <[email protected]> * * Using code from: * - corgi_ts.c * Copyright (C) 2004-2005 Richard Purdie * - omap_ts.[hc], ads7846.h, ts_osk.c * Copyright (C) 2002 MontaVista Software * Copyright (C) 2004 Texas Instruments * Copyright (C) 2005 Dirk Behme * - ad7877.c * Copyright (C) 2006-2008 Analog Devices Inc. */ #include <linux/device.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/property.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/gpio/driver.h> #include <linux/input/touchscreen.h> #include <linux/module.h> #include "ad7879.h" #define AD7879_REG_ZEROS 0 #define AD7879_REG_CTRL1 1 #define AD7879_REG_CTRL2 2 #define AD7879_REG_CTRL3 3 #define AD7879_REG_AUX1HIGH 4 #define AD7879_REG_AUX1LOW 5 #define AD7879_REG_TEMP1HIGH 6 #define AD7879_REG_TEMP1LOW 7 #define AD7879_REG_XPLUS 8 #define AD7879_REG_YPLUS 9 #define AD7879_REG_Z1 10 #define AD7879_REG_Z2 11 #define AD7879_REG_AUXVBAT 12 #define AD7879_REG_TEMP 13 #define AD7879_REG_REVID 14 /* Control REG 1 */ #define AD7879_TMR(x) ((x & 0xFF) << 0) #define AD7879_ACQ(x) ((x & 0x3) << 8) #define AD7879_MODE_NOC (0 << 10) /* Do not convert */ #define AD7879_MODE_SCC (1 << 10) /* Single channel conversion */ #define AD7879_MODE_SEQ0 (2 << 10) /* Sequence 0 in Slave Mode */ #define AD7879_MODE_SEQ1 (3 << 10) /* Sequence 1 in Master Mode */ #define AD7879_MODE_INT (1 << 15) /* PENIRQ disabled INT enabled */ /* Control REG 2 */ #define AD7879_FCD(x) ((x & 0x3) << 0) #define AD7879_RESET (1 << 4) #define AD7879_MFS(x) ((x & 0x3) << 5) #define AD7879_AVG(x) ((x & 0x3) << 7) #define AD7879_SER (1 << 9) /* non-differential */ #define AD7879_DFR (0 << 9) /* differential */ #define AD7879_GPIOPOL (1 << 10) #define AD7879_GPIODIR (1 << 11) #define AD7879_GPIO_DATA (1 << 12) #define AD7879_GPIO_EN (1 << 13) #define AD7879_PM(x) ((x & 0x3) << 14) #define AD7879_PM_SHUTDOWN (0) #define AD7879_PM_DYN (1) #define AD7879_PM_FULLON (2) /* Control REG 3 */ #define AD7879_TEMPMASK_BIT (1<<15) #define AD7879_AUXVBATMASK_BIT (1<<14) #define AD7879_INTMODE_BIT (1<<13) #define AD7879_GPIOALERTMASK_BIT (1<<12) #define AD7879_AUXLOW_BIT (1<<11) #define AD7879_AUXHIGH_BIT (1<<10) #define AD7879_TEMPLOW_BIT (1<<9) #define AD7879_TEMPHIGH_BIT (1<<8) #define AD7879_YPLUS_BIT (1<<7) #define AD7879_XPLUS_BIT (1<<6) #define AD7879_Z1_BIT (1<<5) #define AD7879_Z2_BIT (1<<4) #define AD7879_AUX_BIT (1<<3) #define AD7879_VBAT_BIT (1<<2) #define AD7879_TEMP_BIT (1<<1) enum { AD7879_SEQ_YPOS = 0, AD7879_SEQ_XPOS = 1, AD7879_SEQ_Z1 = 2, AD7879_SEQ_Z2 = 3, AD7879_NR_SENSE = 4, }; #define MAX_12BIT ((1<<12)-1) #define TS_PEN_UP_TIMEOUT msecs_to_jiffies(50) struct ad7879 { struct regmap *regmap; struct device *dev; struct input_dev *input; struct timer_list timer; #ifdef CONFIG_GPIOLIB struct gpio_chip gc; struct mutex mutex; #endif unsigned int irq; bool disabled; /* P: input->mutex */ bool suspended; /* P: input->mutex */ bool swap_xy; u16 conversion_data[AD7879_NR_SENSE]; char phys[32]; u8 first_conversion_delay; u8 acquisition_time; u8 averaging; u8 pen_down_acc_interval; u8 median; u16 x_plate_ohms; u16 cmd_crtl1; u16 cmd_crtl2; u16 cmd_crtl3; int x; int y; int Rt; }; static int ad7879_read(struct ad7879 *ts, u8 reg) { unsigned int val; int error; error = regmap_read(ts->regmap, reg, &val); if (error) { dev_err(ts->dev, "failed to read register %#02x: %d\n", reg, error); return error; } return val; } static int ad7879_write(struct ad7879 *ts, u8 reg, u16 val) { int error; error = regmap_write(ts->regmap, reg, val); if (error) { dev_err(ts->dev, "failed to write %#04x to register %#02x: %d\n", val, reg, error); return error; } return 0; } static int ad7879_report(struct ad7879 *ts) { struct input_dev *input_dev = ts->input; unsigned Rt; u16 x, y, z1, z2; x = ts->conversion_data[AD7879_SEQ_XPOS] & MAX_12BIT; y = ts->conversion_data[AD7879_SEQ_YPOS] & MAX_12BIT; z1 = ts->conversion_data[AD7879_SEQ_Z1] & MAX_12BIT; z2 = ts->conversion_data[AD7879_SEQ_Z2] & MAX_12BIT; if (ts->swap_xy) swap(x, y); /* * The samples processed here are already preprocessed by the AD7879. * The preprocessing function consists of a median and an averaging * filter. The combination of these two techniques provides a robust * solution, discarding the spurious noise in the signal and keeping * only the data of interest. The size of both filters is * programmable. (dev.platform_data, see linux/platform_data/ad7879.h) * Other user-programmable conversion controls include variable * acquisition time, and first conversion delay. Up to 16 averages can * be taken per conversion. */ if (likely(x && z1)) { /* compute touch pressure resistance using equation #1 */ Rt = (z2 - z1) * x * ts->x_plate_ohms; Rt /= z1; Rt = (Rt + 2047) >> 12; /* * Sample found inconsistent, pressure is beyond * the maximum. Don't report it to user space. */ if (Rt > input_abs_get_max(input_dev, ABS_PRESSURE)) return -EINVAL; /* * Note that we delay reporting events by one sample. * This is done to avoid reporting last sample of the * touch sequence, which may be incomplete if finger * leaves the surface before last reading is taken. */ if (timer_pending(&ts->timer)) { /* Touch continues */ input_report_key(input_dev, BTN_TOUCH, 1); input_report_abs(input_dev, ABS_X, ts->x); input_report_abs(input_dev, ABS_Y, ts->y); input_report_abs(input_dev, ABS_PRESSURE, ts->Rt); input_sync(input_dev); } ts->x = x; ts->y = y; ts->Rt = Rt; return 0; } return -EINVAL; } static void ad7879_ts_event_release(struct ad7879 *ts) { struct input_dev *input_dev = ts->input; input_report_abs(input_dev, ABS_PRESSURE, 0); input_report_key(input_dev, BTN_TOUCH, 0); input_sync(input_dev); } static void ad7879_timer(struct timer_list *t) { struct ad7879 *ts = from_timer(ts, t, timer); ad7879_ts_event_release(ts); } static irqreturn_t ad7879_irq(int irq, void *handle) { struct ad7879 *ts = handle; int error; error = regmap_bulk_read(ts->regmap, AD7879_REG_XPLUS, ts->conversion_data, AD7879_NR_SENSE); if (error) dev_err_ratelimited(ts->dev, "failed to read %#02x: %d\n", AD7879_REG_XPLUS, error); else if (!ad7879_report(ts)) mod_timer(&ts->timer, jiffies + TS_PEN_UP_TIMEOUT); return IRQ_HANDLED; } static void __ad7879_enable(struct ad7879 *ts) { ad7879_write(ts, AD7879_REG_CTRL2, ts->cmd_crtl2); ad7879_write(ts, AD7879_REG_CTRL3, ts->cmd_crtl3); ad7879_write(ts, AD7879_REG_CTRL1, ts->cmd_crtl1); enable_irq(ts->irq); } static void __ad7879_disable(struct ad7879 *ts) { u16 reg = (ts->cmd_crtl2 & ~AD7879_PM(-1)) | AD7879_PM(AD7879_PM_SHUTDOWN); disable_irq(ts->irq); if (del_timer_sync(&ts->timer)) ad7879_ts_event_release(ts); ad7879_write(ts, AD7879_REG_CTRL2, reg); } static int ad7879_open(struct input_dev *input) { struct ad7879 *ts = input_get_drvdata(input); /* protected by input->mutex */ if (!ts->disabled && !ts->suspended) __ad7879_enable(ts); return 0; } static void ad7879_close(struct input_dev *input) { struct ad7879 *ts = input_get_drvdata(input); /* protected by input->mutex */ if (!ts->disabled && !ts->suspended) __ad7879_disable(ts); } static int __maybe_unused ad7879_suspend(struct device *dev) { struct ad7879 *ts = dev_get_drvdata(dev); mutex_lock(&ts->input->mutex); if (!ts->suspended && !ts->disabled && input_device_enabled(ts->input)) __ad7879_disable(ts); ts->suspended = true; mutex_unlock(&ts->input->mutex); return 0; } static int __maybe_unused ad7879_resume(struct device *dev) { struct ad7879 *ts = dev_get_drvdata(dev); mutex_lock(&ts->input->mutex); if (ts->suspended && !ts->disabled && input_device_enabled(ts->input)) __ad7879_enable(ts); ts->suspended = false; mutex_unlock(&ts->input->mutex); return 0; } SIMPLE_DEV_PM_OPS(ad7879_pm_ops, ad7879_suspend, ad7879_resume); EXPORT_SYMBOL(ad7879_pm_ops); static void ad7879_toggle(struct ad7879 *ts, bool disable) { mutex_lock(&ts->input->mutex); if (!ts->suspended && input_device_enabled(ts->input)) { if (disable) { if (ts->disabled) __ad7879_enable(ts); } else { if (!ts->disabled) __ad7879_disable(ts); } } ts->disabled = disable; mutex_unlock(&ts->input->mutex); } static ssize_t ad7879_disable_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ad7879 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->disabled); } static ssize_t ad7879_disable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ad7879 *ts = dev_get_drvdata(dev); unsigned int val; int error; error = kstrtouint(buf, 10, &val); if (error) return error; ad7879_toggle(ts, val); return count; } static DEVICE_ATTR(disable, 0664, ad7879_disable_show, ad7879_disable_store); static struct attribute *ad7879_attributes[] = { &dev_attr_disable.attr, NULL }; static const struct attribute_group ad7879_attr_group = { .attrs = ad7879_attributes, }; #ifdef CONFIG_GPIOLIB static int ad7879_gpio_direction_input(struct gpio_chip *chip, unsigned gpio) { struct ad7879 *ts = gpiochip_get_data(chip); int err; mutex_lock(&ts->mutex); ts->cmd_crtl2 |= AD7879_GPIO_EN | AD7879_GPIODIR | AD7879_GPIOPOL; err = ad7879_write(ts, AD7879_REG_CTRL2, ts->cmd_crtl2); mutex_unlock(&ts->mutex); return err; } static int ad7879_gpio_direction_output(struct gpio_chip *chip, unsigned gpio, int level) { struct ad7879 *ts = gpiochip_get_data(chip); int err; mutex_lock(&ts->mutex); ts->cmd_crtl2 &= ~AD7879_GPIODIR; ts->cmd_crtl2 |= AD7879_GPIO_EN | AD7879_GPIOPOL; if (level) ts->cmd_crtl2 |= AD7879_GPIO_DATA; else ts->cmd_crtl2 &= ~AD7879_GPIO_DATA; err = ad7879_write(ts, AD7879_REG_CTRL2, ts->cmd_crtl2); mutex_unlock(&ts->mutex); return err; } static int ad7879_gpio_get_value(struct gpio_chip *chip, unsigned gpio) { struct ad7879 *ts = gpiochip_get_data(chip); u16 val; mutex_lock(&ts->mutex); val = ad7879_read(ts, AD7879_REG_CTRL2); mutex_unlock(&ts->mutex); return !!(val & AD7879_GPIO_DATA); } static void ad7879_gpio_set_value(struct gpio_chip *chip, unsigned gpio, int value) { struct ad7879 *ts = gpiochip_get_data(chip); mutex_lock(&ts->mutex); if (value) ts->cmd_crtl2 |= AD7879_GPIO_DATA; else ts->cmd_crtl2 &= ~AD7879_GPIO_DATA; ad7879_write(ts, AD7879_REG_CTRL2, ts->cmd_crtl2); mutex_unlock(&ts->mutex); } static int ad7879_gpio_add(struct ad7879 *ts) { int ret = 0; mutex_init(&ts->mutex); /* Do not create a chip unless flagged for it */ if (!device_property_read_bool(ts->dev, "gpio-controller")) return 0; ts->gc.direction_input = ad7879_gpio_direction_input; ts->gc.direction_output = ad7879_gpio_direction_output; ts->gc.get = ad7879_gpio_get_value; ts->gc.set = ad7879_gpio_set_value; ts->gc.can_sleep = 1; ts->gc.base = -1; ts->gc.ngpio = 1; ts->gc.label = "AD7879-GPIO"; ts->gc.owner = THIS_MODULE; ts->gc.parent = ts->dev; ret = devm_gpiochip_add_data(ts->dev, &ts->gc, ts); if (ret) dev_err(ts->dev, "failed to register gpio %d\n", ts->gc.base); return ret; } #else static int ad7879_gpio_add(struct ad7879 *ts) { return 0; } #endif static int ad7879_parse_dt(struct device *dev, struct ad7879 *ts) { int err; u32 tmp; err = device_property_read_u32(dev, "adi,resistance-plate-x", &tmp); if (err) { dev_err(dev, "failed to get resistance-plate-x property\n"); return err; } ts->x_plate_ohms = (u16)tmp; device_property_read_u8(dev, "adi,first-conversion-delay", &ts->first_conversion_delay); device_property_read_u8(dev, "adi,acquisition-time", &ts->acquisition_time); device_property_read_u8(dev, "adi,median-filter-size", &ts->median); device_property_read_u8(dev, "adi,averaging", &ts->averaging); device_property_read_u8(dev, "adi,conversion-interval", &ts->pen_down_acc_interval); ts->swap_xy = device_property_read_bool(dev, "touchscreen-swapped-x-y"); return 0; } int ad7879_probe(struct device *dev, struct regmap *regmap, int irq, u16 bustype, u8 devid) { struct ad7879 *ts; struct input_dev *input_dev; int err; u16 revid; if (irq <= 0) { dev_err(dev, "No IRQ specified\n"); return -EINVAL; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; err = ad7879_parse_dt(dev, ts); if (err) return err; input_dev = devm_input_allocate_device(dev); if (!input_dev) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } ts->dev = dev; ts->input = input_dev; ts->irq = irq; ts->regmap = regmap; timer_setup(&ts->timer, ad7879_timer, 0); snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(dev)); input_dev->name = "AD7879 Touchscreen"; input_dev->phys = ts->phys; input_dev->dev.parent = dev; input_dev->id.bustype = bustype; input_dev->open = ad7879_open; input_dev->close = ad7879_close; input_set_drvdata(input_dev, ts); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, 0, 0); input_set_capability(input_dev, EV_ABS, ABS_PRESSURE); touchscreen_parse_properties(input_dev, false, NULL); if (!input_abs_get_max(input_dev, ABS_PRESSURE)) { dev_err(dev, "Touchscreen pressure is not specified\n"); return -EINVAL; } err = ad7879_write(ts, AD7879_REG_CTRL2, AD7879_RESET); if (err < 0) { dev_err(dev, "Failed to write %s\n", input_dev->name); return err; } revid = ad7879_read(ts, AD7879_REG_REVID); input_dev->id.product = (revid & 0xff); input_dev->id.version = revid >> 8; if (input_dev->id.product != devid) { dev_err(dev, "Failed to probe %s (%x vs %x)\n", input_dev->name, devid, revid); return -ENODEV; } ts->cmd_crtl3 = AD7879_YPLUS_BIT | AD7879_XPLUS_BIT | AD7879_Z2_BIT | AD7879_Z1_BIT | AD7879_TEMPMASK_BIT | AD7879_AUXVBATMASK_BIT | AD7879_GPIOALERTMASK_BIT; ts->cmd_crtl2 = AD7879_PM(AD7879_PM_DYN) | AD7879_DFR | AD7879_AVG(ts->averaging) | AD7879_MFS(ts->median) | AD7879_FCD(ts->first_conversion_delay); ts->cmd_crtl1 = AD7879_MODE_INT | AD7879_MODE_SEQ1 | AD7879_ACQ(ts->acquisition_time) | AD7879_TMR(ts->pen_down_acc_interval); err = devm_request_threaded_irq(dev, ts->irq, NULL, ad7879_irq, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, dev_name(dev), ts); if (err) { dev_err(dev, "Failed to request IRQ: %d\n", err); return err; } __ad7879_disable(ts); err = devm_device_add_group(dev, &ad7879_attr_group); if (err) return err; err = ad7879_gpio_add(ts); if (err) return err; err = input_register_device(input_dev); if (err) return err; dev_set_drvdata(dev, ts); return 0; } EXPORT_SYMBOL(ad7879_probe); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("AD7879(-1) touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ad7879.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for cypress touch screen controller * * Copyright (c) 2009 Aava Mobile * * Some cleanups by Alan Cox <[email protected]> */ #include <linux/i2c.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/gpio/consumer.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <asm/byteorder.h> #define CY8CTMG110_DRIVER_NAME "cy8ctmg110" /* Touch coordinates */ #define CY8CTMG110_X_MIN 0 #define CY8CTMG110_Y_MIN 0 #define CY8CTMG110_X_MAX 759 #define CY8CTMG110_Y_MAX 465 /* cy8ctmg110 register definitions */ #define CY8CTMG110_TOUCH_WAKEUP_TIME 0 #define CY8CTMG110_TOUCH_SLEEP_TIME 2 #define CY8CTMG110_TOUCH_X1 3 #define CY8CTMG110_TOUCH_Y1 5 #define CY8CTMG110_TOUCH_X2 7 #define CY8CTMG110_TOUCH_Y2 9 #define CY8CTMG110_FINGERS 11 #define CY8CTMG110_GESTURE 12 #define CY8CTMG110_REG_MAX 13 /* * The touch driver structure. */ struct cy8ctmg110 { struct input_dev *input; char phys[32]; struct i2c_client *client; struct gpio_desc *reset_gpio; }; /* * cy8ctmg110_power is the routine that is called when touch hardware * is being powered off or on. When powering on this routine de-asserts * the RESET line, when powering off reset line is asserted. */ static void cy8ctmg110_power(struct cy8ctmg110 *ts, bool poweron) { if (ts->reset_gpio) gpiod_set_value_cansleep(ts->reset_gpio, !poweron); } static int cy8ctmg110_write_regs(struct cy8ctmg110 *tsc, unsigned char reg, unsigned char len, unsigned char *value) { struct i2c_client *client = tsc->client; int ret; unsigned char i2c_data[6]; BUG_ON(len > 5); i2c_data[0] = reg; memcpy(i2c_data + 1, value, len); ret = i2c_master_send(client, i2c_data, len + 1); if (ret != len + 1) { dev_err(&client->dev, "i2c write data cmd failed\n"); return ret < 0 ? ret : -EIO; } return 0; } static int cy8ctmg110_read_regs(struct cy8ctmg110 *tsc, unsigned char *data, unsigned char len, unsigned char cmd) { struct i2c_client *client = tsc->client; int ret; struct i2c_msg msg[2] = { /* first write slave position to i2c devices */ { .addr = client->addr, .len = 1, .buf = &cmd }, /* Second read data from position */ { .addr = client->addr, .flags = I2C_M_RD, .len = len, .buf = data } }; ret = i2c_transfer(client->adapter, msg, 2); if (ret < 0) return ret; return 0; } static int cy8ctmg110_touch_pos(struct cy8ctmg110 *tsc) { struct input_dev *input = tsc->input; unsigned char reg_p[CY8CTMG110_REG_MAX]; memset(reg_p, 0, CY8CTMG110_REG_MAX); /* Reading coordinates */ if (cy8ctmg110_read_regs(tsc, reg_p, 9, CY8CTMG110_TOUCH_X1) != 0) return -EIO; /* Number of touch */ if (reg_p[8] == 0) { input_report_key(input, BTN_TOUCH, 0); } else { input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, be16_to_cpup((__be16 *)(reg_p + 0))); input_report_abs(input, ABS_Y, be16_to_cpup((__be16 *)(reg_p + 2))); } input_sync(input); return 0; } static int cy8ctmg110_set_sleepmode(struct cy8ctmg110 *ts, bool sleep) { unsigned char reg_p[3]; if (sleep) { reg_p[0] = 0x00; reg_p[1] = 0xff; reg_p[2] = 5; } else { reg_p[0] = 0x10; reg_p[1] = 0xff; reg_p[2] = 0; } return cy8ctmg110_write_regs(ts, CY8CTMG110_TOUCH_WAKEUP_TIME, 3, reg_p); } static irqreturn_t cy8ctmg110_irq_thread(int irq, void *dev_id) { struct cy8ctmg110 *tsc = dev_id; cy8ctmg110_touch_pos(tsc); return IRQ_HANDLED; } static void cy8ctmg110_shut_off(void *_ts) { struct cy8ctmg110 *ts = _ts; cy8ctmg110_set_sleepmode(ts, true); cy8ctmg110_power(ts, false); } static int cy8ctmg110_probe(struct i2c_client *client) { struct cy8ctmg110 *ts; struct input_dev *input_dev; int err; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) return -EIO; ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) return -ENOMEM; ts->client = client; ts->input = input_dev; snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); input_dev->name = CY8CTMG110_DRIVER_NAME " Touchscreen"; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_I2C; input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, CY8CTMG110_X_MIN, CY8CTMG110_X_MAX, 4, 0); input_set_abs_params(input_dev, ABS_Y, CY8CTMG110_Y_MIN, CY8CTMG110_Y_MAX, 4, 0); /* Request and assert reset line */ ts->reset_gpio = devm_gpiod_get_optional(&client->dev, NULL, GPIOD_OUT_HIGH); if (IS_ERR(ts->reset_gpio)) { err = PTR_ERR(ts->reset_gpio); dev_err(&client->dev, "Unable to request reset GPIO: %d\n", err); return err; } cy8ctmg110_power(ts, true); cy8ctmg110_set_sleepmode(ts, false); err = devm_add_action_or_reset(&client->dev, cy8ctmg110_shut_off, ts); if (err) return err; err = devm_request_threaded_irq(&client->dev, client->irq, NULL, cy8ctmg110_irq_thread, IRQF_ONESHOT, "touch_reset_key", ts); if (err) { dev_err(&client->dev, "irq %d busy? error %d\n", client->irq, err); return err; } err = input_register_device(input_dev); if (err) return err; i2c_set_clientdata(client, ts); return 0; } static int cy8ctmg110_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct cy8ctmg110 *ts = i2c_get_clientdata(client); if (!device_may_wakeup(&client->dev)) { cy8ctmg110_set_sleepmode(ts, true); cy8ctmg110_power(ts, false); } return 0; } static int cy8ctmg110_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct cy8ctmg110 *ts = i2c_get_clientdata(client); if (!device_may_wakeup(&client->dev)) { cy8ctmg110_power(ts, true); cy8ctmg110_set_sleepmode(ts, false); } return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(cy8ctmg110_pm, cy8ctmg110_suspend, cy8ctmg110_resume); static const struct i2c_device_id cy8ctmg110_idtable[] = { { CY8CTMG110_DRIVER_NAME, 1 }, { } }; MODULE_DEVICE_TABLE(i2c, cy8ctmg110_idtable); static struct i2c_driver cy8ctmg110_driver = { .driver = { .name = CY8CTMG110_DRIVER_NAME, .pm = pm_sleep_ptr(&cy8ctmg110_pm), }, .id_table = cy8ctmg110_idtable, .probe = cy8ctmg110_probe, }; module_i2c_driver(cy8ctmg110_driver); MODULE_AUTHOR("Samuli Konttila <[email protected]>"); MODULE_DESCRIPTION("cy8ctmg110 TouchScreen Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/cy8ctmg110_ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * LPC32xx built-in touchscreen driver * * Copyright (C) 2010 NXP Semiconductors */ #include <linux/platform_device.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/of.h> /* * Touchscreen controller register offsets */ #define LPC32XX_TSC_STAT 0x00 #define LPC32XX_TSC_SEL 0x04 #define LPC32XX_TSC_CON 0x08 #define LPC32XX_TSC_FIFO 0x0C #define LPC32XX_TSC_DTR 0x10 #define LPC32XX_TSC_RTR 0x14 #define LPC32XX_TSC_UTR 0x18 #define LPC32XX_TSC_TTR 0x1C #define LPC32XX_TSC_DXP 0x20 #define LPC32XX_TSC_MIN_X 0x24 #define LPC32XX_TSC_MAX_X 0x28 #define LPC32XX_TSC_MIN_Y 0x2C #define LPC32XX_TSC_MAX_Y 0x30 #define LPC32XX_TSC_AUX_UTR 0x34 #define LPC32XX_TSC_AUX_MIN 0x38 #define LPC32XX_TSC_AUX_MAX 0x3C #define LPC32XX_TSC_STAT_FIFO_OVRRN BIT(8) #define LPC32XX_TSC_STAT_FIFO_EMPTY BIT(7) #define LPC32XX_TSC_SEL_DEFVAL 0x0284 #define LPC32XX_TSC_ADCCON_IRQ_TO_FIFO_4 (0x1 << 11) #define LPC32XX_TSC_ADCCON_X_SAMPLE_SIZE(s) ((10 - (s)) << 7) #define LPC32XX_TSC_ADCCON_Y_SAMPLE_SIZE(s) ((10 - (s)) << 4) #define LPC32XX_TSC_ADCCON_POWER_UP BIT(2) #define LPC32XX_TSC_ADCCON_AUTO_EN BIT(0) #define LPC32XX_TSC_FIFO_TS_P_LEVEL BIT(31) #define LPC32XX_TSC_FIFO_NORMALIZE_X_VAL(x) (((x) & 0x03FF0000) >> 16) #define LPC32XX_TSC_FIFO_NORMALIZE_Y_VAL(y) ((y) & 0x000003FF) #define LPC32XX_TSC_ADCDAT_VALUE_MASK 0x000003FF #define LPC32XX_TSC_MIN_XY_VAL 0x0 #define LPC32XX_TSC_MAX_XY_VAL 0x3FF #define MOD_NAME "ts-lpc32xx" #define tsc_readl(dev, reg) \ __raw_readl((dev)->tsc_base + (reg)) #define tsc_writel(dev, reg, val) \ __raw_writel((val), (dev)->tsc_base + (reg)) struct lpc32xx_tsc { struct input_dev *dev; void __iomem *tsc_base; int irq; struct clk *clk; }; static void lpc32xx_fifo_clear(struct lpc32xx_tsc *tsc) { while (!(tsc_readl(tsc, LPC32XX_TSC_STAT) & LPC32XX_TSC_STAT_FIFO_EMPTY)) tsc_readl(tsc, LPC32XX_TSC_FIFO); } static irqreturn_t lpc32xx_ts_interrupt(int irq, void *dev_id) { u32 tmp, rv[4], xs[4], ys[4]; int idx; struct lpc32xx_tsc *tsc = dev_id; struct input_dev *input = tsc->dev; tmp = tsc_readl(tsc, LPC32XX_TSC_STAT); if (tmp & LPC32XX_TSC_STAT_FIFO_OVRRN) { /* FIFO overflow - throw away samples */ lpc32xx_fifo_clear(tsc); return IRQ_HANDLED; } /* * Gather and normalize 4 samples. Pen-up events may have less * than 4 samples, but its ok to pop 4 and let the last sample * pen status check drop the samples. */ idx = 0; while (idx < 4 && !(tsc_readl(tsc, LPC32XX_TSC_STAT) & LPC32XX_TSC_STAT_FIFO_EMPTY)) { tmp = tsc_readl(tsc, LPC32XX_TSC_FIFO); xs[idx] = LPC32XX_TSC_ADCDAT_VALUE_MASK - LPC32XX_TSC_FIFO_NORMALIZE_X_VAL(tmp); ys[idx] = LPC32XX_TSC_ADCDAT_VALUE_MASK - LPC32XX_TSC_FIFO_NORMALIZE_Y_VAL(tmp); rv[idx] = tmp; idx++; } /* Data is only valid if pen is still down in last sample */ if (!(rv[3] & LPC32XX_TSC_FIFO_TS_P_LEVEL) && idx == 4) { /* Use average of 2nd and 3rd sample for position */ input_report_abs(input, ABS_X, (xs[1] + xs[2]) / 2); input_report_abs(input, ABS_Y, (ys[1] + ys[2]) / 2); input_report_key(input, BTN_TOUCH, 1); } else { input_report_key(input, BTN_TOUCH, 0); } input_sync(input); return IRQ_HANDLED; } static void lpc32xx_stop_tsc(struct lpc32xx_tsc *tsc) { /* Disable auto mode */ tsc_writel(tsc, LPC32XX_TSC_CON, tsc_readl(tsc, LPC32XX_TSC_CON) & ~LPC32XX_TSC_ADCCON_AUTO_EN); clk_disable_unprepare(tsc->clk); } static int lpc32xx_setup_tsc(struct lpc32xx_tsc *tsc) { u32 tmp; int err; err = clk_prepare_enable(tsc->clk); if (err) return err; tmp = tsc_readl(tsc, LPC32XX_TSC_CON) & ~LPC32XX_TSC_ADCCON_POWER_UP; /* Set the TSC FIFO depth to 4 samples @ 10-bits per sample (max) */ tmp = LPC32XX_TSC_ADCCON_IRQ_TO_FIFO_4 | LPC32XX_TSC_ADCCON_X_SAMPLE_SIZE(10) | LPC32XX_TSC_ADCCON_Y_SAMPLE_SIZE(10); tsc_writel(tsc, LPC32XX_TSC_CON, tmp); /* These values are all preset */ tsc_writel(tsc, LPC32XX_TSC_SEL, LPC32XX_TSC_SEL_DEFVAL); tsc_writel(tsc, LPC32XX_TSC_MIN_X, LPC32XX_TSC_MIN_XY_VAL); tsc_writel(tsc, LPC32XX_TSC_MAX_X, LPC32XX_TSC_MAX_XY_VAL); tsc_writel(tsc, LPC32XX_TSC_MIN_Y, LPC32XX_TSC_MIN_XY_VAL); tsc_writel(tsc, LPC32XX_TSC_MAX_Y, LPC32XX_TSC_MAX_XY_VAL); /* Aux support is not used */ tsc_writel(tsc, LPC32XX_TSC_AUX_UTR, 0); tsc_writel(tsc, LPC32XX_TSC_AUX_MIN, 0); tsc_writel(tsc, LPC32XX_TSC_AUX_MAX, 0); /* * Set sample rate to about 240Hz per X/Y pair. A single measurement * consists of 4 pairs which gives about a 60Hz sample rate based on * a stable 32768Hz clock source. Values are in clocks. * Rate is (32768 / (RTR + XCONV + RTR + YCONV + DXP + TTR + UTR) / 4 */ tsc_writel(tsc, LPC32XX_TSC_RTR, 0x2); tsc_writel(tsc, LPC32XX_TSC_DTR, 0x2); tsc_writel(tsc, LPC32XX_TSC_TTR, 0x10); tsc_writel(tsc, LPC32XX_TSC_DXP, 0x4); tsc_writel(tsc, LPC32XX_TSC_UTR, 88); lpc32xx_fifo_clear(tsc); /* Enable automatic ts event capture */ tsc_writel(tsc, LPC32XX_TSC_CON, tmp | LPC32XX_TSC_ADCCON_AUTO_EN); return 0; } static int lpc32xx_ts_open(struct input_dev *dev) { struct lpc32xx_tsc *tsc = input_get_drvdata(dev); return lpc32xx_setup_tsc(tsc); } static void lpc32xx_ts_close(struct input_dev *dev) { struct lpc32xx_tsc *tsc = input_get_drvdata(dev); lpc32xx_stop_tsc(tsc); } static int lpc32xx_ts_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct lpc32xx_tsc *tsc; struct input_dev *input; int irq; int error; irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; tsc = devm_kzalloc(dev, sizeof(*tsc), GFP_KERNEL); if (!tsc) return -ENOMEM; tsc->irq = irq; tsc->tsc_base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(tsc->tsc_base)) return PTR_ERR(tsc->tsc_base); tsc->clk = devm_clk_get(dev, NULL); if (IS_ERR(tsc->clk)) { dev_err(&pdev->dev, "failed getting clock\n"); return PTR_ERR(tsc->clk); } input = devm_input_allocate_device(dev); if (!input) { dev_err(&pdev->dev, "failed allocating input device\n"); return -ENOMEM; } input->name = MOD_NAME; input->phys = "lpc32xx/input0"; input->id.bustype = BUS_HOST; input->id.vendor = 0x0001; input->id.product = 0x0002; input->id.version = 0x0100; input->open = lpc32xx_ts_open; input->close = lpc32xx_ts_close; input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, LPC32XX_TSC_MIN_XY_VAL, LPC32XX_TSC_MAX_XY_VAL, 0, 0); input_set_abs_params(input, ABS_Y, LPC32XX_TSC_MIN_XY_VAL, LPC32XX_TSC_MAX_XY_VAL, 0, 0); input_set_drvdata(input, tsc); tsc->dev = input; error = devm_request_irq(dev, tsc->irq, lpc32xx_ts_interrupt, 0, pdev->name, tsc); if (error) { dev_err(&pdev->dev, "failed requesting interrupt\n"); return error; } error = input_register_device(input); if (error) { dev_err(&pdev->dev, "failed registering input device\n"); return error; } platform_set_drvdata(pdev, tsc); device_init_wakeup(&pdev->dev, true); return 0; } #ifdef CONFIG_PM static int lpc32xx_ts_suspend(struct device *dev) { struct lpc32xx_tsc *tsc = dev_get_drvdata(dev); struct input_dev *input = tsc->dev; /* * Suspend and resume can be called when the device hasn't been * enabled. If there are no users that have the device open, then * avoid calling the TSC stop and start functions as the TSC * isn't yet clocked. */ mutex_lock(&input->mutex); if (input_device_enabled(input)) { if (device_may_wakeup(dev)) enable_irq_wake(tsc->irq); else lpc32xx_stop_tsc(tsc); } mutex_unlock(&input->mutex); return 0; } static int lpc32xx_ts_resume(struct device *dev) { struct lpc32xx_tsc *tsc = dev_get_drvdata(dev); struct input_dev *input = tsc->dev; mutex_lock(&input->mutex); if (input_device_enabled(input)) { if (device_may_wakeup(dev)) disable_irq_wake(tsc->irq); else lpc32xx_setup_tsc(tsc); } mutex_unlock(&input->mutex); return 0; } static const struct dev_pm_ops lpc32xx_ts_pm_ops = { .suspend = lpc32xx_ts_suspend, .resume = lpc32xx_ts_resume, }; #define LPC32XX_TS_PM_OPS (&lpc32xx_ts_pm_ops) #else #define LPC32XX_TS_PM_OPS NULL #endif #ifdef CONFIG_OF static const struct of_device_id lpc32xx_tsc_of_match[] = { { .compatible = "nxp,lpc3220-tsc", }, { }, }; MODULE_DEVICE_TABLE(of, lpc32xx_tsc_of_match); #endif static struct platform_driver lpc32xx_ts_driver = { .probe = lpc32xx_ts_probe, .driver = { .name = MOD_NAME, .pm = LPC32XX_TS_PM_OPS, .of_match_table = of_match_ptr(lpc32xx_tsc_of_match), }, }; module_platform_driver(lpc32xx_ts_driver); MODULE_AUTHOR("Kevin Wells <[email protected]"); MODULE_DESCRIPTION("LPC32XX TSC Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:lpc32xx_ts");
linux-master
drivers/input/touchscreen/lpc32xx_ts.c
// SPDX-License-Identifier: GPL-2.0 // Samsung S6SY761 Touchscreen device driver // // Copyright (c) 2017 Samsung Electronics Co., Ltd. // Copyright (c) 2017 Andi Shyti <[email protected]> #include <asm/unaligned.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> /* commands */ #define S6SY761_SENSE_ON 0x10 #define S6SY761_SENSE_OFF 0x11 #define S6SY761_TOUCH_FUNCTION 0x30 /* R/W for get/set */ #define S6SY761_FIRMWARE_INTEGRITY 0x21 #define S6SY761_PANEL_INFO 0x23 #define S6SY761_DEVICE_ID 0x52 #define S6SY761_BOOT_STATUS 0x55 #define S6SY761_READ_ONE_EVENT 0x60 #define S6SY761_READ_ALL_EVENT 0x61 #define S6SY761_CLEAR_EVENT_STACK 0x62 #define S6SY761_APPLICATION_MODE 0xe4 /* events */ #define S6SY761_EVENT_INFO 0x02 #define S6SY761_EVENT_VENDOR_INFO 0x07 /* info */ #define S6SY761_INFO_BOOT_COMPLETE 0x00 /* firmware status */ #define S6SY761_FW_OK 0x80 /* * the functionalities are put as a reference * as in the device I am using none of them * works therefore not used in this driver yet. */ /* touchscreen functionalities */ #define S6SY761_MASK_TOUCH BIT(0) #define S6SY761_MASK_HOVER BIT(1) #define S6SY761_MASK_COVER BIT(2) #define S6SY761_MASK_GLOVE BIT(3) #define S6SY761_MASK_STYLUS BIT(4) #define S6SY761_MASK_PALM BIT(5) #define S6SY761_MASK_WET BIT(6) #define S6SY761_MASK_PROXIMITY BIT(7) /* boot status (BS) */ #define S6SY761_BS_BOOT_LOADER 0x10 #define S6SY761_BS_APPLICATION 0x20 /* event id */ #define S6SY761_EVENT_ID_COORDINATE 0x00 #define S6SY761_EVENT_ID_STATUS 0x01 /* event register masks */ #define S6SY761_MASK_TOUCH_STATE 0xc0 /* byte 0 */ #define S6SY761_MASK_TID 0x3c #define S6SY761_MASK_EID 0x03 #define S6SY761_MASK_X 0xf0 /* byte 3 */ #define S6SY761_MASK_Y 0x0f #define S6SY761_MASK_Z 0x3f /* byte 6 */ #define S6SY761_MASK_LEFT_EVENTS 0x3f /* byte 7 */ #define S6SY761_MASK_TOUCH_TYPE 0xc0 /* MSB in byte 6, LSB in byte 7 */ /* event touch state values */ #define S6SY761_TS_NONE 0x00 #define S6SY761_TS_PRESS 0x01 #define S6SY761_TS_MOVE 0x02 #define S6SY761_TS_RELEASE 0x03 /* application modes */ #define S6SY761_APP_NORMAL 0x0 #define S6SY761_APP_LOW_POWER 0x1 #define S6SY761_APP_TEST 0x2 #define S6SY761_APP_FLASH 0x3 #define S6SY761_APP_SLEEP 0x4 #define S6SY761_EVENT_SIZE 8 #define S6SY761_EVENT_COUNT 32 #define S6SY761_DEVID_SIZE 3 #define S6SY761_PANEL_ID_SIZE 11 #define S6SY761_TS_STATUS_SIZE 5 #define S6SY761_MAX_FINGERS 10 #define S6SY761_DEV_NAME "s6sy761" enum s6sy761_regulators { S6SY761_REGULATOR_VDD, S6SY761_REGULATOR_AVDD, }; struct s6sy761_data { struct i2c_client *client; struct regulator_bulk_data regulators[2]; struct input_dev *input; struct touchscreen_properties prop; u8 data[S6SY761_EVENT_SIZE * S6SY761_EVENT_COUNT]; u16 devid; u8 tx_channel; }; /* * We can't simply use i2c_smbus_read_i2c_block_data because we * need to read more than 255 bytes */ static int s6sy761_read_events(struct s6sy761_data *sdata, u16 n_events) { u8 cmd = S6SY761_READ_ALL_EVENT; struct i2c_msg msgs[2] = { { .addr = sdata->client->addr, .len = 1, .buf = &cmd, }, { .addr = sdata->client->addr, .flags = I2C_M_RD, .len = (n_events * S6SY761_EVENT_SIZE), .buf = sdata->data + S6SY761_EVENT_SIZE, }, }; int ret; ret = i2c_transfer(sdata->client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) return ret; return ret == ARRAY_SIZE(msgs) ? 0 : -EIO; } static void s6sy761_report_coordinates(struct s6sy761_data *sdata, u8 *event, u8 tid) { u8 major = event[4]; u8 minor = event[5]; u8 z = event[6] & S6SY761_MASK_Z; u16 x = (event[1] << 4) | ((event[3] & S6SY761_MASK_X) >> 4); u16 y = (event[2] << 4) | (event[3] & S6SY761_MASK_Y); input_mt_slot(sdata->input, tid); input_mt_report_slot_state(sdata->input, MT_TOOL_FINGER, true); input_report_abs(sdata->input, ABS_MT_POSITION_X, x); input_report_abs(sdata->input, ABS_MT_POSITION_Y, y); input_report_abs(sdata->input, ABS_MT_TOUCH_MAJOR, major); input_report_abs(sdata->input, ABS_MT_TOUCH_MINOR, minor); input_report_abs(sdata->input, ABS_MT_PRESSURE, z); input_sync(sdata->input); } static void s6sy761_report_release(struct s6sy761_data *sdata, u8 *event, u8 tid) { input_mt_slot(sdata->input, tid); input_mt_report_slot_state(sdata->input, MT_TOOL_FINGER, false); input_sync(sdata->input); } static void s6sy761_handle_coordinates(struct s6sy761_data *sdata, u8 *event) { u8 tid; u8 touch_state; if (unlikely(!(event[0] & S6SY761_MASK_TID))) return; tid = ((event[0] & S6SY761_MASK_TID) >> 2) - 1; touch_state = (event[0] & S6SY761_MASK_TOUCH_STATE) >> 6; switch (touch_state) { case S6SY761_TS_NONE: break; case S6SY761_TS_RELEASE: s6sy761_report_release(sdata, event, tid); break; case S6SY761_TS_PRESS: case S6SY761_TS_MOVE: s6sy761_report_coordinates(sdata, event, tid); break; } } static void s6sy761_handle_events(struct s6sy761_data *sdata, u8 n_events) { int i; for (i = 0; i < n_events; i++) { u8 *event = &sdata->data[i * S6SY761_EVENT_SIZE]; u8 event_id = event[0] & S6SY761_MASK_EID; if (!event[0]) return; switch (event_id) { case S6SY761_EVENT_ID_COORDINATE: s6sy761_handle_coordinates(sdata, event); break; case S6SY761_EVENT_ID_STATUS: break; default: break; } } } static irqreturn_t s6sy761_irq_handler(int irq, void *dev) { struct s6sy761_data *sdata = dev; int ret; u8 n_events; ret = i2c_smbus_read_i2c_block_data(sdata->client, S6SY761_READ_ONE_EVENT, S6SY761_EVENT_SIZE, sdata->data); if (ret < 0) { dev_err(&sdata->client->dev, "failed to read events\n"); return IRQ_HANDLED; } if (!sdata->data[0]) return IRQ_HANDLED; n_events = sdata->data[7] & S6SY761_MASK_LEFT_EVENTS; if (unlikely(n_events > S6SY761_EVENT_COUNT - 1)) return IRQ_HANDLED; if (n_events) { ret = s6sy761_read_events(sdata, n_events); if (ret < 0) { dev_err(&sdata->client->dev, "failed to read events\n"); return IRQ_HANDLED; } } s6sy761_handle_events(sdata, n_events + 1); return IRQ_HANDLED; } static int s6sy761_input_open(struct input_dev *dev) { struct s6sy761_data *sdata = input_get_drvdata(dev); return i2c_smbus_write_byte(sdata->client, S6SY761_SENSE_ON); } static void s6sy761_input_close(struct input_dev *dev) { struct s6sy761_data *sdata = input_get_drvdata(dev); int ret; ret = i2c_smbus_write_byte(sdata->client, S6SY761_SENSE_OFF); if (ret) dev_err(&sdata->client->dev, "failed to turn off sensing\n"); } static ssize_t s6sy761_sysfs_devid(struct device *dev, struct device_attribute *attr, char *buf) { struct s6sy761_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%#x\n", sdata->devid); } static DEVICE_ATTR(devid, 0444, s6sy761_sysfs_devid, NULL); static struct attribute *s6sy761_sysfs_attrs[] = { &dev_attr_devid.attr, NULL }; static struct attribute_group s6sy761_attribute_group = { .attrs = s6sy761_sysfs_attrs }; static int s6sy761_power_on(struct s6sy761_data *sdata) { u8 buffer[S6SY761_EVENT_SIZE]; u8 event; int ret; ret = regulator_bulk_enable(ARRAY_SIZE(sdata->regulators), sdata->regulators); if (ret) return ret; msleep(140); /* double check whether the touch is functional */ ret = i2c_smbus_read_i2c_block_data(sdata->client, S6SY761_READ_ONE_EVENT, S6SY761_EVENT_SIZE, buffer); if (ret < 0) return ret; event = (buffer[0] >> 2) & 0xf; if ((event != S6SY761_EVENT_INFO && event != S6SY761_EVENT_VENDOR_INFO) || buffer[1] != S6SY761_INFO_BOOT_COMPLETE) { return -ENODEV; } ret = i2c_smbus_read_byte_data(sdata->client, S6SY761_BOOT_STATUS); if (ret < 0) return ret; /* for some reasons the device might be stuck in the bootloader */ if (ret != S6SY761_BS_APPLICATION) return -ENODEV; /* enable touch functionality */ ret = i2c_smbus_write_word_data(sdata->client, S6SY761_TOUCH_FUNCTION, S6SY761_MASK_TOUCH); if (ret) return ret; return 0; } static int s6sy761_hw_init(struct s6sy761_data *sdata, unsigned int *max_x, unsigned int *max_y) { u8 buffer[S6SY761_PANEL_ID_SIZE]; /* larger read size */ int ret; ret = s6sy761_power_on(sdata); if (ret) return ret; ret = i2c_smbus_read_i2c_block_data(sdata->client, S6SY761_DEVICE_ID, S6SY761_DEVID_SIZE, buffer); if (ret < 0) return ret; sdata->devid = get_unaligned_be16(buffer + 1); ret = i2c_smbus_read_i2c_block_data(sdata->client, S6SY761_PANEL_INFO, S6SY761_PANEL_ID_SIZE, buffer); if (ret < 0) return ret; *max_x = get_unaligned_be16(buffer); *max_y = get_unaligned_be16(buffer + 2); /* if no tx channels defined, at least keep one */ sdata->tx_channel = max_t(u8, buffer[8], 1); ret = i2c_smbus_read_byte_data(sdata->client, S6SY761_FIRMWARE_INTEGRITY); if (ret < 0) return ret; else if (ret != S6SY761_FW_OK) return -ENODEV; return 0; } static void s6sy761_power_off(void *data) { struct s6sy761_data *sdata = data; disable_irq(sdata->client->irq); regulator_bulk_disable(ARRAY_SIZE(sdata->regulators), sdata->regulators); } static int s6sy761_probe(struct i2c_client *client) { struct s6sy761_data *sdata; unsigned int max_x, max_y; int err; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C | I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_I2C_BLOCK)) return -ENODEV; sdata = devm_kzalloc(&client->dev, sizeof(*sdata), GFP_KERNEL); if (!sdata) return -ENOMEM; i2c_set_clientdata(client, sdata); sdata->client = client; sdata->regulators[S6SY761_REGULATOR_VDD].supply = "vdd"; sdata->regulators[S6SY761_REGULATOR_AVDD].supply = "avdd"; err = devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(sdata->regulators), sdata->regulators); if (err) return err; err = devm_add_action_or_reset(&client->dev, s6sy761_power_off, sdata); if (err) return err; err = s6sy761_hw_init(sdata, &max_x, &max_y); if (err) return err; sdata->input = devm_input_allocate_device(&client->dev); if (!sdata->input) return -ENOMEM; sdata->input->name = S6SY761_DEV_NAME; sdata->input->id.bustype = BUS_I2C; sdata->input->open = s6sy761_input_open; sdata->input->close = s6sy761_input_close; input_set_abs_params(sdata->input, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(sdata->input, ABS_MT_POSITION_Y, 0, max_y, 0, 0); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MINOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MINOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_PRESSURE, 0, 255, 0, 0); touchscreen_parse_properties(sdata->input, true, &sdata->prop); if (!input_abs_get_max(sdata->input, ABS_X) || !input_abs_get_max(sdata->input, ABS_Y)) { dev_warn(&client->dev, "the axis have not been set\n"); } err = input_mt_init_slots(sdata->input, sdata->tx_channel, INPUT_MT_DIRECT); if (err) return err; input_set_drvdata(sdata->input, sdata); err = input_register_device(sdata->input); if (err) return err; err = devm_request_threaded_irq(&client->dev, client->irq, NULL, s6sy761_irq_handler, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "s6sy761_irq", sdata); if (err) return err; err = devm_device_add_group(&client->dev, &s6sy761_attribute_group); if (err) return err; pm_runtime_enable(&client->dev); return 0; } static void s6sy761_remove(struct i2c_client *client) { pm_runtime_disable(&client->dev); } static int s6sy761_runtime_suspend(struct device *dev) { struct s6sy761_data *sdata = dev_get_drvdata(dev); return i2c_smbus_write_byte_data(sdata->client, S6SY761_APPLICATION_MODE, S6SY761_APP_SLEEP); } static int s6sy761_runtime_resume(struct device *dev) { struct s6sy761_data *sdata = dev_get_drvdata(dev); return i2c_smbus_write_byte_data(sdata->client, S6SY761_APPLICATION_MODE, S6SY761_APP_NORMAL); } static int s6sy761_suspend(struct device *dev) { struct s6sy761_data *sdata = dev_get_drvdata(dev); s6sy761_power_off(sdata); return 0; } static int s6sy761_resume(struct device *dev) { struct s6sy761_data *sdata = dev_get_drvdata(dev); enable_irq(sdata->client->irq); return s6sy761_power_on(sdata); } static const struct dev_pm_ops s6sy761_pm_ops = { SYSTEM_SLEEP_PM_OPS(s6sy761_suspend, s6sy761_resume) RUNTIME_PM_OPS(s6sy761_runtime_suspend, s6sy761_runtime_resume, NULL) }; #ifdef CONFIG_OF static const struct of_device_id s6sy761_of_match[] = { { .compatible = "samsung,s6sy761", }, { }, }; MODULE_DEVICE_TABLE(of, s6sy761_of_match); #endif static const struct i2c_device_id s6sy761_id[] = { { "s6sy761", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, s6sy761_id); static struct i2c_driver s6sy761_driver = { .driver = { .name = S6SY761_DEV_NAME, .of_match_table = of_match_ptr(s6sy761_of_match), .pm = pm_ptr(&s6sy761_pm_ops), }, .probe = s6sy761_probe, .remove = s6sy761_remove, .id_table = s6sy761_id, }; module_i2c_driver(s6sy761_driver); MODULE_AUTHOR("Andi Shyti <[email protected]>"); MODULE_DESCRIPTION("Samsung S6SY761 Touch Screen"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/s6sy761.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/crc-ccitt.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/ihex.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/sizes.h> #include <linux/slab.h> #include <asm/unaligned.h> #define ILI2XXX_POLL_PERIOD 15 #define ILI210X_DATA_SIZE 64 #define ILI211X_DATA_SIZE 43 #define ILI251X_DATA_SIZE1 31 #define ILI251X_DATA_SIZE2 20 /* Touchscreen commands */ #define REG_TOUCHDATA 0x10 #define REG_PANEL_INFO 0x20 #define REG_FIRMWARE_VERSION 0x40 #define REG_PROTOCOL_VERSION 0x42 #define REG_KERNEL_VERSION 0x61 #define REG_IC_BUSY 0x80 #define REG_IC_BUSY_NOT_BUSY 0x50 #define REG_GET_MODE 0xc0 #define REG_GET_MODE_AP 0x5a #define REG_GET_MODE_BL 0x55 #define REG_SET_MODE_AP 0xc1 #define REG_SET_MODE_BL 0xc2 #define REG_WRITE_DATA 0xc3 #define REG_WRITE_ENABLE 0xc4 #define REG_READ_DATA_CRC 0xc7 #define REG_CALIBRATE 0xcc #define ILI251X_FW_FILENAME "ilitek/ili251x.bin" struct ili2xxx_chip { int (*read_reg)(struct i2c_client *client, u8 reg, void *buf, size_t len); int (*get_touch_data)(struct i2c_client *client, u8 *data); bool (*parse_touch_data)(const u8 *data, unsigned int finger, unsigned int *x, unsigned int *y, unsigned int *z); bool (*continue_polling)(const u8 *data, bool touch); unsigned int max_touches; unsigned int resolution; bool has_calibrate_reg; bool has_firmware_proto; bool has_pressure_reg; }; struct ili210x { struct i2c_client *client; struct input_dev *input; struct gpio_desc *reset_gpio; struct touchscreen_properties prop; const struct ili2xxx_chip *chip; u8 version_firmware[8]; u8 version_kernel[5]; u8 version_proto[2]; u8 ic_mode[2]; bool stop; }; static int ili210x_read_reg(struct i2c_client *client, u8 reg, void *buf, size_t len) { struct i2c_msg msg[] = { { .addr = client->addr, .flags = 0, .len = 1, .buf = &reg, }, { .addr = client->addr, .flags = I2C_M_RD, .len = len, .buf = buf, } }; int error, ret; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "%s failed: %d\n", __func__, error); return error; } return 0; } static int ili210x_read_touch_data(struct i2c_client *client, u8 *data) { return ili210x_read_reg(client, REG_TOUCHDATA, data, ILI210X_DATA_SIZE); } static bool ili210x_touchdata_to_coords(const u8 *touchdata, unsigned int finger, unsigned int *x, unsigned int *y, unsigned int *z) { if (!(touchdata[0] & BIT(finger))) return false; *x = get_unaligned_be16(touchdata + 1 + (finger * 4) + 0); *y = get_unaligned_be16(touchdata + 1 + (finger * 4) + 2); return true; } static bool ili210x_check_continue_polling(const u8 *data, bool touch) { return data[0] & 0xf3; } static const struct ili2xxx_chip ili210x_chip = { .read_reg = ili210x_read_reg, .get_touch_data = ili210x_read_touch_data, .parse_touch_data = ili210x_touchdata_to_coords, .continue_polling = ili210x_check_continue_polling, .max_touches = 2, .has_calibrate_reg = true, }; static int ili211x_read_touch_data(struct i2c_client *client, u8 *data) { s16 sum = 0; int error; int ret; int i; ret = i2c_master_recv(client, data, ILI211X_DATA_SIZE); if (ret != ILI211X_DATA_SIZE) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "%s failed: %d\n", __func__, error); return error; } /* This chip uses custom checksum at the end of data */ for (i = 0; i < ILI211X_DATA_SIZE - 1; i++) sum = (sum + data[i]) & 0xff; if ((-sum & 0xff) != data[ILI211X_DATA_SIZE - 1]) { dev_err(&client->dev, "CRC error (crc=0x%02x expected=0x%02x)\n", sum, data[ILI211X_DATA_SIZE - 1]); return -EIO; } return 0; } static bool ili211x_touchdata_to_coords(const u8 *touchdata, unsigned int finger, unsigned int *x, unsigned int *y, unsigned int *z) { u32 data; data = get_unaligned_be32(touchdata + 1 + (finger * 4) + 0); if (data == 0xffffffff) /* Finger up */ return false; *x = ((touchdata[1 + (finger * 4) + 0] & 0xf0) << 4) | touchdata[1 + (finger * 4) + 1]; *y = ((touchdata[1 + (finger * 4) + 0] & 0x0f) << 8) | touchdata[1 + (finger * 4) + 2]; return true; } static bool ili211x_decline_polling(const u8 *data, bool touch) { return false; } static const struct ili2xxx_chip ili211x_chip = { .read_reg = ili210x_read_reg, .get_touch_data = ili211x_read_touch_data, .parse_touch_data = ili211x_touchdata_to_coords, .continue_polling = ili211x_decline_polling, .max_touches = 10, .resolution = 2048, }; static bool ili212x_touchdata_to_coords(const u8 *touchdata, unsigned int finger, unsigned int *x, unsigned int *y, unsigned int *z) { u16 val; val = get_unaligned_be16(touchdata + 3 + (finger * 5) + 0); if (!(val & BIT(15))) /* Touch indication */ return false; *x = val & 0x3fff; *y = get_unaligned_be16(touchdata + 3 + (finger * 5) + 2); return true; } static bool ili212x_check_continue_polling(const u8 *data, bool touch) { return touch; } static const struct ili2xxx_chip ili212x_chip = { .read_reg = ili210x_read_reg, .get_touch_data = ili210x_read_touch_data, .parse_touch_data = ili212x_touchdata_to_coords, .continue_polling = ili212x_check_continue_polling, .max_touches = 10, .has_calibrate_reg = true, }; static int ili251x_read_reg_common(struct i2c_client *client, u8 reg, void *buf, size_t len, unsigned int delay) { int error; int ret; ret = i2c_master_send(client, &reg, 1); if (ret == 1) { if (delay) usleep_range(delay, delay + 500); ret = i2c_master_recv(client, buf, len); if (ret == len) return 0; } error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "%s failed: %d\n", __func__, error); return ret; } static int ili251x_read_reg(struct i2c_client *client, u8 reg, void *buf, size_t len) { return ili251x_read_reg_common(client, reg, buf, len, 5000); } static int ili251x_read_touch_data(struct i2c_client *client, u8 *data) { int error; error = ili251x_read_reg_common(client, REG_TOUCHDATA, data, ILI251X_DATA_SIZE1, 0); if (!error && data[0] == 2) { error = i2c_master_recv(client, data + ILI251X_DATA_SIZE1, ILI251X_DATA_SIZE2); if (error >= 0 && error != ILI251X_DATA_SIZE2) error = -EIO; } return error; } static bool ili251x_touchdata_to_coords(const u8 *touchdata, unsigned int finger, unsigned int *x, unsigned int *y, unsigned int *z) { u16 val; val = get_unaligned_be16(touchdata + 1 + (finger * 5) + 0); if (!(val & BIT(15))) /* Touch indication */ return false; *x = val & 0x3fff; *y = get_unaligned_be16(touchdata + 1 + (finger * 5) + 2); *z = touchdata[1 + (finger * 5) + 4]; return true; } static bool ili251x_check_continue_polling(const u8 *data, bool touch) { return touch; } static const struct ili2xxx_chip ili251x_chip = { .read_reg = ili251x_read_reg, .get_touch_data = ili251x_read_touch_data, .parse_touch_data = ili251x_touchdata_to_coords, .continue_polling = ili251x_check_continue_polling, .max_touches = 10, .has_calibrate_reg = true, .has_firmware_proto = true, .has_pressure_reg = true, }; static bool ili210x_report_events(struct ili210x *priv, u8 *touchdata) { struct input_dev *input = priv->input; int i; bool contact = false, touch; unsigned int x = 0, y = 0, z = 0; for (i = 0; i < priv->chip->max_touches; i++) { touch = priv->chip->parse_touch_data(touchdata, i, &x, &y, &z); input_mt_slot(input, i); if (input_mt_report_slot_state(input, MT_TOOL_FINGER, touch)) { touchscreen_report_pos(input, &priv->prop, x, y, true); if (priv->chip->has_pressure_reg) input_report_abs(input, ABS_MT_PRESSURE, z); contact = true; } } input_mt_report_pointer_emulation(input, false); input_sync(input); return contact; } static irqreturn_t ili210x_irq(int irq, void *irq_data) { struct ili210x *priv = irq_data; struct i2c_client *client = priv->client; const struct ili2xxx_chip *chip = priv->chip; u8 touchdata[ILI210X_DATA_SIZE] = { 0 }; bool keep_polling; ktime_t time_next; s64 time_delta; bool touch; int error; do { time_next = ktime_add_ms(ktime_get(), ILI2XXX_POLL_PERIOD); error = chip->get_touch_data(client, touchdata); if (error) { dev_err(&client->dev, "Unable to get touch data: %d\n", error); break; } touch = ili210x_report_events(priv, touchdata); keep_polling = chip->continue_polling(touchdata, touch); if (keep_polling) { time_delta = ktime_us_delta(time_next, ktime_get()); if (time_delta > 0) usleep_range(time_delta, time_delta + 1000); } } while (!priv->stop && keep_polling); return IRQ_HANDLED; } static int ili251x_firmware_update_resolution(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u16 resx, resy; u8 rs[10]; int error; /* The firmware update blob might have changed the resolution. */ error = priv->chip->read_reg(client, REG_PANEL_INFO, &rs, sizeof(rs)); if (!error) { resx = le16_to_cpup((__le16 *)rs); resy = le16_to_cpup((__le16 *)(rs + 2)); /* The value reported by the firmware is invalid. */ if (!resx || resx == 0xffff || !resy || resy == 0xffff) error = -EINVAL; } /* * In case of error, the firmware might be stuck in bootloader mode, * e.g. after a failed firmware update. Set maximum resolution, but * do not fail to probe, so the user can re-trigger the firmware * update and recover the touch controller. */ if (error) { dev_warn(dev, "Invalid resolution reported by controller.\n"); resx = 16384; resy = 16384; } input_abs_set_max(priv->input, ABS_X, resx - 1); input_abs_set_max(priv->input, ABS_Y, resy - 1); input_abs_set_max(priv->input, ABS_MT_POSITION_X, resx - 1); input_abs_set_max(priv->input, ABS_MT_POSITION_Y, resy - 1); return error; } static ssize_t ili251x_firmware_update_firmware_version(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); int error; u8 fw[8]; /* Get firmware version */ error = priv->chip->read_reg(client, REG_FIRMWARE_VERSION, &fw, sizeof(fw)); if (!error) memcpy(priv->version_firmware, fw, sizeof(fw)); return error; } static ssize_t ili251x_firmware_update_kernel_version(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); int error; u8 kv[5]; /* Get kernel version */ error = priv->chip->read_reg(client, REG_KERNEL_VERSION, &kv, sizeof(kv)); if (!error) memcpy(priv->version_kernel, kv, sizeof(kv)); return error; } static ssize_t ili251x_firmware_update_protocol_version(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); int error; u8 pv[2]; /* Get protocol version */ error = priv->chip->read_reg(client, REG_PROTOCOL_VERSION, &pv, sizeof(pv)); if (!error) memcpy(priv->version_proto, pv, sizeof(pv)); return error; } static ssize_t ili251x_firmware_update_ic_mode(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); int error; u8 md[2]; /* Get chip boot mode */ error = priv->chip->read_reg(client, REG_GET_MODE, &md, sizeof(md)); if (!error) memcpy(priv->ic_mode, md, sizeof(md)); return error; } static int ili251x_firmware_update_cached_state(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); int error; if (!priv->chip->has_firmware_proto) return 0; /* Wait for firmware to boot and stabilize itself. */ msleep(200); /* Firmware does report valid information. */ error = ili251x_firmware_update_resolution(dev); if (error) return error; error = ili251x_firmware_update_firmware_version(dev); if (error) return error; error = ili251x_firmware_update_kernel_version(dev); if (error) return error; error = ili251x_firmware_update_protocol_version(dev); if (error) return error; error = ili251x_firmware_update_ic_mode(dev); if (error) return error; return 0; } static ssize_t ili251x_firmware_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u8 *fw = priv->version_firmware; return sysfs_emit(buf, "%02x%02x.%02x%02x.%02x%02x.%02x%02x\n", fw[0], fw[1], fw[2], fw[3], fw[4], fw[5], fw[6], fw[7]); } static DEVICE_ATTR(firmware_version, 0444, ili251x_firmware_version_show, NULL); static ssize_t ili251x_kernel_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u8 *kv = priv->version_kernel; return sysfs_emit(buf, "%02x.%02x.%02x.%02x.%02x\n", kv[0], kv[1], kv[2], kv[3], kv[4]); } static DEVICE_ATTR(kernel_version, 0444, ili251x_kernel_version_show, NULL); static ssize_t ili251x_protocol_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u8 *pv = priv->version_proto; return sysfs_emit(buf, "%02x.%02x\n", pv[0], pv[1]); } static DEVICE_ATTR(protocol_version, 0444, ili251x_protocol_version_show, NULL); static ssize_t ili251x_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u8 *md = priv->ic_mode; char *mode = "AP"; if (md[0] == REG_GET_MODE_AP) /* Application Mode */ mode = "AP"; else if (md[0] == REG_GET_MODE_BL) /* BootLoader Mode */ mode = "BL"; else /* Unknown Mode */ mode = "??"; return sysfs_emit(buf, "%02x.%02x:%s\n", md[0], md[1], mode); } static DEVICE_ATTR(mode, 0444, ili251x_mode_show, NULL); static ssize_t ili210x_calibrate(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); unsigned long calibrate; int rc; u8 cmd = REG_CALIBRATE; if (kstrtoul(buf, 10, &calibrate)) return -EINVAL; if (calibrate > 1) return -EINVAL; if (calibrate) { rc = i2c_master_send(priv->client, &cmd, sizeof(cmd)); if (rc != sizeof(cmd)) return -EIO; } return count; } static DEVICE_ATTR(calibrate, S_IWUSR, NULL, ili210x_calibrate); static int ili251x_firmware_to_buffer(const struct firmware *fw, u8 **buf, u16 *ac_end, u16 *df_end) { const struct ihex_binrec *rec; u32 fw_addr, fw_last_addr = 0; u16 fw_len; u8 *fw_buf; int error; /* * The firmware ihex blob can never be bigger than 64 kiB, so make this * simple -- allocate a 64 kiB buffer, iterate over the ihex blob records * once, copy them all into this buffer at the right locations, and then * do all operations on this linear buffer. */ fw_buf = kzalloc(SZ_64K, GFP_KERNEL); if (!fw_buf) return -ENOMEM; rec = (const struct ihex_binrec *)fw->data; while (rec) { fw_addr = be32_to_cpu(rec->addr); fw_len = be16_to_cpu(rec->len); /* The last 32 Byte firmware block can be 0xffe0 */ if (fw_addr + fw_len > SZ_64K || fw_addr > SZ_64K - 32) { error = -EFBIG; goto err_big; } /* Find the last address before DF start address, that is AC end */ if (fw_addr == 0xf000) *ac_end = fw_last_addr; fw_last_addr = fw_addr + fw_len; memcpy(fw_buf + fw_addr, rec->data, fw_len); rec = ihex_next_binrec(rec); } /* DF end address is the last address in the firmware blob */ *df_end = fw_addr + fw_len; *buf = fw_buf; return 0; err_big: kfree(fw_buf); return error; } /* Switch mode between Application and BootLoader */ static int ili251x_switch_ic_mode(struct i2c_client *client, u8 cmd_mode) { struct ili210x *priv = i2c_get_clientdata(client); u8 cmd_wren[3] = { REG_WRITE_ENABLE, 0x5a, 0xa5 }; u8 md[2]; int error; error = priv->chip->read_reg(client, REG_GET_MODE, md, sizeof(md)); if (error) return error; /* Mode already set */ if ((cmd_mode == REG_SET_MODE_AP && md[0] == REG_GET_MODE_AP) || (cmd_mode == REG_SET_MODE_BL && md[0] == REG_GET_MODE_BL)) return 0; /* Unlock writes */ error = i2c_master_send(client, cmd_wren, sizeof(cmd_wren)); if (error != sizeof(cmd_wren)) return -EINVAL; mdelay(20); /* Select mode (BootLoader or Application) */ error = i2c_master_send(client, &cmd_mode, 1); if (error != 1) return -EINVAL; mdelay(200); /* Reboot into bootloader takes a lot of time ... */ /* Read back mode */ error = priv->chip->read_reg(client, REG_GET_MODE, md, sizeof(md)); if (error) return error; /* Check if mode is correct now. */ if ((cmd_mode == REG_SET_MODE_AP && md[0] == REG_GET_MODE_AP) || (cmd_mode == REG_SET_MODE_BL && md[0] == REG_GET_MODE_BL)) return 0; return -EINVAL; } static int ili251x_firmware_busy(struct i2c_client *client) { struct ili210x *priv = i2c_get_clientdata(client); int error, i = 0; u8 data; do { /* The read_reg already contains suitable delay */ error = priv->chip->read_reg(client, REG_IC_BUSY, &data, 1); if (error) return error; if (i++ == 100000) return -ETIMEDOUT; } while (data != REG_IC_BUSY_NOT_BUSY); return 0; } static int ili251x_firmware_write_to_ic(struct device *dev, u8 *fwbuf, u16 start, u16 end, u8 dataflash) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); u8 cmd_crc = REG_READ_DATA_CRC; u8 crcrb[4] = { 0 }; u8 fw_data[33]; u16 fw_addr; int error; /* * The DF (dataflash) needs 2 bytes offset for unknown reasons, * the AC (application) has 2 bytes CRC16-CCITT at the end. */ u16 crc = crc_ccitt(0, fwbuf + start + (dataflash ? 2 : 0), end - start - 2); /* Unlock write to either AC (application) or DF (dataflash) area */ u8 cmd_wr[10] = { REG_WRITE_ENABLE, 0x5a, 0xa5, dataflash, (end >> 16) & 0xff, (end >> 8) & 0xff, end & 0xff, (crc >> 16) & 0xff, (crc >> 8) & 0xff, crc & 0xff }; error = i2c_master_send(client, cmd_wr, sizeof(cmd_wr)); if (error != sizeof(cmd_wr)) return -EINVAL; error = ili251x_firmware_busy(client); if (error) return error; for (fw_addr = start; fw_addr < end; fw_addr += 32) { fw_data[0] = REG_WRITE_DATA; memcpy(&(fw_data[1]), fwbuf + fw_addr, 32); error = i2c_master_send(client, fw_data, 33); if (error != sizeof(fw_data)) return error; error = ili251x_firmware_busy(client); if (error) return error; } error = i2c_master_send(client, &cmd_crc, 1); if (error != 1) return -EINVAL; error = ili251x_firmware_busy(client); if (error) return error; error = priv->chip->read_reg(client, REG_READ_DATA_CRC, &crcrb, sizeof(crcrb)); if (error) return error; /* Check CRC readback */ if ((crcrb[0] != (crc & 0xff)) || crcrb[1] != ((crc >> 8) & 0xff)) return -EINVAL; return 0; } static int ili251x_firmware_reset(struct i2c_client *client) { u8 cmd_reset[2] = { 0xf2, 0x01 }; int error; error = i2c_master_send(client, cmd_reset, sizeof(cmd_reset)); if (error != sizeof(cmd_reset)) return -EINVAL; return ili251x_firmware_busy(client); } static void ili210x_hardware_reset(struct gpio_desc *reset_gpio) { /* Reset the controller */ gpiod_set_value_cansleep(reset_gpio, 1); usleep_range(12000, 15000); gpiod_set_value_cansleep(reset_gpio, 0); msleep(300); } static ssize_t ili210x_firmware_update_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); const char *fwname = ILI251X_FW_FILENAME; const struct firmware *fw; u16 ac_end, df_end; u8 *fwbuf; int error; int i; error = request_ihex_firmware(&fw, fwname, dev); if (error) { dev_err(dev, "Failed to request firmware %s, error=%d\n", fwname, error); return error; } error = ili251x_firmware_to_buffer(fw, &fwbuf, &ac_end, &df_end); release_firmware(fw); if (error) return error; /* * Disable touchscreen IRQ, so that we would not get spurious touch * interrupt during firmware update, and so that the IRQ handler won't * trigger and interfere with the firmware update. There is no bit in * the touch controller to disable the IRQs during update, so we have * to do it this way here. */ disable_irq(client->irq); dev_dbg(dev, "Firmware update started, firmware=%s\n", fwname); ili210x_hardware_reset(priv->reset_gpio); error = ili251x_firmware_reset(client); if (error) goto exit; /* This may not succeed on first try, so re-try a few times. */ for (i = 0; i < 5; i++) { error = ili251x_switch_ic_mode(client, REG_SET_MODE_BL); if (!error) break; } if (error) goto exit; dev_dbg(dev, "IC is now in BootLoader mode\n"); msleep(200); /* The bootloader seems to need some time too. */ error = ili251x_firmware_write_to_ic(dev, fwbuf, 0xf000, df_end, 1); if (error) { dev_err(dev, "DF firmware update failed, error=%d\n", error); goto exit; } dev_dbg(dev, "DataFlash firmware written\n"); error = ili251x_firmware_write_to_ic(dev, fwbuf, 0x2000, ac_end, 0); if (error) { dev_err(dev, "AC firmware update failed, error=%d\n", error); goto exit; } dev_dbg(dev, "Application firmware written\n"); /* This may not succeed on first try, so re-try a few times. */ for (i = 0; i < 5; i++) { error = ili251x_switch_ic_mode(client, REG_SET_MODE_AP); if (!error) break; } if (error) goto exit; dev_dbg(dev, "IC is now in Application mode\n"); error = ili251x_firmware_update_cached_state(dev); if (error) goto exit; error = count; exit: ili210x_hardware_reset(priv->reset_gpio); dev_dbg(dev, "Firmware update ended, error=%i\n", error); enable_irq(client->irq); kfree(fwbuf); return error; } static DEVICE_ATTR(firmware_update, 0200, NULL, ili210x_firmware_update_store); static struct attribute *ili210x_attributes[] = { &dev_attr_calibrate.attr, &dev_attr_firmware_update.attr, &dev_attr_firmware_version.attr, &dev_attr_kernel_version.attr, &dev_attr_protocol_version.attr, &dev_attr_mode.attr, NULL, }; static umode_t ili210x_attributes_visible(struct kobject *kobj, struct attribute *attr, int index) { struct device *dev = kobj_to_dev(kobj); struct i2c_client *client = to_i2c_client(dev); struct ili210x *priv = i2c_get_clientdata(client); /* Calibrate is present on all ILI2xxx which have calibrate register */ if (attr == &dev_attr_calibrate.attr) return priv->chip->has_calibrate_reg ? attr->mode : 0; /* Firmware/Kernel/Protocol/BootMode is implememted only for ILI251x */ if (!priv->chip->has_firmware_proto) return 0; return attr->mode; } static const struct attribute_group ili210x_attr_group = { .attrs = ili210x_attributes, .is_visible = ili210x_attributes_visible, }; static void ili210x_power_down(void *data) { struct gpio_desc *reset_gpio = data; gpiod_set_value_cansleep(reset_gpio, 1); } static void ili210x_stop(void *data) { struct ili210x *priv = data; /* Tell ISR to quit even if there is a contact. */ priv->stop = true; } static int ili210x_i2c_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct device *dev = &client->dev; const struct ili2xxx_chip *chip; struct ili210x *priv; struct gpio_desc *reset_gpio; struct input_dev *input; int error; unsigned int max_xy; dev_dbg(dev, "Probing for ILI210X I2C Touschreen driver"); chip = device_get_match_data(dev); if (!chip && id) chip = (const struct ili2xxx_chip *)id->driver_data; if (!chip) { dev_err(&client->dev, "unknown device model\n"); return -ENODEV; } if (client->irq <= 0) { dev_err(dev, "No IRQ!\n"); return -EINVAL; } reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(reset_gpio)) return PTR_ERR(reset_gpio); if (reset_gpio) { error = devm_add_action_or_reset(dev, ili210x_power_down, reset_gpio); if (error) return error; ili210x_hardware_reset(reset_gpio); } priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; priv->client = client; priv->input = input; priv->reset_gpio = reset_gpio; priv->chip = chip; i2c_set_clientdata(client, priv); /* Setup input device */ input->name = "ILI210x Touchscreen"; input->id.bustype = BUS_I2C; /* Multi touch */ max_xy = (chip->resolution ?: SZ_64K) - 1; input_set_abs_params(input, ABS_MT_POSITION_X, 0, max_xy, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, max_xy, 0, 0); if (priv->chip->has_pressure_reg) input_set_abs_params(input, ABS_MT_PRESSURE, 0, 0xa, 0, 0); error = ili251x_firmware_update_cached_state(dev); if (error) dev_warn(dev, "Unable to cache firmware information, err: %d\n", error); touchscreen_parse_properties(input, true, &priv->prop); error = input_mt_init_slots(input, priv->chip->max_touches, INPUT_MT_DIRECT); if (error) { dev_err(dev, "Unable to set up slots, err: %d\n", error); return error; } error = devm_request_threaded_irq(dev, client->irq, NULL, ili210x_irq, IRQF_ONESHOT, client->name, priv); if (error) { dev_err(dev, "Unable to request touchscreen IRQ, err: %d\n", error); return error; } error = devm_add_action_or_reset(dev, ili210x_stop, priv); if (error) return error; error = devm_device_add_group(dev, &ili210x_attr_group); if (error) { dev_err(dev, "Unable to create sysfs attributes, err: %d\n", error); return error; } error = input_register_device(priv->input); if (error) { dev_err(dev, "Cannot register input device, err: %d\n", error); return error; } return 0; } static const struct i2c_device_id ili210x_i2c_id[] = { { "ili210x", (long)&ili210x_chip }, { "ili2117", (long)&ili211x_chip }, { "ili2120", (long)&ili212x_chip }, { "ili251x", (long)&ili251x_chip }, { } }; MODULE_DEVICE_TABLE(i2c, ili210x_i2c_id); static const struct of_device_id ili210x_dt_ids[] = { { .compatible = "ilitek,ili210x", .data = &ili210x_chip }, { .compatible = "ilitek,ili2117", .data = &ili211x_chip }, { .compatible = "ilitek,ili2120", .data = &ili212x_chip }, { .compatible = "ilitek,ili251x", .data = &ili251x_chip }, { } }; MODULE_DEVICE_TABLE(of, ili210x_dt_ids); static struct i2c_driver ili210x_ts_driver = { .driver = { .name = "ili210x_i2c", .of_match_table = ili210x_dt_ids, }, .id_table = ili210x_i2c_id, .probe = ili210x_i2c_probe, }; module_i2c_driver(ili210x_ts_driver); MODULE_AUTHOR("Olivier Sobrie <[email protected]>"); MODULE_DESCRIPTION("ILI210X I2C Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ili210x.c
// SPDX-License-Identifier: GPL-2.0-only /* * ROHM BU21023/24 Dual touch support resistive touch screen driver * Copyright (C) 2012 ROHM CO.,LTD. */ #include <linux/delay.h> #include <linux/firmware.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #define BU21023_NAME "bu21023_ts" #define BU21023_FIRMWARE_NAME "bu21023.bin" #define MAX_CONTACTS 2 #define AXIS_ADJUST 4 #define AXIS_OFFSET 8 #define FIRMWARE_BLOCK_SIZE 32U #define FIRMWARE_RETRY_MAX 4 #define SAMPLING_DELAY 12 /* msec */ #define CALIBRATION_RETRY_MAX 6 #define ROHM_TS_ABS_X_MIN 40 #define ROHM_TS_ABS_X_MAX 990 #define ROHM_TS_ABS_Y_MIN 160 #define ROHM_TS_ABS_Y_MAX 920 #define ROHM_TS_DISPLACEMENT_MAX 0 /* zero for infinite */ /* * BU21023GUL/BU21023MUV/BU21024FV-M registers map */ #define VADOUT_YP_H 0x00 #define VADOUT_YP_L 0x01 #define VADOUT_XP_H 0x02 #define VADOUT_XP_L 0x03 #define VADOUT_YN_H 0x04 #define VADOUT_YN_L 0x05 #define VADOUT_XN_H 0x06 #define VADOUT_XN_L 0x07 #define PRM1_X_H 0x08 #define PRM1_X_L 0x09 #define PRM1_Y_H 0x0a #define PRM1_Y_L 0x0b #define PRM2_X_H 0x0c #define PRM2_X_L 0x0d #define PRM2_Y_H 0x0e #define PRM2_Y_L 0x0f #define MLT_PRM_MONI_X 0x10 #define MLT_PRM_MONI_Y 0x11 #define DEBUG_MONI_1 0x12 #define DEBUG_MONI_2 0x13 #define VADOUT_ZX_H 0x14 #define VADOUT_ZX_L 0x15 #define VADOUT_ZY_H 0x16 #define VADOUT_ZY_L 0x17 #define Z_PARAM_H 0x18 #define Z_PARAM_L 0x19 /* * Value for VADOUT_*_L */ #define VADOUT_L_MASK 0x01 /* * Value for PRM*_*_L */ #define PRM_L_MASK 0x01 #define POS_X1_H 0x20 #define POS_X1_L 0x21 #define POS_Y1_H 0x22 #define POS_Y1_L 0x23 #define POS_X2_H 0x24 #define POS_X2_L 0x25 #define POS_Y2_H 0x26 #define POS_Y2_L 0x27 /* * Value for POS_*_L */ #define POS_L_MASK 0x01 #define TOUCH 0x28 #define TOUCH_DETECT 0x01 #define TOUCH_GESTURE 0x29 #define SINGLE_TOUCH 0x01 #define DUAL_TOUCH 0x03 #define TOUCH_MASK 0x03 #define CALIBRATION_REQUEST 0x04 #define CALIBRATION_STATUS 0x08 #define CALIBRATION_MASK 0x0c #define GESTURE_SPREAD 0x10 #define GESTURE_PINCH 0x20 #define GESTURE_ROTATE_R 0x40 #define GESTURE_ROTATE_L 0x80 #define INT_STATUS 0x2a #define INT_MASK 0x3d #define INT_CLEAR 0x3e /* * Values for INT_* */ #define COORD_UPDATE 0x01 #define CALIBRATION_DONE 0x02 #define SLEEP_IN 0x04 #define SLEEP_OUT 0x08 #define PROGRAM_LOAD_DONE 0x10 #define ERROR 0x80 #define INT_ALL 0x9f #define ERR_STATUS 0x2b #define ERR_MASK 0x3f /* * Values for ERR_* */ #define ADC_TIMEOUT 0x01 #define CPU_TIMEOUT 0x02 #define CALIBRATION_ERR 0x04 #define PROGRAM_LOAD_ERR 0x10 #define COMMON_SETUP1 0x30 #define PROGRAM_LOAD_HOST 0x02 #define PROGRAM_LOAD_EEPROM 0x03 #define CENSOR_4PORT 0x04 #define CENSOR_8PORT 0x00 /* Not supported by BU21023 */ #define CALIBRATION_TYPE_DEFAULT 0x08 #define CALIBRATION_TYPE_SPECIAL 0x00 #define INT_ACTIVE_HIGH 0x10 #define INT_ACTIVE_LOW 0x00 #define AUTO_CALIBRATION 0x40 #define MANUAL_CALIBRATION 0x00 #define COMMON_SETUP1_DEFAULT 0x4e #define COMMON_SETUP2 0x31 #define MAF_NONE 0x00 #define MAF_1SAMPLE 0x01 #define MAF_3SAMPLES 0x02 #define MAF_5SAMPLES 0x03 #define INV_Y 0x04 #define INV_X 0x08 #define SWAP_XY 0x10 #define COMMON_SETUP3 0x32 #define EN_SLEEP 0x01 #define EN_MULTI 0x02 #define EN_GESTURE 0x04 #define EN_INTVL 0x08 #define SEL_STEP 0x10 #define SEL_MULTI 0x20 #define SEL_TBL_DEFAULT 0x40 #define INTERVAL_TIME 0x33 #define INTERVAL_TIME_DEFAULT 0x10 #define STEP_X 0x34 #define STEP_X_DEFAULT 0x41 #define STEP_Y 0x35 #define STEP_Y_DEFAULT 0x8d #define OFFSET_X 0x38 #define OFFSET_X_DEFAULT 0x0c #define OFFSET_Y 0x39 #define OFFSET_Y_DEFAULT 0x0c #define THRESHOLD_TOUCH 0x3a #define THRESHOLD_TOUCH_DEFAULT 0xa0 #define THRESHOLD_GESTURE 0x3b #define THRESHOLD_GESTURE_DEFAULT 0x17 #define SYSTEM 0x40 #define ANALOG_POWER_ON 0x01 #define ANALOG_POWER_OFF 0x00 #define CPU_POWER_ON 0x02 #define CPU_POWER_OFF 0x00 #define FORCE_CALIBRATION 0x42 #define FORCE_CALIBRATION_ON 0x01 #define FORCE_CALIBRATION_OFF 0x00 #define CPU_FREQ 0x50 /* 10 / (reg + 1) MHz */ #define CPU_FREQ_10MHZ 0x00 #define CPU_FREQ_5MHZ 0x01 #define CPU_FREQ_1MHZ 0x09 #define EEPROM_ADDR 0x51 #define CALIBRATION_ADJUST 0x52 #define CALIBRATION_ADJUST_DEFAULT 0x00 #define THRESHOLD_SLEEP_IN 0x53 #define EVR_XY 0x56 #define EVR_XY_DEFAULT 0x10 #define PRM_SWOFF_TIME 0x57 #define PRM_SWOFF_TIME_DEFAULT 0x04 #define PROGRAM_VERSION 0x5f #define ADC_CTRL 0x60 #define ADC_DIV_MASK 0x1f /* The minimum value is 4 */ #define ADC_DIV_DEFAULT 0x08 #define ADC_WAIT 0x61 #define ADC_WAIT_DEFAULT 0x0a #define SWCONT 0x62 #define SWCONT_DEFAULT 0x0f #define EVR_X 0x63 #define EVR_X_DEFAULT 0x86 #define EVR_Y 0x64 #define EVR_Y_DEFAULT 0x64 #define TEST1 0x65 #define DUALTOUCH_STABILIZE_ON 0x01 #define DUALTOUCH_STABILIZE_OFF 0x00 #define DUALTOUCH_REG_ON 0x20 #define DUALTOUCH_REG_OFF 0x00 #define CALIBRATION_REG1 0x68 #define CALIBRATION_REG1_DEFAULT 0xd9 #define CALIBRATION_REG2 0x69 #define CALIBRATION_REG2_DEFAULT 0x36 #define CALIBRATION_REG3 0x6a #define CALIBRATION_REG3_DEFAULT 0x32 #define EX_ADDR_H 0x70 #define EX_ADDR_L 0x71 #define EX_WDAT 0x72 #define EX_RDAT 0x73 #define EX_CHK_SUM1 0x74 #define EX_CHK_SUM2 0x75 #define EX_CHK_SUM3 0x76 struct rohm_ts_data { struct i2c_client *client; struct input_dev *input; bool initialized; unsigned int contact_count[MAX_CONTACTS + 1]; int finger_count; u8 setup2; }; /* * rohm_i2c_burst_read - execute combined I2C message for ROHM BU21023/24 * @client: Handle to ROHM BU21023/24 * @start: Where to start read address from ROHM BU21023/24 * @buf: Where to store read data from ROHM BU21023/24 * @len: How many bytes to read * * Returns negative errno, else zero on success. * * Note * In BU21023/24 burst read, stop condition is needed after "address write". * Therefore, transmission is performed in 2 steps. */ static int rohm_i2c_burst_read(struct i2c_client *client, u8 start, void *buf, size_t len) { struct i2c_adapter *adap = client->adapter; struct i2c_msg msg[2]; int i, ret = 0; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = &start; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].len = len; msg[1].buf = buf; i2c_lock_bus(adap, I2C_LOCK_SEGMENT); for (i = 0; i < 2; i++) { if (__i2c_transfer(adap, &msg[i], 1) < 0) { ret = -EIO; break; } } i2c_unlock_bus(adap, I2C_LOCK_SEGMENT); return ret; } static int rohm_ts_manual_calibration(struct rohm_ts_data *ts) { struct i2c_client *client = ts->client; struct device *dev = &client->dev; u8 buf[33]; /* for PRM1_X_H(0x08)-TOUCH(0x28) */ int retry; bool success = false; bool first_time = true; bool calibration_done; u8 reg1, reg2, reg3; s32 reg1_orig, reg2_orig, reg3_orig; s32 val; int calib_x = 0, calib_y = 0; int reg_x, reg_y; int err_x, err_y; int error, error2; int i; reg1_orig = i2c_smbus_read_byte_data(client, CALIBRATION_REG1); if (reg1_orig < 0) return reg1_orig; reg2_orig = i2c_smbus_read_byte_data(client, CALIBRATION_REG2); if (reg2_orig < 0) return reg2_orig; reg3_orig = i2c_smbus_read_byte_data(client, CALIBRATION_REG3); if (reg3_orig < 0) return reg3_orig; error = i2c_smbus_write_byte_data(client, INT_MASK, COORD_UPDATE | SLEEP_IN | SLEEP_OUT | PROGRAM_LOAD_DONE); if (error) goto out; error = i2c_smbus_write_byte_data(client, TEST1, DUALTOUCH_STABILIZE_ON); if (error) goto out; for (retry = 0; retry < CALIBRATION_RETRY_MAX; retry++) { /* wait 2 sampling for update */ mdelay(2 * SAMPLING_DELAY); #define READ_CALIB_BUF(reg) buf[((reg) - PRM1_X_H)] error = rohm_i2c_burst_read(client, PRM1_X_H, buf, sizeof(buf)); if (error) goto out; if (READ_CALIB_BUF(TOUCH) & TOUCH_DETECT) continue; if (first_time) { /* generate calibration parameter */ calib_x = ((int)READ_CALIB_BUF(PRM1_X_H) << 2 | READ_CALIB_BUF(PRM1_X_L)) - AXIS_OFFSET; calib_y = ((int)READ_CALIB_BUF(PRM1_Y_H) << 2 | READ_CALIB_BUF(PRM1_Y_L)) - AXIS_OFFSET; error = i2c_smbus_write_byte_data(client, TEST1, DUALTOUCH_STABILIZE_ON | DUALTOUCH_REG_ON); if (error) goto out; first_time = false; } else { /* generate adjustment parameter */ err_x = (int)READ_CALIB_BUF(PRM1_X_H) << 2 | READ_CALIB_BUF(PRM1_X_L); err_y = (int)READ_CALIB_BUF(PRM1_Y_H) << 2 | READ_CALIB_BUF(PRM1_Y_L); /* X axis ajust */ if (err_x <= 4) calib_x -= AXIS_ADJUST; else if (err_x >= 60) calib_x += AXIS_ADJUST; /* Y axis ajust */ if (err_y <= 4) calib_y -= AXIS_ADJUST; else if (err_y >= 60) calib_y += AXIS_ADJUST; } /* generate calibration setting value */ reg_x = calib_x + ((calib_x & 0x200) << 1); reg_y = calib_y + ((calib_y & 0x200) << 1); /* convert for register format */ reg1 = reg_x >> 3; reg2 = (reg_y & 0x7) << 4 | (reg_x & 0x7); reg3 = reg_y >> 3; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG1, reg1); if (error) goto out; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG2, reg2); if (error) goto out; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG3, reg3); if (error) goto out; /* * force calibration sequcence */ error = i2c_smbus_write_byte_data(client, FORCE_CALIBRATION, FORCE_CALIBRATION_OFF); if (error) goto out; error = i2c_smbus_write_byte_data(client, FORCE_CALIBRATION, FORCE_CALIBRATION_ON); if (error) goto out; /* clear all interrupts */ error = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); if (error) goto out; /* * Wait for the status change of calibration, max 10 sampling */ calibration_done = false; for (i = 0; i < 10; i++) { mdelay(SAMPLING_DELAY); val = i2c_smbus_read_byte_data(client, TOUCH_GESTURE); if (!(val & CALIBRATION_MASK)) { calibration_done = true; break; } else if (val < 0) { error = val; goto out; } } if (calibration_done) { val = i2c_smbus_read_byte_data(client, INT_STATUS); if (val == CALIBRATION_DONE) { success = true; break; } else if (val < 0) { error = val; goto out; } } else { dev_warn(dev, "calibration timeout\n"); } } if (!success) { error = i2c_smbus_write_byte_data(client, CALIBRATION_REG1, reg1_orig); if (error) goto out; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG2, reg2_orig); if (error) goto out; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG3, reg3_orig); if (error) goto out; /* calibration data enable */ error = i2c_smbus_write_byte_data(client, TEST1, DUALTOUCH_STABILIZE_ON | DUALTOUCH_REG_ON); if (error) goto out; /* wait 10 sampling */ mdelay(10 * SAMPLING_DELAY); error = -EBUSY; } out: error2 = i2c_smbus_write_byte_data(client, INT_MASK, INT_ALL); if (!error2) /* Clear all interrupts */ error2 = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); return error ? error : error2; } static const unsigned int untouch_threshold[3] = { 0, 1, 5 }; static const unsigned int single_touch_threshold[3] = { 0, 0, 4 }; static const unsigned int dual_touch_threshold[3] = { 10, 8, 0 }; static irqreturn_t rohm_ts_soft_irq(int irq, void *dev_id) { struct rohm_ts_data *ts = dev_id; struct i2c_client *client = ts->client; struct input_dev *input_dev = ts->input; struct device *dev = &client->dev; u8 buf[10]; /* for POS_X1_H(0x20)-TOUCH_GESTURE(0x29) */ struct input_mt_pos pos[MAX_CONTACTS]; int slots[MAX_CONTACTS]; u8 touch_flags; unsigned int threshold; int finger_count = -1; int prev_finger_count = ts->finger_count; int count; int error; int i; error = i2c_smbus_write_byte_data(client, INT_MASK, INT_ALL); if (error) return IRQ_HANDLED; /* Clear all interrupts */ error = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); if (error) return IRQ_HANDLED; #define READ_POS_BUF(reg) buf[((reg) - POS_X1_H)] error = rohm_i2c_burst_read(client, POS_X1_H, buf, sizeof(buf)); if (error) return IRQ_HANDLED; touch_flags = READ_POS_BUF(TOUCH_GESTURE) & TOUCH_MASK; if (touch_flags) { /* generate coordinates */ pos[0].x = ((s16)READ_POS_BUF(POS_X1_H) << 2) | READ_POS_BUF(POS_X1_L); pos[0].y = ((s16)READ_POS_BUF(POS_Y1_H) << 2) | READ_POS_BUF(POS_Y1_L); pos[1].x = ((s16)READ_POS_BUF(POS_X2_H) << 2) | READ_POS_BUF(POS_X2_L); pos[1].y = ((s16)READ_POS_BUF(POS_Y2_H) << 2) | READ_POS_BUF(POS_Y2_L); } switch (touch_flags) { case 0: threshold = untouch_threshold[prev_finger_count]; if (++ts->contact_count[0] >= threshold) finger_count = 0; break; case SINGLE_TOUCH: threshold = single_touch_threshold[prev_finger_count]; if (++ts->contact_count[1] >= threshold) finger_count = 1; if (finger_count == 1) { if (pos[1].x != 0 && pos[1].y != 0) { pos[0].x = pos[1].x; pos[0].y = pos[1].y; pos[1].x = 0; pos[1].y = 0; } } break; case DUAL_TOUCH: threshold = dual_touch_threshold[prev_finger_count]; if (++ts->contact_count[2] >= threshold) finger_count = 2; break; default: dev_dbg(dev, "Three or more touches are not supported\n"); return IRQ_HANDLED; } if (finger_count >= 0) { if (prev_finger_count != finger_count) { count = ts->contact_count[finger_count]; memset(ts->contact_count, 0, sizeof(ts->contact_count)); ts->contact_count[finger_count] = count; } input_mt_assign_slots(input_dev, slots, pos, finger_count, ROHM_TS_DISPLACEMENT_MAX); for (i = 0; i < finger_count; i++) { input_mt_slot(input_dev, slots[i]); input_mt_report_slot_state(input_dev, MT_TOOL_FINGER, true); input_report_abs(input_dev, ABS_MT_POSITION_X, pos[i].x); input_report_abs(input_dev, ABS_MT_POSITION_Y, pos[i].y); } input_mt_sync_frame(input_dev); input_mt_report_pointer_emulation(input_dev, true); input_sync(input_dev); ts->finger_count = finger_count; } if (READ_POS_BUF(TOUCH_GESTURE) & CALIBRATION_REQUEST) { error = rohm_ts_manual_calibration(ts); if (error) dev_warn(dev, "manual calibration failed: %d\n", error); } i2c_smbus_write_byte_data(client, INT_MASK, CALIBRATION_DONE | SLEEP_OUT | SLEEP_IN | PROGRAM_LOAD_DONE); return IRQ_HANDLED; } static int rohm_ts_load_firmware(struct i2c_client *client, const char *firmware_name) { struct device *dev = &client->dev; const struct firmware *fw; s32 status; unsigned int offset, len, xfer_len; unsigned int retry = 0; int error, error2; error = request_firmware(&fw, firmware_name, dev); if (error) { dev_err(dev, "unable to retrieve firmware %s: %d\n", firmware_name, error); return error; } error = i2c_smbus_write_byte_data(client, INT_MASK, COORD_UPDATE | CALIBRATION_DONE | SLEEP_IN | SLEEP_OUT); if (error) goto out; do { if (retry) { dev_warn(dev, "retrying firmware load\n"); /* settings for retry */ error = i2c_smbus_write_byte_data(client, EX_WDAT, 0); if (error) goto out; } error = i2c_smbus_write_byte_data(client, EX_ADDR_H, 0); if (error) goto out; error = i2c_smbus_write_byte_data(client, EX_ADDR_L, 0); if (error) goto out; error = i2c_smbus_write_byte_data(client, COMMON_SETUP1, COMMON_SETUP1_DEFAULT); if (error) goto out; /* firmware load to the device */ offset = 0; len = fw->size; while (len) { xfer_len = min(FIRMWARE_BLOCK_SIZE, len); error = i2c_smbus_write_i2c_block_data(client, EX_WDAT, xfer_len, &fw->data[offset]); if (error) goto out; len -= xfer_len; offset += xfer_len; } /* check firmware load result */ status = i2c_smbus_read_byte_data(client, INT_STATUS); if (status < 0) { error = status; goto out; } /* clear all interrupts */ error = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); if (error) goto out; if (status == PROGRAM_LOAD_DONE) break; error = -EIO; } while (++retry <= FIRMWARE_RETRY_MAX); out: error2 = i2c_smbus_write_byte_data(client, INT_MASK, INT_ALL); release_firmware(fw); return error ? error : error2; } static ssize_t swap_xy_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%d\n", !!(ts->setup2 & SWAP_XY)); } static ssize_t swap_xy_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); unsigned int val; int error; error = kstrtouint(buf, 0, &val); if (error) return error; error = mutex_lock_interruptible(&ts->input->mutex); if (error) return error; if (val) ts->setup2 |= SWAP_XY; else ts->setup2 &= ~SWAP_XY; if (ts->initialized) error = i2c_smbus_write_byte_data(ts->client, COMMON_SETUP2, ts->setup2); mutex_unlock(&ts->input->mutex); return error ? error : count; } static ssize_t inv_x_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%d\n", !!(ts->setup2 & INV_X)); } static ssize_t inv_x_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); unsigned int val; int error; error = kstrtouint(buf, 0, &val); if (error) return error; error = mutex_lock_interruptible(&ts->input->mutex); if (error) return error; if (val) ts->setup2 |= INV_X; else ts->setup2 &= ~INV_X; if (ts->initialized) error = i2c_smbus_write_byte_data(ts->client, COMMON_SETUP2, ts->setup2); mutex_unlock(&ts->input->mutex); return error ? error : count; } static ssize_t inv_y_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%d\n", !!(ts->setup2 & INV_Y)); } static ssize_t inv_y_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct rohm_ts_data *ts = i2c_get_clientdata(client); unsigned int val; int error; error = kstrtouint(buf, 0, &val); if (error) return error; error = mutex_lock_interruptible(&ts->input->mutex); if (error) return error; if (val) ts->setup2 |= INV_Y; else ts->setup2 &= ~INV_Y; if (ts->initialized) error = i2c_smbus_write_byte_data(client, COMMON_SETUP2, ts->setup2); mutex_unlock(&ts->input->mutex); return error ? error : count; } static DEVICE_ATTR_RW(swap_xy); static DEVICE_ATTR_RW(inv_x); static DEVICE_ATTR_RW(inv_y); static struct attribute *rohm_ts_attrs[] = { &dev_attr_swap_xy.attr, &dev_attr_inv_x.attr, &dev_attr_inv_y.attr, NULL, }; static const struct attribute_group rohm_ts_attr_group = { .attrs = rohm_ts_attrs, }; static int rohm_ts_device_init(struct i2c_client *client, u8 setup2) { struct device *dev = &client->dev; int error; disable_irq(client->irq); /* * Wait 200usec for reset */ udelay(200); /* Release analog reset */ error = i2c_smbus_write_byte_data(client, SYSTEM, ANALOG_POWER_ON | CPU_POWER_OFF); if (error) return error; /* Waiting for the analog warm-up, max. 200usec */ udelay(200); /* clear all interrupts */ error = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); if (error) return error; error = i2c_smbus_write_byte_data(client, EX_WDAT, 0); if (error) return error; error = i2c_smbus_write_byte_data(client, COMMON_SETUP1, 0); if (error) return error; error = i2c_smbus_write_byte_data(client, COMMON_SETUP2, setup2); if (error) return error; error = i2c_smbus_write_byte_data(client, COMMON_SETUP3, SEL_TBL_DEFAULT | EN_MULTI); if (error) return error; error = i2c_smbus_write_byte_data(client, THRESHOLD_GESTURE, THRESHOLD_GESTURE_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, INTERVAL_TIME, INTERVAL_TIME_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, CPU_FREQ, CPU_FREQ_10MHZ); if (error) return error; error = i2c_smbus_write_byte_data(client, PRM_SWOFF_TIME, PRM_SWOFF_TIME_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, ADC_CTRL, ADC_DIV_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, ADC_WAIT, ADC_WAIT_DEFAULT); if (error) return error; /* * Panel setup, these values change with the panel. */ error = i2c_smbus_write_byte_data(client, STEP_X, STEP_X_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, STEP_Y, STEP_Y_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, OFFSET_X, OFFSET_X_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, OFFSET_Y, OFFSET_Y_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, THRESHOLD_TOUCH, THRESHOLD_TOUCH_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, EVR_XY, EVR_XY_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, EVR_X, EVR_X_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, EVR_Y, EVR_Y_DEFAULT); if (error) return error; /* Fixed value settings */ error = i2c_smbus_write_byte_data(client, CALIBRATION_ADJUST, CALIBRATION_ADJUST_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, SWCONT, SWCONT_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, TEST1, DUALTOUCH_STABILIZE_ON | DUALTOUCH_REG_ON); if (error) return error; error = rohm_ts_load_firmware(client, BU21023_FIRMWARE_NAME); if (error) { dev_err(dev, "failed to load firmware: %d\n", error); return error; } /* * Manual calibration results are not changed in same environment. * If the force calibration is performed, * the controller will not require calibration request interrupt * when the typical values are set to the calibration registers. */ error = i2c_smbus_write_byte_data(client, CALIBRATION_REG1, CALIBRATION_REG1_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG2, CALIBRATION_REG2_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, CALIBRATION_REG3, CALIBRATION_REG3_DEFAULT); if (error) return error; error = i2c_smbus_write_byte_data(client, FORCE_CALIBRATION, FORCE_CALIBRATION_OFF); if (error) return error; error = i2c_smbus_write_byte_data(client, FORCE_CALIBRATION, FORCE_CALIBRATION_ON); if (error) return error; /* Clear all interrupts */ error = i2c_smbus_write_byte_data(client, INT_CLEAR, 0xff); if (error) return error; /* Enable coordinates update interrupt */ error = i2c_smbus_write_byte_data(client, INT_MASK, CALIBRATION_DONE | SLEEP_OUT | SLEEP_IN | PROGRAM_LOAD_DONE); if (error) return error; error = i2c_smbus_write_byte_data(client, ERR_MASK, PROGRAM_LOAD_ERR | CPU_TIMEOUT | ADC_TIMEOUT); if (error) return error; /* controller CPU power on */ error = i2c_smbus_write_byte_data(client, SYSTEM, ANALOG_POWER_ON | CPU_POWER_ON); enable_irq(client->irq); return error; } static int rohm_ts_power_off(struct i2c_client *client) { int error; error = i2c_smbus_write_byte_data(client, SYSTEM, ANALOG_POWER_ON | CPU_POWER_OFF); if (error) { dev_err(&client->dev, "failed to power off device CPU: %d\n", error); return error; } error = i2c_smbus_write_byte_data(client, SYSTEM, ANALOG_POWER_OFF | CPU_POWER_OFF); if (error) dev_err(&client->dev, "failed to power off the device: %d\n", error); return error; } static int rohm_ts_open(struct input_dev *input_dev) { struct rohm_ts_data *ts = input_get_drvdata(input_dev); struct i2c_client *client = ts->client; int error; if (!ts->initialized) { error = rohm_ts_device_init(client, ts->setup2); if (error) { dev_err(&client->dev, "device initialization failed: %d\n", error); return error; } ts->initialized = true; } return 0; } static void rohm_ts_close(struct input_dev *input_dev) { struct rohm_ts_data *ts = input_get_drvdata(input_dev); rohm_ts_power_off(ts->client); ts->initialized = false; } static int rohm_bu21023_i2c_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct rohm_ts_data *ts; struct input_dev *input; int error; if (!client->irq) { dev_err(dev, "IRQ is not assigned\n"); return -EINVAL; } if (!client->adapter->algo->master_xfer) { dev_err(dev, "I2C level transfers not supported\n"); return -EOPNOTSUPP; } /* Turn off CPU just in case */ error = rohm_ts_power_off(client); if (error) return error; ts = devm_kzalloc(dev, sizeof(struct rohm_ts_data), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; ts->setup2 = MAF_1SAMPLE; i2c_set_clientdata(client, ts); input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = BU21023_NAME; input->id.bustype = BUS_I2C; input->open = rohm_ts_open; input->close = rohm_ts_close; ts->input = input; input_set_drvdata(input, ts); input_set_abs_params(input, ABS_MT_POSITION_X, ROHM_TS_ABS_X_MIN, ROHM_TS_ABS_X_MAX, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, ROHM_TS_ABS_Y_MIN, ROHM_TS_ABS_Y_MAX, 0, 0); error = input_mt_init_slots(input, MAX_CONTACTS, INPUT_MT_DIRECT | INPUT_MT_TRACK | INPUT_MT_DROP_UNUSED); if (error) { dev_err(dev, "failed to multi touch slots initialization\n"); return error; } error = devm_request_threaded_irq(dev, client->irq, NULL, rohm_ts_soft_irq, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(dev, "failed to request IRQ: %d\n", error); return error; } error = input_register_device(input); if (error) { dev_err(dev, "failed to register input device: %d\n", error); return error; } error = devm_device_add_group(dev, &rohm_ts_attr_group); if (error) { dev_err(dev, "failed to create sysfs group: %d\n", error); return error; } return error; } static const struct i2c_device_id rohm_bu21023_i2c_id[] = { { BU21023_NAME, 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, rohm_bu21023_i2c_id); static struct i2c_driver rohm_bu21023_i2c_driver = { .driver = { .name = BU21023_NAME, }, .probe = rohm_bu21023_i2c_probe, .id_table = rohm_bu21023_i2c_id, }; module_i2c_driver(rohm_bu21023_i2c_driver); MODULE_DESCRIPTION("ROHM BU21023/24 Touchscreen driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("ROHM Co., Ltd.");
linux-master
drivers/input/touchscreen/rohm_bu21023.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for AUO in-cell touchscreens * * Copyright (c) 2011 Heiko Stuebner <[email protected]> * * loosely based on auo_touch.c from Dell Streak vendor-kernel * * Copyright (c) 2008 QUALCOMM Incorporated. * Copyright (c) 2008 QUALCOMM USA, INC. */ #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/jiffies.h> #include <linux/i2c.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/of.h> #include <linux/property.h> /* * Coordinate calculation: * X1 = X1_LSB + X1_MSB*256 * Y1 = Y1_LSB + Y1_MSB*256 * X2 = X2_LSB + X2_MSB*256 * Y2 = Y2_LSB + Y2_MSB*256 */ #define AUO_PIXCIR_REG_X1_LSB 0x00 #define AUO_PIXCIR_REG_X1_MSB 0x01 #define AUO_PIXCIR_REG_Y1_LSB 0x02 #define AUO_PIXCIR_REG_Y1_MSB 0x03 #define AUO_PIXCIR_REG_X2_LSB 0x04 #define AUO_PIXCIR_REG_X2_MSB 0x05 #define AUO_PIXCIR_REG_Y2_LSB 0x06 #define AUO_PIXCIR_REG_Y2_MSB 0x07 #define AUO_PIXCIR_REG_STRENGTH 0x0d #define AUO_PIXCIR_REG_STRENGTH_X1_LSB 0x0e #define AUO_PIXCIR_REG_STRENGTH_X1_MSB 0x0f #define AUO_PIXCIR_REG_RAW_DATA_X 0x2b #define AUO_PIXCIR_REG_RAW_DATA_Y 0x4f #define AUO_PIXCIR_REG_X_SENSITIVITY 0x6f #define AUO_PIXCIR_REG_Y_SENSITIVITY 0x70 #define AUO_PIXCIR_REG_INT_SETTING 0x71 #define AUO_PIXCIR_REG_INT_WIDTH 0x72 #define AUO_PIXCIR_REG_POWER_MODE 0x73 #define AUO_PIXCIR_REG_VERSION 0x77 #define AUO_PIXCIR_REG_CALIBRATE 0x78 #define AUO_PIXCIR_REG_TOUCHAREA_X1 0x1e #define AUO_PIXCIR_REG_TOUCHAREA_Y1 0x1f #define AUO_PIXCIR_REG_TOUCHAREA_X2 0x20 #define AUO_PIXCIR_REG_TOUCHAREA_Y2 0x21 #define AUO_PIXCIR_REG_EEPROM_CALIB_X 0x42 #define AUO_PIXCIR_REG_EEPROM_CALIB_Y 0xad #define AUO_PIXCIR_INT_TPNUM_MASK 0xe0 #define AUO_PIXCIR_INT_TPNUM_SHIFT 5 #define AUO_PIXCIR_INT_RELEASE (1 << 4) #define AUO_PIXCIR_INT_ENABLE (1 << 3) #define AUO_PIXCIR_INT_POL_HIGH (1 << 2) /* * Interrupt modes: * periodical: interrupt is asserted periodicaly * compare coordinates: interrupt is asserted when coordinates change * indicate touch: interrupt is asserted during touch */ #define AUO_PIXCIR_INT_PERIODICAL 0x00 #define AUO_PIXCIR_INT_COMP_COORD 0x01 #define AUO_PIXCIR_INT_TOUCH_IND 0x02 #define AUO_PIXCIR_INT_MODE_MASK 0x03 /* * Power modes: * active: scan speed 60Hz * sleep: scan speed 10Hz can be auto-activated, wakeup on 1st touch * deep sleep: scan speed 1Hz can only be entered or left manually. */ #define AUO_PIXCIR_POWER_ACTIVE 0x00 #define AUO_PIXCIR_POWER_SLEEP 0x01 #define AUO_PIXCIR_POWER_DEEP_SLEEP 0x02 #define AUO_PIXCIR_POWER_MASK 0x03 #define AUO_PIXCIR_POWER_ALLOW_SLEEP (1 << 2) #define AUO_PIXCIR_POWER_IDLE_TIME(ms) ((ms & 0xf) << 4) #define AUO_PIXCIR_CALIBRATE 0x03 #define AUO_PIXCIR_EEPROM_CALIB_X_LEN 62 #define AUO_PIXCIR_EEPROM_CALIB_Y_LEN 36 #define AUO_PIXCIR_RAW_DATA_X_LEN 18 #define AUO_PIXCIR_RAW_DATA_Y_LEN 11 #define AUO_PIXCIR_STRENGTH_ENABLE (1 << 0) /* Touchscreen absolute values */ #define AUO_PIXCIR_REPORT_POINTS 2 #define AUO_PIXCIR_MAX_AREA 0xff #define AUO_PIXCIR_PENUP_TIMEOUT_MS 10 struct auo_pixcir_ts { struct i2c_client *client; struct input_dev *input; struct gpio_desc *gpio_int; struct gpio_desc *gpio_rst; char phys[32]; unsigned int x_max; unsigned int y_max; /* special handling for touch_indicate interrupt mode */ bool touch_ind_mode; wait_queue_head_t wait; bool stopped; }; struct auo_point_t { int coord_x; int coord_y; int area_major; int area_minor; int orientation; }; static int auo_pixcir_collect_data(struct auo_pixcir_ts *ts, struct auo_point_t *point) { struct i2c_client *client = ts->client; uint8_t raw_coord[8]; uint8_t raw_area[4]; int i, ret; /* touch coordinates */ ret = i2c_smbus_read_i2c_block_data(client, AUO_PIXCIR_REG_X1_LSB, 8, raw_coord); if (ret < 0) { dev_err(&client->dev, "failed to read coordinate, %d\n", ret); return ret; } /* touch area */ ret = i2c_smbus_read_i2c_block_data(client, AUO_PIXCIR_REG_TOUCHAREA_X1, 4, raw_area); if (ret < 0) { dev_err(&client->dev, "could not read touch area, %d\n", ret); return ret; } for (i = 0; i < AUO_PIXCIR_REPORT_POINTS; i++) { point[i].coord_x = raw_coord[4 * i + 1] << 8 | raw_coord[4 * i]; point[i].coord_y = raw_coord[4 * i + 3] << 8 | raw_coord[4 * i + 2]; if (point[i].coord_x > ts->x_max || point[i].coord_y > ts->y_max) { dev_warn(&client->dev, "coordinates (%d,%d) invalid\n", point[i].coord_x, point[i].coord_y); point[i].coord_x = point[i].coord_y = 0; } /* determine touch major, minor and orientation */ point[i].area_major = max(raw_area[2 * i], raw_area[2 * i + 1]); point[i].area_minor = min(raw_area[2 * i], raw_area[2 * i + 1]); point[i].orientation = raw_area[2 * i] > raw_area[2 * i + 1]; } return 0; } static irqreturn_t auo_pixcir_interrupt(int irq, void *dev_id) { struct auo_pixcir_ts *ts = dev_id; struct auo_point_t point[AUO_PIXCIR_REPORT_POINTS]; int i; int ret; int fingers = 0; int abs = -1; while (!ts->stopped) { /* check for up event in touch touch_ind_mode */ if (ts->touch_ind_mode) { if (gpiod_get_value_cansleep(ts->gpio_int) == 0) { input_mt_sync(ts->input); input_report_key(ts->input, BTN_TOUCH, 0); input_sync(ts->input); break; } } ret = auo_pixcir_collect_data(ts, point); if (ret < 0) { /* we want to loop only in touch_ind_mode */ if (!ts->touch_ind_mode) break; wait_event_timeout(ts->wait, ts->stopped, msecs_to_jiffies(AUO_PIXCIR_PENUP_TIMEOUT_MS)); continue; } for (i = 0; i < AUO_PIXCIR_REPORT_POINTS; i++) { if (point[i].coord_x > 0 || point[i].coord_y > 0) { input_report_abs(ts->input, ABS_MT_POSITION_X, point[i].coord_x); input_report_abs(ts->input, ABS_MT_POSITION_Y, point[i].coord_y); input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, point[i].area_major); input_report_abs(ts->input, ABS_MT_TOUCH_MINOR, point[i].area_minor); input_report_abs(ts->input, ABS_MT_ORIENTATION, point[i].orientation); input_mt_sync(ts->input); /* use first finger as source for singletouch */ if (fingers == 0) abs = i; /* number of touch points could also be queried * via i2c but would require an additional call */ fingers++; } } input_report_key(ts->input, BTN_TOUCH, fingers > 0); if (abs > -1) { input_report_abs(ts->input, ABS_X, point[abs].coord_x); input_report_abs(ts->input, ABS_Y, point[abs].coord_y); } input_sync(ts->input); /* we want to loop only in touch_ind_mode */ if (!ts->touch_ind_mode) break; wait_event_timeout(ts->wait, ts->stopped, msecs_to_jiffies(AUO_PIXCIR_PENUP_TIMEOUT_MS)); } return IRQ_HANDLED; } /* * Set the power mode of the device. * Valid modes are * - AUO_PIXCIR_POWER_ACTIVE * - AUO_PIXCIR_POWER_SLEEP - automatically left on first touch * - AUO_PIXCIR_POWER_DEEP_SLEEP */ static int auo_pixcir_power_mode(struct auo_pixcir_ts *ts, int mode) { struct i2c_client *client = ts->client; int ret; ret = i2c_smbus_read_byte_data(client, AUO_PIXCIR_REG_POWER_MODE); if (ret < 0) { dev_err(&client->dev, "unable to read reg %Xh, %d\n", AUO_PIXCIR_REG_POWER_MODE, ret); return ret; } ret &= ~AUO_PIXCIR_POWER_MASK; ret |= mode; ret = i2c_smbus_write_byte_data(client, AUO_PIXCIR_REG_POWER_MODE, ret); if (ret) { dev_err(&client->dev, "unable to write reg %Xh, %d\n", AUO_PIXCIR_REG_POWER_MODE, ret); return ret; } return 0; } static int auo_pixcir_int_config(struct auo_pixcir_ts *ts, int int_setting) { struct i2c_client *client = ts->client; int ret; ret = i2c_smbus_read_byte_data(client, AUO_PIXCIR_REG_INT_SETTING); if (ret < 0) { dev_err(&client->dev, "unable to read reg %Xh, %d\n", AUO_PIXCIR_REG_INT_SETTING, ret); return ret; } ret &= ~AUO_PIXCIR_INT_MODE_MASK; ret |= int_setting; ret |= AUO_PIXCIR_INT_POL_HIGH; /* always use high for interrupts */ ret = i2c_smbus_write_byte_data(client, AUO_PIXCIR_REG_INT_SETTING, ret); if (ret < 0) { dev_err(&client->dev, "unable to write reg %Xh, %d\n", AUO_PIXCIR_REG_INT_SETTING, ret); return ret; } ts->touch_ind_mode = int_setting == AUO_PIXCIR_INT_TOUCH_IND; return 0; } /* control the generation of interrupts on the device side */ static int auo_pixcir_int_toggle(struct auo_pixcir_ts *ts, bool enable) { struct i2c_client *client = ts->client; int ret; ret = i2c_smbus_read_byte_data(client, AUO_PIXCIR_REG_INT_SETTING); if (ret < 0) { dev_err(&client->dev, "unable to read reg %Xh, %d\n", AUO_PIXCIR_REG_INT_SETTING, ret); return ret; } if (enable) ret |= AUO_PIXCIR_INT_ENABLE; else ret &= ~AUO_PIXCIR_INT_ENABLE; ret = i2c_smbus_write_byte_data(client, AUO_PIXCIR_REG_INT_SETTING, ret); if (ret < 0) { dev_err(&client->dev, "unable to write reg %Xh, %d\n", AUO_PIXCIR_REG_INT_SETTING, ret); return ret; } return 0; } static int auo_pixcir_start(struct auo_pixcir_ts *ts) { struct i2c_client *client = ts->client; int ret; ret = auo_pixcir_power_mode(ts, AUO_PIXCIR_POWER_ACTIVE); if (ret < 0) { dev_err(&client->dev, "could not set power mode, %d\n", ret); return ret; } ts->stopped = false; mb(); enable_irq(client->irq); ret = auo_pixcir_int_toggle(ts, 1); if (ret < 0) { dev_err(&client->dev, "could not enable interrupt, %d\n", ret); disable_irq(client->irq); return ret; } return 0; } static int auo_pixcir_stop(struct auo_pixcir_ts *ts) { struct i2c_client *client = ts->client; int ret; ret = auo_pixcir_int_toggle(ts, 0); if (ret < 0) { dev_err(&client->dev, "could not disable interrupt, %d\n", ret); return ret; } /* disable receiving of interrupts */ disable_irq(client->irq); ts->stopped = true; mb(); wake_up(&ts->wait); return auo_pixcir_power_mode(ts, AUO_PIXCIR_POWER_DEEP_SLEEP); } static int auo_pixcir_input_open(struct input_dev *dev) { struct auo_pixcir_ts *ts = input_get_drvdata(dev); return auo_pixcir_start(ts); } static void auo_pixcir_input_close(struct input_dev *dev) { struct auo_pixcir_ts *ts = input_get_drvdata(dev); auo_pixcir_stop(ts); } static int auo_pixcir_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct auo_pixcir_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); /* when configured as wakeup source, device should always wake system * therefore start device if necessary */ if (device_may_wakeup(&client->dev)) { /* need to start device if not open, to be wakeup source */ if (!input_device_enabled(input)) { ret = auo_pixcir_start(ts); if (ret) goto unlock; } enable_irq_wake(client->irq); ret = auo_pixcir_power_mode(ts, AUO_PIXCIR_POWER_SLEEP); } else if (input_device_enabled(input)) { ret = auo_pixcir_stop(ts); } unlock: mutex_unlock(&input->mutex); return ret; } static int auo_pixcir_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct auo_pixcir_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); if (device_may_wakeup(&client->dev)) { disable_irq_wake(client->irq); /* need to stop device if it was not open on suspend */ if (!input_device_enabled(input)) { ret = auo_pixcir_stop(ts); if (ret) goto unlock; } /* device wakes automatically from SLEEP */ } else if (input_device_enabled(input)) { ret = auo_pixcir_start(ts); } unlock: mutex_unlock(&input->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(auo_pixcir_pm_ops, auo_pixcir_suspend, auo_pixcir_resume); static void auo_pixcir_reset(void *data) { struct auo_pixcir_ts *ts = data; gpiod_set_value_cansleep(ts->gpio_rst, 1); } static int auo_pixcir_probe(struct i2c_client *client) { struct auo_pixcir_ts *ts; struct input_dev *input_dev; int version; int error; ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) { dev_err(&client->dev, "could not allocate input device\n"); return -ENOMEM; } ts->client = client; ts->input = input_dev; ts->touch_ind_mode = 0; ts->stopped = true; init_waitqueue_head(&ts->wait); snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); if (device_property_read_u32(&client->dev, "x-size", &ts->x_max)) { dev_err(&client->dev, "failed to get x-size property\n"); return -EINVAL; } if (device_property_read_u32(&client->dev, "y-size", &ts->y_max)) { dev_err(&client->dev, "failed to get y-size property\n"); return -EINVAL; } input_dev->name = "AUO-Pixcir touchscreen"; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_I2C; input_dev->open = auo_pixcir_input_open; input_dev->close = auo_pixcir_input_close; __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); /* For single touch */ input_set_abs_params(input_dev, ABS_X, 0, ts->x_max, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, ts->y_max, 0, 0); /* For multi touch */ input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, ts->x_max, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, ts->y_max, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, AUO_PIXCIR_MAX_AREA, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR, 0, AUO_PIXCIR_MAX_AREA, 0, 0); input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 1, 0, 0); input_set_drvdata(ts->input, ts); ts->gpio_int = devm_gpiod_get_index(&client->dev, NULL, 0, GPIOD_IN); error = PTR_ERR_OR_ZERO(ts->gpio_int); if (error) { dev_err(&client->dev, "request of int gpio failed: %d\n", error); return error; } gpiod_set_consumer_name(ts->gpio_int, "auo_pixcir_ts_int"); /* Take the chip out of reset */ ts->gpio_rst = devm_gpiod_get_index(&client->dev, NULL, 1, GPIOD_OUT_LOW); error = PTR_ERR_OR_ZERO(ts->gpio_rst); if (error) { dev_err(&client->dev, "request of reset gpio failed: %d\n", error); return error; } gpiod_set_consumer_name(ts->gpio_rst, "auo_pixcir_ts_rst"); error = devm_add_action_or_reset(&client->dev, auo_pixcir_reset, ts); if (error) { dev_err(&client->dev, "failed to register reset action, %d\n", error); return error; } msleep(200); version = i2c_smbus_read_byte_data(client, AUO_PIXCIR_REG_VERSION); if (version < 0) { error = version; return error; } dev_info(&client->dev, "firmware version 0x%X\n", version); /* default to asserting the interrupt when the screen is touched */ error = auo_pixcir_int_config(ts, AUO_PIXCIR_INT_TOUCH_IND); if (error) return error; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, auo_pixcir_interrupt, IRQF_ONESHOT, input_dev->name, ts); if (error) { dev_err(&client->dev, "irq %d requested failed, %d\n", client->irq, error); return error; } /* stop device and put it into deep sleep until it is opened */ error = auo_pixcir_stop(ts); if (error) return error; error = input_register_device(input_dev); if (error) { dev_err(&client->dev, "could not register input device, %d\n", error); return error; } i2c_set_clientdata(client, ts); return 0; } static const struct i2c_device_id auo_pixcir_idtable[] = { { "auo_pixcir_ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, auo_pixcir_idtable); #ifdef CONFIG_OF static const struct of_device_id auo_pixcir_ts_dt_idtable[] = { { .compatible = "auo,auo_pixcir_ts" }, {}, }; MODULE_DEVICE_TABLE(of, auo_pixcir_ts_dt_idtable); #endif static struct i2c_driver auo_pixcir_driver = { .driver = { .name = "auo_pixcir_ts", .pm = pm_sleep_ptr(&auo_pixcir_pm_ops), .of_match_table = of_match_ptr(auo_pixcir_ts_dt_idtable), }, .probe = auo_pixcir_probe, .id_table = auo_pixcir_idtable, }; module_i2c_driver(auo_pixcir_driver); MODULE_DESCRIPTION("AUO-PIXCIR touchscreen driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Heiko Stuebner <[email protected]>");
linux-master
drivers/input/touchscreen/auo-pixcir-ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Freescale MXS LRADC touchscreen driver * * Copyright (c) 2012 DENX Software Engineering, GmbH. * Copyright (c) 2017 Ksenija Stanojevic <[email protected]> * * Authors: * Marek Vasut <[email protected]> * Ksenija Stanojevic <[email protected]> */ #include <linux/device.h> #include <linux/err.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/mfd/core.h> #include <linux/mfd/mxs-lradc.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/platform_device.h> static const char * const mxs_lradc_ts_irq_names[] = { "mxs-lradc-touchscreen", "mxs-lradc-channel6", "mxs-lradc-channel7", }; /* * Touchscreen handling */ enum mxs_lradc_ts_plate { LRADC_TOUCH = 0, LRADC_SAMPLE_X, LRADC_SAMPLE_Y, LRADC_SAMPLE_PRESSURE, LRADC_SAMPLE_VALID, }; struct mxs_lradc_ts { struct mxs_lradc *lradc; struct device *dev; void __iomem *base; /* * When the touchscreen is enabled, we give it two private virtual * channels: #6 and #7. This means that only 6 virtual channels (instead * of 8) will be available for buffered capture. */ #define TOUCHSCREEN_VCHANNEL1 7 #define TOUCHSCREEN_VCHANNEL2 6 struct input_dev *ts_input; enum mxs_lradc_ts_plate cur_plate; /* state machine */ bool ts_valid; unsigned int ts_x_pos; unsigned int ts_y_pos; unsigned int ts_pressure; /* handle touchscreen's physical behaviour */ /* samples per coordinate */ unsigned int over_sample_cnt; /* time clocks between samples */ unsigned int over_sample_delay; /* time in clocks to wait after the plates where switched */ unsigned int settling_delay; spinlock_t lock; }; struct state_info { u32 mask; u32 bit; u32 x_plate; u32 y_plate; u32 pressure; }; static struct state_info info[] = { {LRADC_CTRL0_MX23_PLATE_MASK, LRADC_CTRL0_MX23_TOUCH_DETECT_ENABLE, LRADC_CTRL0_MX23_XP | LRADC_CTRL0_MX23_XM, LRADC_CTRL0_MX23_YP | LRADC_CTRL0_MX23_YM, LRADC_CTRL0_MX23_YP | LRADC_CTRL0_MX23_XM}, {LRADC_CTRL0_MX28_PLATE_MASK, LRADC_CTRL0_MX28_TOUCH_DETECT_ENABLE, LRADC_CTRL0_MX28_XPPSW | LRADC_CTRL0_MX28_XNNSW, LRADC_CTRL0_MX28_YPPSW | LRADC_CTRL0_MX28_YNNSW, LRADC_CTRL0_MX28_YPPSW | LRADC_CTRL0_MX28_XNNSW} }; static bool mxs_lradc_check_touch_event(struct mxs_lradc_ts *ts) { return !!(readl(ts->base + LRADC_STATUS) & LRADC_STATUS_TOUCH_DETECT_RAW); } static void mxs_lradc_map_ts_channel(struct mxs_lradc_ts *ts, unsigned int vch, unsigned int ch) { writel(LRADC_CTRL4_LRADCSELECT_MASK(vch), ts->base + LRADC_CTRL4 + STMP_OFFSET_REG_CLR); writel(LRADC_CTRL4_LRADCSELECT(vch, ch), ts->base + LRADC_CTRL4 + STMP_OFFSET_REG_SET); } static void mxs_lradc_setup_ts_channel(struct mxs_lradc_ts *ts, unsigned int ch) { /* * prepare for oversampling conversion * * from the datasheet: * "The ACCUMULATE bit in the appropriate channel register * HW_LRADC_CHn must be set to 1 if NUM_SAMPLES is greater then 0; * otherwise, the IRQs will not fire." */ writel(LRADC_CH_ACCUMULATE | LRADC_CH_NUM_SAMPLES(ts->over_sample_cnt - 1), ts->base + LRADC_CH(ch)); /* from the datasheet: * "Software must clear this register in preparation for a * multi-cycle accumulation. */ writel(LRADC_CH_VALUE_MASK, ts->base + LRADC_CH(ch) + STMP_OFFSET_REG_CLR); /* * prepare the delay/loop unit according to the oversampling count * * from the datasheet: * "The DELAY fields in HW_LRADC_DELAY0, HW_LRADC_DELAY1, * HW_LRADC_DELAY2, and HW_LRADC_DELAY3 must be non-zero; otherwise, * the LRADC will not trigger the delay group." */ writel(LRADC_DELAY_TRIGGER(1 << ch) | LRADC_DELAY_TRIGGER_DELAYS(0) | LRADC_DELAY_LOOP(ts->over_sample_cnt - 1) | LRADC_DELAY_DELAY(ts->over_sample_delay - 1), ts->base + LRADC_DELAY(3)); writel(LRADC_CTRL1_LRADC_IRQ(ch), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); /* * after changing the touchscreen plates setting * the signals need some initial time to settle. Start the * SoC's delay unit and start the conversion later * and automatically. */ writel(LRADC_DELAY_TRIGGER(0) | LRADC_DELAY_TRIGGER_DELAYS(BIT(3)) | LRADC_DELAY_KICK | LRADC_DELAY_DELAY(ts->settling_delay), ts->base + LRADC_DELAY(2)); } /* * Pressure detection is special: * We want to do both required measurements for the pressure detection in * one turn. Use the hardware features to chain both conversions and let the * hardware report one interrupt if both conversions are done */ static void mxs_lradc_setup_ts_pressure(struct mxs_lradc_ts *ts, unsigned int ch1, unsigned int ch2) { u32 reg; /* * prepare for oversampling conversion * * from the datasheet: * "The ACCUMULATE bit in the appropriate channel register * HW_LRADC_CHn must be set to 1 if NUM_SAMPLES is greater then 0; * otherwise, the IRQs will not fire." */ reg = LRADC_CH_ACCUMULATE | LRADC_CH_NUM_SAMPLES(ts->over_sample_cnt - 1); writel(reg, ts->base + LRADC_CH(ch1)); writel(reg, ts->base + LRADC_CH(ch2)); /* from the datasheet: * "Software must clear this register in preparation for a * multi-cycle accumulation. */ writel(LRADC_CH_VALUE_MASK, ts->base + LRADC_CH(ch1) + STMP_OFFSET_REG_CLR); writel(LRADC_CH_VALUE_MASK, ts->base + LRADC_CH(ch2) + STMP_OFFSET_REG_CLR); /* prepare the delay/loop unit according to the oversampling count */ writel(LRADC_DELAY_TRIGGER(1 << ch1) | LRADC_DELAY_TRIGGER(1 << ch2) | LRADC_DELAY_TRIGGER_DELAYS(0) | LRADC_DELAY_LOOP(ts->over_sample_cnt - 1) | LRADC_DELAY_DELAY(ts->over_sample_delay - 1), ts->base + LRADC_DELAY(3)); writel(LRADC_CTRL1_LRADC_IRQ(ch2), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); /* * after changing the touchscreen plates setting * the signals need some initial time to settle. Start the * SoC's delay unit and start the conversion later * and automatically. */ writel(LRADC_DELAY_TRIGGER(0) | LRADC_DELAY_TRIGGER_DELAYS(BIT(3)) | LRADC_DELAY_KICK | LRADC_DELAY_DELAY(ts->settling_delay), ts->base + LRADC_DELAY(2)); } static unsigned int mxs_lradc_ts_read_raw_channel(struct mxs_lradc_ts *ts, unsigned int channel) { u32 reg; unsigned int num_samples, val; reg = readl(ts->base + LRADC_CH(channel)); if (reg & LRADC_CH_ACCUMULATE) num_samples = ts->over_sample_cnt; else num_samples = 1; val = (reg & LRADC_CH_VALUE_MASK) >> LRADC_CH_VALUE_OFFSET; return val / num_samples; } static unsigned int mxs_lradc_read_ts_pressure(struct mxs_lradc_ts *ts, unsigned int ch1, unsigned int ch2) { u32 reg, mask; unsigned int pressure, m1, m2; mask = LRADC_CTRL1_LRADC_IRQ(ch1) | LRADC_CTRL1_LRADC_IRQ(ch2); reg = readl(ts->base + LRADC_CTRL1) & mask; while (reg != mask) { reg = readl(ts->base + LRADC_CTRL1) & mask; dev_dbg(ts->dev, "One channel is still busy: %X\n", reg); } m1 = mxs_lradc_ts_read_raw_channel(ts, ch1); m2 = mxs_lradc_ts_read_raw_channel(ts, ch2); if (m2 == 0) { dev_warn(ts->dev, "Cannot calculate pressure\n"); return 1 << (LRADC_RESOLUTION - 1); } /* simply scale the value from 0 ... max ADC resolution */ pressure = m1; pressure *= (1 << LRADC_RESOLUTION); pressure /= m2; dev_dbg(ts->dev, "Pressure = %u\n", pressure); return pressure; } #define TS_CH_XP 2 #define TS_CH_YP 3 #define TS_CH_XM 4 #define TS_CH_YM 5 /* * YP(open)--+-------------+ * | |--+ * | | | * YM(-)--+-------------+ | * +--------------+ * | | * XP(weak+) XM(open) * * "weak+" means 200k Ohm VDDIO * (-) means GND */ static void mxs_lradc_setup_touch_detection(struct mxs_lradc_ts *ts) { struct mxs_lradc *lradc = ts->lradc; /* * In order to detect a touch event the 'touch detect enable' bit * enables: * - a weak pullup to the X+ connector * - a strong ground at the Y- connector */ writel(info[lradc->soc].mask, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); writel(info[lradc->soc].bit, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_SET); } /* * YP(meas)--+-------------+ * | |--+ * | | | * YM(open)--+-------------+ | * +--------------+ * | | * XP(+) XM(-) * * (+) means here 1.85 V * (-) means here GND */ static void mxs_lradc_prepare_x_pos(struct mxs_lradc_ts *ts) { struct mxs_lradc *lradc = ts->lradc; writel(info[lradc->soc].mask, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); writel(info[lradc->soc].x_plate, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_SET); ts->cur_plate = LRADC_SAMPLE_X; mxs_lradc_map_ts_channel(ts, TOUCHSCREEN_VCHANNEL1, TS_CH_YP); mxs_lradc_setup_ts_channel(ts, TOUCHSCREEN_VCHANNEL1); } /* * YP(+)--+-------------+ * | |--+ * | | | * YM(-)--+-------------+ | * +--------------+ * | | * XP(open) XM(meas) * * (+) means here 1.85 V * (-) means here GND */ static void mxs_lradc_prepare_y_pos(struct mxs_lradc_ts *ts) { struct mxs_lradc *lradc = ts->lradc; writel(info[lradc->soc].mask, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); writel(info[lradc->soc].y_plate, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_SET); ts->cur_plate = LRADC_SAMPLE_Y; mxs_lradc_map_ts_channel(ts, TOUCHSCREEN_VCHANNEL1, TS_CH_XM); mxs_lradc_setup_ts_channel(ts, TOUCHSCREEN_VCHANNEL1); } /* * YP(+)--+-------------+ * | |--+ * | | | * YM(meas)--+-------------+ | * +--------------+ * | | * XP(meas) XM(-) * * (+) means here 1.85 V * (-) means here GND */ static void mxs_lradc_prepare_pressure(struct mxs_lradc_ts *ts) { struct mxs_lradc *lradc = ts->lradc; writel(info[lradc->soc].mask, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); writel(info[lradc->soc].pressure, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_SET); ts->cur_plate = LRADC_SAMPLE_PRESSURE; mxs_lradc_map_ts_channel(ts, TOUCHSCREEN_VCHANNEL1, TS_CH_YM); mxs_lradc_map_ts_channel(ts, TOUCHSCREEN_VCHANNEL2, TS_CH_XP); mxs_lradc_setup_ts_pressure(ts, TOUCHSCREEN_VCHANNEL2, TOUCHSCREEN_VCHANNEL1); } static void mxs_lradc_enable_touch_detection(struct mxs_lradc_ts *ts) { mxs_lradc_setup_touch_detection(ts); ts->cur_plate = LRADC_TOUCH; writel(LRADC_CTRL1_TOUCH_DETECT_IRQ | LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); writel(LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_SET); } static void mxs_lradc_start_touch_event(struct mxs_lradc_ts *ts) { writel(LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); writel(LRADC_CTRL1_LRADC_IRQ_EN(TOUCHSCREEN_VCHANNEL1), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_SET); /* * start with the Y-pos, because it uses nearly the same plate * settings like the touch detection */ mxs_lradc_prepare_y_pos(ts); } static void mxs_lradc_report_ts_event(struct mxs_lradc_ts *ts) { input_report_abs(ts->ts_input, ABS_X, ts->ts_x_pos); input_report_abs(ts->ts_input, ABS_Y, ts->ts_y_pos); input_report_abs(ts->ts_input, ABS_PRESSURE, ts->ts_pressure); input_report_key(ts->ts_input, BTN_TOUCH, 1); input_sync(ts->ts_input); } static void mxs_lradc_complete_touch_event(struct mxs_lradc_ts *ts) { mxs_lradc_setup_touch_detection(ts); ts->cur_plate = LRADC_SAMPLE_VALID; /* * start a dummy conversion to burn time to settle the signals * note: we are not interested in the conversion's value */ writel(0, ts->base + LRADC_CH(TOUCHSCREEN_VCHANNEL1)); writel(LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL1) | LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL2), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); writel(LRADC_DELAY_TRIGGER(1 << TOUCHSCREEN_VCHANNEL1) | LRADC_DELAY_KICK | LRADC_DELAY_DELAY(10), ts->base + LRADC_DELAY(2)); } /* * in order to avoid false measurements, report only samples where * the surface is still touched after the position measurement */ static void mxs_lradc_finish_touch_event(struct mxs_lradc_ts *ts, bool valid) { /* if it is still touched, report the sample */ if (valid && mxs_lradc_check_touch_event(ts)) { ts->ts_valid = true; mxs_lradc_report_ts_event(ts); } /* if it is even still touched, continue with the next measurement */ if (mxs_lradc_check_touch_event(ts)) { mxs_lradc_prepare_y_pos(ts); return; } if (ts->ts_valid) { /* signal the release */ ts->ts_valid = false; input_report_key(ts->ts_input, BTN_TOUCH, 0); input_sync(ts->ts_input); } /* if it is released, wait for the next touch via IRQ */ ts->cur_plate = LRADC_TOUCH; writel(0, ts->base + LRADC_DELAY(2)); writel(0, ts->base + LRADC_DELAY(3)); writel(LRADC_CTRL1_TOUCH_DETECT_IRQ | LRADC_CTRL1_LRADC_IRQ_EN(TOUCHSCREEN_VCHANNEL1) | LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL1), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); writel(LRADC_CTRL1_TOUCH_DETECT_IRQ_EN, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_SET); } /* touchscreen's state machine */ static void mxs_lradc_handle_touch(struct mxs_lradc_ts *ts) { switch (ts->cur_plate) { case LRADC_TOUCH: if (mxs_lradc_check_touch_event(ts)) mxs_lradc_start_touch_event(ts); writel(LRADC_CTRL1_TOUCH_DETECT_IRQ, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); return; case LRADC_SAMPLE_Y: ts->ts_y_pos = mxs_lradc_ts_read_raw_channel(ts, TOUCHSCREEN_VCHANNEL1); mxs_lradc_prepare_x_pos(ts); return; case LRADC_SAMPLE_X: ts->ts_x_pos = mxs_lradc_ts_read_raw_channel(ts, TOUCHSCREEN_VCHANNEL1); mxs_lradc_prepare_pressure(ts); return; case LRADC_SAMPLE_PRESSURE: ts->ts_pressure = mxs_lradc_read_ts_pressure(ts, TOUCHSCREEN_VCHANNEL2, TOUCHSCREEN_VCHANNEL1); mxs_lradc_complete_touch_event(ts); return; case LRADC_SAMPLE_VALID: mxs_lradc_finish_touch_event(ts, 1); break; } } /* IRQ Handling */ static irqreturn_t mxs_lradc_ts_handle_irq(int irq, void *data) { struct mxs_lradc_ts *ts = data; struct mxs_lradc *lradc = ts->lradc; unsigned long reg = readl(ts->base + LRADC_CTRL1); u32 clr_irq = mxs_lradc_irq_mask(lradc); const u32 ts_irq_mask = LRADC_CTRL1_TOUCH_DETECT_IRQ | LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL1) | LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL2); unsigned long flags; if (!(reg & mxs_lradc_irq_mask(lradc))) return IRQ_NONE; if (reg & ts_irq_mask) { spin_lock_irqsave(&ts->lock, flags); mxs_lradc_handle_touch(ts); spin_unlock_irqrestore(&ts->lock, flags); /* Make sure we don't clear the next conversion's interrupt. */ clr_irq &= ~(LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL1) | LRADC_CTRL1_LRADC_IRQ(TOUCHSCREEN_VCHANNEL2)); writel(reg & clr_irq, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); } return IRQ_HANDLED; } static int mxs_lradc_ts_open(struct input_dev *dev) { struct mxs_lradc_ts *ts = input_get_drvdata(dev); /* Enable the touch-detect circuitry. */ mxs_lradc_enable_touch_detection(ts); return 0; } static void mxs_lradc_ts_stop(struct mxs_lradc_ts *ts) { int i; struct mxs_lradc *lradc = ts->lradc; /* stop all interrupts from firing */ writel(LRADC_CTRL1_TOUCH_DETECT_IRQ_EN | LRADC_CTRL1_LRADC_IRQ_EN(TOUCHSCREEN_VCHANNEL1) | LRADC_CTRL1_LRADC_IRQ_EN(TOUCHSCREEN_VCHANNEL2), ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); /* Power-down touchscreen touch-detect circuitry. */ writel(info[lradc->soc].mask, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); writel(lradc->buffer_vchans << LRADC_CTRL1_LRADC_IRQ_EN_OFFSET, ts->base + LRADC_CTRL1 + STMP_OFFSET_REG_CLR); for (i = 1; i < LRADC_MAX_DELAY_CHANS; i++) writel(0, ts->base + LRADC_DELAY(i)); } static void mxs_lradc_ts_close(struct input_dev *dev) { struct mxs_lradc_ts *ts = input_get_drvdata(dev); mxs_lradc_ts_stop(ts); } static void mxs_lradc_ts_hw_init(struct mxs_lradc_ts *ts) { struct mxs_lradc *lradc = ts->lradc; /* Configure the touchscreen type */ if (lradc->soc == IMX28_LRADC) { writel(LRADC_CTRL0_MX28_TOUCH_SCREEN_TYPE, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_CLR); if (lradc->touchscreen_wire == MXS_LRADC_TOUCHSCREEN_5WIRE) writel(LRADC_CTRL0_MX28_TOUCH_SCREEN_TYPE, ts->base + LRADC_CTRL0 + STMP_OFFSET_REG_SET); } } static int mxs_lradc_ts_register(struct mxs_lradc_ts *ts) { struct input_dev *input; struct device *dev = ts->dev; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = "mxs-lradc-ts"; input->id.bustype = BUS_HOST; input->open = mxs_lradc_ts_open; input->close = mxs_lradc_ts_close; __set_bit(INPUT_PROP_DIRECT, input->propbit); input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, 0, LRADC_SINGLE_SAMPLE_MASK, 0, 0); input_set_abs_params(input, ABS_Y, 0, LRADC_SINGLE_SAMPLE_MASK, 0, 0); input_set_abs_params(input, ABS_PRESSURE, 0, LRADC_SINGLE_SAMPLE_MASK, 0, 0); ts->ts_input = input; input_set_drvdata(input, ts); return input_register_device(input); } static int mxs_lradc_ts_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->parent->of_node; struct mxs_lradc *lradc = dev_get_drvdata(dev->parent); struct mxs_lradc_ts *ts; int ret, irq, virq, i; u32 ts_wires = 0, adapt; ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; platform_set_drvdata(pdev, ts); ts->lradc = lradc; ts->dev = dev; spin_lock_init(&ts->lock); ts->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(ts->base)) return PTR_ERR(ts->base); ret = of_property_read_u32(node, "fsl,lradc-touchscreen-wires", &ts_wires); if (ret) return ret; if (of_property_read_u32(node, "fsl,ave-ctrl", &adapt)) { ts->over_sample_cnt = 4; } else { if (adapt >= 1 && adapt <= 32) { ts->over_sample_cnt = adapt; } else { dev_err(ts->dev, "Invalid sample count (%u)\n", adapt); return -EINVAL; } } if (of_property_read_u32(node, "fsl,ave-delay", &adapt)) { ts->over_sample_delay = 2; } else { if (adapt >= 2 && adapt <= LRADC_DELAY_DELAY_MASK + 1) { ts->over_sample_delay = adapt; } else { dev_err(ts->dev, "Invalid sample delay (%u)\n", adapt); return -EINVAL; } } if (of_property_read_u32(node, "fsl,settling", &adapt)) { ts->settling_delay = 10; } else { if (adapt >= 1 && adapt <= LRADC_DELAY_DELAY_MASK) { ts->settling_delay = adapt; } else { dev_err(ts->dev, "Invalid settling delay (%u)\n", adapt); return -EINVAL; } } ret = stmp_reset_block(ts->base); if (ret) return ret; mxs_lradc_ts_hw_init(ts); for (i = 0; i < 3; i++) { irq = platform_get_irq_byname(pdev, mxs_lradc_ts_irq_names[i]); if (irq < 0) return irq; virq = irq_of_parse_and_map(node, irq); mxs_lradc_ts_stop(ts); ret = devm_request_irq(dev, virq, mxs_lradc_ts_handle_irq, 0, mxs_lradc_ts_irq_names[i], ts); if (ret) return ret; } return mxs_lradc_ts_register(ts); } static struct platform_driver mxs_lradc_ts_driver = { .driver = { .name = "mxs-lradc-ts", }, .probe = mxs_lradc_ts_probe, }; module_platform_driver(mxs_lradc_ts_driver); MODULE_AUTHOR("Marek Vasut <[email protected]>"); MODULE_DESCRIPTION("Freescale MXS LRADC touchscreen driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:mxs-lradc-ts");
linux-master
drivers/input/touchscreen/mxs-lradc-ts.c
// SPDX-License-Identifier: GPL-2.0 // STMicroelectronics FTS Touchscreen device driver // // Copyright (c) 2017 Samsung Electronics Co., Ltd. // Copyright (c) 2017 Andi Shyti <[email protected]> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/leds.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> /* I2C commands */ #define STMFTS_READ_INFO 0x80 #define STMFTS_READ_STATUS 0x84 #define STMFTS_READ_ONE_EVENT 0x85 #define STMFTS_READ_ALL_EVENT 0x86 #define STMFTS_LATEST_EVENT 0x87 #define STMFTS_SLEEP_IN 0x90 #define STMFTS_SLEEP_OUT 0x91 #define STMFTS_MS_MT_SENSE_OFF 0x92 #define STMFTS_MS_MT_SENSE_ON 0x93 #define STMFTS_SS_HOVER_SENSE_OFF 0x94 #define STMFTS_SS_HOVER_SENSE_ON 0x95 #define STMFTS_MS_KEY_SENSE_OFF 0x9a #define STMFTS_MS_KEY_SENSE_ON 0x9b #define STMFTS_SYSTEM_RESET 0xa0 #define STMFTS_CLEAR_EVENT_STACK 0xa1 #define STMFTS_FULL_FORCE_CALIBRATION 0xa2 #define STMFTS_MS_CX_TUNING 0xa3 #define STMFTS_SS_CX_TUNING 0xa4 /* events */ #define STMFTS_EV_NO_EVENT 0x00 #define STMFTS_EV_MULTI_TOUCH_DETECTED 0x02 #define STMFTS_EV_MULTI_TOUCH_ENTER 0x03 #define STMFTS_EV_MULTI_TOUCH_LEAVE 0x04 #define STMFTS_EV_MULTI_TOUCH_MOTION 0x05 #define STMFTS_EV_HOVER_ENTER 0x07 #define STMFTS_EV_HOVER_LEAVE 0x08 #define STMFTS_EV_HOVER_MOTION 0x09 #define STMFTS_EV_KEY_STATUS 0x0e #define STMFTS_EV_ERROR 0x0f #define STMFTS_EV_CONTROLLER_READY 0x10 #define STMFTS_EV_SLEEP_OUT_CONTROLLER_READY 0x11 #define STMFTS_EV_STATUS 0x16 #define STMFTS_EV_DEBUG 0xdb /* multi touch related event masks */ #define STMFTS_MASK_EVENT_ID 0x0f #define STMFTS_MASK_TOUCH_ID 0xf0 #define STMFTS_MASK_LEFT_EVENT 0x0f #define STMFTS_MASK_X_MSB 0x0f #define STMFTS_MASK_Y_LSB 0xf0 /* key related event masks */ #define STMFTS_MASK_KEY_NO_TOUCH 0x00 #define STMFTS_MASK_KEY_MENU 0x01 #define STMFTS_MASK_KEY_BACK 0x02 #define STMFTS_EVENT_SIZE 8 #define STMFTS_STACK_DEPTH 32 #define STMFTS_DATA_MAX_SIZE (STMFTS_EVENT_SIZE * STMFTS_STACK_DEPTH) #define STMFTS_MAX_FINGERS 10 #define STMFTS_DEV_NAME "stmfts" enum stmfts_regulators { STMFTS_REGULATOR_VDD, STMFTS_REGULATOR_AVDD, }; struct stmfts_data { struct i2c_client *client; struct input_dev *input; struct led_classdev led_cdev; struct mutex mutex; struct touchscreen_properties prop; struct regulator_bulk_data regulators[2]; /* * Presence of ledvdd will be used also to check * whether the LED is supported. */ struct regulator *ledvdd; u16 chip_id; u8 chip_ver; u16 fw_ver; u8 config_id; u8 config_ver; u8 data[STMFTS_DATA_MAX_SIZE]; struct completion cmd_done; bool use_key; bool led_status; bool hover_enabled; bool running; }; static int stmfts_brightness_set(struct led_classdev *led_cdev, enum led_brightness value) { struct stmfts_data *sdata = container_of(led_cdev, struct stmfts_data, led_cdev); int err; if (value != sdata->led_status && sdata->ledvdd) { if (!value) { regulator_disable(sdata->ledvdd); } else { err = regulator_enable(sdata->ledvdd); if (err) { dev_warn(&sdata->client->dev, "failed to disable ledvdd regulator: %d\n", err); return err; } } sdata->led_status = value; } return 0; } static enum led_brightness stmfts_brightness_get(struct led_classdev *led_cdev) { struct stmfts_data *sdata = container_of(led_cdev, struct stmfts_data, led_cdev); return !!regulator_is_enabled(sdata->ledvdd); } /* * We can't simply use i2c_smbus_read_i2c_block_data because we * need to read more than 255 bytes ( */ static int stmfts_read_events(struct stmfts_data *sdata) { u8 cmd = STMFTS_READ_ALL_EVENT; struct i2c_msg msgs[2] = { { .addr = sdata->client->addr, .len = 1, .buf = &cmd, }, { .addr = sdata->client->addr, .flags = I2C_M_RD, .len = STMFTS_DATA_MAX_SIZE, .buf = sdata->data, }, }; int ret; ret = i2c_transfer(sdata->client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) return ret; return ret == ARRAY_SIZE(msgs) ? 0 : -EIO; } static void stmfts_report_contact_event(struct stmfts_data *sdata, const u8 event[]) { u8 slot_id = (event[0] & STMFTS_MASK_TOUCH_ID) >> 4; u16 x = event[1] | ((event[2] & STMFTS_MASK_X_MSB) << 8); u16 y = (event[2] >> 4) | (event[3] << 4); u8 maj = event[4]; u8 min = event[5]; u8 orientation = event[6]; u8 area = event[7]; input_mt_slot(sdata->input, slot_id); input_mt_report_slot_state(sdata->input, MT_TOOL_FINGER, true); input_report_abs(sdata->input, ABS_MT_POSITION_X, x); input_report_abs(sdata->input, ABS_MT_POSITION_Y, y); input_report_abs(sdata->input, ABS_MT_TOUCH_MAJOR, maj); input_report_abs(sdata->input, ABS_MT_TOUCH_MINOR, min); input_report_abs(sdata->input, ABS_MT_PRESSURE, area); input_report_abs(sdata->input, ABS_MT_ORIENTATION, orientation); input_sync(sdata->input); } static void stmfts_report_contact_release(struct stmfts_data *sdata, const u8 event[]) { u8 slot_id = (event[0] & STMFTS_MASK_TOUCH_ID) >> 4; input_mt_slot(sdata->input, slot_id); input_mt_report_slot_inactive(sdata->input); input_sync(sdata->input); } static void stmfts_report_hover_event(struct stmfts_data *sdata, const u8 event[]) { u16 x = (event[2] << 4) | (event[4] >> 4); u16 y = (event[3] << 4) | (event[4] & STMFTS_MASK_Y_LSB); u8 z = event[5]; input_report_abs(sdata->input, ABS_X, x); input_report_abs(sdata->input, ABS_Y, y); input_report_abs(sdata->input, ABS_DISTANCE, z); input_sync(sdata->input); } static void stmfts_report_key_event(struct stmfts_data *sdata, const u8 event[]) { switch (event[2]) { case 0: input_report_key(sdata->input, KEY_BACK, 0); input_report_key(sdata->input, KEY_MENU, 0); break; case STMFTS_MASK_KEY_BACK: input_report_key(sdata->input, KEY_BACK, 1); break; case STMFTS_MASK_KEY_MENU: input_report_key(sdata->input, KEY_MENU, 1); break; default: dev_warn(&sdata->client->dev, "unknown key event: %#02x\n", event[2]); break; } input_sync(sdata->input); } static void stmfts_parse_events(struct stmfts_data *sdata) { int i; for (i = 0; i < STMFTS_STACK_DEPTH; i++) { u8 *event = &sdata->data[i * STMFTS_EVENT_SIZE]; switch (event[0]) { case STMFTS_EV_CONTROLLER_READY: case STMFTS_EV_SLEEP_OUT_CONTROLLER_READY: case STMFTS_EV_STATUS: complete(&sdata->cmd_done); fallthrough; case STMFTS_EV_NO_EVENT: case STMFTS_EV_DEBUG: return; } switch (event[0] & STMFTS_MASK_EVENT_ID) { case STMFTS_EV_MULTI_TOUCH_ENTER: case STMFTS_EV_MULTI_TOUCH_MOTION: stmfts_report_contact_event(sdata, event); break; case STMFTS_EV_MULTI_TOUCH_LEAVE: stmfts_report_contact_release(sdata, event); break; case STMFTS_EV_HOVER_ENTER: case STMFTS_EV_HOVER_LEAVE: case STMFTS_EV_HOVER_MOTION: stmfts_report_hover_event(sdata, event); break; case STMFTS_EV_KEY_STATUS: stmfts_report_key_event(sdata, event); break; case STMFTS_EV_ERROR: dev_warn(&sdata->client->dev, "error code: 0x%x%x%x%x%x%x", event[6], event[5], event[4], event[3], event[2], event[1]); break; default: dev_err(&sdata->client->dev, "unknown event %#02x\n", event[0]); } } } static irqreturn_t stmfts_irq_handler(int irq, void *dev) { struct stmfts_data *sdata = dev; int err; mutex_lock(&sdata->mutex); err = stmfts_read_events(sdata); if (unlikely(err)) dev_err(&sdata->client->dev, "failed to read events: %d\n", err); else stmfts_parse_events(sdata); mutex_unlock(&sdata->mutex); return IRQ_HANDLED; } static int stmfts_command(struct stmfts_data *sdata, const u8 cmd) { int err; reinit_completion(&sdata->cmd_done); err = i2c_smbus_write_byte(sdata->client, cmd); if (err) return err; if (!wait_for_completion_timeout(&sdata->cmd_done, msecs_to_jiffies(1000))) return -ETIMEDOUT; return 0; } static int stmfts_input_open(struct input_dev *dev) { struct stmfts_data *sdata = input_get_drvdata(dev); int err; err = pm_runtime_resume_and_get(&sdata->client->dev); if (err) return err; err = i2c_smbus_write_byte(sdata->client, STMFTS_MS_MT_SENSE_ON); if (err) { pm_runtime_put_sync(&sdata->client->dev); return err; } mutex_lock(&sdata->mutex); sdata->running = true; if (sdata->hover_enabled) { err = i2c_smbus_write_byte(sdata->client, STMFTS_SS_HOVER_SENSE_ON); if (err) dev_warn(&sdata->client->dev, "failed to enable hover\n"); } mutex_unlock(&sdata->mutex); if (sdata->use_key) { err = i2c_smbus_write_byte(sdata->client, STMFTS_MS_KEY_SENSE_ON); if (err) /* I can still use only the touch screen */ dev_warn(&sdata->client->dev, "failed to enable touchkey\n"); } return 0; } static void stmfts_input_close(struct input_dev *dev) { struct stmfts_data *sdata = input_get_drvdata(dev); int err; err = i2c_smbus_write_byte(sdata->client, STMFTS_MS_MT_SENSE_OFF); if (err) dev_warn(&sdata->client->dev, "failed to disable touchscreen: %d\n", err); mutex_lock(&sdata->mutex); sdata->running = false; if (sdata->hover_enabled) { err = i2c_smbus_write_byte(sdata->client, STMFTS_SS_HOVER_SENSE_OFF); if (err) dev_warn(&sdata->client->dev, "failed to disable hover: %d\n", err); } mutex_unlock(&sdata->mutex); if (sdata->use_key) { err = i2c_smbus_write_byte(sdata->client, STMFTS_MS_KEY_SENSE_OFF); if (err) dev_warn(&sdata->client->dev, "failed to disable touchkey: %d\n", err); } pm_runtime_put_sync(&sdata->client->dev); } static ssize_t stmfts_sysfs_chip_id(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%#x\n", sdata->chip_id); } static ssize_t stmfts_sysfs_chip_version(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%u\n", sdata->chip_ver); } static ssize_t stmfts_sysfs_fw_ver(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%u\n", sdata->fw_ver); } static ssize_t stmfts_sysfs_config_id(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%#x\n", sdata->config_id); } static ssize_t stmfts_sysfs_config_version(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%u\n", sdata->config_ver); } static ssize_t stmfts_sysfs_read_status(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); u8 status[4]; int err; err = i2c_smbus_read_i2c_block_data(sdata->client, STMFTS_READ_STATUS, sizeof(status), status); if (err) return err; return sprintf(buf, "%#02x\n", status[0]); } static ssize_t stmfts_sysfs_hover_enable_read(struct device *dev, struct device_attribute *attr, char *buf) { struct stmfts_data *sdata = dev_get_drvdata(dev); return sprintf(buf, "%u\n", sdata->hover_enabled); } static ssize_t stmfts_sysfs_hover_enable_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct stmfts_data *sdata = dev_get_drvdata(dev); unsigned long value; int err = 0; if (kstrtoul(buf, 0, &value)) return -EINVAL; mutex_lock(&sdata->mutex); if (value && sdata->hover_enabled) goto out; if (sdata->running) err = i2c_smbus_write_byte(sdata->client, value ? STMFTS_SS_HOVER_SENSE_ON : STMFTS_SS_HOVER_SENSE_OFF); if (!err) sdata->hover_enabled = !!value; out: mutex_unlock(&sdata->mutex); return len; } static DEVICE_ATTR(chip_id, 0444, stmfts_sysfs_chip_id, NULL); static DEVICE_ATTR(chip_version, 0444, stmfts_sysfs_chip_version, NULL); static DEVICE_ATTR(fw_ver, 0444, stmfts_sysfs_fw_ver, NULL); static DEVICE_ATTR(config_id, 0444, stmfts_sysfs_config_id, NULL); static DEVICE_ATTR(config_version, 0444, stmfts_sysfs_config_version, NULL); static DEVICE_ATTR(status, 0444, stmfts_sysfs_read_status, NULL); static DEVICE_ATTR(hover_enable, 0644, stmfts_sysfs_hover_enable_read, stmfts_sysfs_hover_enable_write); static struct attribute *stmfts_sysfs_attrs[] = { &dev_attr_chip_id.attr, &dev_attr_chip_version.attr, &dev_attr_fw_ver.attr, &dev_attr_config_id.attr, &dev_attr_config_version.attr, &dev_attr_status.attr, &dev_attr_hover_enable.attr, NULL }; static struct attribute_group stmfts_attribute_group = { .attrs = stmfts_sysfs_attrs }; static int stmfts_power_on(struct stmfts_data *sdata) { int err; u8 reg[8]; err = regulator_bulk_enable(ARRAY_SIZE(sdata->regulators), sdata->regulators); if (err) return err; /* * The datasheet does not specify the power on time, but considering * that the reset time is < 10ms, I sleep 20ms to be sure */ msleep(20); err = i2c_smbus_read_i2c_block_data(sdata->client, STMFTS_READ_INFO, sizeof(reg), reg); if (err < 0) return err; if (err != sizeof(reg)) return -EIO; sdata->chip_id = be16_to_cpup((__be16 *)&reg[6]); sdata->chip_ver = reg[0]; sdata->fw_ver = be16_to_cpup((__be16 *)&reg[2]); sdata->config_id = reg[4]; sdata->config_ver = reg[5]; enable_irq(sdata->client->irq); msleep(50); err = stmfts_command(sdata, STMFTS_SYSTEM_RESET); if (err) return err; err = stmfts_command(sdata, STMFTS_SLEEP_OUT); if (err) return err; /* optional tuning */ err = stmfts_command(sdata, STMFTS_MS_CX_TUNING); if (err) dev_warn(&sdata->client->dev, "failed to perform mutual auto tune: %d\n", err); /* optional tuning */ err = stmfts_command(sdata, STMFTS_SS_CX_TUNING); if (err) dev_warn(&sdata->client->dev, "failed to perform self auto tune: %d\n", err); err = stmfts_command(sdata, STMFTS_FULL_FORCE_CALIBRATION); if (err) return err; /* * At this point no one is using the touchscreen * and I don't really care about the return value */ (void) i2c_smbus_write_byte(sdata->client, STMFTS_SLEEP_IN); return 0; } static void stmfts_power_off(void *data) { struct stmfts_data *sdata = data; disable_irq(sdata->client->irq); regulator_bulk_disable(ARRAY_SIZE(sdata->regulators), sdata->regulators); } /* This function is void because I don't want to prevent using the touch key * only because the LEDs don't get registered */ static int stmfts_enable_led(struct stmfts_data *sdata) { int err; /* get the regulator for powering the leds on */ sdata->ledvdd = devm_regulator_get(&sdata->client->dev, "ledvdd"); if (IS_ERR(sdata->ledvdd)) return PTR_ERR(sdata->ledvdd); sdata->led_cdev.name = STMFTS_DEV_NAME; sdata->led_cdev.max_brightness = LED_ON; sdata->led_cdev.brightness = LED_OFF; sdata->led_cdev.brightness_set_blocking = stmfts_brightness_set; sdata->led_cdev.brightness_get = stmfts_brightness_get; err = devm_led_classdev_register(&sdata->client->dev, &sdata->led_cdev); if (err) { devm_regulator_put(sdata->ledvdd); return err; } return 0; } static int stmfts_probe(struct i2c_client *client) { int err; struct stmfts_data *sdata; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C | I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_I2C_BLOCK)) return -ENODEV; sdata = devm_kzalloc(&client->dev, sizeof(*sdata), GFP_KERNEL); if (!sdata) return -ENOMEM; i2c_set_clientdata(client, sdata); sdata->client = client; mutex_init(&sdata->mutex); init_completion(&sdata->cmd_done); sdata->regulators[STMFTS_REGULATOR_VDD].supply = "vdd"; sdata->regulators[STMFTS_REGULATOR_AVDD].supply = "avdd"; err = devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(sdata->regulators), sdata->regulators); if (err) return err; sdata->input = devm_input_allocate_device(&client->dev); if (!sdata->input) return -ENOMEM; sdata->input->name = STMFTS_DEV_NAME; sdata->input->id.bustype = BUS_I2C; sdata->input->open = stmfts_input_open; sdata->input->close = stmfts_input_close; input_set_capability(sdata->input, EV_ABS, ABS_MT_POSITION_X); input_set_capability(sdata->input, EV_ABS, ABS_MT_POSITION_Y); touchscreen_parse_properties(sdata->input, true, &sdata->prop); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_TOUCH_MINOR, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_ORIENTATION, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_MT_PRESSURE, 0, 255, 0, 0); input_set_abs_params(sdata->input, ABS_DISTANCE, 0, 255, 0, 0); sdata->use_key = device_property_read_bool(&client->dev, "touch-key-connected"); if (sdata->use_key) { input_set_capability(sdata->input, EV_KEY, KEY_MENU); input_set_capability(sdata->input, EV_KEY, KEY_BACK); } err = input_mt_init_slots(sdata->input, STMFTS_MAX_FINGERS, INPUT_MT_DIRECT); if (err) return err; input_set_drvdata(sdata->input, sdata); /* * stmfts_power_on expects interrupt to be disabled, but * at this point the device is still off and I do not trust * the status of the irq line that can generate some spurious * interrupts. To be on the safe side it's better to not enable * the interrupts during their request. */ err = devm_request_threaded_irq(&client->dev, client->irq, NULL, stmfts_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, "stmfts_irq", sdata); if (err) return err; dev_dbg(&client->dev, "initializing ST-Microelectronics FTS...\n"); err = stmfts_power_on(sdata); if (err) return err; err = devm_add_action_or_reset(&client->dev, stmfts_power_off, sdata); if (err) return err; err = input_register_device(sdata->input); if (err) return err; if (sdata->use_key) { err = stmfts_enable_led(sdata); if (err) { /* * Even if the LEDs have failed to be initialized and * used in the driver, I can still use the device even * without LEDs. The ledvdd regulator pointer will be * used as a flag. */ dev_warn(&client->dev, "unable to use touchkey leds\n"); sdata->ledvdd = NULL; } } err = devm_device_add_group(&client->dev, &stmfts_attribute_group); if (err) return err; pm_runtime_enable(&client->dev); device_enable_async_suspend(&client->dev); return 0; } static void stmfts_remove(struct i2c_client *client) { pm_runtime_disable(&client->dev); } static int stmfts_runtime_suspend(struct device *dev) { struct stmfts_data *sdata = dev_get_drvdata(dev); int ret; ret = i2c_smbus_write_byte(sdata->client, STMFTS_SLEEP_IN); if (ret) dev_warn(dev, "failed to suspend device: %d\n", ret); return ret; } static int stmfts_runtime_resume(struct device *dev) { struct stmfts_data *sdata = dev_get_drvdata(dev); int ret; ret = i2c_smbus_write_byte(sdata->client, STMFTS_SLEEP_OUT); if (ret) dev_err(dev, "failed to resume device: %d\n", ret); return ret; } static int stmfts_suspend(struct device *dev) { struct stmfts_data *sdata = dev_get_drvdata(dev); stmfts_power_off(sdata); return 0; } static int stmfts_resume(struct device *dev) { struct stmfts_data *sdata = dev_get_drvdata(dev); return stmfts_power_on(sdata); } static const struct dev_pm_ops stmfts_pm_ops = { SYSTEM_SLEEP_PM_OPS(stmfts_suspend, stmfts_resume) RUNTIME_PM_OPS(stmfts_runtime_suspend, stmfts_runtime_resume, NULL) }; #ifdef CONFIG_OF static const struct of_device_id stmfts_of_match[] = { { .compatible = "st,stmfts", }, { }, }; MODULE_DEVICE_TABLE(of, stmfts_of_match); #endif static const struct i2c_device_id stmfts_id[] = { { "stmfts", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, stmfts_id); static struct i2c_driver stmfts_driver = { .driver = { .name = STMFTS_DEV_NAME, .of_match_table = of_match_ptr(stmfts_of_match), .pm = pm_ptr(&stmfts_pm_ops), .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, .probe = stmfts_probe, .remove = stmfts_remove, .id_table = stmfts_id, }; module_i2c_driver(stmfts_driver); MODULE_AUTHOR("Andi Shyti <[email protected]>"); MODULE_DESCRIPTION("STMicroelectronics FTS Touch Screen"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/stmfts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Elo serial touchscreen driver * * Copyright (c) 2004 Vojtech Pavlik */ /* * This driver can handle serial Elo touchscreens using either the Elo standard * 'E271-2210' 10-byte protocol, Elo legacy 'E281A-4002' 6-byte protocol, Elo * legacy 'E271-140' 4-byte protocol and Elo legacy 'E261-280' 3-byte protocol. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #include <linux/ctype.h> #define DRIVER_DESC "Elo serial touchscreen driver" MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define ELO_MAX_LENGTH 10 #define ELO10_PACKET_LEN 8 #define ELO10_TOUCH 0x03 #define ELO10_PRESSURE 0x80 #define ELO10_LEAD_BYTE 'U' #define ELO10_ID_CMD 'i' #define ELO10_TOUCH_PACKET 'T' #define ELO10_ACK_PACKET 'A' #define ELI10_ID_PACKET 'I' /* * Per-touchscreen data. */ struct elo { struct input_dev *dev; struct serio *serio; struct mutex cmd_mutex; struct completion cmd_done; int id; int idx; unsigned char expected_packet; unsigned char csum; unsigned char data[ELO_MAX_LENGTH]; unsigned char response[ELO10_PACKET_LEN]; char phys[32]; }; static void elo_process_data_10(struct elo *elo, unsigned char data) { struct input_dev *dev = elo->dev; elo->data[elo->idx] = data; switch (elo->idx++) { case 0: elo->csum = 0xaa; if (data != ELO10_LEAD_BYTE) { dev_dbg(&elo->serio->dev, "unsynchronized data: 0x%02x\n", data); elo->idx = 0; } break; case 9: elo->idx = 0; if (data != elo->csum) { dev_dbg(&elo->serio->dev, "bad checksum: 0x%02x, expected 0x%02x\n", data, elo->csum); break; } if (elo->data[1] != elo->expected_packet) { if (elo->data[1] != ELO10_TOUCH_PACKET) dev_dbg(&elo->serio->dev, "unexpected packet: 0x%02x\n", elo->data[1]); break; } if (likely(elo->data[1] == ELO10_TOUCH_PACKET)) { input_report_abs(dev, ABS_X, (elo->data[4] << 8) | elo->data[3]); input_report_abs(dev, ABS_Y, (elo->data[6] << 8) | elo->data[5]); if (elo->data[2] & ELO10_PRESSURE) input_report_abs(dev, ABS_PRESSURE, (elo->data[8] << 8) | elo->data[7]); input_report_key(dev, BTN_TOUCH, elo->data[2] & ELO10_TOUCH); input_sync(dev); } else if (elo->data[1] == ELO10_ACK_PACKET) { if (elo->data[2] == '0') elo->expected_packet = ELO10_TOUCH_PACKET; complete(&elo->cmd_done); } else { memcpy(elo->response, &elo->data[1], ELO10_PACKET_LEN); elo->expected_packet = ELO10_ACK_PACKET; } break; } elo->csum += data; } static void elo_process_data_6(struct elo *elo, unsigned char data) { struct input_dev *dev = elo->dev; elo->data[elo->idx] = data; switch (elo->idx++) { case 0: if ((data & 0xc0) != 0xc0) elo->idx = 0; break; case 1: if ((data & 0xc0) != 0x80) elo->idx = 0; break; case 2: if ((data & 0xc0) != 0x40) elo->idx = 0; break; case 3: if (data & 0xc0) { elo->idx = 0; break; } input_report_abs(dev, ABS_X, ((elo->data[0] & 0x3f) << 6) | (elo->data[1] & 0x3f)); input_report_abs(dev, ABS_Y, ((elo->data[2] & 0x3f) << 6) | (elo->data[3] & 0x3f)); if (elo->id == 2) { input_report_key(dev, BTN_TOUCH, 1); input_sync(dev); elo->idx = 0; } break; case 4: if (data) { input_sync(dev); elo->idx = 0; } break; case 5: if ((data & 0xf0) == 0) { input_report_abs(dev, ABS_PRESSURE, elo->data[5]); input_report_key(dev, BTN_TOUCH, !!elo->data[5]); } input_sync(dev); elo->idx = 0; break; } } static void elo_process_data_3(struct elo *elo, unsigned char data) { struct input_dev *dev = elo->dev; elo->data[elo->idx] = data; switch (elo->idx++) { case 0: if ((data & 0x7f) != 0x01) elo->idx = 0; break; case 2: input_report_key(dev, BTN_TOUCH, !(elo->data[1] & 0x80)); input_report_abs(dev, ABS_X, elo->data[1]); input_report_abs(dev, ABS_Y, elo->data[2]); input_sync(dev); elo->idx = 0; break; } } static irqreturn_t elo_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct elo *elo = serio_get_drvdata(serio); switch (elo->id) { case 0: elo_process_data_10(elo, data); break; case 1: case 2: elo_process_data_6(elo, data); break; case 3: elo_process_data_3(elo, data); break; } return IRQ_HANDLED; } static int elo_command_10(struct elo *elo, unsigned char *packet) { int rc = -1; int i; unsigned char csum = 0xaa + ELO10_LEAD_BYTE; mutex_lock(&elo->cmd_mutex); serio_pause_rx(elo->serio); elo->expected_packet = toupper(packet[0]); init_completion(&elo->cmd_done); serio_continue_rx(elo->serio); if (serio_write(elo->serio, ELO10_LEAD_BYTE)) goto out; for (i = 0; i < ELO10_PACKET_LEN; i++) { csum += packet[i]; if (serio_write(elo->serio, packet[i])) goto out; } if (serio_write(elo->serio, csum)) goto out; wait_for_completion_timeout(&elo->cmd_done, HZ); if (elo->expected_packet == ELO10_TOUCH_PACKET) { /* We are back in reporting mode, the command was ACKed */ memcpy(packet, elo->response, ELO10_PACKET_LEN); rc = 0; } out: mutex_unlock(&elo->cmd_mutex); return rc; } static int elo_setup_10(struct elo *elo) { static const char *elo_types[] = { "Accu", "Dura", "Intelli", "Carroll" }; struct input_dev *dev = elo->dev; unsigned char packet[ELO10_PACKET_LEN] = { ELO10_ID_CMD }; if (elo_command_10(elo, packet)) return -1; dev->id.version = (packet[5] << 8) | packet[4]; input_set_abs_params(dev, ABS_X, 96, 4000, 0, 0); input_set_abs_params(dev, ABS_Y, 96, 4000, 0, 0); if (packet[3] & ELO10_PRESSURE) input_set_abs_params(dev, ABS_PRESSURE, 0, 255, 0, 0); dev_info(&elo->serio->dev, "%sTouch touchscreen, fw: %02x.%02x, features: 0x%02x, controller: 0x%02x\n", elo_types[(packet[1] -'0') & 0x03], packet[5], packet[4], packet[3], packet[7]); return 0; } /* * elo_disconnect() is the opposite of elo_connect() */ static void elo_disconnect(struct serio *serio) { struct elo *elo = serio_get_drvdata(serio); input_get_device(elo->dev); input_unregister_device(elo->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(elo->dev); kfree(elo); } /* * elo_connect() is the routine that is called when someone adds a * new serio device that supports Gunze protocol and registers it as * an input device. */ static int elo_connect(struct serio *serio, struct serio_driver *drv) { struct elo *elo; struct input_dev *input_dev; int err; elo = kzalloc(sizeof(struct elo), GFP_KERNEL); input_dev = input_allocate_device(); if (!elo || !input_dev) { err = -ENOMEM; goto fail1; } elo->serio = serio; elo->id = serio->id.id; elo->dev = input_dev; elo->expected_packet = ELO10_TOUCH_PACKET; mutex_init(&elo->cmd_mutex); init_completion(&elo->cmd_done); snprintf(elo->phys, sizeof(elo->phys), "%s/input0", serio->phys); input_dev->name = "Elo Serial TouchScreen"; input_dev->phys = elo->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_ELO; input_dev->id.product = elo->id; input_dev->id.version = 0x0100; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); serio_set_drvdata(serio, elo); err = serio_open(serio, drv); if (err) goto fail2; switch (elo->id) { case 0: /* 10-byte protocol */ if (elo_setup_10(elo)) { err = -EIO; goto fail3; } break; case 1: /* 6-byte protocol */ input_set_abs_params(input_dev, ABS_PRESSURE, 0, 15, 0, 0); fallthrough; case 2: /* 4-byte protocol */ input_set_abs_params(input_dev, ABS_X, 96, 4000, 0, 0); input_set_abs_params(input_dev, ABS_Y, 96, 4000, 0, 0); break; case 3: /* 3-byte protocol */ input_set_abs_params(input_dev, ABS_X, 0, 255, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, 255, 0, 0); break; } err = input_register_device(elo->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(elo); return err; } /* * The serio driver structure. */ static const struct serio_device_id elo_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_ELO, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, elo_serio_ids); static struct serio_driver elo_drv = { .driver = { .name = "elo", }, .description = DRIVER_DESC, .id_table = elo_serio_ids, .interrupt = elo_interrupt, .connect = elo_connect, .disconnect = elo_disconnect, }; module_serio_driver(elo_drv);
linux-master
drivers/input/touchscreen/elo.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for ELAN eKTF2127 i2c touchscreen controller * * For this driver the layout of the Chipone icn8318 i2c * touchscreencontroller is used. * * Author: * Michel Verlaan <[email protected]> * Siebren Vroegindeweij <[email protected]> * * Original chipone_icn8318 driver: * Hans de Goede <[email protected]> */ #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/module.h> #include <linux/of.h> #include <linux/delay.h> /* Packet header defines (first byte of data send / received) */ #define EKTF2127_NOISE 0x40 #define EKTF2127_RESPONSE 0x52 #define EKTF2127_REQUEST 0x53 #define EKTF2127_HELLO 0x55 #define EKTF2127_REPORT2 0x5a #define EKTF2127_REPORT 0x5d #define EKTF2127_CALIB_DONE 0x66 /* Register defines (second byte of data send / received) */ #define EKTF2127_ENV_NOISY 0x41 #define EKTF2127_HEIGHT 0x60 #define EKTF2127_WIDTH 0x63 /* 2 bytes header + 5 * 3 bytes coordinates + 3 bytes pressure info + footer */ #define EKTF2127_TOUCH_REPORT_SIZE 21 #define EKTF2127_MAX_TOUCHES 5 struct ektf2127_ts { struct i2c_client *client; struct input_dev *input; struct gpio_desc *power_gpios; struct touchscreen_properties prop; }; static void ektf2127_parse_coordinates(const u8 *buf, unsigned int touch_count, struct input_mt_pos *touches) { int index = 0; int i; for (i = 0; i < touch_count; i++) { index = 2 + i * 3; touches[i].x = (buf[index] & 0x0f); touches[i].x <<= 8; touches[i].x |= buf[index + 2]; touches[i].y = (buf[index] & 0xf0); touches[i].y <<= 4; touches[i].y |= buf[index + 1]; } } static void ektf2127_report_event(struct ektf2127_ts *ts, const u8 *buf) { struct input_mt_pos touches[EKTF2127_MAX_TOUCHES]; int slots[EKTF2127_MAX_TOUCHES]; unsigned int touch_count, i; touch_count = buf[1] & 0x07; if (touch_count > EKTF2127_MAX_TOUCHES) { dev_err(&ts->client->dev, "Too many touches %d > %d\n", touch_count, EKTF2127_MAX_TOUCHES); touch_count = EKTF2127_MAX_TOUCHES; } ektf2127_parse_coordinates(buf, touch_count, touches); input_mt_assign_slots(ts->input, slots, touches, touch_count, 0); for (i = 0; i < touch_count; i++) { input_mt_slot(ts->input, slots[i]); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, true); touchscreen_report_pos(ts->input, &ts->prop, touches[i].x, touches[i].y, true); } input_mt_sync_frame(ts->input); input_sync(ts->input); } static void ektf2127_report2_contact(struct ektf2127_ts *ts, int slot, const u8 *buf, bool active) { input_mt_slot(ts->input, slot); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, active); if (active) { int x = (buf[0] & 0xf0) << 4 | buf[1]; int y = (buf[0] & 0x0f) << 8 | buf[2]; touchscreen_report_pos(ts->input, &ts->prop, x, y, true); } } static void ektf2127_report2_event(struct ektf2127_ts *ts, const u8 *buf) { ektf2127_report2_contact(ts, 0, &buf[1], !!(buf[7] & 2)); ektf2127_report2_contact(ts, 1, &buf[4], !!(buf[7] & 4)); input_mt_sync_frame(ts->input); input_sync(ts->input); } static irqreturn_t ektf2127_irq(int irq, void *dev_id) { struct ektf2127_ts *ts = dev_id; struct device *dev = &ts->client->dev; char buf[EKTF2127_TOUCH_REPORT_SIZE]; int ret; ret = i2c_master_recv(ts->client, buf, EKTF2127_TOUCH_REPORT_SIZE); if (ret != EKTF2127_TOUCH_REPORT_SIZE) { dev_err(dev, "Error reading touch data: %d\n", ret); goto out; } switch (buf[0]) { case EKTF2127_REPORT: ektf2127_report_event(ts, buf); break; case EKTF2127_REPORT2: ektf2127_report2_event(ts, buf); break; case EKTF2127_NOISE: if (buf[1] == EKTF2127_ENV_NOISY) dev_dbg(dev, "Environment is electrically noisy\n"); break; case EKTF2127_HELLO: case EKTF2127_CALIB_DONE: break; default: dev_err(dev, "Unexpected packet header byte %#02x\n", buf[0]); break; } out: return IRQ_HANDLED; } static int ektf2127_start(struct input_dev *dev) { struct ektf2127_ts *ts = input_get_drvdata(dev); enable_irq(ts->client->irq); gpiod_set_value_cansleep(ts->power_gpios, 1); return 0; } static void ektf2127_stop(struct input_dev *dev) { struct ektf2127_ts *ts = input_get_drvdata(dev); disable_irq(ts->client->irq); gpiod_set_value_cansleep(ts->power_gpios, 0); } static int ektf2127_suspend(struct device *dev) { struct ektf2127_ts *ts = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&ts->input->mutex); if (input_device_enabled(ts->input)) ektf2127_stop(ts->input); mutex_unlock(&ts->input->mutex); return 0; } static int ektf2127_resume(struct device *dev) { struct ektf2127_ts *ts = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&ts->input->mutex); if (input_device_enabled(ts->input)) ektf2127_start(ts->input); mutex_unlock(&ts->input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(ektf2127_pm_ops, ektf2127_suspend, ektf2127_resume); static int ektf2127_query_dimension(struct i2c_client *client, bool width) { struct device *dev = &client->dev; const char *what = width ? "width" : "height"; u8 what_code = width ? EKTF2127_WIDTH : EKTF2127_HEIGHT; u8 buf[4]; int ret; int error; /* Request dimension */ buf[0] = EKTF2127_REQUEST; buf[1] = width ? EKTF2127_WIDTH : EKTF2127_HEIGHT; buf[2] = 0x00; buf[3] = 0x00; ret = i2c_master_send(client, buf, sizeof(buf)); if (ret != sizeof(buf)) { error = ret < 0 ? ret : -EIO; dev_err(dev, "Failed to request %s: %d\n", what, error); return error; } msleep(20); /* Read response */ ret = i2c_master_recv(client, buf, sizeof(buf)); if (ret != sizeof(buf)) { error = ret < 0 ? ret : -EIO; dev_err(dev, "Failed to receive %s data: %d\n", what, error); return error; } if (buf[0] != EKTF2127_RESPONSE || buf[1] != what_code) { dev_err(dev, "Unexpected %s data: %#02x %#02x\n", what, buf[0], buf[1]); return -EIO; } return (((buf[3] & 0xf0) << 4) | buf[2]) - 1; } static int ektf2127_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ektf2127_ts *ts; struct input_dev *input; u8 buf[4]; int max_x, max_y; int error; if (!client->irq) { dev_err(dev, "Error no irq specified\n"); return -EINVAL; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; /* This requests the gpio *and* turns on the touchscreen controller */ ts->power_gpios = devm_gpiod_get(dev, "power", GPIOD_OUT_HIGH); if (IS_ERR(ts->power_gpios)) return dev_err_probe(dev, PTR_ERR(ts->power_gpios), "Error getting power gpio\n"); input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = client->name; input->id.bustype = BUS_I2C; input->open = ektf2127_start; input->close = ektf2127_stop; ts->client = client; /* Read hello (ignore result, depends on initial power state) */ msleep(20); i2c_master_recv(ts->client, buf, sizeof(buf)); /* Read resolution from chip */ max_x = ektf2127_query_dimension(client, true); if (max_x < 0) return max_x; max_y = ektf2127_query_dimension(client, false); if (max_y < 0) return max_y; input_set_abs_params(input, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, max_y, 0, 0); touchscreen_parse_properties(input, true, &ts->prop); error = input_mt_init_slots(input, EKTF2127_MAX_TOUCHES, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED | INPUT_MT_TRACK); if (error) return error; ts->input = input; input_set_drvdata(input, ts); error = devm_request_threaded_irq(dev, client->irq, NULL, ektf2127_irq, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(dev, "Error requesting irq: %d\n", error); return error; } /* Stop device till opened */ ektf2127_stop(ts->input); error = input_register_device(input); if (error) return error; i2c_set_clientdata(client, ts); return 0; } #ifdef CONFIG_OF static const struct of_device_id ektf2127_of_match[] = { { .compatible = "elan,ektf2127" }, { .compatible = "elan,ektf2132" }, {} }; MODULE_DEVICE_TABLE(of, ektf2127_of_match); #endif static const struct i2c_device_id ektf2127_i2c_id[] = { { "ektf2127", 0 }, { "ektf2132", 0 }, {} }; MODULE_DEVICE_TABLE(i2c, ektf2127_i2c_id); static struct i2c_driver ektf2127_driver = { .driver = { .name = "elan_ektf2127", .pm = pm_sleep_ptr(&ektf2127_pm_ops), .of_match_table = of_match_ptr(ektf2127_of_match), }, .probe = ektf2127_probe, .id_table = ektf2127_i2c_id, }; module_i2c_driver(ektf2127_driver); MODULE_DESCRIPTION("ELAN eKTF2127/eKTF2132 I2C Touchscreen Driver"); MODULE_AUTHOR("Michel Verlaan, Siebren Vroegindeweij"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ektf2127.c
// SPDX-License-Identifier: GPL-2.0-only /* * Elan Microelectronics touch panels with I2C interface * * Copyright (C) 2014 Elan Microelectronics Corporation. * Scott Liu <[email protected]> * * This code is partly based on hid-multitouch.c: * * Copyright (c) 2010-2012 Stephane Chatty <[email protected]> * Copyright (c) 2010-2012 Benjamin Tissoires <[email protected]> * Copyright (c) 2010-2012 Ecole Nationale de l'Aviation Civile, France * * This code is partly based on i2c-hid.c: * * Copyright (c) 2012 Benjamin Tissoires <[email protected]> * Copyright (c) 2012 Ecole Nationale de l'Aviation Civile, France * Copyright (c) 2012 Red Hat, Inc */ #include <linux/bits.h> #include <linux/module.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/platform_device.h> #include <linux/async.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/uaccess.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/firmware.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/acpi.h> #include <linux/of.h> #include <linux/pm_wakeirq.h> #include <linux/gpio/consumer.h> #include <linux/regulator/consumer.h> #include <linux/uuid.h> #include <asm/unaligned.h> /* Device, Driver information */ #define DEVICE_NAME "elants_i2c" /* Convert from rows or columns into resolution */ #define ELAN_TS_RESOLUTION(n, m) (((n) - 1) * (m)) /* FW header data */ #define HEADER_SIZE 4 #define FW_HDR_TYPE 0 #define FW_HDR_COUNT 1 #define FW_HDR_LENGTH 2 /* Buffer mode Queue Header information */ #define QUEUE_HEADER_SINGLE 0x62 #define QUEUE_HEADER_NORMAL 0X63 #define QUEUE_HEADER_WAIT 0x64 #define QUEUE_HEADER_NORMAL2 0x66 /* Command header definition */ #define CMD_HEADER_WRITE 0x54 #define CMD_HEADER_READ 0x53 #define CMD_HEADER_6B_READ 0x5B #define CMD_HEADER_ROM_READ 0x96 #define CMD_HEADER_RESP 0x52 #define CMD_HEADER_6B_RESP 0x9B #define CMD_HEADER_ROM_RESP 0x95 #define CMD_HEADER_HELLO 0x55 #define CMD_HEADER_REK 0x66 /* FW position data */ #define PACKET_SIZE_OLD 40 #define PACKET_SIZE 55 #define MAX_CONTACT_NUM 10 #define FW_POS_HEADER 0 #define FW_POS_STATE 1 #define FW_POS_TOTAL 2 #define FW_POS_XY 3 #define FW_POS_TOOL_TYPE 33 #define FW_POS_CHECKSUM 34 #define FW_POS_WIDTH 35 #define FW_POS_PRESSURE 45 #define HEADER_REPORT_10_FINGER 0x62 /* Header (4 bytes) plus 3 full 10-finger packets */ #define MAX_PACKET_SIZE 169 #define BOOT_TIME_DELAY_MS 50 /* FW read command, 0x53 0x?? 0x0, 0x01 */ #define E_ELAN_INFO_FW_VER 0x00 #define E_ELAN_INFO_BC_VER 0x10 #define E_ELAN_INFO_X_RES 0x60 #define E_ELAN_INFO_Y_RES 0x63 #define E_ELAN_INFO_REK 0xD0 #define E_ELAN_INFO_TEST_VER 0xE0 #define E_ELAN_INFO_FW_ID 0xF0 #define E_INFO_OSR 0xD6 #define E_INFO_PHY_SCAN 0xD7 #define E_INFO_PHY_DRIVER 0xD8 /* FW write command, 0x54 0x?? 0x0, 0x01 */ #define E_POWER_STATE_SLEEP 0x50 #define E_POWER_STATE_RESUME 0x58 #define MAX_RETRIES 3 #define MAX_FW_UPDATE_RETRIES 30 #define ELAN_FW_PAGESIZE 132 /* calibration timeout definition */ #define ELAN_CALI_TIMEOUT_MSEC 12000 #define ELAN_POWERON_DELAY_USEC 5000 #define ELAN_RESET_DELAY_MSEC 20 /* FW boot code version */ #define BC_VER_H_BYTE_FOR_EKTH3900x1_I2C 0x72 #define BC_VER_H_BYTE_FOR_EKTH3900x2_I2C 0x82 #define BC_VER_H_BYTE_FOR_EKTH3900x3_I2C 0x92 #define BC_VER_H_BYTE_FOR_EKTH5312x1_I2C 0x6D #define BC_VER_H_BYTE_FOR_EKTH5312x2_I2C 0x6E #define BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C 0x77 #define BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C 0x78 #define BC_VER_H_BYTE_FOR_EKTH5312x1_I2C_USB 0x67 #define BC_VER_H_BYTE_FOR_EKTH5312x2_I2C_USB 0x68 #define BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C_USB 0x74 #define BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C_USB 0x75 enum elants_chip_id { EKTH3500, EKTF3624, }; enum elants_state { ELAN_STATE_NORMAL, ELAN_WAIT_QUEUE_HEADER, ELAN_WAIT_RECALIBRATION, }; enum elants_iap_mode { ELAN_IAP_OPERATIONAL, ELAN_IAP_RECOVERY, }; /* struct elants_data - represents state of Elan touchscreen device */ struct elants_data { struct i2c_client *client; struct input_dev *input; struct regulator *vcc33; struct regulator *vccio; struct gpio_desc *reset_gpio; u16 fw_version; u8 test_version; u8 solution_version; u8 bc_version; u8 iap_version; u16 hw_version; u8 major_res; unsigned int x_res; /* resolution in units/mm */ unsigned int y_res; unsigned int x_max; unsigned int y_max; unsigned int phy_x; unsigned int phy_y; struct touchscreen_properties prop; enum elants_state state; enum elants_chip_id chip_id; enum elants_iap_mode iap_mode; /* Guards against concurrent access to the device via sysfs */ struct mutex sysfs_mutex; u8 cmd_resp[HEADER_SIZE]; struct completion cmd_done; bool keep_power_in_suspend; /* Must be last to be used for DMA operations */ u8 buf[MAX_PACKET_SIZE] ____cacheline_aligned; }; static int elants_i2c_send(struct i2c_client *client, const void *data, size_t size) { int ret; ret = i2c_master_send(client, data, size); if (ret == size) return 0; if (ret >= 0) ret = -EIO; dev_err(&client->dev, "%s failed (%*ph): %d\n", __func__, (int)size, data, ret); return ret; } static int elants_i2c_read(struct i2c_client *client, void *data, size_t size) { int ret; ret = i2c_master_recv(client, data, size); if (ret == size) return 0; if (ret >= 0) ret = -EIO; dev_err(&client->dev, "%s failed: %d\n", __func__, ret); return ret; } static int elants_i2c_execute_command(struct i2c_client *client, const u8 *cmd, size_t cmd_size, u8 *resp, size_t resp_size, int retries, const char *cmd_name) { struct i2c_msg msgs[2]; int ret; u8 expected_response; switch (cmd[0]) { case CMD_HEADER_READ: expected_response = CMD_HEADER_RESP; break; case CMD_HEADER_6B_READ: expected_response = CMD_HEADER_6B_RESP; break; case CMD_HEADER_ROM_READ: expected_response = CMD_HEADER_ROM_RESP; break; default: dev_err(&client->dev, "(%s): invalid command: %*ph\n", cmd_name, (int)cmd_size, cmd); return -EINVAL; } for (;;) { msgs[0].addr = client->addr; msgs[0].flags = client->flags & I2C_M_TEN; msgs[0].len = cmd_size; msgs[0].buf = (u8 *)cmd; msgs[1].addr = client->addr; msgs[1].flags = (client->flags & I2C_M_TEN) | I2C_M_RD; msgs[1].flags |= I2C_M_RD; msgs[1].len = resp_size; msgs[1].buf = resp; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret < 0) { if (--retries > 0) { dev_dbg(&client->dev, "(%s) I2C transfer failed: %pe (retrying)\n", cmd_name, ERR_PTR(ret)); continue; } dev_err(&client->dev, "(%s) I2C transfer failed: %pe\n", cmd_name, ERR_PTR(ret)); return ret; } if (ret != ARRAY_SIZE(msgs) || resp[FW_HDR_TYPE] != expected_response) { if (--retries > 0) { dev_dbg(&client->dev, "(%s) unexpected response: %*ph (retrying)\n", cmd_name, ret, resp); continue; } dev_err(&client->dev, "(%s) unexpected response: %*ph\n", cmd_name, ret, resp); return -EIO; } return 0; } } static int elants_i2c_calibrate(struct elants_data *ts) { struct i2c_client *client = ts->client; int ret, error; static const u8 w_flashkey[] = { CMD_HEADER_WRITE, 0xC0, 0xE1, 0x5A }; static const u8 rek[] = { CMD_HEADER_WRITE, 0x29, 0x00, 0x01 }; static const u8 rek_resp[] = { CMD_HEADER_REK, 0x66, 0x66, 0x66 }; disable_irq(client->irq); ts->state = ELAN_WAIT_RECALIBRATION; reinit_completion(&ts->cmd_done); elants_i2c_send(client, w_flashkey, sizeof(w_flashkey)); elants_i2c_send(client, rek, sizeof(rek)); enable_irq(client->irq); ret = wait_for_completion_interruptible_timeout(&ts->cmd_done, msecs_to_jiffies(ELAN_CALI_TIMEOUT_MSEC)); ts->state = ELAN_STATE_NORMAL; if (ret <= 0) { error = ret < 0 ? ret : -ETIMEDOUT; dev_err(&client->dev, "error while waiting for calibration to complete: %d\n", error); return error; } if (memcmp(rek_resp, ts->cmd_resp, sizeof(rek_resp))) { dev_err(&client->dev, "unexpected calibration response: %*ph\n", (int)sizeof(ts->cmd_resp), ts->cmd_resp); return -EINVAL; } return 0; } static int elants_i2c_sw_reset(struct i2c_client *client) { const u8 soft_rst_cmd[] = { 0x77, 0x77, 0x77, 0x77 }; int error; error = elants_i2c_send(client, soft_rst_cmd, sizeof(soft_rst_cmd)); if (error) { dev_err(&client->dev, "software reset failed: %d\n", error); return error; } /* * We should wait at least 10 msec (but no more than 40) before * sending fastboot or IAP command to the device. */ msleep(30); return 0; } static u16 elants_i2c_parse_version(u8 *buf) { return get_unaligned_be32(buf) >> 4; } static int elants_i2c_query_hw_version(struct elants_data *ts) { struct i2c_client *client = ts->client; int retry_cnt = MAX_RETRIES; const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_ID, 0x00, 0x01 }; u8 resp[HEADER_SIZE]; int error; while (retry_cnt--) { error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), 1, "read fw id"); if (error) return error; ts->hw_version = elants_i2c_parse_version(resp); if (ts->hw_version != 0xffff) return 0; } dev_err(&client->dev, "Invalid fw id: %#04x\n", ts->hw_version); return -EINVAL; } static int elants_i2c_query_fw_version(struct elants_data *ts) { struct i2c_client *client = ts->client; int retry_cnt = MAX_RETRIES; const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_VER, 0x00, 0x01 }; u8 resp[HEADER_SIZE]; int error; while (retry_cnt--) { error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), 1, "read fw version"); if (error) return error; ts->fw_version = elants_i2c_parse_version(resp); if (ts->fw_version != 0x0000 && ts->fw_version != 0xffff) return 0; dev_dbg(&client->dev, "(read fw version) resp %*phC\n", (int)sizeof(resp), resp); } dev_err(&client->dev, "Invalid fw ver: %#04x\n", ts->fw_version); return -EINVAL; } static int elants_i2c_query_test_version(struct elants_data *ts) { struct i2c_client *client = ts->client; int error; u16 version; const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_TEST_VER, 0x00, 0x01 }; u8 resp[HEADER_SIZE]; error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), MAX_RETRIES, "read test version"); if (error) { dev_err(&client->dev, "Failed to read test version\n"); return error; } version = elants_i2c_parse_version(resp); ts->test_version = version >> 8; ts->solution_version = version & 0xff; return 0; } static int elants_i2c_query_bc_version(struct elants_data *ts) { struct i2c_client *client = ts->client; const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_BC_VER, 0x00, 0x01 }; u8 resp[HEADER_SIZE]; u16 version; int error; error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), 1, "read BC version"); if (error) return error; version = elants_i2c_parse_version(resp); ts->bc_version = version >> 8; ts->iap_version = version & 0xff; return 0; } static int elants_i2c_query_ts_info_ektf(struct elants_data *ts) { struct i2c_client *client = ts->client; int error; u8 resp[4]; u16 phy_x, phy_y; const u8 get_xres_cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_X_RES, 0x00, 0x00 }; const u8 get_yres_cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_Y_RES, 0x00, 0x00 }; /* Get X/Y size in mm */ error = elants_i2c_execute_command(client, get_xres_cmd, sizeof(get_xres_cmd), resp, sizeof(resp), 1, "get X size"); if (error) return error; phy_x = resp[2] | ((resp[3] & 0xF0) << 4); error = elants_i2c_execute_command(client, get_yres_cmd, sizeof(get_yres_cmd), resp, sizeof(resp), 1, "get Y size"); if (error) return error; phy_y = resp[2] | ((resp[3] & 0xF0) << 4); dev_dbg(&client->dev, "phy_x=%d, phy_y=%d\n", phy_x, phy_y); ts->phy_x = phy_x; ts->phy_y = phy_y; /* eKTF doesn't report max size, set it to default values */ ts->x_max = 2240 - 1; ts->y_max = 1408 - 1; return 0; } static int elants_i2c_query_ts_info_ekth(struct elants_data *ts) { struct i2c_client *client = ts->client; int error; u8 resp[17]; u16 phy_x, phy_y, rows, cols, osr; const u8 get_resolution_cmd[] = { CMD_HEADER_6B_READ, 0x00, 0x00, 0x00, 0x00, 0x00 }; const u8 get_osr_cmd[] = { CMD_HEADER_READ, E_INFO_OSR, 0x00, 0x01 }; const u8 get_physical_scan_cmd[] = { CMD_HEADER_READ, E_INFO_PHY_SCAN, 0x00, 0x01 }; const u8 get_physical_drive_cmd[] = { CMD_HEADER_READ, E_INFO_PHY_DRIVER, 0x00, 0x01 }; /* Get trace number */ error = elants_i2c_execute_command(client, get_resolution_cmd, sizeof(get_resolution_cmd), resp, sizeof(resp), 1, "get resolution"); if (error) return error; rows = resp[2] + resp[6] + resp[10]; cols = resp[3] + resp[7] + resp[11]; /* Get report resolution value of ABS_MT_TOUCH_MAJOR */ ts->major_res = resp[16]; /* Process mm_to_pixel information */ error = elants_i2c_execute_command(client, get_osr_cmd, sizeof(get_osr_cmd), resp, sizeof(resp), 1, "get osr"); if (error) return error; osr = resp[3]; error = elants_i2c_execute_command(client, get_physical_scan_cmd, sizeof(get_physical_scan_cmd), resp, sizeof(resp), 1, "get physical scan"); if (error) return error; phy_x = get_unaligned_be16(&resp[2]); error = elants_i2c_execute_command(client, get_physical_drive_cmd, sizeof(get_physical_drive_cmd), resp, sizeof(resp), 1, "get physical drive"); if (error) return error; phy_y = get_unaligned_be16(&resp[2]); dev_dbg(&client->dev, "phy_x=%d, phy_y=%d\n", phy_x, phy_y); if (rows == 0 || cols == 0 || osr == 0) { dev_warn(&client->dev, "invalid trace number data: %d, %d, %d\n", rows, cols, osr); } else { /* translate trace number to TS resolution */ ts->x_max = ELAN_TS_RESOLUTION(rows, osr); ts->x_res = DIV_ROUND_CLOSEST(ts->x_max, phy_x); ts->y_max = ELAN_TS_RESOLUTION(cols, osr); ts->y_res = DIV_ROUND_CLOSEST(ts->y_max, phy_y); ts->phy_x = phy_x; ts->phy_y = phy_y; } return 0; } static int elants_i2c_fastboot(struct i2c_client *client) { const u8 boot_cmd[] = { 0x4D, 0x61, 0x69, 0x6E }; int error; error = elants_i2c_send(client, boot_cmd, sizeof(boot_cmd)); if (error) { dev_err(&client->dev, "boot failed: %d\n", error); return error; } dev_dbg(&client->dev, "boot success -- 0x%x\n", client->addr); return 0; } static int elants_i2c_initialize(struct elants_data *ts) { struct i2c_client *client = ts->client; int error, error2, retry_cnt; const u8 hello_packet[] = { 0x55, 0x55, 0x55, 0x55 }; const u8 recov_packet[] = { 0x55, 0x55, 0x80, 0x80 }; u8 buf[HEADER_SIZE]; for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) { error = elants_i2c_sw_reset(client); if (error) { /* Continue initializing if it's the last try */ if (retry_cnt < MAX_RETRIES - 1) continue; } error = elants_i2c_fastboot(client); if (error) { /* Continue initializing if it's the last try */ if (retry_cnt < MAX_RETRIES - 1) continue; } /* Wait for Hello packet */ msleep(BOOT_TIME_DELAY_MS); error = elants_i2c_read(client, buf, sizeof(buf)); if (error) { dev_err(&client->dev, "failed to read 'hello' packet: %d\n", error); } else if (!memcmp(buf, hello_packet, sizeof(hello_packet))) { ts->iap_mode = ELAN_IAP_OPERATIONAL; break; } else if (!memcmp(buf, recov_packet, sizeof(recov_packet))) { /* * Setting error code will mark device * in recovery mode below. */ error = -EIO; break; } else { error = -EINVAL; dev_err(&client->dev, "invalid 'hello' packet: %*ph\n", (int)sizeof(buf), buf); } } /* hw version is available even if device in recovery state */ error2 = elants_i2c_query_hw_version(ts); if (!error2) error2 = elants_i2c_query_bc_version(ts); if (!error) error = error2; if (!error) error = elants_i2c_query_fw_version(ts); if (!error) error = elants_i2c_query_test_version(ts); switch (ts->chip_id) { case EKTH3500: if (!error) error = elants_i2c_query_ts_info_ekth(ts); break; case EKTF3624: if (!error) error = elants_i2c_query_ts_info_ektf(ts); break; default: BUG(); } if (error) ts->iap_mode = ELAN_IAP_RECOVERY; return 0; } /* * Firmware update interface. */ static int elants_i2c_fw_write_page(struct i2c_client *client, const void *page) { const u8 ack_ok[] = { 0xaa, 0xaa }; u8 buf[2]; int retry; int error; for (retry = 0; retry < MAX_FW_UPDATE_RETRIES; retry++) { error = elants_i2c_send(client, page, ELAN_FW_PAGESIZE); if (error) { dev_err(&client->dev, "IAP Write Page failed: %d\n", error); continue; } error = elants_i2c_read(client, buf, 2); if (error) { dev_err(&client->dev, "IAP Ack read failed: %d\n", error); return error; } if (!memcmp(buf, ack_ok, sizeof(ack_ok))) return 0; error = -EIO; dev_err(&client->dev, "IAP Get Ack Error [%02x:%02x]\n", buf[0], buf[1]); } return error; } static int elants_i2c_validate_remark_id(struct elants_data *ts, const struct firmware *fw) { struct i2c_client *client = ts->client; int error; const u8 cmd[] = { CMD_HEADER_ROM_READ, 0x80, 0x1F, 0x00, 0x00, 0x21 }; u8 resp[6] = { 0 }; u16 ts_remark_id = 0; u16 fw_remark_id = 0; /* Compare TS Remark ID and FW Remark ID */ error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), 1, "read Remark ID"); if (error) return error; ts_remark_id = get_unaligned_be16(&resp[3]); fw_remark_id = get_unaligned_le16(&fw->data[fw->size - 4]); if (fw_remark_id != ts_remark_id) { dev_err(&client->dev, "Remark ID Mismatched: ts_remark_id=0x%04x, fw_remark_id=0x%04x.\n", ts_remark_id, fw_remark_id); return -EINVAL; } return 0; } static bool elants_i2c_should_check_remark_id(struct elants_data *ts) { struct i2c_client *client = ts->client; const u8 bootcode_version = ts->iap_version; bool check; /* I2C eKTH3900 and eKTH5312 are NOT support Remark ID */ if ((bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x1_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x2_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x3_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x1_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x2_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x1_I2C_USB) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x2_I2C_USB) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C_USB) || (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C_USB)) { dev_dbg(&client->dev, "eKTH3900/eKTH5312(0x%02x) are not support remark id\n", bootcode_version); check = false; } else if (bootcode_version >= 0x60) { check = true; } else { check = false; } return check; } static int elants_i2c_do_update_firmware(struct i2c_client *client, const struct firmware *fw, bool force) { struct elants_data *ts = i2c_get_clientdata(client); const u8 enter_iap[] = { 0x45, 0x49, 0x41, 0x50 }; const u8 enter_iap2[] = { 0x54, 0x00, 0x12, 0x34 }; const u8 iap_ack[] = { 0x55, 0xaa, 0x33, 0xcc }; const u8 close_idle[] = { 0x54, 0x2c, 0x01, 0x01 }; u8 buf[HEADER_SIZE]; u16 send_id; int page, n_fw_pages; int error; bool check_remark_id = elants_i2c_should_check_remark_id(ts); /* Recovery mode detection! */ if (force) { dev_dbg(&client->dev, "Recovery mode procedure\n"); if (check_remark_id) { error = elants_i2c_validate_remark_id(ts, fw); if (error) return error; } error = elants_i2c_send(client, enter_iap2, sizeof(enter_iap2)); if (error) { dev_err(&client->dev, "failed to enter IAP mode: %d\n", error); return error; } } else { /* Start IAP Procedure */ dev_dbg(&client->dev, "Normal IAP procedure\n"); /* Close idle mode */ error = elants_i2c_send(client, close_idle, sizeof(close_idle)); if (error) dev_err(&client->dev, "Failed close idle: %d\n", error); msleep(60); elants_i2c_sw_reset(client); msleep(20); if (check_remark_id) { error = elants_i2c_validate_remark_id(ts, fw); if (error) return error; } error = elants_i2c_send(client, enter_iap, sizeof(enter_iap)); if (error) { dev_err(&client->dev, "failed to enter IAP mode: %d\n", error); return error; } } msleep(20); /* check IAP state */ error = elants_i2c_read(client, buf, 4); if (error) { dev_err(&client->dev, "failed to read IAP acknowledgement: %d\n", error); return error; } if (memcmp(buf, iap_ack, sizeof(iap_ack))) { dev_err(&client->dev, "failed to enter IAP: %*ph (expected %*ph)\n", (int)sizeof(buf), buf, (int)sizeof(iap_ack), iap_ack); return -EIO; } dev_info(&client->dev, "successfully entered IAP mode"); send_id = client->addr; error = elants_i2c_send(client, &send_id, 1); if (error) { dev_err(&client->dev, "sending dummy byte failed: %d\n", error); return error; } /* Clear the last page of Master */ error = elants_i2c_send(client, fw->data, ELAN_FW_PAGESIZE); if (error) { dev_err(&client->dev, "clearing of the last page failed: %d\n", error); return error; } error = elants_i2c_read(client, buf, 2); if (error) { dev_err(&client->dev, "failed to read ACK for clearing the last page: %d\n", error); return error; } n_fw_pages = fw->size / ELAN_FW_PAGESIZE; dev_dbg(&client->dev, "IAP Pages = %d\n", n_fw_pages); for (page = 0; page < n_fw_pages; page++) { error = elants_i2c_fw_write_page(client, fw->data + page * ELAN_FW_PAGESIZE); if (error) { dev_err(&client->dev, "failed to write FW page %d: %d\n", page, error); return error; } } /* Old iap needs to wait 200ms for WDT and rest is for hello packets */ msleep(300); dev_info(&client->dev, "firmware update completed\n"); return 0; } static int elants_i2c_fw_update(struct elants_data *ts) { struct i2c_client *client = ts->client; const struct firmware *fw; char *fw_name; int error; fw_name = kasprintf(GFP_KERNEL, "elants_i2c_%04x.bin", ts->hw_version); if (!fw_name) return -ENOMEM; dev_info(&client->dev, "requesting fw name = %s\n", fw_name); error = request_firmware(&fw, fw_name, &client->dev); kfree(fw_name); if (error) { dev_err(&client->dev, "failed to request firmware: %d\n", error); return error; } if (fw->size % ELAN_FW_PAGESIZE) { dev_err(&client->dev, "invalid firmware length: %zu\n", fw->size); error = -EINVAL; goto out; } disable_irq(client->irq); error = elants_i2c_do_update_firmware(client, fw, ts->iap_mode == ELAN_IAP_RECOVERY); if (error) { dev_err(&client->dev, "firmware update failed: %d\n", error); ts->iap_mode = ELAN_IAP_RECOVERY; goto out_enable_irq; } error = elants_i2c_initialize(ts); if (error) { dev_err(&client->dev, "failed to initialize device after firmware update: %d\n", error); ts->iap_mode = ELAN_IAP_RECOVERY; goto out_enable_irq; } ts->iap_mode = ELAN_IAP_OPERATIONAL; out_enable_irq: ts->state = ELAN_STATE_NORMAL; enable_irq(client->irq); msleep(100); if (!error) elants_i2c_calibrate(ts); out: release_firmware(fw); return error; } /* * Event reporting. */ static void elants_i2c_mt_event(struct elants_data *ts, u8 *buf, size_t packet_size) { struct input_dev *input = ts->input; unsigned int n_fingers; unsigned int tool_type; u16 finger_state; int i; n_fingers = buf[FW_POS_STATE + 1] & 0x0f; finger_state = ((buf[FW_POS_STATE + 1] & 0x30) << 4) | buf[FW_POS_STATE]; dev_dbg(&ts->client->dev, "n_fingers: %u, state: %04x\n", n_fingers, finger_state); /* Note: all fingers have the same tool type */ tool_type = buf[FW_POS_TOOL_TYPE] & BIT(0) ? MT_TOOL_FINGER : MT_TOOL_PALM; for (i = 0; i < MAX_CONTACT_NUM && n_fingers; i++) { if (finger_state & 1) { unsigned int x, y, p, w; u8 *pos; pos = &buf[FW_POS_XY + i * 3]; x = (((u16)pos[0] & 0xf0) << 4) | pos[1]; y = (((u16)pos[0] & 0x0f) << 8) | pos[2]; /* * eKTF3624 may have use "old" touch-report format, * depending on a device and TS firmware version. * For example, ASUS Transformer devices use the "old" * format, while ASUS Nexus 7 uses the "new" formant. */ if (packet_size == PACKET_SIZE_OLD && ts->chip_id == EKTF3624) { w = buf[FW_POS_WIDTH + i / 2]; w >>= 4 * (~i & 1); w |= w << 4; w |= !w; p = w; } else { p = buf[FW_POS_PRESSURE + i]; w = buf[FW_POS_WIDTH + i]; } dev_dbg(&ts->client->dev, "i=%d x=%d y=%d p=%d w=%d\n", i, x, y, p, w); input_mt_slot(input, i); input_mt_report_slot_state(input, tool_type, true); touchscreen_report_pos(input, &ts->prop, x, y, true); input_event(input, EV_ABS, ABS_MT_PRESSURE, p); input_event(input, EV_ABS, ABS_MT_TOUCH_MAJOR, w); n_fingers--; } finger_state >>= 1; } input_mt_sync_frame(input); input_sync(input); } static u8 elants_i2c_calculate_checksum(u8 *buf) { u8 checksum = 0; u8 i; for (i = 0; i < FW_POS_CHECKSUM; i++) checksum += buf[i]; return checksum; } static void elants_i2c_event(struct elants_data *ts, u8 *buf, size_t packet_size) { u8 checksum = elants_i2c_calculate_checksum(buf); if (unlikely(buf[FW_POS_CHECKSUM] != checksum)) dev_warn(&ts->client->dev, "%s: invalid checksum for packet %02x: %02x vs. %02x\n", __func__, buf[FW_POS_HEADER], checksum, buf[FW_POS_CHECKSUM]); else if (unlikely(buf[FW_POS_HEADER] != HEADER_REPORT_10_FINGER)) dev_warn(&ts->client->dev, "%s: unknown packet type: %02x\n", __func__, buf[FW_POS_HEADER]); else elants_i2c_mt_event(ts, buf, packet_size); } static irqreturn_t elants_i2c_irq(int irq, void *_dev) { const u8 wait_packet[] = { 0x64, 0x64, 0x64, 0x64 }; struct elants_data *ts = _dev; struct i2c_client *client = ts->client; int report_count, report_len; int i; int len; len = i2c_master_recv_dmasafe(client, ts->buf, sizeof(ts->buf)); if (len < 0) { dev_err(&client->dev, "%s: failed to read data: %d\n", __func__, len); goto out; } dev_dbg(&client->dev, "%s: packet %*ph\n", __func__, HEADER_SIZE, ts->buf); switch (ts->state) { case ELAN_WAIT_RECALIBRATION: if (ts->buf[FW_HDR_TYPE] == CMD_HEADER_REK) { memcpy(ts->cmd_resp, ts->buf, sizeof(ts->cmd_resp)); complete(&ts->cmd_done); ts->state = ELAN_STATE_NORMAL; } break; case ELAN_WAIT_QUEUE_HEADER: if (ts->buf[FW_HDR_TYPE] != QUEUE_HEADER_NORMAL) break; ts->state = ELAN_STATE_NORMAL; fallthrough; case ELAN_STATE_NORMAL: switch (ts->buf[FW_HDR_TYPE]) { case CMD_HEADER_HELLO: case CMD_HEADER_RESP: break; case QUEUE_HEADER_WAIT: if (memcmp(ts->buf, wait_packet, sizeof(wait_packet))) { dev_err(&client->dev, "invalid wait packet %*ph\n", HEADER_SIZE, ts->buf); } else { ts->state = ELAN_WAIT_QUEUE_HEADER; udelay(30); } break; case QUEUE_HEADER_SINGLE: elants_i2c_event(ts, &ts->buf[HEADER_SIZE], ts->buf[FW_HDR_LENGTH]); break; case QUEUE_HEADER_NORMAL2: /* CMD_HEADER_REK */ /* * Depending on firmware version, eKTF3624 touchscreens * may utilize one of these opcodes for the touch events: * 0x63 (NORMAL) and 0x66 (NORMAL2). The 0x63 is used by * older firmware version and differs from 0x66 such that * touch pressure value needs to be adjusted. The 0x66 * opcode of newer firmware is equal to 0x63 of eKTH3500. */ if (ts->chip_id != EKTF3624) break; fallthrough; case QUEUE_HEADER_NORMAL: report_count = ts->buf[FW_HDR_COUNT]; if (report_count == 0 || report_count > 3) { dev_err(&client->dev, "bad report count: %*ph\n", HEADER_SIZE, ts->buf); break; } report_len = ts->buf[FW_HDR_LENGTH] / report_count; if (report_len == PACKET_SIZE_OLD && ts->chip_id == EKTF3624) { dev_dbg_once(&client->dev, "using old report format\n"); } else if (report_len != PACKET_SIZE) { dev_err(&client->dev, "mismatching report length: %*ph\n", HEADER_SIZE, ts->buf); break; } for (i = 0; i < report_count; i++) { u8 *buf = ts->buf + HEADER_SIZE + i * report_len; elants_i2c_event(ts, buf, report_len); } break; default: dev_err(&client->dev, "unknown packet %*ph\n", HEADER_SIZE, ts->buf); break; } break; } out: return IRQ_HANDLED; } /* * sysfs interface */ static ssize_t calibrate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); int error; error = mutex_lock_interruptible(&ts->sysfs_mutex); if (error) return error; error = elants_i2c_calibrate(ts); mutex_unlock(&ts->sysfs_mutex); return error ?: count; } static ssize_t write_update_fw(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); int error; error = mutex_lock_interruptible(&ts->sysfs_mutex); if (error) return error; error = elants_i2c_fw_update(ts); dev_dbg(dev, "firmware update result: %d\n", error); mutex_unlock(&ts->sysfs_mutex); return error ?: count; } static ssize_t show_iap_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%s\n", ts->iap_mode == ELAN_IAP_OPERATIONAL ? "Normal" : "Recovery"); } static ssize_t show_calibration_count(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_REK, 0x00, 0x01 }; u8 resp[HEADER_SIZE]; u16 rek_count; int error; error = elants_i2c_execute_command(client, cmd, sizeof(cmd), resp, sizeof(resp), 1, "read ReK status"); if (error) return sprintf(buf, "%d\n", error); rek_count = get_unaligned_be16(&resp[2]); return sprintf(buf, "0x%04x\n", rek_count); } static DEVICE_ATTR_WO(calibrate); static DEVICE_ATTR(iap_mode, S_IRUGO, show_iap_mode, NULL); static DEVICE_ATTR(calibration_count, S_IRUGO, show_calibration_count, NULL); static DEVICE_ATTR(update_fw, S_IWUSR, NULL, write_update_fw); struct elants_version_attribute { struct device_attribute dattr; size_t field_offset; size_t field_size; }; #define __ELANTS_FIELD_SIZE(_field) \ sizeof(((struct elants_data *)NULL)->_field) #define __ELANTS_VERIFY_SIZE(_field) \ (BUILD_BUG_ON_ZERO(__ELANTS_FIELD_SIZE(_field) > 2) + \ __ELANTS_FIELD_SIZE(_field)) #define ELANTS_VERSION_ATTR(_field) \ struct elants_version_attribute elants_ver_attr_##_field = { \ .dattr = __ATTR(_field, S_IRUGO, \ elants_version_attribute_show, NULL), \ .field_offset = offsetof(struct elants_data, _field), \ .field_size = __ELANTS_VERIFY_SIZE(_field), \ } static ssize_t elants_version_attribute_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); struct elants_version_attribute *attr = container_of(dattr, struct elants_version_attribute, dattr); u8 *field = (u8 *)((char *)ts + attr->field_offset); unsigned int fmt_size; unsigned int val; if (attr->field_size == 1) { val = *field; fmt_size = 2; /* 2 HEX digits */ } else { val = *(u16 *)field; fmt_size = 4; /* 4 HEX digits */ } return sprintf(buf, "%0*x\n", fmt_size, val); } static ELANTS_VERSION_ATTR(fw_version); static ELANTS_VERSION_ATTR(hw_version); static ELANTS_VERSION_ATTR(test_version); static ELANTS_VERSION_ATTR(solution_version); static ELANTS_VERSION_ATTR(bc_version); static ELANTS_VERSION_ATTR(iap_version); static struct attribute *elants_attributes[] = { &dev_attr_calibrate.attr, &dev_attr_update_fw.attr, &dev_attr_iap_mode.attr, &dev_attr_calibration_count.attr, &elants_ver_attr_fw_version.dattr.attr, &elants_ver_attr_hw_version.dattr.attr, &elants_ver_attr_test_version.dattr.attr, &elants_ver_attr_solution_version.dattr.attr, &elants_ver_attr_bc_version.dattr.attr, &elants_ver_attr_iap_version.dattr.attr, NULL }; static const struct attribute_group elants_attribute_group = { .attrs = elants_attributes, }; static int elants_i2c_power_on(struct elants_data *ts) { int error; /* * If we do not have reset gpio assume platform firmware * controls regulators and does power them on for us. */ if (IS_ERR_OR_NULL(ts->reset_gpio)) return 0; error = regulator_enable(ts->vcc33); if (error) { dev_err(&ts->client->dev, "failed to enable vcc33 regulator: %d\n", error); return error; } error = regulator_enable(ts->vccio); if (error) { dev_err(&ts->client->dev, "failed to enable vccio regulator: %d\n", error); regulator_disable(ts->vcc33); return error; } /* * We need to wait a bit after powering on controller before * we are allowed to release reset GPIO. */ usleep_range(ELAN_POWERON_DELAY_USEC, ELAN_POWERON_DELAY_USEC + 100); gpiod_set_value_cansleep(ts->reset_gpio, 0); msleep(ELAN_RESET_DELAY_MSEC); return 0; } static void elants_i2c_power_off(void *_data) { struct elants_data *ts = _data; if (!IS_ERR_OR_NULL(ts->reset_gpio)) { /* * Activate reset gpio to prevent leakage through the * pin once we shut off power to the controller. */ gpiod_set_value_cansleep(ts->reset_gpio, 1); regulator_disable(ts->vccio); regulator_disable(ts->vcc33); } } #ifdef CONFIG_ACPI static const struct acpi_device_id i2c_hid_ids[] = { {"ACPI0C50", 0 }, {"PNP0C50", 0 }, { }, }; static const guid_t i2c_hid_guid = GUID_INIT(0x3CDFF6F7, 0x4267, 0x4555, 0xAD, 0x05, 0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE); static bool elants_acpi_is_hid_device(struct device *dev) { acpi_handle handle = ACPI_HANDLE(dev); union acpi_object *obj; if (acpi_match_device_ids(ACPI_COMPANION(dev), i2c_hid_ids)) return false; obj = acpi_evaluate_dsm_typed(handle, &i2c_hid_guid, 1, 1, NULL, ACPI_TYPE_INTEGER); if (obj) { ACPI_FREE(obj); return true; } return false; } #else static bool elants_acpi_is_hid_device(struct device *dev) { return false; } #endif static int elants_i2c_probe(struct i2c_client *client) { union i2c_smbus_data dummy; struct elants_data *ts; unsigned long irqflags; int error; /* Don't bind to i2c-hid compatible devices, these are handled by the i2c-hid drv. */ if (elants_acpi_is_hid_device(&client->dev)) { dev_warn(&client->dev, "This device appears to be an I2C-HID device, not binding\n"); return -ENODEV; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C check functionality error\n"); return -ENXIO; } ts = devm_kzalloc(&client->dev, sizeof(struct elants_data), GFP_KERNEL); if (!ts) return -ENOMEM; mutex_init(&ts->sysfs_mutex); init_completion(&ts->cmd_done); ts->client = client; ts->chip_id = (enum elants_chip_id)(uintptr_t)device_get_match_data(&client->dev); i2c_set_clientdata(client, ts); ts->vcc33 = devm_regulator_get(&client->dev, "vcc33"); if (IS_ERR(ts->vcc33)) return dev_err_probe(&client->dev, PTR_ERR(ts->vcc33), "Failed to get 'vcc33' regulator\n"); ts->vccio = devm_regulator_get(&client->dev, "vccio"); if (IS_ERR(ts->vccio)) return dev_err_probe(&client->dev, PTR_ERR(ts->vccio), "Failed to get 'vccio' regulator\n"); ts->reset_gpio = devm_gpiod_get(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ts->reset_gpio)) { error = PTR_ERR(ts->reset_gpio); if (error == -EPROBE_DEFER) return error; if (error != -ENOENT && error != -ENOSYS) { dev_err(&client->dev, "failed to get reset gpio: %d\n", error); return error; } ts->keep_power_in_suspend = true; } error = elants_i2c_power_on(ts); if (error) return error; error = devm_add_action_or_reset(&client->dev, elants_i2c_power_off, ts); if (error) { dev_err(&client->dev, "failed to install power off action: %d\n", error); return error; } /* Make sure there is something at this address */ if (i2c_smbus_xfer(client->adapter, client->addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0) { dev_err(&client->dev, "nothing at this address\n"); return -ENXIO; } error = elants_i2c_initialize(ts); if (error) { dev_err(&client->dev, "failed to initialize: %d\n", error); return error; } ts->input = devm_input_allocate_device(&client->dev); if (!ts->input) { dev_err(&client->dev, "Failed to allocate input device\n"); return -ENOMEM; } ts->input->name = "Elan Touchscreen"; ts->input->id.bustype = BUS_I2C; /* Multitouch input params setup */ input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, ts->x_max, 0, 0); input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, ts->y_max, 0, 0); input_set_abs_params(ts->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(ts->input, ABS_MT_PRESSURE, 0, 255, 0, 0); input_set_abs_params(ts->input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_PALM, 0, 0); touchscreen_parse_properties(ts->input, true, &ts->prop); if (ts->chip_id == EKTF3624 && ts->phy_x && ts->phy_y) { /* calculate resolution from size */ ts->x_res = DIV_ROUND_CLOSEST(ts->prop.max_x, ts->phy_x); ts->y_res = DIV_ROUND_CLOSEST(ts->prop.max_y, ts->phy_y); } input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->x_res); input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->y_res); input_abs_set_res(ts->input, ABS_MT_TOUCH_MAJOR, ts->major_res); error = input_mt_init_slots(ts->input, MAX_CONTACT_NUM, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&client->dev, "failed to initialize MT slots: %d\n", error); return error; } error = input_register_device(ts->input); if (error) { dev_err(&client->dev, "unable to register input device: %d\n", error); return error; } /* * Platform code (ACPI, DTS) should normally set up interrupt * for us, but in case it did not let's fall back to using falling * edge to be compatible with older Chromebooks. */ irqflags = irq_get_trigger_type(client->irq); if (!irqflags) irqflags = IRQF_TRIGGER_FALLING; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, elants_i2c_irq, irqflags | IRQF_ONESHOT, client->name, ts); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = devm_device_add_group(&client->dev, &elants_attribute_group); if (error) { dev_err(&client->dev, "failed to create sysfs attributes: %d\n", error); return error; } return 0; } static int elants_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); const u8 set_sleep_cmd[] = { CMD_HEADER_WRITE, E_POWER_STATE_SLEEP, 0x00, 0x01 }; int retry_cnt; int error; /* Command not support in IAP recovery mode */ if (ts->iap_mode != ELAN_IAP_OPERATIONAL) return -EBUSY; disable_irq(client->irq); if (device_may_wakeup(dev)) { /* * The device will automatically enter idle mode * that has reduced power consumption. */ return 0; } else if (ts->keep_power_in_suspend) { for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) { error = elants_i2c_send(client, set_sleep_cmd, sizeof(set_sleep_cmd)); if (!error) break; dev_err(&client->dev, "suspend command failed: %d\n", error); } } else { elants_i2c_power_off(ts); } return 0; } static int elants_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct elants_data *ts = i2c_get_clientdata(client); const u8 set_active_cmd[] = { CMD_HEADER_WRITE, E_POWER_STATE_RESUME, 0x00, 0x01 }; int retry_cnt; int error; if (device_may_wakeup(dev)) { elants_i2c_sw_reset(client); } else if (ts->keep_power_in_suspend) { for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) { error = elants_i2c_send(client, set_active_cmd, sizeof(set_active_cmd)); if (!error) break; dev_err(&client->dev, "resume command failed: %d\n", error); } } else { elants_i2c_power_on(ts); elants_i2c_initialize(ts); } ts->state = ELAN_STATE_NORMAL; enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(elants_i2c_pm_ops, elants_i2c_suspend, elants_i2c_resume); static const struct i2c_device_id elants_i2c_id[] = { { DEVICE_NAME, EKTH3500 }, { "ekth3500", EKTH3500 }, { "ektf3624", EKTF3624 }, { } }; MODULE_DEVICE_TABLE(i2c, elants_i2c_id); #ifdef CONFIG_ACPI static const struct acpi_device_id elants_acpi_id[] = { { "ELAN0001", EKTH3500 }, { } }; MODULE_DEVICE_TABLE(acpi, elants_acpi_id); #endif #ifdef CONFIG_OF static const struct of_device_id elants_of_match[] = { { .compatible = "elan,ekth3500", .data = (void *)EKTH3500 }, { .compatible = "elan,ektf3624", .data = (void *)EKTF3624 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, elants_of_match); #endif static struct i2c_driver elants_i2c_driver = { .probe = elants_i2c_probe, .id_table = elants_i2c_id, .driver = { .name = DEVICE_NAME, .pm = pm_sleep_ptr(&elants_i2c_pm_ops), .acpi_match_table = ACPI_PTR(elants_acpi_id), .of_match_table = of_match_ptr(elants_of_match), .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, }; module_i2c_driver(elants_i2c_driver); MODULE_AUTHOR("Scott Liu <[email protected]>"); MODULE_DESCRIPTION("Elan I2c Touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/elants_i2c.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * STMicroelectronics STMPE811 Touchscreen Driver * * (C) 2010 Luotao Fu <[email protected]> * All rights reserved. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/device.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/workqueue.h> #include <linux/mfd/stmpe.h> /* Register layouts and functionalities are identical on all stmpexxx variants * with touchscreen controller */ #define STMPE_REG_INT_STA 0x0B #define STMPE_REG_TSC_CTRL 0x40 #define STMPE_REG_TSC_CFG 0x41 #define STMPE_REG_FIFO_TH 0x4A #define STMPE_REG_FIFO_STA 0x4B #define STMPE_REG_FIFO_SIZE 0x4C #define STMPE_REG_TSC_DATA_XYZ 0x52 #define STMPE_REG_TSC_FRACTION_Z 0x56 #define STMPE_REG_TSC_I_DRIVE 0x58 #define OP_MOD_XYZ 0 #define STMPE_TSC_CTRL_TSC_EN (1<<0) #define STMPE_FIFO_STA_RESET (1<<0) #define STMPE_IRQ_TOUCH_DET 0 #define STMPE_TS_NAME "stmpe-ts" #define XY_MASK 0xfff /** * struct stmpe_touch - stmpe811 touch screen controller state * @stmpe: pointer back to STMPE MFD container * @idev: registered input device * @work: a work item used to scan the device * @dev: a pointer back to the MFD cell struct device* * @prop: Touchscreen properties * @ave_ctrl: Sample average control * (0 -> 1 sample, 1 -> 2 samples, 2 -> 4 samples, 3 -> 8 samples) * @touch_det_delay: Touch detect interrupt delay * (0 -> 10 us, 1 -> 50 us, 2 -> 100 us, 3 -> 500 us, * 4-> 1 ms, 5 -> 5 ms, 6 -> 10 ms, 7 -> 50 ms) * recommended is 3 * @settling: Panel driver settling time * (0 -> 10 us, 1 -> 100 us, 2 -> 500 us, 3 -> 1 ms, * 4 -> 5 ms, 5 -> 10 ms, 6 for 50 ms, 7 -> 100 ms) * recommended is 2 * @fraction_z: Length of the fractional part in z * (fraction_z ([0..7]) = Count of the fractional part) * recommended is 7 * @i_drive: current limit value of the touchscreen drivers * (0 -> 20 mA typical 35 mA max, 1 -> 50 mA typical 80 mA max) */ struct stmpe_touch { struct stmpe *stmpe; struct input_dev *idev; struct delayed_work work; struct device *dev; struct touchscreen_properties prop; u8 ave_ctrl; u8 touch_det_delay; u8 settling; u8 fraction_z; u8 i_drive; }; static int __stmpe_reset_fifo(struct stmpe *stmpe) { int ret; ret = stmpe_set_bits(stmpe, STMPE_REG_FIFO_STA, STMPE_FIFO_STA_RESET, STMPE_FIFO_STA_RESET); if (ret) return ret; return stmpe_set_bits(stmpe, STMPE_REG_FIFO_STA, STMPE_FIFO_STA_RESET, 0); } static void stmpe_work(struct work_struct *work) { int int_sta; u32 timeout = 40; struct stmpe_touch *ts = container_of(work, struct stmpe_touch, work.work); int_sta = stmpe_reg_read(ts->stmpe, STMPE_REG_INT_STA); /* * touch_det sometimes get desasserted or just get stuck. This appears * to be a silicon bug, We still have to clearify this with the * manufacture. As a workaround We release the key anyway if the * touch_det keeps coming in after 4ms, while the FIFO contains no value * during the whole time. */ while ((int_sta & (1 << STMPE_IRQ_TOUCH_DET)) && (timeout > 0)) { timeout--; int_sta = stmpe_reg_read(ts->stmpe, STMPE_REG_INT_STA); udelay(100); } /* reset the FIFO before we report release event */ __stmpe_reset_fifo(ts->stmpe); input_report_abs(ts->idev, ABS_PRESSURE, 0); input_report_key(ts->idev, BTN_TOUCH, 0); input_sync(ts->idev); } static irqreturn_t stmpe_ts_handler(int irq, void *data) { u8 data_set[4]; int x, y, z; struct stmpe_touch *ts = data; /* * Cancel scheduled polling for release if we have new value * available. Wait if the polling is already running. */ cancel_delayed_work_sync(&ts->work); /* * The FIFO sometimes just crashes and stops generating interrupts. This * appears to be a silicon bug. We still have to clearify this with * the manufacture. As a workaround we disable the TSC while we are * collecting data and flush the FIFO after reading */ stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL, STMPE_TSC_CTRL_TSC_EN, 0); stmpe_block_read(ts->stmpe, STMPE_REG_TSC_DATA_XYZ, 4, data_set); x = (data_set[0] << 4) | (data_set[1] >> 4); y = ((data_set[1] & 0xf) << 8) | data_set[2]; z = data_set[3]; touchscreen_report_pos(ts->idev, &ts->prop, x, y, false); input_report_abs(ts->idev, ABS_PRESSURE, z); input_report_key(ts->idev, BTN_TOUCH, 1); input_sync(ts->idev); /* flush the FIFO after we have read out our values. */ __stmpe_reset_fifo(ts->stmpe); /* reenable the tsc */ stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL, STMPE_TSC_CTRL_TSC_EN, STMPE_TSC_CTRL_TSC_EN); /* start polling for touch_det to detect release */ schedule_delayed_work(&ts->work, msecs_to_jiffies(50)); return IRQ_HANDLED; } static int stmpe_init_hw(struct stmpe_touch *ts) { int ret; u8 tsc_cfg, tsc_cfg_mask; struct stmpe *stmpe = ts->stmpe; struct device *dev = ts->dev; ret = stmpe_enable(stmpe, STMPE_BLOCK_TOUCHSCREEN | STMPE_BLOCK_ADC); if (ret) { dev_err(dev, "Could not enable clock for ADC and TS\n"); return ret; } ret = stmpe811_adc_common_init(stmpe); if (ret) { stmpe_disable(stmpe, STMPE_BLOCK_TOUCHSCREEN | STMPE_BLOCK_ADC); return ret; } tsc_cfg = STMPE_AVE_CTRL(ts->ave_ctrl) | STMPE_DET_DELAY(ts->touch_det_delay) | STMPE_SETTLING(ts->settling); tsc_cfg_mask = STMPE_AVE_CTRL(0xff) | STMPE_DET_DELAY(0xff) | STMPE_SETTLING(0xff); ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_CFG, tsc_cfg_mask, tsc_cfg); if (ret) { dev_err(dev, "Could not config touch\n"); return ret; } ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_FRACTION_Z, STMPE_FRACTION_Z(0xff), STMPE_FRACTION_Z(ts->fraction_z)); if (ret) { dev_err(dev, "Could not config touch\n"); return ret; } ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_I_DRIVE, STMPE_I_DRIVE(0xff), STMPE_I_DRIVE(ts->i_drive)); if (ret) { dev_err(dev, "Could not config touch\n"); return ret; } /* set FIFO to 1 for single point reading */ ret = stmpe_reg_write(stmpe, STMPE_REG_FIFO_TH, 1); if (ret) { dev_err(dev, "Could not set FIFO\n"); return ret; } ret = stmpe_set_bits(stmpe, STMPE_REG_TSC_CTRL, STMPE_OP_MODE(0xff), STMPE_OP_MODE(OP_MOD_XYZ)); if (ret) { dev_err(dev, "Could not set mode\n"); return ret; } return 0; } static int stmpe_ts_open(struct input_dev *dev) { struct stmpe_touch *ts = input_get_drvdata(dev); int ret = 0; ret = __stmpe_reset_fifo(ts->stmpe); if (ret) return ret; return stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL, STMPE_TSC_CTRL_TSC_EN, STMPE_TSC_CTRL_TSC_EN); } static void stmpe_ts_close(struct input_dev *dev) { struct stmpe_touch *ts = input_get_drvdata(dev); cancel_delayed_work_sync(&ts->work); stmpe_set_bits(ts->stmpe, STMPE_REG_TSC_CTRL, STMPE_TSC_CTRL_TSC_EN, 0); } static void stmpe_ts_get_platform_info(struct platform_device *pdev, struct stmpe_touch *ts) { struct device_node *np = pdev->dev.of_node; u32 val; if (np) { if (!of_property_read_u32(np, "st,sample-time", &val)) ts->stmpe->sample_time = val; if (!of_property_read_u32(np, "st,mod-12b", &val)) ts->stmpe->mod_12b = val; if (!of_property_read_u32(np, "st,ref-sel", &val)) ts->stmpe->ref_sel = val; if (!of_property_read_u32(np, "st,adc-freq", &val)) ts->stmpe->adc_freq = val; if (!of_property_read_u32(np, "st,ave-ctrl", &val)) ts->ave_ctrl = val; if (!of_property_read_u32(np, "st,touch-det-delay", &val)) ts->touch_det_delay = val; if (!of_property_read_u32(np, "st,settling", &val)) ts->settling = val; if (!of_property_read_u32(np, "st,fraction-z", &val)) ts->fraction_z = val; if (!of_property_read_u32(np, "st,i-drive", &val)) ts->i_drive = val; } } static int stmpe_input_probe(struct platform_device *pdev) { struct stmpe *stmpe = dev_get_drvdata(pdev->dev.parent); struct stmpe_touch *ts; struct input_dev *idev; int error; int ts_irq; ts_irq = platform_get_irq_byname(pdev, "FIFO_TH"); if (ts_irq < 0) return ts_irq; ts = devm_kzalloc(&pdev->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; idev = devm_input_allocate_device(&pdev->dev); if (!idev) return -ENOMEM; platform_set_drvdata(pdev, ts); ts->stmpe = stmpe; ts->idev = idev; ts->dev = &pdev->dev; stmpe_ts_get_platform_info(pdev, ts); INIT_DELAYED_WORK(&ts->work, stmpe_work); error = devm_request_threaded_irq(&pdev->dev, ts_irq, NULL, stmpe_ts_handler, IRQF_ONESHOT, STMPE_TS_NAME, ts); if (error) { dev_err(&pdev->dev, "Failed to request IRQ %d\n", ts_irq); return error; } error = stmpe_init_hw(ts); if (error) return error; idev->name = STMPE_TS_NAME; idev->phys = STMPE_TS_NAME"/input0"; idev->id.bustype = BUS_I2C; idev->open = stmpe_ts_open; idev->close = stmpe_ts_close; input_set_drvdata(idev, ts); input_set_capability(idev, EV_KEY, BTN_TOUCH); input_set_abs_params(idev, ABS_X, 0, XY_MASK, 0, 0); input_set_abs_params(idev, ABS_Y, 0, XY_MASK, 0, 0); input_set_abs_params(idev, ABS_PRESSURE, 0x0, 0xff, 0, 0); touchscreen_parse_properties(idev, false, &ts->prop); error = input_register_device(idev); if (error) { dev_err(&pdev->dev, "Could not register input device\n"); return error; } return 0; } static int stmpe_ts_remove(struct platform_device *pdev) { struct stmpe_touch *ts = platform_get_drvdata(pdev); stmpe_disable(ts->stmpe, STMPE_BLOCK_TOUCHSCREEN); return 0; } static struct platform_driver stmpe_ts_driver = { .driver = { .name = STMPE_TS_NAME, }, .probe = stmpe_input_probe, .remove = stmpe_ts_remove, }; module_platform_driver(stmpe_ts_driver); static const struct of_device_id stmpe_ts_ids[] = { { .compatible = "st,stmpe-ts", }, { }, }; MODULE_DEVICE_TABLE(of, stmpe_ts_ids); MODULE_AUTHOR("Luotao Fu <[email protected]>"); MODULE_DESCRIPTION("STMPEXXX touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/stmpe-ts.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/bits.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/property.h> #include <linux/regulator/consumer.h> #define IST3038C_HIB_ACCESS (0x800B << 16) #define IST3038C_DIRECT_ACCESS BIT(31) #define IST3038C_REG_CHIPID 0x40001000 #define IST3038C_REG_HIB_BASE 0x30000100 #define IST3038C_REG_TOUCH_STATUS (IST3038C_REG_HIB_BASE | IST3038C_HIB_ACCESS) #define IST3038C_REG_TOUCH_COORD (IST3038C_REG_HIB_BASE | IST3038C_HIB_ACCESS | 0x8) #define IST3038C_REG_INTR_MESSAGE (IST3038C_REG_HIB_BASE | IST3038C_HIB_ACCESS | 0x4) #define IST3038C_WHOAMI 0x38c #define IST3038C_CHIP_ON_DELAY_MS 60 #define IST3038C_I2C_RETRY_COUNT 3 #define IST3038C_MAX_FINGER_NUM 10 #define IST3038C_X_MASK GENMASK(23, 12) #define IST3038C_X_SHIFT 12 #define IST3038C_Y_MASK GENMASK(11, 0) #define IST3038C_AREA_MASK GENMASK(27, 24) #define IST3038C_AREA_SHIFT 24 #define IST3038C_FINGER_COUNT_MASK GENMASK(15, 12) #define IST3038C_FINGER_COUNT_SHIFT 12 #define IST3038C_FINGER_STATUS_MASK GENMASK(9, 0) struct imagis_ts { struct i2c_client *client; struct input_dev *input_dev; struct touchscreen_properties prop; struct regulator_bulk_data supplies[2]; }; static int imagis_i2c_read_reg(struct imagis_ts *ts, unsigned int reg, u32 *data) { __be32 ret_be; __be32 reg_be = cpu_to_be32(reg); struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .buf = (unsigned char *)&reg_be, .len = sizeof(reg_be), }, { .addr = ts->client->addr, .flags = I2C_M_RD, .buf = (unsigned char *)&ret_be, .len = sizeof(ret_be), }, }; int ret, error; int retry = IST3038C_I2C_RETRY_COUNT; /* Retry in case the controller fails to respond */ do { ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret == ARRAY_SIZE(msg)) { *data = be32_to_cpu(ret_be); return 0; } error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "%s - i2c_transfer failed: %d (%d)\n", __func__, error, ret); } while (--retry); return error; } static irqreturn_t imagis_interrupt(int irq, void *dev_id) { struct imagis_ts *ts = dev_id; u32 intr_message, finger_status; unsigned int finger_count, finger_pressed; int i; int error; error = imagis_i2c_read_reg(ts, IST3038C_REG_INTR_MESSAGE, &intr_message); if (error) { dev_err(&ts->client->dev, "failed to read the interrupt message: %d\n", error); goto out; } finger_count = (intr_message & IST3038C_FINGER_COUNT_MASK) >> IST3038C_FINGER_COUNT_SHIFT; if (finger_count > IST3038C_MAX_FINGER_NUM) { dev_err(&ts->client->dev, "finger count %d is more than maximum supported\n", finger_count); goto out; } finger_pressed = intr_message & IST3038C_FINGER_STATUS_MASK; for (i = 0; i < finger_count; i++) { error = imagis_i2c_read_reg(ts, IST3038C_REG_TOUCH_COORD + (i * 4), &finger_status); if (error) { dev_err(&ts->client->dev, "failed to read coordinates for finger %d: %d\n", i, error); goto out; } input_mt_slot(ts->input_dev, i); input_mt_report_slot_state(ts->input_dev, MT_TOOL_FINGER, finger_pressed & BIT(i)); touchscreen_report_pos(ts->input_dev, &ts->prop, (finger_status & IST3038C_X_MASK) >> IST3038C_X_SHIFT, finger_status & IST3038C_Y_MASK, 1); input_report_abs(ts->input_dev, ABS_MT_TOUCH_MAJOR, (finger_status & IST3038C_AREA_MASK) >> IST3038C_AREA_SHIFT); } input_mt_sync_frame(ts->input_dev); input_sync(ts->input_dev); out: return IRQ_HANDLED; } static void imagis_power_off(void *_ts) { struct imagis_ts *ts = _ts; regulator_bulk_disable(ARRAY_SIZE(ts->supplies), ts->supplies); } static int imagis_power_on(struct imagis_ts *ts) { int error; error = regulator_bulk_enable(ARRAY_SIZE(ts->supplies), ts->supplies); if (error) return error; msleep(IST3038C_CHIP_ON_DELAY_MS); return 0; } static int imagis_start(struct imagis_ts *ts) { int error; error = imagis_power_on(ts); if (error) return error; enable_irq(ts->client->irq); return 0; } static int imagis_stop(struct imagis_ts *ts) { disable_irq(ts->client->irq); imagis_power_off(ts); return 0; } static int imagis_input_open(struct input_dev *dev) { struct imagis_ts *ts = input_get_drvdata(dev); return imagis_start(ts); } static void imagis_input_close(struct input_dev *dev) { struct imagis_ts *ts = input_get_drvdata(dev); imagis_stop(ts); } static int imagis_init_input_dev(struct imagis_ts *ts) { struct input_dev *input_dev; int error; input_dev = devm_input_allocate_device(&ts->client->dev); if (!input_dev) return -ENOMEM; ts->input_dev = input_dev; input_dev->name = "Imagis capacitive touchscreen"; input_dev->phys = "input/ts"; input_dev->id.bustype = BUS_I2C; input_dev->open = imagis_input_open; input_dev->close = imagis_input_close; input_set_drvdata(input_dev, ts); input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_Y); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); touchscreen_parse_properties(input_dev, true, &ts->prop); if (!ts->prop.max_x || !ts->prop.max_y) { dev_err(&ts->client->dev, "Touchscreen-size-x and/or touchscreen-size-y not set in dts\n"); return -EINVAL; } error = input_mt_init_slots(input_dev, IST3038C_MAX_FINGER_NUM, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&ts->client->dev, "Failed to initialize MT slots: %d", error); return error; } error = input_register_device(input_dev); if (error) { dev_err(&ts->client->dev, "Failed to register input device: %d", error); return error; } return 0; } static int imagis_init_regulators(struct imagis_ts *ts) { struct i2c_client *client = ts->client; ts->supplies[0].supply = "vdd"; ts->supplies[1].supply = "vddio"; return devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(ts->supplies), ts->supplies); } static int imagis_probe(struct i2c_client *i2c) { struct device *dev = &i2c->dev; struct imagis_ts *ts; int chip_id, error; ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = i2c; error = imagis_init_regulators(ts); if (error) { dev_err(dev, "regulator init error: %d\n", error); return error; } error = imagis_power_on(ts); if (error) { dev_err(dev, "failed to enable regulators: %d\n", error); return error; } error = devm_add_action_or_reset(dev, imagis_power_off, ts); if (error) { dev_err(dev, "failed to install poweroff action: %d\n", error); return error; } error = imagis_i2c_read_reg(ts, IST3038C_REG_CHIPID | IST3038C_DIRECT_ACCESS, &chip_id); if (error) { dev_err(dev, "chip ID read failure: %d\n", error); return error; } if (chip_id != IST3038C_WHOAMI) { dev_err(dev, "unknown chip ID: 0x%x\n", chip_id); return -EINVAL; } error = devm_request_threaded_irq(dev, i2c->irq, NULL, imagis_interrupt, IRQF_ONESHOT | IRQF_NO_AUTOEN, "imagis-touchscreen", ts); if (error) { dev_err(dev, "IRQ %d allocation failure: %d\n", i2c->irq, error); return error; } error = imagis_init_input_dev(ts); if (error) return error; return 0; } static int imagis_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct imagis_ts *ts = i2c_get_clientdata(client); int retval = 0; mutex_lock(&ts->input_dev->mutex); if (input_device_enabled(ts->input_dev)) retval = imagis_stop(ts); mutex_unlock(&ts->input_dev->mutex); return retval; } static int imagis_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct imagis_ts *ts = i2c_get_clientdata(client); int retval = 0; mutex_lock(&ts->input_dev->mutex); if (input_device_enabled(ts->input_dev)) retval = imagis_start(ts); mutex_unlock(&ts->input_dev->mutex); return retval; } static DEFINE_SIMPLE_DEV_PM_OPS(imagis_pm_ops, imagis_suspend, imagis_resume); #ifdef CONFIG_OF static const struct of_device_id imagis_of_match[] = { { .compatible = "imagis,ist3038c", }, { }, }; MODULE_DEVICE_TABLE(of, imagis_of_match); #endif static struct i2c_driver imagis_ts_driver = { .driver = { .name = "imagis-touchscreen", .pm = pm_sleep_ptr(&imagis_pm_ops), .of_match_table = of_match_ptr(imagis_of_match), }, .probe = imagis_probe, }; module_i2c_driver(imagis_ts_driver); MODULE_DESCRIPTION("Imagis IST3038C Touchscreen Driver"); MODULE_AUTHOR("Markuss Broks <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/imagis.c
/* * Weida HiTech WDT87xx TouchScreen I2C driver * * Copyright (c) 2015 Weida Hi-Tech Co., Ltd. * HN Chen <[email protected]> * * This software is licensed under the terms of the GNU General Public * License, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. */ #include <linux/i2c.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/firmware.h> #include <linux/input/mt.h> #include <linux/acpi.h> #include <asm/unaligned.h> #define WDT87XX_NAME "wdt87xx_i2c" #define WDT87XX_FW_NAME "wdt87xx_fw.bin" #define WDT87XX_CFG_NAME "wdt87xx_cfg.bin" #define MODE_ACTIVE 0x01 #define MODE_READY 0x02 #define MODE_IDLE 0x03 #define MODE_SLEEP 0x04 #define MODE_STOP 0xFF #define WDT_MAX_FINGER 10 #define WDT_RAW_BUF_COUNT 54 #define WDT_V1_RAW_BUF_COUNT 74 #define WDT_FIRMWARE_ID 0xa9e368f5 #define PG_SIZE 0x1000 #define MAX_RETRIES 3 #define MAX_UNIT_AXIS 0x7FFF #define PKT_READ_SIZE 72 #define PKT_WRITE_SIZE 80 /* the finger definition of the report event */ #define FINGER_EV_OFFSET_ID 0 #define FINGER_EV_OFFSET_X 1 #define FINGER_EV_OFFSET_Y 3 #define FINGER_EV_SIZE 5 #define FINGER_EV_V1_OFFSET_ID 0 #define FINGER_EV_V1_OFFSET_W 1 #define FINGER_EV_V1_OFFSET_P 2 #define FINGER_EV_V1_OFFSET_X 3 #define FINGER_EV_V1_OFFSET_Y 5 #define FINGER_EV_V1_SIZE 7 /* The definition of a report packet */ #define TOUCH_PK_OFFSET_REPORT_ID 0 #define TOUCH_PK_OFFSET_EVENT 1 #define TOUCH_PK_OFFSET_SCAN_TIME 51 #define TOUCH_PK_OFFSET_FNGR_NUM 53 #define TOUCH_PK_V1_OFFSET_REPORT_ID 0 #define TOUCH_PK_V1_OFFSET_EVENT 1 #define TOUCH_PK_V1_OFFSET_SCAN_TIME 71 #define TOUCH_PK_V1_OFFSET_FNGR_NUM 73 /* The definition of the controller parameters */ #define CTL_PARAM_OFFSET_FW_ID 0 #define CTL_PARAM_OFFSET_PLAT_ID 2 #define CTL_PARAM_OFFSET_XMLS_ID1 4 #define CTL_PARAM_OFFSET_XMLS_ID2 6 #define CTL_PARAM_OFFSET_PHY_CH_X 8 #define CTL_PARAM_OFFSET_PHY_CH_Y 10 #define CTL_PARAM_OFFSET_PHY_X0 12 #define CTL_PARAM_OFFSET_PHY_X1 14 #define CTL_PARAM_OFFSET_PHY_Y0 16 #define CTL_PARAM_OFFSET_PHY_Y1 18 #define CTL_PARAM_OFFSET_PHY_W 22 #define CTL_PARAM_OFFSET_PHY_H 24 #define CTL_PARAM_OFFSET_FACTOR 32 /* The definition of the device descriptor */ #define WDT_GD_DEVICE 1 #define DEV_DESC_OFFSET_VID 8 #define DEV_DESC_OFFSET_PID 10 /* Communication commands */ #define PACKET_SIZE 56 #define VND_REQ_READ 0x06 #define VND_READ_DATA 0x07 #define VND_REQ_WRITE 0x08 #define VND_CMD_START 0x00 #define VND_CMD_STOP 0x01 #define VND_CMD_RESET 0x09 #define VND_CMD_ERASE 0x1A #define VND_GET_CHECKSUM 0x66 #define VND_SET_DATA 0x83 #define VND_SET_COMMAND_DATA 0x84 #define VND_SET_CHECKSUM_CALC 0x86 #define VND_SET_CHECKSUM_LENGTH 0x87 #define VND_CMD_SFLCK 0xFC #define VND_CMD_SFUNL 0xFD #define CMD_SFLCK_KEY 0xC39B #define CMD_SFUNL_KEY 0x95DA #define STRIDX_PLATFORM_ID 0x80 #define STRIDX_PARAMETERS 0x81 #define CMD_BUF_SIZE 8 #define PKT_BUF_SIZE 64 /* The definition of the command packet */ #define CMD_REPORT_ID_OFFSET 0x0 #define CMD_TYPE_OFFSET 0x1 #define CMD_INDEX_OFFSET 0x2 #define CMD_KEY_OFFSET 0x3 #define CMD_LENGTH_OFFSET 0x4 #define CMD_DATA_OFFSET 0x8 /* The definition of firmware chunk tags */ #define FOURCC_ID_RIFF 0x46464952 #define FOURCC_ID_WHIF 0x46494857 #define FOURCC_ID_FRMT 0x544D5246 #define FOURCC_ID_FRWR 0x52575246 #define FOURCC_ID_CNFG 0x47464E43 #define CHUNK_ID_FRMT FOURCC_ID_FRMT #define CHUNK_ID_FRWR FOURCC_ID_FRWR #define CHUNK_ID_CNFG FOURCC_ID_CNFG #define FW_FOURCC1_OFFSET 0 #define FW_SIZE_OFFSET 4 #define FW_FOURCC2_OFFSET 8 #define FW_PAYLOAD_OFFSET 40 #define FW_CHUNK_ID_OFFSET 0 #define FW_CHUNK_SIZE_OFFSET 4 #define FW_CHUNK_TGT_START_OFFSET 8 #define FW_CHUNK_PAYLOAD_LEN_OFFSET 12 #define FW_CHUNK_SRC_START_OFFSET 16 #define FW_CHUNK_VERSION_OFFSET 20 #define FW_CHUNK_ATTR_OFFSET 24 #define FW_CHUNK_PAYLOAD_OFFSET 32 /* Controller requires minimum 300us between commands */ #define WDT_COMMAND_DELAY_MS 2 #define WDT_FLASH_WRITE_DELAY_MS 4 #define WDT_FLASH_ERASE_DELAY_MS 200 #define WDT_FW_RESET_TIME 2500 struct wdt87xx_sys_param { u16 fw_id; u16 plat_id; u16 xmls_id1; u16 xmls_id2; u16 phy_ch_x; u16 phy_ch_y; u16 phy_w; u16 phy_h; u16 scaling_factor; u32 max_x; u32 max_y; u16 vendor_id; u16 product_id; }; struct wdt87xx_data { struct i2c_client *client; struct input_dev *input; /* Mutex for fw update to prevent concurrent access */ struct mutex fw_mutex; struct wdt87xx_sys_param param; u8 phys[32]; }; static int wdt87xx_i2c_xfer(struct i2c_client *client, void *txdata, size_t txlen, void *rxdata, size_t rxlen) { struct i2c_msg msgs[] = { { .addr = client->addr, .flags = 0, .len = txlen, .buf = txdata, }, { .addr = client->addr, .flags = I2C_M_RD, .len = rxlen, .buf = rxdata, }, }; int error; int ret; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "%s: i2c transfer failed: %d\n", __func__, error); return error; } return 0; } static int wdt87xx_get_desc(struct i2c_client *client, u8 desc_idx, u8 *buf, size_t len) { u8 tx_buf[] = { 0x22, 0x00, 0x10, 0x0E, 0x23, 0x00 }; int error; tx_buf[2] |= desc_idx & 0xF; error = wdt87xx_i2c_xfer(client, tx_buf, sizeof(tx_buf), buf, len); if (error) { dev_err(&client->dev, "get desc failed: %d\n", error); return error; } if (buf[0] != len) { dev_err(&client->dev, "unexpected response to get desc: %d\n", buf[0]); return -EINVAL; } mdelay(WDT_COMMAND_DELAY_MS); return 0; } static int wdt87xx_get_string(struct i2c_client *client, u8 str_idx, u8 *buf, size_t len) { u8 tx_buf[] = { 0x22, 0x00, 0x13, 0x0E, str_idx, 0x23, 0x00 }; u8 rx_buf[PKT_WRITE_SIZE]; size_t rx_len = len + 2; int error; if (rx_len > sizeof(rx_buf)) return -EINVAL; error = wdt87xx_i2c_xfer(client, tx_buf, sizeof(tx_buf), rx_buf, rx_len); if (error) { dev_err(&client->dev, "get string failed: %d\n", error); return error; } if (rx_buf[1] != 0x03) { dev_err(&client->dev, "unexpected response to get string: %d\n", rx_buf[1]); return -EINVAL; } rx_len = min_t(size_t, len, rx_buf[0]); memcpy(buf, &rx_buf[2], rx_len); mdelay(WDT_COMMAND_DELAY_MS); return 0; } static int wdt87xx_get_feature(struct i2c_client *client, u8 *buf, size_t buf_size) { u8 tx_buf[8]; u8 rx_buf[PKT_WRITE_SIZE]; size_t tx_len = 0; size_t rx_len = buf_size + 2; int error; if (rx_len > sizeof(rx_buf)) return -EINVAL; /* Get feature command packet */ tx_buf[tx_len++] = 0x22; tx_buf[tx_len++] = 0x00; if (buf[CMD_REPORT_ID_OFFSET] > 0xF) { tx_buf[tx_len++] = 0x30; tx_buf[tx_len++] = 0x02; tx_buf[tx_len++] = buf[CMD_REPORT_ID_OFFSET]; } else { tx_buf[tx_len++] = 0x30 | buf[CMD_REPORT_ID_OFFSET]; tx_buf[tx_len++] = 0x02; } tx_buf[tx_len++] = 0x23; tx_buf[tx_len++] = 0x00; error = wdt87xx_i2c_xfer(client, tx_buf, tx_len, rx_buf, rx_len); if (error) { dev_err(&client->dev, "get feature failed: %d\n", error); return error; } rx_len = min_t(size_t, buf_size, get_unaligned_le16(rx_buf)); memcpy(buf, &rx_buf[2], rx_len); mdelay(WDT_COMMAND_DELAY_MS); return 0; } static int wdt87xx_set_feature(struct i2c_client *client, const u8 *buf, size_t buf_size) { u8 tx_buf[PKT_WRITE_SIZE]; int tx_len = 0; int error; /* Set feature command packet */ tx_buf[tx_len++] = 0x22; tx_buf[tx_len++] = 0x00; if (buf[CMD_REPORT_ID_OFFSET] > 0xF) { tx_buf[tx_len++] = 0x30; tx_buf[tx_len++] = 0x03; tx_buf[tx_len++] = buf[CMD_REPORT_ID_OFFSET]; } else { tx_buf[tx_len++] = 0x30 | buf[CMD_REPORT_ID_OFFSET]; tx_buf[tx_len++] = 0x03; } tx_buf[tx_len++] = 0x23; tx_buf[tx_len++] = 0x00; tx_buf[tx_len++] = (buf_size & 0xFF); tx_buf[tx_len++] = ((buf_size & 0xFF00) >> 8); if (tx_len + buf_size > sizeof(tx_buf)) return -EINVAL; memcpy(&tx_buf[tx_len], buf, buf_size); tx_len += buf_size; error = i2c_master_send(client, tx_buf, tx_len); if (error < 0) { dev_err(&client->dev, "set feature failed: %d\n", error); return error; } mdelay(WDT_COMMAND_DELAY_MS); return 0; } static int wdt87xx_send_command(struct i2c_client *client, int cmd, int value) { u8 cmd_buf[CMD_BUF_SIZE]; /* Set the command packet */ cmd_buf[CMD_REPORT_ID_OFFSET] = VND_REQ_WRITE; cmd_buf[CMD_TYPE_OFFSET] = VND_SET_COMMAND_DATA; put_unaligned_le16((u16)cmd, &cmd_buf[CMD_INDEX_OFFSET]); switch (cmd) { case VND_CMD_START: case VND_CMD_STOP: case VND_CMD_RESET: /* Mode selector */ put_unaligned_le32((value & 0xFF), &cmd_buf[CMD_LENGTH_OFFSET]); break; case VND_CMD_SFLCK: put_unaligned_le16(CMD_SFLCK_KEY, &cmd_buf[CMD_KEY_OFFSET]); break; case VND_CMD_SFUNL: put_unaligned_le16(CMD_SFUNL_KEY, &cmd_buf[CMD_KEY_OFFSET]); break; case VND_CMD_ERASE: case VND_SET_CHECKSUM_CALC: case VND_SET_CHECKSUM_LENGTH: put_unaligned_le32(value, &cmd_buf[CMD_KEY_OFFSET]); break; default: cmd_buf[CMD_REPORT_ID_OFFSET] = 0; dev_err(&client->dev, "Invalid command: %d\n", cmd); return -EINVAL; } return wdt87xx_set_feature(client, cmd_buf, sizeof(cmd_buf)); } static int wdt87xx_sw_reset(struct i2c_client *client) { int error; dev_dbg(&client->dev, "resetting device now\n"); error = wdt87xx_send_command(client, VND_CMD_RESET, 0); if (error) { dev_err(&client->dev, "reset failed\n"); return error; } /* Wait the device to be ready */ msleep(WDT_FW_RESET_TIME); return 0; } static const void *wdt87xx_get_fw_chunk(const struct firmware *fw, u32 id) { size_t pos = FW_PAYLOAD_OFFSET; u32 chunk_id, chunk_size; while (pos < fw->size) { chunk_id = get_unaligned_le32(fw->data + pos + FW_CHUNK_ID_OFFSET); if (chunk_id == id) return fw->data + pos; chunk_size = get_unaligned_le32(fw->data + pos + FW_CHUNK_SIZE_OFFSET); pos += chunk_size + 2 * sizeof(u32); /* chunk ID + size */ } return NULL; } static int wdt87xx_get_sysparam(struct i2c_client *client, struct wdt87xx_sys_param *param) { u8 buf[PKT_READ_SIZE]; int error; error = wdt87xx_get_desc(client, WDT_GD_DEVICE, buf, 18); if (error) { dev_err(&client->dev, "failed to get device desc\n"); return error; } param->vendor_id = get_unaligned_le16(buf + DEV_DESC_OFFSET_VID); param->product_id = get_unaligned_le16(buf + DEV_DESC_OFFSET_PID); error = wdt87xx_get_string(client, STRIDX_PARAMETERS, buf, 34); if (error) { dev_err(&client->dev, "failed to get parameters\n"); return error; } param->xmls_id1 = get_unaligned_le16(buf + CTL_PARAM_OFFSET_XMLS_ID1); param->xmls_id2 = get_unaligned_le16(buf + CTL_PARAM_OFFSET_XMLS_ID2); param->phy_ch_x = get_unaligned_le16(buf + CTL_PARAM_OFFSET_PHY_CH_X); param->phy_ch_y = get_unaligned_le16(buf + CTL_PARAM_OFFSET_PHY_CH_Y); param->phy_w = get_unaligned_le16(buf + CTL_PARAM_OFFSET_PHY_W) / 10; param->phy_h = get_unaligned_le16(buf + CTL_PARAM_OFFSET_PHY_H) / 10; /* Get the scaling factor of pixel to logical coordinate */ param->scaling_factor = get_unaligned_le16(buf + CTL_PARAM_OFFSET_FACTOR); param->max_x = MAX_UNIT_AXIS; param->max_y = DIV_ROUND_CLOSEST(MAX_UNIT_AXIS * param->phy_h, param->phy_w); error = wdt87xx_get_string(client, STRIDX_PLATFORM_ID, buf, 8); if (error) { dev_err(&client->dev, "failed to get platform id\n"); return error; } param->plat_id = buf[1]; buf[0] = 0xf2; error = wdt87xx_get_feature(client, buf, 16); if (error) { dev_err(&client->dev, "failed to get firmware id\n"); return error; } if (buf[0] != 0xf2) { dev_err(&client->dev, "wrong id of fw response: 0x%x\n", buf[0]); return -EINVAL; } param->fw_id = get_unaligned_le16(&buf[1]); dev_info(&client->dev, "fw_id: 0x%x, plat_id: 0x%x, xml_id1: %04x, xml_id2: %04x\n", param->fw_id, param->plat_id, param->xmls_id1, param->xmls_id2); return 0; } static int wdt87xx_validate_firmware(struct wdt87xx_data *wdt, const struct firmware *fw) { const void *fw_chunk; u32 data1, data2; u32 size; u8 fw_chip_id; u8 chip_id; data1 = get_unaligned_le32(fw->data + FW_FOURCC1_OFFSET); data2 = get_unaligned_le32(fw->data + FW_FOURCC2_OFFSET); if (data1 != FOURCC_ID_RIFF || data2 != FOURCC_ID_WHIF) { dev_err(&wdt->client->dev, "check fw tag failed\n"); return -EINVAL; } size = get_unaligned_le32(fw->data + FW_SIZE_OFFSET); if (size != fw->size) { dev_err(&wdt->client->dev, "fw size mismatch: expected %d, actual %zu\n", size, fw->size); return -EINVAL; } /* * Get the chip_id from the firmware. Make sure that it is the * right controller to do the firmware and config update. */ fw_chunk = wdt87xx_get_fw_chunk(fw, CHUNK_ID_FRWR); if (!fw_chunk) { dev_err(&wdt->client->dev, "unable to locate firmware chunk\n"); return -EINVAL; } fw_chip_id = (get_unaligned_le32(fw_chunk + FW_CHUNK_VERSION_OFFSET) >> 12) & 0xF; chip_id = (wdt->param.fw_id >> 12) & 0xF; if (fw_chip_id != chip_id) { dev_err(&wdt->client->dev, "fw version mismatch: fw %d vs. chip %d\n", fw_chip_id, chip_id); return -ENODEV; } return 0; } static int wdt87xx_validate_fw_chunk(const void *data, int id) { if (id == CHUNK_ID_FRWR) { u32 fw_id; fw_id = get_unaligned_le32(data + FW_CHUNK_PAYLOAD_OFFSET); if (fw_id != WDT_FIRMWARE_ID) return -EINVAL; } return 0; } static int wdt87xx_write_data(struct i2c_client *client, const char *data, u32 address, int length) { u16 packet_size; int count = 0; int error; u8 pkt_buf[PKT_BUF_SIZE]; /* Address and length should be 4 bytes aligned */ if ((address & 0x3) != 0 || (length & 0x3) != 0) { dev_err(&client->dev, "addr & len must be 4 bytes aligned %x, %x\n", address, length); return -EINVAL; } while (length) { packet_size = min(length, PACKET_SIZE); pkt_buf[CMD_REPORT_ID_OFFSET] = VND_REQ_WRITE; pkt_buf[CMD_TYPE_OFFSET] = VND_SET_DATA; put_unaligned_le16(packet_size, &pkt_buf[CMD_INDEX_OFFSET]); put_unaligned_le32(address, &pkt_buf[CMD_LENGTH_OFFSET]); memcpy(&pkt_buf[CMD_DATA_OFFSET], data, packet_size); error = wdt87xx_set_feature(client, pkt_buf, sizeof(pkt_buf)); if (error) return error; length -= packet_size; data += packet_size; address += packet_size; /* Wait for the controller to finish the write */ mdelay(WDT_FLASH_WRITE_DELAY_MS); if ((++count % 32) == 0) { /* Delay for fw to clear watch dog */ msleep(20); } } return 0; } static u16 misr(u16 cur_value, u8 new_value) { u32 a, b; u32 bit0; u32 y; a = cur_value; b = new_value; bit0 = a ^ (b & 1); bit0 ^= a >> 1; bit0 ^= a >> 2; bit0 ^= a >> 4; bit0 ^= a >> 5; bit0 ^= a >> 7; bit0 ^= a >> 11; bit0 ^= a >> 15; y = (a << 1) ^ b; y = (y & ~1) | (bit0 & 1); return (u16)y; } static u16 wdt87xx_calculate_checksum(const u8 *data, size_t length) { u16 checksum = 0; size_t i; for (i = 0; i < length; i++) checksum = misr(checksum, data[i]); return checksum; } static int wdt87xx_get_checksum(struct i2c_client *client, u16 *checksum, u32 address, int length) { int error; int time_delay; u8 pkt_buf[PKT_BUF_SIZE]; u8 cmd_buf[CMD_BUF_SIZE]; error = wdt87xx_send_command(client, VND_SET_CHECKSUM_LENGTH, length); if (error) { dev_err(&client->dev, "failed to set checksum length\n"); return error; } error = wdt87xx_send_command(client, VND_SET_CHECKSUM_CALC, address); if (error) { dev_err(&client->dev, "failed to set checksum address\n"); return error; } /* Wait the operation to complete */ time_delay = DIV_ROUND_UP(length, 1024); msleep(time_delay * 30); memset(cmd_buf, 0, sizeof(cmd_buf)); cmd_buf[CMD_REPORT_ID_OFFSET] = VND_REQ_READ; cmd_buf[CMD_TYPE_OFFSET] = VND_GET_CHECKSUM; error = wdt87xx_set_feature(client, cmd_buf, sizeof(cmd_buf)); if (error) { dev_err(&client->dev, "failed to request checksum\n"); return error; } memset(pkt_buf, 0, sizeof(pkt_buf)); pkt_buf[CMD_REPORT_ID_OFFSET] = VND_READ_DATA; error = wdt87xx_get_feature(client, pkt_buf, sizeof(pkt_buf)); if (error) { dev_err(&client->dev, "failed to read checksum\n"); return error; } *checksum = get_unaligned_le16(&pkt_buf[CMD_DATA_OFFSET]); return 0; } static int wdt87xx_write_firmware(struct i2c_client *client, const void *chunk) { u32 start_addr = get_unaligned_le32(chunk + FW_CHUNK_TGT_START_OFFSET); u32 size = get_unaligned_le32(chunk + FW_CHUNK_PAYLOAD_LEN_OFFSET); const void *data = chunk + FW_CHUNK_PAYLOAD_OFFSET; int error; int err1; int page_size; int retry = 0; u16 device_checksum, firmware_checksum; dev_dbg(&client->dev, "start 4k page program\n"); error = wdt87xx_send_command(client, VND_CMD_STOP, MODE_STOP); if (error) { dev_err(&client->dev, "stop report mode failed\n"); return error; } error = wdt87xx_send_command(client, VND_CMD_SFUNL, 0); if (error) { dev_err(&client->dev, "unlock failed\n"); goto out_enable_reporting; } mdelay(10); while (size) { dev_dbg(&client->dev, "%s: %x, %x\n", __func__, start_addr, size); page_size = min_t(u32, size, PG_SIZE); size -= page_size; for (retry = 0; retry < MAX_RETRIES; retry++) { error = wdt87xx_send_command(client, VND_CMD_ERASE, start_addr); if (error) { dev_err(&client->dev, "erase failed at %#08x\n", start_addr); break; } msleep(WDT_FLASH_ERASE_DELAY_MS); error = wdt87xx_write_data(client, data, start_addr, page_size); if (error) { dev_err(&client->dev, "write failed at %#08x (%d bytes)\n", start_addr, page_size); break; } error = wdt87xx_get_checksum(client, &device_checksum, start_addr, page_size); if (error) { dev_err(&client->dev, "failed to retrieve checksum for %#08x (len: %d)\n", start_addr, page_size); break; } firmware_checksum = wdt87xx_calculate_checksum(data, page_size); if (device_checksum == firmware_checksum) break; dev_err(&client->dev, "checksum fail: %d vs %d, retry %d\n", device_checksum, firmware_checksum, retry); } if (retry == MAX_RETRIES) { dev_err(&client->dev, "page write failed\n"); error = -EIO; goto out_lock_device; } start_addr = start_addr + page_size; data = data + page_size; } out_lock_device: err1 = wdt87xx_send_command(client, VND_CMD_SFLCK, 0); if (err1) dev_err(&client->dev, "lock failed\n"); mdelay(10); out_enable_reporting: err1 = wdt87xx_send_command(client, VND_CMD_START, 0); if (err1) dev_err(&client->dev, "start to report failed\n"); return error ? error : err1; } static int wdt87xx_load_chunk(struct i2c_client *client, const struct firmware *fw, u32 ck_id) { const void *chunk; int error; chunk = wdt87xx_get_fw_chunk(fw, ck_id); if (!chunk) { dev_err(&client->dev, "unable to locate chunk (type %d)\n", ck_id); return -EINVAL; } error = wdt87xx_validate_fw_chunk(chunk, ck_id); if (error) { dev_err(&client->dev, "invalid chunk (type %d): %d\n", ck_id, error); return error; } error = wdt87xx_write_firmware(client, chunk); if (error) { dev_err(&client->dev, "failed to write fw chunk (type %d): %d\n", ck_id, error); return error; } return 0; } static int wdt87xx_do_update_firmware(struct i2c_client *client, const struct firmware *fw, unsigned int chunk_id) { struct wdt87xx_data *wdt = i2c_get_clientdata(client); int error; error = wdt87xx_validate_firmware(wdt, fw); if (error) return error; error = mutex_lock_interruptible(&wdt->fw_mutex); if (error) return error; disable_irq(client->irq); error = wdt87xx_load_chunk(client, fw, chunk_id); if (error) { dev_err(&client->dev, "firmware load failed (type: %d): %d\n", chunk_id, error); goto out; } error = wdt87xx_sw_reset(client); if (error) { dev_err(&client->dev, "soft reset failed: %d\n", error); goto out; } /* Refresh the parameters */ error = wdt87xx_get_sysparam(client, &wdt->param); if (error) dev_err(&client->dev, "failed to refresh system parameters: %d\n", error); out: enable_irq(client->irq); mutex_unlock(&wdt->fw_mutex); return error ? error : 0; } static int wdt87xx_update_firmware(struct device *dev, const char *fw_name, unsigned int chunk_id) { struct i2c_client *client = to_i2c_client(dev); const struct firmware *fw; int error; error = request_firmware(&fw, fw_name, dev); if (error) { dev_err(&client->dev, "unable to retrieve firmware %s: %d\n", fw_name, error); return error; } error = wdt87xx_do_update_firmware(client, fw, chunk_id); release_firmware(fw); return error ? error : 0; } static ssize_t config_csum_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct wdt87xx_data *wdt = i2c_get_clientdata(client); u32 cfg_csum; cfg_csum = wdt->param.xmls_id1; cfg_csum = (cfg_csum << 16) | wdt->param.xmls_id2; return scnprintf(buf, PAGE_SIZE, "%x\n", cfg_csum); } static ssize_t fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct wdt87xx_data *wdt = i2c_get_clientdata(client); return scnprintf(buf, PAGE_SIZE, "%x\n", wdt->param.fw_id); } static ssize_t plat_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct wdt87xx_data *wdt = i2c_get_clientdata(client); return scnprintf(buf, PAGE_SIZE, "%x\n", wdt->param.plat_id); } static ssize_t update_config_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int error; error = wdt87xx_update_firmware(dev, WDT87XX_CFG_NAME, CHUNK_ID_CNFG); return error ? error : count; } static ssize_t update_fw_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int error; error = wdt87xx_update_firmware(dev, WDT87XX_FW_NAME, CHUNK_ID_FRWR); return error ? error : count; } static DEVICE_ATTR_RO(config_csum); static DEVICE_ATTR_RO(fw_version); static DEVICE_ATTR_RO(plat_id); static DEVICE_ATTR_WO(update_config); static DEVICE_ATTR_WO(update_fw); static struct attribute *wdt87xx_attrs[] = { &dev_attr_config_csum.attr, &dev_attr_fw_version.attr, &dev_attr_plat_id.attr, &dev_attr_update_config.attr, &dev_attr_update_fw.attr, NULL }; static const struct attribute_group wdt87xx_attr_group = { .attrs = wdt87xx_attrs, }; static void wdt87xx_report_contact(struct input_dev *input, struct wdt87xx_sys_param *param, u8 *buf) { int finger_id; u32 x, y, w; u8 p; finger_id = (buf[FINGER_EV_V1_OFFSET_ID] >> 3) - 1; if (finger_id < 0) return; /* Check if this is an active contact */ if (!(buf[FINGER_EV_V1_OFFSET_ID] & 0x1)) return; w = buf[FINGER_EV_V1_OFFSET_W]; w *= param->scaling_factor; p = buf[FINGER_EV_V1_OFFSET_P]; x = get_unaligned_le16(buf + FINGER_EV_V1_OFFSET_X); y = get_unaligned_le16(buf + FINGER_EV_V1_OFFSET_Y); y = DIV_ROUND_CLOSEST(y * param->phy_h, param->phy_w); /* Refuse incorrect coordinates */ if (x > param->max_x || y > param->max_y) return; dev_dbg(input->dev.parent, "tip on (%d), x(%d), y(%d)\n", finger_id, x, y); input_mt_slot(input, finger_id); input_mt_report_slot_state(input, MT_TOOL_FINGER, 1); input_report_abs(input, ABS_MT_TOUCH_MAJOR, w); input_report_abs(input, ABS_MT_PRESSURE, p); input_report_abs(input, ABS_MT_POSITION_X, x); input_report_abs(input, ABS_MT_POSITION_Y, y); } static irqreturn_t wdt87xx_ts_interrupt(int irq, void *dev_id) { struct wdt87xx_data *wdt = dev_id; struct i2c_client *client = wdt->client; int i, fingers; int error; u8 raw_buf[WDT_V1_RAW_BUF_COUNT] = {0}; error = i2c_master_recv(client, raw_buf, WDT_V1_RAW_BUF_COUNT); if (error < 0) { dev_err(&client->dev, "read v1 raw data failed: %d\n", error); goto irq_exit; } fingers = raw_buf[TOUCH_PK_V1_OFFSET_FNGR_NUM]; if (!fingers) goto irq_exit; for (i = 0; i < WDT_MAX_FINGER; i++) wdt87xx_report_contact(wdt->input, &wdt->param, &raw_buf[TOUCH_PK_V1_OFFSET_EVENT + i * FINGER_EV_V1_SIZE]); input_mt_sync_frame(wdt->input); input_sync(wdt->input); irq_exit: return IRQ_HANDLED; } static int wdt87xx_ts_create_input_device(struct wdt87xx_data *wdt) { struct device *dev = &wdt->client->dev; struct input_dev *input; unsigned int res = DIV_ROUND_CLOSEST(MAX_UNIT_AXIS, wdt->param.phy_w); int error; input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "failed to allocate input device\n"); return -ENOMEM; } wdt->input = input; input->name = "WDT87xx Touchscreen"; input->id.bustype = BUS_I2C; input->id.vendor = wdt->param.vendor_id; input->id.product = wdt->param.product_id; input->phys = wdt->phys; input_set_abs_params(input, ABS_MT_POSITION_X, 0, wdt->param.max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, wdt->param.max_y, 0, 0); input_abs_set_res(input, ABS_MT_POSITION_X, res); input_abs_set_res(input, ABS_MT_POSITION_Y, res); input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, wdt->param.max_x, 0, 0); input_set_abs_params(input, ABS_MT_PRESSURE, 0, 0xFF, 0, 0); input_mt_init_slots(input, WDT_MAX_FINGER, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); error = input_register_device(input); if (error) { dev_err(dev, "failed to register input device: %d\n", error); return error; } return 0; } static int wdt87xx_ts_probe(struct i2c_client *client) { struct wdt87xx_data *wdt; int error; dev_dbg(&client->dev, "adapter=%d, client irq: %d\n", client->adapter->nr, client->irq); /* Check if the I2C function is ok in this adaptor */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) return -ENXIO; wdt = devm_kzalloc(&client->dev, sizeof(*wdt), GFP_KERNEL); if (!wdt) return -ENOMEM; wdt->client = client; mutex_init(&wdt->fw_mutex); i2c_set_clientdata(client, wdt); snprintf(wdt->phys, sizeof(wdt->phys), "i2c-%u-%04x/input0", client->adapter->nr, client->addr); error = wdt87xx_get_sysparam(client, &wdt->param); if (error) return error; error = wdt87xx_ts_create_input_device(wdt); if (error) return error; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, wdt87xx_ts_interrupt, IRQF_ONESHOT, client->name, wdt); if (error) { dev_err(&client->dev, "request irq failed: %d\n", error); return error; } error = devm_device_add_group(&client->dev, &wdt87xx_attr_group); if (error) { dev_err(&client->dev, "create sysfs failed: %d\n", error); return error; } return 0; } static int wdt87xx_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); int error; disable_irq(client->irq); error = wdt87xx_send_command(client, VND_CMD_STOP, MODE_IDLE); if (error) { enable_irq(client->irq); dev_err(&client->dev, "failed to stop device when suspending: %d\n", error); return error; } return 0; } static int wdt87xx_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); int error; /* * The chip may have been reset while system is resuming, * give it some time to settle. */ msleep(100); error = wdt87xx_send_command(client, VND_CMD_START, 0); if (error) dev_err(&client->dev, "failed to start device when resuming: %d\n", error); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(wdt87xx_pm_ops, wdt87xx_suspend, wdt87xx_resume); static const struct i2c_device_id wdt87xx_dev_id[] = { { WDT87XX_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, wdt87xx_dev_id); static const struct acpi_device_id wdt87xx_acpi_id[] = { { "WDHT0001", 0 }, { } }; MODULE_DEVICE_TABLE(acpi, wdt87xx_acpi_id); static struct i2c_driver wdt87xx_driver = { .probe = wdt87xx_ts_probe, .id_table = wdt87xx_dev_id, .driver = { .name = WDT87XX_NAME, .pm = pm_sleep_ptr(&wdt87xx_pm_ops), .acpi_match_table = ACPI_PTR(wdt87xx_acpi_id), }, }; module_i2c_driver(wdt87xx_driver); MODULE_AUTHOR("HN Chen <[email protected]>"); MODULE_DESCRIPTION("WeidaHiTech WDT87XX Touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wdt87xx_i2c.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for ChipOne icn8318 i2c touchscreen controller * * Copyright (c) 2015 Red Hat Inc. * * Red Hat authors: * Hans de Goede <[email protected]> */ #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/module.h> #include <linux/of.h> #define ICN8318_REG_POWER 4 #define ICN8318_REG_TOUCHDATA 16 #define ICN8318_POWER_ACTIVE 0 #define ICN8318_POWER_MONITOR 1 #define ICN8318_POWER_HIBERNATE 2 #define ICN8318_MAX_TOUCHES 5 struct icn8318_touch { __u8 slot; __be16 x; __be16 y; __u8 pressure; /* Seems more like finger width then pressure really */ __u8 event; /* The difference between 2 and 3 is unclear */ #define ICN8318_EVENT_NO_DATA 1 /* No finger seen yet since wakeup */ #define ICN8318_EVENT_UPDATE1 2 /* New or updated coordinates */ #define ICN8318_EVENT_UPDATE2 3 /* New or updated coordinates */ #define ICN8318_EVENT_END 4 /* Finger lifted */ } __packed; struct icn8318_touch_data { __u8 softbutton; __u8 touch_count; struct icn8318_touch touches[ICN8318_MAX_TOUCHES]; } __packed; struct icn8318_data { struct i2c_client *client; struct input_dev *input; struct gpio_desc *wake_gpio; struct touchscreen_properties prop; }; static int icn8318_read_touch_data(struct i2c_client *client, struct icn8318_touch_data *touch_data) { u8 reg = ICN8318_REG_TOUCHDATA; struct i2c_msg msg[2] = { { .addr = client->addr, .len = 1, .buf = &reg }, { .addr = client->addr, .flags = I2C_M_RD, .len = sizeof(struct icn8318_touch_data), .buf = (u8 *)touch_data } }; return i2c_transfer(client->adapter, msg, 2); } static inline bool icn8318_touch_active(u8 event) { return (event == ICN8318_EVENT_UPDATE1) || (event == ICN8318_EVENT_UPDATE2); } static irqreturn_t icn8318_irq(int irq, void *dev_id) { struct icn8318_data *data = dev_id; struct device *dev = &data->client->dev; struct icn8318_touch_data touch_data; int i, ret; ret = icn8318_read_touch_data(data->client, &touch_data); if (ret < 0) { dev_err(dev, "Error reading touch data: %d\n", ret); return IRQ_HANDLED; } if (touch_data.softbutton) { /* * Other data is invalid when a softbutton is pressed. * This needs some extra devicetree bindings to map the icn8318 * softbutton codes to evdev codes. Currently no known devices * use this. */ return IRQ_HANDLED; } if (touch_data.touch_count > ICN8318_MAX_TOUCHES) { dev_warn(dev, "Too much touches %d > %d\n", touch_data.touch_count, ICN8318_MAX_TOUCHES); touch_data.touch_count = ICN8318_MAX_TOUCHES; } for (i = 0; i < touch_data.touch_count; i++) { struct icn8318_touch *touch = &touch_data.touches[i]; bool act = icn8318_touch_active(touch->event); input_mt_slot(data->input, touch->slot); input_mt_report_slot_state(data->input, MT_TOOL_FINGER, act); if (!act) continue; touchscreen_report_pos(data->input, &data->prop, be16_to_cpu(touch->x), be16_to_cpu(touch->y), true); } input_mt_sync_frame(data->input); input_sync(data->input); return IRQ_HANDLED; } static int icn8318_start(struct input_dev *dev) { struct icn8318_data *data = input_get_drvdata(dev); enable_irq(data->client->irq); gpiod_set_value_cansleep(data->wake_gpio, 1); return 0; } static void icn8318_stop(struct input_dev *dev) { struct icn8318_data *data = input_get_drvdata(dev); disable_irq(data->client->irq); i2c_smbus_write_byte_data(data->client, ICN8318_REG_POWER, ICN8318_POWER_HIBERNATE); gpiod_set_value_cansleep(data->wake_gpio, 0); } static int icn8318_suspend(struct device *dev) { struct icn8318_data *data = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&data->input->mutex); if (input_device_enabled(data->input)) icn8318_stop(data->input); mutex_unlock(&data->input->mutex); return 0; } static int icn8318_resume(struct device *dev) { struct icn8318_data *data = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&data->input->mutex); if (input_device_enabled(data->input)) icn8318_start(data->input); mutex_unlock(&data->input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(icn8318_pm_ops, icn8318_suspend, icn8318_resume); static int icn8318_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct icn8318_data *data; struct input_dev *input; int error; if (!client->irq) { dev_err(dev, "Error no irq specified\n"); return -EINVAL; } data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->wake_gpio = devm_gpiod_get(dev, "wake", GPIOD_OUT_LOW); if (IS_ERR(data->wake_gpio)) return dev_err_probe(dev, PTR_ERR(data->wake_gpio), "Error getting wake gpio\n"); input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = client->name; input->id.bustype = BUS_I2C; input->open = icn8318_start; input->close = icn8318_stop; input->dev.parent = dev; input_set_capability(input, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input, EV_ABS, ABS_MT_POSITION_Y); touchscreen_parse_properties(input, true, &data->prop); if (!input_abs_get_max(input, ABS_MT_POSITION_X) || !input_abs_get_max(input, ABS_MT_POSITION_Y)) { dev_err(dev, "Error touchscreen-size-x and/or -y missing\n"); return -EINVAL; } error = input_mt_init_slots(input, ICN8318_MAX_TOUCHES, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; data->client = client; data->input = input; input_set_drvdata(input, data); error = devm_request_threaded_irq(dev, client->irq, NULL, icn8318_irq, IRQF_ONESHOT, client->name, data); if (error) { dev_err(dev, "Error requesting irq: %d\n", error); return error; } /* Stop device till opened */ icn8318_stop(data->input); error = input_register_device(input); if (error) return error; i2c_set_clientdata(client, data); return 0; } static const struct of_device_id icn8318_of_match[] = { { .compatible = "chipone,icn8318" }, { } }; MODULE_DEVICE_TABLE(of, icn8318_of_match); /* This is useless for OF-enabled devices, but it is needed by I2C subsystem */ static const struct i2c_device_id icn8318_i2c_id[] = { { }, }; MODULE_DEVICE_TABLE(i2c, icn8318_i2c_id); static struct i2c_driver icn8318_driver = { .driver = { .name = "chipone_icn8318", .pm = pm_sleep_ptr(&icn8318_pm_ops), .of_match_table = icn8318_of_match, }, .probe = icn8318_probe, .id_table = icn8318_i2c_id, }; module_i2c_driver(icn8318_driver); MODULE_DESCRIPTION("ChipOne icn8318 I2C Touchscreen Driver"); MODULE_AUTHOR("Hans de Goede <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/chipone_icn8318.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for I2C connected EETI EXC3000 multiple touch controller * * Copyright (C) 2017 Ahmet Inan <[email protected]> * * minimal implementation based on egalax_ts.c and egalax_i2c.c */ #include <linux/acpi.h> #include <linux/bitops.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of.h> #include <linux/regulator/consumer.h> #include <linux/sizes.h> #include <linux/timer.h> #include <asm/unaligned.h> #define EXC3000_NUM_SLOTS 10 #define EXC3000_SLOTS_PER_FRAME 5 #define EXC3000_LEN_FRAME 66 #define EXC3000_LEN_VENDOR_REQUEST 68 #define EXC3000_LEN_POINT 10 #define EXC3000_LEN_MODEL_NAME 16 #define EXC3000_LEN_FW_VERSION 16 #define EXC3000_VENDOR_EVENT 0x03 #define EXC3000_MT1_EVENT 0x06 #define EXC3000_MT2_EVENT 0x18 #define EXC3000_TIMEOUT_MS 100 #define EXC3000_RESET_MS 10 #define EXC3000_READY_MS 100 static const struct i2c_device_id exc3000_id[]; struct eeti_dev_info { const char *name; int max_xy; }; enum eeti_dev_id { EETI_EXC3000, EETI_EXC80H60, EETI_EXC80H84, }; static struct eeti_dev_info exc3000_info[] = { [EETI_EXC3000] = { .name = "EETI EXC3000 Touch Screen", .max_xy = SZ_4K - 1, }, [EETI_EXC80H60] = { .name = "EETI EXC80H60 Touch Screen", .max_xy = SZ_16K - 1, }, [EETI_EXC80H84] = { .name = "EETI EXC80H84 Touch Screen", .max_xy = SZ_16K - 1, }, }; struct exc3000_data { struct i2c_client *client; const struct eeti_dev_info *info; struct input_dev *input; struct touchscreen_properties prop; struct gpio_desc *reset; struct timer_list timer; u8 buf[2 * EXC3000_LEN_FRAME]; struct completion wait_event; struct mutex query_lock; }; static void exc3000_report_slots(struct input_dev *input, struct touchscreen_properties *prop, const u8 *buf, int num) { for (; num--; buf += EXC3000_LEN_POINT) { if (buf[0] & BIT(0)) { input_mt_slot(input, buf[1]); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); touchscreen_report_pos(input, prop, get_unaligned_le16(buf + 2), get_unaligned_le16(buf + 4), true); } } } static void exc3000_timer(struct timer_list *t) { struct exc3000_data *data = from_timer(data, t, timer); input_mt_sync_frame(data->input); input_sync(data->input); } static inline void exc3000_schedule_timer(struct exc3000_data *data) { mod_timer(&data->timer, jiffies + msecs_to_jiffies(EXC3000_TIMEOUT_MS)); } static void exc3000_shutdown_timer(void *timer) { timer_shutdown_sync(timer); } static int exc3000_read_frame(struct exc3000_data *data, u8 *buf) { struct i2c_client *client = data->client; int ret; ret = i2c_master_send(client, "'", 2); if (ret < 0) return ret; if (ret != 2) return -EIO; ret = i2c_master_recv(client, buf, EXC3000_LEN_FRAME); if (ret < 0) return ret; if (ret != EXC3000_LEN_FRAME) return -EIO; if (get_unaligned_le16(buf) != EXC3000_LEN_FRAME) return -EINVAL; return 0; } static int exc3000_handle_mt_event(struct exc3000_data *data) { struct input_dev *input = data->input; int ret, total_slots; u8 *buf = data->buf; total_slots = buf[3]; if (!total_slots || total_slots > EXC3000_NUM_SLOTS) { ret = -EINVAL; goto out_fail; } if (total_slots > EXC3000_SLOTS_PER_FRAME) { /* Read 2nd frame to get the rest of the contacts. */ ret = exc3000_read_frame(data, buf + EXC3000_LEN_FRAME); if (ret) goto out_fail; /* 2nd chunk must have number of contacts set to 0. */ if (buf[EXC3000_LEN_FRAME + 3] != 0) { ret = -EINVAL; goto out_fail; } } /* * We read full state successfully, no contacts will be "stuck". */ del_timer_sync(&data->timer); while (total_slots > 0) { int slots = min(total_slots, EXC3000_SLOTS_PER_FRAME); exc3000_report_slots(input, &data->prop, buf + 4, slots); total_slots -= slots; buf += EXC3000_LEN_FRAME; } input_mt_sync_frame(input); input_sync(input); return 0; out_fail: /* Schedule a timer to release "stuck" contacts */ exc3000_schedule_timer(data); return ret; } static irqreturn_t exc3000_interrupt(int irq, void *dev_id) { struct exc3000_data *data = dev_id; u8 *buf = data->buf; int ret; ret = exc3000_read_frame(data, buf); if (ret) { /* Schedule a timer to release "stuck" contacts */ exc3000_schedule_timer(data); goto out; } switch (buf[2]) { case EXC3000_VENDOR_EVENT: complete(&data->wait_event); break; case EXC3000_MT1_EVENT: case EXC3000_MT2_EVENT: exc3000_handle_mt_event(data); break; default: break; } out: return IRQ_HANDLED; } static int exc3000_vendor_data_request(struct exc3000_data *data, u8 *request, u8 request_len, u8 *response, int timeout) { u8 buf[EXC3000_LEN_VENDOR_REQUEST] = { 0x67, 0x00, 0x42, 0x00, 0x03 }; int ret; unsigned long time_left; mutex_lock(&data->query_lock); reinit_completion(&data->wait_event); buf[5] = request_len; memcpy(&buf[6], request, request_len); ret = i2c_master_send(data->client, buf, EXC3000_LEN_VENDOR_REQUEST); if (ret < 0) goto out_unlock; if (response) { time_left = wait_for_completion_timeout(&data->wait_event, timeout * HZ); if (time_left == 0) { ret = -ETIMEDOUT; goto out_unlock; } if (data->buf[3] >= EXC3000_LEN_FRAME) { ret = -ENOSPC; goto out_unlock; } memcpy(response, &data->buf[4], data->buf[3]); ret = data->buf[3]; } out_unlock: mutex_unlock(&data->query_lock); return ret; } static ssize_t fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct exc3000_data *data = i2c_get_clientdata(client); u8 response[EXC3000_LEN_FRAME]; int ret; /* query bootloader info */ ret = exc3000_vendor_data_request(data, (u8[]){0x39, 0x02}, 2, response, 1); if (ret < 0) return ret; /* * If the bootloader version is non-zero then the device is in * bootloader mode and won't answer a query for the application FW * version, so we just use the bootloader version info. */ if (response[2] || response[3]) return sprintf(buf, "%d.%d\n", response[2], response[3]); ret = exc3000_vendor_data_request(data, (u8[]){'D'}, 1, response, 1); if (ret < 0) return ret; return sprintf(buf, "%s\n", &response[1]); } static DEVICE_ATTR_RO(fw_version); static ssize_t model_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct exc3000_data *data = i2c_get_clientdata(client); u8 response[EXC3000_LEN_FRAME]; int ret; ret = exc3000_vendor_data_request(data, (u8[]){'E'}, 1, response, 1); if (ret < 0) return ret; return sprintf(buf, "%s\n", &response[1]); } static DEVICE_ATTR_RO(model); static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct exc3000_data *data = i2c_get_clientdata(client); u8 response[EXC3000_LEN_FRAME]; int ret; ret = exc3000_vendor_data_request(data, (u8[]){'F'}, 1, response, 1); if (ret < 0) return ret; return sprintf(buf, "%s\n", &response[1]); } static DEVICE_ATTR_RO(type); static struct attribute *sysfs_attrs[] = { &dev_attr_fw_version.attr, &dev_attr_model.attr, &dev_attr_type.attr, NULL }; static struct attribute_group exc3000_attribute_group = { .attrs = sysfs_attrs }; static int exc3000_probe(struct i2c_client *client) { struct exc3000_data *data; struct input_dev *input; int error, max_xy, retry; data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->client = client; data->info = device_get_match_data(&client->dev); if (!data->info) { enum eeti_dev_id eeti_dev_id = i2c_match_id(exc3000_id, client)->driver_data; data->info = &exc3000_info[eeti_dev_id]; } timer_setup(&data->timer, exc3000_timer, 0); init_completion(&data->wait_event); mutex_init(&data->query_lock); data->reset = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(data->reset)) return PTR_ERR(data->reset); /* For proper reset sequence, enable power while reset asserted */ error = devm_regulator_get_enable(&client->dev, "vdd"); if (error && error != -ENODEV) return dev_err_probe(&client->dev, error, "failed to request vdd regulator\n"); if (data->reset) { msleep(EXC3000_RESET_MS); gpiod_set_value_cansleep(data->reset, 0); msleep(EXC3000_READY_MS); } input = devm_input_allocate_device(&client->dev); if (!input) return -ENOMEM; data->input = input; input_set_drvdata(input, data); input->name = data->info->name; input->id.bustype = BUS_I2C; max_xy = data->info->max_xy; input_set_abs_params(input, ABS_MT_POSITION_X, 0, max_xy, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, max_xy, 0, 0); touchscreen_parse_properties(input, true, &data->prop); error = input_mt_init_slots(input, EXC3000_NUM_SLOTS, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; error = input_register_device(input); if (error) return error; error = devm_add_action_or_reset(&client->dev, exc3000_shutdown_timer, &data->timer); if (error) return error; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, exc3000_interrupt, IRQF_ONESHOT, client->name, data); if (error) return error; /* * I²C does not have built-in recovery, so retry on failure. This * ensures, that the device probe will not fail for temporary issues * on the bus. This is not needed for the sysfs calls (userspace * will receive the error code and can start another query) and * cannot be done for touch events (but that only means loosing one * or two touch events anyways). */ for (retry = 0; retry < 3; retry++) { u8 response[EXC3000_LEN_FRAME]; error = exc3000_vendor_data_request(data, (u8[]){'E'}, 1, response, 1); if (error > 0) { dev_dbg(&client->dev, "TS Model: %s", &response[1]); error = 0; break; } dev_warn(&client->dev, "Retry %d get EETI EXC3000 model: %d\n", retry + 1, error); } if (error) return error; i2c_set_clientdata(client, data); error = devm_device_add_group(&client->dev, &exc3000_attribute_group); if (error) return error; return 0; } static const struct i2c_device_id exc3000_id[] = { { "exc3000", EETI_EXC3000 }, { "exc80h60", EETI_EXC80H60 }, { "exc80h84", EETI_EXC80H84 }, { } }; MODULE_DEVICE_TABLE(i2c, exc3000_id); #ifdef CONFIG_OF static const struct of_device_id exc3000_of_match[] = { { .compatible = "eeti,exc3000", .data = &exc3000_info[EETI_EXC3000] }, { .compatible = "eeti,exc80h60", .data = &exc3000_info[EETI_EXC80H60] }, { .compatible = "eeti,exc80h84", .data = &exc3000_info[EETI_EXC80H84] }, { } }; MODULE_DEVICE_TABLE(of, exc3000_of_match); #endif #ifdef CONFIG_ACPI static const struct acpi_device_id exc3000_acpi_match[] = { { "EGA00001", .driver_data = (kernel_ulong_t)&exc3000_info[EETI_EXC80H60] }, { } }; MODULE_DEVICE_TABLE(acpi, exc3000_acpi_match); #endif static struct i2c_driver exc3000_driver = { .driver = { .name = "exc3000", .of_match_table = of_match_ptr(exc3000_of_match), .acpi_match_table = ACPI_PTR(exc3000_acpi_match), }, .id_table = exc3000_id, .probe = exc3000_probe, }; module_i2c_driver(exc3000_driver); MODULE_AUTHOR("Ahmet Inan <[email protected]>"); MODULE_DESCRIPTION("I2C connected EETI EXC3000 multiple touch controller driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/exc3000.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/input.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <asm/io.h> #include <asm/delay.h> #include <asm/adc.h> #include <mach/hp6xx.h> #define MODNAME "hp680_ts_input" #define HP680_TS_ABS_X_MIN 40 #define HP680_TS_ABS_X_MAX 950 #define HP680_TS_ABS_Y_MIN 80 #define HP680_TS_ABS_Y_MAX 910 #define PHDR 0xa400012e #define SCPDR 0xa4000136 static void do_softint(struct work_struct *work); static struct input_dev *hp680_ts_dev; static DECLARE_DELAYED_WORK(work, do_softint); static void do_softint(struct work_struct *work) { int absx = 0, absy = 0; u8 scpdr; int touched = 0; if (__raw_readb(PHDR) & PHDR_TS_PEN_DOWN) { scpdr = __raw_readb(SCPDR); scpdr |= SCPDR_TS_SCAN_ENABLE; scpdr &= ~SCPDR_TS_SCAN_Y; __raw_writeb(scpdr, SCPDR); udelay(30); absy = adc_single(ADC_CHANNEL_TS_Y); scpdr = __raw_readb(SCPDR); scpdr |= SCPDR_TS_SCAN_Y; scpdr &= ~SCPDR_TS_SCAN_X; __raw_writeb(scpdr, SCPDR); udelay(30); absx = adc_single(ADC_CHANNEL_TS_X); scpdr = __raw_readb(SCPDR); scpdr |= SCPDR_TS_SCAN_X; scpdr &= ~SCPDR_TS_SCAN_ENABLE; __raw_writeb(scpdr, SCPDR); udelay(100); touched = __raw_readb(PHDR) & PHDR_TS_PEN_DOWN; } if (touched) { input_report_key(hp680_ts_dev, BTN_TOUCH, 1); input_report_abs(hp680_ts_dev, ABS_X, absx); input_report_abs(hp680_ts_dev, ABS_Y, absy); } else { input_report_key(hp680_ts_dev, BTN_TOUCH, 0); } input_sync(hp680_ts_dev); enable_irq(HP680_TS_IRQ); } static irqreturn_t hp680_ts_interrupt(int irq, void *dev) { disable_irq_nosync(irq); schedule_delayed_work(&work, HZ / 20); return IRQ_HANDLED; } static int __init hp680_ts_init(void) { int err; hp680_ts_dev = input_allocate_device(); if (!hp680_ts_dev) return -ENOMEM; hp680_ts_dev->evbit[0] = BIT_MASK(EV_ABS) | BIT_MASK(EV_KEY); hp680_ts_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(hp680_ts_dev, ABS_X, HP680_TS_ABS_X_MIN, HP680_TS_ABS_X_MAX, 0, 0); input_set_abs_params(hp680_ts_dev, ABS_Y, HP680_TS_ABS_Y_MIN, HP680_TS_ABS_Y_MAX, 0, 0); hp680_ts_dev->name = "HP Jornada touchscreen"; hp680_ts_dev->phys = "hp680_ts/input0"; if (request_irq(HP680_TS_IRQ, hp680_ts_interrupt, 0, MODNAME, NULL) < 0) { printk(KERN_ERR "hp680_touchscreen.c: Can't allocate irq %d\n", HP680_TS_IRQ); err = -EBUSY; goto fail1; } err = input_register_device(hp680_ts_dev); if (err) goto fail2; return 0; fail2: free_irq(HP680_TS_IRQ, NULL); cancel_delayed_work_sync(&work); fail1: input_free_device(hp680_ts_dev); return err; } static void __exit hp680_ts_exit(void) { free_irq(HP680_TS_IRQ, NULL); cancel_delayed_work_sync(&work); input_unregister_device(hp680_ts_dev); } module_init(hp680_ts_init); module_exit(hp680_ts_exit); MODULE_AUTHOR("Andriy Skulysh, [email protected]"); MODULE_DESCRIPTION("HP Jornada 680 touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/hp680_ts_input.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * TSI driver for Dialog DA9052 * * Copyright(c) 2012 Dialog Semiconductor Ltd. * * Author: David Dajun Chen <[email protected]> */ #include <linux/module.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/mfd/da9052/reg.h> #include <linux/mfd/da9052/da9052.h> #define TSI_PEN_DOWN_STATUS 0x40 struct da9052_tsi { struct da9052 *da9052; struct input_dev *dev; struct delayed_work ts_pen_work; bool stopped; bool adc_on; }; static void da9052_ts_adc_toggle(struct da9052_tsi *tsi, bool on) { da9052_reg_update(tsi->da9052, DA9052_TSI_CONT_A_REG, 1 << 0, on); tsi->adc_on = on; } static irqreturn_t da9052_ts_pendwn_irq(int irq, void *data) { struct da9052_tsi *tsi = data; if (!tsi->stopped) { /* Mask PEN_DOWN event and unmask TSI_READY event */ da9052_disable_irq_nosync(tsi->da9052, DA9052_IRQ_PENDOWN); da9052_enable_irq(tsi->da9052, DA9052_IRQ_TSIREADY); da9052_ts_adc_toggle(tsi, true); schedule_delayed_work(&tsi->ts_pen_work, HZ / 50); } return IRQ_HANDLED; } static void da9052_ts_read(struct da9052_tsi *tsi) { struct input_dev *input = tsi->dev; int ret; u16 x, y, z; u8 v; ret = da9052_reg_read(tsi->da9052, DA9052_TSI_X_MSB_REG); if (ret < 0) return; x = (u16) ret; ret = da9052_reg_read(tsi->da9052, DA9052_TSI_Y_MSB_REG); if (ret < 0) return; y = (u16) ret; ret = da9052_reg_read(tsi->da9052, DA9052_TSI_Z_MSB_REG); if (ret < 0) return; z = (u16) ret; ret = da9052_reg_read(tsi->da9052, DA9052_TSI_LSB_REG); if (ret < 0) return; v = (u8) ret; x = ((x << 2) & 0x3fc) | (v & 0x3); y = ((y << 2) & 0x3fc) | ((v & 0xc) >> 2); z = ((z << 2) & 0x3fc) | ((v & 0x30) >> 4); input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, x); input_report_abs(input, ABS_Y, y); input_report_abs(input, ABS_PRESSURE, z); input_sync(input); } static irqreturn_t da9052_ts_datardy_irq(int irq, void *data) { struct da9052_tsi *tsi = data; da9052_ts_read(tsi); return IRQ_HANDLED; } static void da9052_ts_pen_work(struct work_struct *work) { struct da9052_tsi *tsi = container_of(work, struct da9052_tsi, ts_pen_work.work); if (!tsi->stopped) { int ret = da9052_reg_read(tsi->da9052, DA9052_TSI_LSB_REG); if (ret < 0 || (ret & TSI_PEN_DOWN_STATUS)) { /* Pen is still DOWN (or read error) */ schedule_delayed_work(&tsi->ts_pen_work, HZ / 50); } else { struct input_dev *input = tsi->dev; /* Pen UP */ da9052_ts_adc_toggle(tsi, false); /* Report Pen UP */ input_report_key(input, BTN_TOUCH, 0); input_report_abs(input, ABS_PRESSURE, 0); input_sync(input); /* * FIXME: Fixes the unhandled irq issue when quick * pen down and pen up events occurs */ ret = da9052_reg_update(tsi->da9052, DA9052_EVENT_B_REG, 0xC0, 0xC0); if (ret < 0) return; /* Mask TSI_READY event and unmask PEN_DOWN event */ da9052_disable_irq(tsi->da9052, DA9052_IRQ_TSIREADY); da9052_enable_irq(tsi->da9052, DA9052_IRQ_PENDOWN); } } } static int da9052_ts_configure_gpio(struct da9052 *da9052) { int error; error = da9052_reg_update(da9052, DA9052_GPIO_2_3_REG, 0x30, 0); if (error < 0) return error; error = da9052_reg_update(da9052, DA9052_GPIO_4_5_REG, 0x33, 0); if (error < 0) return error; error = da9052_reg_update(da9052, DA9052_GPIO_6_7_REG, 0x33, 0); if (error < 0) return error; return 0; } static int da9052_configure_tsi(struct da9052_tsi *tsi) { int error; error = da9052_ts_configure_gpio(tsi->da9052); if (error) return error; /* Measure TSI sample every 1ms */ error = da9052_reg_update(tsi->da9052, DA9052_ADC_CONT_REG, 1 << 6, 1 << 6); if (error < 0) return error; /* TSI_DELAY: 3 slots, TSI_SKIP: 0 slots, TSI_MODE: XYZP */ error = da9052_reg_update(tsi->da9052, DA9052_TSI_CONT_A_REG, 0xFC, 0xC0); if (error < 0) return error; /* Supply TSIRef through LD09 */ error = da9052_reg_write(tsi->da9052, DA9052_LDO9_REG, 0x59); if (error < 0) return error; return 0; } static int da9052_ts_input_open(struct input_dev *input_dev) { struct da9052_tsi *tsi = input_get_drvdata(input_dev); tsi->stopped = false; mb(); /* Unmask PEN_DOWN event */ da9052_enable_irq(tsi->da9052, DA9052_IRQ_PENDOWN); /* Enable Pen Detect Circuit */ return da9052_reg_update(tsi->da9052, DA9052_TSI_CONT_A_REG, 1 << 1, 1 << 1); } static void da9052_ts_input_close(struct input_dev *input_dev) { struct da9052_tsi *tsi = input_get_drvdata(input_dev); tsi->stopped = true; mb(); da9052_disable_irq(tsi->da9052, DA9052_IRQ_PENDOWN); cancel_delayed_work_sync(&tsi->ts_pen_work); if (tsi->adc_on) { da9052_disable_irq(tsi->da9052, DA9052_IRQ_TSIREADY); da9052_ts_adc_toggle(tsi, false); /* * If ADC was on that means that pendwn IRQ was disabled * twice and we need to enable it to keep enable/disable * counter balanced. IRQ is still off though. */ da9052_enable_irq(tsi->da9052, DA9052_IRQ_PENDOWN); } /* Disable Pen Detect Circuit */ da9052_reg_update(tsi->da9052, DA9052_TSI_CONT_A_REG, 1 << 1, 0); } static int da9052_ts_probe(struct platform_device *pdev) { struct da9052 *da9052; struct da9052_tsi *tsi; struct input_dev *input_dev; int error; da9052 = dev_get_drvdata(pdev->dev.parent); if (!da9052) return -EINVAL; tsi = kzalloc(sizeof(struct da9052_tsi), GFP_KERNEL); input_dev = input_allocate_device(); if (!tsi || !input_dev) { error = -ENOMEM; goto err_free_mem; } tsi->da9052 = da9052; tsi->dev = input_dev; tsi->stopped = true; INIT_DELAYED_WORK(&tsi->ts_pen_work, da9052_ts_pen_work); input_dev->id.version = 0x0101; input_dev->id.vendor = 0x15B6; input_dev->id.product = 0x9052; input_dev->name = "Dialog DA9052 TouchScreen Driver"; input_dev->dev.parent = &pdev->dev; input_dev->open = da9052_ts_input_open; input_dev->close = da9052_ts_input_close; __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); input_set_abs_params(input_dev, ABS_X, 0, 1023, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, 1023, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 1023, 0, 0); input_set_drvdata(input_dev, tsi); /* Disable Pen Detect Circuit */ da9052_reg_update(tsi->da9052, DA9052_TSI_CONT_A_REG, 1 << 1, 0); /* Disable ADC */ da9052_ts_adc_toggle(tsi, false); error = da9052_request_irq(tsi->da9052, DA9052_IRQ_PENDOWN, "pendown-irq", da9052_ts_pendwn_irq, tsi); if (error) { dev_err(tsi->da9052->dev, "Failed to register PENDWN IRQ: %d\n", error); goto err_free_mem; } error = da9052_request_irq(tsi->da9052, DA9052_IRQ_TSIREADY, "tsiready-irq", da9052_ts_datardy_irq, tsi); if (error) { dev_err(tsi->da9052->dev, "Failed to register TSIRDY IRQ :%d\n", error); goto err_free_pendwn_irq; } /* Mask PEN_DOWN and TSI_READY events */ da9052_disable_irq(tsi->da9052, DA9052_IRQ_PENDOWN); da9052_disable_irq(tsi->da9052, DA9052_IRQ_TSIREADY); error = da9052_configure_tsi(tsi); if (error) goto err_free_datardy_irq; error = input_register_device(tsi->dev); if (error) goto err_free_datardy_irq; platform_set_drvdata(pdev, tsi); return 0; err_free_datardy_irq: da9052_free_irq(tsi->da9052, DA9052_IRQ_TSIREADY, tsi); err_free_pendwn_irq: da9052_free_irq(tsi->da9052, DA9052_IRQ_PENDOWN, tsi); err_free_mem: kfree(tsi); input_free_device(input_dev); return error; } static int da9052_ts_remove(struct platform_device *pdev) { struct da9052_tsi *tsi = platform_get_drvdata(pdev); da9052_reg_write(tsi->da9052, DA9052_LDO9_REG, 0x19); da9052_free_irq(tsi->da9052, DA9052_IRQ_TSIREADY, tsi); da9052_free_irq(tsi->da9052, DA9052_IRQ_PENDOWN, tsi); input_unregister_device(tsi->dev); kfree(tsi); return 0; } static struct platform_driver da9052_tsi_driver = { .probe = da9052_ts_probe, .remove = da9052_ts_remove, .driver = { .name = "da9052-tsi", }, }; module_platform_driver(da9052_tsi_driver); MODULE_DESCRIPTION("Touchscreen driver for Dialog Semiconductor DA9052"); MODULE_AUTHOR("Anthony Olech <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:da9052-tsi");
linux-master
drivers/input/touchscreen/da9052_tsi.c
// SPDX-License-Identifier: GPL-2.0-only /* * TSC-40 serial touchscreen driver. It should be compatible with * TSC-10 and 25. * * Author: Sebastian Andrzej Siewior <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/serio.h> #define PACKET_LENGTH 5 struct tsc_ser { struct input_dev *dev; struct serio *serio; u32 idx; unsigned char data[PACKET_LENGTH]; char phys[32]; }; static void tsc_process_data(struct tsc_ser *ptsc) { struct input_dev *dev = ptsc->dev; u8 *data = ptsc->data; u32 x; u32 y; x = ((data[1] & 0x03) << 8) | data[2]; y = ((data[3] & 0x03) << 8) | data[4]; input_report_abs(dev, ABS_X, x); input_report_abs(dev, ABS_Y, y); input_report_key(dev, BTN_TOUCH, 1); input_sync(dev); } static irqreturn_t tsc_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct tsc_ser *ptsc = serio_get_drvdata(serio); struct input_dev *dev = ptsc->dev; ptsc->data[ptsc->idx] = data; switch (ptsc->idx++) { case 0: if (unlikely((data & 0x3e) != 0x10)) { dev_dbg(&serio->dev, "unsynchronized packet start (0x%02x)\n", data); ptsc->idx = 0; } else if (!(data & 0x01)) { input_report_key(dev, BTN_TOUCH, 0); input_sync(dev); ptsc->idx = 0; } break; case 1: case 3: if (unlikely(data & 0xfc)) { dev_dbg(&serio->dev, "unsynchronized data 0x%02x at offset %d\n", data, ptsc->idx - 1); ptsc->idx = 0; } break; case 4: tsc_process_data(ptsc); ptsc->idx = 0; break; } return IRQ_HANDLED; } static int tsc_connect(struct serio *serio, struct serio_driver *drv) { struct tsc_ser *ptsc; struct input_dev *input_dev; int error; ptsc = kzalloc(sizeof(struct tsc_ser), GFP_KERNEL); input_dev = input_allocate_device(); if (!ptsc || !input_dev) { error = -ENOMEM; goto fail1; } ptsc->serio = serio; ptsc->dev = input_dev; snprintf(ptsc->phys, sizeof(ptsc->phys), "%s/input0", serio->phys); input_dev->name = "TSC-10/25/40 Serial TouchScreen"; input_dev->phys = ptsc->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_TSC40; input_dev->id.product = 40; input_dev->id.version = 0x0001; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); __set_bit(BTN_TOUCH, input_dev->keybit); input_set_abs_params(ptsc->dev, ABS_X, 0, 0x3ff, 0, 0); input_set_abs_params(ptsc->dev, ABS_Y, 0, 0x3ff, 0, 0); serio_set_drvdata(serio, ptsc); error = serio_open(serio, drv); if (error) goto fail2; error = input_register_device(ptsc->dev); if (error) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(ptsc); return error; } static void tsc_disconnect(struct serio *serio) { struct tsc_ser *ptsc = serio_get_drvdata(serio); serio_close(serio); input_unregister_device(ptsc->dev); kfree(ptsc); serio_set_drvdata(serio, NULL); } static const struct serio_device_id tsc_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_TSC40, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, tsc_serio_ids); #define DRIVER_DESC "TSC-10/25/40 serial touchscreen driver" static struct serio_driver tsc_drv = { .driver = { .name = "tsc40", }, .description = DRIVER_DESC, .id_table = tsc_serio_ids, .interrupt = tsc_interrupt, .connect = tsc_connect, .disconnect = tsc_disconnect, }; module_serio_driver(tsc_drv); MODULE_AUTHOR("Sebastian Andrzej Siewior <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/tsc40.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Surface2.0/SUR40/PixelSense input driver * * Copyright (c) 2014 by Florian 'floe' Echtler <[email protected]> * * Derived from the USB Skeleton driver 1.1, * Copyright (c) 2003 Greg Kroah-Hartman ([email protected]) * * and from the Apple USB BCM5974 multitouch driver, * Copyright (c) 2008 Henrik Rydberg ([email protected]) * * and from the generic hid-multitouch driver, * Copyright (c) 2010-2012 Stephane Chatty <[email protected]> * * and from the v4l2-pci-skeleton driver, * Copyright (c) Copyright 2014 Cisco Systems, Inc. */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/completion.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/printk.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/usb/input.h> #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-dev.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/videobuf2-v4l2.h> #include <media/videobuf2-dma-sg.h> /* read 512 bytes from endpoint 0x86 -> get header + blobs */ struct sur40_header { __le16 type; /* always 0x0001 */ __le16 count; /* count of blobs (if 0: continue prev. packet) */ __le32 packet_id; /* unique ID for all packets in one frame */ __le32 timestamp; /* milliseconds (inc. by 16 or 17 each frame) */ __le32 unknown; /* "epoch?" always 02/03 00 00 00 */ } __packed; struct sur40_blob { __le16 blob_id; u8 action; /* 0x02 = enter/exit, 0x03 = update (?) */ u8 type; /* bitmask (0x01 blob, 0x02 touch, 0x04 tag) */ __le16 bb_pos_x; /* upper left corner of bounding box */ __le16 bb_pos_y; __le16 bb_size_x; /* size of bounding box */ __le16 bb_size_y; __le16 pos_x; /* finger tip position */ __le16 pos_y; __le16 ctr_x; /* centroid position */ __le16 ctr_y; __le16 axis_x; /* somehow related to major/minor axis, mostly: */ __le16 axis_y; /* axis_x == bb_size_y && axis_y == bb_size_x */ __le32 angle; /* orientation in radians relative to x axis - actually an IEEE754 float, don't use in kernel */ __le32 area; /* size in pixels/pressure (?) */ u8 padding[24]; __le32 tag_id; /* valid when type == 0x04 (SUR40_TAG) */ __le32 unknown; } __packed; /* combined header/blob data */ struct sur40_data { struct sur40_header header; struct sur40_blob blobs[]; } __packed; /* read 512 bytes from endpoint 0x82 -> get header below * continue reading 16k blocks until header.size bytes read */ struct sur40_image_header { __le32 magic; /* "SUBF" */ __le32 packet_id; __le32 size; /* always 0x0007e900 = 960x540 */ __le32 timestamp; /* milliseconds (increases by 16 or 17 each frame) */ __le32 unknown; /* "epoch?" always 02/03 00 00 00 */ } __packed; /* version information */ #define DRIVER_SHORT "sur40" #define DRIVER_LONG "Samsung SUR40" #define DRIVER_AUTHOR "Florian 'floe' Echtler <[email protected]>" #define DRIVER_DESC "Surface2.0/SUR40/PixelSense input driver" /* vendor and device IDs */ #define ID_MICROSOFT 0x045e #define ID_SUR40 0x0775 /* sensor resolution */ #define SENSOR_RES_X 1920 #define SENSOR_RES_Y 1080 /* touch data endpoint */ #define TOUCH_ENDPOINT 0x86 /* video data endpoint */ #define VIDEO_ENDPOINT 0x82 /* video header fields */ #define VIDEO_HEADER_MAGIC 0x46425553 #define VIDEO_PACKET_SIZE 16384 /* polling interval (ms) */ #define POLL_INTERVAL 1 /* maximum number of contacts FIXME: this is a guess? */ #define MAX_CONTACTS 64 /* control commands */ #define SUR40_GET_VERSION 0xb0 /* 12 bytes string */ #define SUR40_ACCEL_CAPS 0xb3 /* 5 bytes */ #define SUR40_SENSOR_CAPS 0xc1 /* 24 bytes */ #define SUR40_POKE 0xc5 /* poke register byte */ #define SUR40_PEEK 0xc4 /* 48 bytes registers */ #define SUR40_GET_STATE 0xc5 /* 4 bytes state (?) */ #define SUR40_GET_SENSORS 0xb1 /* 8 bytes sensors */ #define SUR40_BLOB 0x01 #define SUR40_TOUCH 0x02 #define SUR40_TAG 0x04 /* video controls */ #define SUR40_BRIGHTNESS_MAX 0xff #define SUR40_BRIGHTNESS_MIN 0x00 #define SUR40_BRIGHTNESS_DEF 0xff #define SUR40_CONTRAST_MAX 0x0f #define SUR40_CONTRAST_MIN 0x00 #define SUR40_CONTRAST_DEF 0x0a #define SUR40_GAIN_MAX 0x09 #define SUR40_GAIN_MIN 0x00 #define SUR40_GAIN_DEF 0x08 #define SUR40_BACKLIGHT_MAX 0x01 #define SUR40_BACKLIGHT_MIN 0x00 #define SUR40_BACKLIGHT_DEF 0x01 #define sur40_str(s) #s #define SUR40_PARAM_RANGE(lo, hi) " (range " sur40_str(lo) "-" sur40_str(hi) ")" /* module parameters */ static uint brightness = SUR40_BRIGHTNESS_DEF; module_param(brightness, uint, 0644); MODULE_PARM_DESC(brightness, "set initial brightness" SUR40_PARAM_RANGE(SUR40_BRIGHTNESS_MIN, SUR40_BRIGHTNESS_MAX)); static uint contrast = SUR40_CONTRAST_DEF; module_param(contrast, uint, 0644); MODULE_PARM_DESC(contrast, "set initial contrast" SUR40_PARAM_RANGE(SUR40_CONTRAST_MIN, SUR40_CONTRAST_MAX)); static uint gain = SUR40_GAIN_DEF; module_param(gain, uint, 0644); MODULE_PARM_DESC(gain, "set initial gain" SUR40_PARAM_RANGE(SUR40_GAIN_MIN, SUR40_GAIN_MAX)); static const struct v4l2_pix_format sur40_pix_format[] = { { .pixelformat = V4L2_TCH_FMT_TU08, .width = SENSOR_RES_X / 2, .height = SENSOR_RES_Y / 2, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_RAW, .bytesperline = SENSOR_RES_X / 2, .sizeimage = (SENSOR_RES_X/2) * (SENSOR_RES_Y/2), }, { .pixelformat = V4L2_PIX_FMT_GREY, .width = SENSOR_RES_X / 2, .height = SENSOR_RES_Y / 2, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_RAW, .bytesperline = SENSOR_RES_X / 2, .sizeimage = (SENSOR_RES_X/2) * (SENSOR_RES_Y/2), } }; /* master device state */ struct sur40_state { struct usb_device *usbdev; struct device *dev; struct input_dev *input; struct v4l2_device v4l2; struct video_device vdev; struct mutex lock; struct v4l2_pix_format pix_fmt; struct v4l2_ctrl_handler hdl; struct vb2_queue queue; struct list_head buf_list; spinlock_t qlock; int sequence; struct sur40_data *bulk_in_buffer; size_t bulk_in_size; u8 bulk_in_epaddr; u8 vsvideo; char phys[64]; }; struct sur40_buffer { struct vb2_v4l2_buffer vb; struct list_head list; }; /* forward declarations */ static const struct video_device sur40_video_device; static const struct vb2_queue sur40_queue; static void sur40_process_video(struct sur40_state *sur40); static int sur40_s_ctrl(struct v4l2_ctrl *ctrl); static const struct v4l2_ctrl_ops sur40_ctrl_ops = { .s_ctrl = sur40_s_ctrl, }; /* * Note: an earlier, non-public version of this driver used USB_RECIP_ENDPOINT * here by mistake which is very likely to have corrupted the firmware EEPROM * on two separate SUR40 devices. Thanks to Alan Stern who spotted this bug. * Should you ever run into a similar problem, the background story to this * incident and instructions on how to fix the corrupted EEPROM are available * at https://floe.butterbrot.org/matrix/hacking/surface/brick.html */ /* command wrapper */ static int sur40_command(struct sur40_state *dev, u8 command, u16 index, void *buffer, u16 size) { return usb_control_msg(dev->usbdev, usb_rcvctrlpipe(dev->usbdev, 0), command, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN, 0x00, index, buffer, size, 1000); } /* poke a byte in the panel register space */ static int sur40_poke(struct sur40_state *dev, u8 offset, u8 value) { int result; u8 index = 0x96; // 0xae for permanent write result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0), SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, 0x32, index, NULL, 0, 1000); if (result < 0) goto error; msleep(5); result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0), SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, 0x72, offset, NULL, 0, 1000); if (result < 0) goto error; msleep(5); result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0), SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, 0xb2, value, NULL, 0, 1000); if (result < 0) goto error; msleep(5); error: return result; } static int sur40_set_preprocessor(struct sur40_state *dev, u8 value) { u8 setting_07[2] = { 0x01, 0x00 }; u8 setting_17[2] = { 0x85, 0x80 }; int result; if (value > 1) return -ERANGE; result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0), SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, 0x07, setting_07[value], NULL, 0, 1000); if (result < 0) goto error; msleep(5); result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0), SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT, 0x17, setting_17[value], NULL, 0, 1000); if (result < 0) goto error; msleep(5); error: return result; } static void sur40_set_vsvideo(struct sur40_state *handle, u8 value) { int i; for (i = 0; i < 4; i++) sur40_poke(handle, 0x1c+i, value); handle->vsvideo = value; } static void sur40_set_irlevel(struct sur40_state *handle, u8 value) { int i; for (i = 0; i < 8; i++) sur40_poke(handle, 0x08+(2*i), value); } /* Initialization routine, called from sur40_open */ static int sur40_init(struct sur40_state *dev) { int result; u8 *buffer; buffer = kmalloc(24, GFP_KERNEL); if (!buffer) { result = -ENOMEM; goto error; } /* stupidly replay the original MS driver init sequence */ result = sur40_command(dev, SUR40_GET_VERSION, 0x00, buffer, 12); if (result < 0) goto error; result = sur40_command(dev, SUR40_GET_VERSION, 0x01, buffer, 12); if (result < 0) goto error; result = sur40_command(dev, SUR40_GET_VERSION, 0x02, buffer, 12); if (result < 0) goto error; result = sur40_command(dev, SUR40_SENSOR_CAPS, 0x00, buffer, 24); if (result < 0) goto error; result = sur40_command(dev, SUR40_ACCEL_CAPS, 0x00, buffer, 5); if (result < 0) goto error; result = sur40_command(dev, SUR40_GET_VERSION, 0x03, buffer, 12); if (result < 0) goto error; result = 0; /* * Discard the result buffer - no known data inside except * some version strings, maybe extract these sometime... */ error: kfree(buffer); return result; } /* * Callback routines from input_dev */ /* Enable the device, polling will now start. */ static int sur40_open(struct input_dev *input) { struct sur40_state *sur40 = input_get_drvdata(input); dev_dbg(sur40->dev, "open\n"); return sur40_init(sur40); } /* Disable device, polling has stopped. */ static void sur40_close(struct input_dev *input) { struct sur40_state *sur40 = input_get_drvdata(input); dev_dbg(sur40->dev, "close\n"); /* * There is no known way to stop the device, so we simply * stop polling. */ } /* * This function is called when a whole contact has been processed, * so that it can assign it to a slot and store the data there. */ static void sur40_report_blob(struct sur40_blob *blob, struct input_dev *input) { int wide, major, minor; int bb_size_x, bb_size_y, pos_x, pos_y, ctr_x, ctr_y, slotnum; if (blob->type != SUR40_TOUCH) return; slotnum = input_mt_get_slot_by_key(input, blob->blob_id); if (slotnum < 0 || slotnum >= MAX_CONTACTS) return; bb_size_x = le16_to_cpu(blob->bb_size_x); bb_size_y = le16_to_cpu(blob->bb_size_y); pos_x = le16_to_cpu(blob->pos_x); pos_y = le16_to_cpu(blob->pos_y); ctr_x = le16_to_cpu(blob->ctr_x); ctr_y = le16_to_cpu(blob->ctr_y); input_mt_slot(input, slotnum); input_mt_report_slot_state(input, MT_TOOL_FINGER, 1); wide = (bb_size_x > bb_size_y); major = max(bb_size_x, bb_size_y); minor = min(bb_size_x, bb_size_y); input_report_abs(input, ABS_MT_POSITION_X, pos_x); input_report_abs(input, ABS_MT_POSITION_Y, pos_y); input_report_abs(input, ABS_MT_TOOL_X, ctr_x); input_report_abs(input, ABS_MT_TOOL_Y, ctr_y); /* TODO: use a better orientation measure */ input_report_abs(input, ABS_MT_ORIENTATION, wide); input_report_abs(input, ABS_MT_TOUCH_MAJOR, major); input_report_abs(input, ABS_MT_TOUCH_MINOR, minor); } /* core function: poll for new input data */ static void sur40_poll(struct input_dev *input) { struct sur40_state *sur40 = input_get_drvdata(input); int result, bulk_read, need_blobs, packet_blobs, i; struct sur40_header *header = &sur40->bulk_in_buffer->header; struct sur40_blob *inblob = &sur40->bulk_in_buffer->blobs[0]; dev_dbg(sur40->dev, "poll\n"); need_blobs = -1; do { /* perform a blocking bulk read to get data from the device */ result = usb_bulk_msg(sur40->usbdev, usb_rcvbulkpipe(sur40->usbdev, sur40->bulk_in_epaddr), sur40->bulk_in_buffer, sur40->bulk_in_size, &bulk_read, 1000); dev_dbg(sur40->dev, "received %d bytes\n", bulk_read); if (result < 0) { dev_err(sur40->dev, "error in usb_bulk_read\n"); return; } result = bulk_read - sizeof(struct sur40_header); if (result % sizeof(struct sur40_blob) != 0) { dev_err(sur40->dev, "transfer size mismatch\n"); return; } /* first packet? */ if (need_blobs == -1) { need_blobs = le16_to_cpu(header->count); dev_dbg(sur40->dev, "need %d blobs\n", need_blobs); /* packet_id = le32_to_cpu(header->packet_id); */ } /* * Sanity check. when video data is also being retrieved, the * packet ID will usually increase in the middle of a series * instead of at the end. However, the data is still consistent, * so the packet ID is probably just valid for the first packet * in a series. if (packet_id != le32_to_cpu(header->packet_id)) dev_dbg(sur40->dev, "packet ID mismatch\n"); */ packet_blobs = result / sizeof(struct sur40_blob); dev_dbg(sur40->dev, "received %d blobs\n", packet_blobs); /* packets always contain at least 4 blobs, even if empty */ if (packet_blobs > need_blobs) packet_blobs = need_blobs; for (i = 0; i < packet_blobs; i++) { need_blobs--; dev_dbg(sur40->dev, "processing blob\n"); sur40_report_blob(&(inblob[i]), input); } } while (need_blobs > 0); input_mt_sync_frame(input); input_sync(input); sur40_process_video(sur40); } /* deal with video data */ static void sur40_process_video(struct sur40_state *sur40) { struct sur40_image_header *img = (void *)(sur40->bulk_in_buffer); struct sur40_buffer *new_buf; struct usb_sg_request sgr; struct sg_table *sgt; int result, bulk_read; if (!vb2_start_streaming_called(&sur40->queue)) return; /* get a new buffer from the list */ spin_lock(&sur40->qlock); if (list_empty(&sur40->buf_list)) { dev_dbg(sur40->dev, "buffer queue empty\n"); spin_unlock(&sur40->qlock); return; } new_buf = list_entry(sur40->buf_list.next, struct sur40_buffer, list); list_del(&new_buf->list); spin_unlock(&sur40->qlock); dev_dbg(sur40->dev, "buffer acquired\n"); /* retrieve data via bulk read */ result = usb_bulk_msg(sur40->usbdev, usb_rcvbulkpipe(sur40->usbdev, VIDEO_ENDPOINT), sur40->bulk_in_buffer, sur40->bulk_in_size, &bulk_read, 1000); if (result < 0) { dev_err(sur40->dev, "error in usb_bulk_read\n"); goto err_poll; } if (bulk_read != sizeof(struct sur40_image_header)) { dev_err(sur40->dev, "received %d bytes (%zd expected)\n", bulk_read, sizeof(struct sur40_image_header)); goto err_poll; } if (le32_to_cpu(img->magic) != VIDEO_HEADER_MAGIC) { dev_err(sur40->dev, "image magic mismatch\n"); goto err_poll; } if (le32_to_cpu(img->size) != sur40->pix_fmt.sizeimage) { dev_err(sur40->dev, "image size mismatch\n"); goto err_poll; } dev_dbg(sur40->dev, "header acquired\n"); sgt = vb2_dma_sg_plane_desc(&new_buf->vb.vb2_buf, 0); result = usb_sg_init(&sgr, sur40->usbdev, usb_rcvbulkpipe(sur40->usbdev, VIDEO_ENDPOINT), 0, sgt->sgl, sgt->nents, sur40->pix_fmt.sizeimage, 0); if (result < 0) { dev_err(sur40->dev, "error %d in usb_sg_init\n", result); goto err_poll; } usb_sg_wait(&sgr); if (sgr.status < 0) { dev_err(sur40->dev, "error %d in usb_sg_wait\n", sgr.status); goto err_poll; } dev_dbg(sur40->dev, "image acquired\n"); /* return error if streaming was stopped in the meantime */ if (sur40->sequence == -1) return; /* mark as finished */ new_buf->vb.vb2_buf.timestamp = ktime_get_ns(); new_buf->vb.sequence = sur40->sequence++; new_buf->vb.field = V4L2_FIELD_NONE; vb2_buffer_done(&new_buf->vb.vb2_buf, VB2_BUF_STATE_DONE); dev_dbg(sur40->dev, "buffer marked done\n"); return; err_poll: vb2_buffer_done(&new_buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); } /* Initialize input device parameters. */ static int sur40_input_setup_events(struct input_dev *input_dev) { int error; input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, SENSOR_RES_X, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, SENSOR_RES_Y, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOOL_X, 0, SENSOR_RES_X, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOOL_Y, 0, SENSOR_RES_Y, 0, 0); /* max value unknown, but major/minor axis * can never be larger than screen */ input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, SENSOR_RES_X, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR, 0, SENSOR_RES_Y, 0, 0); input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 1, 0, 0); error = input_mt_init_slots(input_dev, MAX_CONTACTS, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(input_dev->dev.parent, "failed to set up slots\n"); return error; } return 0; } /* Check candidate USB interface. */ static int sur40_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *usbdev = interface_to_usbdev(interface); struct sur40_state *sur40; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; struct input_dev *input; int error; /* Check if we really have the right interface. */ iface_desc = interface->cur_altsetting; if (iface_desc->desc.bInterfaceClass != 0xFF) return -ENODEV; if (iface_desc->desc.bNumEndpoints < 5) return -ENODEV; /* Use endpoint #4 (0x86). */ endpoint = &iface_desc->endpoint[4].desc; if (endpoint->bEndpointAddress != TOUCH_ENDPOINT) return -ENODEV; /* Allocate memory for our device state and initialize it. */ sur40 = kzalloc(sizeof(struct sur40_state), GFP_KERNEL); if (!sur40) return -ENOMEM; input = input_allocate_device(); if (!input) { error = -ENOMEM; goto err_free_dev; } /* initialize locks/lists */ INIT_LIST_HEAD(&sur40->buf_list); spin_lock_init(&sur40->qlock); mutex_init(&sur40->lock); /* Set up regular input device structure */ input->name = DRIVER_LONG; usb_to_input_id(usbdev, &input->id); usb_make_path(usbdev, sur40->phys, sizeof(sur40->phys)); strlcat(sur40->phys, "/input0", sizeof(sur40->phys)); input->phys = sur40->phys; input->dev.parent = &interface->dev; input->open = sur40_open; input->close = sur40_close; error = sur40_input_setup_events(input); if (error) goto err_free_input; input_set_drvdata(input, sur40); error = input_setup_polling(input, sur40_poll); if (error) { dev_err(&interface->dev, "failed to set up polling"); goto err_free_input; } input_set_poll_interval(input, POLL_INTERVAL); sur40->usbdev = usbdev; sur40->dev = &interface->dev; sur40->input = input; /* use the bulk-in endpoint tested above */ sur40->bulk_in_size = usb_endpoint_maxp(endpoint); sur40->bulk_in_epaddr = endpoint->bEndpointAddress; sur40->bulk_in_buffer = kmalloc(sur40->bulk_in_size, GFP_KERNEL); if (!sur40->bulk_in_buffer) { dev_err(&interface->dev, "Unable to allocate input buffer."); error = -ENOMEM; goto err_free_input; } /* register the polled input device */ error = input_register_device(input); if (error) { dev_err(&interface->dev, "Unable to register polled input device."); goto err_free_buffer; } /* register the video master device */ snprintf(sur40->v4l2.name, sizeof(sur40->v4l2.name), "%s", DRIVER_LONG); error = v4l2_device_register(sur40->dev, &sur40->v4l2); if (error) { dev_err(&interface->dev, "Unable to register video master device."); goto err_unreg_v4l2; } /* initialize the lock and subdevice */ sur40->queue = sur40_queue; sur40->queue.drv_priv = sur40; sur40->queue.lock = &sur40->lock; sur40->queue.dev = sur40->dev; /* initialize the queue */ error = vb2_queue_init(&sur40->queue); if (error) goto err_unreg_v4l2; sur40->pix_fmt = sur40_pix_format[0]; sur40->vdev = sur40_video_device; sur40->vdev.v4l2_dev = &sur40->v4l2; sur40->vdev.lock = &sur40->lock; sur40->vdev.queue = &sur40->queue; video_set_drvdata(&sur40->vdev, sur40); /* initialize the control handler for 4 controls */ v4l2_ctrl_handler_init(&sur40->hdl, 4); sur40->v4l2.ctrl_handler = &sur40->hdl; sur40->vsvideo = (SUR40_CONTRAST_DEF << 4) | SUR40_GAIN_DEF; v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_BRIGHTNESS, SUR40_BRIGHTNESS_MIN, SUR40_BRIGHTNESS_MAX, 1, clamp(brightness, (uint)SUR40_BRIGHTNESS_MIN, (uint)SUR40_BRIGHTNESS_MAX)); v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_CONTRAST, SUR40_CONTRAST_MIN, SUR40_CONTRAST_MAX, 1, clamp(contrast, (uint)SUR40_CONTRAST_MIN, (uint)SUR40_CONTRAST_MAX)); v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_GAIN, SUR40_GAIN_MIN, SUR40_GAIN_MAX, 1, clamp(gain, (uint)SUR40_GAIN_MIN, (uint)SUR40_GAIN_MAX)); v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_BACKLIGHT_COMPENSATION, SUR40_BACKLIGHT_MIN, SUR40_BACKLIGHT_MAX, 1, SUR40_BACKLIGHT_DEF); v4l2_ctrl_handler_setup(&sur40->hdl); if (sur40->hdl.error) { dev_err(&interface->dev, "Unable to register video controls."); v4l2_ctrl_handler_free(&sur40->hdl); error = sur40->hdl.error; goto err_unreg_v4l2; } error = video_register_device(&sur40->vdev, VFL_TYPE_TOUCH, -1); if (error) { dev_err(&interface->dev, "Unable to register video subdevice."); goto err_unreg_video; } /* we can register the device now, as it is ready */ usb_set_intfdata(interface, sur40); dev_dbg(&interface->dev, "%s is now attached\n", DRIVER_DESC); return 0; err_unreg_video: video_unregister_device(&sur40->vdev); err_unreg_v4l2: v4l2_device_unregister(&sur40->v4l2); err_free_buffer: kfree(sur40->bulk_in_buffer); err_free_input: input_free_device(input); err_free_dev: kfree(sur40); return error; } /* Unregister device & clean up. */ static void sur40_disconnect(struct usb_interface *interface) { struct sur40_state *sur40 = usb_get_intfdata(interface); v4l2_ctrl_handler_free(&sur40->hdl); video_unregister_device(&sur40->vdev); v4l2_device_unregister(&sur40->v4l2); input_unregister_device(sur40->input); kfree(sur40->bulk_in_buffer); kfree(sur40); usb_set_intfdata(interface, NULL); dev_dbg(&interface->dev, "%s is now disconnected\n", DRIVER_DESC); } /* * Setup the constraints of the queue: besides setting the number of planes * per buffer and the size and allocation context of each plane, it also * checks if sufficient buffers have been allocated. Usually 3 is a good * minimum number: many DMA engines need a minimum of 2 buffers in the * queue and you need to have another available for userspace processing. */ static int sur40_queue_setup(struct vb2_queue *q, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct sur40_state *sur40 = vb2_get_drv_priv(q); if (q->num_buffers + *nbuffers < 3) *nbuffers = 3 - q->num_buffers; if (*nplanes) return sizes[0] < sur40->pix_fmt.sizeimage ? -EINVAL : 0; *nplanes = 1; sizes[0] = sur40->pix_fmt.sizeimage; return 0; } /* * Prepare the buffer for queueing to the DMA engine: check and set the * payload size. */ static int sur40_buffer_prepare(struct vb2_buffer *vb) { struct sur40_state *sur40 = vb2_get_drv_priv(vb->vb2_queue); unsigned long size = sur40->pix_fmt.sizeimage; if (vb2_plane_size(vb, 0) < size) { dev_err(&sur40->usbdev->dev, "buffer too small (%lu < %lu)\n", vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } /* * Queue this buffer to the DMA engine. */ static void sur40_buffer_queue(struct vb2_buffer *vb) { struct sur40_state *sur40 = vb2_get_drv_priv(vb->vb2_queue); struct sur40_buffer *buf = (struct sur40_buffer *)vb; spin_lock(&sur40->qlock); list_add_tail(&buf->list, &sur40->buf_list); spin_unlock(&sur40->qlock); } static void return_all_buffers(struct sur40_state *sur40, enum vb2_buffer_state state) { struct sur40_buffer *buf, *node; spin_lock(&sur40->qlock); list_for_each_entry_safe(buf, node, &sur40->buf_list, list) { vb2_buffer_done(&buf->vb.vb2_buf, state); list_del(&buf->list); } spin_unlock(&sur40->qlock); } /* * Start streaming. First check if the minimum number of buffers have been * queued. If not, then return -ENOBUFS and the vb2 framework will call * this function again the next time a buffer has been queued until enough * buffers are available to actually start the DMA engine. */ static int sur40_start_streaming(struct vb2_queue *vq, unsigned int count) { struct sur40_state *sur40 = vb2_get_drv_priv(vq); sur40->sequence = 0; return 0; } /* * 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 sur40_stop_streaming(struct vb2_queue *vq) { struct sur40_state *sur40 = vb2_get_drv_priv(vq); vb2_wait_for_all_buffers(vq); sur40->sequence = -1; /* Release all active buffers */ return_all_buffers(sur40, VB2_BUF_STATE_ERROR); } /* V4L ioctl */ static int sur40_vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct sur40_state *sur40 = video_drvdata(file); strscpy(cap->driver, DRIVER_SHORT, sizeof(cap->driver)); strscpy(cap->card, DRIVER_LONG, sizeof(cap->card)); usb_make_path(sur40->usbdev, cap->bus_info, sizeof(cap->bus_info)); return 0; } static int sur40_vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *i) { if (i->index != 0) return -EINVAL; i->type = V4L2_INPUT_TYPE_TOUCH; i->std = V4L2_STD_UNKNOWN; strscpy(i->name, "In-Cell Sensor", sizeof(i->name)); i->capabilities = 0; return 0; } static int sur40_vidioc_s_input(struct file *file, void *priv, unsigned int i) { return (i == 0) ? 0 : -EINVAL; } static int sur40_vidioc_g_input(struct file *file, void *priv, unsigned int *i) { *i = 0; return 0; } static int sur40_vidioc_try_fmt(struct file *file, void *priv, struct v4l2_format *f) { switch (f->fmt.pix.pixelformat) { case V4L2_PIX_FMT_GREY: f->fmt.pix = sur40_pix_format[1]; break; default: f->fmt.pix = sur40_pix_format[0]; break; } return 0; } static int sur40_vidioc_s_fmt(struct file *file, void *priv, struct v4l2_format *f) { struct sur40_state *sur40 = video_drvdata(file); switch (f->fmt.pix.pixelformat) { case V4L2_PIX_FMT_GREY: sur40->pix_fmt = sur40_pix_format[1]; break; default: sur40->pix_fmt = sur40_pix_format[0]; break; } f->fmt.pix = sur40->pix_fmt; return 0; } static int sur40_vidioc_g_fmt(struct file *file, void *priv, struct v4l2_format *f) { struct sur40_state *sur40 = video_drvdata(file); f->fmt.pix = sur40->pix_fmt; return 0; } static int sur40_s_ctrl(struct v4l2_ctrl *ctrl) { struct sur40_state *sur40 = container_of(ctrl->handler, struct sur40_state, hdl); u8 value = sur40->vsvideo; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: sur40_set_irlevel(sur40, ctrl->val); break; case V4L2_CID_CONTRAST: value = (value & 0x0f) | (ctrl->val << 4); sur40_set_vsvideo(sur40, value); break; case V4L2_CID_GAIN: value = (value & 0xf0) | (ctrl->val); sur40_set_vsvideo(sur40, value); break; case V4L2_CID_BACKLIGHT_COMPENSATION: sur40_set_preprocessor(sur40, ctrl->val); break; } return 0; } static int sur40_ioctl_parm(struct file *file, void *priv, struct v4l2_streamparm *p) { if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; p->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; p->parm.capture.timeperframe.numerator = 1; p->parm.capture.timeperframe.denominator = 60; p->parm.capture.readbuffers = 3; return 0; } static int sur40_vidioc_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *f) { if (f->index >= ARRAY_SIZE(sur40_pix_format)) return -EINVAL; f->pixelformat = sur40_pix_format[f->index].pixelformat; f->flags = 0; return 0; } static int sur40_vidioc_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *f) { struct sur40_state *sur40 = video_drvdata(file); if ((f->index != 0) || ((f->pixel_format != V4L2_TCH_FMT_TU08) && (f->pixel_format != V4L2_PIX_FMT_GREY))) return -EINVAL; f->type = V4L2_FRMSIZE_TYPE_DISCRETE; f->discrete.width = sur40->pix_fmt.width; f->discrete.height = sur40->pix_fmt.height; return 0; } static int sur40_vidioc_enum_frameintervals(struct file *file, void *priv, struct v4l2_frmivalenum *f) { struct sur40_state *sur40 = video_drvdata(file); if ((f->index > 0) || ((f->pixel_format != V4L2_TCH_FMT_TU08) && (f->pixel_format != V4L2_PIX_FMT_GREY)) || (f->width != sur40->pix_fmt.width) || (f->height != sur40->pix_fmt.height)) return -EINVAL; f->type = V4L2_FRMIVAL_TYPE_DISCRETE; f->discrete.denominator = 60; f->discrete.numerator = 1; return 0; } static const struct usb_device_id sur40_table[] = { { USB_DEVICE(ID_MICROSOFT, ID_SUR40) }, /* Samsung SUR40 */ { } /* terminating null entry */ }; MODULE_DEVICE_TABLE(usb, sur40_table); /* V4L2 structures */ static const struct vb2_ops sur40_queue_ops = { .queue_setup = sur40_queue_setup, .buf_prepare = sur40_buffer_prepare, .buf_queue = sur40_buffer_queue, .start_streaming = sur40_start_streaming, .stop_streaming = sur40_stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static const struct vb2_queue sur40_queue = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, /* * VB2_USERPTR in currently not enabled: passing a user pointer to * dma-sg will result in segment sizes that are not a multiple of * 512 bytes, which is required by the host controller. */ .io_modes = VB2_MMAP | VB2_READ | VB2_DMABUF, .buf_struct_size = sizeof(struct sur40_buffer), .ops = &sur40_queue_ops, .mem_ops = &vb2_dma_sg_memops, .timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC, .min_buffers_needed = 3, }; static const struct v4l2_file_operations sur40_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, }; static const struct v4l2_ioctl_ops sur40_video_ioctl_ops = { .vidioc_querycap = sur40_vidioc_querycap, .vidioc_enum_fmt_vid_cap = sur40_vidioc_enum_fmt, .vidioc_try_fmt_vid_cap = sur40_vidioc_try_fmt, .vidioc_s_fmt_vid_cap = sur40_vidioc_s_fmt, .vidioc_g_fmt_vid_cap = sur40_vidioc_g_fmt, .vidioc_enum_framesizes = sur40_vidioc_enum_framesizes, .vidioc_enum_frameintervals = sur40_vidioc_enum_frameintervals, .vidioc_g_parm = sur40_ioctl_parm, .vidioc_s_parm = sur40_ioctl_parm, .vidioc_enum_input = sur40_vidioc_enum_input, .vidioc_g_input = sur40_vidioc_g_input, .vidioc_s_input = sur40_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 sur40_video_device = { .name = DRIVER_LONG, .fops = &sur40_video_fops, .ioctl_ops = &sur40_video_ioctl_ops, .release = video_device_release_empty, .device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING, }; /* USB-specific object needed to register this driver with the USB subsystem. */ static struct usb_driver sur40_driver = { .name = DRIVER_SHORT, .probe = sur40_probe, .disconnect = sur40_disconnect, .id_table = sur40_table, }; module_usb_driver(sur40_driver); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/sur40.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * wm9713.c -- Codec touch driver for Wolfson WM9713 AC97 Codec. * * Copyright 2003, 2004, 2005, 2006, 2007, 2008 Wolfson Microelectronics PLC. * Author: Liam Girdwood <[email protected]> * Parts Copyright : Ian Molton <[email protected]> * Andrew Zabolotny <[email protected]> * Russell King <[email protected]> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/bitops.h> #include <linux/wm97xx.h> #define TS_NAME "wm97xx" #define WM9713_VERSION "1.00" #define DEFAULT_PRESSURE 0xb0c0 /* * Module parameters */ /* * Set internal pull up for pen detect. * * Pull up is in the range 1.02k (least sensitive) to 64k (most sensitive) * i.e. pull up resistance = 64k Ohms / rpu. * * Adjust this value if you are having problems with pen detect not * detecting any down event. */ static int rpu = 8; module_param(rpu, int, 0); MODULE_PARM_DESC(rpu, "Set internal pull up resistor for pen detect."); /* * Set current used for pressure measurement. * * Set pil = 2 to use 400uA * pil = 1 to use 200uA and * pil = 0 to disable pressure measurement. * * This is used to increase the range of values returned by the adc * when measureing touchpanel pressure. */ static int pil; module_param(pil, int, 0); MODULE_PARM_DESC(pil, "Set current used for pressure measurement."); /* * Set threshold for pressure measurement. * * Pen down pressure below threshold is ignored. */ static int pressure = DEFAULT_PRESSURE & 0xfff; module_param(pressure, int, 0); MODULE_PARM_DESC(pressure, "Set threshold for pressure measurement."); /* * Set adc sample delay. * * For accurate touchpanel measurements, some settling time may be * required between the switch matrix applying a voltage across the * touchpanel plate and the ADC sampling the signal. * * This delay can be set by setting delay = n, where n is the array * position of the delay in the array delay_table below. * Long delays > 1ms are supported for completeness, but are not * recommended. */ static int delay = 4; module_param(delay, int, 0); MODULE_PARM_DESC(delay, "Set adc sample delay."); /* * Set five_wire = 1 to use a 5 wire touchscreen. * * NOTE: Five wire mode does not allow for readback of pressure. */ static int five_wire; module_param(five_wire, int, 0); MODULE_PARM_DESC(five_wire, "Set to '1' to use 5-wire touchscreen."); /* * Set adc mask function. * * Sources of glitch noise, such as signals driving an LCD display, may feed * through to the touch screen plates and affect measurement accuracy. In * order to minimise this, a signal may be applied to the MASK pin to delay or * synchronise the sampling. * * 0 = No delay or sync * 1 = High on pin stops conversions * 2 = Edge triggered, edge on pin delays conversion by delay param (above) * 3 = Edge triggered, edge on pin starts conversion after delay param */ static int mask; module_param(mask, int, 0); MODULE_PARM_DESC(mask, "Set adc mask function."); /* * Coordinate Polling Enable. * * Set to 1 to enable coordinate polling. e.g. x,y[,p] is sampled together * for every poll. */ static int coord; module_param(coord, int, 0); MODULE_PARM_DESC(coord, "Polling coordinate mode"); /* * ADC sample delay times in uS */ static const int delay_table[] = { 21, /* 1 AC97 Link frames */ 42, /* 2 */ 84, /* 4 */ 167, /* 8 */ 333, /* 16 */ 667, /* 32 */ 1000, /* 48 */ 1333, /* 64 */ 2000, /* 96 */ 2667, /* 128 */ 3333, /* 160 */ 4000, /* 192 */ 4667, /* 224 */ 5333, /* 256 */ 6000, /* 288 */ 0 /* No delay, switch matrix always on */ }; /* * Delay after issuing a POLL command. * * The delay is 3 AC97 link frames + the touchpanel settling delay */ static inline void poll_delay(int d) { udelay(3 * AC97_LINK_FRAME + delay_table[d]); } /* * set up the physical settings of the WM9713 */ static void wm9713_phy_init(struct wm97xx *wm) { u16 dig1 = 0, dig2, dig3; /* default values */ dig2 = WM97XX_DELAY(4) | WM97XX_SLT(5); dig3 = WM9712_RPU(1); /* rpu */ if (rpu) { dig3 &= 0xffc0; dig3 |= WM9712_RPU(rpu); dev_info(wm->dev, "setting pen detect pull-up to %d Ohms\n", 64000 / rpu); } /* Five wire panel? */ if (five_wire) { dig3 |= WM9713_45W; dev_info(wm->dev, "setting 5-wire touchscreen mode."); if (pil) { dev_warn(wm->dev, "Pressure measurement not supported in 5 " "wire mode, disabling\n"); pil = 0; } } /* touchpanel pressure */ if (pil == 2) { dig3 |= WM9712_PIL; dev_info(wm->dev, "setting pressure measurement current to 400uA."); } else if (pil) dev_info(wm->dev, "setting pressure measurement current to 200uA."); if (!pil) pressure = 0; /* sample settling delay */ if (delay < 0 || delay > 15) { dev_info(wm->dev, "supplied delay out of range."); delay = 4; dev_info(wm->dev, "setting adc sample delay to %d u Secs.", delay_table[delay]); } dig2 &= 0xff0f; dig2 |= WM97XX_DELAY(delay); /* mask */ dig3 |= ((mask & 0x3) << 4); if (coord) dig3 |= WM9713_WAIT; wm->misc = wm97xx_reg_read(wm, 0x5a); wm97xx_reg_write(wm, AC97_WM9713_DIG1, dig1); wm97xx_reg_write(wm, AC97_WM9713_DIG2, dig2); wm97xx_reg_write(wm, AC97_WM9713_DIG3, dig3); wm97xx_reg_write(wm, AC97_GPIO_STICKY, 0x0); } static void wm9713_dig_enable(struct wm97xx *wm, int enable) { u16 val; if (enable) { val = wm97xx_reg_read(wm, AC97_EXTENDED_MID); wm97xx_reg_write(wm, AC97_EXTENDED_MID, val & 0x7fff); wm97xx_reg_write(wm, AC97_WM9713_DIG3, wm->dig[2] | WM97XX_PRP_DET_DIG); wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); /* dummy read */ } else { wm97xx_reg_write(wm, AC97_WM9713_DIG3, wm->dig[2] & ~WM97XX_PRP_DET_DIG); val = wm97xx_reg_read(wm, AC97_EXTENDED_MID); wm97xx_reg_write(wm, AC97_EXTENDED_MID, val | 0x8000); } } static void wm9713_dig_restore(struct wm97xx *wm) { wm97xx_reg_write(wm, AC97_WM9713_DIG1, wm->dig_save[0]); wm97xx_reg_write(wm, AC97_WM9713_DIG2, wm->dig_save[1]); wm97xx_reg_write(wm, AC97_WM9713_DIG3, wm->dig_save[2]); } static void wm9713_aux_prepare(struct wm97xx *wm) { memcpy(wm->dig_save, wm->dig, sizeof(wm->dig)); wm97xx_reg_write(wm, AC97_WM9713_DIG1, 0); wm97xx_reg_write(wm, AC97_WM9713_DIG2, 0); wm97xx_reg_write(wm, AC97_WM9713_DIG3, WM97XX_PRP_DET_DIG); } static inline int is_pden(struct wm97xx *wm) { return wm->dig[2] & WM9713_PDEN; } /* * Read a sample from the WM9713 adc in polling mode. */ static int wm9713_poll_sample(struct wm97xx *wm, int adcsel, int *sample) { u16 dig1; int timeout = 5 * delay; bool wants_pen = adcsel & WM97XX_PEN_DOWN; if (wants_pen && !wm->pen_probably_down) { u16 data = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (!(data & WM97XX_PEN_DOWN)) return RC_PENUP; wm->pen_probably_down = 1; } /* set up digitiser */ dig1 = wm97xx_reg_read(wm, AC97_WM9713_DIG1); dig1 &= ~WM9713_ADCSEL_MASK; /* WM97XX_ADCSEL_* channels need to be converted to WM9713 format */ dig1 |= 1 << ((adcsel & WM97XX_ADCSEL_MASK) >> 12); if (wm->mach_ops && wm->mach_ops->pre_sample) wm->mach_ops->pre_sample(adcsel); wm97xx_reg_write(wm, AC97_WM9713_DIG1, dig1 | WM9713_POLL); /* wait 3 AC97 time slots + delay for conversion */ poll_delay(delay); /* wait for POLL to go low */ while ((wm97xx_reg_read(wm, AC97_WM9713_DIG1) & WM9713_POLL) && timeout) { udelay(AC97_LINK_FRAME); timeout--; } if (timeout <= 0) { /* If PDEN is set, we can get a timeout when pen goes up */ if (is_pden(wm)) wm->pen_probably_down = 0; else dev_dbg(wm->dev, "adc sample timeout"); return RC_PENUP; } *sample = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (wm->mach_ops && wm->mach_ops->post_sample) wm->mach_ops->post_sample(adcsel); /* check we have correct sample */ if ((*sample ^ adcsel) & WM97XX_ADCSEL_MASK) { dev_dbg(wm->dev, "adc wrong sample, wanted %x got %x", adcsel & WM97XX_ADCSEL_MASK, *sample & WM97XX_ADCSEL_MASK); return RC_PENUP; } if (wants_pen && !(*sample & WM97XX_PEN_DOWN)) { wm->pen_probably_down = 0; return RC_PENUP; } return RC_VALID; } /* * Read a coordinate from the WM9713 adc in polling mode. */ static int wm9713_poll_coord(struct wm97xx *wm, struct wm97xx_data *data) { u16 dig1; int timeout = 5 * delay; if (!wm->pen_probably_down) { u16 val = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (!(val & WM97XX_PEN_DOWN)) return RC_PENUP; wm->pen_probably_down = 1; } /* set up digitiser */ dig1 = wm97xx_reg_read(wm, AC97_WM9713_DIG1); dig1 &= ~WM9713_ADCSEL_MASK; if (pil) dig1 |= WM9713_ADCSEL_PRES; if (wm->mach_ops && wm->mach_ops->pre_sample) wm->mach_ops->pre_sample(WM97XX_ADCSEL_X | WM97XX_ADCSEL_Y); wm97xx_reg_write(wm, AC97_WM9713_DIG1, dig1 | WM9713_POLL | WM9713_COO); /* wait 3 AC97 time slots + delay for conversion */ poll_delay(delay); data->x = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); /* wait for POLL to go low */ while ((wm97xx_reg_read(wm, AC97_WM9713_DIG1) & WM9713_POLL) && timeout) { udelay(AC97_LINK_FRAME); timeout--; } if (timeout <= 0) { /* If PDEN is set, we can get a timeout when pen goes up */ if (is_pden(wm)) wm->pen_probably_down = 0; else dev_dbg(wm->dev, "adc sample timeout"); return RC_PENUP; } /* read back data */ data->y = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (pil) data->p = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); else data->p = DEFAULT_PRESSURE; if (wm->mach_ops && wm->mach_ops->post_sample) wm->mach_ops->post_sample(WM97XX_ADCSEL_X | WM97XX_ADCSEL_Y); /* check we have correct sample */ if (!(data->x & WM97XX_ADCSEL_X) || !(data->y & WM97XX_ADCSEL_Y)) goto err; if (pil && !(data->p & WM97XX_ADCSEL_PRES)) goto err; if (!(data->x & WM97XX_PEN_DOWN) || !(data->y & WM97XX_PEN_DOWN)) { wm->pen_probably_down = 0; return RC_PENUP; } return RC_VALID; err: return 0; } /* * Sample the WM9713 touchscreen in polling mode */ static int wm9713_poll_touch(struct wm97xx *wm, struct wm97xx_data *data) { int rc; if (coord) { rc = wm9713_poll_coord(wm, data); if (rc != RC_VALID) return rc; } else { rc = wm9713_poll_sample(wm, WM97XX_ADCSEL_X | WM97XX_PEN_DOWN, &data->x); if (rc != RC_VALID) return rc; rc = wm9713_poll_sample(wm, WM97XX_ADCSEL_Y | WM97XX_PEN_DOWN, &data->y); if (rc != RC_VALID) return rc; if (pil) { rc = wm9713_poll_sample(wm, WM97XX_ADCSEL_PRES | WM97XX_PEN_DOWN, &data->p); if (rc != RC_VALID) return rc; } else data->p = DEFAULT_PRESSURE; } return RC_VALID; } /* * Enable WM9713 continuous mode, i.e. touch data is streamed across * an AC97 slot */ static int wm9713_acc_enable(struct wm97xx *wm, int enable) { u16 dig1, dig2, dig3; int ret = 0; dig1 = wm->dig[0]; dig2 = wm->dig[1]; dig3 = wm->dig[2]; if (enable) { /* continuous mode */ if (wm->mach_ops->acc_startup && (ret = wm->mach_ops->acc_startup(wm)) < 0) return ret; dig1 &= ~WM9713_ADCSEL_MASK; dig1 |= WM9713_CTC | WM9713_COO | WM9713_ADCSEL_X | WM9713_ADCSEL_Y; if (pil) dig1 |= WM9713_ADCSEL_PRES; dig2 &= ~(WM97XX_DELAY_MASK | WM97XX_SLT_MASK | WM97XX_CM_RATE_MASK); dig2 |= WM97XX_SLEN | WM97XX_DELAY(delay) | WM97XX_SLT(wm->acc_slot) | WM97XX_RATE(wm->acc_rate); dig3 |= WM9713_PDEN; } else { dig1 &= ~(WM9713_CTC | WM9713_COO); dig2 &= ~WM97XX_SLEN; dig3 &= ~WM9713_PDEN; if (wm->mach_ops->acc_shutdown) wm->mach_ops->acc_shutdown(wm); } wm97xx_reg_write(wm, AC97_WM9713_DIG1, dig1); wm97xx_reg_write(wm, AC97_WM9713_DIG2, dig2); wm97xx_reg_write(wm, AC97_WM9713_DIG3, dig3); return ret; } struct wm97xx_codec_drv wm9713_codec = { .id = WM9713_ID2, .name = "wm9713", .poll_sample = wm9713_poll_sample, .poll_touch = wm9713_poll_touch, .acc_enable = wm9713_acc_enable, .phy_init = wm9713_phy_init, .dig_enable = wm9713_dig_enable, .dig_restore = wm9713_dig_restore, .aux_prepare = wm9713_aux_prepare, }; EXPORT_SYMBOL_GPL(wm9713_codec); /* Module information */ MODULE_AUTHOR("Liam Girdwood <[email protected]>"); MODULE_DESCRIPTION("WM9713 Touch Screen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wm9713.c
// SPDX-License-Identifier: GPL-2.0-only /* * Goodix Touchscreen firmware upload support * * Copyright (c) 2021 Hans de Goede <[email protected]> * * This is a rewrite of gt9xx_update.c from the Allwinner H3 BSP which is: * Copyright (c) 2010 - 2012 Goodix Technology. * Author: [email protected] */ #include <linux/device.h> #include <linux/firmware.h> #include <linux/i2c.h> #include "goodix.h" #define GOODIX_FW_HEADER_LENGTH sizeof(struct goodix_fw_header) #define GOODIX_FW_SECTION_LENGTH 0x2000 #define GOODIX_FW_DSP_LENGTH 0x1000 #define GOODIX_FW_UPLOAD_ADDRESS 0xc000 #define GOODIX_CFG_LOC_HAVE_KEY 7 #define GOODIX_CFG_LOC_DRVA_NUM 27 #define GOODIX_CFG_LOC_DRVB_NUM 28 #define GOODIX_CFG_LOC_SENS_NUM 29 struct goodix_fw_header { u8 hw_info[4]; u8 pid[8]; u8 vid[2]; } __packed; static u16 goodix_firmware_checksum(const u8 *data, int size) { u16 checksum = 0; int i; for (i = 0; i < size; i += 2) checksum += (data[i] << 8) + data[i + 1]; return checksum; } static int goodix_firmware_verify(struct device *dev, const struct firmware *fw) { const struct goodix_fw_header *fw_header; size_t expected_size; const u8 *data; u16 checksum; char buf[9]; expected_size = GOODIX_FW_HEADER_LENGTH + 4 * GOODIX_FW_SECTION_LENGTH + GOODIX_FW_DSP_LENGTH; if (fw->size != expected_size) { dev_err(dev, "Firmware has wrong size, expected %zu got %zu\n", expected_size, fw->size); return -EINVAL; } data = fw->data + GOODIX_FW_HEADER_LENGTH; checksum = goodix_firmware_checksum(data, 4 * GOODIX_FW_SECTION_LENGTH); if (checksum) { dev_err(dev, "Main firmware checksum error\n"); return -EINVAL; } data += 4 * GOODIX_FW_SECTION_LENGTH; checksum = goodix_firmware_checksum(data, GOODIX_FW_DSP_LENGTH); if (checksum) { dev_err(dev, "DSP firmware checksum error\n"); return -EINVAL; } fw_header = (const struct goodix_fw_header *)fw->data; dev_info(dev, "Firmware hardware info %02x%02x%02x%02x\n", fw_header->hw_info[0], fw_header->hw_info[1], fw_header->hw_info[2], fw_header->hw_info[3]); /* pid is a 8 byte buffer containing a string, weird I know */ memcpy(buf, fw_header->pid, 8); buf[8] = 0; dev_info(dev, "Firmware PID: %s VID: %02x%02x\n", buf, fw_header->vid[0], fw_header->vid[1]); return 0; } static int goodix_enter_upload_mode(struct i2c_client *client) { int tries, error; u8 val; tries = 200; do { error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_SWRST, 0x0c); if (error) return error; error = goodix_i2c_read(client, GOODIX_REG_MISCTL_SWRST, &val, 1); if (error) return error; if (val == 0x0c) break; } while (--tries); if (!tries) { dev_err(&client->dev, "Error could not hold ss51 & dsp\n"); return -EIO; } /* DSP_CK and DSP_ALU_CK PowerOn */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_DSP_CTL, 0x00); if (error) return error; /* Disable watchdog */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_TMR0_EN, 0x00); if (error) return error; /* Clear cache enable */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_CACHE_EN, 0x00); if (error) return error; /* Set boot from SRAM */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_BOOTCTL, 0x02); if (error) return error; /* Software reboot */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_CPU_SWRST_PULSE, 0x01); if (error) return error; /* Clear control flag */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_BOOTCTL, 0x00); if (error) return error; /* Set scramble */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_BOOT_OPT, 0x00); if (error) return error; /* Enable accessing code */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_MEM_CD_EN, 0x01); if (error) return error; return 0; } static int goodix_start_firmware(struct i2c_client *client) { int error; u8 val; /* Init software watchdog */ error = goodix_i2c_write_u8(client, GOODIX_REG_SW_WDT, 0xaa); if (error) return error; /* Release SS51 & DSP */ error = goodix_i2c_write_u8(client, GOODIX_REG_MISCTL_SWRST, 0x00); if (error) return error; error = goodix_i2c_read(client, GOODIX_REG_SW_WDT, &val, 1); if (error) return error; /* The value we've written to SW_WDT should have been cleared now */ if (val == 0xaa) { dev_err(&client->dev, "Error SW_WDT reg not cleared on fw startup\n"); return -EIO; } /* Re-init software watchdog */ error = goodix_i2c_write_u8(client, GOODIX_REG_SW_WDT, 0xaa); if (error) return error; return 0; } static int goodix_firmware_upload(struct goodix_ts_data *ts) { const struct firmware *fw; char fw_name[64]; const u8 *data; int error; snprintf(fw_name, sizeof(fw_name), "goodix/%s", ts->firmware_name); error = request_firmware(&fw, fw_name, &ts->client->dev); if (error) { dev_err(&ts->client->dev, "Firmware request error %d\n", error); return error; } error = goodix_firmware_verify(&ts->client->dev, fw); if (error) goto release; error = goodix_reset_no_int_sync(ts); if (error) goto release; error = goodix_enter_upload_mode(ts->client); if (error) goto release; /* Select SRAM bank 0 and upload section 1 & 2 */ error = goodix_i2c_write_u8(ts->client, GOODIX_REG_MISCTL_SRAM_BANK, 0x00); if (error) goto release; data = fw->data + GOODIX_FW_HEADER_LENGTH; error = goodix_i2c_write(ts->client, GOODIX_FW_UPLOAD_ADDRESS, data, 2 * GOODIX_FW_SECTION_LENGTH); if (error) goto release; /* Select SRAM bank 1 and upload section 3 & 4 */ error = goodix_i2c_write_u8(ts->client, GOODIX_REG_MISCTL_SRAM_BANK, 0x01); if (error) goto release; data += 2 * GOODIX_FW_SECTION_LENGTH; error = goodix_i2c_write(ts->client, GOODIX_FW_UPLOAD_ADDRESS, data, 2 * GOODIX_FW_SECTION_LENGTH); if (error) goto release; /* Select SRAM bank 2 and upload the DSP firmware */ error = goodix_i2c_write_u8(ts->client, GOODIX_REG_MISCTL_SRAM_BANK, 0x02); if (error) goto release; data += 2 * GOODIX_FW_SECTION_LENGTH; error = goodix_i2c_write(ts->client, GOODIX_FW_UPLOAD_ADDRESS, data, GOODIX_FW_DSP_LENGTH); if (error) goto release; error = goodix_start_firmware(ts->client); if (error) goto release; error = goodix_int_sync(ts); release: release_firmware(fw); return error; } static int goodix_prepare_bak_ref(struct goodix_ts_data *ts) { u8 have_key, driver_num, sensor_num; if (ts->bak_ref) return 0; /* Already done */ have_key = (ts->config[GOODIX_CFG_LOC_HAVE_KEY] & 0x01); driver_num = (ts->config[GOODIX_CFG_LOC_DRVA_NUM] & 0x1f) + (ts->config[GOODIX_CFG_LOC_DRVB_NUM] & 0x1f); if (have_key) driver_num--; sensor_num = (ts->config[GOODIX_CFG_LOC_SENS_NUM] & 0x0f) + ((ts->config[GOODIX_CFG_LOC_SENS_NUM] >> 4) & 0x0f); dev_dbg(&ts->client->dev, "Drv %d Sen %d Key %d\n", driver_num, sensor_num, have_key); ts->bak_ref_len = (driver_num * (sensor_num - 2) + 2) * 2; ts->bak_ref = devm_kzalloc(&ts->client->dev, ts->bak_ref_len, GFP_KERNEL); if (!ts->bak_ref) return -ENOMEM; /* * The bak_ref array contains the backup of an array of (self/auto) * calibration related values which the Android version of the driver * stores on the filesystem so that it can be restored after reboot. * The mainline kernel never writes directly to the filesystem like * this, we always start will all the values which give a correction * factor in approx. the -20 - +20 range (in 2s complement) set to 0. * * Note the touchscreen works fine without restoring the reference * values after a reboot / power-cycle. * * The last 2 bytes are a 16 bits unsigned checksum which is expected * to make the addition al all 16 bit unsigned values in the array add * up to 1 (rather then the usual 0), so we must set the last byte to 1. */ ts->bak_ref[ts->bak_ref_len - 1] = 1; return 0; } static int goodix_send_main_clock(struct goodix_ts_data *ts) { u32 main_clk = 54; /* Default main clock */ u8 checksum = 0; int i; device_property_read_u32(&ts->client->dev, "goodix,main-clk", &main_clk); for (i = 0; i < (GOODIX_MAIN_CLK_LEN - 1); i++) { ts->main_clk[i] = main_clk; checksum += main_clk; } /* The value of all bytes combines must be 0 */ ts->main_clk[GOODIX_MAIN_CLK_LEN - 1] = 256 - checksum; return goodix_i2c_write(ts->client, GOODIX_REG_MAIN_CLK, ts->main_clk, GOODIX_MAIN_CLK_LEN); } int goodix_firmware_check(struct goodix_ts_data *ts) { device_property_read_string(&ts->client->dev, "firmware-name", &ts->firmware_name); if (!ts->firmware_name) return 0; if (ts->irq_pin_access_method == IRQ_PIN_ACCESS_NONE) { dev_err(&ts->client->dev, "Error no IRQ-pin access method, cannot upload fw.\n"); return -EINVAL; } dev_info(&ts->client->dev, "Touchscreen controller needs fw-upload\n"); ts->load_cfg_from_disk = true; return goodix_firmware_upload(ts); } bool goodix_handle_fw_request(struct goodix_ts_data *ts) { int error; u8 val; error = goodix_i2c_read(ts->client, GOODIX_REG_REQUEST, &val, 1); if (error) return false; switch (val) { case GOODIX_RQST_RESPONDED: /* * If we read back our own last ack the IRQ was not for * a request. */ return false; case GOODIX_RQST_CONFIG: error = goodix_send_cfg(ts, ts->config, ts->chip->config_len); if (error) return false; break; case GOODIX_RQST_BAK_REF: error = goodix_prepare_bak_ref(ts); if (error) return false; error = goodix_i2c_write(ts->client, GOODIX_REG_BAK_REF, ts->bak_ref, ts->bak_ref_len); if (error) return false; break; case GOODIX_RQST_RESET: error = goodix_firmware_upload(ts); if (error) return false; break; case GOODIX_RQST_MAIN_CLOCK: error = goodix_send_main_clock(ts); if (error) return false; break; case GOODIX_RQST_UNKNOWN: case GOODIX_RQST_IDLE: break; default: dev_err_ratelimited(&ts->client->dev, "Unknown Request: 0x%02x\n", val); } /* Ack the request */ goodix_i2c_write_u8(ts->client, GOODIX_REG_REQUEST, GOODIX_RQST_RESPONDED); return true; } void goodix_save_bak_ref(struct goodix_ts_data *ts) { int error; u8 val; if (!ts->firmware_name) return; error = goodix_i2c_read(ts->client, GOODIX_REG_STATUS, &val, 1); if (error) return; if (!(val & 0x80)) return; error = goodix_i2c_read(ts->client, GOODIX_REG_BAK_REF, ts->bak_ref, ts->bak_ref_len); if (error) { memset(ts->bak_ref, 0, ts->bak_ref_len); ts->bak_ref[ts->bak_ref_len - 1] = 1; } }
linux-master
drivers/input/touchscreen/goodix_fwupload.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/input/touchscreen/jornada720_ts.c * * Copyright (C) 2007 Kristoffer Ericson <[email protected]> * * Copyright (C) 2006 Filip Zyzniewski <[email protected]> * based on HP Jornada 56x touchscreen driver by Alex Lange <[email protected]> * * HP Jornada 710/720/729 Touchscreen Driver */ #include <linux/gpio/consumer.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/io.h> #include <mach/jornada720.h> MODULE_AUTHOR("Kristoffer Ericson <[email protected]>"); MODULE_DESCRIPTION("HP Jornada 710/720/728 touchscreen driver"); MODULE_LICENSE("GPL v2"); struct jornada_ts { struct input_dev *dev; struct gpio_desc *gpio; int x_data[4]; /* X sample values */ int y_data[4]; /* Y sample values */ }; static void jornada720_ts_collect_data(struct jornada_ts *jornada_ts) { /* 3 low word X samples */ jornada_ts->x_data[0] = jornada_ssp_byte(TXDUMMY); jornada_ts->x_data[1] = jornada_ssp_byte(TXDUMMY); jornada_ts->x_data[2] = jornada_ssp_byte(TXDUMMY); /* 3 low word Y samples */ jornada_ts->y_data[0] = jornada_ssp_byte(TXDUMMY); jornada_ts->y_data[1] = jornada_ssp_byte(TXDUMMY); jornada_ts->y_data[2] = jornada_ssp_byte(TXDUMMY); /* combined x samples bits */ jornada_ts->x_data[3] = jornada_ssp_byte(TXDUMMY); /* combined y samples bits */ jornada_ts->y_data[3] = jornada_ssp_byte(TXDUMMY); } static int jornada720_ts_average(int coords[4]) { int coord, high_bits = coords[3]; coord = coords[0] | ((high_bits & 0x03) << 8); coord += coords[1] | ((high_bits & 0x0c) << 6); coord += coords[2] | ((high_bits & 0x30) << 4); return coord / 3; } static irqreturn_t jornada720_ts_interrupt(int irq, void *dev_id) { struct platform_device *pdev = dev_id; struct jornada_ts *jornada_ts = platform_get_drvdata(pdev); struct input_dev *input = jornada_ts->dev; int x, y; /* If gpio is high then report pen up */ if (gpiod_get_value(jornada_ts->gpio)) { input_report_key(input, BTN_TOUCH, 0); input_sync(input); } else { jornada_ssp_start(); /* proper reply to request is always TXDUMMY */ if (jornada_ssp_inout(GETTOUCHSAMPLES) == TXDUMMY) { jornada720_ts_collect_data(jornada_ts); x = jornada720_ts_average(jornada_ts->x_data); y = jornada720_ts_average(jornada_ts->y_data); input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, x); input_report_abs(input, ABS_Y, y); input_sync(input); } jornada_ssp_end(); } return IRQ_HANDLED; } static int jornada720_ts_probe(struct platform_device *pdev) { struct jornada_ts *jornada_ts; struct input_dev *input_dev; int error, irq; jornada_ts = devm_kzalloc(&pdev->dev, sizeof(*jornada_ts), GFP_KERNEL); if (!jornada_ts) return -ENOMEM; input_dev = devm_input_allocate_device(&pdev->dev); if (!input_dev) return -ENOMEM; platform_set_drvdata(pdev, jornada_ts); jornada_ts->gpio = devm_gpiod_get(&pdev->dev, "penup", GPIOD_IN); if (IS_ERR(jornada_ts->gpio)) return PTR_ERR(jornada_ts->gpio); irq = gpiod_to_irq(jornada_ts->gpio); if (irq <= 0) return irq < 0 ? irq : -EINVAL; jornada_ts->dev = input_dev; input_dev->name = "HP Jornada 7xx Touchscreen"; input_dev->phys = "jornadats/input0"; input_dev->id.bustype = BUS_HOST; input_dev->dev.parent = &pdev->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 270, 3900, 0, 0); input_set_abs_params(input_dev, ABS_Y, 180, 3700, 0, 0); error = devm_request_irq(&pdev->dev, irq, jornada720_ts_interrupt, IRQF_TRIGGER_RISING, "HP7XX Touchscreen driver", pdev); if (error) { dev_err(&pdev->dev, "HP7XX TS : Unable to acquire irq!\n"); return error; } error = input_register_device(jornada_ts->dev); if (error) return error; return 0; } /* work with hotplug and coldplug */ MODULE_ALIAS("platform:jornada_ts"); static struct platform_driver jornada720_ts_driver = { .probe = jornada720_ts_probe, .driver = { .name = "jornada_ts", }, }; module_platform_driver(jornada720_ts_driver);
linux-master
drivers/input/touchscreen/jornada720_ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2016, Jelle van der Waa <[email protected]> */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/regulator/consumer.h> #include <asm/unaligned.h> #define ZET6223_MAX_FINGERS 16 #define ZET6223_MAX_PKT_SIZE (3 + 4 * ZET6223_MAX_FINGERS) #define ZET6223_CMD_INFO 0xB2 #define ZET6223_CMD_INFO_LENGTH 17 #define ZET6223_VALID_PACKET 0x3c #define ZET6223_POWER_ON_DELAY_MSEC 30 struct zet6223_ts { struct i2c_client *client; struct input_dev *input; struct regulator *vcc; struct regulator *vio; struct touchscreen_properties prop; struct regulator_bulk_data supplies[2]; u16 max_x; u16 max_y; u8 fingernum; }; static int zet6223_start(struct input_dev *dev) { struct zet6223_ts *ts = input_get_drvdata(dev); enable_irq(ts->client->irq); return 0; } static void zet6223_stop(struct input_dev *dev) { struct zet6223_ts *ts = input_get_drvdata(dev); disable_irq(ts->client->irq); } static irqreturn_t zet6223_irq(int irq, void *dev_id) { struct zet6223_ts *ts = dev_id; u16 finger_bits; /* * First 3 bytes are an identifier, two bytes of finger data. * X, Y data per finger is 4 bytes. */ u8 bufsize = 3 + 4 * ts->fingernum; u8 buf[ZET6223_MAX_PKT_SIZE]; int i; int ret; int error; ret = i2c_master_recv(ts->client, buf, bufsize); if (ret != bufsize) { error = ret < 0 ? ret : -EIO; dev_err_ratelimited(&ts->client->dev, "Error reading input data: %d\n", error); return IRQ_HANDLED; } if (buf[0] != ZET6223_VALID_PACKET) return IRQ_HANDLED; finger_bits = get_unaligned_be16(buf + 1); for (i = 0; i < ts->fingernum; i++) { if (!(finger_bits & BIT(15 - i))) continue; input_mt_slot(ts->input, i); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, true); input_event(ts->input, EV_ABS, ABS_MT_POSITION_X, ((buf[i + 3] >> 4) << 8) + buf[i + 4]); input_event(ts->input, EV_ABS, ABS_MT_POSITION_Y, ((buf[i + 3] & 0xF) << 8) + buf[i + 5]); } input_mt_sync_frame(ts->input); input_sync(ts->input); return IRQ_HANDLED; } static void zet6223_power_off(void *_ts) { struct zet6223_ts *ts = _ts; regulator_bulk_disable(ARRAY_SIZE(ts->supplies), ts->supplies); } static int zet6223_power_on(struct zet6223_ts *ts) { struct device *dev = &ts->client->dev; int error; ts->supplies[0].supply = "vio"; ts->supplies[1].supply = "vcc"; error = devm_regulator_bulk_get(dev, ARRAY_SIZE(ts->supplies), ts->supplies); if (error) return error; error = regulator_bulk_enable(ARRAY_SIZE(ts->supplies), ts->supplies); if (error) return error; msleep(ZET6223_POWER_ON_DELAY_MSEC); error = devm_add_action_or_reset(dev, zet6223_power_off, ts); if (error) { dev_err(dev, "failed to install poweroff action: %d\n", error); return error; } return 0; } static int zet6223_query_device(struct zet6223_ts *ts) { u8 buf[ZET6223_CMD_INFO_LENGTH]; u8 cmd = ZET6223_CMD_INFO; int ret; int error; ret = i2c_master_send(ts->client, &cmd, sizeof(cmd)); if (ret != sizeof(cmd)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "touchpanel info cmd failed: %d\n", error); return error; } ret = i2c_master_recv(ts->client, buf, sizeof(buf)); if (ret != sizeof(buf)) { error = ret < 0 ? ret : -EIO; dev_err(&ts->client->dev, "failed to retrieve touchpanel info: %d\n", error); return error; } ts->fingernum = buf[15] & 0x7F; if (ts->fingernum > ZET6223_MAX_FINGERS) { dev_warn(&ts->client->dev, "touchpanel reports %d fingers, limiting to %d\n", ts->fingernum, ZET6223_MAX_FINGERS); ts->fingernum = ZET6223_MAX_FINGERS; } ts->max_x = get_unaligned_le16(&buf[8]); ts->max_y = get_unaligned_le16(&buf[10]); return 0; } static int zet6223_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct zet6223_ts *ts; struct input_dev *input; int error; if (!client->irq) { dev_err(dev, "no irq specified\n"); return -EINVAL; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; error = zet6223_power_on(ts); if (error) return error; error = zet6223_query_device(ts); if (error) return error; ts->input = input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input_set_drvdata(input, ts); input->name = client->name; input->id.bustype = BUS_I2C; input->open = zet6223_start; input->close = zet6223_stop; input_set_abs_params(input, ABS_MT_POSITION_X, 0, ts->max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, ts->max_y, 0, 0); touchscreen_parse_properties(input, true, &ts->prop); error = input_mt_init_slots(input, ts->fingernum, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; error = devm_request_threaded_irq(dev, client->irq, NULL, zet6223_irq, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(dev, "failed to request irq %d: %d\n", client->irq, error); return error; } zet6223_stop(input); error = input_register_device(input); if (error) return error; return 0; } static const struct of_device_id zet6223_of_match[] = { { .compatible = "zeitec,zet6223" }, { } }; MODULE_DEVICE_TABLE(of, zet6223_of_match); static const struct i2c_device_id zet6223_id[] = { { "zet6223", 0}, { } }; MODULE_DEVICE_TABLE(i2c, zet6223_id); static struct i2c_driver zet6223_driver = { .driver = { .name = "zet6223", .of_match_table = zet6223_of_match, }, .probe = zet6223_probe, .id_table = zet6223_id }; module_i2c_driver(zet6223_driver); MODULE_AUTHOR("Jelle van der Waa <[email protected]>"); MODULE_DESCRIPTION("ZEITEC zet622x I2C touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/zet6223.c
// SPDX-License-Identifier: GPL-2.0 /* * ILITEK Touch IC driver for 23XX, 25XX and Lego series * * Copyright (C) 2011 ILI Technology Corporation. * Copyright (C) 2020 Luca Hsu <[email protected]> * Copyright (C) 2021 Joe Hung <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/gpio/consumer.h> #include <linux/errno.h> #include <linux/acpi.h> #include <linux/input/touchscreen.h> #include <asm/unaligned.h> #define ILITEK_TS_NAME "ilitek_ts" #define BL_V1_8 0x108 #define BL_V1_7 0x107 #define BL_V1_6 0x106 #define ILITEK_TP_CMD_GET_TP_RES 0x20 #define ILITEK_TP_CMD_GET_SCRN_RES 0x21 #define ILITEK_TP_CMD_SET_IC_SLEEP 0x30 #define ILITEK_TP_CMD_SET_IC_WAKE 0x31 #define ILITEK_TP_CMD_GET_FW_VER 0x40 #define ILITEK_TP_CMD_GET_PRL_VER 0x42 #define ILITEK_TP_CMD_GET_MCU_VER 0x61 #define ILITEK_TP_CMD_GET_IC_MODE 0xC0 #define REPORT_COUNT_ADDRESS 61 #define ILITEK_SUPPORT_MAX_POINT 40 struct ilitek_protocol_info { u16 ver; u8 ver_major; }; struct ilitek_ts_data { struct i2c_client *client; struct gpio_desc *reset_gpio; struct input_dev *input_dev; struct touchscreen_properties prop; const struct ilitek_protocol_map *ptl_cb_func; struct ilitek_protocol_info ptl; char product_id[30]; u16 mcu_ver; u8 ic_mode; u8 firmware_ver[8]; s32 reset_time; s32 screen_max_x; s32 screen_max_y; s32 screen_min_x; s32 screen_min_y; s32 max_tp; }; struct ilitek_protocol_map { u16 cmd; const char *name; int (*func)(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf); }; enum ilitek_cmds { /* common cmds */ GET_PTL_VER = 0, GET_FW_VER, GET_SCRN_RES, GET_TP_RES, GET_IC_MODE, GET_MCU_VER, SET_IC_SLEEP, SET_IC_WAKE, /* ALWAYS keep at the end */ MAX_CMD_CNT }; /* ILITEK I2C R/W APIs */ static int ilitek_i2c_write_and_read(struct ilitek_ts_data *ts, u8 *cmd, int write_len, int delay, u8 *data, int read_len) { int error; struct i2c_client *client = ts->client; struct i2c_msg msgs[] = { { .addr = client->addr, .flags = 0, .len = write_len, .buf = cmd, }, { .addr = client->addr, .flags = I2C_M_RD, .len = read_len, .buf = data, }, }; if (delay == 0 && write_len > 0 && read_len > 0) { error = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (error < 0) return error; } else { if (write_len > 0) { error = i2c_transfer(client->adapter, msgs, 1); if (error < 0) return error; } if (delay > 0) mdelay(delay); if (read_len > 0) { error = i2c_transfer(client->adapter, msgs + 1, 1); if (error < 0) return error; } } return 0; } /* ILITEK ISR APIs */ static void ilitek_touch_down(struct ilitek_ts_data *ts, unsigned int id, unsigned int x, unsigned int y) { struct input_dev *input = ts->input_dev; input_mt_slot(input, id); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); touchscreen_report_pos(input, &ts->prop, x, y, true); } static int ilitek_process_and_report_v6(struct ilitek_ts_data *ts) { int error = 0; u8 buf[512]; int packet_len = 5; int packet_max_point = 10; int report_max_point; int i, count; struct input_dev *input = ts->input_dev; struct device *dev = &ts->client->dev; unsigned int x, y, status, id; error = ilitek_i2c_write_and_read(ts, NULL, 0, 0, buf, 64); if (error) { dev_err(dev, "get touch info failed, err:%d\n", error); goto err_sync_frame; } report_max_point = buf[REPORT_COUNT_ADDRESS]; if (report_max_point > ts->max_tp) { dev_err(dev, "FW report max point:%d > panel info. max:%d\n", report_max_point, ts->max_tp); error = -EINVAL; goto err_sync_frame; } count = DIV_ROUND_UP(report_max_point, packet_max_point); for (i = 1; i < count; i++) { error = ilitek_i2c_write_and_read(ts, NULL, 0, 0, buf + i * 64, 64); if (error) { dev_err(dev, "get touch info. failed, cnt:%d, err:%d\n", count, error); goto err_sync_frame; } } for (i = 0; i < report_max_point; i++) { status = buf[i * packet_len + 1] & 0x40; if (!status) continue; id = buf[i * packet_len + 1] & 0x3F; x = get_unaligned_le16(buf + i * packet_len + 2); y = get_unaligned_le16(buf + i * packet_len + 4); if (x > ts->screen_max_x || x < ts->screen_min_x || y > ts->screen_max_y || y < ts->screen_min_y) { dev_warn(dev, "invalid position, X[%d,%u,%d], Y[%d,%u,%d]\n", ts->screen_min_x, x, ts->screen_max_x, ts->screen_min_y, y, ts->screen_max_y); continue; } ilitek_touch_down(ts, id, x, y); } err_sync_frame: input_mt_sync_frame(input); input_sync(input); return error; } /* APIs of cmds for ILITEK Touch IC */ static int api_protocol_set_cmd(struct ilitek_ts_data *ts, u16 idx, u8 *inbuf, u8 *outbuf) { u16 cmd; int error; if (idx >= MAX_CMD_CNT) return -EINVAL; cmd = ts->ptl_cb_func[idx].cmd; error = ts->ptl_cb_func[idx].func(ts, cmd, inbuf, outbuf); if (error) return error; return 0; } static int api_protocol_get_ptl_ver(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 3); if (error) return error; ts->ptl.ver = get_unaligned_be16(outbuf); ts->ptl.ver_major = outbuf[0]; return 0; } static int api_protocol_get_mcu_ver(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 32); if (error) return error; ts->mcu_ver = get_unaligned_le16(outbuf); memset(ts->product_id, 0, sizeof(ts->product_id)); memcpy(ts->product_id, outbuf + 6, 26); return 0; } static int api_protocol_get_fw_ver(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 8); if (error) return error; memcpy(ts->firmware_ver, outbuf, 8); return 0; } static int api_protocol_get_scrn_res(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 8); if (error) return error; ts->screen_min_x = get_unaligned_le16(outbuf); ts->screen_min_y = get_unaligned_le16(outbuf + 2); ts->screen_max_x = get_unaligned_le16(outbuf + 4); ts->screen_max_y = get_unaligned_le16(outbuf + 6); return 0; } static int api_protocol_get_tp_res(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 15); if (error) return error; ts->max_tp = outbuf[8]; if (ts->max_tp > ILITEK_SUPPORT_MAX_POINT) { dev_err(&ts->client->dev, "Invalid MAX_TP:%d from FW\n", ts->max_tp); return -EINVAL; } return 0; } static int api_protocol_get_ic_mode(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { int error; u8 buf[64]; buf[0] = cmd; error = ilitek_i2c_write_and_read(ts, buf, 1, 5, outbuf, 2); if (error) return error; ts->ic_mode = outbuf[0]; return 0; } static int api_protocol_set_ic_sleep(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { u8 buf[64]; buf[0] = cmd; return ilitek_i2c_write_and_read(ts, buf, 1, 0, NULL, 0); } static int api_protocol_set_ic_wake(struct ilitek_ts_data *ts, u16 cmd, u8 *inbuf, u8 *outbuf) { u8 buf[64]; buf[0] = cmd; return ilitek_i2c_write_and_read(ts, buf, 1, 0, NULL, 0); } static const struct ilitek_protocol_map ptl_func_map[] = { /* common cmds */ [GET_PTL_VER] = { ILITEK_TP_CMD_GET_PRL_VER, "GET_PTL_VER", api_protocol_get_ptl_ver }, [GET_FW_VER] = { ILITEK_TP_CMD_GET_FW_VER, "GET_FW_VER", api_protocol_get_fw_ver }, [GET_SCRN_RES] = { ILITEK_TP_CMD_GET_SCRN_RES, "GET_SCRN_RES", api_protocol_get_scrn_res }, [GET_TP_RES] = { ILITEK_TP_CMD_GET_TP_RES, "GET_TP_RES", api_protocol_get_tp_res }, [GET_IC_MODE] = { ILITEK_TP_CMD_GET_IC_MODE, "GET_IC_MODE", api_protocol_get_ic_mode }, [GET_MCU_VER] = { ILITEK_TP_CMD_GET_MCU_VER, "GET_MOD_VER", api_protocol_get_mcu_ver }, [SET_IC_SLEEP] = { ILITEK_TP_CMD_SET_IC_SLEEP, "SET_IC_SLEEP", api_protocol_set_ic_sleep }, [SET_IC_WAKE] = { ILITEK_TP_CMD_SET_IC_WAKE, "SET_IC_WAKE", api_protocol_set_ic_wake }, }; /* Probe APIs */ static void ilitek_reset(struct ilitek_ts_data *ts, int delay) { if (ts->reset_gpio) { gpiod_set_value(ts->reset_gpio, 1); mdelay(10); gpiod_set_value(ts->reset_gpio, 0); mdelay(delay); } } static int ilitek_protocol_init(struct ilitek_ts_data *ts) { int error; u8 outbuf[64]; ts->ptl_cb_func = ptl_func_map; ts->reset_time = 600; error = api_protocol_set_cmd(ts, GET_PTL_VER, NULL, outbuf); if (error) return error; /* Protocol v3 is not support currently */ if (ts->ptl.ver_major == 0x3 || ts->ptl.ver == BL_V1_6 || ts->ptl.ver == BL_V1_7) return -EINVAL; return 0; } static int ilitek_read_tp_info(struct ilitek_ts_data *ts, bool boot) { u8 outbuf[256]; int error; error = api_protocol_set_cmd(ts, GET_PTL_VER, NULL, outbuf); if (error) return error; error = api_protocol_set_cmd(ts, GET_MCU_VER, NULL, outbuf); if (error) return error; error = api_protocol_set_cmd(ts, GET_FW_VER, NULL, outbuf); if (error) return error; if (boot) { error = api_protocol_set_cmd(ts, GET_SCRN_RES, NULL, outbuf); if (error) return error; } error = api_protocol_set_cmd(ts, GET_TP_RES, NULL, outbuf); if (error) return error; error = api_protocol_set_cmd(ts, GET_IC_MODE, NULL, outbuf); if (error) return error; return 0; } static int ilitek_input_dev_init(struct device *dev, struct ilitek_ts_data *ts) { int error; struct input_dev *input; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; ts->input_dev = input; input->name = ILITEK_TS_NAME; input->id.bustype = BUS_I2C; __set_bit(INPUT_PROP_DIRECT, input->propbit); input_set_abs_params(input, ABS_MT_POSITION_X, ts->screen_min_x, ts->screen_max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, ts->screen_min_y, ts->screen_max_y, 0, 0); touchscreen_parse_properties(input, true, &ts->prop); error = input_mt_init_slots(input, ts->max_tp, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(dev, "initialize MT slots failed, err:%d\n", error); return error; } error = input_register_device(input); if (error) { dev_err(dev, "register input device failed, err:%d\n", error); return error; } return 0; } static irqreturn_t ilitek_i2c_isr(int irq, void *dev_id) { struct ilitek_ts_data *ts = dev_id; int error; error = ilitek_process_and_report_v6(ts); if (error < 0) { dev_err(&ts->client->dev, "[%s] err:%d\n", __func__, error); return IRQ_NONE; } return IRQ_HANDLED; } static ssize_t firmware_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ilitek_ts_data *ts = i2c_get_clientdata(client); return scnprintf(buf, PAGE_SIZE, "fw version: [%02X%02X.%02X%02X.%02X%02X.%02X%02X]\n", ts->firmware_ver[0], ts->firmware_ver[1], ts->firmware_ver[2], ts->firmware_ver[3], ts->firmware_ver[4], ts->firmware_ver[5], ts->firmware_ver[6], ts->firmware_ver[7]); } static DEVICE_ATTR_RO(firmware_version); static ssize_t product_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct ilitek_ts_data *ts = i2c_get_clientdata(client); return scnprintf(buf, PAGE_SIZE, "product id: [%04X], module: [%s]\n", ts->mcu_ver, ts->product_id); } static DEVICE_ATTR_RO(product_id); static struct attribute *ilitek_sysfs_attrs[] = { &dev_attr_firmware_version.attr, &dev_attr_product_id.attr, NULL }; static struct attribute_group ilitek_attrs_group = { .attrs = ilitek_sysfs_attrs, }; static int ilitek_ts_i2c_probe(struct i2c_client *client) { struct ilitek_ts_data *ts; struct device *dev = &client->dev; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(dev, "i2c check functionality failed\n"); return -ENXIO; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; i2c_set_clientdata(client, ts); ts->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(ts->reset_gpio)) { error = PTR_ERR(ts->reset_gpio); dev_err(dev, "request gpiod failed: %d", error); return error; } ilitek_reset(ts, 1000); error = ilitek_protocol_init(ts); if (error) { dev_err(dev, "protocol init failed: %d", error); return error; } error = ilitek_read_tp_info(ts, true); if (error) { dev_err(dev, "read tp info failed: %d", error); return error; } error = ilitek_input_dev_init(dev, ts); if (error) { dev_err(dev, "input dev init failed: %d", error); return error; } error = devm_request_threaded_irq(dev, ts->client->irq, NULL, ilitek_i2c_isr, IRQF_ONESHOT, "ilitek_touch_irq", ts); if (error) { dev_err(dev, "request threaded irq failed: %d\n", error); return error; } error = devm_device_add_group(dev, &ilitek_attrs_group); if (error) { dev_err(dev, "sysfs create group failed: %d\n", error); return error; } return 0; } static int ilitek_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ilitek_ts_data *ts = i2c_get_clientdata(client); int error; disable_irq(client->irq); if (!device_may_wakeup(dev)) { error = api_protocol_set_cmd(ts, SET_IC_SLEEP, NULL, NULL); if (error) return error; } return 0; } static int ilitek_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct ilitek_ts_data *ts = i2c_get_clientdata(client); int error; if (!device_may_wakeup(dev)) { error = api_protocol_set_cmd(ts, SET_IC_WAKE, NULL, NULL); if (error) return error; ilitek_reset(ts, ts->reset_time); } enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(ilitek_pm_ops, ilitek_suspend, ilitek_resume); static const struct i2c_device_id ilitek_ts_i2c_id[] = { { ILITEK_TS_NAME, 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, ilitek_ts_i2c_id); #ifdef CONFIG_ACPI static const struct acpi_device_id ilitekts_acpi_id[] = { { "ILTK0001", 0 }, { }, }; MODULE_DEVICE_TABLE(acpi, ilitekts_acpi_id); #endif #ifdef CONFIG_OF static const struct of_device_id ilitek_ts_i2c_match[] = { {.compatible = "ilitek,ili2130",}, {.compatible = "ilitek,ili2131",}, {.compatible = "ilitek,ili2132",}, {.compatible = "ilitek,ili2316",}, {.compatible = "ilitek,ili2322",}, {.compatible = "ilitek,ili2323",}, {.compatible = "ilitek,ili2326",}, {.compatible = "ilitek,ili2520",}, {.compatible = "ilitek,ili2521",}, { }, }; MODULE_DEVICE_TABLE(of, ilitek_ts_i2c_match); #endif static struct i2c_driver ilitek_ts_i2c_driver = { .driver = { .name = ILITEK_TS_NAME, .pm = pm_sleep_ptr(&ilitek_pm_ops), .of_match_table = of_match_ptr(ilitek_ts_i2c_match), .acpi_match_table = ACPI_PTR(ilitekts_acpi_id), }, .probe = ilitek_ts_i2c_probe, .id_table = ilitek_ts_i2c_id, }; module_i2c_driver(ilitek_ts_i2c_driver); MODULE_AUTHOR("ILITEK"); MODULE_DESCRIPTION("ILITEK I2C Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ilitek_ts_i2c.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AD7879/AD7889 touchscreen (SPI bus) * * Copyright (C) 2008-2010 Michael Hennerich, Analog Devices Inc. */ #include <linux/input.h> /* BUS_SPI */ #include <linux/pm.h> #include <linux/spi/spi.h> #include <linux/module.h> #include <linux/of.h> #include <linux/regmap.h> #include "ad7879.h" #define AD7879_DEVID 0x7A /* AD7879/AD7889 */ #define MAX_SPI_FREQ_HZ 5000000 #define AD7879_CMD_MAGIC 0xE0 #define AD7879_CMD_READ BIT(2) static const struct regmap_config ad7879_spi_regmap_config = { .reg_bits = 16, .val_bits = 16, .max_register = 15, .read_flag_mask = AD7879_CMD_MAGIC | AD7879_CMD_READ, .write_flag_mask = AD7879_CMD_MAGIC, }; static int ad7879_spi_probe(struct spi_device *spi) { struct regmap *regmap; /* don't exceed max specified SPI CLK frequency */ if (spi->max_speed_hz > MAX_SPI_FREQ_HZ) { dev_err(&spi->dev, "SPI CLK %d Hz?\n", spi->max_speed_hz); return -EINVAL; } regmap = devm_regmap_init_spi(spi, &ad7879_spi_regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); return ad7879_probe(&spi->dev, regmap, spi->irq, BUS_SPI, AD7879_DEVID); } #ifdef CONFIG_OF static const struct of_device_id ad7879_spi_dt_ids[] = { { .compatible = "adi,ad7879", }, { } }; MODULE_DEVICE_TABLE(of, ad7879_spi_dt_ids); #endif static struct spi_driver ad7879_spi_driver = { .driver = { .name = "ad7879", .pm = &ad7879_pm_ops, .of_match_table = of_match_ptr(ad7879_spi_dt_ids), }, .probe = ad7879_spi_probe, }; module_spi_driver(ad7879_spi_driver); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("AD7879(-1) touchscreen SPI bus driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:ad7879");
linux-master
drivers/input/touchscreen/ad7879-spi.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * mcs5000_ts.c - Touchscreen driver for MELFAS MCS-5000 controller * * Copyright (C) 2009 Samsung Electronics Co.Ltd * Author: Joonyoung Shim <[email protected]> * * Based on wm97xx-core.c */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/irq.h> #include <linux/platform_data/mcs.h> #include <linux/slab.h> /* Registers */ #define MCS5000_TS_STATUS 0x00 #define STATUS_OFFSET 0 #define STATUS_NO (0 << STATUS_OFFSET) #define STATUS_INIT (1 << STATUS_OFFSET) #define STATUS_SENSING (2 << STATUS_OFFSET) #define STATUS_COORD (3 << STATUS_OFFSET) #define STATUS_GESTURE (4 << STATUS_OFFSET) #define ERROR_OFFSET 4 #define ERROR_NO (0 << ERROR_OFFSET) #define ERROR_POWER_ON_RESET (1 << ERROR_OFFSET) #define ERROR_INT_RESET (2 << ERROR_OFFSET) #define ERROR_EXT_RESET (3 << ERROR_OFFSET) #define ERROR_INVALID_REG_ADDRESS (8 << ERROR_OFFSET) #define ERROR_INVALID_REG_VALUE (9 << ERROR_OFFSET) #define MCS5000_TS_OP_MODE 0x01 #define RESET_OFFSET 0 #define RESET_NO (0 << RESET_OFFSET) #define RESET_EXT_SOFT (1 << RESET_OFFSET) #define OP_MODE_OFFSET 1 #define OP_MODE_SLEEP (0 << OP_MODE_OFFSET) #define OP_MODE_ACTIVE (1 << OP_MODE_OFFSET) #define GESTURE_OFFSET 4 #define GESTURE_DISABLE (0 << GESTURE_OFFSET) #define GESTURE_ENABLE (1 << GESTURE_OFFSET) #define PROXIMITY_OFFSET 5 #define PROXIMITY_DISABLE (0 << PROXIMITY_OFFSET) #define PROXIMITY_ENABLE (1 << PROXIMITY_OFFSET) #define SCAN_MODE_OFFSET 6 #define SCAN_MODE_INTERRUPT (0 << SCAN_MODE_OFFSET) #define SCAN_MODE_POLLING (1 << SCAN_MODE_OFFSET) #define REPORT_RATE_OFFSET 7 #define REPORT_RATE_40 (0 << REPORT_RATE_OFFSET) #define REPORT_RATE_80 (1 << REPORT_RATE_OFFSET) #define MCS5000_TS_SENS_CTL 0x02 #define MCS5000_TS_FILTER_CTL 0x03 #define PRI_FILTER_OFFSET 0 #define SEC_FILTER_OFFSET 4 #define MCS5000_TS_X_SIZE_UPPER 0x08 #define MCS5000_TS_X_SIZE_LOWER 0x09 #define MCS5000_TS_Y_SIZE_UPPER 0x0A #define MCS5000_TS_Y_SIZE_LOWER 0x0B #define MCS5000_TS_INPUT_INFO 0x10 #define INPUT_TYPE_OFFSET 0 #define INPUT_TYPE_NONTOUCH (0 << INPUT_TYPE_OFFSET) #define INPUT_TYPE_SINGLE (1 << INPUT_TYPE_OFFSET) #define INPUT_TYPE_DUAL (2 << INPUT_TYPE_OFFSET) #define INPUT_TYPE_PALM (3 << INPUT_TYPE_OFFSET) #define INPUT_TYPE_PROXIMITY (7 << INPUT_TYPE_OFFSET) #define GESTURE_CODE_OFFSET 3 #define GESTURE_CODE_NO (0 << GESTURE_CODE_OFFSET) #define MCS5000_TS_X_POS_UPPER 0x11 #define MCS5000_TS_X_POS_LOWER 0x12 #define MCS5000_TS_Y_POS_UPPER 0x13 #define MCS5000_TS_Y_POS_LOWER 0x14 #define MCS5000_TS_Z_POS 0x15 #define MCS5000_TS_WIDTH 0x16 #define MCS5000_TS_GESTURE_VAL 0x17 #define MCS5000_TS_MODULE_REV 0x20 #define MCS5000_TS_FIRMWARE_VER 0x21 /* Touchscreen absolute values */ #define MCS5000_MAX_XC 0x3ff #define MCS5000_MAX_YC 0x3ff enum mcs5000_ts_read_offset { READ_INPUT_INFO, READ_X_POS_UPPER, READ_X_POS_LOWER, READ_Y_POS_UPPER, READ_Y_POS_LOWER, READ_BLOCK_SIZE, }; /* Each client has this additional data */ struct mcs5000_ts_data { struct i2c_client *client; struct input_dev *input_dev; const struct mcs_platform_data *platform_data; }; static irqreturn_t mcs5000_ts_interrupt(int irq, void *dev_id) { struct mcs5000_ts_data *data = dev_id; struct i2c_client *client = data->client; u8 buffer[READ_BLOCK_SIZE]; int err; int x; int y; err = i2c_smbus_read_i2c_block_data(client, MCS5000_TS_INPUT_INFO, READ_BLOCK_SIZE, buffer); if (err < 0) { dev_err(&client->dev, "%s, err[%d]\n", __func__, err); goto out; } switch (buffer[READ_INPUT_INFO]) { case INPUT_TYPE_NONTOUCH: input_report_key(data->input_dev, BTN_TOUCH, 0); input_sync(data->input_dev); break; case INPUT_TYPE_SINGLE: x = (buffer[READ_X_POS_UPPER] << 8) | buffer[READ_X_POS_LOWER]; y = (buffer[READ_Y_POS_UPPER] << 8) | buffer[READ_Y_POS_LOWER]; input_report_key(data->input_dev, BTN_TOUCH, 1); input_report_abs(data->input_dev, ABS_X, x); input_report_abs(data->input_dev, ABS_Y, y); input_sync(data->input_dev); break; case INPUT_TYPE_DUAL: /* TODO */ break; case INPUT_TYPE_PALM: /* TODO */ break; case INPUT_TYPE_PROXIMITY: /* TODO */ break; default: dev_err(&client->dev, "Unknown ts input type %d\n", buffer[READ_INPUT_INFO]); break; } out: return IRQ_HANDLED; } static void mcs5000_ts_phys_init(struct mcs5000_ts_data *data, const struct mcs_platform_data *platform_data) { struct i2c_client *client = data->client; /* Touch reset & sleep mode */ i2c_smbus_write_byte_data(client, MCS5000_TS_OP_MODE, RESET_EXT_SOFT | OP_MODE_SLEEP); /* Touch size */ i2c_smbus_write_byte_data(client, MCS5000_TS_X_SIZE_UPPER, platform_data->x_size >> 8); i2c_smbus_write_byte_data(client, MCS5000_TS_X_SIZE_LOWER, platform_data->x_size & 0xff); i2c_smbus_write_byte_data(client, MCS5000_TS_Y_SIZE_UPPER, platform_data->y_size >> 8); i2c_smbus_write_byte_data(client, MCS5000_TS_Y_SIZE_LOWER, platform_data->y_size & 0xff); /* Touch active mode & 80 report rate */ i2c_smbus_write_byte_data(data->client, MCS5000_TS_OP_MODE, OP_MODE_ACTIVE | REPORT_RATE_80); } static int mcs5000_ts_probe(struct i2c_client *client) { const struct mcs_platform_data *pdata; struct mcs5000_ts_data *data; struct input_dev *input_dev; int error; pdata = dev_get_platdata(&client->dev); if (!pdata) return -EINVAL; data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (!data) { dev_err(&client->dev, "Failed to allocate memory\n"); return -ENOMEM; } data->client = client; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) { dev_err(&client->dev, "Failed to allocate input device\n"); return -ENOMEM; } input_dev->name = "MELFAS MCS-5000 Touchscreen"; input_dev->id.bustype = BUS_I2C; input_dev->dev.parent = &client->dev; __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); input_set_abs_params(input_dev, ABS_X, 0, MCS5000_MAX_XC, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MCS5000_MAX_YC, 0, 0); data->input_dev = input_dev; if (pdata->cfg_pin) pdata->cfg_pin(); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, mcs5000_ts_interrupt, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "mcs5000_ts", data); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = input_register_device(data->input_dev); if (error) { dev_err(&client->dev, "Failed to register input device\n"); return error; } mcs5000_ts_phys_init(data, pdata); i2c_set_clientdata(client, data); return 0; } static int mcs5000_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); /* Touch sleep mode */ i2c_smbus_write_byte_data(client, MCS5000_TS_OP_MODE, OP_MODE_SLEEP); return 0; } static int mcs5000_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mcs5000_ts_data *data = i2c_get_clientdata(client); const struct mcs_platform_data *pdata = dev_get_platdata(dev); mcs5000_ts_phys_init(data, pdata); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(mcs5000_ts_pm, mcs5000_ts_suspend, mcs5000_ts_resume); static const struct i2c_device_id mcs5000_ts_id[] = { { "mcs5000_ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mcs5000_ts_id); static struct i2c_driver mcs5000_ts_driver = { .probe = mcs5000_ts_probe, .driver = { .name = "mcs5000_ts", .pm = pm_sleep_ptr(&mcs5000_ts_pm), }, .id_table = mcs5000_ts_id, }; module_i2c_driver(mcs5000_ts_driver); /* Module information */ MODULE_AUTHOR("Joonyoung Shim <[email protected]>"); MODULE_DESCRIPTION("Touchscreen driver for MELFAS MCS-5000 controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/mcs5000_ts.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> /* Register Map */ #define ZINITIX_SWRESET_CMD 0x0000 #define ZINITIX_WAKEUP_CMD 0x0001 #define ZINITIX_IDLE_CMD 0x0004 #define ZINITIX_SLEEP_CMD 0x0005 #define ZINITIX_CLEAR_INT_STATUS_CMD 0x0003 #define ZINITIX_CALIBRATE_CMD 0x0006 #define ZINITIX_SAVE_STATUS_CMD 0x0007 #define ZINITIX_SAVE_CALIBRATION_CMD 0x0008 #define ZINITIX_RECALL_FACTORY_CMD 0x000f #define ZINITIX_THRESHOLD 0x0020 #define ZINITIX_LARGE_PALM_REJECT_AREA_TH 0x003F #define ZINITIX_DEBUG_REG 0x0115 /* 0~7 */ #define ZINITIX_TOUCH_MODE 0x0010 #define ZINITIX_CHIP_REVISION 0x0011 #define ZINITIX_FIRMWARE_VERSION 0x0012 #define ZINITIX_USB_DETECT 0x116 #define ZINITIX_MINOR_FW_VERSION 0x0121 #define ZINITIX_VENDOR_ID 0x001C #define ZINITIX_HW_ID 0x0014 #define ZINITIX_DATA_VERSION_REG 0x0013 #define ZINITIX_SUPPORTED_FINGER_NUM 0x0015 #define ZINITIX_EEPROM_INFO 0x0018 #define ZINITIX_INITIAL_TOUCH_MODE 0x0019 #define ZINITIX_TOTAL_NUMBER_OF_X 0x0060 #define ZINITIX_TOTAL_NUMBER_OF_Y 0x0061 #define ZINITIX_DELAY_RAW_FOR_HOST 0x007f #define ZINITIX_BUTTON_SUPPORTED_NUM 0x00B0 #define ZINITIX_BUTTON_SENSITIVITY 0x00B2 #define ZINITIX_DUMMY_BUTTON_SENSITIVITY 0X00C8 #define ZINITIX_X_RESOLUTION 0x00C0 #define ZINITIX_Y_RESOLUTION 0x00C1 #define ZINITIX_POINT_STATUS_REG 0x0080 #define ZINITIX_ICON_STATUS_REG 0x00AA #define ZINITIX_POINT_COORD_REG (ZINITIX_POINT_STATUS_REG + 2) #define ZINITIX_AFE_FREQUENCY 0x0100 #define ZINITIX_DND_N_COUNT 0x0122 #define ZINITIX_DND_U_COUNT 0x0135 #define ZINITIX_RAWDATA_REG 0x0200 #define ZINITIX_EEPROM_INFO_REG 0x0018 #define ZINITIX_INT_ENABLE_FLAG 0x00f0 #define ZINITIX_PERIODICAL_INTERRUPT_INTERVAL 0x00f1 #define ZINITIX_BTN_WIDTH 0x016d #define ZINITIX_CHECKSUM_RESULT 0x012c #define ZINITIX_INIT_FLASH 0x01d0 #define ZINITIX_WRITE_FLASH 0x01d1 #define ZINITIX_READ_FLASH 0x01d2 #define ZINITIX_INTERNAL_FLAG_02 0x011e #define ZINITIX_INTERNAL_FLAG_03 0x011f #define ZINITIX_I2C_CHECKSUM_WCNT 0x016a #define ZINITIX_I2C_CHECKSUM_RESULT 0x016c /* Interrupt & status register flags */ #define BIT_PT_CNT_CHANGE BIT(0) #define BIT_DOWN BIT(1) #define BIT_MOVE BIT(2) #define BIT_UP BIT(3) #define BIT_PALM BIT(4) #define BIT_PALM_REJECT BIT(5) #define BIT_RESERVED_0 BIT(6) #define BIT_RESERVED_1 BIT(7) #define BIT_WEIGHT_CHANGE BIT(8) #define BIT_PT_NO_CHANGE BIT(9) #define BIT_REJECT BIT(10) #define BIT_PT_EXIST BIT(11) #define BIT_RESERVED_2 BIT(12) #define BIT_ERROR BIT(13) #define BIT_DEBUG BIT(14) #define BIT_ICON_EVENT BIT(15) #define SUB_BIT_EXIST BIT(0) #define SUB_BIT_DOWN BIT(1) #define SUB_BIT_MOVE BIT(2) #define SUB_BIT_UP BIT(3) #define SUB_BIT_UPDATE BIT(4) #define SUB_BIT_WAIT BIT(5) #define DEFAULT_TOUCH_POINT_MODE 2 #define MAX_SUPPORTED_FINGER_NUM 5 #define CHIP_ON_DELAY 15 // ms #define FIRMWARE_ON_DELAY 40 // ms struct point_coord { __le16 x; __le16 y; u8 width; u8 sub_status; // currently unused, but needed as padding: u8 minor_width; u8 angle; }; struct touch_event { __le16 status; u8 finger_mask; u8 time_stamp; struct point_coord point_coord[MAX_SUPPORTED_FINGER_NUM]; }; struct bt541_ts_data { struct i2c_client *client; struct input_dev *input_dev; struct touchscreen_properties prop; struct regulator_bulk_data supplies[2]; u32 zinitix_mode; }; static int zinitix_read_data(struct i2c_client *client, u16 reg, void *values, size_t length) { __le16 reg_le = cpu_to_le16(reg); int ret; /* A single i2c_transfer() transaction does not work here. */ ret = i2c_master_send(client, (u8 *)&reg_le, sizeof(reg_le)); if (ret != sizeof(reg_le)) return ret < 0 ? ret : -EIO; ret = i2c_master_recv(client, (u8 *)values, length); if (ret != length) return ret < 0 ? ret : -EIO; return 0; } static int zinitix_write_u16(struct i2c_client *client, u16 reg, u16 value) { __le16 packet[2] = {cpu_to_le16(reg), cpu_to_le16(value)}; int ret; ret = i2c_master_send(client, (u8 *)packet, sizeof(packet)); if (ret != sizeof(packet)) return ret < 0 ? ret : -EIO; return 0; } static int zinitix_write_cmd(struct i2c_client *client, u16 reg) { __le16 reg_le = cpu_to_le16(reg); int ret; ret = i2c_master_send(client, (u8 *)&reg_le, sizeof(reg_le)); if (ret != sizeof(reg_le)) return ret < 0 ? ret : -EIO; return 0; } static int zinitix_init_touch(struct bt541_ts_data *bt541) { struct i2c_client *client = bt541->client; int i; int error; error = zinitix_write_cmd(client, ZINITIX_SWRESET_CMD); if (error) { dev_err(&client->dev, "Failed to write reset command\n"); return error; } error = zinitix_write_u16(client, ZINITIX_INT_ENABLE_FLAG, 0x0); if (error) { dev_err(&client->dev, "Failed to reset interrupt enable flag\n"); return error; } /* initialize */ error = zinitix_write_u16(client, ZINITIX_X_RESOLUTION, bt541->prop.max_x); if (error) return error; error = zinitix_write_u16(client, ZINITIX_Y_RESOLUTION, bt541->prop.max_y); if (error) return error; error = zinitix_write_u16(client, ZINITIX_SUPPORTED_FINGER_NUM, MAX_SUPPORTED_FINGER_NUM); if (error) return error; error = zinitix_write_u16(client, ZINITIX_INITIAL_TOUCH_MODE, bt541->zinitix_mode); if (error) return error; error = zinitix_write_u16(client, ZINITIX_TOUCH_MODE, bt541->zinitix_mode); if (error) return error; error = zinitix_write_u16(client, ZINITIX_INT_ENABLE_FLAG, BIT_PT_CNT_CHANGE | BIT_DOWN | BIT_MOVE | BIT_UP); if (error) return error; /* clear queue */ for (i = 0; i < 10; i++) { zinitix_write_cmd(client, ZINITIX_CLEAR_INT_STATUS_CMD); udelay(10); } return 0; } static int zinitix_init_regulators(struct bt541_ts_data *bt541) { struct device *dev = &bt541->client->dev; int error; /* * Some older device trees have erroneous names for the regulators, * so check if "vddo" is present and in that case use these names. * Else use the proper supply names on the component. */ if (of_property_present(dev->of_node, "vddo-supply")) { bt541->supplies[0].supply = "vdd"; bt541->supplies[1].supply = "vddo"; } else { /* Else use the proper supply names */ bt541->supplies[0].supply = "vcca"; bt541->supplies[1].supply = "vdd"; } error = devm_regulator_bulk_get(dev, ARRAY_SIZE(bt541->supplies), bt541->supplies); if (error < 0) { dev_err(dev, "Failed to get regulators: %d\n", error); return error; } return 0; } static int zinitix_send_power_on_sequence(struct bt541_ts_data *bt541) { int error; struct i2c_client *client = bt541->client; error = zinitix_write_u16(client, 0xc000, 0x0001); if (error) { dev_err(&client->dev, "Failed to send power sequence(vendor cmd enable)\n"); return error; } udelay(10); error = zinitix_write_cmd(client, 0xc004); if (error) { dev_err(&client->dev, "Failed to send power sequence (intn clear)\n"); return error; } udelay(10); error = zinitix_write_u16(client, 0xc002, 0x0001); if (error) { dev_err(&client->dev, "Failed to send power sequence (nvm init)\n"); return error; } mdelay(2); error = zinitix_write_u16(client, 0xc001, 0x0001); if (error) { dev_err(&client->dev, "Failed to send power sequence (program start)\n"); return error; } msleep(FIRMWARE_ON_DELAY); return 0; } static void zinitix_report_finger(struct bt541_ts_data *bt541, int slot, const struct point_coord *p) { u16 x, y; if (unlikely(!(p->sub_status & (SUB_BIT_UP | SUB_BIT_DOWN | SUB_BIT_MOVE)))) { dev_dbg(&bt541->client->dev, "unknown finger event %#02x\n", p->sub_status); return; } x = le16_to_cpu(p->x); y = le16_to_cpu(p->y); input_mt_slot(bt541->input_dev, slot); if (input_mt_report_slot_state(bt541->input_dev, MT_TOOL_FINGER, !(p->sub_status & SUB_BIT_UP))) { touchscreen_report_pos(bt541->input_dev, &bt541->prop, x, y, true); input_report_abs(bt541->input_dev, ABS_MT_TOUCH_MAJOR, p->width); dev_dbg(&bt541->client->dev, "finger %d %s (%u, %u)\n", slot, p->sub_status & SUB_BIT_DOWN ? "down" : "move", x, y); } else { dev_dbg(&bt541->client->dev, "finger %d up (%u, %u)\n", slot, x, y); } } static irqreturn_t zinitix_ts_irq_handler(int irq, void *bt541_handler) { struct bt541_ts_data *bt541 = bt541_handler; struct i2c_client *client = bt541->client; struct touch_event touch_event; unsigned long finger_mask; int error; int i; memset(&touch_event, 0, sizeof(struct touch_event)); error = zinitix_read_data(bt541->client, ZINITIX_POINT_STATUS_REG, &touch_event, sizeof(struct touch_event)); if (error) { dev_err(&client->dev, "Failed to read in touchpoint struct\n"); goto out; } finger_mask = touch_event.finger_mask; for_each_set_bit(i, &finger_mask, MAX_SUPPORTED_FINGER_NUM) { const struct point_coord *p = &touch_event.point_coord[i]; /* Only process contacts that are actually reported */ if (p->sub_status & SUB_BIT_EXIST) zinitix_report_finger(bt541, i, p); } input_mt_sync_frame(bt541->input_dev); input_sync(bt541->input_dev); out: zinitix_write_cmd(bt541->client, ZINITIX_CLEAR_INT_STATUS_CMD); return IRQ_HANDLED; } static int zinitix_start(struct bt541_ts_data *bt541) { int error; error = regulator_bulk_enable(ARRAY_SIZE(bt541->supplies), bt541->supplies); if (error) { dev_err(&bt541->client->dev, "Failed to enable regulators: %d\n", error); return error; } msleep(CHIP_ON_DELAY); error = zinitix_send_power_on_sequence(bt541); if (error) { dev_err(&bt541->client->dev, "Error while sending power-on sequence: %d\n", error); return error; } error = zinitix_init_touch(bt541); if (error) { dev_err(&bt541->client->dev, "Error while configuring touch IC\n"); return error; } enable_irq(bt541->client->irq); return 0; } static int zinitix_stop(struct bt541_ts_data *bt541) { int error; disable_irq(bt541->client->irq); error = regulator_bulk_disable(ARRAY_SIZE(bt541->supplies), bt541->supplies); if (error) { dev_err(&bt541->client->dev, "Failed to disable regulators: %d\n", error); return error; } return 0; } static int zinitix_input_open(struct input_dev *dev) { struct bt541_ts_data *bt541 = input_get_drvdata(dev); return zinitix_start(bt541); } static void zinitix_input_close(struct input_dev *dev) { struct bt541_ts_data *bt541 = input_get_drvdata(dev); zinitix_stop(bt541); } static int zinitix_init_input_dev(struct bt541_ts_data *bt541) { struct input_dev *input_dev; int error; input_dev = devm_input_allocate_device(&bt541->client->dev); if (!input_dev) { dev_err(&bt541->client->dev, "Failed to allocate input device."); return -ENOMEM; } input_set_drvdata(input_dev, bt541); bt541->input_dev = input_dev; input_dev->name = "Zinitix Capacitive TouchScreen"; input_dev->phys = "input/ts"; input_dev->id.bustype = BUS_I2C; input_dev->open = zinitix_input_open; input_dev->close = zinitix_input_close; input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_Y); input_set_abs_params(input_dev, ABS_MT_WIDTH_MAJOR, 0, 255, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); touchscreen_parse_properties(input_dev, true, &bt541->prop); if (!bt541->prop.max_x || !bt541->prop.max_y) { dev_err(&bt541->client->dev, "Touchscreen-size-x and/or touchscreen-size-y not set in dts\n"); return -EINVAL; } error = input_mt_init_slots(input_dev, MAX_SUPPORTED_FINGER_NUM, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&bt541->client->dev, "Failed to initialize MT slots: %d", error); return error; } error = input_register_device(input_dev); if (error) { dev_err(&bt541->client->dev, "Failed to register input device: %d", error); return error; } return 0; } static int zinitix_ts_probe(struct i2c_client *client) { struct bt541_ts_data *bt541; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "Failed to assert adapter's support for plain I2C.\n"); return -ENXIO; } bt541 = devm_kzalloc(&client->dev, sizeof(*bt541), GFP_KERNEL); if (!bt541) return -ENOMEM; bt541->client = client; i2c_set_clientdata(client, bt541); error = zinitix_init_regulators(bt541); if (error) { dev_err(&client->dev, "Failed to initialize regulators: %d\n", error); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, zinitix_ts_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, client->name, bt541); if (error) { dev_err(&client->dev, "Failed to request IRQ: %d\n", error); return error; } error = zinitix_init_input_dev(bt541); if (error) { dev_err(&client->dev, "Failed to initialize input device: %d\n", error); return error; } error = device_property_read_u32(&client->dev, "zinitix,mode", &bt541->zinitix_mode); if (error < 0) { /* fall back to mode 2 */ bt541->zinitix_mode = DEFAULT_TOUCH_POINT_MODE; } if (bt541->zinitix_mode != 2) { /* * If there are devices that don't support mode 2, support * for other modes (0, 1) will be needed. */ dev_err(&client->dev, "Malformed zinitix,mode property, must be 2 (supplied: %d)\n", bt541->zinitix_mode); return -EINVAL; } return 0; } static int zinitix_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct bt541_ts_data *bt541 = i2c_get_clientdata(client); mutex_lock(&bt541->input_dev->mutex); if (input_device_enabled(bt541->input_dev)) zinitix_stop(bt541); mutex_unlock(&bt541->input_dev->mutex); return 0; } static int zinitix_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct bt541_ts_data *bt541 = i2c_get_clientdata(client); int ret = 0; mutex_lock(&bt541->input_dev->mutex); if (input_device_enabled(bt541->input_dev)) ret = zinitix_start(bt541); mutex_unlock(&bt541->input_dev->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(zinitix_pm_ops, zinitix_suspend, zinitix_resume); #ifdef CONFIG_OF static const struct of_device_id zinitix_of_match[] = { { .compatible = "zinitix,bt402" }, { .compatible = "zinitix,bt403" }, { .compatible = "zinitix,bt404" }, { .compatible = "zinitix,bt412" }, { .compatible = "zinitix,bt413" }, { .compatible = "zinitix,bt431" }, { .compatible = "zinitix,bt432" }, { .compatible = "zinitix,bt531" }, { .compatible = "zinitix,bt532" }, { .compatible = "zinitix,bt538" }, { .compatible = "zinitix,bt541" }, { .compatible = "zinitix,bt548" }, { .compatible = "zinitix,bt554" }, { .compatible = "zinitix,at100" }, { } }; MODULE_DEVICE_TABLE(of, zinitix_of_match); #endif static struct i2c_driver zinitix_ts_driver = { .probe = zinitix_ts_probe, .driver = { .name = "Zinitix-TS", .pm = pm_sleep_ptr(&zinitix_pm_ops), .of_match_table = of_match_ptr(zinitix_of_match), }, }; module_i2c_driver(zinitix_ts_driver); MODULE_AUTHOR("Michael Srba <[email protected]>"); MODULE_DESCRIPTION("Zinitix touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/zinitix.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for MAXI MAX11801 - A Resistive touch screen controller with * i2c interface * * Copyright (C) 2011 Freescale Semiconductor, Inc. * Author: Zhang Jiejing <[email protected]> * * Based on mcs5000_ts.c */ /* * This driver aims to support the series of MAXI touch chips max11801 * through max11803. The main difference between these 4 chips can be * found in the table below: * ----------------------------------------------------- * | CHIP | AUTO MODE SUPPORT(FIFO) | INTERFACE | * |----------------------------------------------------| * | max11800 | YES | SPI | * | max11801 | YES | I2C | * | max11802 | NO | SPI | * | max11803 | NO | I2C | * ------------------------------------------------------ * * Currently, this driver only supports max11801. * * Data Sheet: * http://www.maxim-ic.com/datasheet/index.mvp/id/5943 */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/slab.h> #include <linux/bitops.h> /* Register Address define */ #define GENERNAL_STATUS_REG 0x00 #define GENERNAL_CONF_REG 0x01 #define MESURE_RES_CONF_REG 0x02 #define MESURE_AVER_CONF_REG 0x03 #define ADC_SAMPLE_TIME_CONF_REG 0x04 #define PANEL_SETUPTIME_CONF_REG 0x05 #define DELAY_CONVERSION_CONF_REG 0x06 #define TOUCH_DETECT_PULLUP_CONF_REG 0x07 #define AUTO_MODE_TIME_CONF_REG 0x08 /* only for max11800/max11801 */ #define APERTURE_CONF_REG 0x09 /* only for max11800/max11801 */ #define AUX_MESURE_CONF_REG 0x0a #define OP_MODE_CONF_REG 0x0b /* FIFO is found only in max11800 and max11801 */ #define FIFO_RD_CMD (0x50 << 1) #define MAX11801_FIFO_INT (1 << 2) #define MAX11801_FIFO_OVERFLOW (1 << 3) #define XY_BUFSIZE 4 #define XY_BUF_OFFSET 4 #define MAX11801_MAX_X 0xfff #define MAX11801_MAX_Y 0xfff #define MEASURE_TAG_OFFSET 2 #define MEASURE_TAG_MASK (3 << MEASURE_TAG_OFFSET) #define EVENT_TAG_OFFSET 0 #define EVENT_TAG_MASK (3 << EVENT_TAG_OFFSET) #define MEASURE_X_TAG (0 << MEASURE_TAG_OFFSET) #define MEASURE_Y_TAG (1 << MEASURE_TAG_OFFSET) /* These are the state of touch event state machine */ enum { EVENT_INIT, EVENT_MIDDLE, EVENT_RELEASE, EVENT_FIFO_END }; struct max11801_data { struct i2c_client *client; struct input_dev *input_dev; }; static u8 read_register(struct i2c_client *client, int addr) { /* XXX: The chip ignores LSB of register address */ return i2c_smbus_read_byte_data(client, addr << 1); } static int max11801_write_reg(struct i2c_client *client, int addr, int data) { /* XXX: The chip ignores LSB of register address */ return i2c_smbus_write_byte_data(client, addr << 1, data); } static irqreturn_t max11801_ts_interrupt(int irq, void *dev_id) { struct max11801_data *data = dev_id; struct i2c_client *client = data->client; int status, i, ret; u8 buf[XY_BUFSIZE]; int x = -1; int y = -1; status = read_register(data->client, GENERNAL_STATUS_REG); if (status & (MAX11801_FIFO_INT | MAX11801_FIFO_OVERFLOW)) { status = read_register(data->client, GENERNAL_STATUS_REG); ret = i2c_smbus_read_i2c_block_data(client, FIFO_RD_CMD, XY_BUFSIZE, buf); /* * We should get 4 bytes buffer that contains X,Y * and event tag */ if (ret < XY_BUFSIZE) goto out; for (i = 0; i < XY_BUFSIZE; i += XY_BUFSIZE / 2) { if ((buf[i + 1] & MEASURE_TAG_MASK) == MEASURE_X_TAG) x = (buf[i] << XY_BUF_OFFSET) + (buf[i + 1] >> XY_BUF_OFFSET); else if ((buf[i + 1] & MEASURE_TAG_MASK) == MEASURE_Y_TAG) y = (buf[i] << XY_BUF_OFFSET) + (buf[i + 1] >> XY_BUF_OFFSET); } if ((buf[1] & EVENT_TAG_MASK) != (buf[3] & EVENT_TAG_MASK)) goto out; switch (buf[1] & EVENT_TAG_MASK) { case EVENT_INIT: case EVENT_MIDDLE: input_report_abs(data->input_dev, ABS_X, x); input_report_abs(data->input_dev, ABS_Y, y); input_event(data->input_dev, EV_KEY, BTN_TOUCH, 1); input_sync(data->input_dev); break; case EVENT_RELEASE: input_event(data->input_dev, EV_KEY, BTN_TOUCH, 0); input_sync(data->input_dev); break; case EVENT_FIFO_END: break; } } out: return IRQ_HANDLED; } static void max11801_ts_phy_init(struct max11801_data *data) { struct i2c_client *client = data->client; /* Average X,Y, take 16 samples, average eight media sample */ max11801_write_reg(client, MESURE_AVER_CONF_REG, 0xff); /* X,Y panel setup time set to 20us */ max11801_write_reg(client, PANEL_SETUPTIME_CONF_REG, 0x11); /* Rough pullup time (2uS), Fine pullup time (10us) */ max11801_write_reg(client, TOUCH_DETECT_PULLUP_CONF_REG, 0x10); /* Auto mode init period = 5ms , scan period = 5ms*/ max11801_write_reg(client, AUTO_MODE_TIME_CONF_REG, 0xaa); /* Aperture X,Y set to +- 4LSB */ max11801_write_reg(client, APERTURE_CONF_REG, 0x33); /* Enable Power, enable Automode, enable Aperture, enable Average X,Y */ max11801_write_reg(client, OP_MODE_CONF_REG, 0x36); } static int max11801_ts_probe(struct i2c_client *client) { struct max11801_data *data; struct input_dev *input_dev; int error; data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); input_dev = devm_input_allocate_device(&client->dev); if (!data || !input_dev) { dev_err(&client->dev, "Failed to allocate memory\n"); return -ENOMEM; } data->client = client; data->input_dev = input_dev; input_dev->name = "max11801_ts"; input_dev->id.bustype = BUS_I2C; input_dev->dev.parent = &client->dev; __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); input_set_abs_params(input_dev, ABS_X, 0, MAX11801_MAX_X, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX11801_MAX_Y, 0, 0); max11801_ts_phy_init(data); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, max11801_ts_interrupt, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "max11801_ts", data); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = input_register_device(data->input_dev); if (error) return error; return 0; } static const struct i2c_device_id max11801_ts_id[] = { {"max11801", 0}, { } }; MODULE_DEVICE_TABLE(i2c, max11801_ts_id); static const struct of_device_id max11801_ts_dt_ids[] = { { .compatible = "maxim,max11801" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, max11801_ts_dt_ids); static struct i2c_driver max11801_ts_driver = { .driver = { .name = "max11801_ts", .of_match_table = max11801_ts_dt_ids, }, .id_table = max11801_ts_id, .probe = max11801_ts_probe, }; module_i2c_driver(max11801_ts_driver); MODULE_AUTHOR("Zhang Jiejing <[email protected]>"); MODULE_DESCRIPTION("Touchscreen driver for MAXI MAX11801 controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/max11801_ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* ------------------------------------------------------------------------- * Copyright (C) 2014-2015, Intel Corporation * * Derived from: * gslX68X.c * Copyright (C) 2010-2015, Shanghai Sileadinc Co.Ltd * * ------------------------------------------------------------------------- */ #include <linux/i2c.h> #include <linux/module.h> #include <linux/acpi.h> #include <linux/interrupt.h> #include <linux/gpio/consumer.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/irq.h> #include <linux/regulator/consumer.h> #include <asm/unaligned.h> #define SILEAD_TS_NAME "silead_ts" #define SILEAD_REG_RESET 0xE0 #define SILEAD_REG_DATA 0x80 #define SILEAD_REG_TOUCH_NR 0x80 #define SILEAD_REG_POWER 0xBC #define SILEAD_REG_CLOCK 0xE4 #define SILEAD_REG_STATUS 0xB0 #define SILEAD_REG_ID 0xFC #define SILEAD_REG_MEM_CHECK 0xB0 #define SILEAD_STATUS_OK 0x5A5A5A5A #define SILEAD_TS_DATA_LEN 44 #define SILEAD_CLOCK 0x04 #define SILEAD_CMD_RESET 0x88 #define SILEAD_CMD_START 0x00 #define SILEAD_POINT_DATA_LEN 0x04 #define SILEAD_POINT_Y_OFF 0x00 #define SILEAD_POINT_Y_MSB_OFF 0x01 #define SILEAD_POINT_X_OFF 0x02 #define SILEAD_POINT_X_MSB_OFF 0x03 #define SILEAD_EXTRA_DATA_MASK 0xF0 #define SILEAD_CMD_SLEEP_MIN 10000 #define SILEAD_CMD_SLEEP_MAX 20000 #define SILEAD_POWER_SLEEP 20 #define SILEAD_STARTUP_SLEEP 30 #define SILEAD_MAX_FINGERS 10 enum silead_ts_power { SILEAD_POWER_ON = 1, SILEAD_POWER_OFF = 0 }; struct silead_ts_data { struct i2c_client *client; struct gpio_desc *gpio_power; struct input_dev *input; struct input_dev *pen_input; struct regulator_bulk_data regulators[2]; char fw_name[64]; struct touchscreen_properties prop; u32 max_fingers; u32 chip_id; struct input_mt_pos pos[SILEAD_MAX_FINGERS]; int slots[SILEAD_MAX_FINGERS]; int id[SILEAD_MAX_FINGERS]; u32 efi_fw_min_max[4]; bool efi_fw_min_max_set; bool pen_supported; bool pen_down; u32 pen_x_res; u32 pen_y_res; int pen_up_count; }; struct silead_fw_data { u32 offset; u32 val; }; static void silead_apply_efi_fw_min_max(struct silead_ts_data *data) { struct input_absinfo *absinfo_x = &data->input->absinfo[ABS_MT_POSITION_X]; struct input_absinfo *absinfo_y = &data->input->absinfo[ABS_MT_POSITION_Y]; if (!data->efi_fw_min_max_set) return; absinfo_x->minimum = data->efi_fw_min_max[0]; absinfo_x->maximum = data->efi_fw_min_max[1]; absinfo_y->minimum = data->efi_fw_min_max[2]; absinfo_y->maximum = data->efi_fw_min_max[3]; if (data->prop.invert_x) { absinfo_x->maximum -= absinfo_x->minimum; absinfo_x->minimum = 0; } if (data->prop.invert_y) { absinfo_y->maximum -= absinfo_y->minimum; absinfo_y->minimum = 0; } if (data->prop.swap_x_y) { swap(absinfo_x->minimum, absinfo_y->minimum); swap(absinfo_x->maximum, absinfo_y->maximum); } } static int silead_ts_request_input_dev(struct silead_ts_data *data) { struct device *dev = &data->client->dev; int error; data->input = devm_input_allocate_device(dev); if (!data->input) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } input_set_abs_params(data->input, ABS_MT_POSITION_X, 0, 4095, 0, 0); input_set_abs_params(data->input, ABS_MT_POSITION_Y, 0, 4095, 0, 0); touchscreen_parse_properties(data->input, true, &data->prop); silead_apply_efi_fw_min_max(data); input_mt_init_slots(data->input, data->max_fingers, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED | INPUT_MT_TRACK); if (device_property_read_bool(dev, "silead,home-button")) input_set_capability(data->input, EV_KEY, KEY_LEFTMETA); data->input->name = SILEAD_TS_NAME; data->input->phys = "input/ts"; data->input->id.bustype = BUS_I2C; error = input_register_device(data->input); if (error) { dev_err(dev, "Failed to register input device: %d\n", error); return error; } return 0; } static int silead_ts_request_pen_input_dev(struct silead_ts_data *data) { struct device *dev = &data->client->dev; int error; if (!data->pen_supported) return 0; data->pen_input = devm_input_allocate_device(dev); if (!data->pen_input) return -ENOMEM; input_set_abs_params(data->pen_input, ABS_X, 0, 4095, 0, 0); input_set_abs_params(data->pen_input, ABS_Y, 0, 4095, 0, 0); input_set_capability(data->pen_input, EV_KEY, BTN_TOUCH); input_set_capability(data->pen_input, EV_KEY, BTN_TOOL_PEN); set_bit(INPUT_PROP_DIRECT, data->pen_input->propbit); touchscreen_parse_properties(data->pen_input, false, &data->prop); input_abs_set_res(data->pen_input, ABS_X, data->pen_x_res); input_abs_set_res(data->pen_input, ABS_Y, data->pen_y_res); data->pen_input->name = SILEAD_TS_NAME " pen"; data->pen_input->phys = "input/pen"; data->input->id.bustype = BUS_I2C; error = input_register_device(data->pen_input); if (error) { dev_err(dev, "Failed to register pen input device: %d\n", error); return error; } return 0; } static void silead_ts_set_power(struct i2c_client *client, enum silead_ts_power state) { struct silead_ts_data *data = i2c_get_clientdata(client); if (data->gpio_power) { gpiod_set_value_cansleep(data->gpio_power, state); msleep(SILEAD_POWER_SLEEP); } } static bool silead_ts_handle_pen_data(struct silead_ts_data *data, u8 *buf) { u8 *coord = buf + SILEAD_POINT_DATA_LEN; struct input_mt_pos pos; if (!data->pen_supported || buf[2] != 0x00 || buf[3] != 0x00) return false; if (buf[0] == 0x00 && buf[1] == 0x00 && data->pen_down) { data->pen_up_count++; if (data->pen_up_count == 6) { data->pen_down = false; goto sync; } return true; } if (buf[0] == 0x01 && buf[1] == 0x08) { touchscreen_set_mt_pos(&pos, &data->prop, get_unaligned_le16(&coord[SILEAD_POINT_X_OFF]) & 0xfff, get_unaligned_le16(&coord[SILEAD_POINT_Y_OFF]) & 0xfff); input_report_abs(data->pen_input, ABS_X, pos.x); input_report_abs(data->pen_input, ABS_Y, pos.y); data->pen_up_count = 0; data->pen_down = true; goto sync; } return false; sync: input_report_key(data->pen_input, BTN_TOOL_PEN, data->pen_down); input_report_key(data->pen_input, BTN_TOUCH, data->pen_down); input_sync(data->pen_input); return true; } static void silead_ts_read_data(struct i2c_client *client) { struct silead_ts_data *data = i2c_get_clientdata(client); struct input_dev *input = data->input; struct device *dev = &client->dev; u8 *bufp, buf[SILEAD_TS_DATA_LEN]; int touch_nr, softbutton, error, i; bool softbutton_pressed = false; error = i2c_smbus_read_i2c_block_data(client, SILEAD_REG_DATA, SILEAD_TS_DATA_LEN, buf); if (error < 0) { dev_err(dev, "Data read error %d\n", error); return; } if (buf[0] > data->max_fingers) { dev_warn(dev, "More touches reported then supported %d > %d\n", buf[0], data->max_fingers); buf[0] = data->max_fingers; } if (silead_ts_handle_pen_data(data, buf)) goto sync; /* Pen is down, release all previous touches */ touch_nr = 0; bufp = buf + SILEAD_POINT_DATA_LEN; for (i = 0; i < buf[0]; i++, bufp += SILEAD_POINT_DATA_LEN) { softbutton = (bufp[SILEAD_POINT_Y_MSB_OFF] & SILEAD_EXTRA_DATA_MASK) >> 4; if (softbutton) { /* * For now only respond to softbutton == 0x01, some * tablets *without* a capacative button send 0x04 * when crossing the edges of the screen. */ if (softbutton == 0x01) softbutton_pressed = true; continue; } /* * Bits 4-7 are the touch id, note not all models have * hardware touch ids so atm we don't use these. */ data->id[touch_nr] = (bufp[SILEAD_POINT_X_MSB_OFF] & SILEAD_EXTRA_DATA_MASK) >> 4; touchscreen_set_mt_pos(&data->pos[touch_nr], &data->prop, get_unaligned_le16(&bufp[SILEAD_POINT_X_OFF]) & 0xfff, get_unaligned_le16(&bufp[SILEAD_POINT_Y_OFF]) & 0xfff); touch_nr++; } input_mt_assign_slots(input, data->slots, data->pos, touch_nr, 0); for (i = 0; i < touch_nr; i++) { input_mt_slot(input, data->slots[i]); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); input_report_abs(input, ABS_MT_POSITION_X, data->pos[i].x); input_report_abs(input, ABS_MT_POSITION_Y, data->pos[i].y); dev_dbg(dev, "x=%d y=%d hw_id=%d sw_id=%d\n", data->pos[i].x, data->pos[i].y, data->id[i], data->slots[i]); } sync: input_mt_sync_frame(input); input_report_key(input, KEY_LEFTMETA, softbutton_pressed); input_sync(input); } static int silead_ts_init(struct i2c_client *client) { struct silead_ts_data *data = i2c_get_clientdata(client); int error; error = i2c_smbus_write_byte_data(client, SILEAD_REG_RESET, SILEAD_CMD_RESET); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); error = i2c_smbus_write_byte_data(client, SILEAD_REG_TOUCH_NR, data->max_fingers); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); error = i2c_smbus_write_byte_data(client, SILEAD_REG_CLOCK, SILEAD_CLOCK); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); error = i2c_smbus_write_byte_data(client, SILEAD_REG_RESET, SILEAD_CMD_START); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); return 0; i2c_write_err: dev_err(&client->dev, "Registers clear error %d\n", error); return error; } static int silead_ts_reset(struct i2c_client *client) { int error; error = i2c_smbus_write_byte_data(client, SILEAD_REG_RESET, SILEAD_CMD_RESET); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); error = i2c_smbus_write_byte_data(client, SILEAD_REG_CLOCK, SILEAD_CLOCK); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); error = i2c_smbus_write_byte_data(client, SILEAD_REG_POWER, SILEAD_CMD_START); if (error) goto i2c_write_err; usleep_range(SILEAD_CMD_SLEEP_MIN, SILEAD_CMD_SLEEP_MAX); return 0; i2c_write_err: dev_err(&client->dev, "Chip reset error %d\n", error); return error; } static int silead_ts_startup(struct i2c_client *client) { int error; error = i2c_smbus_write_byte_data(client, SILEAD_REG_RESET, 0x00); if (error) { dev_err(&client->dev, "Startup error %d\n", error); return error; } msleep(SILEAD_STARTUP_SLEEP); return 0; } static int silead_ts_load_fw(struct i2c_client *client) { struct device *dev = &client->dev; struct silead_ts_data *data = i2c_get_clientdata(client); const struct firmware *fw = NULL; struct silead_fw_data *fw_data; unsigned int fw_size, i; int error; dev_dbg(dev, "Firmware file name: %s", data->fw_name); /* * Unfortunately, at the time of writing this comment, we have been unable to * get permission from Silead, or from device OEMs, to distribute the necessary * Silead firmware files in linux-firmware. * * On a whole bunch of devices the UEFI BIOS code contains a touchscreen driver, * which contains an embedded copy of the firmware. The fw-loader code has a * "platform" fallback mechanism, which together with info on the firmware * from drivers/platform/x86/touchscreen_dmi.c will use the firmware from the * UEFI driver when the firmware is missing from /lib/firmware. This makes the * touchscreen work OOTB without users needing to manually download the firmware. * * The firmware bundled with the original Windows/Android is usually newer then * the firmware in the UEFI driver and it is better calibrated. This better * calibration can lead to significant differences in the reported min/max * coordinates. * * To deal with this we first try to load the firmware without "platform" * fallback. If that fails we retry with "platform" fallback and if that * succeeds we apply an (optional) set of alternative min/max values from the * "silead,efi-fw-min-max" property. */ error = firmware_request_nowarn(&fw, data->fw_name, dev); if (error) { error = firmware_request_platform(&fw, data->fw_name, dev); if (error) { dev_err(dev, "Firmware request error %d\n", error); return error; } error = device_property_read_u32_array(dev, "silead,efi-fw-min-max", data->efi_fw_min_max, ARRAY_SIZE(data->efi_fw_min_max)); if (!error) data->efi_fw_min_max_set = true; /* The EFI (platform) embedded fw does not have pen support */ if (data->pen_supported) { dev_warn(dev, "Warning loading '%s' from filesystem failed, using EFI embedded copy.\n", data->fw_name); dev_warn(dev, "Warning pen support is known to be broken in the EFI embedded fw version\n"); data->pen_supported = false; } } fw_size = fw->size / sizeof(*fw_data); fw_data = (struct silead_fw_data *)fw->data; for (i = 0; i < fw_size; i++) { error = i2c_smbus_write_i2c_block_data(client, fw_data[i].offset, 4, (u8 *)&fw_data[i].val); if (error) { dev_err(dev, "Firmware load error %d\n", error); break; } } release_firmware(fw); return error ?: 0; } static u32 silead_ts_get_status(struct i2c_client *client) { int error; __le32 status; error = i2c_smbus_read_i2c_block_data(client, SILEAD_REG_STATUS, sizeof(status), (u8 *)&status); if (error < 0) { dev_err(&client->dev, "Status read error %d\n", error); return error; } return le32_to_cpu(status); } static int silead_ts_get_id(struct i2c_client *client) { struct silead_ts_data *data = i2c_get_clientdata(client); __le32 chip_id; int error; error = i2c_smbus_read_i2c_block_data(client, SILEAD_REG_ID, sizeof(chip_id), (u8 *)&chip_id); if (error < 0) return error; data->chip_id = le32_to_cpu(chip_id); dev_info(&client->dev, "Silead chip ID: 0x%8X", data->chip_id); return 0; } static int silead_ts_setup(struct i2c_client *client) { int error; u32 status; /* * Some buggy BIOS-es bring up the chip in a stuck state where it * blocks the I2C bus. The following steps are necessary to * unstuck the chip / bus: * 1. Turn off the Silead chip. * 2. Try to do an I2C transfer with the chip, this will fail in * response to which the I2C-bus-driver will call: * i2c_recover_bus() which will unstuck the I2C-bus. Note the * unstuck-ing of the I2C bus only works if we first drop the * chip off the bus by turning it off. * 3. Turn the chip back on. * * On the x86/ACPI systems were this problem is seen, step 1. and * 3. require making ACPI calls and dealing with ACPI Power * Resources. The workaround below runtime-suspends the chip to * turn it off, leaving it up to the ACPI subsystem to deal with * this. */ if (device_property_read_bool(&client->dev, "silead,stuck-controller-bug")) { pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_allow(&client->dev); pm_runtime_suspend(&client->dev); dev_warn(&client->dev, FW_BUG "Stuck I2C bus: please ignore the next 'controller timed out' error\n"); silead_ts_get_id(client); /* The forbid will also resume the device */ pm_runtime_forbid(&client->dev); pm_runtime_disable(&client->dev); } silead_ts_set_power(client, SILEAD_POWER_OFF); silead_ts_set_power(client, SILEAD_POWER_ON); error = silead_ts_get_id(client); if (error) { dev_err(&client->dev, "Chip ID read error %d\n", error); return error; } error = silead_ts_init(client); if (error) return error; error = silead_ts_reset(client); if (error) return error; error = silead_ts_load_fw(client); if (error) return error; error = silead_ts_startup(client); if (error) return error; status = silead_ts_get_status(client); if (status != SILEAD_STATUS_OK) { dev_err(&client->dev, "Initialization error, status: 0x%X\n", status); return -ENODEV; } return 0; } static irqreturn_t silead_ts_threaded_irq_handler(int irq, void *id) { struct silead_ts_data *data = id; struct i2c_client *client = data->client; silead_ts_read_data(client); return IRQ_HANDLED; } static void silead_ts_read_props(struct i2c_client *client) { struct silead_ts_data *data = i2c_get_clientdata(client); struct device *dev = &client->dev; const char *str; int error; error = device_property_read_u32(dev, "silead,max-fingers", &data->max_fingers); if (error) { dev_dbg(dev, "Max fingers read error %d\n", error); data->max_fingers = 5; /* Most devices handle up-to 5 fingers */ } error = device_property_read_string(dev, "firmware-name", &str); if (!error) snprintf(data->fw_name, sizeof(data->fw_name), "silead/%s", str); else dev_dbg(dev, "Firmware file name read error. Using default."); data->pen_supported = device_property_read_bool(dev, "silead,pen-supported"); device_property_read_u32(dev, "silead,pen-resolution-x", &data->pen_x_res); device_property_read_u32(dev, "silead,pen-resolution-y", &data->pen_y_res); } #ifdef CONFIG_ACPI static int silead_ts_set_default_fw_name(struct silead_ts_data *data, const struct i2c_device_id *id) { const struct acpi_device_id *acpi_id; struct device *dev = &data->client->dev; int i; if (ACPI_HANDLE(dev)) { acpi_id = acpi_match_device(dev->driver->acpi_match_table, dev); if (!acpi_id) return -ENODEV; snprintf(data->fw_name, sizeof(data->fw_name), "silead/%s.fw", acpi_id->id); for (i = 0; i < strlen(data->fw_name); i++) data->fw_name[i] = tolower(data->fw_name[i]); } else { snprintf(data->fw_name, sizeof(data->fw_name), "silead/%s.fw", id->name); } return 0; } #else static int silead_ts_set_default_fw_name(struct silead_ts_data *data, const struct i2c_device_id *id) { snprintf(data->fw_name, sizeof(data->fw_name), "silead/%s.fw", id->name); return 0; } #endif static void silead_disable_regulator(void *arg) { struct silead_ts_data *data = arg; regulator_bulk_disable(ARRAY_SIZE(data->regulators), data->regulators); } static int silead_ts_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct silead_ts_data *data; struct device *dev = &client->dev; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C | I2C_FUNC_SMBUS_READ_I2C_BLOCK | I2C_FUNC_SMBUS_WRITE_I2C_BLOCK)) { dev_err(dev, "I2C functionality check failed\n"); return -ENXIO; } data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; i2c_set_clientdata(client, data); data->client = client; error = silead_ts_set_default_fw_name(data, id); if (error) return error; silead_ts_read_props(client); /* We must have the IRQ provided by DT or ACPI subsystem */ if (client->irq <= 0) return -ENODEV; data->regulators[0].supply = "vddio"; data->regulators[1].supply = "avdd"; error = devm_regulator_bulk_get(dev, ARRAY_SIZE(data->regulators), data->regulators); if (error) return error; /* * Enable regulators at probe and disable them at remove, we need * to keep the chip powered otherwise it forgets its firmware. */ error = regulator_bulk_enable(ARRAY_SIZE(data->regulators), data->regulators); if (error) return error; error = devm_add_action_or_reset(dev, silead_disable_regulator, data); if (error) return error; /* Power GPIO pin */ data->gpio_power = devm_gpiod_get_optional(dev, "power", GPIOD_OUT_LOW); if (IS_ERR(data->gpio_power)) return dev_err_probe(dev, PTR_ERR(data->gpio_power), "Shutdown GPIO request failed\n"); error = silead_ts_setup(client); if (error) return error; error = silead_ts_request_input_dev(data); if (error) return error; error = silead_ts_request_pen_input_dev(data); if (error) return error; error = devm_request_threaded_irq(dev, client->irq, NULL, silead_ts_threaded_irq_handler, IRQF_ONESHOT, client->name, data); if (error) { if (error != -EPROBE_DEFER) dev_err(dev, "IRQ request failed %d\n", error); return error; } return 0; } static int silead_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); disable_irq(client->irq); silead_ts_set_power(client, SILEAD_POWER_OFF); return 0; } static int silead_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); bool second_try = false; int error, status; silead_ts_set_power(client, SILEAD_POWER_ON); retry: error = silead_ts_reset(client); if (error) return error; if (second_try) { error = silead_ts_load_fw(client); if (error) return error; } error = silead_ts_startup(client); if (error) return error; status = silead_ts_get_status(client); if (status != SILEAD_STATUS_OK) { if (!second_try) { second_try = true; dev_dbg(dev, "Reloading firmware after unsuccessful resume\n"); goto retry; } dev_err(dev, "Resume error, status: 0x%02x\n", status); return -ENODEV; } enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(silead_ts_pm, silead_ts_suspend, silead_ts_resume); static const struct i2c_device_id silead_ts_id[] = { { "gsl1680", 0 }, { "gsl1688", 0 }, { "gsl3670", 0 }, { "gsl3675", 0 }, { "gsl3692", 0 }, { "mssl1680", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, silead_ts_id); #ifdef CONFIG_ACPI static const struct acpi_device_id silead_ts_acpi_match[] = { { "GSL1680", 0 }, { "GSL1688", 0 }, { "GSL3670", 0 }, { "GSL3675", 0 }, { "GSL3692", 0 }, { "MSSL1680", 0 }, { "MSSL0001", 0 }, { "MSSL0002", 0 }, { "MSSL0017", 0 }, { } }; MODULE_DEVICE_TABLE(acpi, silead_ts_acpi_match); #endif #ifdef CONFIG_OF static const struct of_device_id silead_ts_of_match[] = { { .compatible = "silead,gsl1680" }, { .compatible = "silead,gsl1688" }, { .compatible = "silead,gsl3670" }, { .compatible = "silead,gsl3675" }, { .compatible = "silead,gsl3692" }, { }, }; MODULE_DEVICE_TABLE(of, silead_ts_of_match); #endif static struct i2c_driver silead_ts_driver = { .probe = silead_ts_probe, .id_table = silead_ts_id, .driver = { .name = SILEAD_TS_NAME, .acpi_match_table = ACPI_PTR(silead_ts_acpi_match), .of_match_table = of_match_ptr(silead_ts_of_match), .pm = pm_sleep_ptr(&silead_ts_pm), }, }; module_i2c_driver(silead_ts_driver); MODULE_AUTHOR("Robert Dolca <[email protected]>"); MODULE_DESCRIPTION("Silead I2C touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/silead.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2016 Golden Delicious Comp. GmbH&Co. KG * Nikolaus Schaller <[email protected]> */ #include <linux/i2c.h> #include <linux/iio/iio.h> #include "tsc2007.h" struct tsc2007_iio { struct tsc2007 *ts; }; #define TSC2007_CHAN_IIO(_chan, _name, _type, _chan_info) \ { \ .datasheet_name = _name, \ .type = _type, \ .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \ BIT(_chan_info), \ .indexed = 1, \ .channel = _chan, \ } static const struct iio_chan_spec tsc2007_iio_channel[] = { TSC2007_CHAN_IIO(0, "x", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(1, "y", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(2, "z1", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(3, "z2", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(4, "adc", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(5, "rt", IIO_VOLTAGE, IIO_CHAN_INFO_RAW), /* Ohms? */ TSC2007_CHAN_IIO(6, "pen", IIO_PRESSURE, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(7, "temp0", IIO_TEMP, IIO_CHAN_INFO_RAW), TSC2007_CHAN_IIO(8, "temp1", IIO_TEMP, IIO_CHAN_INFO_RAW), }; static int tsc2007_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { struct tsc2007_iio *iio = iio_priv(indio_dev); struct tsc2007 *tsc = iio->ts; int adc_chan = chan->channel; int ret = 0; if (adc_chan >= ARRAY_SIZE(tsc2007_iio_channel)) return -EINVAL; if (mask != IIO_CHAN_INFO_RAW) return -EINVAL; mutex_lock(&tsc->mlock); switch (chan->channel) { case 0: *val = tsc2007_xfer(tsc, READ_X); break; case 1: *val = tsc2007_xfer(tsc, READ_Y); break; case 2: *val = tsc2007_xfer(tsc, READ_Z1); break; case 3: *val = tsc2007_xfer(tsc, READ_Z2); break; case 4: *val = tsc2007_xfer(tsc, (ADC_ON_12BIT | TSC2007_MEASURE_AUX)); break; case 5: { struct ts_event tc; tc.x = tsc2007_xfer(tsc, READ_X); tc.z1 = tsc2007_xfer(tsc, READ_Z1); tc.z2 = tsc2007_xfer(tsc, READ_Z2); *val = tsc2007_calculate_resistance(tsc, &tc); break; } case 6: *val = tsc2007_is_pen_down(tsc); break; case 7: *val = tsc2007_xfer(tsc, (ADC_ON_12BIT | TSC2007_MEASURE_TEMP0)); break; case 8: *val = tsc2007_xfer(tsc, (ADC_ON_12BIT | TSC2007_MEASURE_TEMP1)); break; } /* Prepare for next touch reading - power down ADC, enable PENIRQ */ tsc2007_xfer(tsc, PWRDOWN); mutex_unlock(&tsc->mlock); ret = IIO_VAL_INT; return ret; } static const struct iio_info tsc2007_iio_info = { .read_raw = tsc2007_read_raw, }; int tsc2007_iio_configure(struct tsc2007 *ts) { struct iio_dev *indio_dev; struct tsc2007_iio *iio; int error; indio_dev = devm_iio_device_alloc(&ts->client->dev, sizeof(*iio)); if (!indio_dev) { dev_err(&ts->client->dev, "iio_device_alloc failed\n"); return -ENOMEM; } iio = iio_priv(indio_dev); iio->ts = ts; indio_dev->name = "tsc2007"; indio_dev->info = &tsc2007_iio_info; indio_dev->modes = INDIO_DIRECT_MODE; indio_dev->channels = tsc2007_iio_channel; indio_dev->num_channels = ARRAY_SIZE(tsc2007_iio_channel); error = devm_iio_device_register(&ts->client->dev, indio_dev); if (error) { dev_err(&ts->client->dev, "iio_device_register() failed: %d\n", error); return error; } return 0; }
linux-master
drivers/input/touchscreen/tsc2007_iio.c
// SPDX-License-Identifier: GPL-2.0-only /* * Touch Screen driver for SiS 9200 family I2C Touch panels * * Copyright (C) 2015 SiS, Inc. * Copyright (C) 2016 Nextfour Group */ #include <linux/crc-itu-t.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/gpio/consumer.h> #include <linux/module.h> #include <linux/slab.h> #include <asm/unaligned.h> #define SIS_I2C_NAME "sis_i2c_ts" /* * The I2C packet format: * le16 byte count * u8 Report ID * <contact data - variable length> * u8 Number of contacts * le16 Scan Time (optional) * le16 CRC * * One touch point information consists of 6+ bytes, the order is: * u8 contact state * u8 finger id * le16 x axis * le16 y axis * u8 contact width (optional) * u8 contact height (optional) * u8 pressure (optional) * * Maximum amount of data transmitted in one shot is 64 bytes, if controller * needs to report more contacts than fit in one packet it will send true * number of contacts in first packet and 0 as number of contacts in second * packet. */ #define SIS_MAX_PACKET_SIZE 64 #define SIS_PKT_LEN_OFFSET 0 #define SIS_PKT_REPORT_OFFSET 2 /* Report ID/type */ #define SIS_PKT_CONTACT_OFFSET 3 /* First contact */ #define SIS_SCAN_TIME_LEN 2 /* Supported report types */ #define SIS_ALL_IN_ONE_PACKAGE 0x10 #define SIS_PKT_IS_TOUCH(x) (((x) & 0x0f) == 0x01) #define SIS_PKT_IS_HIDI2C(x) (((x) & 0x0f) == 0x06) /* Contact properties within report */ #define SIS_PKT_HAS_AREA(x) ((x) & BIT(4)) #define SIS_PKT_HAS_PRESSURE(x) ((x) & BIT(5)) #define SIS_PKT_HAS_SCANTIME(x) ((x) & BIT(6)) /* Contact size */ #define SIS_BASE_LEN_PER_CONTACT 6 #define SIS_AREA_LEN_PER_CONTACT 2 #define SIS_PRESSURE_LEN_PER_CONTACT 1 /* Offsets within contact data */ #define SIS_CONTACT_STATUS_OFFSET 0 #define SIS_CONTACT_ID_OFFSET 1 /* Contact ID */ #define SIS_CONTACT_X_OFFSET 2 #define SIS_CONTACT_Y_OFFSET 4 #define SIS_CONTACT_WIDTH_OFFSET 6 #define SIS_CONTACT_HEIGHT_OFFSET 7 #define SIS_CONTACT_PRESSURE_OFFSET(id) (SIS_PKT_HAS_AREA(id) ? 8 : 6) /* Individual contact state */ #define SIS_STATUS_UP 0x0 #define SIS_STATUS_DOWN 0x3 /* Touchscreen parameters */ #define SIS_MAX_FINGERS 10 #define SIS_MAX_X 4095 #define SIS_MAX_Y 4095 #define SIS_MAX_PRESSURE 255 /* Resolution diagonal */ #define SIS_AREA_LENGTH_LONGER 5792 /*((SIS_MAX_X^2) + (SIS_MAX_Y^2))^0.5*/ #define SIS_AREA_LENGTH_SHORT 5792 #define SIS_AREA_UNIT (5792 / 32) struct sis_ts_data { struct i2c_client *client; struct input_dev *input; struct gpio_desc *attn_gpio; struct gpio_desc *reset_gpio; u8 packet[SIS_MAX_PACKET_SIZE]; }; static int sis_read_packet(struct i2c_client *client, u8 *buf, unsigned int *num_contacts, unsigned int *contact_size) { int count_idx; int ret; u16 len; u16 crc, pkg_crc; u8 report_id; ret = i2c_master_recv(client, buf, SIS_MAX_PACKET_SIZE); if (ret <= 0) return -EIO; len = get_unaligned_le16(&buf[SIS_PKT_LEN_OFFSET]); if (len > SIS_MAX_PACKET_SIZE) { dev_err(&client->dev, "%s: invalid packet length (%d vs %d)\n", __func__, len, SIS_MAX_PACKET_SIZE); return -E2BIG; } if (len < 10) return -EINVAL; report_id = buf[SIS_PKT_REPORT_OFFSET]; count_idx = len - 1; *contact_size = SIS_BASE_LEN_PER_CONTACT; if (report_id != SIS_ALL_IN_ONE_PACKAGE) { if (SIS_PKT_IS_TOUCH(report_id)) { /* * Calculate CRC ignoring packet length * in the beginning and CRC transmitted * at the end of the packet. */ crc = crc_itu_t(0, buf + 2, len - 2 - 2); pkg_crc = get_unaligned_le16(&buf[len - 2]); if (crc != pkg_crc) { dev_err(&client->dev, "%s: CRC Error (%d vs %d)\n", __func__, crc, pkg_crc); return -EINVAL; } count_idx -= 2; } else if (!SIS_PKT_IS_HIDI2C(report_id)) { dev_err(&client->dev, "%s: invalid packet ID %#02x\n", __func__, report_id); return -EINVAL; } if (SIS_PKT_HAS_SCANTIME(report_id)) count_idx -= SIS_SCAN_TIME_LEN; if (SIS_PKT_HAS_AREA(report_id)) *contact_size += SIS_AREA_LEN_PER_CONTACT; if (SIS_PKT_HAS_PRESSURE(report_id)) *contact_size += SIS_PRESSURE_LEN_PER_CONTACT; } *num_contacts = buf[count_idx]; return 0; } static int sis_ts_report_contact(struct sis_ts_data *ts, const u8 *data, u8 id) { struct input_dev *input = ts->input; int slot; u8 status = data[SIS_CONTACT_STATUS_OFFSET]; u8 pressure; u8 height, width; u16 x, y; if (status != SIS_STATUS_DOWN && status != SIS_STATUS_UP) { dev_err(&ts->client->dev, "Unexpected touch status: %#02x\n", data[SIS_CONTACT_STATUS_OFFSET]); return -EINVAL; } slot = input_mt_get_slot_by_key(input, data[SIS_CONTACT_ID_OFFSET]); if (slot < 0) return -ENOENT; input_mt_slot(input, slot); input_mt_report_slot_state(input, MT_TOOL_FINGER, status == SIS_STATUS_DOWN); if (status == SIS_STATUS_DOWN) { pressure = height = width = 1; if (id != SIS_ALL_IN_ONE_PACKAGE) { if (SIS_PKT_HAS_AREA(id)) { width = data[SIS_CONTACT_WIDTH_OFFSET]; height = data[SIS_CONTACT_HEIGHT_OFFSET]; } if (SIS_PKT_HAS_PRESSURE(id)) pressure = data[SIS_CONTACT_PRESSURE_OFFSET(id)]; } x = get_unaligned_le16(&data[SIS_CONTACT_X_OFFSET]); y = get_unaligned_le16(&data[SIS_CONTACT_Y_OFFSET]); input_report_abs(input, ABS_MT_TOUCH_MAJOR, width * SIS_AREA_UNIT); input_report_abs(input, ABS_MT_TOUCH_MINOR, height * SIS_AREA_UNIT); input_report_abs(input, ABS_MT_PRESSURE, pressure); input_report_abs(input, ABS_MT_POSITION_X, x); input_report_abs(input, ABS_MT_POSITION_Y, y); } return 0; } static void sis_ts_handle_packet(struct sis_ts_data *ts) { const u8 *contact; unsigned int num_to_report = 0; unsigned int num_contacts; unsigned int num_reported; unsigned int contact_size; int error; u8 report_id; do { error = sis_read_packet(ts->client, ts->packet, &num_contacts, &contact_size); if (error) break; if (num_to_report == 0) { num_to_report = num_contacts; } else if (num_contacts != 0) { dev_err(&ts->client->dev, "%s: nonzero (%d) point count in tail packet\n", __func__, num_contacts); break; } report_id = ts->packet[SIS_PKT_REPORT_OFFSET]; contact = &ts->packet[SIS_PKT_CONTACT_OFFSET]; num_reported = 0; while (num_to_report > 0) { error = sis_ts_report_contact(ts, contact, report_id); if (error) break; contact += contact_size; num_to_report--; num_reported++; if (report_id != SIS_ALL_IN_ONE_PACKAGE && num_reported >= 5) { /* * The remainder of contacts is sent * in the 2nd packet. */ break; } } } while (num_to_report > 0); input_mt_sync_frame(ts->input); input_sync(ts->input); } static irqreturn_t sis_ts_irq_handler(int irq, void *dev_id) { struct sis_ts_data *ts = dev_id; do { sis_ts_handle_packet(ts); } while (ts->attn_gpio && gpiod_get_value_cansleep(ts->attn_gpio)); return IRQ_HANDLED; } static void sis_ts_reset(struct sis_ts_data *ts) { if (ts->reset_gpio) { /* Get out of reset */ usleep_range(1000, 2000); gpiod_set_value(ts->reset_gpio, 1); usleep_range(1000, 2000); gpiod_set_value(ts->reset_gpio, 0); msleep(100); } } static int sis_ts_probe(struct i2c_client *client) { struct sis_ts_data *ts; struct input_dev *input; int error; ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; ts->attn_gpio = devm_gpiod_get_optional(&client->dev, "attn", GPIOD_IN); if (IS_ERR(ts->attn_gpio)) return dev_err_probe(&client->dev, PTR_ERR(ts->attn_gpio), "Failed to get attention GPIO\n"); ts->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(ts->reset_gpio)) return dev_err_probe(&client->dev, PTR_ERR(ts->reset_gpio), "Failed to get reset GPIO\n"); sis_ts_reset(ts); ts->input = input = devm_input_allocate_device(&client->dev); if (!input) { dev_err(&client->dev, "Failed to allocate input device\n"); return -ENOMEM; } input->name = "SiS Touchscreen"; input->id.bustype = BUS_I2C; input_set_abs_params(input, ABS_MT_POSITION_X, 0, SIS_MAX_X, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, SIS_MAX_Y, 0, 0); input_set_abs_params(input, ABS_MT_PRESSURE, 0, SIS_MAX_PRESSURE, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, SIS_AREA_LENGTH_LONGER, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, SIS_AREA_LENGTH_SHORT, 0, 0); error = input_mt_init_slots(input, SIS_MAX_FINGERS, INPUT_MT_DIRECT); if (error) { dev_err(&client->dev, "Failed to initialize MT slots: %d\n", error); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, sis_ts_irq_handler, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(&client->dev, "Failed to request IRQ: %d\n", error); return error; } error = input_register_device(ts->input); if (error) { dev_err(&client->dev, "Failed to register input device: %d\n", error); return error; } return 0; } #ifdef CONFIG_OF static const struct of_device_id sis_ts_dt_ids[] = { { .compatible = "sis,9200-ts" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, sis_ts_dt_ids); #endif static const struct i2c_device_id sis_ts_id[] = { { SIS_I2C_NAME, 0 }, { "9200-ts", 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, sis_ts_id); static struct i2c_driver sis_ts_driver = { .driver = { .name = SIS_I2C_NAME, .of_match_table = of_match_ptr(sis_ts_dt_ids), }, .probe = sis_ts_probe, .id_table = sis_ts_id, }; module_i2c_driver(sis_ts_driver); MODULE_DESCRIPTION("SiS 9200 Family Touchscreen Driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Mika Penttilä <[email protected]>");
linux-master
drivers/input/touchscreen/sis_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Raydium touchscreen I2C driver. * * Copyright (C) 2012-2014, Raydium Semiconductor Corporation. * * Raydium reserves the right to make changes without further notice * to the materials described herein. Raydium does not assume any * liability arising out of the application described herein. * * Contact Raydium Semiconductor Corporation at www.rad-ic.com */ #include <linux/acpi.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of.h> #include <linux/pm_wakeirq.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <asm/unaligned.h> /* Slave I2C mode */ #define RM_BOOT_BLDR 0x02 #define RM_BOOT_MAIN 0x03 /* I2C bootoloader commands */ #define RM_CMD_BOOT_PAGE_WRT 0x0B /* send bl page write */ #define RM_CMD_BOOT_WRT 0x11 /* send bl write */ #define RM_CMD_BOOT_ACK 0x22 /* send ack*/ #define RM_CMD_BOOT_CHK 0x33 /* send data check */ #define RM_CMD_BOOT_READ 0x44 /* send wait bl data ready*/ #define RM_BOOT_RDY 0xFF /* bl data ready */ #define RM_BOOT_CMD_READHWID 0x0E /* read hwid */ /* I2C main commands */ #define RM_CMD_QUERY_BANK 0x2B #define RM_CMD_DATA_BANK 0x4D #define RM_CMD_ENTER_SLEEP 0x4E #define RM_CMD_BANK_SWITCH 0xAA #define RM_RESET_MSG_ADDR 0x40000004 #define RM_MAX_READ_SIZE 56 #define RM_PACKET_CRC_SIZE 2 /* Touch relative info */ #define RM_MAX_RETRIES 3 #define RM_RETRY_DELAY_MS 20 #define RM_MAX_TOUCH_NUM 10 #define RM_BOOT_DELAY_MS 100 /* Offsets in contact data */ #define RM_CONTACT_STATE_POS 0 #define RM_CONTACT_X_POS 1 #define RM_CONTACT_Y_POS 3 #define RM_CONTACT_PRESSURE_POS 5 #define RM_CONTACT_WIDTH_X_POS 6 #define RM_CONTACT_WIDTH_Y_POS 7 /* Bootloader relative info */ #define RM_BL_WRT_CMD_SIZE 3 /* bl flash wrt cmd size */ #define RM_BL_WRT_PKG_SIZE 32 /* bl wrt pkg size */ #define RM_BL_WRT_LEN (RM_BL_WRT_PKG_SIZE + RM_BL_WRT_CMD_SIZE) #define RM_FW_PAGE_SIZE 128 #define RM_MAX_FW_RETRIES 30 #define RM_MAX_FW_SIZE 0xD000 #define RM_POWERON_DELAY_USEC 500 #define RM_RESET_DELAY_MSEC 50 enum raydium_bl_cmd { BL_HEADER = 0, BL_PAGE_STR, BL_PKG_IDX, BL_DATA_STR, }; enum raydium_bl_ack { RAYDIUM_ACK_NULL = 0, RAYDIUM_WAIT_READY, RAYDIUM_PATH_READY, }; enum raydium_boot_mode { RAYDIUM_TS_MAIN = 0, RAYDIUM_TS_BLDR, }; /* Response to RM_CMD_DATA_BANK request */ struct raydium_data_info { __le32 data_bank_addr; u8 pkg_size; u8 tp_info_size; }; struct raydium_info { __le32 hw_ver; /*device version */ u8 main_ver; u8 sub_ver; __le16 ft_ver; /* test version */ u8 x_num; u8 y_num; __le16 x_max; __le16 y_max; u8 x_res; /* units/mm */ u8 y_res; /* units/mm */ }; /* struct raydium_data - represents state of Raydium touchscreen device */ struct raydium_data { struct i2c_client *client; struct input_dev *input; struct regulator *avdd; struct regulator *vccio; struct gpio_desc *reset_gpio; struct raydium_info info; struct mutex sysfs_mutex; u8 *report_data; u32 data_bank_addr; u8 report_size; u8 contact_size; u8 pkg_size; enum raydium_boot_mode boot_mode; }; /* * Header to be sent for RM_CMD_BANK_SWITCH command. This is used by * raydium_i2c_{read|send} below. */ struct __packed raydium_bank_switch_header { u8 cmd; __be32 be_addr; }; static int raydium_i2c_xfer(struct i2c_client *client, u32 addr, struct i2c_msg *xfer, size_t xfer_count) { int ret; /* * If address is greater than 255, then RM_CMD_BANK_SWITCH needs to be * sent first. Else, skip the header i.e. xfer[0]. */ int xfer_start_idx = (addr > 0xff) ? 0 : 1; xfer_count -= xfer_start_idx; ret = i2c_transfer(client->adapter, &xfer[xfer_start_idx], xfer_count); if (likely(ret == xfer_count)) return 0; return ret < 0 ? ret : -EIO; } static int raydium_i2c_send(struct i2c_client *client, u32 addr, const void *data, size_t len) { int tries = 0; int error; u8 *tx_buf; u8 reg_addr = addr & 0xff; tx_buf = kmalloc(len + 1, GFP_KERNEL); if (!tx_buf) return -ENOMEM; tx_buf[0] = reg_addr; memcpy(tx_buf + 1, data, len); do { struct raydium_bank_switch_header header = { .cmd = RM_CMD_BANK_SWITCH, .be_addr = cpu_to_be32(addr), }; /* * Perform as a single i2c_transfer transaction to ensure that * no other I2C transactions are initiated on the bus to any * other device in between. Initiating transacations to other * devices after RM_CMD_BANK_SWITCH is sent is known to cause * issues. This is also why regmap infrastructure cannot be used * for this driver. Regmap handles page(bank) switch and reads * as separate i2c_transfer() operations. This can result in * problems if the Raydium device is on a shared I2C bus. */ struct i2c_msg xfer[] = { { .addr = client->addr, .len = sizeof(header), .buf = (u8 *)&header, }, { .addr = client->addr, .len = len + 1, .buf = tx_buf, }, }; error = raydium_i2c_xfer(client, addr, xfer, ARRAY_SIZE(xfer)); if (likely(!error)) goto out; msleep(RM_RETRY_DELAY_MS); } while (++tries < RM_MAX_RETRIES); dev_err(&client->dev, "%s failed: %d\n", __func__, error); out: kfree(tx_buf); return error; } static int raydium_i2c_read(struct i2c_client *client, u32 addr, void *data, size_t len) { int error; while (len) { u8 reg_addr = addr & 0xff; struct raydium_bank_switch_header header = { .cmd = RM_CMD_BANK_SWITCH, .be_addr = cpu_to_be32(addr), }; size_t xfer_len = min_t(size_t, len, RM_MAX_READ_SIZE); /* * Perform as a single i2c_transfer transaction to ensure that * no other I2C transactions are initiated on the bus to any * other device in between. Initiating transacations to other * devices after RM_CMD_BANK_SWITCH is sent is known to cause * issues. This is also why regmap infrastructure cannot be used * for this driver. Regmap handles page(bank) switch and writes * as separate i2c_transfer() operations. This can result in * problems if the Raydium device is on a shared I2C bus. */ struct i2c_msg xfer[] = { { .addr = client->addr, .len = sizeof(header), .buf = (u8 *)&header, }, { .addr = client->addr, .len = 1, .buf = &reg_addr, }, { .addr = client->addr, .len = xfer_len, .buf = data, .flags = I2C_M_RD, } }; error = raydium_i2c_xfer(client, addr, xfer, ARRAY_SIZE(xfer)); if (unlikely(error)) return error; len -= xfer_len; data += xfer_len; addr += xfer_len; } return 0; } static int raydium_i2c_sw_reset(struct i2c_client *client) { const u8 soft_rst_cmd = 0x01; int error; error = raydium_i2c_send(client, RM_RESET_MSG_ADDR, &soft_rst_cmd, sizeof(soft_rst_cmd)); if (error) { dev_err(&client->dev, "software reset failed: %d\n", error); return error; } msleep(RM_RESET_DELAY_MSEC); return 0; } static int raydium_i2c_query_ts_bootloader_info(struct raydium_data *ts) { struct i2c_client *client = ts->client; static const u8 get_hwid[] = { RM_BOOT_CMD_READHWID, 0x10, 0xc0, 0x01, 0x00, 0x04, 0x00 }; u8 rbuf[5] = { 0 }; u32 hw_ver; int error; error = raydium_i2c_send(client, RM_CMD_BOOT_WRT, get_hwid, sizeof(get_hwid)); if (error) { dev_err(&client->dev, "WRT HWID command failed: %d\n", error); return error; } error = raydium_i2c_send(client, RM_CMD_BOOT_ACK, rbuf, 1); if (error) { dev_err(&client->dev, "Ack HWID command failed: %d\n", error); return error; } error = raydium_i2c_read(client, RM_CMD_BOOT_CHK, rbuf, sizeof(rbuf)); if (error) { dev_err(&client->dev, "Read HWID command failed: %d (%4ph)\n", error, rbuf + 1); hw_ver = 0xffffffffUL; } else { hw_ver = get_unaligned_be32(rbuf + 1); } ts->info.hw_ver = cpu_to_le32(hw_ver); ts->info.main_ver = 0xff; ts->info.sub_ver = 0xff; return error; } static int raydium_i2c_query_ts_info(struct raydium_data *ts) { struct i2c_client *client = ts->client; struct raydium_data_info data_info; __le32 query_bank_addr; int error, retry_cnt; for (retry_cnt = 0; retry_cnt < RM_MAX_RETRIES; retry_cnt++) { error = raydium_i2c_read(client, RM_CMD_DATA_BANK, &data_info, sizeof(data_info)); if (error) continue; /* * Warn user if we already allocated memory for reports and * then the size changed (due to firmware update?) and keep * old size instead. */ if (ts->report_data && ts->pkg_size != data_info.pkg_size) { dev_warn(&client->dev, "report size changes, was: %d, new: %d\n", ts->pkg_size, data_info.pkg_size); } else { ts->pkg_size = data_info.pkg_size; ts->report_size = ts->pkg_size - RM_PACKET_CRC_SIZE; } ts->contact_size = data_info.tp_info_size; ts->data_bank_addr = le32_to_cpu(data_info.data_bank_addr); dev_dbg(&client->dev, "data_bank_addr: %#08x, report_size: %d, contact_size: %d\n", ts->data_bank_addr, ts->report_size, ts->contact_size); error = raydium_i2c_read(client, RM_CMD_QUERY_BANK, &query_bank_addr, sizeof(query_bank_addr)); if (error) continue; error = raydium_i2c_read(client, le32_to_cpu(query_bank_addr), &ts->info, sizeof(ts->info)); if (error) continue; return 0; } dev_err(&client->dev, "failed to query device parameters: %d\n", error); return error; } static int raydium_i2c_check_fw_status(struct raydium_data *ts) { struct i2c_client *client = ts->client; static const u8 bl_ack = 0x62; static const u8 main_ack = 0x66; u8 buf[4]; int error; error = raydium_i2c_read(client, RM_CMD_BOOT_READ, buf, sizeof(buf)); if (!error) { if (buf[0] == bl_ack) ts->boot_mode = RAYDIUM_TS_BLDR; else if (buf[0] == main_ack) ts->boot_mode = RAYDIUM_TS_MAIN; return 0; } return error; } static int raydium_i2c_initialize(struct raydium_data *ts) { struct i2c_client *client = ts->client; int error, retry_cnt; for (retry_cnt = 0; retry_cnt < RM_MAX_RETRIES; retry_cnt++) { /* Wait for Hello packet */ msleep(RM_BOOT_DELAY_MS); error = raydium_i2c_check_fw_status(ts); if (error) { dev_err(&client->dev, "failed to read 'hello' packet: %d\n", error); continue; } if (ts->boot_mode == RAYDIUM_TS_BLDR || ts->boot_mode == RAYDIUM_TS_MAIN) { break; } } if (error) ts->boot_mode = RAYDIUM_TS_BLDR; if (ts->boot_mode == RAYDIUM_TS_BLDR) raydium_i2c_query_ts_bootloader_info(ts); else raydium_i2c_query_ts_info(ts); return error; } static int raydium_i2c_bl_chk_state(struct i2c_client *client, enum raydium_bl_ack state) { static const u8 ack_ok[] = { 0xFF, 0x39, 0x30, 0x30, 0x54 }; u8 rbuf[sizeof(ack_ok)]; u8 retry; int error; for (retry = 0; retry < RM_MAX_FW_RETRIES; retry++) { switch (state) { case RAYDIUM_ACK_NULL: return 0; case RAYDIUM_WAIT_READY: error = raydium_i2c_read(client, RM_CMD_BOOT_CHK, &rbuf[0], 1); if (!error && rbuf[0] == RM_BOOT_RDY) return 0; break; case RAYDIUM_PATH_READY: error = raydium_i2c_read(client, RM_CMD_BOOT_CHK, rbuf, sizeof(rbuf)); if (!error && !memcmp(rbuf, ack_ok, sizeof(ack_ok))) return 0; break; default: dev_err(&client->dev, "%s: invalid target state %d\n", __func__, state); return -EINVAL; } msleep(20); } return -ETIMEDOUT; } static int raydium_i2c_write_object(struct i2c_client *client, const void *data, size_t len, enum raydium_bl_ack state) { int error; static const u8 cmd[] = { 0xFF, 0x39 }; error = raydium_i2c_send(client, RM_CMD_BOOT_WRT, data, len); if (error) { dev_err(&client->dev, "WRT obj command failed: %d\n", error); return error; } error = raydium_i2c_send(client, RM_CMD_BOOT_ACK, cmd, sizeof(cmd)); if (error) { dev_err(&client->dev, "Ack obj command failed: %d\n", error); return error; } error = raydium_i2c_bl_chk_state(client, state); if (error) { dev_err(&client->dev, "BL check state failed: %d\n", error); return error; } return 0; } static int raydium_i2c_boot_trigger(struct i2c_client *client) { static const u8 cmd[7][6] = { { 0x08, 0x0C, 0x09, 0x00, 0x50, 0xD7 }, { 0x08, 0x04, 0x09, 0x00, 0x50, 0xA5 }, { 0x08, 0x04, 0x09, 0x00, 0x50, 0x00 }, { 0x08, 0x04, 0x09, 0x00, 0x50, 0xA5 }, { 0x08, 0x0C, 0x09, 0x00, 0x50, 0x00 }, { 0x06, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x02, 0xA2, 0x00, 0x00, 0x00, 0x00 }, }; int i; int error; for (i = 0; i < 7; i++) { error = raydium_i2c_write_object(client, cmd[i], sizeof(cmd[i]), RAYDIUM_WAIT_READY); if (error) { dev_err(&client->dev, "boot trigger failed at step %d: %d\n", i, error); return error; } } return 0; } static int raydium_i2c_fw_trigger(struct i2c_client *client) { static const u8 cmd[5][11] = { { 0, 0x09, 0x71, 0x0C, 0x09, 0x00, 0x50, 0xD7, 0, 0, 0 }, { 0, 0x09, 0x71, 0x04, 0x09, 0x00, 0x50, 0xA5, 0, 0, 0 }, { 0, 0x09, 0x71, 0x04, 0x09, 0x00, 0x50, 0x00, 0, 0, 0 }, { 0, 0x09, 0x71, 0x04, 0x09, 0x00, 0x50, 0xA5, 0, 0, 0 }, { 0, 0x09, 0x71, 0x0C, 0x09, 0x00, 0x50, 0x00, 0, 0, 0 }, }; int i; int error; for (i = 0; i < 5; i++) { error = raydium_i2c_write_object(client, cmd[i], sizeof(cmd[i]), RAYDIUM_ACK_NULL); if (error) { dev_err(&client->dev, "fw trigger failed at step %d: %d\n", i, error); return error; } } return 0; } static int raydium_i2c_check_path(struct i2c_client *client) { static const u8 cmd[] = { 0x09, 0x00, 0x09, 0x00, 0x50, 0x10, 0x00 }; int error; error = raydium_i2c_write_object(client, cmd, sizeof(cmd), RAYDIUM_PATH_READY); if (error) { dev_err(&client->dev, "check path command failed: %d\n", error); return error; } return 0; } static int raydium_i2c_enter_bl(struct i2c_client *client) { static const u8 cal_cmd[] = { 0x00, 0x01, 0x52 }; int error; error = raydium_i2c_write_object(client, cal_cmd, sizeof(cal_cmd), RAYDIUM_ACK_NULL); if (error) { dev_err(&client->dev, "enter bl command failed: %d\n", error); return error; } msleep(RM_BOOT_DELAY_MS); return 0; } static int raydium_i2c_leave_bl(struct i2c_client *client) { static const u8 leave_cmd[] = { 0x05, 0x00 }; int error; error = raydium_i2c_write_object(client, leave_cmd, sizeof(leave_cmd), RAYDIUM_ACK_NULL); if (error) { dev_err(&client->dev, "leave bl command failed: %d\n", error); return error; } msleep(RM_BOOT_DELAY_MS); return 0; } static int raydium_i2c_write_checksum(struct i2c_client *client, size_t length, u16 checksum) { u8 checksum_cmd[] = { 0x00, 0x05, 0x6D, 0x00, 0x00, 0x00, 0x00 }; int error; put_unaligned_le16(length, &checksum_cmd[3]); put_unaligned_le16(checksum, &checksum_cmd[5]); error = raydium_i2c_write_object(client, checksum_cmd, sizeof(checksum_cmd), RAYDIUM_ACK_NULL); if (error) { dev_err(&client->dev, "failed to write checksum: %d\n", error); return error; } return 0; } static int raydium_i2c_disable_watch_dog(struct i2c_client *client) { static const u8 cmd[] = { 0x0A, 0xAA }; int error; error = raydium_i2c_write_object(client, cmd, sizeof(cmd), RAYDIUM_WAIT_READY); if (error) { dev_err(&client->dev, "disable watchdog command failed: %d\n", error); return error; } return 0; } static int raydium_i2c_fw_write_page(struct i2c_client *client, u16 page_idx, const void *data, size_t len) { u8 buf[RM_BL_WRT_LEN]; size_t xfer_len; int error; int i; BUILD_BUG_ON((RM_FW_PAGE_SIZE % RM_BL_WRT_PKG_SIZE) != 0); for (i = 0; i < RM_FW_PAGE_SIZE / RM_BL_WRT_PKG_SIZE; i++) { buf[BL_HEADER] = RM_CMD_BOOT_PAGE_WRT; buf[BL_PAGE_STR] = page_idx ? 0xff : 0; buf[BL_PKG_IDX] = i + 1; xfer_len = min_t(size_t, len, RM_BL_WRT_PKG_SIZE); memcpy(&buf[BL_DATA_STR], data, xfer_len); if (len < RM_BL_WRT_PKG_SIZE) memset(&buf[BL_DATA_STR + xfer_len], 0xff, RM_BL_WRT_PKG_SIZE - xfer_len); error = raydium_i2c_write_object(client, buf, RM_BL_WRT_LEN, RAYDIUM_WAIT_READY); if (error) { dev_err(&client->dev, "page write command failed for page %d, chunk %d: %d\n", page_idx, i, error); return error; } data += xfer_len; len -= xfer_len; } return error; } static u16 raydium_calc_chksum(const u8 *buf, u16 len) { u16 checksum = 0; u16 i; for (i = 0; i < len; i++) checksum += buf[i]; return checksum; } static int raydium_i2c_do_update_firmware(struct raydium_data *ts, const struct firmware *fw) { struct i2c_client *client = ts->client; const void *data; size_t data_len; size_t len; int page_nr; int i; int error; u16 fw_checksum; if (fw->size == 0 || fw->size > RM_MAX_FW_SIZE) { dev_err(&client->dev, "Invalid firmware length\n"); return -EINVAL; } error = raydium_i2c_check_fw_status(ts); if (error) { dev_err(&client->dev, "Unable to access IC %d\n", error); return error; } if (ts->boot_mode == RAYDIUM_TS_MAIN) { for (i = 0; i < RM_MAX_RETRIES; i++) { error = raydium_i2c_enter_bl(client); if (!error) { error = raydium_i2c_check_fw_status(ts); if (error) { dev_err(&client->dev, "unable to access IC: %d\n", error); return error; } if (ts->boot_mode == RAYDIUM_TS_BLDR) break; } } if (ts->boot_mode == RAYDIUM_TS_MAIN) { dev_err(&client->dev, "failed to jump to boot loader: %d\n", error); return -EIO; } } error = raydium_i2c_disable_watch_dog(client); if (error) return error; error = raydium_i2c_check_path(client); if (error) return error; error = raydium_i2c_boot_trigger(client); if (error) { dev_err(&client->dev, "send boot trigger fail: %d\n", error); return error; } msleep(RM_BOOT_DELAY_MS); data = fw->data; data_len = fw->size; page_nr = 0; while (data_len) { len = min_t(size_t, data_len, RM_FW_PAGE_SIZE); error = raydium_i2c_fw_write_page(client, page_nr++, data, len); if (error) return error; msleep(20); data += len; data_len -= len; } error = raydium_i2c_leave_bl(client); if (error) { dev_err(&client->dev, "failed to leave boot loader: %d\n", error); return error; } dev_dbg(&client->dev, "left boot loader mode\n"); msleep(RM_BOOT_DELAY_MS); error = raydium_i2c_check_fw_status(ts); if (error) { dev_err(&client->dev, "failed to check fw status after write: %d\n", error); return error; } if (ts->boot_mode != RAYDIUM_TS_MAIN) { dev_err(&client->dev, "failed to switch to main fw after writing firmware: %d\n", error); return -EINVAL; } error = raydium_i2c_fw_trigger(client); if (error) { dev_err(&client->dev, "failed to trigger fw: %d\n", error); return error; } fw_checksum = raydium_calc_chksum(fw->data, fw->size); error = raydium_i2c_write_checksum(client, fw->size, fw_checksum); if (error) return error; return 0; } static int raydium_i2c_fw_update(struct raydium_data *ts) { struct i2c_client *client = ts->client; const struct firmware *fw = NULL; char *fw_file; int error; fw_file = kasprintf(GFP_KERNEL, "raydium_%#04x.fw", le32_to_cpu(ts->info.hw_ver)); if (!fw_file) return -ENOMEM; dev_dbg(&client->dev, "firmware name: %s\n", fw_file); error = request_firmware(&fw, fw_file, &client->dev); if (error) { dev_err(&client->dev, "Unable to open firmware %s\n", fw_file); goto out_free_fw_file; } disable_irq(client->irq); error = raydium_i2c_do_update_firmware(ts, fw); if (error) { dev_err(&client->dev, "firmware update failed: %d\n", error); ts->boot_mode = RAYDIUM_TS_BLDR; goto out_enable_irq; } error = raydium_i2c_initialize(ts); if (error) { dev_err(&client->dev, "failed to initialize device after firmware update: %d\n", error); ts->boot_mode = RAYDIUM_TS_BLDR; goto out_enable_irq; } ts->boot_mode = RAYDIUM_TS_MAIN; out_enable_irq: enable_irq(client->irq); msleep(100); release_firmware(fw); out_free_fw_file: kfree(fw_file); return error; } static void raydium_mt_event(struct raydium_data *ts) { int i; for (i = 0; i < ts->report_size / ts->contact_size; i++) { u8 *contact = &ts->report_data[ts->contact_size * i]; bool state = contact[RM_CONTACT_STATE_POS]; u8 wx, wy; input_mt_slot(ts->input, i); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, state); if (!state) continue; input_report_abs(ts->input, ABS_MT_POSITION_X, get_unaligned_le16(&contact[RM_CONTACT_X_POS])); input_report_abs(ts->input, ABS_MT_POSITION_Y, get_unaligned_le16(&contact[RM_CONTACT_Y_POS])); input_report_abs(ts->input, ABS_MT_PRESSURE, contact[RM_CONTACT_PRESSURE_POS]); wx = contact[RM_CONTACT_WIDTH_X_POS]; wy = contact[RM_CONTACT_WIDTH_Y_POS]; input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, max(wx, wy)); input_report_abs(ts->input, ABS_MT_TOUCH_MINOR, min(wx, wy)); } input_mt_sync_frame(ts->input); input_sync(ts->input); } static irqreturn_t raydium_i2c_irq(int irq, void *_dev) { struct raydium_data *ts = _dev; int error; u16 fw_crc; u16 calc_crc; if (ts->boot_mode != RAYDIUM_TS_MAIN) goto out; error = raydium_i2c_read(ts->client, ts->data_bank_addr, ts->report_data, ts->pkg_size); if (error) goto out; fw_crc = get_unaligned_le16(&ts->report_data[ts->report_size]); calc_crc = raydium_calc_chksum(ts->report_data, ts->report_size); if (unlikely(fw_crc != calc_crc)) { dev_warn(&ts->client->dev, "%s: invalid packet crc %#04x vs %#04x\n", __func__, calc_crc, fw_crc); goto out; } raydium_mt_event(ts); out: return IRQ_HANDLED; } static ssize_t raydium_i2c_fw_ver_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%d.%d\n", ts->info.main_ver, ts->info.sub_ver); } static ssize_t raydium_i2c_hw_ver_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%#04x\n", le32_to_cpu(ts->info.hw_ver)); } static ssize_t raydium_i2c_boot_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); return sprintf(buf, "%s\n", ts->boot_mode == RAYDIUM_TS_MAIN ? "Normal" : "Recovery"); } static ssize_t raydium_i2c_update_fw_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); int error; error = mutex_lock_interruptible(&ts->sysfs_mutex); if (error) return error; error = raydium_i2c_fw_update(ts); mutex_unlock(&ts->sysfs_mutex); return error ?: count; } static ssize_t raydium_i2c_calibrate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); static const u8 cal_cmd[] = { 0x00, 0x01, 0x9E }; int error; error = mutex_lock_interruptible(&ts->sysfs_mutex); if (error) return error; error = raydium_i2c_write_object(client, cal_cmd, sizeof(cal_cmd), RAYDIUM_WAIT_READY); if (error) dev_err(&client->dev, "calibrate command failed: %d\n", error); mutex_unlock(&ts->sysfs_mutex); return error ?: count; } static DEVICE_ATTR(fw_version, S_IRUGO, raydium_i2c_fw_ver_show, NULL); static DEVICE_ATTR(hw_version, S_IRUGO, raydium_i2c_hw_ver_show, NULL); static DEVICE_ATTR(boot_mode, S_IRUGO, raydium_i2c_boot_mode_show, NULL); static DEVICE_ATTR(update_fw, S_IWUSR, NULL, raydium_i2c_update_fw_store); static DEVICE_ATTR(calibrate, S_IWUSR, NULL, raydium_i2c_calibrate_store); static struct attribute *raydium_i2c_attributes[] = { &dev_attr_update_fw.attr, &dev_attr_boot_mode.attr, &dev_attr_fw_version.attr, &dev_attr_hw_version.attr, &dev_attr_calibrate.attr, NULL }; static const struct attribute_group raydium_i2c_attribute_group = { .attrs = raydium_i2c_attributes, }; static int raydium_i2c_power_on(struct raydium_data *ts) { int error; if (!ts->reset_gpio) return 0; gpiod_set_value_cansleep(ts->reset_gpio, 1); error = regulator_enable(ts->avdd); if (error) { dev_err(&ts->client->dev, "failed to enable avdd regulator: %d\n", error); goto release_reset_gpio; } error = regulator_enable(ts->vccio); if (error) { regulator_disable(ts->avdd); dev_err(&ts->client->dev, "failed to enable vccio regulator: %d\n", error); goto release_reset_gpio; } udelay(RM_POWERON_DELAY_USEC); release_reset_gpio: gpiod_set_value_cansleep(ts->reset_gpio, 0); if (error) return error; msleep(RM_RESET_DELAY_MSEC); return 0; } static void raydium_i2c_power_off(void *_data) { struct raydium_data *ts = _data; if (ts->reset_gpio) { gpiod_set_value_cansleep(ts->reset_gpio, 1); regulator_disable(ts->vccio); regulator_disable(ts->avdd); } } static int raydium_i2c_probe(struct i2c_client *client) { union i2c_smbus_data dummy; struct raydium_data *ts; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "i2c check functionality error (need I2C_FUNC_I2C)\n"); return -ENXIO; } ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; mutex_init(&ts->sysfs_mutex); ts->client = client; i2c_set_clientdata(client, ts); ts->avdd = devm_regulator_get(&client->dev, "avdd"); if (IS_ERR(ts->avdd)) return dev_err_probe(&client->dev, PTR_ERR(ts->avdd), "Failed to get 'avdd' regulator\n"); ts->vccio = devm_regulator_get(&client->dev, "vccio"); if (IS_ERR(ts->vccio)) return dev_err_probe(&client->dev, PTR_ERR(ts->vccio), "Failed to get 'vccio' regulator\n"); ts->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(ts->reset_gpio)) return dev_err_probe(&client->dev, PTR_ERR(ts->reset_gpio), "Failed to get reset gpio\n"); error = raydium_i2c_power_on(ts); if (error) return error; error = devm_add_action_or_reset(&client->dev, raydium_i2c_power_off, ts); if (error) { dev_err(&client->dev, "failed to install power off action: %d\n", error); return error; } /* Make sure there is something at this address */ if (i2c_smbus_xfer(client->adapter, client->addr, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0) { dev_err(&client->dev, "nothing at this address\n"); return -ENXIO; } error = raydium_i2c_initialize(ts); if (error) { dev_err(&client->dev, "failed to initialize: %d\n", error); return error; } ts->report_data = devm_kmalloc(&client->dev, ts->pkg_size, GFP_KERNEL); if (!ts->report_data) return -ENOMEM; ts->input = devm_input_allocate_device(&client->dev); if (!ts->input) { dev_err(&client->dev, "Failed to allocate input device\n"); return -ENOMEM; } ts->input->name = "Raydium Touchscreen"; ts->input->id.bustype = BUS_I2C; input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, le16_to_cpu(ts->info.x_max), 0, 0); input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, le16_to_cpu(ts->info.y_max), 0, 0); input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->info.x_res); input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->info.y_res); input_set_abs_params(ts->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(ts->input, ABS_MT_PRESSURE, 0, 255, 0, 0); error = input_mt_init_slots(ts->input, RM_MAX_TOUCH_NUM, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&client->dev, "failed to initialize MT slots: %d\n", error); return error; } error = input_register_device(ts->input); if (error) { dev_err(&client->dev, "unable to register input device: %d\n", error); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, raydium_i2c_irq, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = devm_device_add_group(&client->dev, &raydium_i2c_attribute_group); if (error) { dev_err(&client->dev, "failed to create sysfs attributes: %d\n", error); return error; } return 0; } static void raydium_enter_sleep(struct i2c_client *client) { static const u8 sleep_cmd[] = { 0x5A, 0xff, 0x00, 0x0f }; int error; error = raydium_i2c_send(client, RM_CMD_ENTER_SLEEP, sleep_cmd, sizeof(sleep_cmd)); if (error) dev_err(&client->dev, "sleep command failed: %d\n", error); } static int raydium_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); /* Sleep is not available in BLDR recovery mode */ if (ts->boot_mode != RAYDIUM_TS_MAIN) return -EBUSY; disable_irq(client->irq); if (device_may_wakeup(dev)) { raydium_enter_sleep(client); } else { raydium_i2c_power_off(ts); } return 0; } static int raydium_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct raydium_data *ts = i2c_get_clientdata(client); if (device_may_wakeup(dev)) { raydium_i2c_sw_reset(client); } else { raydium_i2c_power_on(ts); raydium_i2c_initialize(ts); } enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(raydium_i2c_pm_ops, raydium_i2c_suspend, raydium_i2c_resume); static const struct i2c_device_id raydium_i2c_id[] = { { "raydium_i2c", 0 }, { "rm32380", 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, raydium_i2c_id); #ifdef CONFIG_ACPI static const struct acpi_device_id raydium_acpi_id[] = { { "RAYD0001", 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(acpi, raydium_acpi_id); #endif #ifdef CONFIG_OF static const struct of_device_id raydium_of_match[] = { { .compatible = "raydium,rm32380", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, raydium_of_match); #endif static struct i2c_driver raydium_i2c_driver = { .probe = raydium_i2c_probe, .id_table = raydium_i2c_id, .driver = { .name = "raydium_ts", .pm = pm_sleep_ptr(&raydium_i2c_pm_ops), .acpi_match_table = ACPI_PTR(raydium_acpi_id), .of_match_table = of_match_ptr(raydium_of_match), }, }; module_i2c_driver(raydium_i2c_driver); MODULE_AUTHOR("Raydium"); MODULE_DESCRIPTION("Raydium I2c Touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/raydium_i2c_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2015 Broadcom Corporation * */ #include <linux/module.h> #include <linux/init.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/keyboard.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/of.h> #include <asm/irq.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/serio.h> #include <linux/mfd/syscon.h> #include <linux/regmap.h> #define IPROC_TS_NAME "iproc-ts" #define PEN_DOWN_STATUS 1 #define PEN_UP_STATUS 0 #define X_MIN 0 #define Y_MIN 0 #define X_MAX 0xFFF #define Y_MAX 0xFFF /* Value given by controller for invalid coordinate. */ #define INVALID_COORD 0xFFFFFFFF /* Register offsets */ #define REGCTL1 0x00 #define REGCTL2 0x04 #define INTERRUPT_THRES 0x08 #define INTERRUPT_MASK 0x0c #define INTERRUPT_STATUS 0x10 #define CONTROLLER_STATUS 0x14 #define FIFO_DATA 0x18 #define FIFO_DATA_X_Y_MASK 0xFFFF #define ANALOG_CONTROL 0x1c #define AUX_DATA 0x20 #define DEBOUNCE_CNTR_STAT 0x24 #define SCAN_CNTR_STAT 0x28 #define REM_CNTR_STAT 0x2c #define SETTLING_TIMER_STAT 0x30 #define SPARE_REG 0x34 #define SOFT_BYPASS_CONTROL 0x38 #define SOFT_BYPASS_DATA 0x3c /* Bit values for INTERRUPT_MASK and INTERRUPT_STATUS regs */ #define TS_PEN_INTR_MASK BIT(0) #define TS_FIFO_INTR_MASK BIT(2) /* Bit values for CONTROLLER_STATUS reg1 */ #define TS_PEN_DOWN BIT(0) /* Shift values for control reg1 */ #define SCANNING_PERIOD_SHIFT 24 #define DEBOUNCE_TIMEOUT_SHIFT 16 #define SETTLING_TIMEOUT_SHIFT 8 #define TOUCH_TIMEOUT_SHIFT 0 /* Shift values for coordinates from fifo */ #define X_COORD_SHIFT 0 #define Y_COORD_SHIFT 16 /* Bit values for REGCTL2 */ #define TS_CONTROLLER_EN_BIT BIT(16) #define TS_CONTROLLER_AVGDATA_SHIFT 8 #define TS_CONTROLLER_AVGDATA_MASK (0x7 << TS_CONTROLLER_AVGDATA_SHIFT) #define TS_CONTROLLER_PWR_LDO BIT(5) #define TS_CONTROLLER_PWR_ADC BIT(4) #define TS_CONTROLLER_PWR_BGP BIT(3) #define TS_CONTROLLER_PWR_TS BIT(2) #define TS_WIRE_MODE_BIT BIT(1) #define dbg_reg(dev, priv, reg) \ do { \ u32 val; \ regmap_read(priv->regmap, reg, &val); \ dev_dbg(dev, "%20s= 0x%08x\n", #reg, val); \ } while (0) struct tsc_param { /* Each step is 1024 us. Valid 1-256 */ u32 scanning_period; /* Each step is 512 us. Valid 0-255 */ u32 debounce_timeout; /* * The settling duration (in ms) is the amount of time the tsc * waits to allow the voltage to settle after turning on the * drivers in detection mode. Valid values: 0-11 * 0 = 0.008 ms * 1 = 0.01 ms * 2 = 0.02 ms * 3 = 0.04 ms * 4 = 0.08 ms * 5 = 0.16 ms * 6 = 0.32 ms * 7 = 0.64 ms * 8 = 1.28 ms * 9 = 2.56 ms * 10 = 5.12 ms * 11 = 10.24 ms */ u32 settling_timeout; /* touch timeout in sample counts */ u32 touch_timeout; /* * Number of data samples which are averaged before a final data point * is placed into the FIFO */ u32 average_data; /* FIFO threshold */ u32 fifo_threshold; /* Optional standard touchscreen properties. */ u32 max_x; u32 max_y; u32 fuzz_x; u32 fuzz_y; bool invert_x; bool invert_y; }; struct iproc_ts_priv { struct platform_device *pdev; struct input_dev *idev; struct regmap *regmap; struct clk *tsc_clk; int pen_status; struct tsc_param cfg_params; }; /* * Set default values the same as hardware reset values * except for fifo_threshold with is set to 1. */ static const struct tsc_param iproc_default_config = { .scanning_period = 0x5, /* 1 to 256 */ .debounce_timeout = 0x28, /* 0 to 255 */ .settling_timeout = 0x7, /* 0 to 11 */ .touch_timeout = 0xa, /* 0 to 255 */ .average_data = 5, /* entry 5 = 32 pts */ .fifo_threshold = 1, /* 0 to 31 */ .max_x = X_MAX, .max_y = Y_MAX, }; static void ts_reg_dump(struct iproc_ts_priv *priv) { struct device *dev = &priv->pdev->dev; dbg_reg(dev, priv, REGCTL1); dbg_reg(dev, priv, REGCTL2); dbg_reg(dev, priv, INTERRUPT_THRES); dbg_reg(dev, priv, INTERRUPT_MASK); dbg_reg(dev, priv, INTERRUPT_STATUS); dbg_reg(dev, priv, CONTROLLER_STATUS); dbg_reg(dev, priv, FIFO_DATA); dbg_reg(dev, priv, ANALOG_CONTROL); dbg_reg(dev, priv, AUX_DATA); dbg_reg(dev, priv, DEBOUNCE_CNTR_STAT); dbg_reg(dev, priv, SCAN_CNTR_STAT); dbg_reg(dev, priv, REM_CNTR_STAT); dbg_reg(dev, priv, SETTLING_TIMER_STAT); dbg_reg(dev, priv, SPARE_REG); dbg_reg(dev, priv, SOFT_BYPASS_CONTROL); dbg_reg(dev, priv, SOFT_BYPASS_DATA); } static irqreturn_t iproc_touchscreen_interrupt(int irq, void *data) { struct platform_device *pdev = data; struct iproc_ts_priv *priv = platform_get_drvdata(pdev); u32 intr_status; u32 raw_coordinate; u16 x; u16 y; int i; bool needs_sync = false; regmap_read(priv->regmap, INTERRUPT_STATUS, &intr_status); intr_status &= TS_PEN_INTR_MASK | TS_FIFO_INTR_MASK; if (intr_status == 0) return IRQ_NONE; /* Clear all interrupt status bits, write-1-clear */ regmap_write(priv->regmap, INTERRUPT_STATUS, intr_status); /* Pen up/down */ if (intr_status & TS_PEN_INTR_MASK) { regmap_read(priv->regmap, CONTROLLER_STATUS, &priv->pen_status); if (priv->pen_status & TS_PEN_DOWN) priv->pen_status = PEN_DOWN_STATUS; else priv->pen_status = PEN_UP_STATUS; input_report_key(priv->idev, BTN_TOUCH, priv->pen_status); needs_sync = true; dev_dbg(&priv->pdev->dev, "pen up-down (%d)\n", priv->pen_status); } /* coordinates in FIFO exceed the theshold */ if (intr_status & TS_FIFO_INTR_MASK) { for (i = 0; i < priv->cfg_params.fifo_threshold; i++) { regmap_read(priv->regmap, FIFO_DATA, &raw_coordinate); if (raw_coordinate == INVALID_COORD) continue; /* * The x and y coordinate are 16 bits each * with the x in the lower 16 bits and y in the * upper 16 bits. */ x = (raw_coordinate >> X_COORD_SHIFT) & FIFO_DATA_X_Y_MASK; y = (raw_coordinate >> Y_COORD_SHIFT) & FIFO_DATA_X_Y_MASK; /* We only want to retain the 12 msb of the 16 */ x = (x >> 4) & 0x0FFF; y = (y >> 4) & 0x0FFF; /* Adjust x y according to LCD tsc mount angle. */ if (priv->cfg_params.invert_x) x = priv->cfg_params.max_x - x; if (priv->cfg_params.invert_y) y = priv->cfg_params.max_y - y; input_report_abs(priv->idev, ABS_X, x); input_report_abs(priv->idev, ABS_Y, y); needs_sync = true; dev_dbg(&priv->pdev->dev, "xy (0x%x 0x%x)\n", x, y); } } if (needs_sync) input_sync(priv->idev); return IRQ_HANDLED; } static int iproc_ts_start(struct input_dev *idev) { u32 val; u32 mask; int error; struct iproc_ts_priv *priv = input_get_drvdata(idev); /* Enable clock */ error = clk_prepare_enable(priv->tsc_clk); if (error) { dev_err(&priv->pdev->dev, "%s clk_prepare_enable failed %d\n", __func__, error); return error; } /* * Interrupt is generated when: * FIFO reaches the int_th value, and pen event(up/down) */ val = TS_PEN_INTR_MASK | TS_FIFO_INTR_MASK; regmap_update_bits(priv->regmap, INTERRUPT_MASK, val, val); val = priv->cfg_params.fifo_threshold; regmap_write(priv->regmap, INTERRUPT_THRES, val); /* Initialize control reg1 */ val = 0; val |= priv->cfg_params.scanning_period << SCANNING_PERIOD_SHIFT; val |= priv->cfg_params.debounce_timeout << DEBOUNCE_TIMEOUT_SHIFT; val |= priv->cfg_params.settling_timeout << SETTLING_TIMEOUT_SHIFT; val |= priv->cfg_params.touch_timeout << TOUCH_TIMEOUT_SHIFT; regmap_write(priv->regmap, REGCTL1, val); /* Try to clear all interrupt status */ val = TS_FIFO_INTR_MASK | TS_PEN_INTR_MASK; regmap_update_bits(priv->regmap, INTERRUPT_STATUS, val, val); /* Initialize control reg2 */ val = TS_CONTROLLER_EN_BIT | TS_WIRE_MODE_BIT; val |= priv->cfg_params.average_data << TS_CONTROLLER_AVGDATA_SHIFT; mask = (TS_CONTROLLER_AVGDATA_MASK); mask |= (TS_CONTROLLER_PWR_LDO | /* PWR up LDO */ TS_CONTROLLER_PWR_ADC | /* PWR up ADC */ TS_CONTROLLER_PWR_BGP | /* PWR up BGP */ TS_CONTROLLER_PWR_TS); /* PWR up TS */ mask |= val; regmap_update_bits(priv->regmap, REGCTL2, mask, val); ts_reg_dump(priv); return 0; } static void iproc_ts_stop(struct input_dev *dev) { u32 val; struct iproc_ts_priv *priv = input_get_drvdata(dev); /* * Disable FIFO int_th and pen event(up/down)Interrupts only * as the interrupt mask register is shared between ADC, TS and * flextimer. */ val = TS_PEN_INTR_MASK | TS_FIFO_INTR_MASK; regmap_update_bits(priv->regmap, INTERRUPT_MASK, val, 0); /* Only power down touch screen controller */ val = TS_CONTROLLER_PWR_TS; regmap_update_bits(priv->regmap, REGCTL2, val, val); clk_disable(priv->tsc_clk); } static int iproc_get_tsc_config(struct device *dev, struct iproc_ts_priv *priv) { struct device_node *np = dev->of_node; u32 val; priv->cfg_params = iproc_default_config; if (!np) return 0; if (of_property_read_u32(np, "scanning_period", &val) >= 0) { if (val < 1 || val > 256) { dev_err(dev, "scanning_period (%u) must be [1-256]\n", val); return -EINVAL; } priv->cfg_params.scanning_period = val; } if (of_property_read_u32(np, "debounce_timeout", &val) >= 0) { if (val > 255) { dev_err(dev, "debounce_timeout (%u) must be [0-255]\n", val); return -EINVAL; } priv->cfg_params.debounce_timeout = val; } if (of_property_read_u32(np, "settling_timeout", &val) >= 0) { if (val > 11) { dev_err(dev, "settling_timeout (%u) must be [0-11]\n", val); return -EINVAL; } priv->cfg_params.settling_timeout = val; } if (of_property_read_u32(np, "touch_timeout", &val) >= 0) { if (val > 255) { dev_err(dev, "touch_timeout (%u) must be [0-255]\n", val); return -EINVAL; } priv->cfg_params.touch_timeout = val; } if (of_property_read_u32(np, "average_data", &val) >= 0) { if (val > 8) { dev_err(dev, "average_data (%u) must be [0-8]\n", val); return -EINVAL; } priv->cfg_params.average_data = val; } if (of_property_read_u32(np, "fifo_threshold", &val) >= 0) { if (val > 31) { dev_err(dev, "fifo_threshold (%u)) must be [0-31]\n", val); return -EINVAL; } priv->cfg_params.fifo_threshold = val; } /* Parse optional properties. */ of_property_read_u32(np, "touchscreen-size-x", &priv->cfg_params.max_x); of_property_read_u32(np, "touchscreen-size-y", &priv->cfg_params.max_y); of_property_read_u32(np, "touchscreen-fuzz-x", &priv->cfg_params.fuzz_x); of_property_read_u32(np, "touchscreen-fuzz-y", &priv->cfg_params.fuzz_y); priv->cfg_params.invert_x = of_property_read_bool(np, "touchscreen-inverted-x"); priv->cfg_params.invert_y = of_property_read_bool(np, "touchscreen-inverted-y"); return 0; } static int iproc_ts_probe(struct platform_device *pdev) { struct iproc_ts_priv *priv; struct input_dev *idev; int irq; int error; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; /* touchscreen controller memory mapped regs via syscon*/ priv->regmap = syscon_regmap_lookup_by_phandle(pdev->dev.of_node, "ts_syscon"); if (IS_ERR(priv->regmap)) { error = PTR_ERR(priv->regmap); dev_err(&pdev->dev, "unable to map I/O memory:%d\n", error); return error; } priv->tsc_clk = devm_clk_get(&pdev->dev, "tsc_clk"); if (IS_ERR(priv->tsc_clk)) { error = PTR_ERR(priv->tsc_clk); dev_err(&pdev->dev, "failed getting clock tsc_clk: %d\n", error); return error; } priv->pdev = pdev; error = iproc_get_tsc_config(&pdev->dev, priv); if (error) { dev_err(&pdev->dev, "get_tsc_config failed: %d\n", error); return error; } idev = devm_input_allocate_device(&pdev->dev); if (!idev) { dev_err(&pdev->dev, "failed to allocate input device\n"); return -ENOMEM; } priv->idev = idev; priv->pen_status = PEN_UP_STATUS; /* Set input device info */ idev->name = IPROC_TS_NAME; idev->dev.parent = &pdev->dev; idev->id.bustype = BUS_HOST; idev->id.vendor = SERIO_UNKNOWN; idev->id.product = 0; idev->id.version = 0; idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); __set_bit(BTN_TOUCH, idev->keybit); input_set_abs_params(idev, ABS_X, X_MIN, priv->cfg_params.max_x, priv->cfg_params.fuzz_x, 0); input_set_abs_params(idev, ABS_Y, Y_MIN, priv->cfg_params.max_y, priv->cfg_params.fuzz_y, 0); idev->open = iproc_ts_start; idev->close = iproc_ts_stop; input_set_drvdata(idev, priv); platform_set_drvdata(pdev, priv); /* get interrupt */ irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; error = devm_request_irq(&pdev->dev, irq, iproc_touchscreen_interrupt, IRQF_SHARED, IPROC_TS_NAME, pdev); if (error) return error; error = input_register_device(priv->idev); if (error) { dev_err(&pdev->dev, "failed to register input device: %d\n", error); return error; } return 0; } static const struct of_device_id iproc_ts_of_match[] = { {.compatible = "brcm,iproc-touchscreen", }, { }, }; MODULE_DEVICE_TABLE(of, iproc_ts_of_match); static struct platform_driver iproc_ts_driver = { .probe = iproc_ts_probe, .driver = { .name = IPROC_TS_NAME, .of_match_table = iproc_ts_of_match, }, }; module_platform_driver(iproc_ts_driver); MODULE_DESCRIPTION("IPROC Touchscreen driver"); MODULE_AUTHOR("Broadcom"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/bcm_iproc_tsc.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for ChipOne icn8505 i2c touchscreen controller * * Copyright (c) 2015-2018 Red Hat Inc. * * Red Hat authors: * Hans de Goede <[email protected]> */ #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/crc32.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/module.h> /* Normal operation mode defines */ #define ICN8505_REG_ADDR_WIDTH 16 #define ICN8505_REG_POWER 0x0004 #define ICN8505_REG_TOUCHDATA 0x1000 #define ICN8505_REG_CONFIGDATA 0x8000 /* ICN8505_REG_POWER commands */ #define ICN8505_POWER_ACTIVE 0x00 #define ICN8505_POWER_MONITOR 0x01 #define ICN8505_POWER_HIBERNATE 0x02 /* * The Android driver uses these to turn on/off the charger filter, but the * filter is way too aggressive making e.g. onscreen keyboards unusable. */ #define ICN8505_POWER_ENA_CHARGER_MODE 0x55 #define ICN8505_POWER_DIS_CHARGER_MODE 0x66 #define ICN8505_MAX_TOUCHES 10 /* Programming mode defines */ #define ICN8505_PROG_I2C_ADDR 0x30 #define ICN8505_PROG_REG_ADDR_WIDTH 24 #define MAX_FW_UPLOAD_TRIES 3 struct icn8505_touch { u8 slot; u8 x[2]; u8 y[2]; u8 pressure; /* Seems more like finger width then pressure really */ u8 event; /* The difference between 2 and 3 is unclear */ #define ICN8505_EVENT_NO_DATA 1 /* No finger seen yet since wakeup */ #define ICN8505_EVENT_UPDATE1 2 /* New or updated coordinates */ #define ICN8505_EVENT_UPDATE2 3 /* New or updated coordinates */ #define ICN8505_EVENT_END 4 /* Finger lifted */ } __packed; struct icn8505_touch_data { u8 softbutton; u8 touch_count; struct icn8505_touch touches[ICN8505_MAX_TOUCHES]; } __packed; struct icn8505_data { struct i2c_client *client; struct input_dev *input; struct gpio_desc *wake_gpio; struct touchscreen_properties prop; char firmware_name[32]; }; static int icn8505_read_xfer(struct i2c_client *client, u16 i2c_addr, int reg_addr, int reg_addr_width, void *data, int len, bool silent) { u8 buf[3]; int i, ret; struct i2c_msg msg[2] = { { .addr = i2c_addr, .buf = buf, .len = reg_addr_width / 8, }, { .addr = i2c_addr, .flags = I2C_M_RD, .buf = data, .len = len, } }; for (i = 0; i < (reg_addr_width / 8); i++) buf[i] = (reg_addr >> (reg_addr_width - (i + 1) * 8)) & 0xff; ret = i2c_transfer(client->adapter, msg, 2); if (ret != ARRAY_SIZE(msg)) { if (ret >= 0) ret = -EIO; if (!silent) dev_err(&client->dev, "Error reading addr %#x reg %#x: %d\n", i2c_addr, reg_addr, ret); return ret; } return 0; } static int icn8505_write_xfer(struct i2c_client *client, u16 i2c_addr, int reg_addr, int reg_addr_width, const void *data, int len, bool silent) { u8 buf[3 + 32]; /* 3 bytes for 24 bit reg-addr + 32 bytes max len */ int i, ret; struct i2c_msg msg = { .addr = i2c_addr, .buf = buf, .len = reg_addr_width / 8 + len, }; if (WARN_ON(len > 32)) return -EINVAL; for (i = 0; i < (reg_addr_width / 8); i++) buf[i] = (reg_addr >> (reg_addr_width - (i + 1) * 8)) & 0xff; memcpy(buf + reg_addr_width / 8, data, len); ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) { if (ret >= 0) ret = -EIO; if (!silent) dev_err(&client->dev, "Error writing addr %#x reg %#x: %d\n", i2c_addr, reg_addr, ret); return ret; } return 0; } static int icn8505_read_data(struct icn8505_data *icn8505, int reg, void *buf, int len) { return icn8505_read_xfer(icn8505->client, icn8505->client->addr, reg, ICN8505_REG_ADDR_WIDTH, buf, len, false); } static int icn8505_read_reg_silent(struct icn8505_data *icn8505, int reg) { u8 buf; int error; error = icn8505_read_xfer(icn8505->client, icn8505->client->addr, reg, ICN8505_REG_ADDR_WIDTH, &buf, 1, true); if (error) return error; return buf; } static int icn8505_write_reg(struct icn8505_data *icn8505, int reg, u8 val) { return icn8505_write_xfer(icn8505->client, icn8505->client->addr, reg, ICN8505_REG_ADDR_WIDTH, &val, 1, false); } static int icn8505_read_prog_data(struct icn8505_data *icn8505, int reg, void *buf, int len) { return icn8505_read_xfer(icn8505->client, ICN8505_PROG_I2C_ADDR, reg, ICN8505_PROG_REG_ADDR_WIDTH, buf, len, false); } static int icn8505_write_prog_data(struct icn8505_data *icn8505, int reg, const void *buf, int len) { return icn8505_write_xfer(icn8505->client, ICN8505_PROG_I2C_ADDR, reg, ICN8505_PROG_REG_ADDR_WIDTH, buf, len, false); } static int icn8505_write_prog_reg(struct icn8505_data *icn8505, int reg, u8 val) { return icn8505_write_xfer(icn8505->client, ICN8505_PROG_I2C_ADDR, reg, ICN8505_PROG_REG_ADDR_WIDTH, &val, 1, false); } /* * Note this function uses a number of magic register addresses and values, * there are deliberately no defines for these because the algorithm is taken * from the icn85xx Android driver and I do not want to make up possibly wrong * names for the addresses and/or values. */ static int icn8505_try_fw_upload(struct icn8505_data *icn8505, const struct firmware *fw) { struct device *dev = &icn8505->client->dev; size_t offset, count; int error; u8 buf[4]; u32 crc; /* Put the controller in programming mode */ error = icn8505_write_prog_reg(icn8505, 0xcc3355, 0x5a); if (error) return error; usleep_range(2000, 5000); error = icn8505_write_prog_reg(icn8505, 0x040400, 0x01); if (error) return error; usleep_range(2000, 5000); error = icn8505_read_prog_data(icn8505, 0x040002, buf, 1); if (error) return error; if (buf[0] != 0x85) { dev_err(dev, "Failed to enter programming mode\n"); return -ENODEV; } usleep_range(1000, 5000); /* Enable CRC mode */ error = icn8505_write_prog_reg(icn8505, 0x40028, 1); if (error) return error; /* Send the firmware to SRAM */ for (offset = 0; offset < fw->size; offset += count) { count = min_t(size_t, fw->size - offset, 32); error = icn8505_write_prog_data(icn8505, offset, fw->data + offset, count); if (error) return error; } /* Disable CRC mode */ error = icn8505_write_prog_reg(icn8505, 0x40028, 0); if (error) return error; /* Get and check length and CRC */ error = icn8505_read_prog_data(icn8505, 0x40034, buf, 2); if (error) return error; if (get_unaligned_le16(buf) != fw->size) { dev_warn(dev, "Length mismatch after uploading fw\n"); return -EIO; } error = icn8505_read_prog_data(icn8505, 0x4002c, buf, 4); if (error) return error; crc = crc32_be(0, fw->data, fw->size); if (get_unaligned_le32(buf) != crc) { dev_warn(dev, "CRC mismatch after uploading fw\n"); return -EIO; } /* Boot controller from SRAM */ error = icn8505_write_prog_reg(icn8505, 0x40400, 0x03); if (error) return error; usleep_range(2000, 5000); return 0; } static int icn8505_upload_fw(struct icn8505_data *icn8505) { struct device *dev = &icn8505->client->dev; const struct firmware *fw; int i, error; /* * Always load the firmware, even if we don't need it at boot, we * we may need it at resume. Having loaded it once will make the * firmware class code cache it at suspend/resume. */ error = firmware_request_platform(&fw, icn8505->firmware_name, dev); if (error) { dev_err(dev, "Firmware request error %d\n", error); return error; } /* Check if the controller is not already up and running */ if (icn8505_read_reg_silent(icn8505, 0x000a) == 0x85) goto success; for (i = 1; i <= MAX_FW_UPLOAD_TRIES; i++) { error = icn8505_try_fw_upload(icn8505, fw); if (!error) goto success; dev_err(dev, "Failed to upload firmware: %d (attempt %d/%d)\n", error, i, MAX_FW_UPLOAD_TRIES); usleep_range(2000, 5000); } success: release_firmware(fw); return error; } static bool icn8505_touch_active(u8 event) { return event == ICN8505_EVENT_UPDATE1 || event == ICN8505_EVENT_UPDATE2; } static irqreturn_t icn8505_irq(int irq, void *dev_id) { struct icn8505_data *icn8505 = dev_id; struct device *dev = &icn8505->client->dev; struct icn8505_touch_data touch_data; int i, error; error = icn8505_read_data(icn8505, ICN8505_REG_TOUCHDATA, &touch_data, sizeof(touch_data)); if (error) { dev_err(dev, "Error reading touch data: %d\n", error); return IRQ_HANDLED; } if (touch_data.touch_count > ICN8505_MAX_TOUCHES) { dev_warn(dev, "Too many touches %d > %d\n", touch_data.touch_count, ICN8505_MAX_TOUCHES); touch_data.touch_count = ICN8505_MAX_TOUCHES; } for (i = 0; i < touch_data.touch_count; i++) { struct icn8505_touch *touch = &touch_data.touches[i]; bool act = icn8505_touch_active(touch->event); input_mt_slot(icn8505->input, touch->slot); input_mt_report_slot_state(icn8505->input, MT_TOOL_FINGER, act); if (!act) continue; touchscreen_report_pos(icn8505->input, &icn8505->prop, get_unaligned_le16(touch->x), get_unaligned_le16(touch->y), true); } input_mt_sync_frame(icn8505->input); input_report_key(icn8505->input, KEY_LEFTMETA, touch_data.softbutton == 1); input_sync(icn8505->input); return IRQ_HANDLED; } static int icn8505_probe_acpi(struct icn8505_data *icn8505, struct device *dev) { const char *subsys; int error; subsys = acpi_get_subsystem_id(ACPI_HANDLE(dev)); error = PTR_ERR_OR_ZERO(subsys); if (error == -ENODATA) subsys = "unknown"; else if (error) return error; snprintf(icn8505->firmware_name, sizeof(icn8505->firmware_name), "chipone/icn8505-%s.fw", subsys); kfree_const(subsys); return 0; } static int icn8505_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct icn8505_data *icn8505; struct input_dev *input; __le16 resolution[2]; int error; if (!client->irq) { dev_err(dev, "No irq specified\n"); return -EINVAL; } icn8505 = devm_kzalloc(dev, sizeof(*icn8505), GFP_KERNEL); if (!icn8505) return -ENOMEM; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = client->name; input->id.bustype = BUS_I2C; input_set_capability(input, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input, EV_ABS, ABS_MT_POSITION_Y); input_set_capability(input, EV_KEY, KEY_LEFTMETA); icn8505->client = client; icn8505->input = input; input_set_drvdata(input, icn8505); error = icn8505_probe_acpi(icn8505, dev); if (error) return error; error = icn8505_upload_fw(icn8505); if (error) return error; error = icn8505_read_data(icn8505, ICN8505_REG_CONFIGDATA, resolution, sizeof(resolution)); if (error) { dev_err(dev, "Error reading resolution: %d\n", error); return error; } input_set_abs_params(input, ABS_MT_POSITION_X, 0, le16_to_cpu(resolution[0]) - 1, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, le16_to_cpu(resolution[1]) - 1, 0, 0); touchscreen_parse_properties(input, true, &icn8505->prop); if (!input_abs_get_max(input, ABS_MT_POSITION_X) || !input_abs_get_max(input, ABS_MT_POSITION_Y)) { dev_err(dev, "Error touchscreen-size-x and/or -y missing\n"); return -EINVAL; } error = input_mt_init_slots(input, ICN8505_MAX_TOUCHES, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; error = devm_request_threaded_irq(dev, client->irq, NULL, icn8505_irq, IRQF_ONESHOT, client->name, icn8505); if (error) { dev_err(dev, "Error requesting irq: %d\n", error); return error; } error = input_register_device(input); if (error) return error; i2c_set_clientdata(client, icn8505); return 0; } static int icn8505_suspend(struct device *dev) { struct icn8505_data *icn8505 = i2c_get_clientdata(to_i2c_client(dev)); disable_irq(icn8505->client->irq); icn8505_write_reg(icn8505, ICN8505_REG_POWER, ICN8505_POWER_HIBERNATE); return 0; } static int icn8505_resume(struct device *dev) { struct icn8505_data *icn8505 = i2c_get_clientdata(to_i2c_client(dev)); int error; error = icn8505_upload_fw(icn8505); if (error) return error; enable_irq(icn8505->client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(icn8505_pm_ops, icn8505_suspend, icn8505_resume); static const struct acpi_device_id icn8505_acpi_match[] = { { "CHPN0001" }, { } }; MODULE_DEVICE_TABLE(acpi, icn8505_acpi_match); static struct i2c_driver icn8505_driver = { .driver = { .name = "chipone_icn8505", .pm = pm_sleep_ptr(&icn8505_pm_ops), .acpi_match_table = icn8505_acpi_match, }, .probe = icn8505_probe, }; module_i2c_driver(icn8505_driver); MODULE_DESCRIPTION("ChipOne icn8505 I2C Touchscreen Driver"); MODULE_AUTHOR("Hans de Goede <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/chipone_icn8505.c
// SPDX-License-Identifier: GPL-2.0+ /* * Azoteq IQS550/572/525 Trackpad/Touchscreen Controller * * Copyright (C) 2018 Jeff LaBundy <[email protected]> * * These devices require firmware exported from a PC-based configuration tool * made available by the vendor. Firmware files may be pushed to the device's * nonvolatile memory by writing the filename to the 'fw_file' sysfs control. * * Link to PC-based configuration tool and datasheet: https://www.azoteq.com/ */ #include <linux/bits.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/slab.h> #include <asm/unaligned.h> #define IQS5XX_FW_FILE_LEN 64 #define IQS5XX_NUM_RETRIES 10 #define IQS5XX_NUM_CONTACTS 5 #define IQS5XX_WR_BYTES_MAX 2 #define IQS5XX_PROD_NUM_IQS550 40 #define IQS5XX_PROD_NUM_IQS572 58 #define IQS5XX_PROD_NUM_IQS525 52 #define IQS5XX_SHOW_RESET BIT(7) #define IQS5XX_ACK_RESET BIT(7) #define IQS5XX_SUSPEND BIT(0) #define IQS5XX_RESUME 0 #define IQS5XX_SETUP_COMPLETE BIT(6) #define IQS5XX_WDT BIT(5) #define IQS5XX_ALP_REATI BIT(3) #define IQS5XX_REATI BIT(2) #define IQS5XX_TP_EVENT BIT(2) #define IQS5XX_EVENT_MODE BIT(0) #define IQS5XX_PROD_NUM 0x0000 #define IQS5XX_SYS_INFO0 0x000F #define IQS5XX_SYS_INFO1 0x0010 #define IQS5XX_SYS_CTRL0 0x0431 #define IQS5XX_SYS_CTRL1 0x0432 #define IQS5XX_SYS_CFG0 0x058E #define IQS5XX_SYS_CFG1 0x058F #define IQS5XX_X_RES 0x066E #define IQS5XX_Y_RES 0x0670 #define IQS5XX_EXP_FILE 0x0677 #define IQS5XX_CHKSM 0x83C0 #define IQS5XX_APP 0x8400 #define IQS5XX_CSTM 0xBE00 #define IQS5XX_PMAP_END 0xBFFF #define IQS5XX_END_COMM 0xEEEE #define IQS5XX_CHKSM_LEN (IQS5XX_APP - IQS5XX_CHKSM) #define IQS5XX_APP_LEN (IQS5XX_CSTM - IQS5XX_APP) #define IQS5XX_CSTM_LEN (IQS5XX_PMAP_END + 1 - IQS5XX_CSTM) #define IQS5XX_PMAP_LEN (IQS5XX_PMAP_END + 1 - IQS5XX_CHKSM) #define IQS5XX_REC_HDR_LEN 4 #define IQS5XX_REC_LEN_MAX 255 #define IQS5XX_REC_TYPE_DATA 0x00 #define IQS5XX_REC_TYPE_EOF 0x01 #define IQS5XX_BL_ADDR_MASK 0x40 #define IQS5XX_BL_CMD_VER 0x00 #define IQS5XX_BL_CMD_READ 0x01 #define IQS5XX_BL_CMD_EXEC 0x02 #define IQS5XX_BL_CMD_CRC 0x03 #define IQS5XX_BL_BLK_LEN_MAX 64 #define IQS5XX_BL_ID 0x0200 #define IQS5XX_BL_STATUS_NONE 0xEE #define IQS5XX_BL_CRC_PASS 0x00 #define IQS5XX_BL_CRC_FAIL 0x01 #define IQS5XX_BL_ATTEMPTS 3 struct iqs5xx_dev_id_info { __be16 prod_num; __be16 proj_num; u8 major_ver; u8 minor_ver; u8 bl_status; } __packed; struct iqs5xx_ihex_rec { char start; char len[2]; char addr[4]; char type[2]; char data[2]; } __packed; struct iqs5xx_touch_data { __be16 abs_x; __be16 abs_y; __be16 strength; u8 area; } __packed; struct iqs5xx_status { u8 sys_info[2]; u8 num_active; __be16 rel_x; __be16 rel_y; struct iqs5xx_touch_data touch_data[IQS5XX_NUM_CONTACTS]; } __packed; struct iqs5xx_private { struct i2c_client *client; struct input_dev *input; struct gpio_desc *reset_gpio; struct touchscreen_properties prop; struct mutex lock; struct iqs5xx_dev_id_info dev_id_info; u8 exp_file[2]; }; static int iqs5xx_read_burst(struct i2c_client *client, u16 reg, void *val, u16 len) { __be16 reg_buf = cpu_to_be16(reg); int ret, i; struct i2c_msg msg[] = { { .addr = client->addr, .flags = 0, .len = sizeof(reg_buf), .buf = (u8 *)&reg_buf, }, { .addr = client->addr, .flags = I2C_M_RD, .len = len, .buf = (u8 *)val, }, }; /* * The first addressing attempt outside of a communication window fails * and must be retried, after which the device clock stretches until it * is available. */ for (i = 0; i < IQS5XX_NUM_RETRIES; i++) { ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret == ARRAY_SIZE(msg)) return 0; usleep_range(200, 300); } if (ret >= 0) ret = -EIO; dev_err(&client->dev, "Failed to read from address 0x%04X: %d\n", reg, ret); return ret; } static int iqs5xx_read_word(struct i2c_client *client, u16 reg, u16 *val) { __be16 val_buf; int error; error = iqs5xx_read_burst(client, reg, &val_buf, sizeof(val_buf)); if (error) return error; *val = be16_to_cpu(val_buf); return 0; } static int iqs5xx_write_burst(struct i2c_client *client, u16 reg, const void *val, u16 len) { int ret, i; u16 mlen = sizeof(reg) + len; u8 mbuf[sizeof(reg) + IQS5XX_WR_BYTES_MAX]; if (len > IQS5XX_WR_BYTES_MAX) return -EINVAL; put_unaligned_be16(reg, mbuf); memcpy(mbuf + sizeof(reg), val, len); /* * The first addressing attempt outside of a communication window fails * and must be retried, after which the device clock stretches until it * is available. */ for (i = 0; i < IQS5XX_NUM_RETRIES; i++) { ret = i2c_master_send(client, mbuf, mlen); if (ret == mlen) return 0; usleep_range(200, 300); } if (ret >= 0) ret = -EIO; dev_err(&client->dev, "Failed to write to address 0x%04X: %d\n", reg, ret); return ret; } static int iqs5xx_write_word(struct i2c_client *client, u16 reg, u16 val) { __be16 val_buf = cpu_to_be16(val); return iqs5xx_write_burst(client, reg, &val_buf, sizeof(val_buf)); } static int iqs5xx_write_byte(struct i2c_client *client, u16 reg, u8 val) { return iqs5xx_write_burst(client, reg, &val, sizeof(val)); } static void iqs5xx_reset(struct i2c_client *client) { struct iqs5xx_private *iqs5xx = i2c_get_clientdata(client); gpiod_set_value_cansleep(iqs5xx->reset_gpio, 1); usleep_range(200, 300); gpiod_set_value_cansleep(iqs5xx->reset_gpio, 0); } static int iqs5xx_bl_cmd(struct i2c_client *client, u8 bl_cmd, u16 bl_addr) { struct i2c_msg msg; int ret; u8 mbuf[sizeof(bl_cmd) + sizeof(bl_addr)]; msg.addr = client->addr ^ IQS5XX_BL_ADDR_MASK; msg.flags = 0; msg.len = sizeof(bl_cmd); msg.buf = mbuf; *mbuf = bl_cmd; switch (bl_cmd) { case IQS5XX_BL_CMD_VER: case IQS5XX_BL_CMD_CRC: case IQS5XX_BL_CMD_EXEC: break; case IQS5XX_BL_CMD_READ: msg.len += sizeof(bl_addr); put_unaligned_be16(bl_addr, mbuf + sizeof(bl_cmd)); break; default: return -EINVAL; } ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) goto msg_fail; switch (bl_cmd) { case IQS5XX_BL_CMD_VER: msg.len = sizeof(u16); break; case IQS5XX_BL_CMD_CRC: msg.len = sizeof(u8); /* * This delay saves the bus controller the trouble of having to * tolerate a relatively long clock-stretching period while the * CRC is calculated. */ msleep(50); break; case IQS5XX_BL_CMD_EXEC: usleep_range(10000, 10100); fallthrough; default: return 0; } msg.flags = I2C_M_RD; ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) goto msg_fail; if (bl_cmd == IQS5XX_BL_CMD_VER && get_unaligned_be16(mbuf) != IQS5XX_BL_ID) { dev_err(&client->dev, "Unrecognized bootloader ID: 0x%04X\n", get_unaligned_be16(mbuf)); return -EINVAL; } if (bl_cmd == IQS5XX_BL_CMD_CRC && *mbuf != IQS5XX_BL_CRC_PASS) { dev_err(&client->dev, "Bootloader CRC failed\n"); return -EIO; } return 0; msg_fail: if (ret >= 0) ret = -EIO; if (bl_cmd != IQS5XX_BL_CMD_VER) dev_err(&client->dev, "Unsuccessful bootloader command 0x%02X: %d\n", bl_cmd, ret); return ret; } static int iqs5xx_bl_open(struct i2c_client *client) { int error, i, j; /* * The device opens a bootloader polling window for 2 ms following the * release of reset. If the host cannot establish communication during * this time frame, it must cycle reset again. */ for (i = 0; i < IQS5XX_BL_ATTEMPTS; i++) { iqs5xx_reset(client); usleep_range(350, 400); for (j = 0; j < IQS5XX_NUM_RETRIES; j++) { error = iqs5xx_bl_cmd(client, IQS5XX_BL_CMD_VER, 0); if (!error) usleep_range(10000, 10100); else if (error != -EINVAL) continue; return error; } } dev_err(&client->dev, "Failed to open bootloader: %d\n", error); return error; } static int iqs5xx_bl_write(struct i2c_client *client, u16 bl_addr, u8 *pmap_data, u16 pmap_len) { struct i2c_msg msg; int ret, i; u8 mbuf[sizeof(bl_addr) + IQS5XX_BL_BLK_LEN_MAX]; if (pmap_len % IQS5XX_BL_BLK_LEN_MAX) return -EINVAL; msg.addr = client->addr ^ IQS5XX_BL_ADDR_MASK; msg.flags = 0; msg.len = sizeof(mbuf); msg.buf = mbuf; for (i = 0; i < pmap_len; i += IQS5XX_BL_BLK_LEN_MAX) { put_unaligned_be16(bl_addr + i, mbuf); memcpy(mbuf + sizeof(bl_addr), pmap_data + i, sizeof(mbuf) - sizeof(bl_addr)); ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) goto msg_fail; usleep_range(10000, 10100); } return 0; msg_fail: if (ret >= 0) ret = -EIO; dev_err(&client->dev, "Failed to write block at address 0x%04X: %d\n", bl_addr + i, ret); return ret; } static int iqs5xx_bl_verify(struct i2c_client *client, u16 bl_addr, u8 *pmap_data, u16 pmap_len) { struct i2c_msg msg; int ret, i; u8 bl_data[IQS5XX_BL_BLK_LEN_MAX]; if (pmap_len % IQS5XX_BL_BLK_LEN_MAX) return -EINVAL; msg.addr = client->addr ^ IQS5XX_BL_ADDR_MASK; msg.flags = I2C_M_RD; msg.len = sizeof(bl_data); msg.buf = bl_data; for (i = 0; i < pmap_len; i += IQS5XX_BL_BLK_LEN_MAX) { ret = iqs5xx_bl_cmd(client, IQS5XX_BL_CMD_READ, bl_addr + i); if (ret) return ret; ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) goto msg_fail; if (memcmp(bl_data, pmap_data + i, sizeof(bl_data))) { dev_err(&client->dev, "Failed to verify block at address 0x%04X\n", bl_addr + i); return -EIO; } } return 0; msg_fail: if (ret >= 0) ret = -EIO; dev_err(&client->dev, "Failed to read block at address 0x%04X: %d\n", bl_addr + i, ret); return ret; } static int iqs5xx_set_state(struct i2c_client *client, u8 state) { struct iqs5xx_private *iqs5xx = i2c_get_clientdata(client); int error1, error2; if (!iqs5xx->dev_id_info.bl_status) return 0; mutex_lock(&iqs5xx->lock); /* * Addressing the device outside of a communication window prompts it * to assert the RDY output, so disable the interrupt line to prevent * the handler from servicing a false interrupt. */ disable_irq(client->irq); error1 = iqs5xx_write_byte(client, IQS5XX_SYS_CTRL1, state); error2 = iqs5xx_write_byte(client, IQS5XX_END_COMM, 0); usleep_range(50, 100); enable_irq(client->irq); mutex_unlock(&iqs5xx->lock); if (error1) return error1; return error2; } static int iqs5xx_open(struct input_dev *input) { struct iqs5xx_private *iqs5xx = input_get_drvdata(input); return iqs5xx_set_state(iqs5xx->client, IQS5XX_RESUME); } static void iqs5xx_close(struct input_dev *input) { struct iqs5xx_private *iqs5xx = input_get_drvdata(input); iqs5xx_set_state(iqs5xx->client, IQS5XX_SUSPEND); } static int iqs5xx_axis_init(struct i2c_client *client) { struct iqs5xx_private *iqs5xx = i2c_get_clientdata(client); struct touchscreen_properties *prop = &iqs5xx->prop; struct input_dev *input = iqs5xx->input; u16 max_x, max_y; int error; if (!input) { input = devm_input_allocate_device(&client->dev); if (!input) return -ENOMEM; input->name = client->name; input->id.bustype = BUS_I2C; input->open = iqs5xx_open; input->close = iqs5xx_close; input_set_drvdata(input, iqs5xx); iqs5xx->input = input; } error = iqs5xx_read_word(client, IQS5XX_X_RES, &max_x); if (error) return error; error = iqs5xx_read_word(client, IQS5XX_Y_RES, &max_y); if (error) return error; input_set_abs_params(input, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, max_y, 0, 0); input_set_abs_params(input, ABS_MT_PRESSURE, 0, U16_MAX, 0, 0); touchscreen_parse_properties(input, true, prop); /* * The device reserves 0xFFFF for coordinates that correspond to slots * which are not in a state of touch. */ if (prop->max_x >= U16_MAX || prop->max_y >= U16_MAX) { dev_err(&client->dev, "Invalid touchscreen size: %u*%u\n", prop->max_x, prop->max_y); return -EINVAL; } if (prop->max_x != max_x) { error = iqs5xx_write_word(client, IQS5XX_X_RES, prop->max_x); if (error) return error; } if (prop->max_y != max_y) { error = iqs5xx_write_word(client, IQS5XX_Y_RES, prop->max_y); if (error) return error; } error = input_mt_init_slots(input, IQS5XX_NUM_CONTACTS, INPUT_MT_DIRECT); if (error) dev_err(&client->dev, "Failed to initialize slots: %d\n", error); return error; } static int iqs5xx_dev_init(struct i2c_client *client) { struct iqs5xx_private *iqs5xx = i2c_get_clientdata(client); struct iqs5xx_dev_id_info *dev_id_info; int error; u8 buf[sizeof(*dev_id_info) + 1]; error = iqs5xx_read_burst(client, IQS5XX_PROD_NUM, &buf[1], sizeof(*dev_id_info)); if (error) return iqs5xx_bl_open(client); /* * A000 and B000 devices use 8-bit and 16-bit addressing, respectively. * Querying an A000 device's version information with 16-bit addressing * gives the appearance that the data is shifted by one byte; a nonzero * leading array element suggests this could be the case (in which case * the missing zero is prepended). */ buf[0] = 0; dev_id_info = (struct iqs5xx_dev_id_info *)&buf[buf[1] ? 0 : 1]; switch (be16_to_cpu(dev_id_info->prod_num)) { case IQS5XX_PROD_NUM_IQS550: case IQS5XX_PROD_NUM_IQS572: case IQS5XX_PROD_NUM_IQS525: break; default: dev_err(&client->dev, "Unrecognized product number: %u\n", be16_to_cpu(dev_id_info->prod_num)); return -EINVAL; } /* * With the product number recognized yet shifted by one byte, open the * bootloader and wait for user space to convert the A000 device into a * B000 device via new firmware. */ if (buf[1]) { dev_err(&client->dev, "Opening bootloader for A000 device\n"); return iqs5xx_bl_open(client); } error = iqs5xx_read_burst(client, IQS5XX_EXP_FILE, iqs5xx->exp_file, sizeof(iqs5xx->exp_file)); if (error) return error; error = iqs5xx_axis_init(client); if (error) return error; error = iqs5xx_write_byte(client, IQS5XX_SYS_CTRL0, IQS5XX_ACK_RESET); if (error) return error; error = iqs5xx_write_byte(client, IQS5XX_SYS_CFG0, IQS5XX_SETUP_COMPLETE | IQS5XX_WDT | IQS5XX_ALP_REATI | IQS5XX_REATI); if (error) return error; error = iqs5xx_write_byte(client, IQS5XX_SYS_CFG1, IQS5XX_TP_EVENT | IQS5XX_EVENT_MODE); if (error) return error; error = iqs5xx_write_byte(client, IQS5XX_END_COMM, 0); if (error) return error; iqs5xx->dev_id_info = *dev_id_info; /* * The following delay allows ATI to complete before the open and close * callbacks are free to elicit I2C communication. Any attempts to read * from or write to the device during this time may face extended clock * stretching and prompt the I2C controller to report an error. */ msleep(250); return 0; } static irqreturn_t iqs5xx_irq(int irq, void *data) { struct iqs5xx_private *iqs5xx = data; struct iqs5xx_status status; struct i2c_client *client = iqs5xx->client; struct input_dev *input = iqs5xx->input; int error, i; /* * This check is purely a precaution, as the device does not assert the * RDY output during bootloader mode. If the device operates outside of * bootloader mode, the input device is guaranteed to be allocated. */ if (!iqs5xx->dev_id_info.bl_status) return IRQ_NONE; error = iqs5xx_read_burst(client, IQS5XX_SYS_INFO0, &status, sizeof(status)); if (error) return IRQ_NONE; if (status.sys_info[0] & IQS5XX_SHOW_RESET) { dev_err(&client->dev, "Unexpected device reset\n"); error = iqs5xx_dev_init(client); if (error) { dev_err(&client->dev, "Failed to re-initialize device: %d\n", error); return IRQ_NONE; } return IRQ_HANDLED; } for (i = 0; i < ARRAY_SIZE(status.touch_data); i++) { struct iqs5xx_touch_data *touch_data = &status.touch_data[i]; u16 pressure = be16_to_cpu(touch_data->strength); input_mt_slot(input, i); if (input_mt_report_slot_state(input, MT_TOOL_FINGER, pressure != 0)) { touchscreen_report_pos(input, &iqs5xx->prop, be16_to_cpu(touch_data->abs_x), be16_to_cpu(touch_data->abs_y), true); input_report_abs(input, ABS_MT_PRESSURE, pressure); } } input_mt_sync_frame(input); input_sync(input); error = iqs5xx_write_byte(client, IQS5XX_END_COMM, 0); if (error) return IRQ_NONE; /* * Once the communication window is closed, a small delay is added to * ensure the device's RDY output has been deasserted by the time the * interrupt handler returns. */ usleep_range(50, 100); return IRQ_HANDLED; } static int iqs5xx_fw_file_parse(struct i2c_client *client, const char *fw_file, u8 *pmap) { const struct firmware *fw; struct iqs5xx_ihex_rec *rec; size_t pos = 0; int error, i; u16 rec_num = 1; u16 rec_addr; u8 rec_len, rec_type, rec_chksm, chksm; u8 rec_hdr[IQS5XX_REC_HDR_LEN]; u8 rec_data[IQS5XX_REC_LEN_MAX]; /* * Firmware exported from the vendor's configuration tool deviates from * standard ihex as follows: (1) the checksum for records corresponding * to user-exported settings is not recalculated, and (2) an address of * 0xFFFF is used for the EOF record. * * Because the ihex2fw tool tolerates neither (1) nor (2), the slightly * nonstandard ihex firmware is parsed directly by the driver. */ error = request_firmware(&fw, fw_file, &client->dev); if (error) { dev_err(&client->dev, "Failed to request firmware %s: %d\n", fw_file, error); return error; } do { if (pos + sizeof(*rec) > fw->size) { dev_err(&client->dev, "Insufficient firmware size\n"); error = -EINVAL; break; } rec = (struct iqs5xx_ihex_rec *)(fw->data + pos); pos += sizeof(*rec); if (rec->start != ':') { dev_err(&client->dev, "Invalid start at record %u\n", rec_num); error = -EINVAL; break; } error = hex2bin(rec_hdr, rec->len, sizeof(rec_hdr)); if (error) { dev_err(&client->dev, "Invalid header at record %u\n", rec_num); break; } rec_len = *rec_hdr; rec_addr = get_unaligned_be16(rec_hdr + sizeof(rec_len)); rec_type = *(rec_hdr + sizeof(rec_len) + sizeof(rec_addr)); if (pos + rec_len * 2 > fw->size) { dev_err(&client->dev, "Insufficient firmware size\n"); error = -EINVAL; break; } pos += (rec_len * 2); error = hex2bin(rec_data, rec->data, rec_len); if (error) { dev_err(&client->dev, "Invalid data at record %u\n", rec_num); break; } error = hex2bin(&rec_chksm, rec->data + rec_len * 2, sizeof(rec_chksm)); if (error) { dev_err(&client->dev, "Invalid checksum at record %u\n", rec_num); break; } chksm = 0; for (i = 0; i < sizeof(rec_hdr); i++) chksm += rec_hdr[i]; for (i = 0; i < rec_len; i++) chksm += rec_data[i]; chksm = ~chksm + 1; if (chksm != rec_chksm && rec_addr < IQS5XX_CSTM) { dev_err(&client->dev, "Incorrect checksum at record %u\n", rec_num); error = -EINVAL; break; } switch (rec_type) { case IQS5XX_REC_TYPE_DATA: if (rec_addr < IQS5XX_CHKSM || rec_addr > IQS5XX_PMAP_END) { dev_err(&client->dev, "Invalid address at record %u\n", rec_num); error = -EINVAL; } else { memcpy(pmap + rec_addr - IQS5XX_CHKSM, rec_data, rec_len); } break; case IQS5XX_REC_TYPE_EOF: break; default: dev_err(&client->dev, "Invalid type at record %u\n", rec_num); error = -EINVAL; } if (error) break; rec_num++; while (pos < fw->size) { if (*(fw->data + pos) == ':') break; pos++; } } while (rec_type != IQS5XX_REC_TYPE_EOF); release_firmware(fw); return error; } static int iqs5xx_fw_file_write(struct i2c_client *client, const char *fw_file) { struct iqs5xx_private *iqs5xx = i2c_get_clientdata(client); int error, error_init = 0; u8 *pmap; pmap = kzalloc(IQS5XX_PMAP_LEN, GFP_KERNEL); if (!pmap) return -ENOMEM; error = iqs5xx_fw_file_parse(client, fw_file, pmap); if (error) goto err_kfree; mutex_lock(&iqs5xx->lock); /* * Disable the interrupt line in case the first attempt(s) to enter the * bootloader don't happen quickly enough, in which case the device may * assert the RDY output until the next attempt. */ disable_irq(client->irq); iqs5xx->dev_id_info.bl_status = 0; error = iqs5xx_bl_cmd(client, IQS5XX_BL_CMD_VER, 0); if (error) { error = iqs5xx_bl_open(client); if (error) goto err_reset; } error = iqs5xx_bl_write(client, IQS5XX_CHKSM, pmap, IQS5XX_PMAP_LEN); if (error) goto err_reset; error = iqs5xx_bl_cmd(client, IQS5XX_BL_CMD_CRC, 0); if (error) goto err_reset; error = iqs5xx_bl_verify(client, IQS5XX_CSTM, pmap + IQS5XX_CHKSM_LEN + IQS5XX_APP_LEN, IQS5XX_CSTM_LEN); err_reset: iqs5xx_reset(client); usleep_range(15000, 15100); error_init = iqs5xx_dev_init(client); if (!iqs5xx->dev_id_info.bl_status) error_init = error_init ? : -EINVAL; enable_irq(client->irq); mutex_unlock(&iqs5xx->lock); err_kfree: kfree(pmap); return error ? : error_init; } static ssize_t fw_file_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct iqs5xx_private *iqs5xx = dev_get_drvdata(dev); struct i2c_client *client = iqs5xx->client; size_t len = count; bool input_reg = !iqs5xx->input; char fw_file[IQS5XX_FW_FILE_LEN + 1]; int error; if (!len) return -EINVAL; if (buf[len - 1] == '\n') len--; if (len > IQS5XX_FW_FILE_LEN) return -ENAMETOOLONG; memcpy(fw_file, buf, len); fw_file[len] = '\0'; error = iqs5xx_fw_file_write(client, fw_file); if (error) return error; /* * If the input device was not allocated already, it is guaranteed to * be allocated by this point and can finally be registered. */ if (input_reg) { error = input_register_device(iqs5xx->input); if (error) { dev_err(&client->dev, "Failed to register device: %d\n", error); return error; } } return count; } static ssize_t fw_info_show(struct device *dev, struct device_attribute *attr, char *buf) { struct iqs5xx_private *iqs5xx = dev_get_drvdata(dev); if (!iqs5xx->dev_id_info.bl_status) return -ENODATA; return scnprintf(buf, PAGE_SIZE, "%u.%u.%u.%u:%u.%u\n", be16_to_cpu(iqs5xx->dev_id_info.prod_num), be16_to_cpu(iqs5xx->dev_id_info.proj_num), iqs5xx->dev_id_info.major_ver, iqs5xx->dev_id_info.minor_ver, iqs5xx->exp_file[0], iqs5xx->exp_file[1]); } static DEVICE_ATTR_WO(fw_file); static DEVICE_ATTR_RO(fw_info); static struct attribute *iqs5xx_attrs[] = { &dev_attr_fw_file.attr, &dev_attr_fw_info.attr, NULL, }; static umode_t iqs5xx_attr_is_visible(struct kobject *kobj, struct attribute *attr, int i) { struct device *dev = kobj_to_dev(kobj); struct iqs5xx_private *iqs5xx = dev_get_drvdata(dev); if (attr == &dev_attr_fw_file.attr && (iqs5xx->dev_id_info.bl_status == IQS5XX_BL_STATUS_NONE || !iqs5xx->reset_gpio)) return 0; return attr->mode; } static const struct attribute_group iqs5xx_attr_group = { .is_visible = iqs5xx_attr_is_visible, .attrs = iqs5xx_attrs, }; static int iqs5xx_suspend(struct device *dev) { struct iqs5xx_private *iqs5xx = dev_get_drvdata(dev); struct input_dev *input = iqs5xx->input; int error = 0; if (!input || device_may_wakeup(dev)) return error; mutex_lock(&input->mutex); if (input_device_enabled(input)) error = iqs5xx_set_state(iqs5xx->client, IQS5XX_SUSPEND); mutex_unlock(&input->mutex); return error; } static int iqs5xx_resume(struct device *dev) { struct iqs5xx_private *iqs5xx = dev_get_drvdata(dev); struct input_dev *input = iqs5xx->input; int error = 0; if (!input || device_may_wakeup(dev)) return error; mutex_lock(&input->mutex); if (input_device_enabled(input)) error = iqs5xx_set_state(iqs5xx->client, IQS5XX_RESUME); mutex_unlock(&input->mutex); return error; } static DEFINE_SIMPLE_DEV_PM_OPS(iqs5xx_pm, iqs5xx_suspend, iqs5xx_resume); static int iqs5xx_probe(struct i2c_client *client) { struct iqs5xx_private *iqs5xx; int error; iqs5xx = devm_kzalloc(&client->dev, sizeof(*iqs5xx), GFP_KERNEL); if (!iqs5xx) return -ENOMEM; i2c_set_clientdata(client, iqs5xx); iqs5xx->client = client; iqs5xx->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(iqs5xx->reset_gpio)) { error = PTR_ERR(iqs5xx->reset_gpio); dev_err(&client->dev, "Failed to request GPIO: %d\n", error); return error; } mutex_init(&iqs5xx->lock); error = iqs5xx_dev_init(client); if (error) return error; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, iqs5xx_irq, IRQF_ONESHOT, client->name, iqs5xx); if (error) { dev_err(&client->dev, "Failed to request IRQ: %d\n", error); return error; } error = devm_device_add_group(&client->dev, &iqs5xx_attr_group); if (error) { dev_err(&client->dev, "Failed to add attributes: %d\n", error); return error; } if (iqs5xx->input) { error = input_register_device(iqs5xx->input); if (error) dev_err(&client->dev, "Failed to register device: %d\n", error); } return error; } static const struct i2c_device_id iqs5xx_id[] = { { "iqs550", 0 }, { "iqs572", 1 }, { "iqs525", 2 }, { } }; MODULE_DEVICE_TABLE(i2c, iqs5xx_id); static const struct of_device_id iqs5xx_of_match[] = { { .compatible = "azoteq,iqs550" }, { .compatible = "azoteq,iqs572" }, { .compatible = "azoteq,iqs525" }, { } }; MODULE_DEVICE_TABLE(of, iqs5xx_of_match); static struct i2c_driver iqs5xx_i2c_driver = { .driver = { .name = "iqs5xx", .of_match_table = iqs5xx_of_match, .pm = pm_sleep_ptr(&iqs5xx_pm), }, .id_table = iqs5xx_id, .probe = iqs5xx_probe, }; module_i2c_driver(iqs5xx_i2c_driver); MODULE_AUTHOR("Jeff LaBundy <[email protected]>"); MODULE_DESCRIPTION("Azoteq IQS550/572/525 Trackpad/Touchscreen Controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/iqs5xx.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2012-2016 Synaptics Incorporated */ #include <linux/input.h> #include <linux/input/mt.h> #include <linux/rmi.h> #include "rmi_driver.h" #include "rmi_2d_sensor.h" enum rmi_f12_object_type { RMI_F12_OBJECT_NONE = 0x00, RMI_F12_OBJECT_FINGER = 0x01, RMI_F12_OBJECT_STYLUS = 0x02, RMI_F12_OBJECT_PALM = 0x03, RMI_F12_OBJECT_UNCLASSIFIED = 0x04, RMI_F12_OBJECT_GLOVED_FINGER = 0x06, RMI_F12_OBJECT_NARROW_OBJECT = 0x07, RMI_F12_OBJECT_HAND_EDGE = 0x08, RMI_F12_OBJECT_COVER = 0x0A, RMI_F12_OBJECT_STYLUS_2 = 0x0B, RMI_F12_OBJECT_ERASER = 0x0C, RMI_F12_OBJECT_SMALL_OBJECT = 0x0D, }; #define F12_DATA1_BYTES_PER_OBJ 8 struct f12_data { struct rmi_2d_sensor sensor; struct rmi_2d_sensor_platform_data sensor_pdata; bool has_dribble; u16 data_addr; struct rmi_register_descriptor query_reg_desc; struct rmi_register_descriptor control_reg_desc; struct rmi_register_descriptor data_reg_desc; /* F12 Data1 describes sensed objects */ const struct rmi_register_desc_item *data1; u16 data1_offset; /* F12 Data5 describes finger ACM */ const struct rmi_register_desc_item *data5; u16 data5_offset; /* F12 Data5 describes Pen */ const struct rmi_register_desc_item *data6; u16 data6_offset; /* F12 Data9 reports relative data */ const struct rmi_register_desc_item *data9; u16 data9_offset; const struct rmi_register_desc_item *data15; u16 data15_offset; unsigned long *abs_mask; unsigned long *rel_mask; }; static int rmi_f12_read_sensor_tuning(struct f12_data *f12) { const struct rmi_register_desc_item *item; struct rmi_2d_sensor *sensor = &f12->sensor; struct rmi_function *fn = sensor->fn; struct rmi_device *rmi_dev = fn->rmi_dev; int ret; int offset; u8 buf[15]; int pitch_x = 0; int pitch_y = 0; int rx_receivers = 0; int tx_receivers = 0; item = rmi_get_register_desc_item(&f12->control_reg_desc, 8); if (!item) { dev_err(&fn->dev, "F12 does not have the sensor tuning control register\n"); return -ENODEV; } offset = rmi_register_desc_calc_reg_offset(&f12->control_reg_desc, 8); if (item->reg_size > sizeof(buf)) { dev_err(&fn->dev, "F12 control8 should be no bigger than %zd bytes, not: %ld\n", sizeof(buf), item->reg_size); return -ENODEV; } ret = rmi_read_block(rmi_dev, fn->fd.control_base_addr + offset, buf, item->reg_size); if (ret) return ret; offset = 0; if (rmi_register_desc_has_subpacket(item, 0)) { sensor->max_x = (buf[offset + 1] << 8) | buf[offset]; sensor->max_y = (buf[offset + 3] << 8) | buf[offset + 2]; offset += 4; } rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: max_x: %d max_y: %d\n", __func__, sensor->max_x, sensor->max_y); if (rmi_register_desc_has_subpacket(item, 1)) { pitch_x = (buf[offset + 1] << 8) | buf[offset]; pitch_y = (buf[offset + 3] << 8) | buf[offset + 2]; offset += 4; } if (rmi_register_desc_has_subpacket(item, 2)) { /* Units 1/128 sensor pitch */ rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: Inactive Border xlo:%d xhi:%d ylo:%d yhi:%d\n", __func__, buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]); offset += 4; } if (rmi_register_desc_has_subpacket(item, 3)) { rx_receivers = buf[offset]; tx_receivers = buf[offset + 1]; offset += 2; } /* Skip over sensor flags */ if (rmi_register_desc_has_subpacket(item, 4)) offset += 1; sensor->x_mm = (pitch_x * rx_receivers) >> 12; sensor->y_mm = (pitch_y * tx_receivers) >> 12; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: x_mm: %d y_mm: %d\n", __func__, sensor->x_mm, sensor->y_mm); return 0; } static void rmi_f12_process_objects(struct f12_data *f12, u8 *data1, int size) { int i; struct rmi_2d_sensor *sensor = &f12->sensor; int objects = f12->data1->num_subpackets; if ((f12->data1->num_subpackets * F12_DATA1_BYTES_PER_OBJ) > size) objects = size / F12_DATA1_BYTES_PER_OBJ; for (i = 0; i < objects; i++) { struct rmi_2d_sensor_abs_object *obj = &sensor->objs[i]; obj->type = RMI_2D_OBJECT_NONE; obj->mt_tool = MT_TOOL_FINGER; switch (data1[0]) { case RMI_F12_OBJECT_FINGER: obj->type = RMI_2D_OBJECT_FINGER; break; case RMI_F12_OBJECT_STYLUS: obj->type = RMI_2D_OBJECT_STYLUS; obj->mt_tool = MT_TOOL_PEN; break; case RMI_F12_OBJECT_PALM: obj->type = RMI_2D_OBJECT_PALM; obj->mt_tool = MT_TOOL_PALM; break; case RMI_F12_OBJECT_UNCLASSIFIED: obj->type = RMI_2D_OBJECT_UNCLASSIFIED; break; } obj->x = (data1[2] << 8) | data1[1]; obj->y = (data1[4] << 8) | data1[3]; obj->z = data1[5]; obj->wx = data1[6]; obj->wy = data1[7]; rmi_2d_sensor_abs_process(sensor, obj, i); data1 += F12_DATA1_BYTES_PER_OBJ; } if (sensor->kernel_tracking) input_mt_assign_slots(sensor->input, sensor->tracking_slots, sensor->tracking_pos, sensor->nbr_fingers, sensor->dmax); for (i = 0; i < objects; i++) rmi_2d_sensor_abs_report(sensor, &sensor->objs[i], i); } static irqreturn_t rmi_f12_attention(int irq, void *ctx) { int retval; struct rmi_function *fn = ctx; struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct f12_data *f12 = dev_get_drvdata(&fn->dev); struct rmi_2d_sensor *sensor = &f12->sensor; int valid_bytes = sensor->pkt_size; if (drvdata->attn_data.data) { if (sensor->attn_size > drvdata->attn_data.size) valid_bytes = drvdata->attn_data.size; else valid_bytes = sensor->attn_size; memcpy(sensor->data_pkt, drvdata->attn_data.data, valid_bytes); drvdata->attn_data.data += valid_bytes; drvdata->attn_data.size -= valid_bytes; } else { retval = rmi_read_block(rmi_dev, f12->data_addr, sensor->data_pkt, sensor->pkt_size); if (retval < 0) { dev_err(&fn->dev, "Failed to read object data. Code: %d.\n", retval); return IRQ_RETVAL(retval); } } if (f12->data1) rmi_f12_process_objects(f12, &sensor->data_pkt[f12->data1_offset], valid_bytes); input_mt_sync_frame(sensor->input); return IRQ_HANDLED; } static int rmi_f12_write_control_regs(struct rmi_function *fn) { int ret; const struct rmi_register_desc_item *item; struct rmi_device *rmi_dev = fn->rmi_dev; struct f12_data *f12 = dev_get_drvdata(&fn->dev); int control_size; char buf[3]; u16 control_offset = 0; u8 subpacket_offset = 0; if (f12->has_dribble && (f12->sensor.dribble != RMI_REG_STATE_DEFAULT)) { item = rmi_get_register_desc_item(&f12->control_reg_desc, 20); if (item) { control_offset = rmi_register_desc_calc_reg_offset( &f12->control_reg_desc, 20); /* * The byte containing the EnableDribble bit will be * in either byte 0 or byte 2 of control 20. Depending * on the existence of subpacket 0. If control 20 is * larger then 3 bytes, just read the first 3. */ control_size = min(item->reg_size, 3UL); ret = rmi_read_block(rmi_dev, fn->fd.control_base_addr + control_offset, buf, control_size); if (ret) return ret; if (rmi_register_desc_has_subpacket(item, 0)) subpacket_offset += 1; switch (f12->sensor.dribble) { case RMI_REG_STATE_OFF: buf[subpacket_offset] &= ~BIT(2); break; case RMI_REG_STATE_ON: buf[subpacket_offset] |= BIT(2); break; case RMI_REG_STATE_DEFAULT: default: break; } ret = rmi_write_block(rmi_dev, fn->fd.control_base_addr + control_offset, buf, control_size); if (ret) return ret; } } return 0; } static int rmi_f12_config(struct rmi_function *fn) { struct rmi_driver *drv = fn->rmi_dev->driver; struct f12_data *f12 = dev_get_drvdata(&fn->dev); struct rmi_2d_sensor *sensor; int ret; sensor = &f12->sensor; if (!sensor->report_abs) drv->clear_irq_bits(fn->rmi_dev, f12->abs_mask); else drv->set_irq_bits(fn->rmi_dev, f12->abs_mask); drv->clear_irq_bits(fn->rmi_dev, f12->rel_mask); ret = rmi_f12_write_control_regs(fn); if (ret) dev_warn(&fn->dev, "Failed to write F12 control registers: %d\n", ret); return 0; } static int rmi_f12_probe(struct rmi_function *fn) { struct f12_data *f12; int ret; struct rmi_device *rmi_dev = fn->rmi_dev; char buf; u16 query_addr = fn->fd.query_base_addr; const struct rmi_register_desc_item *item; struct rmi_2d_sensor *sensor; struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); u16 data_offset = 0; int mask_size; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s\n", __func__); mask_size = BITS_TO_LONGS(drvdata->irq_count) * sizeof(unsigned long); ret = rmi_read(fn->rmi_dev, query_addr, &buf); if (ret < 0) { dev_err(&fn->dev, "Failed to read general info register: %d\n", ret); return -ENODEV; } ++query_addr; if (!(buf & BIT(0))) { dev_err(&fn->dev, "Behavior of F12 without register descriptors is undefined.\n"); return -ENODEV; } f12 = devm_kzalloc(&fn->dev, sizeof(struct f12_data) + mask_size * 2, GFP_KERNEL); if (!f12) return -ENOMEM; f12->abs_mask = (unsigned long *)((char *)f12 + sizeof(struct f12_data)); f12->rel_mask = (unsigned long *)((char *)f12 + sizeof(struct f12_data) + mask_size); set_bit(fn->irq_pos, f12->abs_mask); set_bit(fn->irq_pos + 1, f12->rel_mask); f12->has_dribble = !!(buf & BIT(3)); if (fn->dev.of_node) { ret = rmi_2d_sensor_of_probe(&fn->dev, &f12->sensor_pdata); if (ret) return ret; } else { f12->sensor_pdata = pdata->sensor_pdata; } ret = rmi_read_register_desc(rmi_dev, query_addr, &f12->query_reg_desc); if (ret) { dev_err(&fn->dev, "Failed to read the Query Register Descriptor: %d\n", ret); return ret; } query_addr += 3; ret = rmi_read_register_desc(rmi_dev, query_addr, &f12->control_reg_desc); if (ret) { dev_err(&fn->dev, "Failed to read the Control Register Descriptor: %d\n", ret); return ret; } query_addr += 3; ret = rmi_read_register_desc(rmi_dev, query_addr, &f12->data_reg_desc); if (ret) { dev_err(&fn->dev, "Failed to read the Data Register Descriptor: %d\n", ret); return ret; } query_addr += 3; sensor = &f12->sensor; sensor->fn = fn; f12->data_addr = fn->fd.data_base_addr; sensor->pkt_size = rmi_register_desc_calc_size(&f12->data_reg_desc); sensor->axis_align = f12->sensor_pdata.axis_align; sensor->x_mm = f12->sensor_pdata.x_mm; sensor->y_mm = f12->sensor_pdata.y_mm; sensor->dribble = f12->sensor_pdata.dribble; if (sensor->sensor_type == rmi_sensor_default) sensor->sensor_type = f12->sensor_pdata.sensor_type; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: data packet size: %d\n", __func__, sensor->pkt_size); sensor->data_pkt = devm_kzalloc(&fn->dev, sensor->pkt_size, GFP_KERNEL); if (!sensor->data_pkt) return -ENOMEM; dev_set_drvdata(&fn->dev, f12); ret = rmi_f12_read_sensor_tuning(f12); if (ret) return ret; /* * Figure out what data is contained in the data registers. HID devices * may have registers defined, but their data is not reported in the * HID attention report. Registers which are not reported in the HID * attention report check to see if the device is receiving data from * HID attention reports. */ item = rmi_get_register_desc_item(&f12->data_reg_desc, 0); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 1); if (item) { f12->data1 = item; f12->data1_offset = data_offset; data_offset += item->reg_size; sensor->nbr_fingers = item->num_subpackets; sensor->report_abs = 1; sensor->attn_size += item->reg_size; } item = rmi_get_register_desc_item(&f12->data_reg_desc, 2); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 3); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 4); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 5); if (item) { f12->data5 = item; f12->data5_offset = data_offset; data_offset += item->reg_size; sensor->attn_size += item->reg_size; } item = rmi_get_register_desc_item(&f12->data_reg_desc, 6); if (item && !drvdata->attn_data.data) { f12->data6 = item; f12->data6_offset = data_offset; data_offset += item->reg_size; } item = rmi_get_register_desc_item(&f12->data_reg_desc, 7); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 8); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 9); if (item && !drvdata->attn_data.data) { f12->data9 = item; f12->data9_offset = data_offset; data_offset += item->reg_size; if (!sensor->report_abs) sensor->report_rel = 1; } item = rmi_get_register_desc_item(&f12->data_reg_desc, 10); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 11); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 12); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 13); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 14); if (item && !drvdata->attn_data.data) data_offset += item->reg_size; item = rmi_get_register_desc_item(&f12->data_reg_desc, 15); if (item && !drvdata->attn_data.data) { f12->data15 = item; f12->data15_offset = data_offset; data_offset += item->reg_size; } /* allocate the in-kernel tracking buffers */ sensor->tracking_pos = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(struct input_mt_pos), GFP_KERNEL); sensor->tracking_slots = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(int), GFP_KERNEL); sensor->objs = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(struct rmi_2d_sensor_abs_object), GFP_KERNEL); if (!sensor->tracking_pos || !sensor->tracking_slots || !sensor->objs) return -ENOMEM; ret = rmi_2d_sensor_configure_input(fn, sensor); if (ret) return ret; return 0; } struct rmi_function_handler rmi_f12_handler = { .driver = { .name = "rmi4_f12", }, .func = 0x12, .probe = rmi_f12_probe, .config = rmi_f12_config, .attention = rmi_f12_attention, };
linux-master
drivers/input/rmi4/rmi_f12.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/device.h> #include <linux/irq.h> #include <linux/irqdomain.h> #include <linux/list.h> #include <linux/pm.h> #include <linux/rmi.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/of.h> #include "rmi_bus.h" #include "rmi_driver.h" static int debug_flags; module_param(debug_flags, int, 0644); MODULE_PARM_DESC(debug_flags, "control debugging information"); void rmi_dbg(int flags, struct device *dev, const char *fmt, ...) { struct va_format vaf; va_list args; if (flags & debug_flags) { va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; dev_printk(KERN_DEBUG, dev, "%pV", &vaf); va_end(args); } } EXPORT_SYMBOL_GPL(rmi_dbg); /* * RMI Physical devices * * Physical RMI device consists of several functions serving particular * purpose. For example F11 is a 2D touch sensor while F01 is a generic * function present in every RMI device. */ static void rmi_release_device(struct device *dev) { struct rmi_device *rmi_dev = to_rmi_device(dev); kfree(rmi_dev); } static const struct device_type rmi_device_type = { .name = "rmi4_sensor", .release = rmi_release_device, }; bool rmi_is_physical_device(struct device *dev) { return dev->type == &rmi_device_type; } /** * rmi_register_transport_device - register a transport device connection * on the RMI bus. Transport drivers provide communication from the devices * on a bus (such as SPI, I2C, and so on) to the RMI4 sensor. * * @xport: the transport device to register */ int rmi_register_transport_device(struct rmi_transport_dev *xport) { static atomic_t transport_device_count = ATOMIC_INIT(0); struct rmi_device *rmi_dev; int error; rmi_dev = kzalloc(sizeof(struct rmi_device), GFP_KERNEL); if (!rmi_dev) return -ENOMEM; device_initialize(&rmi_dev->dev); rmi_dev->xport = xport; rmi_dev->number = atomic_inc_return(&transport_device_count) - 1; dev_set_name(&rmi_dev->dev, "rmi4-%02d", rmi_dev->number); rmi_dev->dev.bus = &rmi_bus_type; rmi_dev->dev.type = &rmi_device_type; rmi_dev->dev.parent = xport->dev; xport->rmi_dev = rmi_dev; error = device_add(&rmi_dev->dev); if (error) goto err_put_device; rmi_dbg(RMI_DEBUG_CORE, xport->dev, "%s: Registered %s as %s.\n", __func__, dev_name(rmi_dev->xport->dev), dev_name(&rmi_dev->dev)); return 0; err_put_device: put_device(&rmi_dev->dev); return error; } EXPORT_SYMBOL_GPL(rmi_register_transport_device); /** * rmi_unregister_transport_device - unregister a transport device connection * @xport: the transport driver to unregister * */ void rmi_unregister_transport_device(struct rmi_transport_dev *xport) { struct rmi_device *rmi_dev = xport->rmi_dev; device_del(&rmi_dev->dev); put_device(&rmi_dev->dev); } EXPORT_SYMBOL(rmi_unregister_transport_device); /* Function specific stuff */ static void rmi_release_function(struct device *dev) { struct rmi_function *fn = to_rmi_function(dev); kfree(fn); } static const struct device_type rmi_function_type = { .name = "rmi4_function", .release = rmi_release_function, }; bool rmi_is_function_device(struct device *dev) { return dev->type == &rmi_function_type; } static int rmi_function_match(struct device *dev, struct device_driver *drv) { struct rmi_function_handler *handler = to_rmi_function_handler(drv); struct rmi_function *fn = to_rmi_function(dev); return fn->fd.function_number == handler->func; } #ifdef CONFIG_OF static void rmi_function_of_probe(struct rmi_function *fn) { char of_name[9]; struct device_node *node = fn->rmi_dev->xport->dev->of_node; snprintf(of_name, sizeof(of_name), "rmi4-f%02x", fn->fd.function_number); fn->dev.of_node = of_get_child_by_name(node, of_name); } #else static inline void rmi_function_of_probe(struct rmi_function *fn) {} #endif static struct irq_chip rmi_irq_chip = { .name = "rmi4", }; static int rmi_create_function_irq(struct rmi_function *fn, struct rmi_function_handler *handler) { struct rmi_driver_data *drvdata = dev_get_drvdata(&fn->rmi_dev->dev); int i, error; for (i = 0; i < fn->num_of_irqs; i++) { set_bit(fn->irq_pos + i, fn->irq_mask); fn->irq[i] = irq_create_mapping(drvdata->irqdomain, fn->irq_pos + i); irq_set_chip_data(fn->irq[i], fn); irq_set_chip_and_handler(fn->irq[i], &rmi_irq_chip, handle_simple_irq); irq_set_nested_thread(fn->irq[i], 1); error = devm_request_threaded_irq(&fn->dev, fn->irq[i], NULL, handler->attention, IRQF_ONESHOT, dev_name(&fn->dev), fn); if (error) { dev_err(&fn->dev, "Error %d registering IRQ\n", error); return error; } } return 0; } static int rmi_function_probe(struct device *dev) { struct rmi_function *fn = to_rmi_function(dev); struct rmi_function_handler *handler = to_rmi_function_handler(dev->driver); int error; rmi_function_of_probe(fn); if (handler->probe) { error = handler->probe(fn); if (error) return error; } if (fn->num_of_irqs && handler->attention) { error = rmi_create_function_irq(fn, handler); if (error) return error; } return 0; } static int rmi_function_remove(struct device *dev) { struct rmi_function *fn = to_rmi_function(dev); struct rmi_function_handler *handler = to_rmi_function_handler(dev->driver); if (handler->remove) handler->remove(fn); return 0; } int rmi_register_function(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; int error; device_initialize(&fn->dev); dev_set_name(&fn->dev, "%s.fn%02x", dev_name(&rmi_dev->dev), fn->fd.function_number); fn->dev.parent = &rmi_dev->dev; fn->dev.type = &rmi_function_type; fn->dev.bus = &rmi_bus_type; error = device_add(&fn->dev); if (error) { dev_err(&rmi_dev->dev, "Failed device_register function device %s\n", dev_name(&fn->dev)); goto err_put_device; } rmi_dbg(RMI_DEBUG_CORE, &rmi_dev->dev, "Registered F%02X.\n", fn->fd.function_number); return 0; err_put_device: put_device(&fn->dev); return error; } void rmi_unregister_function(struct rmi_function *fn) { int i; rmi_dbg(RMI_DEBUG_CORE, &fn->dev, "Unregistering F%02X.\n", fn->fd.function_number); device_del(&fn->dev); of_node_put(fn->dev.of_node); put_device(&fn->dev); for (i = 0; i < fn->num_of_irqs; i++) irq_dispose_mapping(fn->irq[i]); } /** * __rmi_register_function_handler - register a handler for an RMI function * @handler: RMI handler that should be registered. * @owner: pointer to module that implements the handler * @mod_name: name of the module implementing the handler * * This function performs additional setup of RMI function handler and * registers it with the RMI core so that it can be bound to * RMI function devices. */ int __rmi_register_function_handler(struct rmi_function_handler *handler, struct module *owner, const char *mod_name) { struct device_driver *driver = &handler->driver; int error; driver->bus = &rmi_bus_type; driver->owner = owner; driver->mod_name = mod_name; driver->probe = rmi_function_probe; driver->remove = rmi_function_remove; error = driver_register(driver); if (error) { pr_err("driver_register() failed for %s, error: %d\n", driver->name, error); return error; } return 0; } EXPORT_SYMBOL_GPL(__rmi_register_function_handler); /** * rmi_unregister_function_handler - unregister given RMI function handler * @handler: RMI handler that should be unregistered. * * This function unregisters given function handler from RMI core which * causes it to be unbound from the function devices. */ void rmi_unregister_function_handler(struct rmi_function_handler *handler) { driver_unregister(&handler->driver); } EXPORT_SYMBOL_GPL(rmi_unregister_function_handler); /* Bus specific stuff */ static int rmi_bus_match(struct device *dev, struct device_driver *drv) { bool physical = rmi_is_physical_device(dev); /* First see if types are not compatible */ if (physical != rmi_is_physical_driver(drv)) return 0; return physical || rmi_function_match(dev, drv); } struct bus_type rmi_bus_type = { .match = rmi_bus_match, .name = "rmi4", }; static struct rmi_function_handler *fn_handlers[] = { &rmi_f01_handler, #ifdef CONFIG_RMI4_F03 &rmi_f03_handler, #endif #ifdef CONFIG_RMI4_F11 &rmi_f11_handler, #endif #ifdef CONFIG_RMI4_F12 &rmi_f12_handler, #endif #ifdef CONFIG_RMI4_F30 &rmi_f30_handler, #endif #ifdef CONFIG_RMI4_F34 &rmi_f34_handler, #endif #ifdef CONFIG_RMI4_F3A &rmi_f3a_handler, #endif #ifdef CONFIG_RMI4_F54 &rmi_f54_handler, #endif #ifdef CONFIG_RMI4_F55 &rmi_f55_handler, #endif }; static void __rmi_unregister_function_handlers(int start_idx) { int i; for (i = start_idx; i >= 0; i--) rmi_unregister_function_handler(fn_handlers[i]); } static void rmi_unregister_function_handlers(void) { __rmi_unregister_function_handlers(ARRAY_SIZE(fn_handlers) - 1); } static int rmi_register_function_handlers(void) { int ret; int i; for (i = 0; i < ARRAY_SIZE(fn_handlers); i++) { ret = rmi_register_function_handler(fn_handlers[i]); if (ret) { pr_err("%s: error registering the RMI F%02x handler: %d\n", __func__, fn_handlers[i]->func, ret); goto err_unregister_function_handlers; } } return 0; err_unregister_function_handlers: __rmi_unregister_function_handlers(i - 1); return ret; } int rmi_of_property_read_u32(struct device *dev, u32 *result, const char *prop, bool optional) { int retval; u32 val = 0; retval = of_property_read_u32(dev->of_node, prop, &val); if (retval && (!optional && retval == -EINVAL)) { dev_err(dev, "Failed to get %s value: %d\n", prop, retval); return retval; } *result = val; return 0; } EXPORT_SYMBOL_GPL(rmi_of_property_read_u32); static int __init rmi_bus_init(void) { int error; error = bus_register(&rmi_bus_type); if (error) { pr_err("%s: error registering the RMI bus: %d\n", __func__, error); return error; } error = rmi_register_function_handlers(); if (error) goto err_unregister_bus; error = rmi_register_physical_driver(); if (error) { pr_err("%s: error registering the RMI physical driver: %d\n", __func__, error); goto err_unregister_bus; } return 0; err_unregister_bus: bus_unregister(&rmi_bus_type); return error; } module_init(rmi_bus_init); static void __exit rmi_bus_exit(void) { /* * We should only ever get here if all drivers are unloaded, so * all we have to do at this point is unregister ourselves. */ rmi_unregister_physical_driver(); rmi_unregister_function_handlers(); bus_unregister(&rmi_bus_type); } module_exit(rmi_bus_exit); MODULE_AUTHOR("Christopher Heiny <[email protected]"); MODULE_AUTHOR("Andrew Duggan <[email protected]"); MODULE_DESCRIPTION("RMI bus"); MODULE_LICENSE("GPL");
linux-master
drivers/input/rmi4/rmi_bus.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/device.h> #include <linux/of.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/rmi.h> #include "rmi_driver.h" #include "rmi_2d_sensor.h" #define RMI_2D_REL_POS_MIN -128 #define RMI_2D_REL_POS_MAX 127 /* maximum ABS_MT_POSITION displacement (in mm) */ #define DMAX 10 void rmi_2d_sensor_abs_process(struct rmi_2d_sensor *sensor, struct rmi_2d_sensor_abs_object *obj, int slot) { struct rmi_2d_axis_alignment *axis_align = &sensor->axis_align; /* we keep the previous values if the finger is released */ if (obj->type == RMI_2D_OBJECT_NONE) return; if (axis_align->flip_x) obj->x = sensor->max_x - obj->x; if (axis_align->flip_y) obj->y = sensor->max_y - obj->y; if (axis_align->swap_axes) swap(obj->x, obj->y); /* * Here checking if X offset or y offset are specified is * redundant. We just add the offsets or clip the values. * * Note: offsets need to be applied before clipping occurs, * or we could get funny values that are outside of * clipping boundaries. */ obj->x += axis_align->offset_x; obj->y += axis_align->offset_y; obj->x = max(axis_align->clip_x_low, obj->x); obj->y = max(axis_align->clip_y_low, obj->y); if (axis_align->clip_x_high) obj->x = min(sensor->max_x, obj->x); if (axis_align->clip_y_high) obj->y = min(sensor->max_y, obj->y); sensor->tracking_pos[slot].x = obj->x; sensor->tracking_pos[slot].y = obj->y; } EXPORT_SYMBOL_GPL(rmi_2d_sensor_abs_process); void rmi_2d_sensor_abs_report(struct rmi_2d_sensor *sensor, struct rmi_2d_sensor_abs_object *obj, int slot) { struct rmi_2d_axis_alignment *axis_align = &sensor->axis_align; struct input_dev *input = sensor->input; int wide, major, minor; if (sensor->kernel_tracking) input_mt_slot(input, sensor->tracking_slots[slot]); else input_mt_slot(input, slot); input_mt_report_slot_state(input, obj->mt_tool, obj->type != RMI_2D_OBJECT_NONE); if (obj->type != RMI_2D_OBJECT_NONE) { obj->x = sensor->tracking_pos[slot].x; obj->y = sensor->tracking_pos[slot].y; if (axis_align->swap_axes) swap(obj->wx, obj->wy); wide = (obj->wx > obj->wy); major = max(obj->wx, obj->wy); minor = min(obj->wx, obj->wy); if (obj->type == RMI_2D_OBJECT_STYLUS) { major = max(1, major); minor = max(1, minor); } input_event(sensor->input, EV_ABS, ABS_MT_POSITION_X, obj->x); input_event(sensor->input, EV_ABS, ABS_MT_POSITION_Y, obj->y); input_event(sensor->input, EV_ABS, ABS_MT_ORIENTATION, wide); input_event(sensor->input, EV_ABS, ABS_MT_PRESSURE, obj->z); input_event(sensor->input, EV_ABS, ABS_MT_TOUCH_MAJOR, major); input_event(sensor->input, EV_ABS, ABS_MT_TOUCH_MINOR, minor); rmi_dbg(RMI_DEBUG_2D_SENSOR, &sensor->input->dev, "%s: obj[%d]: type: 0x%02x X: %d Y: %d Z: %d WX: %d WY: %d\n", __func__, slot, obj->type, obj->x, obj->y, obj->z, obj->wx, obj->wy); } } EXPORT_SYMBOL_GPL(rmi_2d_sensor_abs_report); void rmi_2d_sensor_rel_report(struct rmi_2d_sensor *sensor, int x, int y) { struct rmi_2d_axis_alignment *axis_align = &sensor->axis_align; x = min(RMI_2D_REL_POS_MAX, max(RMI_2D_REL_POS_MIN, (int)x)); y = min(RMI_2D_REL_POS_MAX, max(RMI_2D_REL_POS_MIN, (int)y)); if (axis_align->flip_x) x = min(RMI_2D_REL_POS_MAX, -x); if (axis_align->flip_y) y = min(RMI_2D_REL_POS_MAX, -y); if (axis_align->swap_axes) swap(x, y); if (x || y) { input_report_rel(sensor->input, REL_X, x); input_report_rel(sensor->input, REL_Y, y); } } EXPORT_SYMBOL_GPL(rmi_2d_sensor_rel_report); static void rmi_2d_sensor_set_input_params(struct rmi_2d_sensor *sensor) { struct input_dev *input = sensor->input; int res_x; int res_y; int max_x, max_y; int input_flags = 0; if (sensor->report_abs) { sensor->min_x = sensor->axis_align.clip_x_low; if (sensor->axis_align.clip_x_high) sensor->max_x = min(sensor->max_x, sensor->axis_align.clip_x_high); sensor->min_y = sensor->axis_align.clip_y_low; if (sensor->axis_align.clip_y_high) sensor->max_y = min(sensor->max_y, sensor->axis_align.clip_y_high); set_bit(EV_ABS, input->evbit); max_x = sensor->max_x; max_y = sensor->max_y; if (sensor->axis_align.swap_axes) swap(max_x, max_y); input_set_abs_params(input, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, max_y, 0, 0); if (sensor->x_mm && sensor->y_mm) { res_x = (sensor->max_x - sensor->min_x) / sensor->x_mm; res_y = (sensor->max_y - sensor->min_y) / sensor->y_mm; if (sensor->axis_align.swap_axes) swap(res_x, res_y); input_abs_set_res(input, ABS_X, res_x); input_abs_set_res(input, ABS_Y, res_y); input_abs_set_res(input, ABS_MT_POSITION_X, res_x); input_abs_set_res(input, ABS_MT_POSITION_Y, res_y); if (!sensor->dmax) sensor->dmax = DMAX * res_x; } input_set_abs_params(input, ABS_MT_PRESSURE, 0, 0xff, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 0x0f, 0, 0); input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 0x0f, 0, 0); input_set_abs_params(input, ABS_MT_ORIENTATION, 0, 1, 0, 0); input_set_abs_params(input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); if (sensor->sensor_type == rmi_sensor_touchpad) input_flags = INPUT_MT_POINTER; else input_flags = INPUT_MT_DIRECT; if (sensor->kernel_tracking) input_flags |= INPUT_MT_TRACK; input_mt_init_slots(input, sensor->nbr_fingers, input_flags); } if (sensor->report_rel) { set_bit(EV_REL, input->evbit); set_bit(REL_X, input->relbit); set_bit(REL_Y, input->relbit); } if (sensor->topbuttonpad) set_bit(INPUT_PROP_TOPBUTTONPAD, input->propbit); } int rmi_2d_sensor_configure_input(struct rmi_function *fn, struct rmi_2d_sensor *sensor) { struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); if (!drv_data->input) return -ENODEV; sensor->input = drv_data->input; rmi_2d_sensor_set_input_params(sensor); return 0; } EXPORT_SYMBOL_GPL(rmi_2d_sensor_configure_input); #ifdef CONFIG_OF int rmi_2d_sensor_of_probe(struct device *dev, struct rmi_2d_sensor_platform_data *pdata) { int retval; u32 val; pdata->axis_align.swap_axes = of_property_read_bool(dev->of_node, "touchscreen-swapped-x-y"); pdata->axis_align.flip_x = of_property_read_bool(dev->of_node, "touchscreen-inverted-x"); pdata->axis_align.flip_y = of_property_read_bool(dev->of_node, "touchscreen-inverted-y"); retval = rmi_of_property_read_u32(dev, &val, "syna,clip-x-low", 1); if (retval) return retval; pdata->axis_align.clip_x_low = val; retval = rmi_of_property_read_u32(dev, &val, "syna,clip-y-low", 1); if (retval) return retval; pdata->axis_align.clip_y_low = val; retval = rmi_of_property_read_u32(dev, &val, "syna,clip-x-high", 1); if (retval) return retval; pdata->axis_align.clip_x_high = val; retval = rmi_of_property_read_u32(dev, &val, "syna,clip-y-high", 1); if (retval) return retval; pdata->axis_align.clip_y_high = val; retval = rmi_of_property_read_u32(dev, &val, "syna,offset-x", 1); if (retval) return retval; pdata->axis_align.offset_x = val; retval = rmi_of_property_read_u32(dev, &val, "syna,offset-y", 1); if (retval) return retval; pdata->axis_align.offset_y = val; retval = rmi_of_property_read_u32(dev, &val, "syna,delta-x-threshold", 1); if (retval) return retval; pdata->axis_align.delta_x_threshold = val; retval = rmi_of_property_read_u32(dev, &val, "syna,delta-y-threshold", 1); if (retval) return retval; pdata->axis_align.delta_y_threshold = val; retval = rmi_of_property_read_u32(dev, (u32 *)&pdata->sensor_type, "syna,sensor-type", 1); if (retval) return retval; retval = rmi_of_property_read_u32(dev, &val, "touchscreen-x-mm", 1); if (retval) return retval; pdata->x_mm = val; retval = rmi_of_property_read_u32(dev, &val, "touchscreen-y-mm", 1); if (retval) return retval; pdata->y_mm = val; retval = rmi_of_property_read_u32(dev, &val, "syna,disable-report-mask", 1); if (retval) return retval; pdata->disable_report_mask = val; retval = rmi_of_property_read_u32(dev, &val, "syna,rezero-wait-ms", 1); if (retval) return retval; pdata->rezero_wait = val; return 0; } #else inline int rmi_2d_sensor_of_probe(struct device *dev, struct rmi_2d_sensor_platform_data *pdata) { return -ENODEV; } #endif EXPORT_SYMBOL_GPL(rmi_2d_sensor_of_probe);
linux-master
drivers/input/rmi4/rmi_2d_sensor.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2007-2016, Synaptics Incorporated * Copyright (C) 2016 Zodiac Inflight Innovations */ #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/firmware.h> #include <asm/unaligned.h> #include <linux/bitops.h> #include "rmi_driver.h" #include "rmi_f34.h" static int rmi_f34_write_bootloader_id(struct f34_data *f34) { struct rmi_function *fn = f34->fn; struct rmi_device *rmi_dev = fn->rmi_dev; u8 bootloader_id[F34_BOOTLOADER_ID_LEN]; int ret; ret = rmi_read_block(rmi_dev, fn->fd.query_base_addr, bootloader_id, sizeof(bootloader_id)); if (ret) { dev_err(&fn->dev, "%s: Reading bootloader ID failed: %d\n", __func__, ret); return ret; } rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: writing bootloader id '%c%c'\n", __func__, bootloader_id[0], bootloader_id[1]); ret = rmi_write_block(rmi_dev, fn->fd.data_base_addr + F34_BLOCK_DATA_OFFSET, bootloader_id, sizeof(bootloader_id)); if (ret) { dev_err(&fn->dev, "Failed to write bootloader ID: %d\n", ret); return ret; } return 0; } static int rmi_f34_command(struct f34_data *f34, u8 command, unsigned int timeout, bool write_bl_id) { struct rmi_function *fn = f34->fn; struct rmi_device *rmi_dev = fn->rmi_dev; int ret; if (write_bl_id) { ret = rmi_f34_write_bootloader_id(f34); if (ret) return ret; } init_completion(&f34->v5.cmd_done); ret = rmi_read(rmi_dev, f34->v5.ctrl_address, &f34->v5.status); if (ret) { dev_err(&f34->fn->dev, "%s: Failed to read cmd register: %d (command %#02x)\n", __func__, ret, command); return ret; } f34->v5.status |= command & 0x0f; ret = rmi_write(rmi_dev, f34->v5.ctrl_address, f34->v5.status); if (ret < 0) { dev_err(&f34->fn->dev, "Failed to write F34 command %#02x: %d\n", command, ret); return ret; } if (!wait_for_completion_timeout(&f34->v5.cmd_done, msecs_to_jiffies(timeout))) { ret = rmi_read(rmi_dev, f34->v5.ctrl_address, &f34->v5.status); if (ret) { dev_err(&f34->fn->dev, "%s: cmd %#02x timed out: %d\n", __func__, command, ret); return ret; } if (f34->v5.status & 0x7f) { dev_err(&f34->fn->dev, "%s: cmd %#02x timed out, status: %#02x\n", __func__, command, f34->v5.status); return -ETIMEDOUT; } } return 0; } static irqreturn_t rmi_f34_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct f34_data *f34 = dev_get_drvdata(&fn->dev); int ret; u8 status; if (f34->bl_version == 5) { ret = rmi_read(f34->fn->rmi_dev, f34->v5.ctrl_address, &status); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: status: %#02x, ret: %d\n", __func__, status, ret); if (!ret && !(status & 0x7f)) complete(&f34->v5.cmd_done); } else { ret = rmi_read_block(f34->fn->rmi_dev, f34->fn->fd.data_base_addr + V7_COMMAND_OFFSET, &status, sizeof(status)); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: cmd: %#02x, ret: %d\n", __func__, status, ret); if (!ret && status == CMD_V7_IDLE) complete(&f34->v7.cmd_done); } return IRQ_HANDLED; } static int rmi_f34_write_blocks(struct f34_data *f34, const void *data, int block_count, u8 command) { struct rmi_function *fn = f34->fn; struct rmi_device *rmi_dev = fn->rmi_dev; u16 address = fn->fd.data_base_addr + F34_BLOCK_DATA_OFFSET; u8 start_address[] = { 0, 0 }; int i; int ret; ret = rmi_write_block(rmi_dev, fn->fd.data_base_addr, start_address, sizeof(start_address)); if (ret) { dev_err(&fn->dev, "Failed to write initial zeros: %d\n", ret); return ret; } for (i = 0; i < block_count; i++) { ret = rmi_write_block(rmi_dev, address, data, f34->v5.block_size); if (ret) { dev_err(&fn->dev, "failed to write block #%d: %d\n", i, ret); return ret; } ret = rmi_f34_command(f34, command, F34_IDLE_WAIT_MS, false); if (ret) { dev_err(&fn->dev, "Failed to write command for block #%d: %d\n", i, ret); return ret; } rmi_dbg(RMI_DEBUG_FN, &fn->dev, "wrote block %d of %d\n", i + 1, block_count); data += f34->v5.block_size; f34->update_progress += f34->v5.block_size; f34->update_status = (f34->update_progress * 100) / f34->update_size; } return 0; } static int rmi_f34_write_firmware(struct f34_data *f34, const void *data) { return rmi_f34_write_blocks(f34, data, f34->v5.fw_blocks, F34_WRITE_FW_BLOCK); } static int rmi_f34_write_config(struct f34_data *f34, const void *data) { return rmi_f34_write_blocks(f34, data, f34->v5.config_blocks, F34_WRITE_CONFIG_BLOCK); } static int rmi_f34_enable_flash(struct f34_data *f34) { return rmi_f34_command(f34, F34_ENABLE_FLASH_PROG, F34_ENABLE_WAIT_MS, true); } static int rmi_f34_flash_firmware(struct f34_data *f34, const struct rmi_f34_firmware *syn_fw) { struct rmi_function *fn = f34->fn; u32 image_size = le32_to_cpu(syn_fw->image_size); u32 config_size = le32_to_cpu(syn_fw->config_size); int ret; f34->update_progress = 0; f34->update_size = image_size + config_size; if (image_size) { dev_info(&fn->dev, "Erasing firmware...\n"); ret = rmi_f34_command(f34, F34_ERASE_ALL, F34_ERASE_WAIT_MS, true); if (ret) return ret; dev_info(&fn->dev, "Writing firmware (%d bytes)...\n", image_size); ret = rmi_f34_write_firmware(f34, syn_fw->data); if (ret) return ret; } if (config_size) { /* * We only need to erase config if we haven't updated * firmware. */ if (!image_size) { dev_info(&fn->dev, "Erasing config...\n"); ret = rmi_f34_command(f34, F34_ERASE_CONFIG, F34_ERASE_WAIT_MS, true); if (ret) return ret; } dev_info(&fn->dev, "Writing config (%d bytes)...\n", config_size); ret = rmi_f34_write_config(f34, &syn_fw->data[image_size]); if (ret) return ret; } return 0; } static int rmi_f34_update_firmware(struct f34_data *f34, const struct firmware *fw) { const struct rmi_f34_firmware *syn_fw = (const struct rmi_f34_firmware *)fw->data; u32 image_size = le32_to_cpu(syn_fw->image_size); u32 config_size = le32_to_cpu(syn_fw->config_size); int ret; BUILD_BUG_ON(offsetof(struct rmi_f34_firmware, data) != F34_FW_IMAGE_OFFSET); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "FW size:%zd, checksum:%08x, image_size:%d, config_size:%d\n", fw->size, le32_to_cpu(syn_fw->checksum), image_size, config_size); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "FW bootloader_id:%02x, product_id:%.*s, info: %02x%02x\n", syn_fw->bootloader_version, (int)sizeof(syn_fw->product_id), syn_fw->product_id, syn_fw->product_info[0], syn_fw->product_info[1]); if (image_size && image_size != f34->v5.fw_blocks * f34->v5.block_size) { dev_err(&f34->fn->dev, "Bad firmware image: fw size %d, expected %d\n", image_size, f34->v5.fw_blocks * f34->v5.block_size); ret = -EILSEQ; goto out; } if (config_size && config_size != f34->v5.config_blocks * f34->v5.block_size) { dev_err(&f34->fn->dev, "Bad firmware image: config size %d, expected %d\n", config_size, f34->v5.config_blocks * f34->v5.block_size); ret = -EILSEQ; goto out; } if (image_size && !config_size) { dev_err(&f34->fn->dev, "Bad firmware image: no config data\n"); ret = -EILSEQ; goto out; } dev_info(&f34->fn->dev, "Firmware image OK\n"); mutex_lock(&f34->v5.flash_mutex); ret = rmi_f34_flash_firmware(f34, syn_fw); mutex_unlock(&f34->v5.flash_mutex); out: return ret; } static int rmi_f34_status(struct rmi_function *fn) { struct f34_data *f34 = dev_get_drvdata(&fn->dev); /* * The status is the percentage complete, or once complete, * zero for success or a negative return code. */ return f34->update_status; } static ssize_t rmi_driver_bootloader_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct rmi_function *fn = data->f34_container; struct f34_data *f34; if (fn) { f34 = dev_get_drvdata(&fn->dev); if (f34->bl_version == 5) return sysfs_emit(buf, "%c%c\n", f34->bootloader_id[0], f34->bootloader_id[1]); else return sysfs_emit(buf, "V%d.%d\n", f34->bootloader_id[1], f34->bootloader_id[0]); } return 0; } static DEVICE_ATTR(bootloader_id, 0444, rmi_driver_bootloader_id_show, NULL); static ssize_t rmi_driver_configuration_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct rmi_function *fn = data->f34_container; struct f34_data *f34; if (fn) { f34 = dev_get_drvdata(&fn->dev); return sysfs_emit(buf, "%s\n", f34->configuration_id); } return 0; } static DEVICE_ATTR(configuration_id, 0444, rmi_driver_configuration_id_show, NULL); static int rmi_firmware_update(struct rmi_driver_data *data, const struct firmware *fw) { struct rmi_device *rmi_dev = data->rmi_dev; struct device *dev = &rmi_dev->dev; struct f34_data *f34; int ret; if (!data->f34_container) { dev_warn(dev, "%s: No F34 present!\n", __func__); return -EINVAL; } f34 = dev_get_drvdata(&data->f34_container->dev); if (f34->bl_version >= 7) { if (data->pdt_props & HAS_BSR) { dev_err(dev, "%s: LTS not supported\n", __func__); return -ENODEV; } } else if (f34->bl_version != 5) { dev_warn(dev, "F34 V%d not supported!\n", data->f34_container->fd.function_version); return -ENODEV; } /* Enter flash mode */ if (f34->bl_version >= 7) ret = rmi_f34v7_start_reflash(f34, fw); else ret = rmi_f34_enable_flash(f34); if (ret) return ret; rmi_disable_irq(rmi_dev, false); /* Tear down functions and re-probe */ rmi_free_function_list(rmi_dev); ret = rmi_probe_interrupts(data); if (ret) return ret; ret = rmi_init_functions(data); if (ret) return ret; if (!data->bootloader_mode || !data->f34_container) { dev_warn(dev, "%s: No F34 present or not in bootloader!\n", __func__); return -EINVAL; } rmi_enable_irq(rmi_dev, false); f34 = dev_get_drvdata(&data->f34_container->dev); /* Perform firmware update */ if (f34->bl_version >= 7) ret = rmi_f34v7_do_reflash(f34, fw); else ret = rmi_f34_update_firmware(f34, fw); if (ret) { f34->update_status = ret; dev_err(&f34->fn->dev, "Firmware update failed, status: %d\n", ret); } else { dev_info(&f34->fn->dev, "Firmware update complete\n"); } rmi_disable_irq(rmi_dev, false); /* Re-probe */ rmi_dbg(RMI_DEBUG_FN, dev, "Re-probing device\n"); rmi_free_function_list(rmi_dev); ret = rmi_scan_pdt(rmi_dev, NULL, rmi_initial_reset); if (ret < 0) dev_warn(dev, "RMI reset failed!\n"); ret = rmi_probe_interrupts(data); if (ret) return ret; ret = rmi_init_functions(data); if (ret) return ret; rmi_enable_irq(rmi_dev, false); if (data->f01_container->dev.driver) /* Driver already bound, so enable ATTN now. */ return rmi_enable_sensor(rmi_dev); rmi_dbg(RMI_DEBUG_FN, dev, "%s complete\n", __func__); return ret; } static ssize_t rmi_driver_update_fw_store(struct device *dev, struct device_attribute *dattr, const char *buf, size_t count) { struct rmi_driver_data *data = dev_get_drvdata(dev); char fw_name[NAME_MAX]; const struct firmware *fw; size_t copy_count = count; int ret; if (count == 0 || count >= NAME_MAX) return -EINVAL; if (buf[count - 1] == '\0' || buf[count - 1] == '\n') copy_count -= 1; strncpy(fw_name, buf, copy_count); fw_name[copy_count] = '\0'; ret = request_firmware(&fw, fw_name, dev); if (ret) return ret; dev_info(dev, "Flashing %s\n", fw_name); ret = rmi_firmware_update(data, fw); release_firmware(fw); return ret ?: count; } static DEVICE_ATTR(update_fw, 0200, NULL, rmi_driver_update_fw_store); static ssize_t rmi_driver_update_fw_status_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); int update_status = 0; if (data->f34_container) update_status = rmi_f34_status(data->f34_container); return sysfs_emit(buf, "%d\n", update_status); } static DEVICE_ATTR(update_fw_status, 0444, rmi_driver_update_fw_status_show, NULL); static struct attribute *rmi_firmware_attrs[] = { &dev_attr_bootloader_id.attr, &dev_attr_configuration_id.attr, &dev_attr_update_fw.attr, &dev_attr_update_fw_status.attr, NULL }; static const struct attribute_group rmi_firmware_attr_group = { .attrs = rmi_firmware_attrs, }; static int rmi_f34_probe(struct rmi_function *fn) { struct f34_data *f34; unsigned char f34_queries[9]; bool has_config_id; u8 version = fn->fd.function_version; int ret; f34 = devm_kzalloc(&fn->dev, sizeof(struct f34_data), GFP_KERNEL); if (!f34) return -ENOMEM; f34->fn = fn; dev_set_drvdata(&fn->dev, f34); /* v5 code only supported version 0, try V7 probe */ if (version > 0) return rmi_f34v7_probe(f34); f34->bl_version = 5; ret = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr, f34_queries, sizeof(f34_queries)); if (ret) { dev_err(&fn->dev, "%s: Failed to query properties\n", __func__); return ret; } snprintf(f34->bootloader_id, sizeof(f34->bootloader_id), "%c%c", f34_queries[0], f34_queries[1]); mutex_init(&f34->v5.flash_mutex); init_completion(&f34->v5.cmd_done); f34->v5.block_size = get_unaligned_le16(&f34_queries[3]); f34->v5.fw_blocks = get_unaligned_le16(&f34_queries[5]); f34->v5.config_blocks = get_unaligned_le16(&f34_queries[7]); f34->v5.ctrl_address = fn->fd.data_base_addr + F34_BLOCK_DATA_OFFSET + f34->v5.block_size; has_config_id = f34_queries[2] & (1 << 2); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Bootloader ID: %s\n", f34->bootloader_id); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Block size: %d\n", f34->v5.block_size); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "FW blocks: %d\n", f34->v5.fw_blocks); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "CFG blocks: %d\n", f34->v5.config_blocks); if (has_config_id) { ret = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr, f34_queries, sizeof(f34_queries)); if (ret) { dev_err(&fn->dev, "Failed to read F34 config ID\n"); return ret; } snprintf(f34->configuration_id, sizeof(f34->configuration_id), "%02x%02x%02x%02x", f34_queries[0], f34_queries[1], f34_queries[2], f34_queries[3]); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Configuration ID: %s\n", f34->configuration_id); } return 0; } int rmi_f34_create_sysfs(struct rmi_device *rmi_dev) { return sysfs_create_group(&rmi_dev->dev.kobj, &rmi_firmware_attr_group); } void rmi_f34_remove_sysfs(struct rmi_device *rmi_dev) { sysfs_remove_group(&rmi_dev->dev.kobj, &rmi_firmware_attr_group); } struct rmi_function_handler rmi_f34_handler = { .driver = { .name = "rmi4_f34", }, .func = 0x34, .probe = rmi_f34_probe, .attention = rmi_f34_attention, };
linux-master
drivers/input/rmi4/rmi_f34.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2012-2015 Synaptics Incorporated * Copyright (C) 2016 Zodiac Inflight Innovations */ #include <linux/bitops.h> #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/slab.h> #include "rmi_driver.h" #define F55_NAME "rmi4_f55" /* F55 data offsets */ #define F55_NUM_RX_OFFSET 0 #define F55_NUM_TX_OFFSET 1 #define F55_PHYS_CHAR_OFFSET 2 /* Only read required query registers */ #define F55_QUERY_LEN 3 /* F55 capabilities */ #define F55_CAP_SENSOR_ASSIGN BIT(0) struct f55_data { struct rmi_function *fn; u8 qry[F55_QUERY_LEN]; u8 num_rx_electrodes; u8 cfg_num_rx_electrodes; u8 num_tx_electrodes; u8 cfg_num_tx_electrodes; }; static int rmi_f55_detect(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); struct f55_data *f55; int error; f55 = dev_get_drvdata(&fn->dev); error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr, &f55->qry, sizeof(f55->qry)); if (error) { dev_err(&fn->dev, "%s: Failed to query F55 properties\n", __func__); return error; } f55->num_rx_electrodes = f55->qry[F55_NUM_RX_OFFSET]; f55->num_tx_electrodes = f55->qry[F55_NUM_TX_OFFSET]; f55->cfg_num_rx_electrodes = f55->num_rx_electrodes; f55->cfg_num_tx_electrodes = f55->num_rx_electrodes; drv_data->num_rx_electrodes = f55->cfg_num_rx_electrodes; drv_data->num_tx_electrodes = f55->cfg_num_rx_electrodes; if (f55->qry[F55_PHYS_CHAR_OFFSET] & F55_CAP_SENSOR_ASSIGN) { int i, total; u8 buf[256]; /* * Calculate the number of enabled receive and transmit * electrodes by reading F55:Ctrl1 (sensor receiver assignment) * and F55:Ctrl2 (sensor transmitter assignment). The number of * enabled electrodes is the sum of all field entries with a * value other than 0xff. */ error = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr + 1, buf, f55->num_rx_electrodes); if (!error) { total = 0; for (i = 0; i < f55->num_rx_electrodes; i++) { if (buf[i] != 0xff) total++; } f55->cfg_num_rx_electrodes = total; drv_data->num_rx_electrodes = total; } error = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr + 2, buf, f55->num_tx_electrodes); if (!error) { total = 0; for (i = 0; i < f55->num_tx_electrodes; i++) { if (buf[i] != 0xff) total++; } f55->cfg_num_tx_electrodes = total; drv_data->num_tx_electrodes = total; } } rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F55 num_rx_electrodes: %d (raw %d)\n", f55->cfg_num_rx_electrodes, f55->num_rx_electrodes); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F55 num_tx_electrodes: %d (raw %d)\n", f55->cfg_num_tx_electrodes, f55->num_tx_electrodes); return 0; } static int rmi_f55_probe(struct rmi_function *fn) { struct f55_data *f55; f55 = devm_kzalloc(&fn->dev, sizeof(struct f55_data), GFP_KERNEL); if (!f55) return -ENOMEM; f55->fn = fn; dev_set_drvdata(&fn->dev, f55); return rmi_f55_detect(fn); } struct rmi_function_handler rmi_f55_handler = { .driver = { .name = F55_NAME, }, .func = 0x55, .probe = rmi_f55_probe, };
linux-master
drivers/input/rmi4/rmi_f55.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2015 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/rmi.h> #include <linux/slab.h> #include <linux/of.h> #include "rmi_driver.h" #include "rmi_2d_sensor.h" #define F11_MAX_NUM_OF_FINGERS 10 #define F11_MAX_NUM_OF_TOUCH_SHAPES 16 #define FINGER_STATE_MASK 0x03 #define F11_CTRL_SENSOR_MAX_X_POS_OFFSET 6 #define F11_CTRL_SENSOR_MAX_Y_POS_OFFSET 8 #define DEFAULT_XY_MAX 9999 #define DEFAULT_MAX_ABS_MT_PRESSURE 255 #define DEFAULT_MAX_ABS_MT_TOUCH 15 #define DEFAULT_MAX_ABS_MT_ORIENTATION 1 #define DEFAULT_MIN_ABS_MT_TRACKING_ID 1 #define DEFAULT_MAX_ABS_MT_TRACKING_ID 10 /* * A note about RMI4 F11 register structure. * * The properties for a given sensor are described by its query registers. The * number of query registers and the layout of their contents are described by * the F11 device queries as well as the sensor query information. * * Similarly, each sensor has control registers that govern its behavior. The * size and layout of the control registers for a given sensor can be determined * by parsing that sensors query registers. * * And in a likewise fashion, each sensor has data registers where it reports * its touch data and other interesting stuff. The size and layout of a * sensors data registers must be determined by parsing its query registers. * * The short story is that we need to read and parse a lot of query * registers in order to determine the attributes of a sensor. Then * we need to use that data to compute the size of the control and data * registers for sensor. * * The end result is that we have a number of structs that aren't used to * directly generate the input events, but their size, location and contents * are critical to determining where the data we are interested in lives. * * At this time, the driver does not yet comprehend all possible F11 * configuration options, but it should be sufficient to cover 99% of RMI4 F11 * devices currently in the field. */ /* maximum ABS_MT_POSITION displacement (in mm) */ #define DMAX 10 /* * Writing this to the F11 command register will cause the sensor to * calibrate to the current capacitive state. */ #define RMI_F11_REZERO 0x01 #define RMI_F11_HAS_QUERY9 (1 << 3) #define RMI_F11_HAS_QUERY11 (1 << 4) #define RMI_F11_HAS_QUERY12 (1 << 5) #define RMI_F11_HAS_QUERY27 (1 << 6) #define RMI_F11_HAS_QUERY28 (1 << 7) /** Defs for Query 1 */ #define RMI_F11_NR_FINGERS_MASK 0x07 #define RMI_F11_HAS_REL (1 << 3) #define RMI_F11_HAS_ABS (1 << 4) #define RMI_F11_HAS_GESTURES (1 << 5) #define RMI_F11_HAS_SENSITIVITY_ADJ (1 << 6) #define RMI_F11_CONFIGURABLE (1 << 7) /** Defs for Query 2, 3, and 4. */ #define RMI_F11_NR_ELECTRODES_MASK 0x7F /** Defs for Query 5 */ #define RMI_F11_ABS_DATA_SIZE_MASK 0x03 #define RMI_F11_HAS_ANCHORED_FINGER (1 << 2) #define RMI_F11_HAS_ADJ_HYST (1 << 3) #define RMI_F11_HAS_DRIBBLE (1 << 4) #define RMI_F11_HAS_BENDING_CORRECTION (1 << 5) #define RMI_F11_HAS_LARGE_OBJECT_SUPPRESSION (1 << 6) #define RMI_F11_HAS_JITTER_FILTER (1 << 7) /** Defs for Query 7 */ #define RMI_F11_HAS_SINGLE_TAP (1 << 0) #define RMI_F11_HAS_TAP_AND_HOLD (1 << 1) #define RMI_F11_HAS_DOUBLE_TAP (1 << 2) #define RMI_F11_HAS_EARLY_TAP (1 << 3) #define RMI_F11_HAS_FLICK (1 << 4) #define RMI_F11_HAS_PRESS (1 << 5) #define RMI_F11_HAS_PINCH (1 << 6) #define RMI_F11_HAS_CHIRAL (1 << 7) /** Defs for Query 8 */ #define RMI_F11_HAS_PALM_DET (1 << 0) #define RMI_F11_HAS_ROTATE (1 << 1) #define RMI_F11_HAS_TOUCH_SHAPES (1 << 2) #define RMI_F11_HAS_SCROLL_ZONES (1 << 3) #define RMI_F11_HAS_INDIVIDUAL_SCROLL_ZONES (1 << 4) #define RMI_F11_HAS_MF_SCROLL (1 << 5) #define RMI_F11_HAS_MF_EDGE_MOTION (1 << 6) #define RMI_F11_HAS_MF_SCROLL_INERTIA (1 << 7) /** Defs for Query 9. */ #define RMI_F11_HAS_PEN (1 << 0) #define RMI_F11_HAS_PROXIMITY (1 << 1) #define RMI_F11_HAS_PALM_DET_SENSITIVITY (1 << 2) #define RMI_F11_HAS_SUPPRESS_ON_PALM_DETECT (1 << 3) #define RMI_F11_HAS_TWO_PEN_THRESHOLDS (1 << 4) #define RMI_F11_HAS_CONTACT_GEOMETRY (1 << 5) #define RMI_F11_HAS_PEN_HOVER_DISCRIMINATION (1 << 6) #define RMI_F11_HAS_PEN_FILTERS (1 << 7) /** Defs for Query 10. */ #define RMI_F11_NR_TOUCH_SHAPES_MASK 0x1F /** Defs for Query 11 */ #define RMI_F11_HAS_Z_TUNING (1 << 0) #define RMI_F11_HAS_ALGORITHM_SELECTION (1 << 1) #define RMI_F11_HAS_W_TUNING (1 << 2) #define RMI_F11_HAS_PITCH_INFO (1 << 3) #define RMI_F11_HAS_FINGER_SIZE (1 << 4) #define RMI_F11_HAS_SEGMENTATION_AGGRESSIVENESS (1 << 5) #define RMI_F11_HAS_XY_CLIP (1 << 6) #define RMI_F11_HAS_DRUMMING_FILTER (1 << 7) /** Defs for Query 12. */ #define RMI_F11_HAS_GAPLESS_FINGER (1 << 0) #define RMI_F11_HAS_GAPLESS_FINGER_TUNING (1 << 1) #define RMI_F11_HAS_8BIT_W (1 << 2) #define RMI_F11_HAS_ADJUSTABLE_MAPPING (1 << 3) #define RMI_F11_HAS_INFO2 (1 << 4) #define RMI_F11_HAS_PHYSICAL_PROPS (1 << 5) #define RMI_F11_HAS_FINGER_LIMIT (1 << 6) #define RMI_F11_HAS_LINEAR_COEFF (1 << 7) /** Defs for Query 13. */ #define RMI_F11_JITTER_WINDOW_MASK 0x1F #define RMI_F11_JITTER_FILTER_MASK 0x60 #define RMI_F11_JITTER_FILTER_SHIFT 5 /** Defs for Query 14. */ #define RMI_F11_LIGHT_CONTROL_MASK 0x03 #define RMI_F11_IS_CLEAR (1 << 2) #define RMI_F11_CLICKPAD_PROPS_MASK 0x18 #define RMI_F11_CLICKPAD_PROPS_SHIFT 3 #define RMI_F11_MOUSE_BUTTONS_MASK 0x60 #define RMI_F11_MOUSE_BUTTONS_SHIFT 5 #define RMI_F11_HAS_ADVANCED_GESTURES (1 << 7) #define RMI_F11_QUERY_SIZE 4 #define RMI_F11_QUERY_GESTURE_SIZE 2 #define F11_LIGHT_CTL_NONE 0x00 #define F11_LUXPAD 0x01 #define F11_DUAL_MODE 0x02 #define F11_NOT_CLICKPAD 0x00 #define F11_HINGED_CLICKPAD 0x01 #define F11_UNIFORM_CLICKPAD 0x02 /** * struct f11_2d_sensor_queries - describes sensor capabilities * * Query registers 1 through 4 are always present. * * @nr_fingers: describes the maximum number of fingers the 2-D sensor * supports. * @has_rel: the sensor supports relative motion reporting. * @has_abs: the sensor supports absolute poition reporting. * @has_gestures: the sensor supports gesture reporting. * @has_sensitivity_adjust: the sensor supports a global sensitivity * adjustment. * @configurable: the sensor supports various configuration options. * @nr_x_electrodes: the maximum number of electrodes the 2-D sensor * supports on the X axis. * @nr_y_electrodes: the maximum number of electrodes the 2-D sensor * supports on the Y axis. * @max_electrodes: the total number of X and Y electrodes that may be * configured. * * Query 5 is present if the has_abs bit is set. * * @abs_data_size: describes the format of data reported by the absolute * data source. Only one format (the kind used here) is supported at this * time. * @has_anchored_finger: then the sensor supports the high-precision second * finger tracking provided by the manual tracking and motion sensitivity * options. * @has_adj_hyst: the difference between the finger release threshold and * the touch threshold. * @has_dribble: the sensor supports the generation of dribble interrupts, * which may be enabled or disabled with the dribble control bit. * @has_bending_correction: Bending related data registers 28 and 36, and * control register 52..57 are present. * @has_large_object_suppression: control register 58 and data register 28 * exist. * @has_jitter_filter: query 13 and control 73..76 exist. * * Query 6 is present if the has_rel it is set. * * @f11_2d_query6: this register is reserved. * * Gesture information queries 7 and 8 are present if has_gestures bit is set. * * @has_single_tap: a basic single-tap gesture is supported. * @has_tap_n_hold: tap-and-hold gesture is supported. * @has_double_tap: double-tap gesture is supported. * @has_early_tap: early tap is supported and reported as soon as the finger * lifts for any tap event that could be interpreted as either a single * tap or as the first tap of a double-tap or tap-and-hold gesture. * @has_flick: flick detection is supported. * @has_press: press gesture reporting is supported. * @has_pinch: pinch gesture detection is supported. * @has_chiral: chiral (circular) scrolling gesture detection is supported. * @has_palm_det: the 2-D sensor notifies the host whenever a large conductive * object such as a palm or a cheek touches the 2-D sensor. * @has_rotate: rotation gesture detection is supported. * @has_touch_shapes: TouchShapes are supported. A TouchShape is a fixed * rectangular area on the sensor that behaves like a capacitive button. * @has_scroll_zones: scrolling areas near the sensor edges are supported. * @has_individual_scroll_zones: if 1, then 4 scroll zones are supported; * if 0, then only two are supported. * @has_mf_scroll: the multifinger_scrolling bit will be set when * more than one finger is involved in a scrolling action. * @has_mf_edge_motion: indicates whether multi-finger edge motion gesture * is supported. * @has_mf_scroll_inertia: indicates whether multi-finger scroll inertia * feature is supported. * * Convenience for checking bytes in the gesture info registers. This is done * often enough that we put it here to declutter the conditionals * * @query7_nonzero: true if none of the query 7 bits are set * @query8_nonzero: true if none of the query 8 bits are set * * Query 9 is present if the has_query9 is set. * * @has_pen: detection of a stylus is supported and registers F11_2D_Ctrl20 * and F11_2D_Ctrl21 exist. * @has_proximity: detection of fingers near the sensor is supported and * registers F11_2D_Ctrl22 through F11_2D_Ctrl26 exist. * @has_palm_det_sensitivity: the sensor supports the palm detect sensitivity * feature and register F11_2D_Ctrl27 exists. * @has_suppress_on_palm_detect: the device supports the large object detect * suppression feature and register F11_2D_Ctrl27 exists. * @has_two_pen_thresholds: if has_pen is also set, then F11_2D_Ctrl35 exists. * @has_contact_geometry: the sensor supports the use of contact geometry to * map absolute X and Y target positions and registers F11_2D_Data18 * through F11_2D_Data27 exist. * @has_pen_hover_discrimination: if has_pen is also set, then registers * F11_2D_Data29 through F11_2D_Data31, F11_2D_Ctrl68.*, F11_2D_Ctrl69 * and F11_2D_Ctrl72 exist. * @has_pen_filters: if has_pen is also set, then registers F11_2D_Ctrl70 and * F11_2D_Ctrl71 exist. * * Touch shape info (query 10) is present if has_touch_shapes is set. * * @nr_touch_shapes: the total number of touch shapes supported. * * Query 11 is present if the has_query11 bit is set in query 0. * * @has_z_tuning: if set, the sensor supports Z tuning and registers * F11_2D_Ctrl29 through F11_2D_Ctrl33 exist. * @has_algorithm_selection: controls choice of noise suppression algorithm * @has_w_tuning: the sensor supports Wx and Wy scaling and registers * F11_2D_Ctrl36 through F11_2D_Ctrl39 exist. * @has_pitch_info: the X and Y pitches of the sensor electrodes can be * configured and registers F11_2D_Ctrl40 and F11_2D_Ctrl41 exist. * @has_finger_size: the default finger width settings for the sensor * can be configured and registers F11_2D_Ctrl42 through F11_2D_Ctrl44 * exist. * @has_segmentation_aggressiveness: the sensor’s ability to distinguish * multiple objects close together can be configured and register * F11_2D_Ctrl45 exists. * @has_XY_clip: the inactive outside borders of the sensor can be * configured and registers F11_2D_Ctrl46 through F11_2D_Ctrl49 exist. * @has_drumming_filter: the sensor can be configured to distinguish * between a fast flick and a quick drumming movement and registers * F11_2D_Ctrl50 and F11_2D_Ctrl51 exist. * * Query 12 is present if hasQuery12 bit is set. * * @has_gapless_finger: control registers relating to gapless finger are * present. * @has_gapless_finger_tuning: additional control and data registers relating * to gapless finger are present. * @has_8bit_w: larger W value reporting is supported. * @has_adjustable_mapping: TBD * @has_info2: the general info query14 is present * @has_physical_props: additional queries describing the physical properties * of the sensor are present. * @has_finger_limit: indicates that F11 Ctrl 80 exists. * @has_linear_coeff_2: indicates that F11 Ctrl 81 exists. * * Query 13 is present if Query 5's has_jitter_filter bit is set. * * @jitter_window_size: used by Design Studio 4. * @jitter_filter_type: used by Design Studio 4. * * Query 14 is present if query 12's has_general_info2 flag is set. * * @light_control: Indicates what light/led control features are present, * if any. * @is_clear: if set, this is a clear sensor (indicating direct pointing * application), otherwise it's opaque (indicating indirect pointing). * @clickpad_props: specifies if this is a clickpad, and if so what sort of * mechanism it uses * @mouse_buttons: specifies the number of mouse buttons present (if any). * @has_advanced_gestures: advanced driver gestures are supported. * * @x_sensor_size_mm: size of the sensor in millimeters on the X axis. * @y_sensor_size_mm: size of the sensor in millimeters on the Y axis. */ struct f11_2d_sensor_queries { /* query1 */ u8 nr_fingers; bool has_rel; bool has_abs; bool has_gestures; bool has_sensitivity_adjust; bool configurable; /* query2 */ u8 nr_x_electrodes; /* query3 */ u8 nr_y_electrodes; /* query4 */ u8 max_electrodes; /* query5 */ u8 abs_data_size; bool has_anchored_finger; bool has_adj_hyst; bool has_dribble; bool has_bending_correction; bool has_large_object_suppression; bool has_jitter_filter; u8 f11_2d_query6; /* query 7 */ bool has_single_tap; bool has_tap_n_hold; bool has_double_tap; bool has_early_tap; bool has_flick; bool has_press; bool has_pinch; bool has_chiral; bool query7_nonzero; /* query 8 */ bool has_palm_det; bool has_rotate; bool has_touch_shapes; bool has_scroll_zones; bool has_individual_scroll_zones; bool has_mf_scroll; bool has_mf_edge_motion; bool has_mf_scroll_inertia; bool query8_nonzero; /* Query 9 */ bool has_pen; bool has_proximity; bool has_palm_det_sensitivity; bool has_suppress_on_palm_detect; bool has_two_pen_thresholds; bool has_contact_geometry; bool has_pen_hover_discrimination; bool has_pen_filters; /* Query 10 */ u8 nr_touch_shapes; /* Query 11. */ bool has_z_tuning; bool has_algorithm_selection; bool has_w_tuning; bool has_pitch_info; bool has_finger_size; bool has_segmentation_aggressiveness; bool has_XY_clip; bool has_drumming_filter; /* Query 12 */ bool has_gapless_finger; bool has_gapless_finger_tuning; bool has_8bit_w; bool has_adjustable_mapping; bool has_info2; bool has_physical_props; bool has_finger_limit; bool has_linear_coeff_2; /* Query 13 */ u8 jitter_window_size; u8 jitter_filter_type; /* Query 14 */ u8 light_control; bool is_clear; u8 clickpad_props; u8 mouse_buttons; bool has_advanced_gestures; /* Query 15 - 18 */ u16 x_sensor_size_mm; u16 y_sensor_size_mm; }; /* Defs for Ctrl0. */ #define RMI_F11_REPORT_MODE_MASK 0x07 #define RMI_F11_REPORT_MODE_CONTINUOUS (0 << 0) #define RMI_F11_REPORT_MODE_REDUCED (1 << 0) #define RMI_F11_REPORT_MODE_FS_CHANGE (2 << 0) #define RMI_F11_REPORT_MODE_FP_CHANGE (3 << 0) #define RMI_F11_ABS_POS_FILT (1 << 3) #define RMI_F11_REL_POS_FILT (1 << 4) #define RMI_F11_REL_BALLISTICS (1 << 5) #define RMI_F11_DRIBBLE (1 << 6) #define RMI_F11_REPORT_BEYOND_CLIP (1 << 7) /* Defs for Ctrl1. */ #define RMI_F11_PALM_DETECT_THRESH_MASK 0x0F #define RMI_F11_MOTION_SENSITIVITY_MASK 0x30 #define RMI_F11_MANUAL_TRACKING (1 << 6) #define RMI_F11_MANUAL_TRACKED_FINGER (1 << 7) #define RMI_F11_DELTA_X_THRESHOLD 2 #define RMI_F11_DELTA_Y_THRESHOLD 3 #define RMI_F11_CTRL_REG_COUNT 12 struct f11_2d_ctrl { u8 ctrl0_11[RMI_F11_CTRL_REG_COUNT]; u16 ctrl0_11_address; }; #define RMI_F11_ABS_BYTES 5 #define RMI_F11_REL_BYTES 2 /* Defs for Data 8 */ #define RMI_F11_SINGLE_TAP (1 << 0) #define RMI_F11_TAP_AND_HOLD (1 << 1) #define RMI_F11_DOUBLE_TAP (1 << 2) #define RMI_F11_EARLY_TAP (1 << 3) #define RMI_F11_FLICK (1 << 4) #define RMI_F11_PRESS (1 << 5) #define RMI_F11_PINCH (1 << 6) /* Defs for Data 9 */ #define RMI_F11_PALM_DETECT (1 << 0) #define RMI_F11_ROTATE (1 << 1) #define RMI_F11_SHAPE (1 << 2) #define RMI_F11_SCROLLZONE (1 << 3) #define RMI_F11_GESTURE_FINGER_COUNT_MASK 0x70 /** Handy pointers into our data buffer. * * @f_state - start of finger state registers. * @abs_pos - start of absolute position registers (if present). * @rel_pos - start of relative data registers (if present). * @gest_1 - gesture flags (if present). * @gest_2 - gesture flags & finger count (if present). * @pinch - pinch motion register (if present). * @flick - flick distance X & Y, flick time (if present). * @rotate - rotate motion and finger separation. * @multi_scroll - chiral deltas for X and Y (if present). * @scroll_zones - scroll deltas for 4 regions (if present). */ struct f11_2d_data { u8 *f_state; u8 *abs_pos; s8 *rel_pos; u8 *gest_1; u8 *gest_2; s8 *pinch; u8 *flick; u8 *rotate; u8 *shapes; s8 *multi_scroll; s8 *scroll_zones; }; /** Data pertaining to F11 in general. For per-sensor data, see struct * f11_2d_sensor. * * @dev_query - F11 device specific query registers. * @dev_controls - F11 device specific control registers. * @dev_controls_mutex - lock for the control registers. * @rezero_wait_ms - if nonzero, upon resume we will wait this many * milliseconds before rezeroing the sensor(s). This is useful in systems with * poor electrical behavior on resume, where the initial calibration of the * sensor(s) coming out of sleep state may be bogus. * @sensors - per sensor data structures. */ struct f11_data { bool has_query9; bool has_query11; bool has_query12; bool has_query27; bool has_query28; bool has_acm; struct f11_2d_ctrl dev_controls; struct mutex dev_controls_mutex; u16 rezero_wait_ms; struct rmi_2d_sensor sensor; struct f11_2d_sensor_queries sens_query; struct f11_2d_data data; struct rmi_2d_sensor_platform_data sensor_pdata; unsigned long *abs_mask; unsigned long *rel_mask; }; enum f11_finger_state { F11_NO_FINGER = 0x00, F11_PRESENT = 0x01, F11_INACCURATE = 0x02, F11_RESERVED = 0x03 }; static void rmi_f11_rel_pos_report(struct f11_data *f11, u8 n_finger) { struct rmi_2d_sensor *sensor = &f11->sensor; struct f11_2d_data *data = &f11->data; s8 x, y; x = data->rel_pos[n_finger * RMI_F11_REL_BYTES]; y = data->rel_pos[n_finger * RMI_F11_REL_BYTES + 1]; rmi_2d_sensor_rel_report(sensor, x, y); } static void rmi_f11_abs_pos_process(struct f11_data *f11, struct rmi_2d_sensor *sensor, struct rmi_2d_sensor_abs_object *obj, enum f11_finger_state finger_state, u8 n_finger) { struct f11_2d_data *data = &f11->data; u8 *pos_data = &data->abs_pos[n_finger * RMI_F11_ABS_BYTES]; int tool_type = MT_TOOL_FINGER; switch (finger_state) { case F11_PRESENT: obj->type = RMI_2D_OBJECT_FINGER; break; default: obj->type = RMI_2D_OBJECT_NONE; } obj->mt_tool = tool_type; obj->x = (pos_data[0] << 4) | (pos_data[2] & 0x0F); obj->y = (pos_data[1] << 4) | (pos_data[2] >> 4); obj->z = pos_data[4]; obj->wx = pos_data[3] & 0x0f; obj->wy = pos_data[3] >> 4; rmi_2d_sensor_abs_process(sensor, obj, n_finger); } static inline u8 rmi_f11_parse_finger_state(const u8 *f_state, u8 n_finger) { return (f_state[n_finger / 4] >> (2 * (n_finger % 4))) & FINGER_STATE_MASK; } static void rmi_f11_finger_handler(struct f11_data *f11, struct rmi_2d_sensor *sensor, int size) { const u8 *f_state = f11->data.f_state; u8 finger_state; u8 i; int abs_fingers; int rel_fingers; int abs_size = sensor->nbr_fingers * RMI_F11_ABS_BYTES; if (sensor->report_abs) { if (abs_size > size) abs_fingers = size / RMI_F11_ABS_BYTES; else abs_fingers = sensor->nbr_fingers; for (i = 0; i < abs_fingers; i++) { /* Possible of having 4 fingers per f_state register */ finger_state = rmi_f11_parse_finger_state(f_state, i); if (finger_state == F11_RESERVED) { pr_err("Invalid finger state[%d]: 0x%02x", i, finger_state); continue; } rmi_f11_abs_pos_process(f11, sensor, &sensor->objs[i], finger_state, i); } /* * the absolute part is made in 2 parts to allow the kernel * tracking to take place. */ if (sensor->kernel_tracking) input_mt_assign_slots(sensor->input, sensor->tracking_slots, sensor->tracking_pos, sensor->nbr_fingers, sensor->dmax); for (i = 0; i < abs_fingers; i++) { finger_state = rmi_f11_parse_finger_state(f_state, i); if (finger_state == F11_RESERVED) /* no need to send twice the error */ continue; rmi_2d_sensor_abs_report(sensor, &sensor->objs[i], i); } input_mt_sync_frame(sensor->input); } else if (sensor->report_rel) { if ((abs_size + sensor->nbr_fingers * RMI_F11_REL_BYTES) > size) rel_fingers = (size - abs_size) / RMI_F11_REL_BYTES; else rel_fingers = sensor->nbr_fingers; for (i = 0; i < rel_fingers; i++) rmi_f11_rel_pos_report(f11, i); } } static int f11_2d_construct_data(struct f11_data *f11) { struct rmi_2d_sensor *sensor = &f11->sensor; struct f11_2d_sensor_queries *query = &f11->sens_query; struct f11_2d_data *data = &f11->data; int i; sensor->nbr_fingers = (query->nr_fingers == 5 ? 10 : query->nr_fingers + 1); sensor->pkt_size = DIV_ROUND_UP(sensor->nbr_fingers, 4); if (query->has_abs) { sensor->pkt_size += (sensor->nbr_fingers * 5); sensor->attn_size = sensor->pkt_size; } if (query->has_rel) sensor->pkt_size += (sensor->nbr_fingers * 2); /* Check if F11_2D_Query7 is non-zero */ if (query->query7_nonzero) sensor->pkt_size += sizeof(u8); /* Check if F11_2D_Query7 or F11_2D_Query8 is non-zero */ if (query->query7_nonzero || query->query8_nonzero) sensor->pkt_size += sizeof(u8); if (query->has_pinch || query->has_flick || query->has_rotate) { sensor->pkt_size += 3; if (!query->has_flick) sensor->pkt_size--; if (!query->has_rotate) sensor->pkt_size--; } if (query->has_touch_shapes) sensor->pkt_size += DIV_ROUND_UP(query->nr_touch_shapes + 1, 8); sensor->data_pkt = devm_kzalloc(&sensor->fn->dev, sensor->pkt_size, GFP_KERNEL); if (!sensor->data_pkt) return -ENOMEM; data->f_state = sensor->data_pkt; i = DIV_ROUND_UP(sensor->nbr_fingers, 4); if (query->has_abs) { data->abs_pos = &sensor->data_pkt[i]; i += (sensor->nbr_fingers * RMI_F11_ABS_BYTES); } if (query->has_rel) { data->rel_pos = &sensor->data_pkt[i]; i += (sensor->nbr_fingers * RMI_F11_REL_BYTES); } if (query->query7_nonzero) { data->gest_1 = &sensor->data_pkt[i]; i++; } if (query->query7_nonzero || query->query8_nonzero) { data->gest_2 = &sensor->data_pkt[i]; i++; } if (query->has_pinch) { data->pinch = &sensor->data_pkt[i]; i++; } if (query->has_flick) { if (query->has_pinch) { data->flick = data->pinch; i += 2; } else { data->flick = &sensor->data_pkt[i]; i += 3; } } if (query->has_rotate) { if (query->has_flick) { data->rotate = data->flick + 1; } else { data->rotate = &sensor->data_pkt[i]; i += 2; } } if (query->has_touch_shapes) data->shapes = &sensor->data_pkt[i]; return 0; } static int f11_read_control_regs(struct rmi_function *fn, struct f11_2d_ctrl *ctrl, u16 ctrl_base_addr) { struct rmi_device *rmi_dev = fn->rmi_dev; int error = 0; ctrl->ctrl0_11_address = ctrl_base_addr; error = rmi_read_block(rmi_dev, ctrl_base_addr, ctrl->ctrl0_11, RMI_F11_CTRL_REG_COUNT); if (error < 0) { dev_err(&fn->dev, "Failed to read ctrl0, code: %d.\n", error); return error; } return 0; } static int f11_write_control_regs(struct rmi_function *fn, struct f11_2d_sensor_queries *query, struct f11_2d_ctrl *ctrl, u16 ctrl_base_addr) { struct rmi_device *rmi_dev = fn->rmi_dev; int error; error = rmi_write_block(rmi_dev, ctrl_base_addr, ctrl->ctrl0_11, RMI_F11_CTRL_REG_COUNT); if (error < 0) return error; return 0; } static int rmi_f11_get_query_parameters(struct rmi_device *rmi_dev, struct f11_data *f11, struct f11_2d_sensor_queries *sensor_query, u16 query_base_addr) { int query_size; int rc; u8 query_buf[RMI_F11_QUERY_SIZE]; bool has_query36 = false; rc = rmi_read_block(rmi_dev, query_base_addr, query_buf, RMI_F11_QUERY_SIZE); if (rc < 0) return rc; sensor_query->nr_fingers = query_buf[0] & RMI_F11_NR_FINGERS_MASK; sensor_query->has_rel = !!(query_buf[0] & RMI_F11_HAS_REL); sensor_query->has_abs = !!(query_buf[0] & RMI_F11_HAS_ABS); sensor_query->has_gestures = !!(query_buf[0] & RMI_F11_HAS_GESTURES); sensor_query->has_sensitivity_adjust = !!(query_buf[0] & RMI_F11_HAS_SENSITIVITY_ADJ); sensor_query->configurable = !!(query_buf[0] & RMI_F11_CONFIGURABLE); sensor_query->nr_x_electrodes = query_buf[1] & RMI_F11_NR_ELECTRODES_MASK; sensor_query->nr_y_electrodes = query_buf[2] & RMI_F11_NR_ELECTRODES_MASK; sensor_query->max_electrodes = query_buf[3] & RMI_F11_NR_ELECTRODES_MASK; query_size = RMI_F11_QUERY_SIZE; if (sensor_query->has_abs) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->abs_data_size = query_buf[0] & RMI_F11_ABS_DATA_SIZE_MASK; sensor_query->has_anchored_finger = !!(query_buf[0] & RMI_F11_HAS_ANCHORED_FINGER); sensor_query->has_adj_hyst = !!(query_buf[0] & RMI_F11_HAS_ADJ_HYST); sensor_query->has_dribble = !!(query_buf[0] & RMI_F11_HAS_DRIBBLE); sensor_query->has_bending_correction = !!(query_buf[0] & RMI_F11_HAS_BENDING_CORRECTION); sensor_query->has_large_object_suppression = !!(query_buf[0] & RMI_F11_HAS_LARGE_OBJECT_SUPPRESSION); sensor_query->has_jitter_filter = !!(query_buf[0] & RMI_F11_HAS_JITTER_FILTER); query_size++; } if (sensor_query->has_rel) { rc = rmi_read(rmi_dev, query_base_addr + query_size, &sensor_query->f11_2d_query6); if (rc < 0) return rc; query_size++; } if (sensor_query->has_gestures) { rc = rmi_read_block(rmi_dev, query_base_addr + query_size, query_buf, RMI_F11_QUERY_GESTURE_SIZE); if (rc < 0) return rc; sensor_query->has_single_tap = !!(query_buf[0] & RMI_F11_HAS_SINGLE_TAP); sensor_query->has_tap_n_hold = !!(query_buf[0] & RMI_F11_HAS_TAP_AND_HOLD); sensor_query->has_double_tap = !!(query_buf[0] & RMI_F11_HAS_DOUBLE_TAP); sensor_query->has_early_tap = !!(query_buf[0] & RMI_F11_HAS_EARLY_TAP); sensor_query->has_flick = !!(query_buf[0] & RMI_F11_HAS_FLICK); sensor_query->has_press = !!(query_buf[0] & RMI_F11_HAS_PRESS); sensor_query->has_pinch = !!(query_buf[0] & RMI_F11_HAS_PINCH); sensor_query->has_chiral = !!(query_buf[0] & RMI_F11_HAS_CHIRAL); /* query 8 */ sensor_query->has_palm_det = !!(query_buf[1] & RMI_F11_HAS_PALM_DET); sensor_query->has_rotate = !!(query_buf[1] & RMI_F11_HAS_ROTATE); sensor_query->has_touch_shapes = !!(query_buf[1] & RMI_F11_HAS_TOUCH_SHAPES); sensor_query->has_scroll_zones = !!(query_buf[1] & RMI_F11_HAS_SCROLL_ZONES); sensor_query->has_individual_scroll_zones = !!(query_buf[1] & RMI_F11_HAS_INDIVIDUAL_SCROLL_ZONES); sensor_query->has_mf_scroll = !!(query_buf[1] & RMI_F11_HAS_MF_SCROLL); sensor_query->has_mf_edge_motion = !!(query_buf[1] & RMI_F11_HAS_MF_EDGE_MOTION); sensor_query->has_mf_scroll_inertia = !!(query_buf[1] & RMI_F11_HAS_MF_SCROLL_INERTIA); sensor_query->query7_nonzero = !!(query_buf[0]); sensor_query->query8_nonzero = !!(query_buf[1]); query_size += 2; } if (f11->has_query9) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->has_pen = !!(query_buf[0] & RMI_F11_HAS_PEN); sensor_query->has_proximity = !!(query_buf[0] & RMI_F11_HAS_PROXIMITY); sensor_query->has_palm_det_sensitivity = !!(query_buf[0] & RMI_F11_HAS_PALM_DET_SENSITIVITY); sensor_query->has_suppress_on_palm_detect = !!(query_buf[0] & RMI_F11_HAS_SUPPRESS_ON_PALM_DETECT); sensor_query->has_two_pen_thresholds = !!(query_buf[0] & RMI_F11_HAS_TWO_PEN_THRESHOLDS); sensor_query->has_contact_geometry = !!(query_buf[0] & RMI_F11_HAS_CONTACT_GEOMETRY); sensor_query->has_pen_hover_discrimination = !!(query_buf[0] & RMI_F11_HAS_PEN_HOVER_DISCRIMINATION); sensor_query->has_pen_filters = !!(query_buf[0] & RMI_F11_HAS_PEN_FILTERS); query_size++; } if (sensor_query->has_touch_shapes) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->nr_touch_shapes = query_buf[0] & RMI_F11_NR_TOUCH_SHAPES_MASK; query_size++; } if (f11->has_query11) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->has_z_tuning = !!(query_buf[0] & RMI_F11_HAS_Z_TUNING); sensor_query->has_algorithm_selection = !!(query_buf[0] & RMI_F11_HAS_ALGORITHM_SELECTION); sensor_query->has_w_tuning = !!(query_buf[0] & RMI_F11_HAS_W_TUNING); sensor_query->has_pitch_info = !!(query_buf[0] & RMI_F11_HAS_PITCH_INFO); sensor_query->has_finger_size = !!(query_buf[0] & RMI_F11_HAS_FINGER_SIZE); sensor_query->has_segmentation_aggressiveness = !!(query_buf[0] & RMI_F11_HAS_SEGMENTATION_AGGRESSIVENESS); sensor_query->has_XY_clip = !!(query_buf[0] & RMI_F11_HAS_XY_CLIP); sensor_query->has_drumming_filter = !!(query_buf[0] & RMI_F11_HAS_DRUMMING_FILTER); query_size++; } if (f11->has_query12) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->has_gapless_finger = !!(query_buf[0] & RMI_F11_HAS_GAPLESS_FINGER); sensor_query->has_gapless_finger_tuning = !!(query_buf[0] & RMI_F11_HAS_GAPLESS_FINGER_TUNING); sensor_query->has_8bit_w = !!(query_buf[0] & RMI_F11_HAS_8BIT_W); sensor_query->has_adjustable_mapping = !!(query_buf[0] & RMI_F11_HAS_ADJUSTABLE_MAPPING); sensor_query->has_info2 = !!(query_buf[0] & RMI_F11_HAS_INFO2); sensor_query->has_physical_props = !!(query_buf[0] & RMI_F11_HAS_PHYSICAL_PROPS); sensor_query->has_finger_limit = !!(query_buf[0] & RMI_F11_HAS_FINGER_LIMIT); sensor_query->has_linear_coeff_2 = !!(query_buf[0] & RMI_F11_HAS_LINEAR_COEFF); query_size++; } if (sensor_query->has_jitter_filter) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->jitter_window_size = query_buf[0] & RMI_F11_JITTER_WINDOW_MASK; sensor_query->jitter_filter_type = (query_buf[0] & RMI_F11_JITTER_FILTER_MASK) >> RMI_F11_JITTER_FILTER_SHIFT; query_size++; } if (sensor_query->has_info2) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; sensor_query->light_control = query_buf[0] & RMI_F11_LIGHT_CONTROL_MASK; sensor_query->is_clear = !!(query_buf[0] & RMI_F11_IS_CLEAR); sensor_query->clickpad_props = (query_buf[0] & RMI_F11_CLICKPAD_PROPS_MASK) >> RMI_F11_CLICKPAD_PROPS_SHIFT; sensor_query->mouse_buttons = (query_buf[0] & RMI_F11_MOUSE_BUTTONS_MASK) >> RMI_F11_MOUSE_BUTTONS_SHIFT; sensor_query->has_advanced_gestures = !!(query_buf[0] & RMI_F11_HAS_ADVANCED_GESTURES); query_size++; } if (sensor_query->has_physical_props) { rc = rmi_read_block(rmi_dev, query_base_addr + query_size, query_buf, 4); if (rc < 0) return rc; sensor_query->x_sensor_size_mm = (query_buf[0] | (query_buf[1] << 8)) / 10; sensor_query->y_sensor_size_mm = (query_buf[2] | (query_buf[3] << 8)) / 10; /* * query 15 - 18 contain the size of the sensor * and query 19 - 26 contain bezel dimensions */ query_size += 12; } if (f11->has_query27) ++query_size; if (f11->has_query28) { rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; has_query36 = !!(query_buf[0] & BIT(6)); } if (has_query36) { query_size += 2; rc = rmi_read(rmi_dev, query_base_addr + query_size, query_buf); if (rc < 0) return rc; if (!!(query_buf[0] & BIT(5))) f11->has_acm = true; } return query_size; } static int rmi_f11_initialize(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; struct f11_data *f11; struct f11_2d_ctrl *ctrl; u8 query_offset; u16 query_base_addr; u16 control_base_addr; u16 max_x_pos, max_y_pos; int rc; const struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct rmi_2d_sensor *sensor; u8 buf; int mask_size; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Initializing F11 values.\n"); mask_size = BITS_TO_LONGS(drvdata->irq_count) * sizeof(unsigned long); /* ** init instance data, fill in values and create any sysfs files */ f11 = devm_kzalloc(&fn->dev, sizeof(struct f11_data) + mask_size * 2, GFP_KERNEL); if (!f11) return -ENOMEM; if (fn->dev.of_node) { rc = rmi_2d_sensor_of_probe(&fn->dev, &f11->sensor_pdata); if (rc) return rc; } else { f11->sensor_pdata = pdata->sensor_pdata; } f11->rezero_wait_ms = f11->sensor_pdata.rezero_wait; f11->abs_mask = (unsigned long *)((char *)f11 + sizeof(struct f11_data)); f11->rel_mask = (unsigned long *)((char *)f11 + sizeof(struct f11_data) + mask_size); set_bit(fn->irq_pos, f11->abs_mask); set_bit(fn->irq_pos + 1, f11->rel_mask); query_base_addr = fn->fd.query_base_addr; control_base_addr = fn->fd.control_base_addr; rc = rmi_read(rmi_dev, query_base_addr, &buf); if (rc < 0) return rc; f11->has_query9 = !!(buf & RMI_F11_HAS_QUERY9); f11->has_query11 = !!(buf & RMI_F11_HAS_QUERY11); f11->has_query12 = !!(buf & RMI_F11_HAS_QUERY12); f11->has_query27 = !!(buf & RMI_F11_HAS_QUERY27); f11->has_query28 = !!(buf & RMI_F11_HAS_QUERY28); query_offset = (query_base_addr + 1); sensor = &f11->sensor; sensor->fn = fn; rc = rmi_f11_get_query_parameters(rmi_dev, f11, &f11->sens_query, query_offset); if (rc < 0) return rc; query_offset += rc; rc = f11_read_control_regs(fn, &f11->dev_controls, control_base_addr); if (rc < 0) { dev_err(&fn->dev, "Failed to read F11 control params.\n"); return rc; } if (f11->sens_query.has_info2) { if (f11->sens_query.is_clear) f11->sensor.sensor_type = rmi_sensor_touchscreen; else f11->sensor.sensor_type = rmi_sensor_touchpad; } sensor->report_abs = f11->sens_query.has_abs; sensor->axis_align = f11->sensor_pdata.axis_align; sensor->topbuttonpad = f11->sensor_pdata.topbuttonpad; sensor->kernel_tracking = f11->sensor_pdata.kernel_tracking; sensor->dmax = f11->sensor_pdata.dmax; sensor->dribble = f11->sensor_pdata.dribble; sensor->palm_detect = f11->sensor_pdata.palm_detect; if (f11->sens_query.has_physical_props) { sensor->x_mm = f11->sens_query.x_sensor_size_mm; sensor->y_mm = f11->sens_query.y_sensor_size_mm; } else { sensor->x_mm = f11->sensor_pdata.x_mm; sensor->y_mm = f11->sensor_pdata.y_mm; } if (sensor->sensor_type == rmi_sensor_default) sensor->sensor_type = f11->sensor_pdata.sensor_type; sensor->report_abs = sensor->report_abs && !(f11->sensor_pdata.disable_report_mask & RMI_F11_DISABLE_ABS_REPORT); if (!sensor->report_abs) /* * If device doesn't have abs or if it has been disables * fallback to reporting rel data. */ sensor->report_rel = f11->sens_query.has_rel; rc = rmi_read_block(rmi_dev, control_base_addr + F11_CTRL_SENSOR_MAX_X_POS_OFFSET, (u8 *)&max_x_pos, sizeof(max_x_pos)); if (rc < 0) return rc; rc = rmi_read_block(rmi_dev, control_base_addr + F11_CTRL_SENSOR_MAX_Y_POS_OFFSET, (u8 *)&max_y_pos, sizeof(max_y_pos)); if (rc < 0) return rc; sensor->max_x = max_x_pos; sensor->max_y = max_y_pos; rc = f11_2d_construct_data(f11); if (rc < 0) return rc; if (f11->has_acm) f11->sensor.attn_size += f11->sensor.nbr_fingers * 2; /* allocate the in-kernel tracking buffers */ sensor->tracking_pos = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(struct input_mt_pos), GFP_KERNEL); sensor->tracking_slots = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(int), GFP_KERNEL); sensor->objs = devm_kcalloc(&fn->dev, sensor->nbr_fingers, sizeof(struct rmi_2d_sensor_abs_object), GFP_KERNEL); if (!sensor->tracking_pos || !sensor->tracking_slots || !sensor->objs) return -ENOMEM; ctrl = &f11->dev_controls; if (sensor->axis_align.delta_x_threshold) ctrl->ctrl0_11[RMI_F11_DELTA_X_THRESHOLD] = sensor->axis_align.delta_x_threshold; if (sensor->axis_align.delta_y_threshold) ctrl->ctrl0_11[RMI_F11_DELTA_Y_THRESHOLD] = sensor->axis_align.delta_y_threshold; /* * If distance threshold values are set, switch to reduced reporting * mode so they actually get used by the controller. */ if (sensor->axis_align.delta_x_threshold || sensor->axis_align.delta_y_threshold) { ctrl->ctrl0_11[0] &= ~RMI_F11_REPORT_MODE_MASK; ctrl->ctrl0_11[0] |= RMI_F11_REPORT_MODE_REDUCED; } if (f11->sens_query.has_dribble) { switch (sensor->dribble) { case RMI_REG_STATE_OFF: ctrl->ctrl0_11[0] &= ~BIT(6); break; case RMI_REG_STATE_ON: ctrl->ctrl0_11[0] |= BIT(6); break; case RMI_REG_STATE_DEFAULT: default: break; } } if (f11->sens_query.has_palm_det) { switch (sensor->palm_detect) { case RMI_REG_STATE_OFF: ctrl->ctrl0_11[11] &= ~BIT(0); break; case RMI_REG_STATE_ON: ctrl->ctrl0_11[11] |= BIT(0); break; case RMI_REG_STATE_DEFAULT: default: break; } } rc = f11_write_control_regs(fn, &f11->sens_query, &f11->dev_controls, fn->fd.control_base_addr); if (rc) dev_warn(&fn->dev, "Failed to write control registers\n"); mutex_init(&f11->dev_controls_mutex); dev_set_drvdata(&fn->dev, f11); return 0; } static int rmi_f11_config(struct rmi_function *fn) { struct f11_data *f11 = dev_get_drvdata(&fn->dev); struct rmi_driver *drv = fn->rmi_dev->driver; struct rmi_2d_sensor *sensor = &f11->sensor; int rc; if (!sensor->report_abs) drv->clear_irq_bits(fn->rmi_dev, f11->abs_mask); else drv->set_irq_bits(fn->rmi_dev, f11->abs_mask); if (!sensor->report_rel) drv->clear_irq_bits(fn->rmi_dev, f11->rel_mask); else drv->set_irq_bits(fn->rmi_dev, f11->rel_mask); rc = f11_write_control_regs(fn, &f11->sens_query, &f11->dev_controls, fn->fd.query_base_addr); if (rc < 0) return rc; return 0; } static irqreturn_t rmi_f11_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct f11_data *f11 = dev_get_drvdata(&fn->dev); u16 data_base_addr = fn->fd.data_base_addr; int error; int valid_bytes = f11->sensor.pkt_size; if (drvdata->attn_data.data) { /* * The valid data in the attention report is less then * expected. Only process the complete fingers. */ if (f11->sensor.attn_size > drvdata->attn_data.size) valid_bytes = drvdata->attn_data.size; else valid_bytes = f11->sensor.attn_size; memcpy(f11->sensor.data_pkt, drvdata->attn_data.data, valid_bytes); drvdata->attn_data.data += valid_bytes; drvdata->attn_data.size -= valid_bytes; } else { error = rmi_read_block(rmi_dev, data_base_addr, f11->sensor.data_pkt, f11->sensor.pkt_size); if (error < 0) return IRQ_RETVAL(error); } rmi_f11_finger_handler(f11, &f11->sensor, valid_bytes); return IRQ_HANDLED; } static int rmi_f11_resume(struct rmi_function *fn) { struct f11_data *f11 = dev_get_drvdata(&fn->dev); int error; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Resuming...\n"); if (!f11->rezero_wait_ms) return 0; mdelay(f11->rezero_wait_ms); error = rmi_write(fn->rmi_dev, fn->fd.command_base_addr, RMI_F11_REZERO); if (error) { dev_err(&fn->dev, "%s: failed to issue rezero command, error = %d.", __func__, error); return error; } return 0; } static int rmi_f11_probe(struct rmi_function *fn) { int error; struct f11_data *f11; error = rmi_f11_initialize(fn); if (error) return error; f11 = dev_get_drvdata(&fn->dev); error = rmi_2d_sensor_configure_input(fn, &f11->sensor); if (error) return error; return 0; } struct rmi_function_handler rmi_f11_handler = { .driver = { .name = "rmi4_f11", }, .func = 0x11, .probe = rmi_f11_probe, .config = rmi_f11_config, .attention = rmi_f11_attention, .resume = rmi_f11_resume, };
linux-master
drivers/input/rmi4/rmi_f11.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015 - 2016 Red Hat, Inc * Copyright (c) 2011, 2012 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/kconfig.h> #include <linux/lockdep.h> #include <linux/module.h> #include <linux/pm.h> #include <linux/rmi.h> #include <linux/slab.h> #include "rmi_driver.h" #define SMB_PROTOCOL_VERSION_ADDRESS 0xfd #define SMB_MAX_COUNT 32 #define RMI_SMB2_MAP_SIZE 8 /* 8 entry of 4 bytes each */ #define RMI_SMB2_MAP_FLAGS_WE 0x01 struct mapping_table_entry { __le16 rmiaddr; u8 readcount; u8 flags; }; struct rmi_smb_xport { struct rmi_transport_dev xport; struct i2c_client *client; struct mutex page_mutex; int page; u8 table_index; struct mutex mappingtable_mutex; struct mapping_table_entry mapping_table[RMI_SMB2_MAP_SIZE]; }; static int rmi_smb_get_version(struct rmi_smb_xport *rmi_smb) { struct i2c_client *client = rmi_smb->client; int retval; /* Check if for SMBus new version device by reading version byte. */ retval = i2c_smbus_read_byte_data(client, SMB_PROTOCOL_VERSION_ADDRESS); if (retval < 0) { dev_err(&client->dev, "failed to get SMBus version number!\n"); return retval; } return retval + 1; } /* SMB block write - wrapper over ic2_smb_write_block */ static int smb_block_write(struct rmi_transport_dev *xport, u8 commandcode, const void *buf, size_t len) { struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); struct i2c_client *client = rmi_smb->client; int retval; retval = i2c_smbus_write_block_data(client, commandcode, len, buf); rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "wrote %zd bytes at %#04x: %d (%*ph)\n", len, commandcode, retval, (int)len, buf); return retval; } /* * The function to get command code for smbus operations and keeps * records to the driver mapping table */ static int rmi_smb_get_command_code(struct rmi_transport_dev *xport, u16 rmiaddr, int bytecount, bool isread, u8 *commandcode) { struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); struct mapping_table_entry new_map; int i; int retval = 0; mutex_lock(&rmi_smb->mappingtable_mutex); for (i = 0; i < RMI_SMB2_MAP_SIZE; i++) { struct mapping_table_entry *entry = &rmi_smb->mapping_table[i]; if (le16_to_cpu(entry->rmiaddr) == rmiaddr) { if (isread) { if (entry->readcount == bytecount) goto exit; } else { if (entry->flags & RMI_SMB2_MAP_FLAGS_WE) { goto exit; } } } } i = rmi_smb->table_index; rmi_smb->table_index = (i + 1) % RMI_SMB2_MAP_SIZE; /* constructs mapping table data entry. 4 bytes each entry */ memset(&new_map, 0, sizeof(new_map)); new_map.rmiaddr = cpu_to_le16(rmiaddr); new_map.readcount = bytecount; new_map.flags = !isread ? RMI_SMB2_MAP_FLAGS_WE : 0; retval = smb_block_write(xport, i + 0x80, &new_map, sizeof(new_map)); if (retval < 0) { /* * if not written to device mapping table * clear the driver mapping table records */ memset(&new_map, 0, sizeof(new_map)); } /* save to the driver level mapping table */ rmi_smb->mapping_table[i] = new_map; exit: mutex_unlock(&rmi_smb->mappingtable_mutex); if (retval < 0) return retval; *commandcode = i; return 0; } static int rmi_smb_write_block(struct rmi_transport_dev *xport, u16 rmiaddr, const void *databuff, size_t len) { int retval = 0; u8 commandcode; struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); int cur_len = (int)len; mutex_lock(&rmi_smb->page_mutex); while (cur_len > 0) { /* * break into 32 bytes chunks to write get command code */ int block_len = min_t(int, len, SMB_MAX_COUNT); retval = rmi_smb_get_command_code(xport, rmiaddr, block_len, false, &commandcode); if (retval < 0) goto exit; retval = smb_block_write(xport, commandcode, databuff, block_len); if (retval < 0) goto exit; /* prepare to write next block of bytes */ cur_len -= SMB_MAX_COUNT; databuff += SMB_MAX_COUNT; rmiaddr += SMB_MAX_COUNT; } exit: mutex_unlock(&rmi_smb->page_mutex); return retval; } /* SMB block read - wrapper over ic2_smb_read_block */ static int smb_block_read(struct rmi_transport_dev *xport, u8 commandcode, void *buf, size_t len) { struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); struct i2c_client *client = rmi_smb->client; int retval; retval = i2c_smbus_read_block_data(client, commandcode, buf); if (retval < 0) return retval; return retval; } static int rmi_smb_read_block(struct rmi_transport_dev *xport, u16 rmiaddr, void *databuff, size_t len) { struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); int retval; u8 commandcode; int cur_len = (int)len; mutex_lock(&rmi_smb->page_mutex); memset(databuff, 0, len); while (cur_len > 0) { /* break into 32 bytes chunks to write get command code */ int block_len = min_t(int, cur_len, SMB_MAX_COUNT); retval = rmi_smb_get_command_code(xport, rmiaddr, block_len, true, &commandcode); if (retval < 0) goto exit; retval = smb_block_read(xport, commandcode, databuff, block_len); if (retval < 0) goto exit; /* prepare to read next block of bytes */ cur_len -= SMB_MAX_COUNT; databuff += SMB_MAX_COUNT; rmiaddr += SMB_MAX_COUNT; } retval = 0; exit: mutex_unlock(&rmi_smb->page_mutex); return retval; } static void rmi_smb_clear_state(struct rmi_smb_xport *rmi_smb) { /* the mapping table has been flushed, discard the current one */ mutex_lock(&rmi_smb->mappingtable_mutex); memset(rmi_smb->mapping_table, 0, sizeof(rmi_smb->mapping_table)); mutex_unlock(&rmi_smb->mappingtable_mutex); } static int rmi_smb_enable_smbus_mode(struct rmi_smb_xport *rmi_smb) { int retval; /* we need to get the smbus version to activate the touchpad */ retval = rmi_smb_get_version(rmi_smb); if (retval < 0) return retval; return 0; } static int rmi_smb_reset(struct rmi_transport_dev *xport, u16 reset_addr) { struct rmi_smb_xport *rmi_smb = container_of(xport, struct rmi_smb_xport, xport); rmi_smb_clear_state(rmi_smb); /* * we do not call the actual reset command, it has to be handled in * PS/2 or there will be races between PS/2 and SMBus. * PS/2 should ensure that a psmouse_reset is called before * intializing the device and after it has been removed to be in a known * state. */ return rmi_smb_enable_smbus_mode(rmi_smb); } static const struct rmi_transport_ops rmi_smb_ops = { .write_block = rmi_smb_write_block, .read_block = rmi_smb_read_block, .reset = rmi_smb_reset, }; static int rmi_smb_probe(struct i2c_client *client) { struct rmi_device_platform_data *pdata = dev_get_platdata(&client->dev); struct rmi_smb_xport *rmi_smb; int smbus_version; int error; if (!pdata) { dev_err(&client->dev, "no platform data, aborting\n"); return -ENOMEM; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BLOCK_DATA | I2C_FUNC_SMBUS_HOST_NOTIFY)) { dev_err(&client->dev, "adapter does not support required functionality\n"); return -ENODEV; } if (client->irq <= 0) { dev_err(&client->dev, "no IRQ provided, giving up\n"); return client->irq ? client->irq : -ENODEV; } rmi_smb = devm_kzalloc(&client->dev, sizeof(struct rmi_smb_xport), GFP_KERNEL); if (!rmi_smb) return -ENOMEM; rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "Probing %s\n", dev_name(&client->dev)); rmi_smb->client = client; mutex_init(&rmi_smb->page_mutex); mutex_init(&rmi_smb->mappingtable_mutex); rmi_smb->xport.dev = &client->dev; rmi_smb->xport.pdata = *pdata; rmi_smb->xport.pdata.irq = client->irq; rmi_smb->xport.proto_name = "smb"; rmi_smb->xport.ops = &rmi_smb_ops; smbus_version = rmi_smb_get_version(rmi_smb); if (smbus_version < 0) return smbus_version; rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "Smbus version is %d", smbus_version); if (smbus_version != 2 && smbus_version != 3) { dev_err(&client->dev, "Unrecognized SMB version %d\n", smbus_version); return -ENODEV; } i2c_set_clientdata(client, rmi_smb); dev_info(&client->dev, "registering SMbus-connected sensor\n"); error = rmi_register_transport_device(&rmi_smb->xport); if (error) { dev_err(&client->dev, "failed to register sensor: %d\n", error); return error; } return 0; } static void rmi_smb_remove(struct i2c_client *client) { struct rmi_smb_xport *rmi_smb = i2c_get_clientdata(client); rmi_unregister_transport_device(&rmi_smb->xport); } static int rmi_smb_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_smb_xport *rmi_smb = i2c_get_clientdata(client); int ret; ret = rmi_driver_suspend(rmi_smb->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to suspend device: %d\n", ret); return ret; } static int rmi_smb_runtime_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_smb_xport *rmi_smb = i2c_get_clientdata(client); int ret; ret = rmi_driver_suspend(rmi_smb->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to suspend device: %d\n", ret); return ret; } static int rmi_smb_resume(struct device *dev) { struct i2c_client *client = container_of(dev, struct i2c_client, dev); struct rmi_smb_xport *rmi_smb = i2c_get_clientdata(client); struct rmi_device *rmi_dev = rmi_smb->xport.rmi_dev; int ret; rmi_smb_reset(&rmi_smb->xport, 0); rmi_reset(rmi_dev); ret = rmi_driver_resume(rmi_smb->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return 0; } static int rmi_smb_runtime_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_smb_xport *rmi_smb = i2c_get_clientdata(client); int ret; ret = rmi_driver_resume(rmi_smb->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return 0; } static const struct dev_pm_ops rmi_smb_pm = { SYSTEM_SLEEP_PM_OPS(rmi_smb_suspend, rmi_smb_resume) RUNTIME_PM_OPS(rmi_smb_runtime_suspend, rmi_smb_runtime_resume, NULL) }; static const struct i2c_device_id rmi_id[] = { { "rmi4_smbus", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, rmi_id); static struct i2c_driver rmi_smb_driver = { .driver = { .name = "rmi4_smbus", .pm = pm_ptr(&rmi_smb_pm), }, .id_table = rmi_id, .probe = rmi_smb_probe, .remove = rmi_smb_remove, }; module_i2c_driver(rmi_smb_driver); MODULE_AUTHOR("Andrew Duggan <[email protected]>"); MODULE_AUTHOR("Benjamin Tissoires <[email protected]>"); MODULE_DESCRIPTION("RMI4 SMBus driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/rmi4/rmi_smbus.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2012-2016 Synaptics Incorporated */ #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/input.h> #include <linux/slab.h> #include "rmi_driver.h" #define RMI_F30_QUERY_SIZE 2 /* Defs for Query 0 */ #define RMI_F30_EXTENDED_PATTERNS 0x01 #define RMI_F30_HAS_MAPPABLE_BUTTONS BIT(1) #define RMI_F30_HAS_LED BIT(2) #define RMI_F30_HAS_GPIO BIT(3) #define RMI_F30_HAS_HAPTIC BIT(4) #define RMI_F30_HAS_GPIO_DRV_CTL BIT(5) #define RMI_F30_HAS_MECH_MOUSE_BTNS BIT(6) /* Defs for Query 1 */ #define RMI_F30_GPIO_LED_COUNT 0x1F /* Defs for Control Registers */ #define RMI_F30_CTRL_1_GPIO_DEBOUNCE 0x01 #define RMI_F30_CTRL_1_HALT BIT(4) #define RMI_F30_CTRL_1_HALTED BIT(5) #define RMI_F30_CTRL_10_NUM_MECH_MOUSE_BTNS 0x03 #define RMI_F30_CTRL_MAX_REGS 32 #define RMI_F30_CTRL_MAX_BYTES DIV_ROUND_UP(RMI_F30_CTRL_MAX_REGS, 8) #define RMI_F30_CTRL_MAX_REG_BLOCKS 11 #define RMI_F30_CTRL_REGS_MAX_SIZE (RMI_F30_CTRL_MAX_BYTES \ + 1 \ + RMI_F30_CTRL_MAX_BYTES \ + RMI_F30_CTRL_MAX_BYTES \ + RMI_F30_CTRL_MAX_BYTES \ + 6 \ + RMI_F30_CTRL_MAX_REGS \ + RMI_F30_CTRL_MAX_REGS \ + RMI_F30_CTRL_MAX_BYTES \ + 1 \ + 1) #define TRACKSTICK_RANGE_START 3 #define TRACKSTICK_RANGE_END 6 struct rmi_f30_ctrl_data { int address; int length; u8 *regs; }; struct f30_data { /* Query Data */ bool has_extended_pattern; bool has_mappable_buttons; bool has_led; bool has_gpio; bool has_haptic; bool has_gpio_driver_control; bool has_mech_mouse_btns; u8 gpioled_count; u8 register_count; /* Control Register Data */ struct rmi_f30_ctrl_data ctrl[RMI_F30_CTRL_MAX_REG_BLOCKS]; u8 ctrl_regs[RMI_F30_CTRL_REGS_MAX_SIZE]; u32 ctrl_regs_size; u8 data_regs[RMI_F30_CTRL_MAX_BYTES]; u16 *gpioled_key_map; struct input_dev *input; struct rmi_function *f03; bool trackstick_buttons; }; static int rmi_f30_read_control_parameters(struct rmi_function *fn, struct f30_data *f30) { int error; error = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr, f30->ctrl_regs, f30->ctrl_regs_size); if (error) { dev_err(&fn->dev, "%s: Could not read control registers at 0x%x: %d\n", __func__, fn->fd.control_base_addr, error); return error; } return 0; } static void rmi_f30_report_button(struct rmi_function *fn, struct f30_data *f30, unsigned int button) { unsigned int reg_num = button >> 3; unsigned int bit_num = button & 0x07; u16 key_code = f30->gpioled_key_map[button]; bool key_down = !(f30->data_regs[reg_num] & BIT(bit_num)); if (f30->trackstick_buttons && button >= TRACKSTICK_RANGE_START && button <= TRACKSTICK_RANGE_END) { rmi_f03_overwrite_button(f30->f03, key_code, key_down); } else { rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: call input report key (0x%04x) value (0x%02x)", __func__, key_code, key_down); input_report_key(f30->input, key_code, key_down); } } static irqreturn_t rmi_f30_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct f30_data *f30 = dev_get_drvdata(&fn->dev); struct rmi_driver_data *drvdata = dev_get_drvdata(&fn->rmi_dev->dev); int error; int i; /* Read the gpi led data. */ if (drvdata->attn_data.data) { if (drvdata->attn_data.size < f30->register_count) { dev_warn(&fn->dev, "F30 interrupted, but data is missing\n"); return IRQ_HANDLED; } memcpy(f30->data_regs, drvdata->attn_data.data, f30->register_count); drvdata->attn_data.data += f30->register_count; drvdata->attn_data.size -= f30->register_count; } else { error = rmi_read_block(fn->rmi_dev, fn->fd.data_base_addr, f30->data_regs, f30->register_count); if (error) { dev_err(&fn->dev, "%s: Failed to read F30 data registers: %d\n", __func__, error); return IRQ_RETVAL(error); } } if (f30->has_gpio) { for (i = 0; i < f30->gpioled_count; i++) if (f30->gpioled_key_map[i] != KEY_RESERVED) rmi_f30_report_button(fn, f30, i); if (f30->trackstick_buttons) rmi_f03_commit_buttons(f30->f03); } return IRQ_HANDLED; } static int rmi_f30_config(struct rmi_function *fn) { struct f30_data *f30 = dev_get_drvdata(&fn->dev); struct rmi_driver *drv = fn->rmi_dev->driver; const struct rmi_device_platform_data *pdata = rmi_get_platform_data(fn->rmi_dev); int error; /* can happen if gpio_data.disable is set */ if (!f30) return 0; if (pdata->gpio_data.trackstick_buttons) { /* Try [re-]establish link to F03. */ f30->f03 = rmi_find_function(fn->rmi_dev, 0x03); f30->trackstick_buttons = f30->f03 != NULL; } if (pdata->gpio_data.disable) { drv->clear_irq_bits(fn->rmi_dev, fn->irq_mask); } else { /* Write Control Register values back to device */ error = rmi_write_block(fn->rmi_dev, fn->fd.control_base_addr, f30->ctrl_regs, f30->ctrl_regs_size); if (error) { dev_err(&fn->dev, "%s: Could not write control registers at 0x%x: %d\n", __func__, fn->fd.control_base_addr, error); return error; } drv->set_irq_bits(fn->rmi_dev, fn->irq_mask); } return 0; } static void rmi_f30_set_ctrl_data(struct rmi_f30_ctrl_data *ctrl, int *ctrl_addr, int len, u8 **reg) { ctrl->address = *ctrl_addr; ctrl->length = len; ctrl->regs = *reg; *ctrl_addr += len; *reg += len; } static bool rmi_f30_is_valid_button(int button, struct rmi_f30_ctrl_data *ctrl) { int byte_position = button >> 3; int bit_position = button & 0x07; /* * ctrl2 -> dir == 0 -> input mode * ctrl3 -> data == 1 -> actual button */ return !(ctrl[2].regs[byte_position] & BIT(bit_position)) && (ctrl[3].regs[byte_position] & BIT(bit_position)); } static int rmi_f30_map_gpios(struct rmi_function *fn, struct f30_data *f30) { const struct rmi_device_platform_data *pdata = rmi_get_platform_data(fn->rmi_dev); struct input_dev *input = f30->input; unsigned int button = BTN_LEFT; unsigned int trackstick_button = BTN_LEFT; bool button_mapped = false; int i; int button_count = min_t(u8, f30->gpioled_count, TRACKSTICK_RANGE_END); f30->gpioled_key_map = devm_kcalloc(&fn->dev, button_count, sizeof(f30->gpioled_key_map[0]), GFP_KERNEL); if (!f30->gpioled_key_map) { dev_err(&fn->dev, "Failed to allocate gpioled map memory.\n"); return -ENOMEM; } for (i = 0; i < button_count; i++) { if (!rmi_f30_is_valid_button(i, f30->ctrl)) continue; if (pdata->gpio_data.trackstick_buttons && i >= TRACKSTICK_RANGE_START && i < TRACKSTICK_RANGE_END) { f30->gpioled_key_map[i] = trackstick_button++; } else if (!pdata->gpio_data.buttonpad || !button_mapped) { f30->gpioled_key_map[i] = button; input_set_capability(input, EV_KEY, button++); button_mapped = true; } } input->keycode = f30->gpioled_key_map; input->keycodesize = sizeof(f30->gpioled_key_map[0]); input->keycodemax = f30->gpioled_count; /* * Buttonpad could be also inferred from f30->has_mech_mouse_btns, * but I am not sure, so use only the pdata info and the number of * mapped buttons. */ if (pdata->gpio_data.buttonpad || (button - BTN_LEFT == 1)) __set_bit(INPUT_PROP_BUTTONPAD, input->propbit); return 0; } static int rmi_f30_initialize(struct rmi_function *fn, struct f30_data *f30) { u8 *ctrl_reg = f30->ctrl_regs; int control_address = fn->fd.control_base_addr; u8 buf[RMI_F30_QUERY_SIZE]; int error; error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr, buf, RMI_F30_QUERY_SIZE); if (error) { dev_err(&fn->dev, "Failed to read query register\n"); return error; } f30->has_extended_pattern = buf[0] & RMI_F30_EXTENDED_PATTERNS; f30->has_mappable_buttons = buf[0] & RMI_F30_HAS_MAPPABLE_BUTTONS; f30->has_led = buf[0] & RMI_F30_HAS_LED; f30->has_gpio = buf[0] & RMI_F30_HAS_GPIO; f30->has_haptic = buf[0] & RMI_F30_HAS_HAPTIC; f30->has_gpio_driver_control = buf[0] & RMI_F30_HAS_GPIO_DRV_CTL; f30->has_mech_mouse_btns = buf[0] & RMI_F30_HAS_MECH_MOUSE_BTNS; f30->gpioled_count = buf[1] & RMI_F30_GPIO_LED_COUNT; f30->register_count = DIV_ROUND_UP(f30->gpioled_count, 8); if (f30->has_gpio && f30->has_led) rmi_f30_set_ctrl_data(&f30->ctrl[0], &control_address, f30->register_count, &ctrl_reg); rmi_f30_set_ctrl_data(&f30->ctrl[1], &control_address, sizeof(u8), &ctrl_reg); if (f30->has_gpio) { rmi_f30_set_ctrl_data(&f30->ctrl[2], &control_address, f30->register_count, &ctrl_reg); rmi_f30_set_ctrl_data(&f30->ctrl[3], &control_address, f30->register_count, &ctrl_reg); } if (f30->has_led) { rmi_f30_set_ctrl_data(&f30->ctrl[4], &control_address, f30->register_count, &ctrl_reg); rmi_f30_set_ctrl_data(&f30->ctrl[5], &control_address, f30->has_extended_pattern ? 6 : 2, &ctrl_reg); } if (f30->has_led || f30->has_gpio_driver_control) { /* control 6 uses a byte per gpio/led */ rmi_f30_set_ctrl_data(&f30->ctrl[6], &control_address, f30->gpioled_count, &ctrl_reg); } if (f30->has_mappable_buttons) { /* control 7 uses a byte per gpio/led */ rmi_f30_set_ctrl_data(&f30->ctrl[7], &control_address, f30->gpioled_count, &ctrl_reg); } if (f30->has_haptic) { rmi_f30_set_ctrl_data(&f30->ctrl[8], &control_address, f30->register_count, &ctrl_reg); rmi_f30_set_ctrl_data(&f30->ctrl[9], &control_address, sizeof(u8), &ctrl_reg); } if (f30->has_mech_mouse_btns) rmi_f30_set_ctrl_data(&f30->ctrl[10], &control_address, sizeof(u8), &ctrl_reg); f30->ctrl_regs_size = ctrl_reg - f30->ctrl_regs ?: RMI_F30_CTRL_REGS_MAX_SIZE; error = rmi_f30_read_control_parameters(fn, f30); if (error) { dev_err(&fn->dev, "Failed to initialize F30 control params: %d\n", error); return error; } if (f30->has_gpio) { error = rmi_f30_map_gpios(fn, f30); if (error) return error; } return 0; } static int rmi_f30_probe(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; const struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); struct f30_data *f30; int error; if (pdata->gpio_data.disable) return 0; if (!drv_data->input) { dev_info(&fn->dev, "F30: no input device found, ignoring\n"); return -ENXIO; } f30 = devm_kzalloc(&fn->dev, sizeof(*f30), GFP_KERNEL); if (!f30) return -ENOMEM; f30->input = drv_data->input; error = rmi_f30_initialize(fn, f30); if (error) return error; dev_set_drvdata(&fn->dev, f30); return 0; } struct rmi_function_handler rmi_f30_handler = { .driver = { .name = "rmi4_f30", }, .func = 0x30, .probe = rmi_f30_probe, .config = rmi_f30_config, .attention = rmi_f30_attention, };
linux-master
drivers/input/rmi4/rmi_f30.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2016, Zodiac Inflight Innovations * Copyright (c) 2007-2016, Synaptics Incorporated * Copyright (C) 2012 Alexandra Chin <[email protected]> * Copyright (C) 2012 Scott Lin <[email protected]> */ #include <linux/bitops.h> #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/firmware.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <asm/unaligned.h> #include "rmi_driver.h" #include "rmi_f34.h" static int rmi_f34v7_read_flash_status(struct f34_data *f34) { u8 status; u8 command; int ret; ret = rmi_read_block(f34->fn->rmi_dev, f34->fn->fd.data_base_addr + V7_FLASH_STATUS_OFFSET, &status, sizeof(status)); if (ret < 0) { rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Error %d reading flash status\n", __func__, ret); return ret; } f34->v7.in_bl_mode = status >> 7; f34->v7.flash_status = status & 0x1f; if (f34->v7.flash_status != 0x00) { dev_err(&f34->fn->dev, "%s: status=%d, command=0x%02x\n", __func__, f34->v7.flash_status, f34->v7.command); } ret = rmi_read_block(f34->fn->rmi_dev, f34->fn->fd.data_base_addr + V7_COMMAND_OFFSET, &command, sizeof(command)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read flash command\n", __func__); return ret; } f34->v7.command = command; return 0; } static int rmi_f34v7_wait_for_idle(struct f34_data *f34, int timeout_ms) { unsigned long timeout; timeout = msecs_to_jiffies(timeout_ms); if (!wait_for_completion_timeout(&f34->v7.cmd_done, timeout)) { dev_warn(&f34->fn->dev, "%s: Timed out waiting for idle status\n", __func__); return -ETIMEDOUT; } return 0; } static int rmi_f34v7_check_command_status(struct f34_data *f34, int timeout_ms) { int ret; ret = rmi_f34v7_wait_for_idle(f34, timeout_ms); if (ret < 0) return ret; ret = rmi_f34v7_read_flash_status(f34); if (ret < 0) return ret; if (f34->v7.flash_status != 0x00) return -EIO; return 0; } static int rmi_f34v7_write_command_single_transaction(struct f34_data *f34, u8 cmd) { int ret; u8 base; struct f34v7_data_1_5 data_1_5; base = f34->fn->fd.data_base_addr; memset(&data_1_5, 0, sizeof(data_1_5)); switch (cmd) { case v7_CMD_ERASE_ALL: data_1_5.partition_id = CORE_CODE_PARTITION; data_1_5.command = CMD_V7_ERASE_AP; break; case v7_CMD_ERASE_UI_FIRMWARE: data_1_5.partition_id = CORE_CODE_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ERASE_BL_CONFIG: data_1_5.partition_id = GLOBAL_PARAMETERS_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ERASE_UI_CONFIG: data_1_5.partition_id = CORE_CONFIG_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ERASE_DISP_CONFIG: data_1_5.partition_id = DISPLAY_CONFIG_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ERASE_FLASH_CONFIG: data_1_5.partition_id = FLASH_CONFIG_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ERASE_GUEST_CODE: data_1_5.partition_id = GUEST_CODE_PARTITION; data_1_5.command = CMD_V7_ERASE; break; case v7_CMD_ENABLE_FLASH_PROG: data_1_5.partition_id = BOOTLOADER_PARTITION; data_1_5.command = CMD_V7_ENTER_BL; break; } data_1_5.payload[0] = f34->bootloader_id[0]; data_1_5.payload[1] = f34->bootloader_id[1]; ret = rmi_write_block(f34->fn->rmi_dev, base + V7_PARTITION_ID_OFFSET, &data_1_5, sizeof(data_1_5)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write single transaction command\n", __func__); return ret; } return 0; } static int rmi_f34v7_write_command(struct f34_data *f34, u8 cmd) { int ret; u8 base; u8 command; base = f34->fn->fd.data_base_addr; switch (cmd) { case v7_CMD_WRITE_FW: case v7_CMD_WRITE_CONFIG: case v7_CMD_WRITE_GUEST_CODE: command = CMD_V7_WRITE; break; case v7_CMD_READ_CONFIG: command = CMD_V7_READ; break; case v7_CMD_ERASE_ALL: command = CMD_V7_ERASE_AP; break; case v7_CMD_ERASE_UI_FIRMWARE: case v7_CMD_ERASE_BL_CONFIG: case v7_CMD_ERASE_UI_CONFIG: case v7_CMD_ERASE_DISP_CONFIG: case v7_CMD_ERASE_FLASH_CONFIG: case v7_CMD_ERASE_GUEST_CODE: command = CMD_V7_ERASE; break; case v7_CMD_ENABLE_FLASH_PROG: command = CMD_V7_ENTER_BL; break; default: dev_err(&f34->fn->dev, "%s: Invalid command 0x%02x\n", __func__, cmd); return -EINVAL; } f34->v7.command = command; switch (cmd) { case v7_CMD_ERASE_ALL: case v7_CMD_ERASE_UI_FIRMWARE: case v7_CMD_ERASE_BL_CONFIG: case v7_CMD_ERASE_UI_CONFIG: case v7_CMD_ERASE_DISP_CONFIG: case v7_CMD_ERASE_FLASH_CONFIG: case v7_CMD_ERASE_GUEST_CODE: case v7_CMD_ENABLE_FLASH_PROG: ret = rmi_f34v7_write_command_single_transaction(f34, cmd); if (ret < 0) return ret; else return 0; default: break; } rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: writing cmd %02X\n", __func__, command); ret = rmi_write_block(f34->fn->rmi_dev, base + V7_COMMAND_OFFSET, &command, sizeof(command)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write flash command\n", __func__); return ret; } return 0; } static int rmi_f34v7_write_partition_id(struct f34_data *f34, u8 cmd) { int ret; u8 base; u8 partition; base = f34->fn->fd.data_base_addr; switch (cmd) { case v7_CMD_WRITE_FW: partition = CORE_CODE_PARTITION; break; case v7_CMD_WRITE_CONFIG: case v7_CMD_READ_CONFIG: if (f34->v7.config_area == v7_UI_CONFIG_AREA) partition = CORE_CONFIG_PARTITION; else if (f34->v7.config_area == v7_DP_CONFIG_AREA) partition = DISPLAY_CONFIG_PARTITION; else if (f34->v7.config_area == v7_PM_CONFIG_AREA) partition = GUEST_SERIALIZATION_PARTITION; else if (f34->v7.config_area == v7_BL_CONFIG_AREA) partition = GLOBAL_PARAMETERS_PARTITION; else if (f34->v7.config_area == v7_FLASH_CONFIG_AREA) partition = FLASH_CONFIG_PARTITION; break; case v7_CMD_WRITE_GUEST_CODE: partition = GUEST_CODE_PARTITION; break; case v7_CMD_ERASE_ALL: partition = CORE_CODE_PARTITION; break; case v7_CMD_ERASE_BL_CONFIG: partition = GLOBAL_PARAMETERS_PARTITION; break; case v7_CMD_ERASE_UI_CONFIG: partition = CORE_CONFIG_PARTITION; break; case v7_CMD_ERASE_DISP_CONFIG: partition = DISPLAY_CONFIG_PARTITION; break; case v7_CMD_ERASE_FLASH_CONFIG: partition = FLASH_CONFIG_PARTITION; break; case v7_CMD_ERASE_GUEST_CODE: partition = GUEST_CODE_PARTITION; break; case v7_CMD_ENABLE_FLASH_PROG: partition = BOOTLOADER_PARTITION; break; default: dev_err(&f34->fn->dev, "%s: Invalid command 0x%02x\n", __func__, cmd); return -EINVAL; } ret = rmi_write_block(f34->fn->rmi_dev, base + V7_PARTITION_ID_OFFSET, &partition, sizeof(partition)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write partition ID\n", __func__); return ret; } return 0; } static int rmi_f34v7_read_partition_table(struct f34_data *f34) { int ret; unsigned long timeout; u8 base; __le16 length; u16 block_number = 0; base = f34->fn->fd.data_base_addr; f34->v7.config_area = v7_FLASH_CONFIG_AREA; ret = rmi_f34v7_write_partition_id(f34, v7_CMD_READ_CONFIG); if (ret < 0) return ret; ret = rmi_write_block(f34->fn->rmi_dev, base + V7_BLOCK_NUMBER_OFFSET, &block_number, sizeof(block_number)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write block number\n", __func__); return ret; } put_unaligned_le16(f34->v7.flash_config_length, &length); ret = rmi_write_block(f34->fn->rmi_dev, base + V7_TRANSFER_LENGTH_OFFSET, &length, sizeof(length)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write transfer length\n", __func__); return ret; } init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_write_command(f34, v7_CMD_READ_CONFIG); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write command\n", __func__); return ret; } /* * rmi_f34v7_check_command_status() can't be used here, as this * function is called before IRQs are available */ timeout = msecs_to_jiffies(F34_WRITE_WAIT_MS); while (time_before(jiffies, timeout)) { usleep_range(5000, 6000); rmi_f34v7_read_flash_status(f34); if (f34->v7.command == v7_CMD_IDLE && f34->v7.flash_status == 0x00) { break; } } ret = rmi_read_block(f34->fn->rmi_dev, base + V7_PAYLOAD_OFFSET, f34->v7.read_config_buf, f34->v7.partition_table_bytes); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read block data\n", __func__); return ret; } return 0; } static void rmi_f34v7_parse_partition_table(struct f34_data *f34, const void *partition_table, struct block_count *blkcount, struct physical_address *phyaddr) { int i; int index; u16 partition_length; u16 physical_address; const struct partition_table *ptable; for (i = 0; i < f34->v7.partitions; i++) { index = i * 8 + 2; ptable = partition_table + index; partition_length = le16_to_cpu(ptable->partition_length); physical_address = le16_to_cpu(ptable->start_physical_address); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Partition entry %d: %*ph\n", __func__, i, sizeof(struct partition_table), ptable); switch (ptable->partition_id & 0x1f) { case CORE_CODE_PARTITION: blkcount->ui_firmware = partition_length; phyaddr->ui_firmware = physical_address; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Core code block count: %d\n", __func__, blkcount->ui_firmware); break; case CORE_CONFIG_PARTITION: blkcount->ui_config = partition_length; phyaddr->ui_config = physical_address; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Core config block count: %d\n", __func__, blkcount->ui_config); break; case DISPLAY_CONFIG_PARTITION: blkcount->dp_config = partition_length; phyaddr->dp_config = physical_address; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Display config block count: %d\n", __func__, blkcount->dp_config); break; case FLASH_CONFIG_PARTITION: blkcount->fl_config = partition_length; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Flash config block count: %d\n", __func__, blkcount->fl_config); break; case GUEST_CODE_PARTITION: blkcount->guest_code = partition_length; phyaddr->guest_code = physical_address; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Guest code block count: %d\n", __func__, blkcount->guest_code); break; case GUEST_SERIALIZATION_PARTITION: blkcount->pm_config = partition_length; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Guest serialization block count: %d\n", __func__, blkcount->pm_config); break; case GLOBAL_PARAMETERS_PARTITION: blkcount->bl_config = partition_length; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Global parameters block count: %d\n", __func__, blkcount->bl_config); break; case DEVICE_CONFIG_PARTITION: blkcount->lockdown = partition_length; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Device config block count: %d\n", __func__, blkcount->lockdown); break; } } } static int rmi_f34v7_read_queries_bl_version(struct f34_data *f34) { int ret; u8 base; int offset; u8 query_0; struct f34v7_query_1_7 query_1_7; base = f34->fn->fd.query_base_addr; ret = rmi_read_block(f34->fn->rmi_dev, base, &query_0, sizeof(query_0)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read query 0\n", __func__); return ret; } offset = (query_0 & 0x7) + 1; ret = rmi_read_block(f34->fn->rmi_dev, base + offset, &query_1_7, sizeof(query_1_7)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read queries 1 to 7\n", __func__); return ret; } f34->bootloader_id[0] = query_1_7.bl_minor_revision; f34->bootloader_id[1] = query_1_7.bl_major_revision; rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "Bootloader V%d.%d\n", f34->bootloader_id[1], f34->bootloader_id[0]); return 0; } static int rmi_f34v7_read_queries(struct f34_data *f34) { int ret; int i; u8 base; int offset; u8 *ptable; u8 query_0; struct f34v7_query_1_7 query_1_7; base = f34->fn->fd.query_base_addr; ret = rmi_read_block(f34->fn->rmi_dev, base, &query_0, sizeof(query_0)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read query 0\n", __func__); return ret; } offset = (query_0 & 0x07) + 1; ret = rmi_read_block(f34->fn->rmi_dev, base + offset, &query_1_7, sizeof(query_1_7)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read queries 1 to 7\n", __func__); return ret; } f34->bootloader_id[0] = query_1_7.bl_minor_revision; f34->bootloader_id[1] = query_1_7.bl_major_revision; f34->v7.block_size = le16_to_cpu(query_1_7.block_size); f34->v7.flash_config_length = le16_to_cpu(query_1_7.flash_config_length); f34->v7.payload_length = le16_to_cpu(query_1_7.payload_length); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: f34->v7.block_size = %d\n", __func__, f34->v7.block_size); f34->v7.has_display_cfg = query_1_7.partition_support[1] & HAS_DISP_CFG; f34->v7.has_guest_code = query_1_7.partition_support[1] & HAS_GUEST_CODE; if (query_0 & HAS_CONFIG_ID) { u8 f34_ctrl[CONFIG_ID_SIZE]; ret = rmi_read_block(f34->fn->rmi_dev, f34->fn->fd.control_base_addr, f34_ctrl, sizeof(f34_ctrl)); if (ret) return ret; /* Eat leading zeros */ for (i = 0; i < sizeof(f34_ctrl) - 1 && !f34_ctrl[i]; i++) /* Empty */; snprintf(f34->configuration_id, sizeof(f34->configuration_id), "%*phN", (int)sizeof(f34_ctrl) - i, f34_ctrl + i); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "Configuration ID: %s\n", f34->configuration_id); } f34->v7.partitions = 0; for (i = 0; i < sizeof(query_1_7.partition_support); i++) f34->v7.partitions += hweight8(query_1_7.partition_support[i]); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: Supported partitions: %*ph\n", __func__, sizeof(query_1_7.partition_support), query_1_7.partition_support); f34->v7.partition_table_bytes = f34->v7.partitions * 8 + 2; f34->v7.read_config_buf = devm_kzalloc(&f34->fn->dev, f34->v7.partition_table_bytes, GFP_KERNEL); if (!f34->v7.read_config_buf) { f34->v7.read_config_buf_size = 0; return -ENOMEM; } f34->v7.read_config_buf_size = f34->v7.partition_table_bytes; ptable = f34->v7.read_config_buf; ret = rmi_f34v7_read_partition_table(f34); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read partition table\n", __func__); return ret; } rmi_f34v7_parse_partition_table(f34, ptable, &f34->v7.blkcount, &f34->v7.phyaddr); return 0; } static int rmi_f34v7_check_bl_config_size(struct f34_data *f34) { u16 block_count; block_count = f34->v7.img.bl_config.size / f34->v7.block_size; f34->update_size += block_count; if (block_count != f34->v7.blkcount.bl_config) { dev_err(&f34->fn->dev, "Bootloader config size mismatch\n"); return -EINVAL; } return 0; } static int rmi_f34v7_erase_all(struct f34_data *f34) { int ret; dev_info(&f34->fn->dev, "Erasing firmware...\n"); init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_write_command(f34, v7_CMD_ERASE_ALL); if (ret < 0) return ret; ret = rmi_f34v7_check_command_status(f34, F34_ERASE_WAIT_MS); if (ret < 0) return ret; return 0; } static int rmi_f34v7_read_blocks(struct f34_data *f34, u16 block_cnt, u8 command) { int ret; u8 base; __le16 length; u16 transfer; u16 max_transfer; u16 remaining = block_cnt; u16 block_number = 0; u16 index = 0; base = f34->fn->fd.data_base_addr; ret = rmi_f34v7_write_partition_id(f34, command); if (ret < 0) return ret; ret = rmi_write_block(f34->fn->rmi_dev, base + V7_BLOCK_NUMBER_OFFSET, &block_number, sizeof(block_number)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write block number\n", __func__); return ret; } max_transfer = min(f34->v7.payload_length, (u16)(PAGE_SIZE / f34->v7.block_size)); do { transfer = min(remaining, max_transfer); put_unaligned_le16(transfer, &length); ret = rmi_write_block(f34->fn->rmi_dev, base + V7_TRANSFER_LENGTH_OFFSET, &length, sizeof(length)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Write transfer length fail (%d remaining)\n", __func__, remaining); return ret; } init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_write_command(f34, command); if (ret < 0) return ret; ret = rmi_f34v7_check_command_status(f34, F34_ENABLE_WAIT_MS); if (ret < 0) return ret; ret = rmi_read_block(f34->fn->rmi_dev, base + V7_PAYLOAD_OFFSET, &f34->v7.read_config_buf[index], transfer * f34->v7.block_size); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Read block failed (%d blks remaining)\n", __func__, remaining); return ret; } index += (transfer * f34->v7.block_size); remaining -= transfer; } while (remaining); return 0; } static int rmi_f34v7_write_f34v7_blocks(struct f34_data *f34, const void *block_ptr, u16 block_cnt, u8 command) { int ret; u8 base; __le16 length; u16 transfer; u16 max_transfer; u16 remaining = block_cnt; u16 block_number = 0; base = f34->fn->fd.data_base_addr; ret = rmi_f34v7_write_partition_id(f34, command); if (ret < 0) return ret; ret = rmi_write_block(f34->fn->rmi_dev, base + V7_BLOCK_NUMBER_OFFSET, &block_number, sizeof(block_number)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to write block number\n", __func__); return ret; } if (f34->v7.payload_length > (PAGE_SIZE / f34->v7.block_size)) max_transfer = PAGE_SIZE / f34->v7.block_size; else max_transfer = f34->v7.payload_length; do { transfer = min(remaining, max_transfer); put_unaligned_le16(transfer, &length); init_completion(&f34->v7.cmd_done); ret = rmi_write_block(f34->fn->rmi_dev, base + V7_TRANSFER_LENGTH_OFFSET, &length, sizeof(length)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Write transfer length fail (%d remaining)\n", __func__, remaining); return ret; } ret = rmi_f34v7_write_command(f34, command); if (ret < 0) return ret; ret = rmi_write_block(f34->fn->rmi_dev, base + V7_PAYLOAD_OFFSET, block_ptr, transfer * f34->v7.block_size); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed writing data (%d blks remaining)\n", __func__, remaining); return ret; } ret = rmi_f34v7_check_command_status(f34, F34_ENABLE_WAIT_MS); if (ret < 0) return ret; block_ptr += (transfer * f34->v7.block_size); remaining -= transfer; f34->update_progress += transfer; f34->update_status = (f34->update_progress * 100) / f34->update_size; } while (remaining); return 0; } static int rmi_f34v7_write_config(struct f34_data *f34) { return rmi_f34v7_write_f34v7_blocks(f34, f34->v7.config_data, f34->v7.config_block_count, v7_CMD_WRITE_CONFIG); } static int rmi_f34v7_write_ui_config(struct f34_data *f34) { f34->v7.config_area = v7_UI_CONFIG_AREA; f34->v7.config_data = f34->v7.img.ui_config.data; f34->v7.config_size = f34->v7.img.ui_config.size; f34->v7.config_block_count = f34->v7.config_size / f34->v7.block_size; return rmi_f34v7_write_config(f34); } static int rmi_f34v7_write_dp_config(struct f34_data *f34) { f34->v7.config_area = v7_DP_CONFIG_AREA; f34->v7.config_data = f34->v7.img.dp_config.data; f34->v7.config_size = f34->v7.img.dp_config.size; f34->v7.config_block_count = f34->v7.config_size / f34->v7.block_size; return rmi_f34v7_write_config(f34); } static int rmi_f34v7_write_guest_code(struct f34_data *f34) { return rmi_f34v7_write_f34v7_blocks(f34, f34->v7.img.guest_code.data, f34->v7.img.guest_code.size / f34->v7.block_size, v7_CMD_WRITE_GUEST_CODE); } static int rmi_f34v7_write_flash_config(struct f34_data *f34) { int ret; f34->v7.config_area = v7_FLASH_CONFIG_AREA; f34->v7.config_data = f34->v7.img.fl_config.data; f34->v7.config_size = f34->v7.img.fl_config.size; f34->v7.config_block_count = f34->v7.config_size / f34->v7.block_size; if (f34->v7.config_block_count != f34->v7.blkcount.fl_config) { dev_err(&f34->fn->dev, "%s: Flash config size mismatch\n", __func__); return -EINVAL; } init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_write_config(f34); if (ret < 0) return ret; return 0; } static int rmi_f34v7_write_partition_table(struct f34_data *f34) { u16 block_count; int ret; block_count = f34->v7.blkcount.bl_config; f34->v7.config_area = v7_BL_CONFIG_AREA; f34->v7.config_size = f34->v7.block_size * block_count; devm_kfree(&f34->fn->dev, f34->v7.read_config_buf); f34->v7.read_config_buf = devm_kzalloc(&f34->fn->dev, f34->v7.config_size, GFP_KERNEL); if (!f34->v7.read_config_buf) { f34->v7.read_config_buf_size = 0; return -ENOMEM; } f34->v7.read_config_buf_size = f34->v7.config_size; ret = rmi_f34v7_read_blocks(f34, block_count, v7_CMD_READ_CONFIG); if (ret < 0) return ret; ret = rmi_f34v7_write_flash_config(f34); if (ret < 0) return ret; f34->v7.config_area = v7_BL_CONFIG_AREA; f34->v7.config_data = f34->v7.read_config_buf; f34->v7.config_size = f34->v7.img.bl_config.size; f34->v7.config_block_count = f34->v7.config_size / f34->v7.block_size; ret = rmi_f34v7_write_config(f34); if (ret < 0) return ret; return 0; } static int rmi_f34v7_write_firmware(struct f34_data *f34) { u16 blk_count; blk_count = f34->v7.img.ui_firmware.size / f34->v7.block_size; return rmi_f34v7_write_f34v7_blocks(f34, f34->v7.img.ui_firmware.data, blk_count, v7_CMD_WRITE_FW); } static void rmi_f34v7_parse_img_header_10_bl_container(struct f34_data *f34, const void *image) { int i; int num_of_containers; unsigned int addr; unsigned int container_id; unsigned int length; const void *content; const struct container_descriptor *descriptor; num_of_containers = f34->v7.img.bootloader.size / 4 - 1; for (i = 1; i <= num_of_containers; i++) { addr = get_unaligned_le32(f34->v7.img.bootloader.data + i * 4); descriptor = image + addr; container_id = le16_to_cpu(descriptor->container_id); content = image + le32_to_cpu(descriptor->content_address); length = le32_to_cpu(descriptor->content_length); switch (container_id) { case BL_CONFIG_CONTAINER: case GLOBAL_PARAMETERS_CONTAINER: f34->v7.img.bl_config.data = content; f34->v7.img.bl_config.size = length; break; case BL_LOCKDOWN_INFO_CONTAINER: case DEVICE_CONFIG_CONTAINER: f34->v7.img.lockdown.data = content; f34->v7.img.lockdown.size = length; break; default: break; } } } static void rmi_f34v7_parse_image_header_10(struct f34_data *f34) { unsigned int i; unsigned int num_of_containers; unsigned int addr; unsigned int offset; unsigned int container_id; unsigned int length; const void *image = f34->v7.image; const u8 *content; const struct container_descriptor *descriptor; const struct image_header_10 *header = image; f34->v7.img.checksum = le32_to_cpu(header->checksum); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: f34->v7.img.checksum=%X\n", __func__, f34->v7.img.checksum); /* address of top level container */ offset = le32_to_cpu(header->top_level_container_start_addr); descriptor = image + offset; /* address of top level container content */ offset = le32_to_cpu(descriptor->content_address); num_of_containers = le32_to_cpu(descriptor->content_length) / 4; for (i = 0; i < num_of_containers; i++) { addr = get_unaligned_le32(image + offset); offset += 4; descriptor = image + addr; container_id = le16_to_cpu(descriptor->container_id); content = image + le32_to_cpu(descriptor->content_address); length = le32_to_cpu(descriptor->content_length); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: container_id=%d, length=%d\n", __func__, container_id, length); switch (container_id) { case UI_CONTAINER: case CORE_CODE_CONTAINER: f34->v7.img.ui_firmware.data = content; f34->v7.img.ui_firmware.size = length; break; case UI_CONFIG_CONTAINER: case CORE_CONFIG_CONTAINER: f34->v7.img.ui_config.data = content; f34->v7.img.ui_config.size = length; break; case BL_CONTAINER: f34->v7.img.bl_version = *content; f34->v7.img.bootloader.data = content; f34->v7.img.bootloader.size = length; rmi_f34v7_parse_img_header_10_bl_container(f34, image); break; case GUEST_CODE_CONTAINER: f34->v7.img.contains_guest_code = true; f34->v7.img.guest_code.data = content; f34->v7.img.guest_code.size = length; break; case DISPLAY_CONFIG_CONTAINER: f34->v7.img.contains_display_cfg = true; f34->v7.img.dp_config.data = content; f34->v7.img.dp_config.size = length; break; case FLASH_CONFIG_CONTAINER: f34->v7.img.contains_flash_config = true; f34->v7.img.fl_config.data = content; f34->v7.img.fl_config.size = length; break; case GENERAL_INFORMATION_CONTAINER: f34->v7.img.contains_firmware_id = true; f34->v7.img.firmware_id = get_unaligned_le32(content + 4); break; default: break; } } } static int rmi_f34v7_parse_image_info(struct f34_data *f34) { const struct image_header_10 *header = f34->v7.image; memset(&f34->v7.img, 0x00, sizeof(f34->v7.img)); rmi_dbg(RMI_DEBUG_FN, &f34->fn->dev, "%s: header->major_header_version = %d\n", __func__, header->major_header_version); switch (header->major_header_version) { case IMAGE_HEADER_VERSION_10: rmi_f34v7_parse_image_header_10(f34); break; default: dev_err(&f34->fn->dev, "Unsupported image file format %02X\n", header->major_header_version); return -EINVAL; } if (!f34->v7.img.contains_flash_config) { dev_err(&f34->fn->dev, "%s: No flash config in fw image\n", __func__); return -EINVAL; } rmi_f34v7_parse_partition_table(f34, f34->v7.img.fl_config.data, &f34->v7.img.blkcount, &f34->v7.img.phyaddr); return 0; } int rmi_f34v7_do_reflash(struct f34_data *f34, const struct firmware *fw) { int ret; f34->fn->rmi_dev->driver->set_irq_bits(f34->fn->rmi_dev, f34->fn->irq_mask); rmi_f34v7_read_queries_bl_version(f34); f34->v7.image = fw->data; f34->update_progress = 0; f34->update_size = 0; ret = rmi_f34v7_parse_image_info(f34); if (ret < 0) return ret; ret = rmi_f34v7_check_bl_config_size(f34); if (ret < 0) return ret; ret = rmi_f34v7_erase_all(f34); if (ret < 0) return ret; ret = rmi_f34v7_write_partition_table(f34); if (ret < 0) return ret; dev_info(&f34->fn->dev, "%s: Partition table programmed\n", __func__); /* * Reset to reload partition table - as the previous firmware has been * erased, we remain in bootloader mode. */ ret = rmi_scan_pdt(f34->fn->rmi_dev, NULL, rmi_initial_reset); if (ret < 0) dev_warn(&f34->fn->dev, "RMI reset failed!\n"); dev_info(&f34->fn->dev, "Writing firmware (%d bytes)...\n", f34->v7.img.ui_firmware.size); ret = rmi_f34v7_write_firmware(f34); if (ret < 0) return ret; dev_info(&f34->fn->dev, "Writing config (%d bytes)...\n", f34->v7.img.ui_config.size); f34->v7.config_area = v7_UI_CONFIG_AREA; ret = rmi_f34v7_write_ui_config(f34); if (ret < 0) return ret; if (f34->v7.has_display_cfg && f34->v7.img.contains_display_cfg) { dev_info(&f34->fn->dev, "Writing display config...\n"); ret = rmi_f34v7_write_dp_config(f34); if (ret < 0) return ret; } if (f34->v7.has_guest_code && f34->v7.img.contains_guest_code) { dev_info(&f34->fn->dev, "Writing guest code...\n"); ret = rmi_f34v7_write_guest_code(f34); if (ret < 0) return ret; } return 0; } static int rmi_f34v7_enter_flash_prog(struct f34_data *f34) { int ret; f34->fn->rmi_dev->driver->set_irq_bits(f34->fn->rmi_dev, f34->fn->irq_mask); ret = rmi_f34v7_read_flash_status(f34); if (ret < 0) return ret; if (f34->v7.in_bl_mode) { dev_info(&f34->fn->dev, "%s: Device in bootloader mode\n", __func__); return 0; } init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_write_command(f34, v7_CMD_ENABLE_FLASH_PROG); if (ret < 0) return ret; ret = rmi_f34v7_check_command_status(f34, F34_ENABLE_WAIT_MS); if (ret < 0) return ret; return 0; } int rmi_f34v7_start_reflash(struct f34_data *f34, const struct firmware *fw) { int ret = 0; f34->v7.config_area = v7_UI_CONFIG_AREA; f34->v7.image = fw->data; ret = rmi_f34v7_parse_image_info(f34); if (ret < 0) return ret; dev_info(&f34->fn->dev, "Firmware image OK\n"); return rmi_f34v7_enter_flash_prog(f34); } int rmi_f34v7_probe(struct f34_data *f34) { int ret; /* Read bootloader version */ ret = rmi_read_block(f34->fn->rmi_dev, f34->fn->fd.query_base_addr + V7_BOOTLOADER_ID_OFFSET, f34->bootloader_id, sizeof(f34->bootloader_id)); if (ret < 0) { dev_err(&f34->fn->dev, "%s: Failed to read bootloader ID\n", __func__); return ret; } if (f34->bootloader_id[1] == '5') { f34->bl_version = 5; } else if (f34->bootloader_id[1] == '6') { f34->bl_version = 6; } else if (f34->bootloader_id[1] == 7) { f34->bl_version = 7; } else if (f34->bootloader_id[1] == 8) { f34->bl_version = 8; } else { dev_err(&f34->fn->dev, "%s: Unrecognized bootloader version: %d (%c) %d (%c)\n", __func__, f34->bootloader_id[0], f34->bootloader_id[0], f34->bootloader_id[1], f34->bootloader_id[1]); return -EINVAL; } memset(&f34->v7.blkcount, 0x00, sizeof(f34->v7.blkcount)); memset(&f34->v7.phyaddr, 0x00, sizeof(f34->v7.phyaddr)); init_completion(&f34->v7.cmd_done); ret = rmi_f34v7_read_queries(f34); if (ret < 0) return ret; return 0; }
linux-master
drivers/input/rmi4/rmi_f34v7.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere * * This driver provides the core support for a single RMI4-based device. * * The RMI4 specification can be found here (URL split for line length): * * http://www.synaptics.com/sites/default/files/ * 511-000136-01-Rev-E-RMI4-Interfacing-Guide.pdf */ #include <linux/bitmap.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/irq.h> #include <linux/pm.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/irqdomain.h> #include <uapi/linux/input.h> #include <linux/rmi.h> #include "rmi_bus.h" #include "rmi_driver.h" #define HAS_NONSTANDARD_PDT_MASK 0x40 #define RMI4_MAX_PAGE 0xff #define RMI4_PAGE_SIZE 0x100 #define RMI4_PAGE_MASK 0xFF00 #define RMI_DEVICE_RESET_CMD 0x01 #define DEFAULT_RESET_DELAY_MS 100 void rmi_free_function_list(struct rmi_device *rmi_dev) { struct rmi_function *fn, *tmp; struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); rmi_dbg(RMI_DEBUG_CORE, &rmi_dev->dev, "Freeing function list\n"); /* Doing it in the reverse order so F01 will be removed last */ list_for_each_entry_safe_reverse(fn, tmp, &data->function_list, node) { list_del(&fn->node); rmi_unregister_function(fn); } devm_kfree(&rmi_dev->dev, data->irq_memory); data->irq_memory = NULL; data->irq_status = NULL; data->fn_irq_bits = NULL; data->current_irq_mask = NULL; data->new_irq_mask = NULL; data->f01_container = NULL; data->f34_container = NULL; } static int reset_one_function(struct rmi_function *fn) { struct rmi_function_handler *fh; int retval = 0; if (!fn || !fn->dev.driver) return 0; fh = to_rmi_function_handler(fn->dev.driver); if (fh->reset) { retval = fh->reset(fn); if (retval < 0) dev_err(&fn->dev, "Reset failed with code %d.\n", retval); } return retval; } static int configure_one_function(struct rmi_function *fn) { struct rmi_function_handler *fh; int retval = 0; if (!fn || !fn->dev.driver) return 0; fh = to_rmi_function_handler(fn->dev.driver); if (fh->config) { retval = fh->config(fn); if (retval < 0) dev_err(&fn->dev, "Config failed with code %d.\n", retval); } return retval; } static int rmi_driver_process_reset_requests(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi_function *entry; int retval; list_for_each_entry(entry, &data->function_list, node) { retval = reset_one_function(entry); if (retval < 0) return retval; } return 0; } static int rmi_driver_process_config_requests(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi_function *entry; int retval; list_for_each_entry(entry, &data->function_list, node) { retval = configure_one_function(entry); if (retval < 0) return retval; } return 0; } static int rmi_process_interrupt_requests(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct device *dev = &rmi_dev->dev; int i; int error; if (!data) return 0; if (!data->attn_data.data) { error = rmi_read_block(rmi_dev, data->f01_container->fd.data_base_addr + 1, data->irq_status, data->num_of_irq_regs); if (error < 0) { dev_err(dev, "Failed to read irqs, code=%d\n", error); return error; } } mutex_lock(&data->irq_mutex); bitmap_and(data->irq_status, data->irq_status, data->fn_irq_bits, data->irq_count); /* * At this point, irq_status has all bits that are set in the * interrupt status register and are enabled. */ mutex_unlock(&data->irq_mutex); for_each_set_bit(i, data->irq_status, data->irq_count) handle_nested_irq(irq_find_mapping(data->irqdomain, i)); if (data->input) input_sync(data->input); return 0; } void rmi_set_attn_data(struct rmi_device *rmi_dev, unsigned long irq_status, void *data, size_t size) { struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct rmi4_attn_data attn_data; void *fifo_data; if (!drvdata->enabled) return; fifo_data = kmemdup(data, size, GFP_ATOMIC); if (!fifo_data) return; attn_data.irq_status = irq_status; attn_data.size = size; attn_data.data = fifo_data; kfifo_put(&drvdata->attn_fifo, attn_data); } EXPORT_SYMBOL_GPL(rmi_set_attn_data); static irqreturn_t rmi_irq_fn(int irq, void *dev_id) { struct rmi_device *rmi_dev = dev_id; struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct rmi4_attn_data attn_data = {0}; int ret, count; count = kfifo_get(&drvdata->attn_fifo, &attn_data); if (count) { *(drvdata->irq_status) = attn_data.irq_status; drvdata->attn_data = attn_data; } ret = rmi_process_interrupt_requests(rmi_dev); if (ret) rmi_dbg(RMI_DEBUG_CORE, &rmi_dev->dev, "Failed to process interrupt request: %d\n", ret); if (count) { kfree(attn_data.data); drvdata->attn_data.data = NULL; } if (!kfifo_is_empty(&drvdata->attn_fifo)) return rmi_irq_fn(irq, dev_id); return IRQ_HANDLED; } static int rmi_irq_init(struct rmi_device *rmi_dev) { struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); int irq_flags = irq_get_trigger_type(pdata->irq); int ret; if (!irq_flags) irq_flags = IRQF_TRIGGER_LOW; ret = devm_request_threaded_irq(&rmi_dev->dev, pdata->irq, NULL, rmi_irq_fn, irq_flags | IRQF_ONESHOT, dev_driver_string(rmi_dev->xport->dev), rmi_dev); if (ret < 0) { dev_err(&rmi_dev->dev, "Failed to register interrupt %d\n", pdata->irq); return ret; } data->enabled = true; return 0; } struct rmi_function *rmi_find_function(struct rmi_device *rmi_dev, u8 number) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi_function *entry; list_for_each_entry(entry, &data->function_list, node) { if (entry->fd.function_number == number) return entry; } return NULL; } static int suspend_one_function(struct rmi_function *fn) { struct rmi_function_handler *fh; int retval = 0; if (!fn || !fn->dev.driver) return 0; fh = to_rmi_function_handler(fn->dev.driver); if (fh->suspend) { retval = fh->suspend(fn); if (retval < 0) dev_err(&fn->dev, "Suspend failed with code %d.\n", retval); } return retval; } static int rmi_suspend_functions(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi_function *entry; int retval; list_for_each_entry(entry, &data->function_list, node) { retval = suspend_one_function(entry); if (retval < 0) return retval; } return 0; } static int resume_one_function(struct rmi_function *fn) { struct rmi_function_handler *fh; int retval = 0; if (!fn || !fn->dev.driver) return 0; fh = to_rmi_function_handler(fn->dev.driver); if (fh->resume) { retval = fh->resume(fn); if (retval < 0) dev_err(&fn->dev, "Resume failed with code %d.\n", retval); } return retval; } static int rmi_resume_functions(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi_function *entry; int retval; list_for_each_entry(entry, &data->function_list, node) { retval = resume_one_function(entry); if (retval < 0) return retval; } return 0; } int rmi_enable_sensor(struct rmi_device *rmi_dev) { int retval = 0; retval = rmi_driver_process_config_requests(rmi_dev); if (retval < 0) return retval; return rmi_process_interrupt_requests(rmi_dev); } /** * rmi_driver_set_input_params - set input device id and other data. * * @rmi_dev: Pointer to an RMI device * @input: Pointer to input device * */ static int rmi_driver_set_input_params(struct rmi_device *rmi_dev, struct input_dev *input) { input->name = SYNAPTICS_INPUT_DEVICE_NAME; input->id.vendor = SYNAPTICS_VENDOR_ID; input->id.bustype = BUS_RMI; return 0; } static void rmi_driver_set_input_name(struct rmi_device *rmi_dev, struct input_dev *input) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); const char *device_name = rmi_f01_get_product_ID(data->f01_container); char *name; name = devm_kasprintf(&rmi_dev->dev, GFP_KERNEL, "Synaptics %s", device_name); if (!name) return; input->name = name; } static int rmi_driver_set_irq_bits(struct rmi_device *rmi_dev, unsigned long *mask) { int error = 0; struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct device *dev = &rmi_dev->dev; mutex_lock(&data->irq_mutex); bitmap_or(data->new_irq_mask, data->current_irq_mask, mask, data->irq_count); error = rmi_write_block(rmi_dev, data->f01_container->fd.control_base_addr + 1, data->new_irq_mask, data->num_of_irq_regs); if (error < 0) { dev_err(dev, "%s: Failed to change enabled interrupts!", __func__); goto error_unlock; } bitmap_copy(data->current_irq_mask, data->new_irq_mask, data->num_of_irq_regs); bitmap_or(data->fn_irq_bits, data->fn_irq_bits, mask, data->irq_count); error_unlock: mutex_unlock(&data->irq_mutex); return error; } static int rmi_driver_clear_irq_bits(struct rmi_device *rmi_dev, unsigned long *mask) { int error = 0; struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct device *dev = &rmi_dev->dev; mutex_lock(&data->irq_mutex); bitmap_andnot(data->fn_irq_bits, data->fn_irq_bits, mask, data->irq_count); bitmap_andnot(data->new_irq_mask, data->current_irq_mask, mask, data->irq_count); error = rmi_write_block(rmi_dev, data->f01_container->fd.control_base_addr + 1, data->new_irq_mask, data->num_of_irq_regs); if (error < 0) { dev_err(dev, "%s: Failed to change enabled interrupts!", __func__); goto error_unlock; } bitmap_copy(data->current_irq_mask, data->new_irq_mask, data->num_of_irq_regs); error_unlock: mutex_unlock(&data->irq_mutex); return error; } static int rmi_driver_reset_handler(struct rmi_device *rmi_dev) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); int error; /* * Can get called before the driver is fully ready to deal with * this situation. */ if (!data || !data->f01_container) { dev_warn(&rmi_dev->dev, "Not ready to handle reset yet!\n"); return 0; } error = rmi_read_block(rmi_dev, data->f01_container->fd.control_base_addr + 1, data->current_irq_mask, data->num_of_irq_regs); if (error < 0) { dev_err(&rmi_dev->dev, "%s: Failed to read current IRQ mask.\n", __func__); return error; } error = rmi_driver_process_reset_requests(rmi_dev); if (error < 0) return error; error = rmi_driver_process_config_requests(rmi_dev); if (error < 0) return error; return 0; } static int rmi_read_pdt_entry(struct rmi_device *rmi_dev, struct pdt_entry *entry, u16 pdt_address) { u8 buf[RMI_PDT_ENTRY_SIZE]; int error; error = rmi_read_block(rmi_dev, pdt_address, buf, RMI_PDT_ENTRY_SIZE); if (error) { dev_err(&rmi_dev->dev, "Read PDT entry at %#06x failed, code: %d.\n", pdt_address, error); return error; } entry->page_start = pdt_address & RMI4_PAGE_MASK; entry->query_base_addr = buf[0]; entry->command_base_addr = buf[1]; entry->control_base_addr = buf[2]; entry->data_base_addr = buf[3]; entry->interrupt_source_count = buf[4] & RMI_PDT_INT_SOURCE_COUNT_MASK; entry->function_version = (buf[4] & RMI_PDT_FUNCTION_VERSION_MASK) >> 5; entry->function_number = buf[5]; return 0; } static void rmi_driver_copy_pdt_to_fd(const struct pdt_entry *pdt, struct rmi_function_descriptor *fd) { fd->query_base_addr = pdt->query_base_addr + pdt->page_start; fd->command_base_addr = pdt->command_base_addr + pdt->page_start; fd->control_base_addr = pdt->control_base_addr + pdt->page_start; fd->data_base_addr = pdt->data_base_addr + pdt->page_start; fd->function_number = pdt->function_number; fd->interrupt_source_count = pdt->interrupt_source_count; fd->function_version = pdt->function_version; } #define RMI_SCAN_CONTINUE 0 #define RMI_SCAN_DONE 1 static int rmi_scan_pdt_page(struct rmi_device *rmi_dev, int page, int *empty_pages, void *ctx, int (*callback)(struct rmi_device *rmi_dev, void *ctx, const struct pdt_entry *entry)) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct pdt_entry pdt_entry; u16 page_start = RMI4_PAGE_SIZE * page; u16 pdt_start = page_start + PDT_START_SCAN_LOCATION; u16 pdt_end = page_start + PDT_END_SCAN_LOCATION; u16 addr; int error; int retval; for (addr = pdt_start; addr >= pdt_end; addr -= RMI_PDT_ENTRY_SIZE) { error = rmi_read_pdt_entry(rmi_dev, &pdt_entry, addr); if (error) return error; if (RMI4_END_OF_PDT(pdt_entry.function_number)) break; retval = callback(rmi_dev, ctx, &pdt_entry); if (retval != RMI_SCAN_CONTINUE) return retval; } /* * Count number of empty PDT pages. If a gap of two pages * or more is found, stop scanning. */ if (addr == pdt_start) ++*empty_pages; else *empty_pages = 0; return (data->bootloader_mode || *empty_pages >= 2) ? RMI_SCAN_DONE : RMI_SCAN_CONTINUE; } int rmi_scan_pdt(struct rmi_device *rmi_dev, void *ctx, int (*callback)(struct rmi_device *rmi_dev, void *ctx, const struct pdt_entry *entry)) { int page; int empty_pages = 0; int retval = RMI_SCAN_DONE; for (page = 0; page <= RMI4_MAX_PAGE; page++) { retval = rmi_scan_pdt_page(rmi_dev, page, &empty_pages, ctx, callback); if (retval != RMI_SCAN_CONTINUE) break; } return retval < 0 ? retval : 0; } int rmi_read_register_desc(struct rmi_device *d, u16 addr, struct rmi_register_descriptor *rdesc) { int ret; u8 size_presence_reg; u8 buf[35]; int presense_offset = 1; u8 *struct_buf; int reg; int offset = 0; int map_offset = 0; int i; int b; /* * The first register of the register descriptor is the size of * the register descriptor's presense register. */ ret = rmi_read(d, addr, &size_presence_reg); if (ret) return ret; ++addr; if (size_presence_reg < 0 || size_presence_reg > 35) return -EIO; memset(buf, 0, sizeof(buf)); /* * The presence register contains the size of the register structure * and a bitmap which identified which packet registers are present * for this particular register type (ie query, control, or data). */ ret = rmi_read_block(d, addr, buf, size_presence_reg); if (ret) return ret; ++addr; if (buf[0] == 0) { presense_offset = 3; rdesc->struct_size = buf[1] | (buf[2] << 8); } else { rdesc->struct_size = buf[0]; } for (i = presense_offset; i < size_presence_reg; i++) { for (b = 0; b < 8; b++) { if (buf[i] & (0x1 << b)) bitmap_set(rdesc->presense_map, map_offset, 1); ++map_offset; } } rdesc->num_registers = bitmap_weight(rdesc->presense_map, RMI_REG_DESC_PRESENSE_BITS); rdesc->registers = devm_kcalloc(&d->dev, rdesc->num_registers, sizeof(struct rmi_register_desc_item), GFP_KERNEL); if (!rdesc->registers) return -ENOMEM; /* * Allocate a temporary buffer to hold the register structure. * I'm not using devm_kzalloc here since it will not be retained * after exiting this function */ struct_buf = kzalloc(rdesc->struct_size, GFP_KERNEL); if (!struct_buf) return -ENOMEM; /* * The register structure contains information about every packet * register of this type. This includes the size of the packet * register and a bitmap of all subpackets contained in the packet * register. */ ret = rmi_read_block(d, addr, struct_buf, rdesc->struct_size); if (ret) goto free_struct_buff; reg = find_first_bit(rdesc->presense_map, RMI_REG_DESC_PRESENSE_BITS); for (i = 0; i < rdesc->num_registers; i++) { struct rmi_register_desc_item *item = &rdesc->registers[i]; int reg_size = struct_buf[offset]; ++offset; if (reg_size == 0) { reg_size = struct_buf[offset] | (struct_buf[offset + 1] << 8); offset += 2; } if (reg_size == 0) { reg_size = struct_buf[offset] | (struct_buf[offset + 1] << 8) | (struct_buf[offset + 2] << 16) | (struct_buf[offset + 3] << 24); offset += 4; } item->reg = reg; item->reg_size = reg_size; map_offset = 0; do { for (b = 0; b < 7; b++) { if (struct_buf[offset] & (0x1 << b)) bitmap_set(item->subpacket_map, map_offset, 1); ++map_offset; } } while (struct_buf[offset++] & 0x80); item->num_subpackets = bitmap_weight(item->subpacket_map, RMI_REG_DESC_SUBPACKET_BITS); rmi_dbg(RMI_DEBUG_CORE, &d->dev, "%s: reg: %d reg size: %ld subpackets: %d\n", __func__, item->reg, item->reg_size, item->num_subpackets); reg = find_next_bit(rdesc->presense_map, RMI_REG_DESC_PRESENSE_BITS, reg + 1); } free_struct_buff: kfree(struct_buf); return ret; } const struct rmi_register_desc_item *rmi_get_register_desc_item( struct rmi_register_descriptor *rdesc, u16 reg) { const struct rmi_register_desc_item *item; int i; for (i = 0; i < rdesc->num_registers; i++) { item = &rdesc->registers[i]; if (item->reg == reg) return item; } return NULL; } size_t rmi_register_desc_calc_size(struct rmi_register_descriptor *rdesc) { const struct rmi_register_desc_item *item; int i; size_t size = 0; for (i = 0; i < rdesc->num_registers; i++) { item = &rdesc->registers[i]; size += item->reg_size; } return size; } /* Compute the register offset relative to the base address */ int rmi_register_desc_calc_reg_offset( struct rmi_register_descriptor *rdesc, u16 reg) { const struct rmi_register_desc_item *item; int offset = 0; int i; for (i = 0; i < rdesc->num_registers; i++) { item = &rdesc->registers[i]; if (item->reg == reg) return offset; ++offset; } return -1; } bool rmi_register_desc_has_subpacket(const struct rmi_register_desc_item *item, u8 subpacket) { return find_next_bit(item->subpacket_map, RMI_REG_DESC_PRESENSE_BITS, subpacket) == subpacket; } static int rmi_check_bootloader_mode(struct rmi_device *rmi_dev, const struct pdt_entry *pdt) { struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); int ret; u8 status; if (pdt->function_number == 0x34 && pdt->function_version > 1) { ret = rmi_read(rmi_dev, pdt->data_base_addr, &status); if (ret) { dev_err(&rmi_dev->dev, "Failed to read F34 status: %d.\n", ret); return ret; } if (status & BIT(7)) data->bootloader_mode = true; } else if (pdt->function_number == 0x01) { ret = rmi_read(rmi_dev, pdt->data_base_addr, &status); if (ret) { dev_err(&rmi_dev->dev, "Failed to read F01 status: %d.\n", ret); return ret; } if (status & BIT(6)) data->bootloader_mode = true; } return 0; } static int rmi_count_irqs(struct rmi_device *rmi_dev, void *ctx, const struct pdt_entry *pdt) { int *irq_count = ctx; int ret; *irq_count += pdt->interrupt_source_count; ret = rmi_check_bootloader_mode(rmi_dev, pdt); if (ret < 0) return ret; return RMI_SCAN_CONTINUE; } int rmi_initial_reset(struct rmi_device *rmi_dev, void *ctx, const struct pdt_entry *pdt) { int error; if (pdt->function_number == 0x01) { u16 cmd_addr = pdt->page_start + pdt->command_base_addr; u8 cmd_buf = RMI_DEVICE_RESET_CMD; const struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); if (rmi_dev->xport->ops->reset) { error = rmi_dev->xport->ops->reset(rmi_dev->xport, cmd_addr); if (error) return error; return RMI_SCAN_DONE; } rmi_dbg(RMI_DEBUG_CORE, &rmi_dev->dev, "Sending reset\n"); error = rmi_write_block(rmi_dev, cmd_addr, &cmd_buf, 1); if (error) { dev_err(&rmi_dev->dev, "Initial reset failed. Code = %d.\n", error); return error; } mdelay(pdata->reset_delay_ms ?: DEFAULT_RESET_DELAY_MS); return RMI_SCAN_DONE; } /* F01 should always be on page 0. If we don't find it there, fail. */ return pdt->page_start == 0 ? RMI_SCAN_CONTINUE : -ENODEV; } static int rmi_create_function(struct rmi_device *rmi_dev, void *ctx, const struct pdt_entry *pdt) { struct device *dev = &rmi_dev->dev; struct rmi_driver_data *data = dev_get_drvdata(dev); int *current_irq_count = ctx; struct rmi_function *fn; int i; int error; rmi_dbg(RMI_DEBUG_CORE, dev, "Initializing F%02X.\n", pdt->function_number); fn = kzalloc(sizeof(struct rmi_function) + BITS_TO_LONGS(data->irq_count) * sizeof(unsigned long), GFP_KERNEL); if (!fn) { dev_err(dev, "Failed to allocate memory for F%02X\n", pdt->function_number); return -ENOMEM; } INIT_LIST_HEAD(&fn->node); rmi_driver_copy_pdt_to_fd(pdt, &fn->fd); fn->rmi_dev = rmi_dev; fn->num_of_irqs = pdt->interrupt_source_count; fn->irq_pos = *current_irq_count; *current_irq_count += fn->num_of_irqs; for (i = 0; i < fn->num_of_irqs; i++) set_bit(fn->irq_pos + i, fn->irq_mask); error = rmi_register_function(fn); if (error) return error; if (pdt->function_number == 0x01) data->f01_container = fn; else if (pdt->function_number == 0x34) data->f34_container = fn; list_add_tail(&fn->node, &data->function_list); return RMI_SCAN_CONTINUE; } void rmi_enable_irq(struct rmi_device *rmi_dev, bool clear_wake) { struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); int irq = pdata->irq; int irq_flags; int retval; mutex_lock(&data->enabled_mutex); if (data->enabled) goto out; enable_irq(irq); data->enabled = true; if (clear_wake && device_may_wakeup(rmi_dev->xport->dev)) { retval = disable_irq_wake(irq); if (retval) dev_warn(&rmi_dev->dev, "Failed to disable irq for wake: %d\n", retval); } /* * Call rmi_process_interrupt_requests() after enabling irq, * otherwise we may lose interrupt on edge-triggered systems. */ irq_flags = irq_get_trigger_type(pdata->irq); if (irq_flags & IRQ_TYPE_EDGE_BOTH) rmi_process_interrupt_requests(rmi_dev); out: mutex_unlock(&data->enabled_mutex); } void rmi_disable_irq(struct rmi_device *rmi_dev, bool enable_wake) { struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); struct rmi4_attn_data attn_data = {0}; int irq = pdata->irq; int retval, count; mutex_lock(&data->enabled_mutex); if (!data->enabled) goto out; data->enabled = false; disable_irq(irq); if (enable_wake && device_may_wakeup(rmi_dev->xport->dev)) { retval = enable_irq_wake(irq); if (retval) dev_warn(&rmi_dev->dev, "Failed to enable irq for wake: %d\n", retval); } /* make sure the fifo is clean */ while (!kfifo_is_empty(&data->attn_fifo)) { count = kfifo_get(&data->attn_fifo, &attn_data); if (count) kfree(attn_data.data); } out: mutex_unlock(&data->enabled_mutex); } int rmi_driver_suspend(struct rmi_device *rmi_dev, bool enable_wake) { int retval; retval = rmi_suspend_functions(rmi_dev); if (retval) dev_warn(&rmi_dev->dev, "Failed to suspend functions: %d\n", retval); rmi_disable_irq(rmi_dev, enable_wake); return retval; } EXPORT_SYMBOL_GPL(rmi_driver_suspend); int rmi_driver_resume(struct rmi_device *rmi_dev, bool clear_wake) { int retval; rmi_enable_irq(rmi_dev, clear_wake); retval = rmi_resume_functions(rmi_dev); if (retval) dev_warn(&rmi_dev->dev, "Failed to suspend functions: %d\n", retval); return retval; } EXPORT_SYMBOL_GPL(rmi_driver_resume); static int rmi_driver_remove(struct device *dev) { struct rmi_device *rmi_dev = to_rmi_device(dev); struct rmi_driver_data *data = dev_get_drvdata(&rmi_dev->dev); rmi_disable_irq(rmi_dev, false); irq_domain_remove(data->irqdomain); data->irqdomain = NULL; rmi_f34_remove_sysfs(rmi_dev); rmi_free_function_list(rmi_dev); return 0; } #ifdef CONFIG_OF static int rmi_driver_of_probe(struct device *dev, struct rmi_device_platform_data *pdata) { int retval; retval = rmi_of_property_read_u32(dev, &pdata->reset_delay_ms, "syna,reset-delay-ms", 1); if (retval) return retval; return 0; } #else static inline int rmi_driver_of_probe(struct device *dev, struct rmi_device_platform_data *pdata) { return -ENODEV; } #endif int rmi_probe_interrupts(struct rmi_driver_data *data) { struct rmi_device *rmi_dev = data->rmi_dev; struct device *dev = &rmi_dev->dev; struct fwnode_handle *fwnode = rmi_dev->xport->dev->fwnode; int irq_count = 0; size_t size; int retval; /* * We need to count the IRQs and allocate their storage before scanning * the PDT and creating the function entries, because adding a new * function can trigger events that result in the IRQ related storage * being accessed. */ rmi_dbg(RMI_DEBUG_CORE, dev, "%s: Counting IRQs.\n", __func__); data->bootloader_mode = false; retval = rmi_scan_pdt(rmi_dev, &irq_count, rmi_count_irqs); if (retval < 0) { dev_err(dev, "IRQ counting failed with code %d.\n", retval); return retval; } if (data->bootloader_mode) dev_warn(dev, "Device in bootloader mode.\n"); /* Allocate and register a linear revmap irq_domain */ data->irqdomain = irq_domain_create_linear(fwnode, irq_count, &irq_domain_simple_ops, data); if (!data->irqdomain) { dev_err(&rmi_dev->dev, "Failed to create IRQ domain\n"); return -ENOMEM; } data->irq_count = irq_count; data->num_of_irq_regs = (data->irq_count + 7) / 8; size = BITS_TO_LONGS(data->irq_count) * sizeof(unsigned long); data->irq_memory = devm_kcalloc(dev, size, 4, GFP_KERNEL); if (!data->irq_memory) { dev_err(dev, "Failed to allocate memory for irq masks.\n"); return -ENOMEM; } data->irq_status = data->irq_memory + size * 0; data->fn_irq_bits = data->irq_memory + size * 1; data->current_irq_mask = data->irq_memory + size * 2; data->new_irq_mask = data->irq_memory + size * 3; return retval; } int rmi_init_functions(struct rmi_driver_data *data) { struct rmi_device *rmi_dev = data->rmi_dev; struct device *dev = &rmi_dev->dev; int irq_count = 0; int retval; rmi_dbg(RMI_DEBUG_CORE, dev, "%s: Creating functions.\n", __func__); retval = rmi_scan_pdt(rmi_dev, &irq_count, rmi_create_function); if (retval < 0) { dev_err(dev, "Function creation failed with code %d.\n", retval); goto err_destroy_functions; } if (!data->f01_container) { dev_err(dev, "Missing F01 container!\n"); retval = -EINVAL; goto err_destroy_functions; } retval = rmi_read_block(rmi_dev, data->f01_container->fd.control_base_addr + 1, data->current_irq_mask, data->num_of_irq_regs); if (retval < 0) { dev_err(dev, "%s: Failed to read current IRQ mask.\n", __func__); goto err_destroy_functions; } return 0; err_destroy_functions: rmi_free_function_list(rmi_dev); return retval; } static int rmi_driver_probe(struct device *dev) { struct rmi_driver *rmi_driver; struct rmi_driver_data *data; struct rmi_device_platform_data *pdata; struct rmi_device *rmi_dev; int retval; rmi_dbg(RMI_DEBUG_CORE, dev, "%s: Starting probe.\n", __func__); if (!rmi_is_physical_device(dev)) { rmi_dbg(RMI_DEBUG_CORE, dev, "Not a physical device.\n"); return -ENODEV; } rmi_dev = to_rmi_device(dev); rmi_driver = to_rmi_driver(dev->driver); rmi_dev->driver = rmi_driver; pdata = rmi_get_platform_data(rmi_dev); if (rmi_dev->xport->dev->of_node) { retval = rmi_driver_of_probe(rmi_dev->xport->dev, pdata); if (retval) return retval; } data = devm_kzalloc(dev, sizeof(struct rmi_driver_data), GFP_KERNEL); if (!data) return -ENOMEM; INIT_LIST_HEAD(&data->function_list); data->rmi_dev = rmi_dev; dev_set_drvdata(&rmi_dev->dev, data); /* * Right before a warm boot, the sensor might be in some unusual state, * such as F54 diagnostics, or F34 bootloader mode after a firmware * or configuration update. In order to clear the sensor to a known * state and/or apply any updates, we issue a initial reset to clear any * previous settings and force it into normal operation. * * We have to do this before actually building the PDT because * the reflash updates (if any) might cause various registers to move * around. * * For a number of reasons, this initial reset may fail to return * within the specified time, but we'll still be able to bring up the * driver normally after that failure. This occurs most commonly in * a cold boot situation (where then firmware takes longer to come up * than from a warm boot) and the reset_delay_ms in the platform data * has been set too short to accommodate that. Since the sensor will * eventually come up and be usable, we don't want to just fail here * and leave the customer's device unusable. So we warn them, and * continue processing. */ retval = rmi_scan_pdt(rmi_dev, NULL, rmi_initial_reset); if (retval < 0) dev_warn(dev, "RMI initial reset failed! Continuing in spite of this.\n"); retval = rmi_read(rmi_dev, PDT_PROPERTIES_LOCATION, &data->pdt_props); if (retval < 0) { /* * we'll print out a warning and continue since * failure to get the PDT properties is not a cause to fail */ dev_warn(dev, "Could not read PDT properties from %#06x (code %d). Assuming 0x00.\n", PDT_PROPERTIES_LOCATION, retval); } mutex_init(&data->irq_mutex); mutex_init(&data->enabled_mutex); retval = rmi_probe_interrupts(data); if (retval) goto err; if (rmi_dev->xport->input) { /* * The transport driver already has an input device. * In some cases it is preferable to reuse the transport * devices input device instead of creating a new one here. * One example is some HID touchpads report "pass-through" * button events are not reported by rmi registers. */ data->input = rmi_dev->xport->input; } else { data->input = devm_input_allocate_device(dev); if (!data->input) { dev_err(dev, "%s: Failed to allocate input device.\n", __func__); retval = -ENOMEM; goto err; } rmi_driver_set_input_params(rmi_dev, data->input); data->input->phys = devm_kasprintf(dev, GFP_KERNEL, "%s/input0", dev_name(dev)); } retval = rmi_init_functions(data); if (retval) goto err; retval = rmi_f34_create_sysfs(rmi_dev); if (retval) goto err; if (data->input) { rmi_driver_set_input_name(rmi_dev, data->input); if (!rmi_dev->xport->input) { retval = input_register_device(data->input); if (retval) { dev_err(dev, "%s: Failed to register input device.\n", __func__); goto err_destroy_functions; } } } retval = rmi_irq_init(rmi_dev); if (retval < 0) goto err_destroy_functions; if (data->f01_container->dev.driver) { /* Driver already bound, so enable ATTN now. */ retval = rmi_enable_sensor(rmi_dev); if (retval) goto err_disable_irq; } return 0; err_disable_irq: rmi_disable_irq(rmi_dev, false); err_destroy_functions: rmi_free_function_list(rmi_dev); err: return retval; } static struct rmi_driver rmi_physical_driver = { .driver = { .owner = THIS_MODULE, .name = "rmi4_physical", .bus = &rmi_bus_type, .probe = rmi_driver_probe, .remove = rmi_driver_remove, }, .reset_handler = rmi_driver_reset_handler, .clear_irq_bits = rmi_driver_clear_irq_bits, .set_irq_bits = rmi_driver_set_irq_bits, .set_input_params = rmi_driver_set_input_params, }; bool rmi_is_physical_driver(struct device_driver *drv) { return drv == &rmi_physical_driver.driver; } int __init rmi_register_physical_driver(void) { int error; error = driver_register(&rmi_physical_driver.driver); if (error) { pr_err("%s: driver register failed, code=%d.\n", __func__, error); return error; } return 0; } void __exit rmi_unregister_physical_driver(void) { driver_unregister(&rmi_physical_driver.driver); }
linux-master
drivers/input/rmi4/rmi_driver.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/of.h> #include <asm/unaligned.h> #include "rmi_driver.h" #define RMI_PRODUCT_ID_LENGTH 10 #define RMI_PRODUCT_INFO_LENGTH 2 #define RMI_DATE_CODE_LENGTH 3 #define PRODUCT_ID_OFFSET 0x10 #define PRODUCT_INFO_OFFSET 0x1E /* Force a firmware reset of the sensor */ #define RMI_F01_CMD_DEVICE_RESET 1 /* Various F01_RMI_QueryX bits */ #define RMI_F01_QRY1_CUSTOM_MAP BIT(0) #define RMI_F01_QRY1_NON_COMPLIANT BIT(1) #define RMI_F01_QRY1_HAS_LTS BIT(2) #define RMI_F01_QRY1_HAS_SENSOR_ID BIT(3) #define RMI_F01_QRY1_HAS_CHARGER_INP BIT(4) #define RMI_F01_QRY1_HAS_ADJ_DOZE BIT(5) #define RMI_F01_QRY1_HAS_ADJ_DOZE_HOFF BIT(6) #define RMI_F01_QRY1_HAS_QUERY42 BIT(7) #define RMI_F01_QRY5_YEAR_MASK 0x1f #define RMI_F01_QRY6_MONTH_MASK 0x0f #define RMI_F01_QRY7_DAY_MASK 0x1f #define RMI_F01_QRY2_PRODINFO_MASK 0x7f #define RMI_F01_BASIC_QUERY_LEN 21 /* From Query 00 through 20 */ struct f01_basic_properties { u8 manufacturer_id; bool has_lts; bool has_adjustable_doze; bool has_adjustable_doze_holdoff; char dom[11]; /* YYYY/MM/DD + '\0' */ u8 product_id[RMI_PRODUCT_ID_LENGTH + 1]; u16 productinfo; u32 firmware_id; u32 package_id; }; /* F01 device status bits */ /* Most recent device status event */ #define RMI_F01_STATUS_CODE(status) ((status) & 0x0f) /* The device has lost its configuration for some reason. */ #define RMI_F01_STATUS_UNCONFIGURED(status) (!!((status) & 0x80)) /* The device is in bootloader mode */ #define RMI_F01_STATUS_BOOTLOADER(status) ((status) & 0x40) /* Control register bits */ /* * Sleep mode controls power management on the device and affects all * functions of the device. */ #define RMI_F01_CTRL0_SLEEP_MODE_MASK 0x03 #define RMI_SLEEP_MODE_NORMAL 0x00 #define RMI_SLEEP_MODE_SENSOR_SLEEP 0x01 #define RMI_SLEEP_MODE_RESERVED0 0x02 #define RMI_SLEEP_MODE_RESERVED1 0x03 /* * This bit disables whatever sleep mode may be selected by the sleep_mode * field and forces the device to run at full power without sleeping. */ #define RMI_F01_CTRL0_NOSLEEP_BIT BIT(2) /* * When this bit is set, the touch controller employs a noise-filtering * algorithm designed for use with a connected battery charger. */ #define RMI_F01_CTRL0_CHARGER_BIT BIT(5) /* * Sets the report rate for the device. The effect of this setting is * highly product dependent. Check the spec sheet for your particular * touch sensor. */ #define RMI_F01_CTRL0_REPORTRATE_BIT BIT(6) /* * Written by the host as an indicator that the device has been * successfully configured. */ #define RMI_F01_CTRL0_CONFIGURED_BIT BIT(7) /** * struct f01_device_control - controls basic sensor functions * * @ctrl0: see the bit definitions above. * @doze_interval: controls the interval between checks for finger presence * when the touch sensor is in doze mode, in units of 10ms. * @wakeup_threshold: controls the capacitance threshold at which the touch * sensor will decide to wake up from that low power state. * @doze_holdoff: controls how long the touch sensor waits after the last * finger lifts before entering the doze state, in units of 100ms. */ struct f01_device_control { u8 ctrl0; u8 doze_interval; u8 wakeup_threshold; u8 doze_holdoff; }; struct f01_data { struct f01_basic_properties properties; struct f01_device_control device_control; u16 doze_interval_addr; u16 wakeup_threshold_addr; u16 doze_holdoff_addr; bool suspended; bool old_nosleep; unsigned int num_of_irq_regs; }; static int rmi_f01_read_properties(struct rmi_device *rmi_dev, u16 query_base_addr, struct f01_basic_properties *props) { u8 queries[RMI_F01_BASIC_QUERY_LEN]; int ret; int query_offset = query_base_addr; bool has_ds4_queries = false; bool has_query42 = false; bool has_sensor_id = false; bool has_package_id_query = false; bool has_build_id_query = false; u16 prod_info_addr; u8 ds4_query_len; ret = rmi_read_block(rmi_dev, query_offset, queries, RMI_F01_BASIC_QUERY_LEN); if (ret) { dev_err(&rmi_dev->dev, "Failed to read device query registers: %d\n", ret); return ret; } prod_info_addr = query_offset + 17; query_offset += RMI_F01_BASIC_QUERY_LEN; /* Now parse what we got */ props->manufacturer_id = queries[0]; props->has_lts = queries[1] & RMI_F01_QRY1_HAS_LTS; props->has_adjustable_doze = queries[1] & RMI_F01_QRY1_HAS_ADJ_DOZE; props->has_adjustable_doze_holdoff = queries[1] & RMI_F01_QRY1_HAS_ADJ_DOZE_HOFF; has_query42 = queries[1] & RMI_F01_QRY1_HAS_QUERY42; has_sensor_id = queries[1] & RMI_F01_QRY1_HAS_SENSOR_ID; snprintf(props->dom, sizeof(props->dom), "20%02d/%02d/%02d", queries[5] & RMI_F01_QRY5_YEAR_MASK, queries[6] & RMI_F01_QRY6_MONTH_MASK, queries[7] & RMI_F01_QRY7_DAY_MASK); memcpy(props->product_id, &queries[11], RMI_PRODUCT_ID_LENGTH); props->product_id[RMI_PRODUCT_ID_LENGTH] = '\0'; props->productinfo = ((queries[2] & RMI_F01_QRY2_PRODINFO_MASK) << 7) | (queries[3] & RMI_F01_QRY2_PRODINFO_MASK); if (has_sensor_id) query_offset++; if (has_query42) { ret = rmi_read(rmi_dev, query_offset, queries); if (ret) { dev_err(&rmi_dev->dev, "Failed to read query 42 register: %d\n", ret); return ret; } has_ds4_queries = !!(queries[0] & BIT(0)); query_offset++; } if (has_ds4_queries) { ret = rmi_read(rmi_dev, query_offset, &ds4_query_len); if (ret) { dev_err(&rmi_dev->dev, "Failed to read DS4 queries length: %d\n", ret); return ret; } query_offset++; if (ds4_query_len > 0) { ret = rmi_read(rmi_dev, query_offset, queries); if (ret) { dev_err(&rmi_dev->dev, "Failed to read DS4 queries: %d\n", ret); return ret; } has_package_id_query = !!(queries[0] & BIT(0)); has_build_id_query = !!(queries[0] & BIT(1)); } if (has_package_id_query) { ret = rmi_read_block(rmi_dev, prod_info_addr, queries, sizeof(__le64)); if (ret) { dev_err(&rmi_dev->dev, "Failed to read package info: %d\n", ret); return ret; } props->package_id = get_unaligned_le64(queries); prod_info_addr++; } if (has_build_id_query) { ret = rmi_read_block(rmi_dev, prod_info_addr, queries, 3); if (ret) { dev_err(&rmi_dev->dev, "Failed to read product info: %d\n", ret); return ret; } props->firmware_id = queries[1] << 8 | queries[0]; props->firmware_id += queries[2] * 65536; } } return 0; } const char *rmi_f01_get_product_ID(struct rmi_function *fn) { struct f01_data *f01 = dev_get_drvdata(&fn->dev); return f01->properties.product_id; } static ssize_t rmi_driver_manufacturer_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct f01_data *f01 = dev_get_drvdata(&data->f01_container->dev); return scnprintf(buf, PAGE_SIZE, "%d\n", f01->properties.manufacturer_id); } static DEVICE_ATTR(manufacturer_id, 0444, rmi_driver_manufacturer_id_show, NULL); static ssize_t rmi_driver_dom_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct f01_data *f01 = dev_get_drvdata(&data->f01_container->dev); return scnprintf(buf, PAGE_SIZE, "%s\n", f01->properties.dom); } static DEVICE_ATTR(date_of_manufacture, 0444, rmi_driver_dom_show, NULL); static ssize_t rmi_driver_product_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct f01_data *f01 = dev_get_drvdata(&data->f01_container->dev); return scnprintf(buf, PAGE_SIZE, "%s\n", f01->properties.product_id); } static DEVICE_ATTR(product_id, 0444, rmi_driver_product_id_show, NULL); static ssize_t rmi_driver_firmware_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct f01_data *f01 = dev_get_drvdata(&data->f01_container->dev); return scnprintf(buf, PAGE_SIZE, "%d\n", f01->properties.firmware_id); } static DEVICE_ATTR(firmware_id, 0444, rmi_driver_firmware_id_show, NULL); static ssize_t rmi_driver_package_id_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct rmi_driver_data *data = dev_get_drvdata(dev); struct f01_data *f01 = dev_get_drvdata(&data->f01_container->dev); u32 package_id = f01->properties.package_id; return scnprintf(buf, PAGE_SIZE, "%04x.%04x\n", package_id & 0xffff, (package_id >> 16) & 0xffff); } static DEVICE_ATTR(package_id, 0444, rmi_driver_package_id_show, NULL); static struct attribute *rmi_f01_attrs[] = { &dev_attr_manufacturer_id.attr, &dev_attr_date_of_manufacture.attr, &dev_attr_product_id.attr, &dev_attr_firmware_id.attr, &dev_attr_package_id.attr, NULL }; static const struct attribute_group rmi_f01_attr_group = { .attrs = rmi_f01_attrs, }; #ifdef CONFIG_OF static int rmi_f01_of_probe(struct device *dev, struct rmi_device_platform_data *pdata) { int retval; u32 val; retval = rmi_of_property_read_u32(dev, (u32 *)&pdata->power_management.nosleep, "syna,nosleep-mode", 1); if (retval) return retval; retval = rmi_of_property_read_u32(dev, &val, "syna,wakeup-threshold", 1); if (retval) return retval; pdata->power_management.wakeup_threshold = val; retval = rmi_of_property_read_u32(dev, &val, "syna,doze-holdoff-ms", 1); if (retval) return retval; pdata->power_management.doze_holdoff = val * 100; retval = rmi_of_property_read_u32(dev, &val, "syna,doze-interval-ms", 1); if (retval) return retval; pdata->power_management.doze_interval = val / 10; return 0; } #else static inline int rmi_f01_of_probe(struct device *dev, struct rmi_device_platform_data *pdata) { return -ENODEV; } #endif static int rmi_f01_probe(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *driver_data = dev_get_drvdata(&rmi_dev->dev); struct rmi_device_platform_data *pdata = rmi_get_platform_data(rmi_dev); struct f01_data *f01; int error; u16 ctrl_base_addr = fn->fd.control_base_addr; u8 device_status; u8 temp; if (fn->dev.of_node) { error = rmi_f01_of_probe(&fn->dev, pdata); if (error) return error; } f01 = devm_kzalloc(&fn->dev, sizeof(struct f01_data), GFP_KERNEL); if (!f01) return -ENOMEM; f01->num_of_irq_regs = driver_data->num_of_irq_regs; /* * Set the configured bit and (optionally) other important stuff * in the device control register. */ error = rmi_read(rmi_dev, fn->fd.control_base_addr, &f01->device_control.ctrl0); if (error) { dev_err(&fn->dev, "Failed to read F01 control: %d\n", error); return error; } switch (pdata->power_management.nosleep) { case RMI_REG_STATE_DEFAULT: break; case RMI_REG_STATE_OFF: f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_NOSLEEP_BIT; break; case RMI_REG_STATE_ON: f01->device_control.ctrl0 |= RMI_F01_CTRL0_NOSLEEP_BIT; break; } /* * Sleep mode might be set as a hangover from a system crash or * reboot without power cycle. If so, clear it so the sensor * is certain to function. */ if ((f01->device_control.ctrl0 & RMI_F01_CTRL0_SLEEP_MODE_MASK) != RMI_SLEEP_MODE_NORMAL) { dev_warn(&fn->dev, "WARNING: Non-zero sleep mode found. Clearing...\n"); f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_SLEEP_MODE_MASK; } f01->device_control.ctrl0 |= RMI_F01_CTRL0_CONFIGURED_BIT; error = rmi_write(rmi_dev, fn->fd.control_base_addr, f01->device_control.ctrl0); if (error) { dev_err(&fn->dev, "Failed to write F01 control: %d\n", error); return error; } /* Dummy read in order to clear irqs */ error = rmi_read(rmi_dev, fn->fd.data_base_addr + 1, &temp); if (error < 0) { dev_err(&fn->dev, "Failed to read Interrupt Status.\n"); return error; } error = rmi_f01_read_properties(rmi_dev, fn->fd.query_base_addr, &f01->properties); if (error < 0) { dev_err(&fn->dev, "Failed to read F01 properties.\n"); return error; } dev_info(&fn->dev, "found RMI device, manufacturer: %s, product: %s, fw id: %d\n", f01->properties.manufacturer_id == 1 ? "Synaptics" : "unknown", f01->properties.product_id, f01->properties.firmware_id); /* Advance to interrupt control registers, then skip over them. */ ctrl_base_addr++; ctrl_base_addr += f01->num_of_irq_regs; /* read control register */ if (f01->properties.has_adjustable_doze) { f01->doze_interval_addr = ctrl_base_addr; ctrl_base_addr++; if (pdata->power_management.doze_interval) { f01->device_control.doze_interval = pdata->power_management.doze_interval; error = rmi_write(rmi_dev, f01->doze_interval_addr, f01->device_control.doze_interval); if (error) { dev_err(&fn->dev, "Failed to configure F01 doze interval register: %d\n", error); return error; } } else { error = rmi_read(rmi_dev, f01->doze_interval_addr, &f01->device_control.doze_interval); if (error) { dev_err(&fn->dev, "Failed to read F01 doze interval register: %d\n", error); return error; } } f01->wakeup_threshold_addr = ctrl_base_addr; ctrl_base_addr++; if (pdata->power_management.wakeup_threshold) { f01->device_control.wakeup_threshold = pdata->power_management.wakeup_threshold; error = rmi_write(rmi_dev, f01->wakeup_threshold_addr, f01->device_control.wakeup_threshold); if (error) { dev_err(&fn->dev, "Failed to configure F01 wakeup threshold register: %d\n", error); return error; } } else { error = rmi_read(rmi_dev, f01->wakeup_threshold_addr, &f01->device_control.wakeup_threshold); if (error < 0) { dev_err(&fn->dev, "Failed to read F01 wakeup threshold register: %d\n", error); return error; } } } if (f01->properties.has_lts) ctrl_base_addr++; if (f01->properties.has_adjustable_doze_holdoff) { f01->doze_holdoff_addr = ctrl_base_addr; ctrl_base_addr++; if (pdata->power_management.doze_holdoff) { f01->device_control.doze_holdoff = pdata->power_management.doze_holdoff; error = rmi_write(rmi_dev, f01->doze_holdoff_addr, f01->device_control.doze_holdoff); if (error) { dev_err(&fn->dev, "Failed to configure F01 doze holdoff register: %d\n", error); return error; } } else { error = rmi_read(rmi_dev, f01->doze_holdoff_addr, &f01->device_control.doze_holdoff); if (error) { dev_err(&fn->dev, "Failed to read F01 doze holdoff register: %d\n", error); return error; } } } error = rmi_read(rmi_dev, fn->fd.data_base_addr, &device_status); if (error < 0) { dev_err(&fn->dev, "Failed to read device status: %d\n", error); return error; } if (RMI_F01_STATUS_UNCONFIGURED(device_status)) { dev_err(&fn->dev, "Device was reset during configuration process, status: %#02x!\n", RMI_F01_STATUS_CODE(device_status)); return -EINVAL; } dev_set_drvdata(&fn->dev, f01); error = sysfs_create_group(&fn->rmi_dev->dev.kobj, &rmi_f01_attr_group); if (error) dev_warn(&fn->dev, "Failed to create sysfs group: %d\n", error); return 0; } static void rmi_f01_remove(struct rmi_function *fn) { /* Note that the bus device is used, not the F01 device */ sysfs_remove_group(&fn->rmi_dev->dev.kobj, &rmi_f01_attr_group); } static int rmi_f01_config(struct rmi_function *fn) { struct f01_data *f01 = dev_get_drvdata(&fn->dev); int error; error = rmi_write(fn->rmi_dev, fn->fd.control_base_addr, f01->device_control.ctrl0); if (error) { dev_err(&fn->dev, "Failed to write device_control register: %d\n", error); return error; } if (f01->properties.has_adjustable_doze) { error = rmi_write(fn->rmi_dev, f01->doze_interval_addr, f01->device_control.doze_interval); if (error) { dev_err(&fn->dev, "Failed to write doze interval: %d\n", error); return error; } error = rmi_write_block(fn->rmi_dev, f01->wakeup_threshold_addr, &f01->device_control.wakeup_threshold, sizeof(u8)); if (error) { dev_err(&fn->dev, "Failed to write wakeup threshold: %d\n", error); return error; } } if (f01->properties.has_adjustable_doze_holdoff) { error = rmi_write(fn->rmi_dev, f01->doze_holdoff_addr, f01->device_control.doze_holdoff); if (error) { dev_err(&fn->dev, "Failed to write doze holdoff: %d\n", error); return error; } } return 0; } static int rmi_f01_suspend(struct rmi_function *fn) { struct f01_data *f01 = dev_get_drvdata(&fn->dev); int error; f01->old_nosleep = f01->device_control.ctrl0 & RMI_F01_CTRL0_NOSLEEP_BIT; f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_NOSLEEP_BIT; f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_SLEEP_MODE_MASK; if (device_may_wakeup(fn->rmi_dev->xport->dev)) f01->device_control.ctrl0 |= RMI_SLEEP_MODE_RESERVED1; else f01->device_control.ctrl0 |= RMI_SLEEP_MODE_SENSOR_SLEEP; error = rmi_write(fn->rmi_dev, fn->fd.control_base_addr, f01->device_control.ctrl0); if (error) { dev_err(&fn->dev, "Failed to write sleep mode: %d.\n", error); if (f01->old_nosleep) f01->device_control.ctrl0 |= RMI_F01_CTRL0_NOSLEEP_BIT; f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_SLEEP_MODE_MASK; f01->device_control.ctrl0 |= RMI_SLEEP_MODE_NORMAL; return error; } return 0; } static int rmi_f01_resume(struct rmi_function *fn) { struct f01_data *f01 = dev_get_drvdata(&fn->dev); int error; if (f01->old_nosleep) f01->device_control.ctrl0 |= RMI_F01_CTRL0_NOSLEEP_BIT; f01->device_control.ctrl0 &= ~RMI_F01_CTRL0_SLEEP_MODE_MASK; f01->device_control.ctrl0 |= RMI_SLEEP_MODE_NORMAL; error = rmi_write(fn->rmi_dev, fn->fd.control_base_addr, f01->device_control.ctrl0); if (error) { dev_err(&fn->dev, "Failed to restore normal operation: %d.\n", error); return error; } return 0; } static irqreturn_t rmi_f01_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct rmi_device *rmi_dev = fn->rmi_dev; int error; u8 device_status; error = rmi_read(rmi_dev, fn->fd.data_base_addr, &device_status); if (error) { dev_err(&fn->dev, "Failed to read device status: %d.\n", error); return IRQ_RETVAL(error); } if (RMI_F01_STATUS_BOOTLOADER(device_status)) dev_warn(&fn->dev, "Device in bootloader mode, please update firmware\n"); if (RMI_F01_STATUS_UNCONFIGURED(device_status)) { dev_warn(&fn->dev, "Device reset detected.\n"); error = rmi_dev->driver->reset_handler(rmi_dev); if (error) { dev_err(&fn->dev, "Device reset failed: %d\n", error); return IRQ_RETVAL(error); } } return IRQ_HANDLED; } struct rmi_function_handler rmi_f01_handler = { .driver = { .name = "rmi4_f01", /* * Do not allow user unbinding F01 as it is critical * function. */ .suppress_bind_attrs = true, }, .func = 0x01, .probe = rmi_f01_probe, .remove = rmi_f01_remove, .config = rmi_f01_config, .attention = rmi_f01_attention, .suspend = rmi_f01_suspend, .resume = rmi_f01_resume, };
linux-master
drivers/input/rmi4/rmi_f01.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2012-2015 Synaptics Incorporated * Copyright (C) 2016 Zodiac Inflight Innovations */ #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/input.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/i2c.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/videobuf2-v4l2.h> #include <media/videobuf2-vmalloc.h> #include "rmi_driver.h" #define F54_NAME "rmi4_f54" /* F54 data offsets */ #define F54_REPORT_DATA_OFFSET 3 #define F54_FIFO_OFFSET 1 #define F54_NUM_TX_OFFSET 1 #define F54_NUM_RX_OFFSET 0 /* * The smbus protocol can read only 32 bytes max at a time. * But this should be fine for i2c/spi as well. */ #define F54_REPORT_DATA_SIZE 32 /* F54 commands */ #define F54_GET_REPORT 1 #define F54_FORCE_CAL 2 /* F54 capabilities */ #define F54_CAP_BASELINE (1 << 2) #define F54_CAP_IMAGE8 (1 << 3) #define F54_CAP_IMAGE16 (1 << 6) /** * enum rmi_f54_report_type - RMI4 F54 report types * * @F54_REPORT_NONE: No Image Report. * * @F54_8BIT_IMAGE: Normalized 8-Bit Image Report. The capacitance variance * from baseline for each pixel. * * @F54_16BIT_IMAGE: Normalized 16-Bit Image Report. The capacitance variance * from baseline for each pixel. * * @F54_RAW_16BIT_IMAGE: * Raw 16-Bit Image Report. The raw capacitance for each * pixel. * * @F54_TRUE_BASELINE: True Baseline Report. The baseline capacitance for each * pixel. * * @F54_FULL_RAW_CAP: Full Raw Capacitance Report. The raw capacitance with * low reference set to its minimum value and high * reference set to its maximum value. * * @F54_FULL_RAW_CAP_RX_OFFSET_REMOVED: * Full Raw Capacitance with Receiver Offset Removed * Report. Set Low reference to its minimum value and high * references to its maximum value, then report the raw * capacitance for each pixel. * * @F54_MAX_REPORT_TYPE: * Maximum number of Report Types. Used for sanity * checking. */ enum rmi_f54_report_type { F54_REPORT_NONE = 0, F54_8BIT_IMAGE = 1, F54_16BIT_IMAGE = 2, F54_RAW_16BIT_IMAGE = 3, F54_TRUE_BASELINE = 9, F54_FULL_RAW_CAP = 19, F54_FULL_RAW_CAP_RX_OFFSET_REMOVED = 20, F54_MAX_REPORT_TYPE, }; static const char * const rmi_f54_report_type_names[] = { [F54_REPORT_NONE] = "Unknown", [F54_8BIT_IMAGE] = "Normalized 8-Bit Image", [F54_16BIT_IMAGE] = "Normalized 16-Bit Image", [F54_RAW_16BIT_IMAGE] = "Raw 16-Bit Image", [F54_TRUE_BASELINE] = "True Baseline", [F54_FULL_RAW_CAP] = "Full Raw Capacitance", [F54_FULL_RAW_CAP_RX_OFFSET_REMOVED] = "Full Raw Capacitance RX Offset Removed", }; struct f54_data { struct rmi_function *fn; u8 num_rx_electrodes; u8 num_tx_electrodes; u8 capabilities; u16 clock_rate; u8 family; enum rmi_f54_report_type report_type; u8 *report_data; int report_size; bool is_busy; struct mutex status_mutex; struct mutex data_mutex; struct workqueue_struct *workqueue; struct delayed_work work; unsigned long timeout; struct completion cmd_done; /* V4L2 support */ struct v4l2_device v4l2; struct v4l2_pix_format format; struct video_device vdev; struct vb2_queue queue; struct mutex lock; u32 sequence; int input; enum rmi_f54_report_type inputs[F54_MAX_REPORT_TYPE]; }; /* * Basic checks on report_type to ensure we write a valid type * to the sensor. */ static bool is_f54_report_type_valid(struct f54_data *f54, enum rmi_f54_report_type reptype) { switch (reptype) { case F54_8BIT_IMAGE: return f54->capabilities & F54_CAP_IMAGE8; case F54_16BIT_IMAGE: case F54_RAW_16BIT_IMAGE: return f54->capabilities & F54_CAP_IMAGE16; case F54_TRUE_BASELINE: return f54->capabilities & F54_CAP_IMAGE16; case F54_FULL_RAW_CAP: case F54_FULL_RAW_CAP_RX_OFFSET_REMOVED: return true; default: return false; } } static enum rmi_f54_report_type rmi_f54_get_reptype(struct f54_data *f54, unsigned int i) { if (i >= F54_MAX_REPORT_TYPE) return F54_REPORT_NONE; return f54->inputs[i]; } static void rmi_f54_create_input_map(struct f54_data *f54) { int i = 0; enum rmi_f54_report_type reptype; for (reptype = 1; reptype < F54_MAX_REPORT_TYPE; reptype++) { if (!is_f54_report_type_valid(f54, reptype)) continue; f54->inputs[i++] = reptype; } /* Remaining values are zero via kzalloc */ } static int rmi_f54_request_report(struct rmi_function *fn, u8 report_type) { struct f54_data *f54 = dev_get_drvdata(&fn->dev); struct rmi_device *rmi_dev = fn->rmi_dev; int error; /* Write Report Type into F54_AD_Data0 */ if (f54->report_type != report_type) { error = rmi_write(rmi_dev, f54->fn->fd.data_base_addr, report_type); if (error) return error; f54->report_type = report_type; } /* * Small delay after disabling interrupts to avoid race condition * in firmare. This value is a bit higher than absolutely necessary. * Should be removed once issue is resolved in firmware. */ usleep_range(2000, 3000); mutex_lock(&f54->data_mutex); error = rmi_write(rmi_dev, fn->fd.command_base_addr, F54_GET_REPORT); if (error < 0) goto unlock; init_completion(&f54->cmd_done); f54->is_busy = 1; f54->timeout = jiffies + msecs_to_jiffies(100); queue_delayed_work(f54->workqueue, &f54->work, 0); unlock: mutex_unlock(&f54->data_mutex); return error; } static size_t rmi_f54_get_report_size(struct f54_data *f54) { struct rmi_device *rmi_dev = f54->fn->rmi_dev; struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); u8 rx = drv_data->num_rx_electrodes ? : f54->num_rx_electrodes; u8 tx = drv_data->num_tx_electrodes ? : f54->num_tx_electrodes; size_t size; switch (rmi_f54_get_reptype(f54, f54->input)) { case F54_8BIT_IMAGE: size = rx * tx; break; case F54_16BIT_IMAGE: case F54_RAW_16BIT_IMAGE: case F54_TRUE_BASELINE: case F54_FULL_RAW_CAP: case F54_FULL_RAW_CAP_RX_OFFSET_REMOVED: size = sizeof(u16) * rx * tx; break; default: size = 0; } return size; } static int rmi_f54_get_pixel_fmt(enum rmi_f54_report_type reptype, u32 *pixfmt) { int ret = 0; switch (reptype) { case F54_8BIT_IMAGE: *pixfmt = V4L2_TCH_FMT_DELTA_TD08; break; case F54_16BIT_IMAGE: *pixfmt = V4L2_TCH_FMT_DELTA_TD16; break; case F54_RAW_16BIT_IMAGE: case F54_TRUE_BASELINE: case F54_FULL_RAW_CAP: case F54_FULL_RAW_CAP_RX_OFFSET_REMOVED: *pixfmt = V4L2_TCH_FMT_TU16; break; case F54_REPORT_NONE: case F54_MAX_REPORT_TYPE: ret = -EINVAL; break; } return ret; } static const struct v4l2_file_operations rmi_f54_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, }; static int rmi_f54_queue_setup(struct vb2_queue *q, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct f54_data *f54 = q->drv_priv; if (*nplanes) return sizes[0] < rmi_f54_get_report_size(f54) ? -EINVAL : 0; *nplanes = 1; sizes[0] = rmi_f54_get_report_size(f54); return 0; } static void rmi_f54_buffer_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct f54_data *f54 = vb2_get_drv_priv(vb->vb2_queue); u16 *ptr; enum vb2_buffer_state state; enum rmi_f54_report_type reptype; int ret; mutex_lock(&f54->status_mutex); vb2_set_plane_payload(vb, 0, 0); reptype = rmi_f54_get_reptype(f54, f54->input); if (reptype == F54_REPORT_NONE) { state = VB2_BUF_STATE_ERROR; goto done; } if (f54->is_busy) { state = VB2_BUF_STATE_ERROR; goto done; } ret = rmi_f54_request_report(f54->fn, reptype); if (ret) { dev_err(&f54->fn->dev, "Error requesting F54 report\n"); state = VB2_BUF_STATE_ERROR; goto done; } /* get frame data */ mutex_lock(&f54->data_mutex); while (f54->is_busy) { mutex_unlock(&f54->data_mutex); if (!wait_for_completion_timeout(&f54->cmd_done, msecs_to_jiffies(1000))) { dev_err(&f54->fn->dev, "Timed out\n"); state = VB2_BUF_STATE_ERROR; goto done; } mutex_lock(&f54->data_mutex); } ptr = vb2_plane_vaddr(vb, 0); if (!ptr) { dev_err(&f54->fn->dev, "Error acquiring frame ptr\n"); state = VB2_BUF_STATE_ERROR; goto data_done; } memcpy(ptr, f54->report_data, f54->report_size); vb2_set_plane_payload(vb, 0, rmi_f54_get_report_size(f54)); state = VB2_BUF_STATE_DONE; data_done: mutex_unlock(&f54->data_mutex); done: vb->timestamp = ktime_get_ns(); vbuf->field = V4L2_FIELD_NONE; vbuf->sequence = f54->sequence++; vb2_buffer_done(vb, state); mutex_unlock(&f54->status_mutex); } static void rmi_f54_stop_streaming(struct vb2_queue *q) { struct f54_data *f54 = vb2_get_drv_priv(q); f54->sequence = 0; } /* V4L2 structures */ static const struct vb2_ops rmi_f54_queue_ops = { .queue_setup = rmi_f54_queue_setup, .buf_queue = rmi_f54_buffer_queue, .stop_streaming = rmi_f54_stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static const struct vb2_queue rmi_f54_queue = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ, .buf_struct_size = sizeof(struct vb2_v4l2_buffer), .ops = &rmi_f54_queue_ops, .mem_ops = &vb2_vmalloc_memops, .timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC, }; static int rmi_f54_vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct f54_data *f54 = video_drvdata(file); strscpy(cap->driver, F54_NAME, sizeof(cap->driver)); strscpy(cap->card, SYNAPTICS_INPUT_DEVICE_NAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "rmi4:%s", dev_name(&f54->fn->dev)); return 0; } static int rmi_f54_vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *i) { struct f54_data *f54 = video_drvdata(file); enum rmi_f54_report_type reptype; reptype = rmi_f54_get_reptype(f54, i->index); if (reptype == F54_REPORT_NONE) return -EINVAL; i->type = V4L2_INPUT_TYPE_TOUCH; strscpy(i->name, rmi_f54_report_type_names[reptype], sizeof(i->name)); return 0; } static int rmi_f54_set_input(struct f54_data *f54, unsigned int i) { struct rmi_device *rmi_dev = f54->fn->rmi_dev; struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); u8 rx = drv_data->num_rx_electrodes ? : f54->num_rx_electrodes; u8 tx = drv_data->num_tx_electrodes ? : f54->num_tx_electrodes; struct v4l2_pix_format *f = &f54->format; enum rmi_f54_report_type reptype; int ret; reptype = rmi_f54_get_reptype(f54, i); if (reptype == F54_REPORT_NONE) return -EINVAL; ret = rmi_f54_get_pixel_fmt(reptype, &f->pixelformat); if (ret) return ret; f54->input = i; f->width = rx; f->height = tx; f->field = V4L2_FIELD_NONE; f->colorspace = V4L2_COLORSPACE_RAW; f->bytesperline = f->width * sizeof(u16); f->sizeimage = f->width * f->height * sizeof(u16); return 0; } static int rmi_f54_vidioc_s_input(struct file *file, void *priv, unsigned int i) { return rmi_f54_set_input(video_drvdata(file), i); } static int rmi_f54_vidioc_g_input(struct file *file, void *priv, unsigned int *i) { struct f54_data *f54 = video_drvdata(file); *i = f54->input; return 0; } static int rmi_f54_vidioc_fmt(struct file *file, void *priv, struct v4l2_format *f) { struct f54_data *f54 = video_drvdata(file); f->fmt.pix = f54->format; return 0; } static int rmi_f54_vidioc_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *fmt) { struct f54_data *f54 = video_drvdata(file); if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; if (fmt->index) return -EINVAL; fmt->pixelformat = f54->format.pixelformat; return 0; } static int rmi_f54_vidioc_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a) { if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; a->parm.capture.readbuffers = 1; a->parm.capture.timeperframe.numerator = 1; a->parm.capture.timeperframe.denominator = 10; return 0; } static const struct v4l2_ioctl_ops rmi_f54_video_ioctl_ops = { .vidioc_querycap = rmi_f54_vidioc_querycap, .vidioc_enum_fmt_vid_cap = rmi_f54_vidioc_enum_fmt, .vidioc_s_fmt_vid_cap = rmi_f54_vidioc_fmt, .vidioc_g_fmt_vid_cap = rmi_f54_vidioc_fmt, .vidioc_try_fmt_vid_cap = rmi_f54_vidioc_fmt, .vidioc_g_parm = rmi_f54_vidioc_g_parm, .vidioc_enum_input = rmi_f54_vidioc_enum_input, .vidioc_g_input = rmi_f54_vidioc_g_input, .vidioc_s_input = rmi_f54_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 rmi_f54_video_device = { .name = "Synaptics RMI4", .fops = &rmi_f54_video_fops, .ioctl_ops = &rmi_f54_video_ioctl_ops, .release = video_device_release_empty, .device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING, }; static void rmi_f54_work(struct work_struct *work) { struct f54_data *f54 = container_of(work, struct f54_data, work.work); struct rmi_function *fn = f54->fn; u8 fifo[2]; int report_size; u8 command; int error; int i; report_size = rmi_f54_get_report_size(f54); if (report_size == 0) { dev_err(&fn->dev, "Bad report size, report type=%d\n", f54->report_type); error = -EINVAL; goto error; /* retry won't help */ } mutex_lock(&f54->data_mutex); /* * Need to check if command has completed. * If not try again later. */ error = rmi_read(fn->rmi_dev, f54->fn->fd.command_base_addr, &command); if (error) { dev_err(&fn->dev, "Failed to read back command\n"); goto error; } if (command & F54_GET_REPORT) { if (time_after(jiffies, f54->timeout)) { dev_err(&fn->dev, "Get report command timed out\n"); error = -ETIMEDOUT; } report_size = 0; goto error; } rmi_dbg(RMI_DEBUG_FN, &fn->dev, "Get report command completed, reading data\n"); for (i = 0; i < report_size; i += F54_REPORT_DATA_SIZE) { int size = min(F54_REPORT_DATA_SIZE, report_size - i); fifo[0] = i & 0xff; fifo[1] = i >> 8; error = rmi_write_block(fn->rmi_dev, fn->fd.data_base_addr + F54_FIFO_OFFSET, fifo, sizeof(fifo)); if (error) { dev_err(&fn->dev, "Failed to set fifo start offset\n"); goto abort; } error = rmi_read_block(fn->rmi_dev, fn->fd.data_base_addr + F54_REPORT_DATA_OFFSET, f54->report_data + i, size); if (error) { dev_err(&fn->dev, "%s: read [%d bytes] returned %d\n", __func__, size, error); goto abort; } } abort: f54->report_size = error ? 0 : report_size; error: if (error) report_size = 0; if (report_size == 0 && !error) { queue_delayed_work(f54->workqueue, &f54->work, msecs_to_jiffies(1)); } else { f54->is_busy = false; complete(&f54->cmd_done); } mutex_unlock(&f54->data_mutex); } static int rmi_f54_config(struct rmi_function *fn) { struct rmi_driver *drv = fn->rmi_dev->driver; drv->clear_irq_bits(fn->rmi_dev, fn->irq_mask); return 0; } static int rmi_f54_detect(struct rmi_function *fn) { int error; struct f54_data *f54; u8 buf[6]; f54 = dev_get_drvdata(&fn->dev); error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr, buf, sizeof(buf)); if (error) { dev_err(&fn->dev, "%s: Failed to query F54 properties\n", __func__); return error; } f54->num_rx_electrodes = buf[0]; f54->num_tx_electrodes = buf[1]; f54->capabilities = buf[2]; f54->clock_rate = buf[3] | (buf[4] << 8); f54->family = buf[5]; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F54 num_rx_electrodes: %d\n", f54->num_rx_electrodes); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F54 num_tx_electrodes: %d\n", f54->num_tx_electrodes); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F54 capabilities: 0x%x\n", f54->capabilities); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F54 clock rate: 0x%x\n", f54->clock_rate); rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F54 family: 0x%x\n", f54->family); f54->is_busy = false; return 0; } static int rmi_f54_probe(struct rmi_function *fn) { struct f54_data *f54; int ret; u8 rx, tx; f54 = devm_kzalloc(&fn->dev, sizeof(struct f54_data), GFP_KERNEL); if (!f54) return -ENOMEM; f54->fn = fn; dev_set_drvdata(&fn->dev, f54); ret = rmi_f54_detect(fn); if (ret) return ret; mutex_init(&f54->data_mutex); mutex_init(&f54->status_mutex); rx = f54->num_rx_electrodes; tx = f54->num_tx_electrodes; f54->report_data = devm_kzalloc(&fn->dev, array3_size(tx, rx, sizeof(u16)), GFP_KERNEL); if (f54->report_data == NULL) return -ENOMEM; INIT_DELAYED_WORK(&f54->work, rmi_f54_work); f54->workqueue = create_singlethread_workqueue("rmi4-poller"); if (!f54->workqueue) return -ENOMEM; rmi_f54_create_input_map(f54); rmi_f54_set_input(f54, 0); /* register video device */ strscpy(f54->v4l2.name, F54_NAME, sizeof(f54->v4l2.name)); ret = v4l2_device_register(&fn->dev, &f54->v4l2); if (ret) { dev_err(&fn->dev, "Unable to register video dev.\n"); goto remove_wq; } /* initialize the queue */ mutex_init(&f54->lock); f54->queue = rmi_f54_queue; f54->queue.drv_priv = f54; f54->queue.lock = &f54->lock; f54->queue.dev = &fn->dev; ret = vb2_queue_init(&f54->queue); if (ret) goto remove_v4l2; f54->vdev = rmi_f54_video_device; f54->vdev.v4l2_dev = &f54->v4l2; f54->vdev.lock = &f54->lock; f54->vdev.vfl_dir = VFL_DIR_RX; f54->vdev.queue = &f54->queue; video_set_drvdata(&f54->vdev, f54); ret = video_register_device(&f54->vdev, VFL_TYPE_TOUCH, -1); if (ret) { dev_err(&fn->dev, "Unable to register video subdevice."); goto remove_v4l2; } return 0; remove_v4l2: v4l2_device_unregister(&f54->v4l2); remove_wq: cancel_delayed_work_sync(&f54->work); destroy_workqueue(f54->workqueue); return ret; } static void rmi_f54_remove(struct rmi_function *fn) { struct f54_data *f54 = dev_get_drvdata(&fn->dev); video_unregister_device(&f54->vdev); v4l2_device_unregister(&f54->v4l2); destroy_workqueue(f54->workqueue); } struct rmi_function_handler rmi_f54_handler = { .driver = { .name = F54_NAME, }, .func = 0x54, .probe = rmi_f54_probe, .config = rmi_f54_config, .remove = rmi_f54_remove, };
linux-master
drivers/input/rmi4/rmi_f54.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2012-2020 Synaptics Incorporated */ #include <linux/kernel.h> #include <linux/rmi.h> #include <linux/input.h> #include <linux/slab.h> #include "rmi_driver.h" #define RMI_F3A_MAX_GPIO_COUNT 128 #define RMI_F3A_MAX_REG_SIZE DIV_ROUND_UP(RMI_F3A_MAX_GPIO_COUNT, 8) /* Defs for Query 0 */ #define RMI_F3A_GPIO_COUNT 0x7F #define RMI_F3A_DATA_REGS_MAX_SIZE RMI_F3A_MAX_REG_SIZE #define TRACKSTICK_RANGE_START 3 #define TRACKSTICK_RANGE_END 6 struct f3a_data { /* Query Data */ u8 gpio_count; u8 register_count; u8 data_regs[RMI_F3A_DATA_REGS_MAX_SIZE]; u16 *gpio_key_map; struct input_dev *input; struct rmi_function *f03; bool trackstick_buttons; }; static void rmi_f3a_report_button(struct rmi_function *fn, struct f3a_data *f3a, unsigned int button) { u16 key_code = f3a->gpio_key_map[button]; bool key_down = !(f3a->data_regs[0] & BIT(button)); if (f3a->trackstick_buttons && button >= TRACKSTICK_RANGE_START && button <= TRACKSTICK_RANGE_END) { rmi_f03_overwrite_button(f3a->f03, key_code, key_down); } else { rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: call input report key (0x%04x) value (0x%02x)", __func__, key_code, key_down); input_report_key(f3a->input, key_code, key_down); } } static irqreturn_t rmi_f3a_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct f3a_data *f3a = dev_get_drvdata(&fn->dev); struct rmi_driver_data *drvdata = dev_get_drvdata(&fn->rmi_dev->dev); int error; int i; if (drvdata->attn_data.data) { if (drvdata->attn_data.size < f3a->register_count) { dev_warn(&fn->dev, "F3A interrupted, but data is missing\n"); return IRQ_HANDLED; } memcpy(f3a->data_regs, drvdata->attn_data.data, f3a->register_count); drvdata->attn_data.data += f3a->register_count; drvdata->attn_data.size -= f3a->register_count; } else { error = rmi_read_block(fn->rmi_dev, fn->fd.data_base_addr, f3a->data_regs, f3a->register_count); if (error) { dev_err(&fn->dev, "%s: Failed to read F3a data registers: %d\n", __func__, error); return IRQ_RETVAL(error); } } for (i = 0; i < f3a->gpio_count; i++) if (f3a->gpio_key_map[i] != KEY_RESERVED) rmi_f3a_report_button(fn, f3a, i); if (f3a->trackstick_buttons) rmi_f03_commit_buttons(f3a->f03); return IRQ_HANDLED; } static int rmi_f3a_config(struct rmi_function *fn) { struct f3a_data *f3a = dev_get_drvdata(&fn->dev); struct rmi_driver *drv = fn->rmi_dev->driver; const struct rmi_device_platform_data *pdata = rmi_get_platform_data(fn->rmi_dev); if (!f3a) return 0; if (pdata->gpio_data.trackstick_buttons) { /* Try [re-]establish link to F03. */ f3a->f03 = rmi_find_function(fn->rmi_dev, 0x03); f3a->trackstick_buttons = f3a->f03 != NULL; } drv->set_irq_bits(fn->rmi_dev, fn->irq_mask); return 0; } static bool rmi_f3a_is_valid_button(int button, struct f3a_data *f3a, u8 *query1_regs, u8 *ctrl1_regs) { /* gpio exist && direction input */ return (query1_regs[0] & BIT(button)) && !(ctrl1_regs[0] & BIT(button)); } static int rmi_f3a_map_gpios(struct rmi_function *fn, struct f3a_data *f3a, u8 *query1_regs, u8 *ctrl1_regs) { const struct rmi_device_platform_data *pdata = rmi_get_platform_data(fn->rmi_dev); struct input_dev *input = f3a->input; unsigned int button = BTN_LEFT; unsigned int trackstick_button = BTN_LEFT; bool button_mapped = false; int i; int button_count = min_t(u8, f3a->gpio_count, TRACKSTICK_RANGE_END); f3a->gpio_key_map = devm_kcalloc(&fn->dev, button_count, sizeof(f3a->gpio_key_map[0]), GFP_KERNEL); if (!f3a->gpio_key_map) { dev_err(&fn->dev, "Failed to allocate gpio map memory.\n"); return -ENOMEM; } for (i = 0; i < button_count; i++) { if (!rmi_f3a_is_valid_button(i, f3a, query1_regs, ctrl1_regs)) continue; if (pdata->gpio_data.trackstick_buttons && i >= TRACKSTICK_RANGE_START && i < TRACKSTICK_RANGE_END) { f3a->gpio_key_map[i] = trackstick_button++; } else if (!pdata->gpio_data.buttonpad || !button_mapped) { f3a->gpio_key_map[i] = button; input_set_capability(input, EV_KEY, button++); button_mapped = true; } } input->keycode = f3a->gpio_key_map; input->keycodesize = sizeof(f3a->gpio_key_map[0]); input->keycodemax = f3a->gpio_count; if (pdata->gpio_data.buttonpad || (button - BTN_LEFT == 1)) __set_bit(INPUT_PROP_BUTTONPAD, input->propbit); return 0; } static int rmi_f3a_initialize(struct rmi_function *fn, struct f3a_data *f3a) { u8 query1[RMI_F3A_MAX_REG_SIZE]; u8 ctrl1[RMI_F3A_MAX_REG_SIZE]; u8 buf; int error; error = rmi_read(fn->rmi_dev, fn->fd.query_base_addr, &buf); if (error < 0) { dev_err(&fn->dev, "Failed to read general info register: %d\n", error); return -ENODEV; } f3a->gpio_count = buf & RMI_F3A_GPIO_COUNT; f3a->register_count = DIV_ROUND_UP(f3a->gpio_count, 8); /* Query1 -> gpio exist */ error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr + 1, query1, f3a->register_count); if (error) { dev_err(&fn->dev, "Failed to read query1 register\n"); return error; } /* Ctrl1 -> gpio direction */ error = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr + 1, ctrl1, f3a->register_count); if (error) { dev_err(&fn->dev, "Failed to read control1 register\n"); return error; } error = rmi_f3a_map_gpios(fn, f3a, query1, ctrl1); if (error) return error; return 0; } static int rmi_f3a_probe(struct rmi_function *fn) { struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); struct f3a_data *f3a; int error; if (!drv_data->input) { dev_info(&fn->dev, "F3A: no input device found, ignoring\n"); return -ENXIO; } f3a = devm_kzalloc(&fn->dev, sizeof(*f3a), GFP_KERNEL); if (!f3a) return -ENOMEM; f3a->input = drv_data->input; error = rmi_f3a_initialize(fn, f3a); if (error) return error; dev_set_drvdata(&fn->dev, f3a); return 0; } struct rmi_function_handler rmi_f3a_handler = { .driver = { .name = "rmi4_f3a", }, .func = 0x3a, .probe = rmi_f3a_probe, .config = rmi_f3a_config, .attention = rmi_f3a_attention, };
linux-master
drivers/input/rmi4/rmi_f3a.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/rmi.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/of.h> #include "rmi_driver.h" #define RMI_SPI_DEFAULT_XFER_BUF_SIZE 64 #define RMI_PAGE_SELECT_REGISTER 0x00FF #define RMI_SPI_PAGE(addr) (((addr) >> 8) & 0x80) #define RMI_SPI_XFER_SIZE_LIMIT 255 #define BUFFER_SIZE_INCREMENT 32 enum rmi_spi_op { RMI_SPI_WRITE = 0, RMI_SPI_READ, RMI_SPI_V2_READ_UNIFIED, RMI_SPI_V2_READ_SPLIT, RMI_SPI_V2_WRITE, }; struct rmi_spi_cmd { enum rmi_spi_op op; u16 addr; }; struct rmi_spi_xport { struct rmi_transport_dev xport; struct spi_device *spi; struct mutex page_mutex; int page; u8 *rx_buf; u8 *tx_buf; int xfer_buf_size; struct spi_transfer *rx_xfers; struct spi_transfer *tx_xfers; int rx_xfer_count; int tx_xfer_count; }; static int rmi_spi_manage_pools(struct rmi_spi_xport *rmi_spi, int len) { struct spi_device *spi = rmi_spi->spi; int buf_size = rmi_spi->xfer_buf_size ? rmi_spi->xfer_buf_size : RMI_SPI_DEFAULT_XFER_BUF_SIZE; struct spi_transfer *xfer_buf; void *buf; void *tmp; while (buf_size < len) buf_size *= 2; if (buf_size > RMI_SPI_XFER_SIZE_LIMIT) buf_size = RMI_SPI_XFER_SIZE_LIMIT; tmp = rmi_spi->rx_buf; buf = devm_kcalloc(&spi->dev, buf_size, 2, GFP_KERNEL | GFP_DMA); if (!buf) return -ENOMEM; rmi_spi->rx_buf = buf; rmi_spi->tx_buf = &rmi_spi->rx_buf[buf_size]; rmi_spi->xfer_buf_size = buf_size; if (tmp) devm_kfree(&spi->dev, tmp); if (rmi_spi->xport.pdata.spi_data.read_delay_us) rmi_spi->rx_xfer_count = buf_size; else rmi_spi->rx_xfer_count = 1; if (rmi_spi->xport.pdata.spi_data.write_delay_us) rmi_spi->tx_xfer_count = buf_size; else rmi_spi->tx_xfer_count = 1; /* * Allocate a pool of spi_transfer buffers for devices which need * per byte delays. */ tmp = rmi_spi->rx_xfers; xfer_buf = devm_kcalloc(&spi->dev, rmi_spi->rx_xfer_count + rmi_spi->tx_xfer_count, sizeof(struct spi_transfer), GFP_KERNEL); if (!xfer_buf) return -ENOMEM; rmi_spi->rx_xfers = xfer_buf; rmi_spi->tx_xfers = &xfer_buf[rmi_spi->rx_xfer_count]; if (tmp) devm_kfree(&spi->dev, tmp); return 0; } static int rmi_spi_xfer(struct rmi_spi_xport *rmi_spi, const struct rmi_spi_cmd *cmd, const u8 *tx_buf, int tx_len, u8 *rx_buf, int rx_len) { struct spi_device *spi = rmi_spi->spi; struct rmi_device_platform_data_spi *spi_data = &rmi_spi->xport.pdata.spi_data; struct spi_message msg; struct spi_transfer *xfer; int ret = 0; int len; int cmd_len = 0; int total_tx_len; int i; u16 addr = cmd->addr; spi_message_init(&msg); switch (cmd->op) { case RMI_SPI_WRITE: case RMI_SPI_READ: cmd_len += 2; break; case RMI_SPI_V2_READ_UNIFIED: case RMI_SPI_V2_READ_SPLIT: case RMI_SPI_V2_WRITE: cmd_len += 4; break; } total_tx_len = cmd_len + tx_len; len = max(total_tx_len, rx_len); if (len > RMI_SPI_XFER_SIZE_LIMIT) return -EINVAL; if (rmi_spi->xfer_buf_size < len) { ret = rmi_spi_manage_pools(rmi_spi, len); if (ret < 0) return ret; } if (addr == 0) /* * SPI needs an address. Use 0x7FF if we want to keep * reading from the last position of the register pointer. */ addr = 0x7FF; switch (cmd->op) { case RMI_SPI_WRITE: rmi_spi->tx_buf[0] = (addr >> 8); rmi_spi->tx_buf[1] = addr & 0xFF; break; case RMI_SPI_READ: rmi_spi->tx_buf[0] = (addr >> 8) | 0x80; rmi_spi->tx_buf[1] = addr & 0xFF; break; case RMI_SPI_V2_READ_UNIFIED: break; case RMI_SPI_V2_READ_SPLIT: break; case RMI_SPI_V2_WRITE: rmi_spi->tx_buf[0] = 0x40; rmi_spi->tx_buf[1] = (addr >> 8) & 0xFF; rmi_spi->tx_buf[2] = addr & 0xFF; rmi_spi->tx_buf[3] = tx_len; break; } if (tx_buf) memcpy(&rmi_spi->tx_buf[cmd_len], tx_buf, tx_len); if (rmi_spi->tx_xfer_count > 1) { for (i = 0; i < total_tx_len; i++) { xfer = &rmi_spi->tx_xfers[i]; memset(xfer, 0, sizeof(struct spi_transfer)); xfer->tx_buf = &rmi_spi->tx_buf[i]; xfer->len = 1; xfer->delay.value = spi_data->write_delay_us; xfer->delay.unit = SPI_DELAY_UNIT_USECS; spi_message_add_tail(xfer, &msg); } } else { xfer = rmi_spi->tx_xfers; memset(xfer, 0, sizeof(struct spi_transfer)); xfer->tx_buf = rmi_spi->tx_buf; xfer->len = total_tx_len; spi_message_add_tail(xfer, &msg); } rmi_dbg(RMI_DEBUG_XPORT, &spi->dev, "%s: cmd: %s tx_buf len: %d tx_buf: %*ph\n", __func__, cmd->op == RMI_SPI_WRITE ? "WRITE" : "READ", total_tx_len, total_tx_len, rmi_spi->tx_buf); if (rx_buf) { if (rmi_spi->rx_xfer_count > 1) { for (i = 0; i < rx_len; i++) { xfer = &rmi_spi->rx_xfers[i]; memset(xfer, 0, sizeof(struct spi_transfer)); xfer->rx_buf = &rmi_spi->rx_buf[i]; xfer->len = 1; xfer->delay.value = spi_data->read_delay_us; xfer->delay.unit = SPI_DELAY_UNIT_USECS; spi_message_add_tail(xfer, &msg); } } else { xfer = rmi_spi->rx_xfers; memset(xfer, 0, sizeof(struct spi_transfer)); xfer->rx_buf = rmi_spi->rx_buf; xfer->len = rx_len; spi_message_add_tail(xfer, &msg); } } ret = spi_sync(spi, &msg); if (ret < 0) { dev_err(&spi->dev, "spi xfer failed: %d\n", ret); return ret; } if (rx_buf) { memcpy(rx_buf, rmi_spi->rx_buf, rx_len); rmi_dbg(RMI_DEBUG_XPORT, &spi->dev, "%s: (%d) %*ph\n", __func__, rx_len, rx_len, rx_buf); } return 0; } /* * rmi_set_page - Set RMI page * @xport: The pointer to the rmi_transport_dev struct * @page: The new page address. * * RMI devices have 16-bit addressing, but some of the transport * implementations (like SMBus) only have 8-bit addressing. So RMI implements * a page address at 0xff of every page so we can reliable page addresses * every 256 registers. * * The page_mutex lock must be held when this function is entered. * * Returns zero on success, non-zero on failure. */ static int rmi_set_page(struct rmi_spi_xport *rmi_spi, u8 page) { struct rmi_spi_cmd cmd; int ret; cmd.op = RMI_SPI_WRITE; cmd.addr = RMI_PAGE_SELECT_REGISTER; ret = rmi_spi_xfer(rmi_spi, &cmd, &page, 1, NULL, 0); if (ret) rmi_spi->page = page; return ret; } static int rmi_spi_write_block(struct rmi_transport_dev *xport, u16 addr, const void *buf, size_t len) { struct rmi_spi_xport *rmi_spi = container_of(xport, struct rmi_spi_xport, xport); struct rmi_spi_cmd cmd; int ret; mutex_lock(&rmi_spi->page_mutex); if (RMI_SPI_PAGE(addr) != rmi_spi->page) { ret = rmi_set_page(rmi_spi, RMI_SPI_PAGE(addr)); if (ret) goto exit; } cmd.op = RMI_SPI_WRITE; cmd.addr = addr; ret = rmi_spi_xfer(rmi_spi, &cmd, buf, len, NULL, 0); exit: mutex_unlock(&rmi_spi->page_mutex); return ret; } static int rmi_spi_read_block(struct rmi_transport_dev *xport, u16 addr, void *buf, size_t len) { struct rmi_spi_xport *rmi_spi = container_of(xport, struct rmi_spi_xport, xport); struct rmi_spi_cmd cmd; int ret; mutex_lock(&rmi_spi->page_mutex); if (RMI_SPI_PAGE(addr) != rmi_spi->page) { ret = rmi_set_page(rmi_spi, RMI_SPI_PAGE(addr)); if (ret) goto exit; } cmd.op = RMI_SPI_READ; cmd.addr = addr; ret = rmi_spi_xfer(rmi_spi, &cmd, NULL, 0, buf, len); exit: mutex_unlock(&rmi_spi->page_mutex); return ret; } static const struct rmi_transport_ops rmi_spi_ops = { .write_block = rmi_spi_write_block, .read_block = rmi_spi_read_block, }; #ifdef CONFIG_OF static int rmi_spi_of_probe(struct spi_device *spi, struct rmi_device_platform_data *pdata) { struct device *dev = &spi->dev; int retval; retval = rmi_of_property_read_u32(dev, &pdata->spi_data.read_delay_us, "spi-rx-delay-us", 1); if (retval) return retval; retval = rmi_of_property_read_u32(dev, &pdata->spi_data.write_delay_us, "spi-tx-delay-us", 1); if (retval) return retval; return 0; } static const struct of_device_id rmi_spi_of_match[] = { { .compatible = "syna,rmi4-spi" }, {}, }; MODULE_DEVICE_TABLE(of, rmi_spi_of_match); #else static inline int rmi_spi_of_probe(struct spi_device *spi, struct rmi_device_platform_data *pdata) { return -ENODEV; } #endif static void rmi_spi_unregister_transport(void *data) { struct rmi_spi_xport *rmi_spi = data; rmi_unregister_transport_device(&rmi_spi->xport); } static int rmi_spi_probe(struct spi_device *spi) { struct rmi_spi_xport *rmi_spi; struct rmi_device_platform_data *pdata; struct rmi_device_platform_data *spi_pdata = spi->dev.platform_data; int error; if (spi->master->flags & SPI_MASTER_HALF_DUPLEX) return -EINVAL; rmi_spi = devm_kzalloc(&spi->dev, sizeof(struct rmi_spi_xport), GFP_KERNEL); if (!rmi_spi) return -ENOMEM; pdata = &rmi_spi->xport.pdata; if (spi->dev.of_node) { error = rmi_spi_of_probe(spi, pdata); if (error) return error; } else if (spi_pdata) { *pdata = *spi_pdata; } if (pdata->spi_data.bits_per_word) spi->bits_per_word = pdata->spi_data.bits_per_word; if (pdata->spi_data.mode) spi->mode = pdata->spi_data.mode; error = spi_setup(spi); if (error < 0) { dev_err(&spi->dev, "spi_setup failed!\n"); return error; } pdata->irq = spi->irq; rmi_spi->spi = spi; mutex_init(&rmi_spi->page_mutex); rmi_spi->xport.dev = &spi->dev; rmi_spi->xport.proto_name = "spi"; rmi_spi->xport.ops = &rmi_spi_ops; spi_set_drvdata(spi, rmi_spi); error = rmi_spi_manage_pools(rmi_spi, RMI_SPI_DEFAULT_XFER_BUF_SIZE); if (error) return error; /* * Setting the page to zero will (a) make sure the PSR is in a * known state, and (b) make sure we can talk to the device. */ error = rmi_set_page(rmi_spi, 0); if (error) { dev_err(&spi->dev, "Failed to set page select to 0.\n"); return error; } dev_info(&spi->dev, "registering SPI-connected sensor\n"); error = rmi_register_transport_device(&rmi_spi->xport); if (error) { dev_err(&spi->dev, "failed to register sensor: %d\n", error); return error; } error = devm_add_action_or_reset(&spi->dev, rmi_spi_unregister_transport, rmi_spi); if (error) return error; return 0; } static int rmi_spi_suspend(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct rmi_spi_xport *rmi_spi = spi_get_drvdata(spi); int ret; ret = rmi_driver_suspend(rmi_spi->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return ret; } static int rmi_spi_resume(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct rmi_spi_xport *rmi_spi = spi_get_drvdata(spi); int ret; ret = rmi_driver_resume(rmi_spi->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return ret; } static int rmi_spi_runtime_suspend(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct rmi_spi_xport *rmi_spi = spi_get_drvdata(spi); int ret; ret = rmi_driver_suspend(rmi_spi->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return 0; } static int rmi_spi_runtime_resume(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct rmi_spi_xport *rmi_spi = spi_get_drvdata(spi); int ret; ret = rmi_driver_resume(rmi_spi->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return 0; } static const struct dev_pm_ops rmi_spi_pm = { SYSTEM_SLEEP_PM_OPS(rmi_spi_suspend, rmi_spi_resume) RUNTIME_PM_OPS(rmi_spi_runtime_suspend, rmi_spi_runtime_resume, NULL) }; static const struct spi_device_id rmi_id[] = { { "rmi4-spi", 0 }, { } }; MODULE_DEVICE_TABLE(spi, rmi_id); static struct spi_driver rmi_spi_driver = { .driver = { .name = "rmi4_spi", .pm = pm_ptr(&rmi_spi_pm), .of_match_table = of_match_ptr(rmi_spi_of_match), }, .id_table = rmi_id, .probe = rmi_spi_probe, }; module_spi_driver(rmi_spi_driver); MODULE_AUTHOR("Christopher Heiny <[email protected]>"); MODULE_AUTHOR("Andrew Duggan <[email protected]>"); MODULE_DESCRIPTION("RMI SPI driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/rmi4/rmi_spi.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2015-2016 Red Hat * Copyright (C) 2015 Lyude Paul <[email protected]> */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/serio.h> #include <linux/notifier.h> #include "rmi_driver.h" #define RMI_F03_RX_DATA_OFB 0x01 #define RMI_F03_OB_SIZE 2 #define RMI_F03_OB_OFFSET 2 #define RMI_F03_OB_DATA_OFFSET 1 #define RMI_F03_OB_FLAG_TIMEOUT BIT(6) #define RMI_F03_OB_FLAG_PARITY BIT(7) #define RMI_F03_DEVICE_COUNT 0x07 #define RMI_F03_BYTES_PER_DEVICE 0x07 #define RMI_F03_BYTES_PER_DEVICE_SHIFT 4 #define RMI_F03_QUEUE_LENGTH 0x0F #define PSMOUSE_OOB_EXTRA_BTNS 0x01 struct f03_data { struct rmi_function *fn; struct serio *serio; bool serio_registered; unsigned int overwrite_buttons; u8 device_count; u8 rx_queue_length; }; int rmi_f03_overwrite_button(struct rmi_function *fn, unsigned int button, int value) { struct f03_data *f03 = dev_get_drvdata(&fn->dev); unsigned int bit; if (button < BTN_LEFT || button > BTN_MIDDLE) return -EINVAL; bit = BIT(button - BTN_LEFT); if (value) f03->overwrite_buttons |= bit; else f03->overwrite_buttons &= ~bit; return 0; } void rmi_f03_commit_buttons(struct rmi_function *fn) { struct f03_data *f03 = dev_get_drvdata(&fn->dev); struct serio *serio = f03->serio; serio_pause_rx(serio); if (serio->drv) { serio->drv->interrupt(serio, PSMOUSE_OOB_EXTRA_BTNS, SERIO_OOB_DATA); serio->drv->interrupt(serio, f03->overwrite_buttons, SERIO_OOB_DATA); } serio_continue_rx(serio); } static int rmi_f03_pt_write(struct serio *id, unsigned char val) { struct f03_data *f03 = id->port_data; int error; rmi_dbg(RMI_DEBUG_FN, &f03->fn->dev, "%s: Wrote %.2hhx to PS/2 passthrough address", __func__, val); error = rmi_write(f03->fn->rmi_dev, f03->fn->fd.data_base_addr, val); if (error) { dev_err(&f03->fn->dev, "%s: Failed to write to F03 TX register (%d).\n", __func__, error); return error; } return 0; } static int rmi_f03_initialize(struct f03_data *f03) { struct rmi_function *fn = f03->fn; struct device *dev = &fn->dev; int error; u8 bytes_per_device; u8 query1; u8 query2[RMI_F03_DEVICE_COUNT * RMI_F03_BYTES_PER_DEVICE]; size_t query2_len; error = rmi_read(fn->rmi_dev, fn->fd.query_base_addr, &query1); if (error) { dev_err(dev, "Failed to read query register (%d).\n", error); return error; } f03->device_count = query1 & RMI_F03_DEVICE_COUNT; bytes_per_device = (query1 >> RMI_F03_BYTES_PER_DEVICE_SHIFT) & RMI_F03_BYTES_PER_DEVICE; query2_len = f03->device_count * bytes_per_device; /* * The first generation of image sensors don't have a second part to * their f03 query, as such we have to set some of these values manually */ if (query2_len < 1) { f03->device_count = 1; f03->rx_queue_length = 7; } else { error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr + 1, query2, query2_len); if (error) { dev_err(dev, "Failed to read second set of query registers (%d).\n", error); return error; } f03->rx_queue_length = query2[0] & RMI_F03_QUEUE_LENGTH; } return 0; } static int rmi_f03_pt_open(struct serio *serio) { struct f03_data *f03 = serio->port_data; struct rmi_function *fn = f03->fn; const u8 ob_len = f03->rx_queue_length * RMI_F03_OB_SIZE; const u16 data_addr = fn->fd.data_base_addr + RMI_F03_OB_OFFSET; u8 obs[RMI_F03_QUEUE_LENGTH * RMI_F03_OB_SIZE]; int error; /* * Consume any pending data. Some devices like to spam with * 0xaa 0x00 announcements which may confuse us as we try to * probe the device. */ error = rmi_read_block(fn->rmi_dev, data_addr, &obs, ob_len); if (!error) rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: Consumed %*ph (%d) from PS2 guest\n", __func__, ob_len, obs, ob_len); return fn->rmi_dev->driver->set_irq_bits(fn->rmi_dev, fn->irq_mask); } static void rmi_f03_pt_close(struct serio *serio) { struct f03_data *f03 = serio->port_data; struct rmi_function *fn = f03->fn; fn->rmi_dev->driver->clear_irq_bits(fn->rmi_dev, fn->irq_mask); } static int rmi_f03_register_pt(struct f03_data *f03) { struct serio *serio; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = SERIO_PS_PSTHRU; serio->write = rmi_f03_pt_write; serio->open = rmi_f03_pt_open; serio->close = rmi_f03_pt_close; serio->port_data = f03; strscpy(serio->name, "RMI4 PS/2 pass-through", sizeof(serio->name)); snprintf(serio->phys, sizeof(serio->phys), "%s/serio0", dev_name(&f03->fn->dev)); serio->dev.parent = &f03->fn->dev; f03->serio = serio; printk(KERN_INFO "serio: %s port at %s\n", serio->name, dev_name(&f03->fn->dev)); serio_register_port(serio); return 0; } static int rmi_f03_probe(struct rmi_function *fn) { struct device *dev = &fn->dev; struct f03_data *f03; int error; f03 = devm_kzalloc(dev, sizeof(struct f03_data), GFP_KERNEL); if (!f03) return -ENOMEM; f03->fn = fn; error = rmi_f03_initialize(f03); if (error < 0) return error; if (f03->device_count != 1) dev_warn(dev, "found %d devices on PS/2 passthrough", f03->device_count); dev_set_drvdata(dev, f03); return 0; } static int rmi_f03_config(struct rmi_function *fn) { struct f03_data *f03 = dev_get_drvdata(&fn->dev); int error; if (!f03->serio_registered) { error = rmi_f03_register_pt(f03); if (error) return error; f03->serio_registered = true; } else { /* * We must be re-configuring the sensor, just enable * interrupts for this function. */ fn->rmi_dev->driver->set_irq_bits(fn->rmi_dev, fn->irq_mask); } return 0; } static irqreturn_t rmi_f03_attention(int irq, void *ctx) { struct rmi_function *fn = ctx; struct rmi_device *rmi_dev = fn->rmi_dev; struct rmi_driver_data *drvdata = dev_get_drvdata(&rmi_dev->dev); struct f03_data *f03 = dev_get_drvdata(&fn->dev); const u16 data_addr = fn->fd.data_base_addr + RMI_F03_OB_OFFSET; const u8 ob_len = f03->rx_queue_length * RMI_F03_OB_SIZE; u8 obs[RMI_F03_QUEUE_LENGTH * RMI_F03_OB_SIZE]; u8 ob_status; u8 ob_data; unsigned int serio_flags; int i; int error; if (drvdata->attn_data.data) { /* First grab the data passed by the transport device */ if (drvdata->attn_data.size < ob_len) { dev_warn(&fn->dev, "F03 interrupted, but data is missing!\n"); return IRQ_HANDLED; } memcpy(obs, drvdata->attn_data.data, ob_len); drvdata->attn_data.data += ob_len; drvdata->attn_data.size -= ob_len; } else { /* Grab all of the data registers, and check them for data */ error = rmi_read_block(fn->rmi_dev, data_addr, &obs, ob_len); if (error) { dev_err(&fn->dev, "%s: Failed to read F03 output buffers: %d\n", __func__, error); serio_interrupt(f03->serio, 0, SERIO_TIMEOUT); return IRQ_RETVAL(error); } } for (i = 0; i < ob_len; i += RMI_F03_OB_SIZE) { ob_status = obs[i]; ob_data = obs[i + RMI_F03_OB_DATA_OFFSET]; serio_flags = 0; if (!(ob_status & RMI_F03_RX_DATA_OFB)) continue; if (ob_status & RMI_F03_OB_FLAG_TIMEOUT) serio_flags |= SERIO_TIMEOUT; if (ob_status & RMI_F03_OB_FLAG_PARITY) serio_flags |= SERIO_PARITY; rmi_dbg(RMI_DEBUG_FN, &fn->dev, "%s: Received %.2hhx from PS2 guest T: %c P: %c\n", __func__, ob_data, serio_flags & SERIO_TIMEOUT ? 'Y' : 'N', serio_flags & SERIO_PARITY ? 'Y' : 'N'); serio_interrupt(f03->serio, ob_data, serio_flags); } return IRQ_HANDLED; } static void rmi_f03_remove(struct rmi_function *fn) { struct f03_data *f03 = dev_get_drvdata(&fn->dev); if (f03->serio_registered) serio_unregister_port(f03->serio); } struct rmi_function_handler rmi_f03_handler = { .driver = { .name = "rmi4_f03", }, .func = 0x03, .probe = rmi_f03_probe, .config = rmi_f03_config, .attention = rmi_f03_attention, .remove = rmi_f03_remove, }; MODULE_AUTHOR("Lyude Paul <[email protected]>"); MODULE_DESCRIPTION("RMI F03 module"); MODULE_LICENSE("GPL");
linux-master
drivers/input/rmi4/rmi_f03.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2011-2016 Synaptics Incorporated * Copyright (c) 2011 Unixphere */ #include <linux/i2c.h> #include <linux/rmi.h> #include <linux/of.h> #include <linux/delay.h> #include <linux/regulator/consumer.h> #include "rmi_driver.h" #define BUFFER_SIZE_INCREMENT 32 /** * struct rmi_i2c_xport - stores information for i2c communication * * @xport: The transport interface structure * @client: The I2C client device structure * * @page_mutex: Locks current page to avoid changing pages in unexpected ways. * @page: Keeps track of the current virtual page * * @tx_buf: Buffer used for transmitting data to the sensor over i2c. * @tx_buf_size: Size of the buffer * * @supplies: Array of voltage regulators * @startup_delay: Milliseconds to pause after powering up the regulators */ struct rmi_i2c_xport { struct rmi_transport_dev xport; struct i2c_client *client; struct mutex page_mutex; int page; u8 *tx_buf; size_t tx_buf_size; struct regulator_bulk_data supplies[2]; u32 startup_delay; }; #define RMI_PAGE_SELECT_REGISTER 0xff #define RMI_I2C_PAGE(addr) (((addr) >> 8) & 0xff) /* * rmi_set_page - Set RMI page * @xport: The pointer to the rmi_transport_dev struct * @page: The new page address. * * RMI devices have 16-bit addressing, but some of the transport * implementations (like SMBus) only have 8-bit addressing. So RMI implements * a page address at 0xff of every page so we can reliable page addresses * every 256 registers. * * The page_mutex lock must be held when this function is entered. * * Returns zero on success, non-zero on failure. */ static int rmi_set_page(struct rmi_i2c_xport *rmi_i2c, u8 page) { struct i2c_client *client = rmi_i2c->client; u8 txbuf[2] = {RMI_PAGE_SELECT_REGISTER, page}; int retval; retval = i2c_master_send(client, txbuf, sizeof(txbuf)); if (retval != sizeof(txbuf)) { dev_err(&client->dev, "%s: set page failed: %d.", __func__, retval); return (retval < 0) ? retval : -EIO; } rmi_i2c->page = page; return 0; } static int rmi_i2c_write_block(struct rmi_transport_dev *xport, u16 addr, const void *buf, size_t len) { struct rmi_i2c_xport *rmi_i2c = container_of(xport, struct rmi_i2c_xport, xport); struct i2c_client *client = rmi_i2c->client; size_t tx_size = len + 1; int retval; mutex_lock(&rmi_i2c->page_mutex); if (!rmi_i2c->tx_buf || rmi_i2c->tx_buf_size < tx_size) { if (rmi_i2c->tx_buf) devm_kfree(&client->dev, rmi_i2c->tx_buf); rmi_i2c->tx_buf_size = tx_size + BUFFER_SIZE_INCREMENT; rmi_i2c->tx_buf = devm_kzalloc(&client->dev, rmi_i2c->tx_buf_size, GFP_KERNEL); if (!rmi_i2c->tx_buf) { rmi_i2c->tx_buf_size = 0; retval = -ENOMEM; goto exit; } } rmi_i2c->tx_buf[0] = addr & 0xff; memcpy(rmi_i2c->tx_buf + 1, buf, len); if (RMI_I2C_PAGE(addr) != rmi_i2c->page) { retval = rmi_set_page(rmi_i2c, RMI_I2C_PAGE(addr)); if (retval) goto exit; } retval = i2c_master_send(client, rmi_i2c->tx_buf, tx_size); if (retval == tx_size) retval = 0; else if (retval >= 0) retval = -EIO; exit: rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "write %zd bytes at %#06x: %d (%*ph)\n", len, addr, retval, (int)len, buf); mutex_unlock(&rmi_i2c->page_mutex); return retval; } static int rmi_i2c_read_block(struct rmi_transport_dev *xport, u16 addr, void *buf, size_t len) { struct rmi_i2c_xport *rmi_i2c = container_of(xport, struct rmi_i2c_xport, xport); struct i2c_client *client = rmi_i2c->client; u8 addr_offset = addr & 0xff; int retval; struct i2c_msg msgs[] = { { .addr = client->addr, .len = sizeof(addr_offset), .buf = &addr_offset, }, { .addr = client->addr, .flags = I2C_M_RD, .len = len, .buf = buf, }, }; mutex_lock(&rmi_i2c->page_mutex); if (RMI_I2C_PAGE(addr) != rmi_i2c->page) { retval = rmi_set_page(rmi_i2c, RMI_I2C_PAGE(addr)); if (retval) goto exit; } retval = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (retval == ARRAY_SIZE(msgs)) retval = 0; /* success */ else if (retval >= 0) retval = -EIO; exit: rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "read %zd bytes at %#06x: %d (%*ph)\n", len, addr, retval, (int)len, buf); mutex_unlock(&rmi_i2c->page_mutex); return retval; } static const struct rmi_transport_ops rmi_i2c_ops = { .write_block = rmi_i2c_write_block, .read_block = rmi_i2c_read_block, }; #ifdef CONFIG_OF static const struct of_device_id rmi_i2c_of_match[] = { { .compatible = "syna,rmi4-i2c" }, {}, }; MODULE_DEVICE_TABLE(of, rmi_i2c_of_match); #endif static void rmi_i2c_regulator_bulk_disable(void *data) { struct rmi_i2c_xport *rmi_i2c = data; regulator_bulk_disable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); } static void rmi_i2c_unregister_transport(void *data) { struct rmi_i2c_xport *rmi_i2c = data; rmi_unregister_transport_device(&rmi_i2c->xport); } static int rmi_i2c_probe(struct i2c_client *client) { struct rmi_device_platform_data *pdata; struct rmi_device_platform_data *client_pdata = dev_get_platdata(&client->dev); struct rmi_i2c_xport *rmi_i2c; int error; rmi_i2c = devm_kzalloc(&client->dev, sizeof(struct rmi_i2c_xport), GFP_KERNEL); if (!rmi_i2c) return -ENOMEM; pdata = &rmi_i2c->xport.pdata; if (!client->dev.of_node && client_pdata) *pdata = *client_pdata; pdata->irq = client->irq; rmi_dbg(RMI_DEBUG_XPORT, &client->dev, "Probing %s.\n", dev_name(&client->dev)); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "adapter does not support required functionality\n"); return -ENODEV; } rmi_i2c->supplies[0].supply = "vdd"; rmi_i2c->supplies[1].supply = "vio"; error = devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); if (error < 0) return error; error = regulator_bulk_enable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); if (error < 0) return error; error = devm_add_action_or_reset(&client->dev, rmi_i2c_regulator_bulk_disable, rmi_i2c); if (error) return error; of_property_read_u32(client->dev.of_node, "syna,startup-delay-ms", &rmi_i2c->startup_delay); msleep(rmi_i2c->startup_delay); rmi_i2c->client = client; mutex_init(&rmi_i2c->page_mutex); rmi_i2c->xport.dev = &client->dev; rmi_i2c->xport.proto_name = "i2c"; rmi_i2c->xport.ops = &rmi_i2c_ops; i2c_set_clientdata(client, rmi_i2c); /* * Setting the page to zero will (a) make sure the PSR is in a * known state, and (b) make sure we can talk to the device. */ error = rmi_set_page(rmi_i2c, 0); if (error) { dev_err(&client->dev, "Failed to set page select to 0\n"); return error; } dev_info(&client->dev, "registering I2C-connected sensor\n"); error = rmi_register_transport_device(&rmi_i2c->xport); if (error) { dev_err(&client->dev, "failed to register sensor: %d\n", error); return error; } error = devm_add_action_or_reset(&client->dev, rmi_i2c_unregister_transport, rmi_i2c); if (error) return error; return 0; } static int rmi_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_i2c_xport *rmi_i2c = i2c_get_clientdata(client); int ret; ret = rmi_driver_suspend(rmi_i2c->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); regulator_bulk_disable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); return ret; } static int rmi_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_i2c_xport *rmi_i2c = i2c_get_clientdata(client); int ret; ret = regulator_bulk_enable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); if (ret) return ret; msleep(rmi_i2c->startup_delay); ret = rmi_driver_resume(rmi_i2c->xport.rmi_dev, true); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return ret; } static int rmi_i2c_runtime_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_i2c_xport *rmi_i2c = i2c_get_clientdata(client); int ret; ret = rmi_driver_suspend(rmi_i2c->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); regulator_bulk_disable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); return 0; } static int rmi_i2c_runtime_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct rmi_i2c_xport *rmi_i2c = i2c_get_clientdata(client); int ret; ret = regulator_bulk_enable(ARRAY_SIZE(rmi_i2c->supplies), rmi_i2c->supplies); if (ret) return ret; msleep(rmi_i2c->startup_delay); ret = rmi_driver_resume(rmi_i2c->xport.rmi_dev, false); if (ret) dev_warn(dev, "Failed to resume device: %d\n", ret); return 0; } static const struct dev_pm_ops rmi_i2c_pm = { SYSTEM_SLEEP_PM_OPS(rmi_i2c_suspend, rmi_i2c_resume) RUNTIME_PM_OPS(rmi_i2c_runtime_suspend, rmi_i2c_runtime_resume, NULL) }; static const struct i2c_device_id rmi_id[] = { { "rmi4_i2c", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, rmi_id); static struct i2c_driver rmi_i2c_driver = { .driver = { .name = "rmi4_i2c", .pm = pm_ptr(&rmi_i2c_pm), .of_match_table = of_match_ptr(rmi_i2c_of_match), }, .id_table = rmi_id, .probe = rmi_i2c_probe, }; module_i2c_driver(rmi_i2c_driver); MODULE_AUTHOR("Christopher Heiny <[email protected]>"); MODULE_AUTHOR("Andrew Duggan <[email protected]>"); MODULE_DESCRIPTION("RMI I2C driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/rmi4/rmi_i2c.c
// SPDX-License-Identifier: GPL-2.0 /* * KUnit test for the input core. * * Copyright (c) 2023 Red Hat Inc */ #include <linux/delay.h> #include <linux/input.h> #include <kunit/test.h> #define POLL_INTERVAL 100 static int input_test_init(struct kunit *test) { struct input_dev *input_dev; int ret; input_dev = input_allocate_device(); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, input_dev); input_dev->name = "Test input device"; input_dev->id.bustype = BUS_VIRTUAL; input_dev->id.vendor = 1; input_dev->id.product = 1; input_dev->id.version = 1; input_set_capability(input_dev, EV_KEY, BTN_LEFT); input_set_capability(input_dev, EV_KEY, BTN_RIGHT); ret = input_register_device(input_dev); if (ret) { input_free_device(input_dev); KUNIT_ASSERT_FAILURE(test, "Register device failed: %d", ret); } test->priv = input_dev; return 0; } static void input_test_exit(struct kunit *test) { struct input_dev *input_dev = test->priv; if (input_dev) input_unregister_device(input_dev); } static void input_test_poll(struct input_dev *input) { } static void input_test_polling(struct kunit *test) { struct input_dev *input_dev = test->priv; /* Must fail because a poll handler has not been set-up yet */ KUNIT_ASSERT_EQ(test, input_get_poll_interval(input_dev), -EINVAL); KUNIT_ASSERT_EQ(test, input_setup_polling(input_dev, input_test_poll), 0); input_set_poll_interval(input_dev, POLL_INTERVAL); /* Must succeed because poll handler was set-up and poll interval set */ KUNIT_ASSERT_EQ(test, input_get_poll_interval(input_dev), POLL_INTERVAL); } static void input_test_timestamp(struct kunit *test) { const ktime_t invalid_timestamp = ktime_set(0, 0); struct input_dev *input_dev = test->priv; ktime_t *timestamp, time; timestamp = input_get_timestamp(input_dev); time = timestamp[INPUT_CLK_MONO]; /* The returned timestamp must always be valid */ KUNIT_ASSERT_EQ(test, ktime_compare(time, invalid_timestamp), 1); time = ktime_get(); input_set_timestamp(input_dev, time); timestamp = input_get_timestamp(input_dev); /* The timestamp must be the same than set before */ KUNIT_ASSERT_EQ(test, ktime_compare(timestamp[INPUT_CLK_MONO], time), 0); } static void input_test_match_device_id(struct kunit *test) { struct input_dev *input_dev = test->priv; struct input_device_id id = { 0 }; /* * Must match when the input device bus, vendor, product, version * and events capable of handling are the same and fail to match * otherwise. */ id.flags = INPUT_DEVICE_ID_MATCH_BUS; id.bustype = BUS_VIRTUAL; KUNIT_ASSERT_TRUE(test, input_match_device_id(input_dev, &id)); id.bustype = BUS_I2C; KUNIT_ASSERT_FALSE(test, input_match_device_id(input_dev, &id)); id.flags = INPUT_DEVICE_ID_MATCH_VENDOR; id.vendor = 1; KUNIT_ASSERT_TRUE(test, input_match_device_id(input_dev, &id)); id.vendor = 2; KUNIT_ASSERT_FALSE(test, input_match_device_id(input_dev, &id)); id.flags = INPUT_DEVICE_ID_MATCH_PRODUCT; id.product = 1; KUNIT_ASSERT_TRUE(test, input_match_device_id(input_dev, &id)); id.product = 2; KUNIT_ASSERT_FALSE(test, input_match_device_id(input_dev, &id)); id.flags = INPUT_DEVICE_ID_MATCH_VERSION; id.version = 1; KUNIT_ASSERT_TRUE(test, input_match_device_id(input_dev, &id)); id.version = 2; KUNIT_ASSERT_FALSE(test, input_match_device_id(input_dev, &id)); id.flags = INPUT_DEVICE_ID_MATCH_EVBIT; __set_bit(EV_KEY, id.evbit); KUNIT_ASSERT_TRUE(test, input_match_device_id(input_dev, &id)); __set_bit(EV_ABS, id.evbit); KUNIT_ASSERT_FALSE(test, input_match_device_id(input_dev, &id)); } static void input_test_grab(struct kunit *test) { struct input_dev *input_dev = test->priv; struct input_handle test_handle; struct input_handler handler; struct input_handle handle; struct input_device_id id; int res; handler.name = "handler"; handler.id_table = &id; handle.dev = input_get_device(input_dev); handle.name = dev_name(&input_dev->dev); handle.handler = &handler; res = input_grab_device(&handle); KUNIT_ASSERT_TRUE(test, res == 0); test_handle.dev = input_get_device(input_dev); test_handle.name = dev_name(&input_dev->dev); test_handle.handler = &handler; res = input_grab_device(&test_handle); KUNIT_ASSERT_EQ(test, res, -EBUSY); input_release_device(&handle); input_put_device(input_dev); res = input_grab_device(&test_handle); KUNIT_ASSERT_TRUE(test, res == 0); input_put_device(input_dev); } static struct kunit_case input_tests[] = { KUNIT_CASE(input_test_polling), KUNIT_CASE(input_test_timestamp), KUNIT_CASE(input_test_match_device_id), KUNIT_CASE(input_test_grab), { /* sentinel */ } }; static struct kunit_suite input_test_suite = { .name = "input_core", .init = input_test_init, .exit = input_test_exit, .test_cases = input_tests, }; kunit_test_suite(input_test_suite); MODULE_AUTHOR("Javier Martinez Canillas <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/tests/input_test.c
// SPDX-License-Identifier: GPL-2.0-only /* * Elan I2C/SMBus Touchpad driver - SMBus interface * * Copyright (c) 2013 ELAN Microelectronics Corp. * * Author: 林政維 (Duson Lin) <[email protected]> * * Based on cyapa driver: * copyright (c) 2011-2012 Cypress Semiconductor, Inc. * copyright (c) 2011-2012 Google, Inc. * * Trademarks are the property of their respective owners. */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/kernel.h> #include "elan_i2c.h" /* Elan SMbus commands */ #define ETP_SMBUS_IAP_CMD 0x00 #define ETP_SMBUS_ENABLE_TP 0x20 #define ETP_SMBUS_SLEEP_CMD 0x21 #define ETP_SMBUS_IAP_PASSWORD_WRITE 0x29 #define ETP_SMBUS_IAP_PASSWORD_READ 0x80 #define ETP_SMBUS_WRITE_FW_BLOCK 0x2A #define ETP_SMBUS_IAP_RESET_CMD 0x2B #define ETP_SMBUS_RANGE_CMD 0xA0 #define ETP_SMBUS_FW_VERSION_CMD 0xA1 #define ETP_SMBUS_XY_TRACENUM_CMD 0xA2 #define ETP_SMBUS_SM_VERSION_CMD 0xA3 #define ETP_SMBUS_UNIQUEID_CMD 0xA3 #define ETP_SMBUS_RESOLUTION_CMD 0xA4 #define ETP_SMBUS_HELLOPACKET_CMD 0xA7 #define ETP_SMBUS_PACKET_QUERY 0xA8 #define ETP_SMBUS_IAP_VERSION_CMD 0xAC #define ETP_SMBUS_IAP_CTRL_CMD 0xAD #define ETP_SMBUS_IAP_CHECKSUM_CMD 0xAE #define ETP_SMBUS_FW_CHECKSUM_CMD 0xAF #define ETP_SMBUS_MAX_BASELINE_CMD 0xC3 #define ETP_SMBUS_MIN_BASELINE_CMD 0xC4 #define ETP_SMBUS_CALIBRATE_QUERY 0xC5 #define ETP_SMBUS_REPORT_LEN 32 #define ETP_SMBUS_REPORT_LEN2 7 #define ETP_SMBUS_REPORT_OFFSET 2 #define ETP_SMBUS_HELLOPACKET_LEN 5 #define ETP_SMBUS_IAP_PASSWORD 0x1234 #define ETP_SMBUS_IAP_MODE_ON (1 << 6) static int elan_smbus_initialize(struct i2c_client *client) { u8 check[ETP_SMBUS_HELLOPACKET_LEN] = { 0x55, 0x55, 0x55, 0x55, 0x55 }; u8 values[I2C_SMBUS_BLOCK_MAX] = {0}; int len, error; /* Get hello packet */ len = i2c_smbus_read_block_data(client, ETP_SMBUS_HELLOPACKET_CMD, values); if (len != ETP_SMBUS_HELLOPACKET_LEN) { dev_err(&client->dev, "hello packet length fail: %d\n", len); error = len < 0 ? len : -EIO; return error; } /* compare hello packet */ if (memcmp(values, check, ETP_SMBUS_HELLOPACKET_LEN)) { dev_err(&client->dev, "hello packet fail [%*ph]\n", ETP_SMBUS_HELLOPACKET_LEN, values); return -ENXIO; } /* enable tp */ error = i2c_smbus_write_byte(client, ETP_SMBUS_ENABLE_TP); if (error) { dev_err(&client->dev, "failed to enable touchpad: %d\n", error); return error; } return 0; } static int elan_smbus_set_mode(struct i2c_client *client, u8 mode) { u8 cmd[4] = { 0x00, 0x07, 0x00, mode }; return i2c_smbus_write_block_data(client, ETP_SMBUS_IAP_CMD, sizeof(cmd), cmd); } static int elan_smbus_sleep_control(struct i2c_client *client, bool sleep) { if (sleep) return i2c_smbus_write_byte(client, ETP_SMBUS_SLEEP_CMD); else return 0; /* XXX should we send ETP_SMBUS_ENABLE_TP here? */ } static int elan_smbus_power_control(struct i2c_client *client, bool enable) { return 0; /* A no-op */ } static int elan_smbus_calibrate(struct i2c_client *client) { u8 cmd[4] = { 0x00, 0x08, 0x00, 0x01 }; return i2c_smbus_write_block_data(client, ETP_SMBUS_IAP_CMD, sizeof(cmd), cmd); } static int elan_smbus_calibrate_result(struct i2c_client *client, u8 *val) { int error; u8 buf[I2C_SMBUS_BLOCK_MAX] = {0}; BUILD_BUG_ON(ETP_CALIBRATE_MAX_LEN > sizeof(buf)); error = i2c_smbus_read_block_data(client, ETP_SMBUS_CALIBRATE_QUERY, buf); if (error < 0) return error; memcpy(val, buf, ETP_CALIBRATE_MAX_LEN); return 0; } static int elan_smbus_get_baseline_data(struct i2c_client *client, bool max_baseline, u8 *value) { int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, max_baseline ? ETP_SMBUS_MAX_BASELINE_CMD : ETP_SMBUS_MIN_BASELINE_CMD, val); if (error < 0) return error; *value = be16_to_cpup((__be16 *)val); return 0; } static int elan_smbus_get_version(struct i2c_client *client, u8 pattern, bool iap, u8 *version) { int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, iap ? ETP_SMBUS_IAP_VERSION_CMD : ETP_SMBUS_FW_VERSION_CMD, val); if (error < 0) { dev_err(&client->dev, "failed to get %s version: %d\n", iap ? "IAP" : "FW", error); return error; } *version = val[2]; return 0; } static int elan_smbus_get_sm_version(struct i2c_client *client, u8 pattern, u16 *ic_type, u8 *version, u8 *clickpad) { int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, ETP_SMBUS_SM_VERSION_CMD, val); if (error < 0) { dev_err(&client->dev, "failed to get SM version: %d\n", error); return error; } *version = val[0]; *ic_type = val[1]; *clickpad = val[0] & 0x10; return 0; } static int elan_smbus_get_product_id(struct i2c_client *client, u16 *id) { int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, ETP_SMBUS_UNIQUEID_CMD, val); if (error < 0) { dev_err(&client->dev, "failed to get product ID: %d\n", error); return error; } *id = be16_to_cpup((__be16 *)val); return 0; } static int elan_smbus_get_checksum(struct i2c_client *client, bool iap, u16 *csum) { int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, iap ? ETP_SMBUS_FW_CHECKSUM_CMD : ETP_SMBUS_IAP_CHECKSUM_CMD, val); if (error < 0) { dev_err(&client->dev, "failed to get %s checksum: %d\n", iap ? "IAP" : "FW", error); return error; } *csum = be16_to_cpup((__be16 *)val); return 0; } static int elan_smbus_get_max(struct i2c_client *client, unsigned int *max_x, unsigned int *max_y) { int ret; int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; ret = i2c_smbus_read_block_data(client, ETP_SMBUS_RANGE_CMD, val); if (ret != 3) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "failed to get dimensions: %d\n", error); return error; } *max_x = (0x0f & val[0]) << 8 | val[1]; *max_y = (0xf0 & val[0]) << 4 | val[2]; return 0; } static int elan_smbus_get_resolution(struct i2c_client *client, u8 *hw_res_x, u8 *hw_res_y) { int ret; int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; ret = i2c_smbus_read_block_data(client, ETP_SMBUS_RESOLUTION_CMD, val); if (ret != 3) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "failed to get resolution: %d\n", error); return error; } *hw_res_x = val[1] & 0x0F; *hw_res_y = (val[1] & 0xF0) >> 4; return 0; } static int elan_smbus_get_num_traces(struct i2c_client *client, unsigned int *x_traces, unsigned int *y_traces) { int ret; int error; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; ret = i2c_smbus_read_block_data(client, ETP_SMBUS_XY_TRACENUM_CMD, val); if (ret != 3) { error = ret < 0 ? ret : -EIO; dev_err(&client->dev, "failed to get trace info: %d\n", error); return error; } *x_traces = val[1]; *y_traces = val[2]; return 0; } static int elan_smbus_get_pressure_adjustment(struct i2c_client *client, int *adjustment) { *adjustment = ETP_PRESSURE_OFFSET; return 0; } static int elan_smbus_iap_get_mode(struct i2c_client *client, enum tp_mode *mode) { int error; u16 constant; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; error = i2c_smbus_read_block_data(client, ETP_SMBUS_IAP_CTRL_CMD, val); if (error < 0) { dev_err(&client->dev, "failed to read iap ctrol register: %d\n", error); return error; } constant = be16_to_cpup((__be16 *)val); dev_dbg(&client->dev, "iap control reg: 0x%04x.\n", constant); *mode = (constant & ETP_SMBUS_IAP_MODE_ON) ? IAP_MODE : MAIN_MODE; return 0; } static int elan_smbus_iap_reset(struct i2c_client *client) { int error; error = i2c_smbus_write_byte(client, ETP_SMBUS_IAP_RESET_CMD); if (error) { dev_err(&client->dev, "cannot reset IC: %d\n", error); return error; } return 0; } static int elan_smbus_set_flash_key(struct i2c_client *client) { int error; u8 cmd[4] = { 0x00, 0x0B, 0x00, 0x5A }; error = i2c_smbus_write_block_data(client, ETP_SMBUS_IAP_CMD, sizeof(cmd), cmd); if (error) { dev_err(&client->dev, "cannot set flash key: %d\n", error); return error; } return 0; } static int elan_smbus_prepare_fw_update(struct i2c_client *client, u16 ic_type, u8 iap_version, u16 fw_page_size) { struct device *dev = &client->dev; int len; int error; enum tp_mode mode; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; u8 cmd[4] = {0x0F, 0x78, 0x00, 0x06}; u16 password; /* Get FW in which mode (IAP_MODE/MAIN_MODE) */ error = elan_smbus_iap_get_mode(client, &mode); if (error) return error; if (mode == MAIN_MODE) { /* set flash key */ error = elan_smbus_set_flash_key(client); if (error) return error; /* write iap password */ if (i2c_smbus_write_byte(client, ETP_SMBUS_IAP_PASSWORD_WRITE) < 0) { dev_err(dev, "cannot write iap password\n"); return -EIO; } error = i2c_smbus_write_block_data(client, ETP_SMBUS_IAP_CMD, sizeof(cmd), cmd); if (error) { dev_err(dev, "failed to write iap password: %d\n", error); return error; } /* * Read back password to make sure we enabled flash * successfully. */ len = i2c_smbus_read_block_data(client, ETP_SMBUS_IAP_PASSWORD_READ, val); if (len < (int)sizeof(u16)) { error = len < 0 ? len : -EIO; dev_err(dev, "failed to read iap password: %d\n", error); return error; } password = be16_to_cpup((__be16 *)val); if (password != ETP_SMBUS_IAP_PASSWORD) { dev_err(dev, "wrong iap password = 0x%X\n", password); return -EIO; } /* Wait 30ms for MAIN_MODE change to IAP_MODE */ msleep(30); } error = elan_smbus_set_flash_key(client); if (error) return error; /* Reset IC */ error = elan_smbus_iap_reset(client); if (error) return error; return 0; } static int elan_smbus_write_fw_block(struct i2c_client *client, u16 fw_page_size, const u8 *page, u16 checksum, int idx) { struct device *dev = &client->dev; int error; u16 result; u8 val[I2C_SMBUS_BLOCK_MAX] = {0}; /* * Due to the limitation of smbus protocol limiting * transfer to 32 bytes at a time, we must split block * in 2 transfers. */ error = i2c_smbus_write_block_data(client, ETP_SMBUS_WRITE_FW_BLOCK, fw_page_size / 2, page); if (error) { dev_err(dev, "Failed to write page %d (part %d): %d\n", idx, 1, error); return error; } error = i2c_smbus_write_block_data(client, ETP_SMBUS_WRITE_FW_BLOCK, fw_page_size / 2, page + fw_page_size / 2); if (error) { dev_err(dev, "Failed to write page %d (part %d): %d\n", idx, 2, error); return error; } /* Wait for F/W to update one page ROM data. */ usleep_range(8000, 10000); error = i2c_smbus_read_block_data(client, ETP_SMBUS_IAP_CTRL_CMD, val); if (error < 0) { dev_err(dev, "Failed to read IAP write result: %d\n", error); return error; } result = be16_to_cpup((__be16 *)val); if (result & (ETP_FW_IAP_PAGE_ERR | ETP_FW_IAP_INTF_ERR)) { dev_err(dev, "IAP reports failed write: %04hx\n", result); return -EIO; } return 0; } static int elan_smbus_get_report_features(struct i2c_client *client, u8 pattern, unsigned int *features, unsigned int *report_len) { /* * SMBus controllers with pattern 2 lack area info, as newer * high-precision packets use that space for coordinates. */ *features = pattern <= 0x01 ? ETP_FEATURE_REPORT_MK : 0; *report_len = ETP_SMBUS_REPORT_LEN; return 0; } static int elan_smbus_get_report(struct i2c_client *client, u8 *report, unsigned int report_len) { int len; BUILD_BUG_ON(I2C_SMBUS_BLOCK_MAX > ETP_SMBUS_REPORT_LEN); len = i2c_smbus_read_block_data(client, ETP_SMBUS_PACKET_QUERY, &report[ETP_SMBUS_REPORT_OFFSET]); if (len < 0) { dev_err(&client->dev, "failed to read report data: %d\n", len); return len; } if (report[ETP_REPORT_ID_OFFSET] == ETP_TP_REPORT_ID2) report_len = ETP_SMBUS_REPORT_LEN2; if (len != report_len) { dev_err(&client->dev, "wrong report length (%d vs %d expected)\n", len, report_len); return -EIO; } return 0; } static int elan_smbus_finish_fw_update(struct i2c_client *client, struct completion *fw_completion) { /* No special handling unlike I2C transport */ return 0; } static int elan_smbus_get_pattern(struct i2c_client *client, u8 *pattern) { *pattern = 0; return 0; } const struct elan_transport_ops elan_smbus_ops = { .initialize = elan_smbus_initialize, .sleep_control = elan_smbus_sleep_control, .power_control = elan_smbus_power_control, .set_mode = elan_smbus_set_mode, .calibrate = elan_smbus_calibrate, .calibrate_result = elan_smbus_calibrate_result, .get_baseline_data = elan_smbus_get_baseline_data, .get_version = elan_smbus_get_version, .get_sm_version = elan_smbus_get_sm_version, .get_product_id = elan_smbus_get_product_id, .get_checksum = elan_smbus_get_checksum, .get_pressure_adjustment = elan_smbus_get_pressure_adjustment, .get_max = elan_smbus_get_max, .get_resolution = elan_smbus_get_resolution, .get_num_traces = elan_smbus_get_num_traces, .iap_get_mode = elan_smbus_iap_get_mode, .iap_reset = elan_smbus_iap_reset, .prepare_fw_update = elan_smbus_prepare_fw_update, .write_fw_block = elan_smbus_write_fw_block, .finish_fw_update = elan_smbus_finish_fw_update, .get_report_features = elan_smbus_get_report_features, .get_report = elan_smbus_get_report, .get_pattern = elan_smbus_get_pattern, };
linux-master
drivers/input/mouse/elan_i2c_smbus.c
// SPDX-License-Identifier: GPL-2.0-only /* * Acorn RiscPC mouse driver for Linux/ARM * * Copyright (c) 2000-2002 Vojtech Pavlik * Copyright (C) 1996-2002 Russell King */ /* * * This handles the Acorn RiscPCs mouse. We basically have a couple of * hardware registers that track the sensor count for the X-Y movement and * another register holding the button state. On every VSYNC interrupt we read * the complete state and then work out if something has changed. */ #include <linux/module.h> #include <linux/ptrace.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/input.h> #include <linux/io.h> #include <mach/hardware.h> #include <asm/irq.h> #include <asm/hardware/iomd.h> MODULE_AUTHOR("Vojtech Pavlik, Russell King"); MODULE_DESCRIPTION("Acorn RiscPC mouse driver"); MODULE_LICENSE("GPL"); static short rpcmouse_lastx, rpcmouse_lasty; static struct input_dev *rpcmouse_dev; static irqreturn_t rpcmouse_irq(int irq, void *dev_id) { struct input_dev *dev = dev_id; short x, y, dx, dy, b; x = (short) iomd_readl(IOMD_MOUSEX); y = (short) iomd_readl(IOMD_MOUSEY); b = (short) (__raw_readl(IOMEM(0xe0310000)) ^ 0x70); dx = x - rpcmouse_lastx; dy = y - rpcmouse_lasty; rpcmouse_lastx = x; rpcmouse_lasty = y; input_report_rel(dev, REL_X, dx); input_report_rel(dev, REL_Y, -dy); input_report_key(dev, BTN_LEFT, b & 0x40); input_report_key(dev, BTN_MIDDLE, b & 0x20); input_report_key(dev, BTN_RIGHT, b & 0x10); input_sync(dev); return IRQ_HANDLED; } static int __init rpcmouse_init(void) { int err; rpcmouse_dev = input_allocate_device(); if (!rpcmouse_dev) return -ENOMEM; rpcmouse_dev->name = "Acorn RiscPC Mouse"; rpcmouse_dev->phys = "rpcmouse/input0"; rpcmouse_dev->id.bustype = BUS_HOST; rpcmouse_dev->id.vendor = 0x0005; rpcmouse_dev->id.product = 0x0001; rpcmouse_dev->id.version = 0x0100; rpcmouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); rpcmouse_dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT); rpcmouse_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); rpcmouse_lastx = (short) iomd_readl(IOMD_MOUSEX); rpcmouse_lasty = (short) iomd_readl(IOMD_MOUSEY); if (request_irq(IRQ_VSYNCPULSE, rpcmouse_irq, IRQF_SHARED, "rpcmouse", rpcmouse_dev)) { printk(KERN_ERR "rpcmouse: unable to allocate VSYNC interrupt\n"); err = -EBUSY; goto err_free_dev; } err = input_register_device(rpcmouse_dev); if (err) goto err_free_irq; return 0; err_free_irq: free_irq(IRQ_VSYNCPULSE, rpcmouse_dev); err_free_dev: input_free_device(rpcmouse_dev); return err; } static void __exit rpcmouse_exit(void) { free_irq(IRQ_VSYNCPULSE, rpcmouse_dev); input_unregister_device(rpcmouse_dev); } module_init(rpcmouse_init); module_exit(rpcmouse_exit);
linux-master
drivers/input/mouse/rpcmouse.c
// SPDX-License-Identifier: GPL-2.0-only /* * PS/2 mouse driver * * Copyright (c) 1999-2002 Vojtech Pavlik * Copyright (c) 2003-2004 Dmitry Torokhov */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define psmouse_fmt(fmt) fmt #include <linux/bitops.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/serio.h> #include <linux/init.h> #include <linux/libps2.h> #include <linux/mutex.h> #include <linux/types.h> #include "psmouse.h" #include "synaptics.h" #include "logips2pp.h" #include "alps.h" #include "hgpk.h" #include "lifebook.h" #include "trackpoint.h" #include "touchkit_ps2.h" #include "elantech.h" #include "sentelic.h" #include "cypress_ps2.h" #include "focaltech.h" #include "vmmouse.h" #include "byd.h" #define DRIVER_DESC "PS/2 mouse driver" MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); static unsigned int psmouse_max_proto = PSMOUSE_AUTO; static int psmouse_set_maxproto(const char *val, const struct kernel_param *); static int psmouse_get_maxproto(char *buffer, const struct kernel_param *kp); static const struct kernel_param_ops param_ops_proto_abbrev = { .set = psmouse_set_maxproto, .get = psmouse_get_maxproto, }; #define param_check_proto_abbrev(name, p) __param_check(name, p, unsigned int) module_param_named(proto, psmouse_max_proto, proto_abbrev, 0644); MODULE_PARM_DESC(proto, "Highest protocol extension to probe (bare, imps, exps, any). Useful for KVM switches."); static unsigned int psmouse_resolution = 200; module_param_named(resolution, psmouse_resolution, uint, 0644); MODULE_PARM_DESC(resolution, "Resolution, in dpi."); static unsigned int psmouse_rate = 100; module_param_named(rate, psmouse_rate, uint, 0644); MODULE_PARM_DESC(rate, "Report rate, in reports per second."); static bool psmouse_smartscroll = true; module_param_named(smartscroll, psmouse_smartscroll, bool, 0644); MODULE_PARM_DESC(smartscroll, "Logitech Smartscroll autorepeat, 1 = enabled (default), 0 = disabled."); static bool psmouse_a4tech_2wheels; module_param_named(a4tech_workaround, psmouse_a4tech_2wheels, bool, 0644); MODULE_PARM_DESC(a4tech_workaround, "A4Tech second scroll wheel workaround, 1 = enabled, 0 = disabled (default)."); static unsigned int psmouse_resetafter = 5; module_param_named(resetafter, psmouse_resetafter, uint, 0644); MODULE_PARM_DESC(resetafter, "Reset device after so many bad packets (0 = never)."); static unsigned int psmouse_resync_time; module_param_named(resync_time, psmouse_resync_time, uint, 0644); MODULE_PARM_DESC(resync_time, "How long can mouse stay idle before forcing resync (in seconds, 0 = never)."); PSMOUSE_DEFINE_ATTR(protocol, S_IWUSR | S_IRUGO, NULL, psmouse_attr_show_protocol, psmouse_attr_set_protocol); PSMOUSE_DEFINE_ATTR(rate, S_IWUSR | S_IRUGO, (void *) offsetof(struct psmouse, rate), psmouse_show_int_attr, psmouse_attr_set_rate); PSMOUSE_DEFINE_ATTR(resolution, S_IWUSR | S_IRUGO, (void *) offsetof(struct psmouse, resolution), psmouse_show_int_attr, psmouse_attr_set_resolution); PSMOUSE_DEFINE_ATTR(resetafter, S_IWUSR | S_IRUGO, (void *) offsetof(struct psmouse, resetafter), psmouse_show_int_attr, psmouse_set_int_attr); PSMOUSE_DEFINE_ATTR(resync_time, S_IWUSR | S_IRUGO, (void *) offsetof(struct psmouse, resync_time), psmouse_show_int_attr, psmouse_set_int_attr); static struct attribute *psmouse_dev_attrs[] = { &psmouse_attr_protocol.dattr.attr, &psmouse_attr_rate.dattr.attr, &psmouse_attr_resolution.dattr.attr, &psmouse_attr_resetafter.dattr.attr, &psmouse_attr_resync_time.dattr.attr, NULL }; ATTRIBUTE_GROUPS(psmouse_dev); /* * psmouse_mutex protects all operations changing state of mouse * (connecting, disconnecting, changing rate or resolution via * sysfs). We could use a per-device semaphore but since there * rarely more than one PS/2 mouse connected and since semaphore * is taken in "slow" paths it is not worth it. */ static DEFINE_MUTEX(psmouse_mutex); static struct workqueue_struct *kpsmoused_wq; struct psmouse *psmouse_from_serio(struct serio *serio) { struct ps2dev *ps2dev = serio_get_drvdata(serio); return container_of(ps2dev, struct psmouse, ps2dev); } void psmouse_report_standard_buttons(struct input_dev *dev, u8 buttons) { input_report_key(dev, BTN_LEFT, buttons & BIT(0)); input_report_key(dev, BTN_MIDDLE, buttons & BIT(2)); input_report_key(dev, BTN_RIGHT, buttons & BIT(1)); } void psmouse_report_standard_motion(struct input_dev *dev, u8 *packet) { int x, y; x = packet[1] ? packet[1] - ((packet[0] << 4) & 0x100) : 0; y = packet[2] ? packet[2] - ((packet[0] << 3) & 0x100) : 0; input_report_rel(dev, REL_X, x); input_report_rel(dev, REL_Y, -y); } void psmouse_report_standard_packet(struct input_dev *dev, u8 *packet) { psmouse_report_standard_buttons(dev, packet[0]); psmouse_report_standard_motion(dev, packet); } /* * psmouse_process_byte() analyzes the PS/2 data stream and reports * relevant events to the input module once full packet has arrived. */ psmouse_ret_t psmouse_process_byte(struct psmouse *psmouse) { struct input_dev *dev = psmouse->dev; u8 *packet = psmouse->packet; int wheel; if (psmouse->pktcnt < psmouse->pktsize) return PSMOUSE_GOOD_DATA; /* Full packet accumulated, process it */ switch (psmouse->protocol->type) { case PSMOUSE_IMPS: /* IntelliMouse has scroll wheel */ input_report_rel(dev, REL_WHEEL, -(s8) packet[3]); break; case PSMOUSE_IMEX: /* Scroll wheel and buttons on IntelliMouse Explorer */ switch (packet[3] & 0xC0) { case 0x80: /* vertical scroll on IntelliMouse Explorer 4.0 */ input_report_rel(dev, REL_WHEEL, -sign_extend32(packet[3], 5)); break; case 0x40: /* horizontal scroll on IntelliMouse Explorer 4.0 */ input_report_rel(dev, REL_HWHEEL, -sign_extend32(packet[3], 5)); break; case 0x00: case 0xC0: wheel = sign_extend32(packet[3], 3); /* * Some A4Tech mice have two scroll wheels, with first * one reporting +/-1 in the lower nibble, and second * one reporting +/-2. */ if (psmouse_a4tech_2wheels && abs(wheel) > 1) input_report_rel(dev, REL_HWHEEL, wheel / 2); else input_report_rel(dev, REL_WHEEL, -wheel); input_report_key(dev, BTN_SIDE, packet[3] & BIT(4)); input_report_key(dev, BTN_EXTRA, packet[3] & BIT(5)); break; } break; case PSMOUSE_GENPS: /* Report scroll buttons on NetMice */ input_report_rel(dev, REL_WHEEL, -(s8) packet[3]); /* Extra buttons on Genius NewNet 3D */ input_report_key(dev, BTN_SIDE, packet[0] & BIT(6)); input_report_key(dev, BTN_EXTRA, packet[0] & BIT(7)); break; case PSMOUSE_THINKPS: /* Extra button on ThinkingMouse */ input_report_key(dev, BTN_EXTRA, packet[0] & BIT(3)); /* * Without this bit of weirdness moving up gives wildly * high Y changes. */ packet[1] |= (packet[0] & 0x40) << 1; break; case PSMOUSE_CORTRON: /* * Cortron PS2 Trackball reports SIDE button in the * 4th bit of the first byte. */ input_report_key(dev, BTN_SIDE, packet[0] & BIT(3)); packet[0] |= BIT(3); break; default: break; } /* Generic PS/2 Mouse */ packet[0] |= psmouse->extra_buttons; psmouse_report_standard_packet(dev, packet); input_sync(dev); return PSMOUSE_FULL_PACKET; } void psmouse_queue_work(struct psmouse *psmouse, struct delayed_work *work, unsigned long delay) { queue_delayed_work(kpsmoused_wq, work, delay); } /* * __psmouse_set_state() sets new psmouse state and resets all flags. */ static inline void __psmouse_set_state(struct psmouse *psmouse, enum psmouse_state new_state) { psmouse->state = new_state; psmouse->pktcnt = psmouse->out_of_sync_cnt = 0; psmouse->ps2dev.flags = 0; psmouse->last = jiffies; } /* * psmouse_set_state() sets new psmouse state and resets all flags and * counters while holding serio lock so fighting with interrupt handler * is not a concern. */ void psmouse_set_state(struct psmouse *psmouse, enum psmouse_state new_state) { serio_pause_rx(psmouse->ps2dev.serio); __psmouse_set_state(psmouse, new_state); serio_continue_rx(psmouse->ps2dev.serio); } /* * psmouse_handle_byte() processes one byte of the input data stream * by calling corresponding protocol handler. */ static int psmouse_handle_byte(struct psmouse *psmouse) { psmouse_ret_t rc = psmouse->protocol_handler(psmouse); switch (rc) { case PSMOUSE_BAD_DATA: if (psmouse->state == PSMOUSE_ACTIVATED) { psmouse_warn(psmouse, "%s at %s lost sync at byte %d\n", psmouse->name, psmouse->phys, psmouse->pktcnt); if (++psmouse->out_of_sync_cnt == psmouse->resetafter) { __psmouse_set_state(psmouse, PSMOUSE_IGNORE); psmouse_notice(psmouse, "issuing reconnect request\n"); serio_reconnect(psmouse->ps2dev.serio); return -EIO; } } psmouse->pktcnt = 0; break; case PSMOUSE_FULL_PACKET: psmouse->pktcnt = 0; if (psmouse->out_of_sync_cnt) { psmouse->out_of_sync_cnt = 0; psmouse_notice(psmouse, "%s at %s - driver resynced.\n", psmouse->name, psmouse->phys); } break; case PSMOUSE_GOOD_DATA: break; } return 0; } static void psmouse_handle_oob_data(struct psmouse *psmouse, u8 data) { switch (psmouse->oob_data_type) { case PSMOUSE_OOB_NONE: psmouse->oob_data_type = data; break; case PSMOUSE_OOB_EXTRA_BTNS: psmouse_report_standard_buttons(psmouse->dev, data); input_sync(psmouse->dev); psmouse->extra_buttons = data; psmouse->oob_data_type = PSMOUSE_OOB_NONE; break; default: psmouse_warn(psmouse, "unknown OOB_DATA type: 0x%02x\n", psmouse->oob_data_type); psmouse->oob_data_type = PSMOUSE_OOB_NONE; break; } } static enum ps2_disposition psmouse_pre_receive_byte(struct ps2dev *ps2dev, u8 data, unsigned int flags) { struct psmouse *psmouse = container_of(ps2dev, struct psmouse, ps2dev); if (psmouse->state == PSMOUSE_IGNORE) return PS2_IGNORE; if (unlikely((flags & SERIO_TIMEOUT) || ((flags & SERIO_PARITY) && !psmouse->protocol->ignore_parity))) { if (psmouse->state == PSMOUSE_ACTIVATED) psmouse_warn(psmouse, "bad data from KBC -%s%s\n", flags & SERIO_TIMEOUT ? " timeout" : "", flags & SERIO_PARITY ? " bad parity" : ""); return PS2_ERROR; } if (flags & SERIO_OOB_DATA) { psmouse_handle_oob_data(psmouse, data); return PS2_IGNORE; } return PS2_PROCESS; } static void psmouse_receive_byte(struct ps2dev *ps2dev, u8 data) { struct psmouse *psmouse = container_of(ps2dev, struct psmouse, ps2dev); pm_wakeup_event(&ps2dev->serio->dev, 0); if (psmouse->state <= PSMOUSE_RESYNCING) return; if (psmouse->state == PSMOUSE_ACTIVATED && psmouse->pktcnt && time_after(jiffies, psmouse->last + HZ/2)) { psmouse_info(psmouse, "%s at %s lost synchronization, throwing %d bytes away.\n", psmouse->name, psmouse->phys, psmouse->pktcnt); psmouse->badbyte = psmouse->packet[0]; __psmouse_set_state(psmouse, PSMOUSE_RESYNCING); psmouse_queue_work(psmouse, &psmouse->resync_work, 0); return; } psmouse->packet[psmouse->pktcnt++] = data; /* Check if this is a new device announcement (0xAA 0x00) */ if (unlikely(psmouse->packet[0] == PSMOUSE_RET_BAT && psmouse->pktcnt <= 2)) { if (psmouse->pktcnt == 1) { psmouse->last = jiffies; return; } if (psmouse->packet[1] == PSMOUSE_RET_ID || (psmouse->protocol->type == PSMOUSE_HGPK && psmouse->packet[1] == PSMOUSE_RET_BAT)) { __psmouse_set_state(psmouse, PSMOUSE_IGNORE); serio_reconnect(ps2dev->serio); return; } /* Not a new device, try processing first byte normally */ psmouse->pktcnt = 1; if (psmouse_handle_byte(psmouse)) return; psmouse->packet[psmouse->pktcnt++] = data; } /* * See if we need to force resync because mouse was idle for * too long. */ if (psmouse->state == PSMOUSE_ACTIVATED && psmouse->pktcnt == 1 && psmouse->resync_time && time_after(jiffies, psmouse->last + psmouse->resync_time * HZ)) { psmouse->badbyte = psmouse->packet[0]; __psmouse_set_state(psmouse, PSMOUSE_RESYNCING); psmouse_queue_work(psmouse, &psmouse->resync_work, 0); return; } psmouse->last = jiffies; psmouse_handle_byte(psmouse); } /* * psmouse_reset() resets the mouse into power-on state. */ int psmouse_reset(struct psmouse *psmouse) { u8 param[2]; int error; error = ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_RESET_BAT); if (error) return error; if (param[0] != PSMOUSE_RET_BAT && param[1] != PSMOUSE_RET_ID) return -EIO; return 0; } /* * Here we set the mouse resolution. */ void psmouse_set_resolution(struct psmouse *psmouse, unsigned int resolution) { static const u8 params[] = { 0, 1, 2, 2, 3 }; u8 p; if (resolution == 0 || resolution > 200) resolution = 200; p = params[resolution / 50]; ps2_command(&psmouse->ps2dev, &p, PSMOUSE_CMD_SETRES); psmouse->resolution = 25 << p; } /* * Here we set the mouse report rate. */ static void psmouse_set_rate(struct psmouse *psmouse, unsigned int rate) { static const u8 rates[] = { 200, 100, 80, 60, 40, 20, 10, 0 }; u8 r; int i = 0; while (rates[i] > rate) i++; r = rates[i]; ps2_command(&psmouse->ps2dev, &r, PSMOUSE_CMD_SETRATE); psmouse->rate = r; } /* * Here we set the mouse scaling. */ static void psmouse_set_scale(struct psmouse *psmouse, enum psmouse_scale scale) { ps2_command(&psmouse->ps2dev, NULL, scale == PSMOUSE_SCALE21 ? PSMOUSE_CMD_SETSCALE21 : PSMOUSE_CMD_SETSCALE11); } /* * psmouse_poll() - default poll handler. Everyone except for ALPS uses it. */ static int psmouse_poll(struct psmouse *psmouse) { return ps2_command(&psmouse->ps2dev, psmouse->packet, PSMOUSE_CMD_POLL | (psmouse->pktsize << 8)); } static bool psmouse_check_pnp_id(const char *id, const char * const ids[]) { int i; for (i = 0; ids[i]; i++) if (!strcasecmp(id, ids[i])) return true; return false; } /* * psmouse_matches_pnp_id - check if psmouse matches one of the passed in ids. */ bool psmouse_matches_pnp_id(struct psmouse *psmouse, const char * const ids[]) { struct serio *serio = psmouse->ps2dev.serio; char *p, *fw_id_copy, *save_ptr; bool found = false; if (strncmp(serio->firmware_id, "PNP: ", 5)) return false; fw_id_copy = kstrndup(&serio->firmware_id[5], sizeof(serio->firmware_id) - 5, GFP_KERNEL); if (!fw_id_copy) return false; save_ptr = fw_id_copy; while ((p = strsep(&fw_id_copy, " ")) != NULL) { if (psmouse_check_pnp_id(p, ids)) { found = true; break; } } kfree(save_ptr); return found; } /* * Genius NetMouse magic init. */ static int genius_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[4]; param[0] = 3; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11); ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11); ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11); ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO); if (param[0] != 0x00 || param[1] != 0x33 || param[2] != 0x55) return -ENODEV; if (set_properties) { __set_bit(BTN_MIDDLE, psmouse->dev->keybit); __set_bit(BTN_EXTRA, psmouse->dev->keybit); __set_bit(BTN_SIDE, psmouse->dev->keybit); __set_bit(REL_WHEEL, psmouse->dev->relbit); psmouse->vendor = "Genius"; psmouse->name = "Mouse"; psmouse->pktsize = 4; } return 0; } /* * IntelliMouse magic init. */ static int intellimouse_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[2]; param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 100; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 80; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); ps2_command(ps2dev, param, PSMOUSE_CMD_GETID); if (param[0] != 3) return -ENODEV; if (set_properties) { __set_bit(BTN_MIDDLE, psmouse->dev->keybit); __set_bit(REL_WHEEL, psmouse->dev->relbit); if (!psmouse->vendor) psmouse->vendor = "Generic"; if (!psmouse->name) psmouse->name = "Wheel Mouse"; psmouse->pktsize = 4; } return 0; } /* * Try IntelliMouse/Explorer magic init. */ static int im_explorer_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[2]; intellimouse_detect(psmouse, 0); param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 80; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); ps2_command(ps2dev, param, PSMOUSE_CMD_GETID); if (param[0] != 4) return -ENODEV; /* Magic to enable horizontal scrolling on IntelliMouse 4.0 */ param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 80; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 40; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); if (set_properties) { __set_bit(BTN_MIDDLE, psmouse->dev->keybit); __set_bit(REL_WHEEL, psmouse->dev->relbit); __set_bit(REL_HWHEEL, psmouse->dev->relbit); __set_bit(BTN_SIDE, psmouse->dev->keybit); __set_bit(BTN_EXTRA, psmouse->dev->keybit); if (!psmouse->vendor) psmouse->vendor = "Generic"; if (!psmouse->name) psmouse->name = "Explorer Mouse"; psmouse->pktsize = 4; } return 0; } /* * Kensington ThinkingMouse / ExpertMouse magic init. */ static int thinking_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[2]; static const u8 seq[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 }; int i; param[0] = 10; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 0; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); for (i = 0; i < ARRAY_SIZE(seq); i++) { param[0] = seq[i]; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); } ps2_command(ps2dev, param, PSMOUSE_CMD_GETID); if (param[0] != 2) return -ENODEV; if (set_properties) { __set_bit(BTN_MIDDLE, psmouse->dev->keybit); __set_bit(BTN_EXTRA, psmouse->dev->keybit); psmouse->vendor = "Kensington"; psmouse->name = "ThinkingMouse"; } return 0; } /* * Bare PS/2 protocol "detection". Always succeeds. */ static int ps2bare_detect(struct psmouse *psmouse, bool set_properties) { if (set_properties) { if (!psmouse->vendor) psmouse->vendor = "Generic"; if (!psmouse->name) psmouse->name = "Mouse"; /* * We have no way of figuring true number of buttons so let's * assume that the device has 3. */ input_set_capability(psmouse->dev, EV_KEY, BTN_MIDDLE); } return 0; } /* * Cortron PS/2 protocol detection. There's no special way to detect it, so it * must be forced by sysfs protocol writing. */ static int cortron_detect(struct psmouse *psmouse, bool set_properties) { if (set_properties) { psmouse->vendor = "Cortron"; psmouse->name = "PS/2 Trackball"; __set_bit(BTN_MIDDLE, psmouse->dev->keybit); __set_bit(BTN_SIDE, psmouse->dev->keybit); } return 0; } static const struct psmouse_protocol psmouse_protocols[] = { { .type = PSMOUSE_PS2, .name = "PS/2", .alias = "bare", .maxproto = true, .ignore_parity = true, .detect = ps2bare_detect, .try_passthru = true, }, #ifdef CONFIG_MOUSE_PS2_LOGIPS2PP { .type = PSMOUSE_PS2PP, .name = "PS2++", .alias = "logitech", .detect = ps2pp_detect, }, #endif { .type = PSMOUSE_THINKPS, .name = "ThinkPS/2", .alias = "thinkps", .detect = thinking_detect, }, #ifdef CONFIG_MOUSE_PS2_CYPRESS { .type = PSMOUSE_CYPRESS, .name = "CyPS/2", .alias = "cypress", .detect = cypress_detect, .init = cypress_init, }, #endif { .type = PSMOUSE_GENPS, .name = "GenPS/2", .alias = "genius", .detect = genius_detect, }, { .type = PSMOUSE_IMPS, .name = "ImPS/2", .alias = "imps", .maxproto = true, .ignore_parity = true, .detect = intellimouse_detect, .try_passthru = true, }, { .type = PSMOUSE_IMEX, .name = "ImExPS/2", .alias = "exps", .maxproto = true, .ignore_parity = true, .detect = im_explorer_detect, .try_passthru = true, }, #ifdef CONFIG_MOUSE_PS2_SYNAPTICS { .type = PSMOUSE_SYNAPTICS, .name = "SynPS/2", .alias = "synaptics", .detect = synaptics_detect, .init = synaptics_init_absolute, }, { .type = PSMOUSE_SYNAPTICS_RELATIVE, .name = "SynRelPS/2", .alias = "synaptics-relative", .detect = synaptics_detect, .init = synaptics_init_relative, }, #endif #ifdef CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS { .type = PSMOUSE_SYNAPTICS_SMBUS, .name = "SynSMBus", .alias = "synaptics-smbus", .detect = synaptics_detect, .init = synaptics_init_smbus, .smbus_companion = true, }, #endif #ifdef CONFIG_MOUSE_PS2_ALPS { .type = PSMOUSE_ALPS, .name = "AlpsPS/2", .alias = "alps", .detect = alps_detect, .init = alps_init, }, #endif #ifdef CONFIG_MOUSE_PS2_LIFEBOOK { .type = PSMOUSE_LIFEBOOK, .name = "LBPS/2", .alias = "lifebook", .detect = lifebook_detect, .init = lifebook_init, }, #endif #ifdef CONFIG_MOUSE_PS2_TRACKPOINT { .type = PSMOUSE_TRACKPOINT, .name = "TPPS/2", .alias = "trackpoint", .detect = trackpoint_detect, .try_passthru = true, }, #endif #ifdef CONFIG_MOUSE_PS2_TOUCHKIT { .type = PSMOUSE_TOUCHKIT_PS2, .name = "touchkitPS/2", .alias = "touchkit", .detect = touchkit_ps2_detect, }, #endif #ifdef CONFIG_MOUSE_PS2_OLPC { .type = PSMOUSE_HGPK, .name = "OLPC HGPK", .alias = "hgpk", .detect = hgpk_detect, }, #endif #ifdef CONFIG_MOUSE_PS2_ELANTECH { .type = PSMOUSE_ELANTECH, .name = "ETPS/2", .alias = "elantech", .detect = elantech_detect, .init = elantech_init_ps2, }, #endif #ifdef CONFIG_MOUSE_PS2_ELANTECH_SMBUS { .type = PSMOUSE_ELANTECH_SMBUS, .name = "ETSMBus", .alias = "elantech-smbus", .detect = elantech_detect, .init = elantech_init_smbus, .smbus_companion = true, }, #endif #ifdef CONFIG_MOUSE_PS2_SENTELIC { .type = PSMOUSE_FSP, .name = "FSPPS/2", .alias = "fsp", .detect = fsp_detect, .init = fsp_init, }, #endif { .type = PSMOUSE_CORTRON, .name = "CortronPS/2", .alias = "cortps", .detect = cortron_detect, }, #ifdef CONFIG_MOUSE_PS2_FOCALTECH { .type = PSMOUSE_FOCALTECH, .name = "FocalTechPS/2", .alias = "focaltech", .detect = focaltech_detect, .init = focaltech_init, }, #endif #ifdef CONFIG_MOUSE_PS2_VMMOUSE { .type = PSMOUSE_VMMOUSE, .name = VMMOUSE_PSNAME, .alias = "vmmouse", .detect = vmmouse_detect, .init = vmmouse_init, }, #endif #ifdef CONFIG_MOUSE_PS2_BYD { .type = PSMOUSE_BYD, .name = "BYDPS/2", .alias = "byd", .detect = byd_detect, .init = byd_init, }, #endif { .type = PSMOUSE_AUTO, .name = "auto", .alias = "any", .maxproto = true, }, }; static const struct psmouse_protocol *__psmouse_protocol_by_type(enum psmouse_type type) { int i; for (i = 0; i < ARRAY_SIZE(psmouse_protocols); i++) if (psmouse_protocols[i].type == type) return &psmouse_protocols[i]; return NULL; } static const struct psmouse_protocol *psmouse_protocol_by_type(enum psmouse_type type) { const struct psmouse_protocol *proto; proto = __psmouse_protocol_by_type(type); if (proto) return proto; WARN_ON(1); return &psmouse_protocols[0]; } static const struct psmouse_protocol *psmouse_protocol_by_name(const char *name, size_t len) { const struct psmouse_protocol *p; int i; for (i = 0; i < ARRAY_SIZE(psmouse_protocols); i++) { p = &psmouse_protocols[i]; if ((strlen(p->name) == len && !strncmp(p->name, name, len)) || (strlen(p->alias) == len && !strncmp(p->alias, name, len))) return &psmouse_protocols[i]; } return NULL; } /* * Apply default settings to the psmouse structure. Most of them will * be overridden by individual protocol initialization routines. */ static void psmouse_apply_defaults(struct psmouse *psmouse) { struct input_dev *input_dev = psmouse->dev; bitmap_zero(input_dev->evbit, EV_CNT); bitmap_zero(input_dev->keybit, KEY_CNT); bitmap_zero(input_dev->relbit, REL_CNT); bitmap_zero(input_dev->absbit, ABS_CNT); bitmap_zero(input_dev->mscbit, MSC_CNT); input_set_capability(input_dev, EV_KEY, BTN_LEFT); input_set_capability(input_dev, EV_KEY, BTN_RIGHT); input_set_capability(input_dev, EV_REL, REL_X); input_set_capability(input_dev, EV_REL, REL_Y); __set_bit(INPUT_PROP_POINTER, input_dev->propbit); psmouse->protocol = &psmouse_protocols[0]; psmouse->set_rate = psmouse_set_rate; psmouse->set_resolution = psmouse_set_resolution; psmouse->set_scale = psmouse_set_scale; psmouse->poll = psmouse_poll; psmouse->protocol_handler = psmouse_process_byte; psmouse->pktsize = 3; psmouse->reconnect = NULL; psmouse->fast_reconnect = NULL; psmouse->disconnect = NULL; psmouse->cleanup = NULL; psmouse->pt_activate = NULL; psmouse->pt_deactivate = NULL; } static bool psmouse_do_detect(int (*detect)(struct psmouse *, bool), struct psmouse *psmouse, bool allow_passthrough, bool set_properties) { if (psmouse->ps2dev.serio->id.type == SERIO_PS_PSTHRU && !allow_passthrough) { return false; } if (set_properties) psmouse_apply_defaults(psmouse); return detect(psmouse, set_properties) == 0; } static bool psmouse_try_protocol(struct psmouse *psmouse, enum psmouse_type type, unsigned int *max_proto, bool set_properties, bool init_allowed) { const struct psmouse_protocol *proto; proto = __psmouse_protocol_by_type(type); if (!proto) return false; if (!psmouse_do_detect(proto->detect, psmouse, proto->try_passthru, set_properties)) return false; if (set_properties && proto->init && init_allowed) { if (proto->init(psmouse) != 0) { /* * We detected device, but init failed. Adjust * max_proto so we only try standard protocols. */ if (*max_proto > PSMOUSE_IMEX) *max_proto = PSMOUSE_IMEX; return false; } } return true; } /* * psmouse_extensions() probes for any extensions to the basic PS/2 protocol * the mouse may have. */ static int psmouse_extensions(struct psmouse *psmouse, unsigned int max_proto, bool set_properties) { bool synaptics_hardware = false; int ret; /* * Always check for focaltech, this is safe as it uses pnp-id * matching. */ if (psmouse_do_detect(focaltech_detect, psmouse, false, set_properties)) { if (max_proto > PSMOUSE_IMEX && IS_ENABLED(CONFIG_MOUSE_PS2_FOCALTECH) && (!set_properties || focaltech_init(psmouse) == 0)) { return PSMOUSE_FOCALTECH; } /* * Restrict psmouse_max_proto so that psmouse_initialize() * does not try to reset rate and resolution, because even * that upsets the device. * This also causes us to basically fall through to basic * protocol detection, where we fully reset the mouse, * and set it up as bare PS/2 protocol device. */ psmouse_max_proto = max_proto = PSMOUSE_PS2; } /* * We always check for LifeBook because it does not disturb mouse * (it only checks DMI information). */ if (psmouse_try_protocol(psmouse, PSMOUSE_LIFEBOOK, &max_proto, set_properties, max_proto > PSMOUSE_IMEX)) return PSMOUSE_LIFEBOOK; if (psmouse_try_protocol(psmouse, PSMOUSE_VMMOUSE, &max_proto, set_properties, max_proto > PSMOUSE_IMEX)) return PSMOUSE_VMMOUSE; /* * Try Kensington ThinkingMouse (we try first, because Synaptics * probe upsets the ThinkingMouse). */ if (max_proto > PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_THINKPS, &max_proto, set_properties, true)) { return PSMOUSE_THINKPS; } /* * Try Synaptics TouchPad. Note that probing is done even if * Synaptics protocol support is disabled in config - we need to * know if it is Synaptics so we can reset it properly after * probing for IntelliMouse. */ if (max_proto > PSMOUSE_PS2 && psmouse_do_detect(synaptics_detect, psmouse, false, set_properties)) { synaptics_hardware = true; if (max_proto > PSMOUSE_IMEX) { /* * Try activating protocol, but check if support is * enabled first, since we try detecting Synaptics * even when protocol is disabled. */ if (IS_ENABLED(CONFIG_MOUSE_PS2_SYNAPTICS) || IS_ENABLED(CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS)) { if (!set_properties) return PSMOUSE_SYNAPTICS; ret = synaptics_init(psmouse); if (ret >= 0) return ret; } /* * Some Synaptics touchpads can emulate extended * protocols (like IMPS/2). Unfortunately * Logitech/Genius probes confuse some firmware * versions so we'll have to skip them. */ max_proto = PSMOUSE_IMEX; } /* * Make sure that touchpad is in relative mode, gestures * (taps) are enabled. */ synaptics_reset(psmouse); } /* * Try Cypress Trackpad. We must try it before Finger Sensing Pad * because Finger Sensing Pad probe upsets some modules of Cypress * Trackpads. */ if (max_proto > PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_CYPRESS, &max_proto, set_properties, true)) { return PSMOUSE_CYPRESS; } /* Try ALPS TouchPad */ if (max_proto > PSMOUSE_IMEX) { ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_RESET_DIS); if (psmouse_try_protocol(psmouse, PSMOUSE_ALPS, &max_proto, set_properties, true)) return PSMOUSE_ALPS; } /* Try OLPC HGPK touchpad */ if (max_proto > PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_HGPK, &max_proto, set_properties, true)) { return PSMOUSE_HGPK; } /* Try Elantech touchpad */ if (max_proto > PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_ELANTECH, &max_proto, set_properties, false)) { if (!set_properties) return PSMOUSE_ELANTECH; ret = elantech_init(psmouse); if (ret >= 0) return ret; } if (max_proto > PSMOUSE_IMEX) { if (psmouse_try_protocol(psmouse, PSMOUSE_GENPS, &max_proto, set_properties, true)) return PSMOUSE_GENPS; if (psmouse_try_protocol(psmouse, PSMOUSE_PS2PP, &max_proto, set_properties, true)) return PSMOUSE_PS2PP; if (psmouse_try_protocol(psmouse, PSMOUSE_TRACKPOINT, &max_proto, set_properties, true)) return PSMOUSE_TRACKPOINT; if (psmouse_try_protocol(psmouse, PSMOUSE_TOUCHKIT_PS2, &max_proto, set_properties, true)) return PSMOUSE_TOUCHKIT_PS2; } /* * Try Finger Sensing Pad. We do it here because its probe upsets * Trackpoint devices (causing TP_READ_ID command to time out). */ if (max_proto > PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_FSP, &max_proto, set_properties, true)) { return PSMOUSE_FSP; } /* * Reset to defaults in case the device got confused by extended * protocol probes. Note that we follow up with full reset because * some mice put themselves to sleep when they see PSMOUSE_RESET_DIS. */ ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_RESET_DIS); psmouse_reset(psmouse); if (max_proto >= PSMOUSE_IMEX && psmouse_try_protocol(psmouse, PSMOUSE_IMEX, &max_proto, set_properties, true)) { return PSMOUSE_IMEX; } if (max_proto >= PSMOUSE_IMPS && psmouse_try_protocol(psmouse, PSMOUSE_IMPS, &max_proto, set_properties, true)) { return PSMOUSE_IMPS; } /* * Okay, all failed, we have a standard mouse here. The number of * the buttons is still a question, though. We assume 3. */ psmouse_try_protocol(psmouse, PSMOUSE_PS2, &max_proto, set_properties, true); if (synaptics_hardware) { /* * We detected Synaptics hardware but it did not respond to * IMPS/2 probes. We need to reset the touchpad because if * there is a track point on the pass through port it could * get disabled while probing for protocol extensions. */ psmouse_reset(psmouse); } return PSMOUSE_PS2; } /* * psmouse_probe() probes for a PS/2 mouse. */ static int psmouse_probe(struct psmouse *psmouse) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[2]; int error; /* * First, we check if it's a mouse. It should send 0x00 or 0x03 in * case of an IntelliMouse in 4-byte mode or 0x04 for IM Explorer. * Sunrex K8561 IR Keyboard/Mouse reports 0xff on second and * subsequent ID queries, probably due to a firmware bug. */ param[0] = 0xa5; error = ps2_command(ps2dev, param, PSMOUSE_CMD_GETID); if (error) return error; if (param[0] != 0x00 && param[0] != 0x03 && param[0] != 0x04 && param[0] != 0xff) return -ENODEV; /* * Then we reset and disable the mouse so that it doesn't generate * events. */ error = ps2_command(ps2dev, NULL, PSMOUSE_CMD_RESET_DIS); if (error) psmouse_warn(psmouse, "Failed to reset mouse on %s: %d\n", ps2dev->serio->phys, error); return 0; } /* * psmouse_initialize() initializes the mouse to a sane state. */ static void psmouse_initialize(struct psmouse *psmouse) { /* * We set the mouse report rate, resolution and scaling. */ if (psmouse_max_proto != PSMOUSE_PS2) { psmouse->set_rate(psmouse, psmouse->rate); psmouse->set_resolution(psmouse, psmouse->resolution); psmouse->set_scale(psmouse, PSMOUSE_SCALE11); } } /* * psmouse_activate() enables the mouse so that we get motion reports from it. */ int psmouse_activate(struct psmouse *psmouse) { if (ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_ENABLE)) { psmouse_warn(psmouse, "Failed to enable mouse on %s\n", psmouse->ps2dev.serio->phys); return -1; } psmouse_set_state(psmouse, PSMOUSE_ACTIVATED); return 0; } /* * psmouse_deactivate() puts the mouse into poll mode so that we don't get * motion reports from it unless we explicitly request it. */ int psmouse_deactivate(struct psmouse *psmouse) { int error; error = ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_DISABLE); if (error) { psmouse_warn(psmouse, "Failed to deactivate mouse on %s: %d\n", psmouse->ps2dev.serio->phys, error); return error; } psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); return 0; } /* * psmouse_resync() attempts to re-validate current protocol. */ static void psmouse_resync(struct work_struct *work) { struct psmouse *parent = NULL, *psmouse = container_of(work, struct psmouse, resync_work.work); struct serio *serio = psmouse->ps2dev.serio; psmouse_ret_t rc = PSMOUSE_GOOD_DATA; bool failed = false, enabled = false; int i; mutex_lock(&psmouse_mutex); if (psmouse->state != PSMOUSE_RESYNCING) goto out; if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } /* * Some mice don't ACK commands sent while they are in the middle of * transmitting motion packet. To avoid delay we use ps2_sendbyte() * instead of ps2_command() which would wait for 200ms for an ACK * that may never come. * As an additional quirk ALPS touchpads may not only forget to ACK * disable command but will stop reporting taps, so if we see that * mouse at least once ACKs disable we will do full reconnect if ACK * is missing. */ psmouse->num_resyncs++; if (ps2_sendbyte(&psmouse->ps2dev, PSMOUSE_CMD_DISABLE, 20)) { if (psmouse->num_resyncs < 3 || psmouse->acks_disable_command) failed = true; } else psmouse->acks_disable_command = true; /* * Poll the mouse. If it was reset the packet will be shorter than * psmouse->pktsize and ps2_command will fail. We do not expect and * do not handle scenario when mouse "upgrades" its protocol while * disconnected since it would require additional delay. If we ever * see a mouse that does it we'll adjust the code. */ if (!failed) { if (psmouse->poll(psmouse)) failed = true; else { psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); for (i = 0; i < psmouse->pktsize; i++) { psmouse->pktcnt++; rc = psmouse->protocol_handler(psmouse); if (rc != PSMOUSE_GOOD_DATA) break; } if (rc != PSMOUSE_FULL_PACKET) failed = true; psmouse_set_state(psmouse, PSMOUSE_RESYNCING); } } /* * Now try to enable mouse. We try to do that even if poll failed * and also repeat our attempts 5 times, otherwise we may be left * out with disabled mouse. */ for (i = 0; i < 5; i++) { if (!ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_ENABLE)) { enabled = true; break; } msleep(200); } if (!enabled) { psmouse_warn(psmouse, "failed to re-enable mouse on %s\n", psmouse->ps2dev.serio->phys); failed = true; } if (failed) { psmouse_set_state(psmouse, PSMOUSE_IGNORE); psmouse_info(psmouse, "resync failed, issuing reconnect request\n"); serio_reconnect(serio); } else psmouse_set_state(psmouse, PSMOUSE_ACTIVATED); if (parent) psmouse_activate(parent); out: mutex_unlock(&psmouse_mutex); } /* * psmouse_cleanup() resets the mouse into power-on state. */ static void psmouse_cleanup(struct serio *serio) { struct psmouse *psmouse = psmouse_from_serio(serio); struct psmouse *parent = NULL; mutex_lock(&psmouse_mutex); if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } psmouse_set_state(psmouse, PSMOUSE_INITIALIZING); /* * Disable stream mode so cleanup routine can proceed undisturbed. */ if (ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_DISABLE)) psmouse_warn(psmouse, "Failed to disable mouse on %s\n", psmouse->ps2dev.serio->phys); if (psmouse->cleanup) psmouse->cleanup(psmouse); /* * Reset the mouse to defaults (bare PS/2 protocol). */ ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_RESET_DIS); /* * Some boxes, such as HP nx7400, get terribly confused if mouse * is not fully enabled before suspending/shutting down. */ ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_ENABLE); if (parent) { if (parent->pt_deactivate) parent->pt_deactivate(parent); psmouse_activate(parent); } mutex_unlock(&psmouse_mutex); } /* * psmouse_disconnect() closes and frees. */ static void psmouse_disconnect(struct serio *serio) { struct psmouse *psmouse = psmouse_from_serio(serio); struct psmouse *parent = NULL; mutex_lock(&psmouse_mutex); psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); /* make sure we don't have a resync in progress */ mutex_unlock(&psmouse_mutex); flush_workqueue(kpsmoused_wq); mutex_lock(&psmouse_mutex); if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } if (psmouse->disconnect) psmouse->disconnect(psmouse); if (parent && parent->pt_deactivate) parent->pt_deactivate(parent); psmouse_set_state(psmouse, PSMOUSE_IGNORE); serio_close(serio); serio_set_drvdata(serio, NULL); if (psmouse->dev) input_unregister_device(psmouse->dev); kfree(psmouse); if (parent) psmouse_activate(parent); mutex_unlock(&psmouse_mutex); } static int psmouse_switch_protocol(struct psmouse *psmouse, const struct psmouse_protocol *proto) { const struct psmouse_protocol *selected_proto; struct input_dev *input_dev = psmouse->dev; enum psmouse_type type; input_dev->dev.parent = &psmouse->ps2dev.serio->dev; if (proto && (proto->detect || proto->init)) { psmouse_apply_defaults(psmouse); if (proto->detect && proto->detect(psmouse, true) < 0) return -1; if (proto->init && proto->init(psmouse) < 0) return -1; selected_proto = proto; } else { type = psmouse_extensions(psmouse, psmouse_max_proto, true); selected_proto = psmouse_protocol_by_type(type); } psmouse->protocol = selected_proto; /* * If mouse's packet size is 3 there is no point in polling the * device in hopes to detect protocol reset - we won't get less * than 3 bytes response anyhow. */ if (psmouse->pktsize == 3) psmouse->resync_time = 0; /* * Some smart KVMs fake response to POLL command returning just * 3 bytes and messing up our resync logic, so if initial poll * fails we won't try polling the device anymore. Hopefully * such KVM will maintain initially selected protocol. */ if (psmouse->resync_time && psmouse->poll(psmouse)) psmouse->resync_time = 0; snprintf(psmouse->devname, sizeof(psmouse->devname), "%s %s %s", selected_proto->name, psmouse->vendor, psmouse->name); input_dev->name = psmouse->devname; input_dev->phys = psmouse->phys; input_dev->id.bustype = BUS_I8042; input_dev->id.vendor = 0x0002; input_dev->id.product = psmouse->protocol->type; input_dev->id.version = psmouse->model; return 0; } /* * psmouse_connect() is a callback from the serio module when * an unhandled serio port is found. */ static int psmouse_connect(struct serio *serio, struct serio_driver *drv) { struct psmouse *psmouse, *parent = NULL; struct input_dev *input_dev; int retval = 0, error = -ENOMEM; mutex_lock(&psmouse_mutex); /* * If this is a pass-through port deactivate parent so the device * connected to this port can be successfully identified */ if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } psmouse = kzalloc(sizeof(struct psmouse), GFP_KERNEL); input_dev = input_allocate_device(); if (!psmouse || !input_dev) goto err_free; ps2_init(&psmouse->ps2dev, serio, psmouse_pre_receive_byte, psmouse_receive_byte); INIT_DELAYED_WORK(&psmouse->resync_work, psmouse_resync); psmouse->dev = input_dev; snprintf(psmouse->phys, sizeof(psmouse->phys), "%s/input0", serio->phys); psmouse_set_state(psmouse, PSMOUSE_INITIALIZING); error = serio_open(serio, drv); if (error) goto err_clear_drvdata; /* give PT device some time to settle down before probing */ if (serio->id.type == SERIO_PS_PSTHRU) usleep_range(10000, 15000); if (psmouse_probe(psmouse) < 0) { error = -ENODEV; goto err_close_serio; } psmouse->rate = psmouse_rate; psmouse->resolution = psmouse_resolution; psmouse->resetafter = psmouse_resetafter; psmouse->resync_time = parent ? 0 : psmouse_resync_time; psmouse->smartscroll = psmouse_smartscroll; psmouse_switch_protocol(psmouse, NULL); if (!psmouse->protocol->smbus_companion) { psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); psmouse_initialize(psmouse); error = input_register_device(input_dev); if (error) goto err_protocol_disconnect; } else { /* Smbus companion will be reporting events, not us. */ input_free_device(input_dev); psmouse->dev = input_dev = NULL; } if (parent && parent->pt_activate) parent->pt_activate(parent); /* * PS/2 devices having SMBus companions should stay disabled * on PS/2 side, in order to have SMBus part operable. */ if (!psmouse->protocol->smbus_companion) psmouse_activate(psmouse); out: /* If this is a pass-through port the parent needs to be re-activated */ if (parent) psmouse_activate(parent); mutex_unlock(&psmouse_mutex); return retval; err_protocol_disconnect: if (psmouse->disconnect) psmouse->disconnect(psmouse); psmouse_set_state(psmouse, PSMOUSE_IGNORE); err_close_serio: serio_close(serio); err_clear_drvdata: serio_set_drvdata(serio, NULL); err_free: input_free_device(input_dev); kfree(psmouse); retval = error; goto out; } static int __psmouse_reconnect(struct serio *serio, bool fast_reconnect) { struct psmouse *psmouse = psmouse_from_serio(serio); struct psmouse *parent = NULL; int (*reconnect_handler)(struct psmouse *); enum psmouse_type type; int rc = -1; mutex_lock(&psmouse_mutex); if (fast_reconnect) { reconnect_handler = psmouse->fast_reconnect; if (!reconnect_handler) { rc = -ENOENT; goto out_unlock; } } else { reconnect_handler = psmouse->reconnect; } if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } psmouse_set_state(psmouse, PSMOUSE_INITIALIZING); if (reconnect_handler) { if (reconnect_handler(psmouse)) goto out; } else { psmouse_reset(psmouse); if (psmouse_probe(psmouse) < 0) goto out; type = psmouse_extensions(psmouse, psmouse_max_proto, false); if (psmouse->protocol->type != type) goto out; } /* * OK, the device type (and capabilities) match the old one, * we can continue using it, complete initialization */ if (!psmouse->protocol->smbus_companion) { psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); psmouse_initialize(psmouse); } if (parent && parent->pt_activate) parent->pt_activate(parent); /* * PS/2 devices having SMBus companions should stay disabled * on PS/2 side, in order to have SMBus part operable. */ if (!psmouse->protocol->smbus_companion) psmouse_activate(psmouse); rc = 0; out: /* If this is a pass-through port the parent waits to be activated */ if (parent) psmouse_activate(parent); out_unlock: mutex_unlock(&psmouse_mutex); return rc; } static int psmouse_reconnect(struct serio *serio) { return __psmouse_reconnect(serio, false); } static int psmouse_fast_reconnect(struct serio *serio) { return __psmouse_reconnect(serio, true); } static struct serio_device_id psmouse_serio_ids[] = { { .type = SERIO_8042, .proto = SERIO_ANY, .id = SERIO_ANY, .extra = SERIO_ANY, }, { .type = SERIO_PS_PSTHRU, .proto = SERIO_ANY, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, psmouse_serio_ids); static struct serio_driver psmouse_drv = { .driver = { .name = "psmouse", .dev_groups = psmouse_dev_groups, }, .description = DRIVER_DESC, .id_table = psmouse_serio_ids, .interrupt = ps2_interrupt, .connect = psmouse_connect, .reconnect = psmouse_reconnect, .fast_reconnect = psmouse_fast_reconnect, .disconnect = psmouse_disconnect, .cleanup = psmouse_cleanup, }; ssize_t psmouse_attr_show_helper(struct device *dev, struct device_attribute *devattr, char *buf) { struct serio *serio = to_serio_port(dev); struct psmouse_attribute *attr = to_psmouse_attr(devattr); struct psmouse *psmouse = psmouse_from_serio(serio); if (psmouse->protocol->smbus_companion && devattr != &psmouse_attr_protocol.dattr) return -ENOENT; return attr->show(psmouse, attr->data, buf); } ssize_t psmouse_attr_set_helper(struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { struct serio *serio = to_serio_port(dev); struct psmouse_attribute *attr = to_psmouse_attr(devattr); struct psmouse *psmouse, *parent = NULL; int retval; retval = mutex_lock_interruptible(&psmouse_mutex); if (retval) goto out; psmouse = psmouse_from_serio(serio); if (psmouse->protocol->smbus_companion && devattr != &psmouse_attr_protocol.dattr) { retval = -ENOENT; goto out_unlock; } if (attr->protect) { if (psmouse->state == PSMOUSE_IGNORE) { retval = -ENODEV; goto out_unlock; } if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); psmouse_deactivate(parent); } if (!psmouse->protocol->smbus_companion) psmouse_deactivate(psmouse); } retval = attr->set(psmouse, attr->data, buf, count); if (attr->protect) { if (retval != -ENODEV && !psmouse->protocol->smbus_companion) psmouse_activate(psmouse); if (parent) psmouse_activate(parent); } out_unlock: mutex_unlock(&psmouse_mutex); out: return retval; } static ssize_t psmouse_show_int_attr(struct psmouse *psmouse, void *offset, char *buf) { unsigned int *field = (unsigned int *)((char *)psmouse + (size_t)offset); return sprintf(buf, "%u\n", *field); } static ssize_t psmouse_set_int_attr(struct psmouse *psmouse, void *offset, const char *buf, size_t count) { unsigned int *field = (unsigned int *)((char *)psmouse + (size_t)offset); unsigned int value; int err; err = kstrtouint(buf, 10, &value); if (err) return err; *field = value; return count; } static ssize_t psmouse_attr_show_protocol(struct psmouse *psmouse, void *data, char *buf) { return sprintf(buf, "%s\n", psmouse->protocol->name); } static ssize_t psmouse_attr_set_protocol(struct psmouse *psmouse, void *data, const char *buf, size_t count) { struct serio *serio = psmouse->ps2dev.serio; struct psmouse *parent = NULL; struct input_dev *old_dev, *new_dev; const struct psmouse_protocol *proto, *old_proto; int error; int retry = 0; proto = psmouse_protocol_by_name(buf, count); if (!proto) return -EINVAL; if (psmouse->protocol == proto) return count; new_dev = input_allocate_device(); if (!new_dev) return -ENOMEM; while (!list_empty(&serio->children)) { if (++retry > 3) { psmouse_warn(psmouse, "failed to destroy children ports, protocol change aborted.\n"); input_free_device(new_dev); return -EIO; } mutex_unlock(&psmouse_mutex); serio_unregister_child_port(serio); mutex_lock(&psmouse_mutex); if (serio->drv != &psmouse_drv) { input_free_device(new_dev); return -ENODEV; } if (psmouse->protocol == proto) { input_free_device(new_dev); return count; /* switched by other thread */ } } if (serio->parent && serio->id.type == SERIO_PS_PSTHRU) { parent = psmouse_from_serio(serio->parent); if (parent->pt_deactivate) parent->pt_deactivate(parent); } old_dev = psmouse->dev; old_proto = psmouse->protocol; if (psmouse->disconnect) psmouse->disconnect(psmouse); psmouse_set_state(psmouse, PSMOUSE_IGNORE); psmouse->dev = new_dev; psmouse_set_state(psmouse, PSMOUSE_INITIALIZING); if (psmouse_switch_protocol(psmouse, proto) < 0) { psmouse_reset(psmouse); /* default to PSMOUSE_PS2 */ psmouse_switch_protocol(psmouse, &psmouse_protocols[0]); } psmouse_initialize(psmouse); psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); if (psmouse->protocol->smbus_companion) { input_free_device(psmouse->dev); psmouse->dev = NULL; } else { error = input_register_device(psmouse->dev); if (error) { if (psmouse->disconnect) psmouse->disconnect(psmouse); psmouse_set_state(psmouse, PSMOUSE_IGNORE); input_free_device(new_dev); psmouse->dev = old_dev; psmouse_set_state(psmouse, PSMOUSE_INITIALIZING); psmouse_switch_protocol(psmouse, old_proto); psmouse_initialize(psmouse); psmouse_set_state(psmouse, PSMOUSE_CMD_MODE); return error; } } if (old_dev) input_unregister_device(old_dev); if (parent && parent->pt_activate) parent->pt_activate(parent); return count; } static ssize_t psmouse_attr_set_rate(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int value; int err; err = kstrtouint(buf, 10, &value); if (err) return err; psmouse->set_rate(psmouse, value); return count; } static ssize_t psmouse_attr_set_resolution(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int value; int err; err = kstrtouint(buf, 10, &value); if (err) return err; psmouse->set_resolution(psmouse, value); return count; } static int psmouse_set_maxproto(const char *val, const struct kernel_param *kp) { const struct psmouse_protocol *proto; if (!val) return -EINVAL; proto = psmouse_protocol_by_name(val, strlen(val)); if (!proto || !proto->maxproto) return -EINVAL; *((unsigned int *)kp->arg) = proto->type; return 0; } static int psmouse_get_maxproto(char *buffer, const struct kernel_param *kp) { int type = *((unsigned int *)kp->arg); return sprintf(buffer, "%s\n", psmouse_protocol_by_type(type)->name); } static int __init psmouse_init(void) { int err; lifebook_module_init(); synaptics_module_init(); hgpk_module_init(); err = psmouse_smbus_module_init(); if (err) return err; kpsmoused_wq = alloc_ordered_workqueue("kpsmoused", 0); if (!kpsmoused_wq) { pr_err("failed to create kpsmoused workqueue\n"); err = -ENOMEM; goto err_smbus_exit; } err = serio_register_driver(&psmouse_drv); if (err) goto err_destroy_wq; return 0; err_destroy_wq: destroy_workqueue(kpsmoused_wq); err_smbus_exit: psmouse_smbus_module_exit(); return err; } static void __exit psmouse_exit(void) { serio_unregister_driver(&psmouse_drv); destroy_workqueue(kpsmoused_wq); psmouse_smbus_module_exit(); } module_init(psmouse_init); module_exit(psmouse_exit);
linux-master
drivers/input/mouse/psmouse-base.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 1999-2001 Vojtech Pavlik * * Based on the work of: * Teemu Rantanen Derrick Cole * Peter Cervasio Christoph Niemann * Philip Blundell Russell King * Bob Harris */ /* * Inport (ATI XL and Microsoft) busmouse driver for Linux */ #include <linux/module.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/input.h> #include <asm/io.h> #include <asm/irq.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Inport (ATI XL and Microsoft) busmouse driver"); MODULE_LICENSE("GPL"); #define INPORT_BASE 0x23c #define INPORT_EXTENT 4 #define INPORT_CONTROL_PORT INPORT_BASE + 0 #define INPORT_DATA_PORT INPORT_BASE + 1 #define INPORT_SIGNATURE_PORT INPORT_BASE + 2 #define INPORT_REG_BTNS 0x00 #define INPORT_REG_X 0x01 #define INPORT_REG_Y 0x02 #define INPORT_REG_MODE 0x07 #define INPORT_RESET 0x80 #ifdef CONFIG_MOUSE_ATIXL #define INPORT_NAME "ATI XL Mouse" #define INPORT_VENDOR 0x0002 #define INPORT_SPEED_30HZ 0x01 #define INPORT_SPEED_50HZ 0x02 #define INPORT_SPEED_100HZ 0x03 #define INPORT_SPEED_200HZ 0x04 #define INPORT_MODE_BASE INPORT_SPEED_100HZ #define INPORT_MODE_IRQ 0x08 #else #define INPORT_NAME "Microsoft InPort Mouse" #define INPORT_VENDOR 0x0001 #define INPORT_MODE_BASE 0x10 #define INPORT_MODE_IRQ 0x01 #endif #define INPORT_MODE_HOLD 0x20 #define INPORT_IRQ 5 static int inport_irq = INPORT_IRQ; module_param_hw_named(irq, inport_irq, uint, irq, 0); MODULE_PARM_DESC(irq, "IRQ number (5=default)"); static struct input_dev *inport_dev; static irqreturn_t inport_interrupt(int irq, void *dev_id) { unsigned char buttons; outb(INPORT_REG_MODE, INPORT_CONTROL_PORT); outb(INPORT_MODE_HOLD | INPORT_MODE_IRQ | INPORT_MODE_BASE, INPORT_DATA_PORT); outb(INPORT_REG_X, INPORT_CONTROL_PORT); input_report_rel(inport_dev, REL_X, inb(INPORT_DATA_PORT)); outb(INPORT_REG_Y, INPORT_CONTROL_PORT); input_report_rel(inport_dev, REL_Y, inb(INPORT_DATA_PORT)); outb(INPORT_REG_BTNS, INPORT_CONTROL_PORT); buttons = inb(INPORT_DATA_PORT); input_report_key(inport_dev, BTN_MIDDLE, buttons & 1); input_report_key(inport_dev, BTN_LEFT, buttons & 2); input_report_key(inport_dev, BTN_RIGHT, buttons & 4); outb(INPORT_REG_MODE, INPORT_CONTROL_PORT); outb(INPORT_MODE_IRQ | INPORT_MODE_BASE, INPORT_DATA_PORT); input_sync(inport_dev); return IRQ_HANDLED; } static int inport_open(struct input_dev *dev) { if (request_irq(inport_irq, inport_interrupt, 0, "inport", NULL)) return -EBUSY; outb(INPORT_REG_MODE, INPORT_CONTROL_PORT); outb(INPORT_MODE_IRQ | INPORT_MODE_BASE, INPORT_DATA_PORT); return 0; } static void inport_close(struct input_dev *dev) { outb(INPORT_REG_MODE, INPORT_CONTROL_PORT); outb(INPORT_MODE_BASE, INPORT_DATA_PORT); free_irq(inport_irq, NULL); } static int __init inport_init(void) { unsigned char a, b, c; int err; if (!request_region(INPORT_BASE, INPORT_EXTENT, "inport")) { printk(KERN_ERR "inport.c: Can't allocate ports at %#x\n", INPORT_BASE); return -EBUSY; } a = inb(INPORT_SIGNATURE_PORT); b = inb(INPORT_SIGNATURE_PORT); c = inb(INPORT_SIGNATURE_PORT); if (a == b || a != c) { printk(KERN_INFO "inport.c: Didn't find InPort mouse at %#x\n", INPORT_BASE); err = -ENODEV; goto err_release_region; } inport_dev = input_allocate_device(); if (!inport_dev) { printk(KERN_ERR "inport.c: Not enough memory for input device\n"); err = -ENOMEM; goto err_release_region; } inport_dev->name = INPORT_NAME; inport_dev->phys = "isa023c/input0"; inport_dev->id.bustype = BUS_ISA; inport_dev->id.vendor = INPORT_VENDOR; inport_dev->id.product = 0x0001; inport_dev->id.version = 0x0100; inport_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); inport_dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT); inport_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); inport_dev->open = inport_open; inport_dev->close = inport_close; outb(INPORT_RESET, INPORT_CONTROL_PORT); outb(INPORT_REG_MODE, INPORT_CONTROL_PORT); outb(INPORT_MODE_BASE, INPORT_DATA_PORT); err = input_register_device(inport_dev); if (err) goto err_free_dev; return 0; err_free_dev: input_free_device(inport_dev); err_release_region: release_region(INPORT_BASE, INPORT_EXTENT); return err; } static void __exit inport_exit(void) { input_unregister_device(inport_dev); release_region(INPORT_BASE, INPORT_EXTENT); } module_init(inport_init); module_exit(inport_exit);
linux-master
drivers/input/mouse/inport.c
/* * Cypress APA trackpad with I2C interface * * Author: Dudley Du <[email protected]> * Further cleanup and restructuring by: * Daniel Kurtz <[email protected]> * Benson Leung <[email protected]> * * Copyright (C) 2011-2015 Cypress Semiconductor, Inc. * Copyright (C) 2011-2012 Google, Inc. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/module.h> #include <linux/slab.h> #include <asm/unaligned.h> #include "cyapa.h" #define GEN3_MAX_FINGERS 5 #define GEN3_FINGER_NUM(x) (((x) >> 4) & 0x07) #define BLK_HEAD_BYTES 32 /* Macro for register map group offset. */ #define PRODUCT_ID_SIZE 16 #define QUERY_DATA_SIZE 27 #define REG_PROTOCOL_GEN_QUERY_OFFSET 20 #define REG_OFFSET_DATA_BASE 0x0000 #define REG_OFFSET_COMMAND_BASE 0x0028 #define REG_OFFSET_QUERY_BASE 0x002a #define CYAPA_OFFSET_SOFT_RESET REG_OFFSET_COMMAND_BASE #define OP_RECALIBRATION_MASK 0x80 #define OP_REPORT_BASELINE_MASK 0x40 #define REG_OFFSET_MAX_BASELINE 0x0026 #define REG_OFFSET_MIN_BASELINE 0x0027 #define REG_OFFSET_POWER_MODE (REG_OFFSET_COMMAND_BASE + 1) #define SET_POWER_MODE_DELAY 10000 /* Unit: us */ #define SET_POWER_MODE_TRIES 5 #define GEN3_BL_CMD_CHECKSUM_SEED 0xff #define GEN3_BL_CMD_INITIATE_BL 0x38 #define GEN3_BL_CMD_WRITE_BLOCK 0x39 #define GEN3_BL_CMD_VERIFY_BLOCK 0x3a #define GEN3_BL_CMD_TERMINATE_BL 0x3b #define GEN3_BL_CMD_LAUNCH_APP 0xa5 /* * CYAPA trackpad device states. * Used in register 0x00, bit1-0, DeviceStatus field. * Other values indicate device is in an abnormal state and must be reset. */ #define CYAPA_DEV_NORMAL 0x03 #define CYAPA_DEV_BUSY 0x01 #define CYAPA_FW_BLOCK_SIZE 64 #define CYAPA_FW_READ_SIZE 16 #define CYAPA_FW_HDR_START 0x0780 #define CYAPA_FW_HDR_BLOCK_COUNT 2 #define CYAPA_FW_HDR_BLOCK_START (CYAPA_FW_HDR_START / CYAPA_FW_BLOCK_SIZE) #define CYAPA_FW_HDR_SIZE (CYAPA_FW_HDR_BLOCK_COUNT * \ CYAPA_FW_BLOCK_SIZE) #define CYAPA_FW_DATA_START 0x0800 #define CYAPA_FW_DATA_BLOCK_COUNT 480 #define CYAPA_FW_DATA_BLOCK_START (CYAPA_FW_DATA_START / CYAPA_FW_BLOCK_SIZE) #define CYAPA_FW_DATA_SIZE (CYAPA_FW_DATA_BLOCK_COUNT * \ CYAPA_FW_BLOCK_SIZE) #define CYAPA_FW_SIZE (CYAPA_FW_HDR_SIZE + CYAPA_FW_DATA_SIZE) #define CYAPA_CMD_LEN 16 #define GEN3_BL_IDLE_FW_MAJ_VER_OFFSET 0x0b #define GEN3_BL_IDLE_FW_MIN_VER_OFFSET (GEN3_BL_IDLE_FW_MAJ_VER_OFFSET + 1) struct cyapa_touch { /* * high bits or x/y position value * bit 7 - 4: high 4 bits of x position value * bit 3 - 0: high 4 bits of y position value */ u8 xy_hi; u8 x_lo; /* low 8 bits of x position value. */ u8 y_lo; /* low 8 bits of y position value. */ u8 pressure; /* id range is 1 - 15. It is incremented with every new touch. */ u8 id; } __packed; struct cyapa_reg_data { /* * bit 0 - 1: device status * bit 3 - 2: power mode * bit 6 - 4: reserved * bit 7: interrupt valid bit */ u8 device_status; /* * bit 7 - 4: number of fingers currently touching pad * bit 3: valid data check bit * bit 2: middle mechanism button state if exists * bit 1: right mechanism button state if exists * bit 0: left mechanism button state if exists */ u8 finger_btn; /* CYAPA reports up to 5 touches per packet. */ struct cyapa_touch touches[5]; } __packed; struct gen3_write_block_cmd { u8 checksum_seed; /* Always be 0xff */ u8 cmd_code; /* command code: 0x39 */ u8 key[8]; /* 8-byte security key */ __be16 block_num; u8 block_data[CYAPA_FW_BLOCK_SIZE]; u8 block_checksum; /* Calculated using bytes 12 - 75 */ u8 cmd_checksum; /* Calculated using bytes 0-76 */ } __packed; static const u8 security_key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; static const u8 bl_activate[] = { 0x00, 0xff, 0x38, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; static const u8 bl_deactivate[] = { 0x00, 0xff, 0x3b, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; static const u8 bl_exit[] = { 0x00, 0xff, 0xa5, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; /* for byte read/write command */ #define CMD_RESET 0 #define CMD_POWER_MODE 1 #define CMD_DEV_STATUS 2 #define CMD_REPORT_MAX_BASELINE 3 #define CMD_REPORT_MIN_BASELINE 4 #define SMBUS_BYTE_CMD(cmd) (((cmd) & 0x3f) << 1) #define CYAPA_SMBUS_RESET SMBUS_BYTE_CMD(CMD_RESET) #define CYAPA_SMBUS_POWER_MODE SMBUS_BYTE_CMD(CMD_POWER_MODE) #define CYAPA_SMBUS_DEV_STATUS SMBUS_BYTE_CMD(CMD_DEV_STATUS) #define CYAPA_SMBUS_MAX_BASELINE SMBUS_BYTE_CMD(CMD_REPORT_MAX_BASELINE) #define CYAPA_SMBUS_MIN_BASELINE SMBUS_BYTE_CMD(CMD_REPORT_MIN_BASELINE) /* for group registers read/write command */ #define REG_GROUP_DATA 0 #define REG_GROUP_CMD 2 #define REG_GROUP_QUERY 3 #define SMBUS_GROUP_CMD(grp) (0x80 | (((grp) & 0x07) << 3)) #define CYAPA_SMBUS_GROUP_DATA SMBUS_GROUP_CMD(REG_GROUP_DATA) #define CYAPA_SMBUS_GROUP_CMD SMBUS_GROUP_CMD(REG_GROUP_CMD) #define CYAPA_SMBUS_GROUP_QUERY SMBUS_GROUP_CMD(REG_GROUP_QUERY) /* for register block read/write command */ #define CMD_BL_STATUS 0 #define CMD_BL_HEAD 1 #define CMD_BL_CMD 2 #define CMD_BL_DATA 3 #define CMD_BL_ALL 4 #define CMD_BLK_PRODUCT_ID 5 #define CMD_BLK_HEAD 6 #define SMBUS_BLOCK_CMD(cmd) (0xc0 | (((cmd) & 0x1f) << 1)) /* register block read/write command in bootloader mode */ #define CYAPA_SMBUS_BL_STATUS SMBUS_BLOCK_CMD(CMD_BL_STATUS) #define CYAPA_SMBUS_BL_HEAD SMBUS_BLOCK_CMD(CMD_BL_HEAD) #define CYAPA_SMBUS_BL_CMD SMBUS_BLOCK_CMD(CMD_BL_CMD) #define CYAPA_SMBUS_BL_DATA SMBUS_BLOCK_CMD(CMD_BL_DATA) #define CYAPA_SMBUS_BL_ALL SMBUS_BLOCK_CMD(CMD_BL_ALL) /* register block read/write command in operational mode */ #define CYAPA_SMBUS_BLK_PRODUCT_ID SMBUS_BLOCK_CMD(CMD_BLK_PRODUCT_ID) #define CYAPA_SMBUS_BLK_HEAD SMBUS_BLOCK_CMD(CMD_BLK_HEAD) struct cyapa_cmd_len { u8 cmd; u8 len; }; /* maps generic CYAPA_CMD_* code to the I2C equivalent */ static const struct cyapa_cmd_len cyapa_i2c_cmds[] = { { CYAPA_OFFSET_SOFT_RESET, 1 }, /* CYAPA_CMD_SOFT_RESET */ { REG_OFFSET_COMMAND_BASE + 1, 1 }, /* CYAPA_CMD_POWER_MODE */ { REG_OFFSET_DATA_BASE, 1 }, /* CYAPA_CMD_DEV_STATUS */ { REG_OFFSET_DATA_BASE, sizeof(struct cyapa_reg_data) }, /* CYAPA_CMD_GROUP_DATA */ { REG_OFFSET_COMMAND_BASE, 0 }, /* CYAPA_CMD_GROUP_CMD */ { REG_OFFSET_QUERY_BASE, QUERY_DATA_SIZE }, /* CYAPA_CMD_GROUP_QUERY */ { BL_HEAD_OFFSET, 3 }, /* CYAPA_CMD_BL_STATUS */ { BL_HEAD_OFFSET, 16 }, /* CYAPA_CMD_BL_HEAD */ { BL_HEAD_OFFSET, 16 }, /* CYAPA_CMD_BL_CMD */ { BL_DATA_OFFSET, 16 }, /* CYAPA_CMD_BL_DATA */ { BL_HEAD_OFFSET, 32 }, /* CYAPA_CMD_BL_ALL */ { REG_OFFSET_QUERY_BASE, PRODUCT_ID_SIZE }, /* CYAPA_CMD_BLK_PRODUCT_ID */ { REG_OFFSET_DATA_BASE, 32 }, /* CYAPA_CMD_BLK_HEAD */ { REG_OFFSET_MAX_BASELINE, 1 }, /* CYAPA_CMD_MAX_BASELINE */ { REG_OFFSET_MIN_BASELINE, 1 }, /* CYAPA_CMD_MIN_BASELINE */ }; static const struct cyapa_cmd_len cyapa_smbus_cmds[] = { { CYAPA_SMBUS_RESET, 1 }, /* CYAPA_CMD_SOFT_RESET */ { CYAPA_SMBUS_POWER_MODE, 1 }, /* CYAPA_CMD_POWER_MODE */ { CYAPA_SMBUS_DEV_STATUS, 1 }, /* CYAPA_CMD_DEV_STATUS */ { CYAPA_SMBUS_GROUP_DATA, sizeof(struct cyapa_reg_data) }, /* CYAPA_CMD_GROUP_DATA */ { CYAPA_SMBUS_GROUP_CMD, 2 }, /* CYAPA_CMD_GROUP_CMD */ { CYAPA_SMBUS_GROUP_QUERY, QUERY_DATA_SIZE }, /* CYAPA_CMD_GROUP_QUERY */ { CYAPA_SMBUS_BL_STATUS, 3 }, /* CYAPA_CMD_BL_STATUS */ { CYAPA_SMBUS_BL_HEAD, 16 }, /* CYAPA_CMD_BL_HEAD */ { CYAPA_SMBUS_BL_CMD, 16 }, /* CYAPA_CMD_BL_CMD */ { CYAPA_SMBUS_BL_DATA, 16 }, /* CYAPA_CMD_BL_DATA */ { CYAPA_SMBUS_BL_ALL, 32 }, /* CYAPA_CMD_BL_ALL */ { CYAPA_SMBUS_BLK_PRODUCT_ID, PRODUCT_ID_SIZE }, /* CYAPA_CMD_BLK_PRODUCT_ID */ { CYAPA_SMBUS_BLK_HEAD, 16 }, /* CYAPA_CMD_BLK_HEAD */ { CYAPA_SMBUS_MAX_BASELINE, 1 }, /* CYAPA_CMD_MAX_BASELINE */ { CYAPA_SMBUS_MIN_BASELINE, 1 }, /* CYAPA_CMD_MIN_BASELINE */ }; static int cyapa_gen3_try_poll_handler(struct cyapa *cyapa); /* * cyapa_smbus_read_block - perform smbus block read command * @cyapa - private data structure of the driver * @cmd - the properly encoded smbus command * @len - expected length of smbus command result * @values - buffer to store smbus command result * * Returns negative errno, else the number of bytes written. * * Note: * In trackpad device, the memory block allocated for I2C register map * is 256 bytes, so the max read block for I2C bus is 256 bytes. */ ssize_t cyapa_smbus_read_block(struct cyapa *cyapa, u8 cmd, size_t len, u8 *values) { ssize_t ret; u8 index; u8 smbus_cmd; u8 *buf; struct i2c_client *client = cyapa->client; if (!(SMBUS_BYTE_BLOCK_CMD_MASK & cmd)) return -EINVAL; if (SMBUS_GROUP_BLOCK_CMD_MASK & cmd) { /* read specific block registers command. */ smbus_cmd = SMBUS_ENCODE_RW(cmd, SMBUS_READ); ret = i2c_smbus_read_block_data(client, smbus_cmd, values); goto out; } ret = 0; for (index = 0; index * I2C_SMBUS_BLOCK_MAX < len; index++) { smbus_cmd = SMBUS_ENCODE_IDX(cmd, index); smbus_cmd = SMBUS_ENCODE_RW(smbus_cmd, SMBUS_READ); buf = values + I2C_SMBUS_BLOCK_MAX * index; ret = i2c_smbus_read_block_data(client, smbus_cmd, buf); if (ret < 0) goto out; } out: return ret > 0 ? len : ret; } static s32 cyapa_read_byte(struct cyapa *cyapa, u8 cmd_idx) { u8 cmd; if (cyapa->smbus) { cmd = cyapa_smbus_cmds[cmd_idx].cmd; cmd = SMBUS_ENCODE_RW(cmd, SMBUS_READ); } else { cmd = cyapa_i2c_cmds[cmd_idx].cmd; } return i2c_smbus_read_byte_data(cyapa->client, cmd); } static s32 cyapa_write_byte(struct cyapa *cyapa, u8 cmd_idx, u8 value) { u8 cmd; if (cyapa->smbus) { cmd = cyapa_smbus_cmds[cmd_idx].cmd; cmd = SMBUS_ENCODE_RW(cmd, SMBUS_WRITE); } else { cmd = cyapa_i2c_cmds[cmd_idx].cmd; } return i2c_smbus_write_byte_data(cyapa->client, cmd, value); } ssize_t cyapa_i2c_reg_read_block(struct cyapa *cyapa, u8 reg, size_t len, u8 *values) { return i2c_smbus_read_i2c_block_data(cyapa->client, reg, len, values); } static ssize_t cyapa_i2c_reg_write_block(struct cyapa *cyapa, u8 reg, size_t len, const u8 *values) { return i2c_smbus_write_i2c_block_data(cyapa->client, reg, len, values); } ssize_t cyapa_read_block(struct cyapa *cyapa, u8 cmd_idx, u8 *values) { u8 cmd; size_t len; if (cyapa->smbus) { cmd = cyapa_smbus_cmds[cmd_idx].cmd; len = cyapa_smbus_cmds[cmd_idx].len; return cyapa_smbus_read_block(cyapa, cmd, len, values); } cmd = cyapa_i2c_cmds[cmd_idx].cmd; len = cyapa_i2c_cmds[cmd_idx].len; return cyapa_i2c_reg_read_block(cyapa, cmd, len, values); } /* * Determine the Gen3 trackpad device's current operating state. * */ static int cyapa_gen3_state_parse(struct cyapa *cyapa, u8 *reg_data, int len) { cyapa->state = CYAPA_STATE_NO_DEVICE; /* Parse based on Gen3 characteristic registers and bits */ if (reg_data[REG_BL_FILE] == BL_FILE && reg_data[REG_BL_ERROR] == BL_ERROR_NO_ERR_IDLE && (reg_data[REG_BL_STATUS] == (BL_STATUS_RUNNING | BL_STATUS_CSUM_VALID) || reg_data[REG_BL_STATUS] == BL_STATUS_RUNNING)) { /* * Normal state after power on or reset, * REG_BL_STATUS == 0x11, firmware image checksum is valid. * REG_BL_STATUS == 0x10, firmware image checksum is invalid. */ cyapa->gen = CYAPA_GEN3; cyapa->state = CYAPA_STATE_BL_IDLE; } else if (reg_data[REG_BL_FILE] == BL_FILE && (reg_data[REG_BL_STATUS] & BL_STATUS_RUNNING) == BL_STATUS_RUNNING) { cyapa->gen = CYAPA_GEN3; if (reg_data[REG_BL_STATUS] & BL_STATUS_BUSY) { cyapa->state = CYAPA_STATE_BL_BUSY; } else { if ((reg_data[REG_BL_ERROR] & BL_ERROR_BOOTLOADING) == BL_ERROR_BOOTLOADING) cyapa->state = CYAPA_STATE_BL_ACTIVE; else cyapa->state = CYAPA_STATE_BL_IDLE; } } else if ((reg_data[REG_OP_STATUS] & OP_STATUS_SRC) && (reg_data[REG_OP_DATA1] & OP_DATA_VALID)) { /* * Normal state when running in operational mode, * may also not in full power state or * busying in command process. */ if (GEN3_FINGER_NUM(reg_data[REG_OP_DATA1]) <= GEN3_MAX_FINGERS) { /* Finger number data is valid. */ cyapa->gen = CYAPA_GEN3; cyapa->state = CYAPA_STATE_OP; } } else if (reg_data[REG_OP_STATUS] == 0x0C && reg_data[REG_OP_DATA1] == 0x08) { /* Op state when first two registers overwritten with 0x00 */ cyapa->gen = CYAPA_GEN3; cyapa->state = CYAPA_STATE_OP; } else if (reg_data[REG_BL_STATUS] & (BL_STATUS_RUNNING | BL_STATUS_BUSY)) { cyapa->gen = CYAPA_GEN3; cyapa->state = CYAPA_STATE_BL_BUSY; } if (cyapa->gen == CYAPA_GEN3 && (cyapa->state == CYAPA_STATE_OP || cyapa->state == CYAPA_STATE_BL_IDLE || cyapa->state == CYAPA_STATE_BL_ACTIVE || cyapa->state == CYAPA_STATE_BL_BUSY)) return 0; return -EAGAIN; } /* * Enter bootloader by soft resetting the device. * * If device is already in the bootloader, the function just returns. * Otherwise, reset the device; after reset, device enters bootloader idle * state immediately. * * Returns: * 0 on success * -EAGAIN device was reset, but is not now in bootloader idle state * < 0 if the device never responds within the timeout */ static int cyapa_gen3_bl_enter(struct cyapa *cyapa) { int error; int waiting_time; error = cyapa_poll_state(cyapa, 500); if (error) return error; if (cyapa->state == CYAPA_STATE_BL_IDLE) { /* Already in BL_IDLE. Skipping reset. */ return 0; } if (cyapa->state != CYAPA_STATE_OP) return -EAGAIN; cyapa->operational = false; cyapa->state = CYAPA_STATE_NO_DEVICE; error = cyapa_write_byte(cyapa, CYAPA_CMD_SOFT_RESET, 0x01); if (error) return -EIO; usleep_range(25000, 50000); waiting_time = 2000; /* For some shipset, max waiting time is 1~2s. */ do { error = cyapa_poll_state(cyapa, 500); if (error) { if (error == -ETIMEDOUT) { waiting_time -= 500; continue; } return error; } if ((cyapa->state == CYAPA_STATE_BL_IDLE) && !(cyapa->status[REG_BL_STATUS] & BL_STATUS_WATCHDOG)) break; msleep(100); waiting_time -= 100; } while (waiting_time > 0); if ((cyapa->state != CYAPA_STATE_BL_IDLE) || (cyapa->status[REG_BL_STATUS] & BL_STATUS_WATCHDOG)) return -EAGAIN; return 0; } static int cyapa_gen3_bl_activate(struct cyapa *cyapa) { int error; error = cyapa_i2c_reg_write_block(cyapa, 0, sizeof(bl_activate), bl_activate); if (error) return error; /* Wait for bootloader to activate; takes between 2 and 12 seconds */ msleep(2000); error = cyapa_poll_state(cyapa, 11000); if (error) return error; if (cyapa->state != CYAPA_STATE_BL_ACTIVE) return -EAGAIN; return 0; } static int cyapa_gen3_bl_deactivate(struct cyapa *cyapa) { int error; error = cyapa_i2c_reg_write_block(cyapa, 0, sizeof(bl_deactivate), bl_deactivate); if (error) return error; /* Wait for bootloader to switch to idle state; should take < 100ms */ msleep(100); error = cyapa_poll_state(cyapa, 500); if (error) return error; if (cyapa->state != CYAPA_STATE_BL_IDLE) return -EAGAIN; return 0; } /* * Exit bootloader * * Send bl_exit command, then wait 50 - 100 ms to let device transition to * operational mode. If this is the first time the device's firmware is * running, it can take up to 2 seconds to calibrate its sensors. So, poll * the device's new state for up to 2 seconds. * * Returns: * -EIO failure while reading from device * -EAGAIN device is stuck in bootloader, b/c it has invalid firmware * 0 device is supported and in operational mode */ static int cyapa_gen3_bl_exit(struct cyapa *cyapa) { int error; error = cyapa_i2c_reg_write_block(cyapa, 0, sizeof(bl_exit), bl_exit); if (error) return error; /* * Wait for bootloader to exit, and operation mode to start. * Normally, this takes at least 50 ms. */ msleep(50); /* * In addition, when a device boots for the first time after being * updated to new firmware, it must first calibrate its sensors, which * can take up to an additional 2 seconds. If the device power is * running low, this may take even longer. */ error = cyapa_poll_state(cyapa, 4000); if (error < 0) return error; if (cyapa->state != CYAPA_STATE_OP) return -EAGAIN; return 0; } static u16 cyapa_gen3_csum(const u8 *buf, size_t count) { int i; u16 csum = 0; for (i = 0; i < count; i++) csum += buf[i]; return csum; } /* * Verify the integrity of a CYAPA firmware image file. * * The firmware image file is 30848 bytes, composed of 482 64-byte blocks. * * The first 2 blocks are the firmware header. * The next 480 blocks are the firmware image. * * The first two bytes of the header hold the header checksum, computed by * summing the other 126 bytes of the header. * The last two bytes of the header hold the firmware image checksum, computed * by summing the 30720 bytes of the image modulo 0xffff. * * Both checksums are stored little-endian. */ static int cyapa_gen3_check_fw(struct cyapa *cyapa, const struct firmware *fw) { struct device *dev = &cyapa->client->dev; u16 csum; u16 csum_expected; /* Firmware must match exact 30848 bytes = 482 64-byte blocks. */ if (fw->size != CYAPA_FW_SIZE) { dev_err(dev, "invalid firmware size = %zu, expected %u.\n", fw->size, CYAPA_FW_SIZE); return -EINVAL; } /* Verify header block */ csum_expected = (fw->data[0] << 8) | fw->data[1]; csum = cyapa_gen3_csum(&fw->data[2], CYAPA_FW_HDR_SIZE - 2); if (csum != csum_expected) { dev_err(dev, "%s %04x, expected: %04x\n", "invalid firmware header checksum = ", csum, csum_expected); return -EINVAL; } /* Verify firmware image */ csum_expected = (fw->data[CYAPA_FW_HDR_SIZE - 2] << 8) | fw->data[CYAPA_FW_HDR_SIZE - 1]; csum = cyapa_gen3_csum(&fw->data[CYAPA_FW_HDR_SIZE], CYAPA_FW_DATA_SIZE); if (csum != csum_expected) { dev_err(dev, "%s %04x, expected: %04x\n", "invalid firmware header checksum = ", csum, csum_expected); return -EINVAL; } return 0; } /* * Write a |len| byte long buffer |buf| to the device, by chopping it up into a * sequence of smaller |CYAPA_CMD_LEN|-length write commands. * * The data bytes for a write command are prepended with the 1-byte offset * of the data relative to the start of |buf|. */ static int cyapa_gen3_write_buffer(struct cyapa *cyapa, const u8 *buf, size_t len) { int error; size_t i; unsigned char cmd[CYAPA_CMD_LEN + 1]; size_t cmd_len; for (i = 0; i < len; i += CYAPA_CMD_LEN) { const u8 *payload = &buf[i]; cmd_len = (len - i >= CYAPA_CMD_LEN) ? CYAPA_CMD_LEN : len - i; cmd[0] = i; memcpy(&cmd[1], payload, cmd_len); error = cyapa_i2c_reg_write_block(cyapa, 0, cmd_len + 1, cmd); if (error) return error; } return 0; } /* * A firmware block write command writes 64 bytes of data to a single flash * page in the device. The 78-byte block write command has the format: * <0xff> <CMD> <Key> <Start> <Data> <Data-Checksum> <CMD Checksum> * * <0xff> - every command starts with 0xff * <CMD> - the write command value is 0x39 * <Key> - write commands include an 8-byte key: { 00 01 02 03 04 05 06 07 } * <Block> - Memory Block number (address / 64) (16-bit, big-endian) * <Data> - 64 bytes of firmware image data * <Data Checksum> - sum of 64 <Data> bytes, modulo 0xff * <CMD Checksum> - sum of 77 bytes, from 0xff to <Data Checksum> * * Each write command is split into 5 i2c write transactions of up to 16 bytes. * Each transaction starts with an i2c register offset: (00, 10, 20, 30, 40). */ static int cyapa_gen3_write_fw_block(struct cyapa *cyapa, u16 block, const u8 *data) { int ret; struct gen3_write_block_cmd write_block_cmd; u8 status[BL_STATUS_SIZE]; int tries; u8 bl_status, bl_error; /* Set write command and security key bytes. */ write_block_cmd.checksum_seed = GEN3_BL_CMD_CHECKSUM_SEED; write_block_cmd.cmd_code = GEN3_BL_CMD_WRITE_BLOCK; memcpy(write_block_cmd.key, security_key, sizeof(security_key)); put_unaligned_be16(block, &write_block_cmd.block_num); memcpy(write_block_cmd.block_data, data, CYAPA_FW_BLOCK_SIZE); write_block_cmd.block_checksum = cyapa_gen3_csum( write_block_cmd.block_data, CYAPA_FW_BLOCK_SIZE); write_block_cmd.cmd_checksum = cyapa_gen3_csum((u8 *)&write_block_cmd, sizeof(write_block_cmd) - 1); ret = cyapa_gen3_write_buffer(cyapa, (u8 *)&write_block_cmd, sizeof(write_block_cmd)); if (ret) return ret; /* Wait for write to finish */ tries = 11; /* Programming for one block can take about 100ms. */ do { usleep_range(10000, 20000); /* Check block write command result status. */ ret = cyapa_i2c_reg_read_block(cyapa, BL_HEAD_OFFSET, BL_STATUS_SIZE, status); if (ret != BL_STATUS_SIZE) return (ret < 0) ? ret : -EIO; } while ((status[REG_BL_STATUS] & BL_STATUS_BUSY) && --tries); /* Ignore WATCHDOG bit and reserved bits. */ bl_status = status[REG_BL_STATUS] & ~BL_STATUS_REV_MASK; bl_error = status[REG_BL_ERROR] & ~BL_ERROR_RESERVED; if (bl_status & BL_STATUS_BUSY) ret = -ETIMEDOUT; else if (bl_status != BL_STATUS_RUNNING || bl_error != BL_ERROR_BOOTLOADING) ret = -EIO; else ret = 0; return ret; } static int cyapa_gen3_write_blocks(struct cyapa *cyapa, size_t start_block, size_t block_count, const u8 *image_data) { int error; int i; for (i = 0; i < block_count; i++) { size_t block = start_block + i; size_t addr = i * CYAPA_FW_BLOCK_SIZE; const u8 *data = &image_data[addr]; error = cyapa_gen3_write_fw_block(cyapa, block, data); if (error) return error; } return 0; } static int cyapa_gen3_do_fw_update(struct cyapa *cyapa, const struct firmware *fw) { struct device *dev = &cyapa->client->dev; int error; /* First write data, starting at byte 128 of fw->data */ error = cyapa_gen3_write_blocks(cyapa, CYAPA_FW_DATA_BLOCK_START, CYAPA_FW_DATA_BLOCK_COUNT, &fw->data[CYAPA_FW_HDR_BLOCK_COUNT * CYAPA_FW_BLOCK_SIZE]); if (error) { dev_err(dev, "FW update aborted, write image: %d\n", error); return error; } /* Then write checksum */ error = cyapa_gen3_write_blocks(cyapa, CYAPA_FW_HDR_BLOCK_START, CYAPA_FW_HDR_BLOCK_COUNT, &fw->data[0]); if (error) { dev_err(dev, "FW update aborted, write checksum: %d\n", error); return error; } return 0; } static ssize_t cyapa_gen3_do_calibrate(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct cyapa *cyapa = dev_get_drvdata(dev); unsigned long timeout; int ret; ret = cyapa_read_byte(cyapa, CYAPA_CMD_DEV_STATUS); if (ret < 0) { dev_err(dev, "Error reading dev status: %d\n", ret); goto out; } if ((ret & CYAPA_DEV_NORMAL) != CYAPA_DEV_NORMAL) { dev_warn(dev, "Trackpad device is busy, device state: 0x%02x\n", ret); ret = -EAGAIN; goto out; } ret = cyapa_write_byte(cyapa, CYAPA_CMD_SOFT_RESET, OP_RECALIBRATION_MASK); if (ret < 0) { dev_err(dev, "Failed to send calibrate command: %d\n", ret); goto out; } /* max recalibration timeout 2s. */ timeout = jiffies + 2 * HZ; do { /* * For this recalibration, the max time will not exceed 2s. * The average time is approximately 500 - 700 ms, and we * will check the status every 100 - 200ms. */ msleep(100); ret = cyapa_read_byte(cyapa, CYAPA_CMD_DEV_STATUS); if (ret < 0) { dev_err(dev, "Error reading dev status: %d\n", ret); goto out; } if ((ret & CYAPA_DEV_NORMAL) == CYAPA_DEV_NORMAL) { dev_dbg(dev, "Calibration successful.\n"); goto out; } } while (time_is_after_jiffies(timeout)); dev_err(dev, "Failed to calibrate. Timeout.\n"); ret = -ETIMEDOUT; out: return ret < 0 ? ret : count; } static ssize_t cyapa_gen3_show_baseline(struct device *dev, struct device_attribute *attr, char *buf) { struct cyapa *cyapa = dev_get_drvdata(dev); int max_baseline, min_baseline; int tries; int ret; ret = cyapa_read_byte(cyapa, CYAPA_CMD_DEV_STATUS); if (ret < 0) { dev_err(dev, "Error reading dev status. err = %d\n", ret); goto out; } if ((ret & CYAPA_DEV_NORMAL) != CYAPA_DEV_NORMAL) { dev_warn(dev, "Trackpad device is busy. device state = 0x%x\n", ret); ret = -EAGAIN; goto out; } ret = cyapa_write_byte(cyapa, CYAPA_CMD_SOFT_RESET, OP_REPORT_BASELINE_MASK); if (ret < 0) { dev_err(dev, "Failed to send report baseline command. %d\n", ret); goto out; } tries = 3; /* Try for 30 to 60 ms */ do { usleep_range(10000, 20000); ret = cyapa_read_byte(cyapa, CYAPA_CMD_DEV_STATUS); if (ret < 0) { dev_err(dev, "Error reading dev status. err = %d\n", ret); goto out; } if ((ret & CYAPA_DEV_NORMAL) == CYAPA_DEV_NORMAL) break; } while (--tries); if (tries == 0) { dev_err(dev, "Device timed out going to Normal state.\n"); ret = -ETIMEDOUT; goto out; } ret = cyapa_read_byte(cyapa, CYAPA_CMD_MAX_BASELINE); if (ret < 0) { dev_err(dev, "Failed to read max baseline. err = %d\n", ret); goto out; } max_baseline = ret; ret = cyapa_read_byte(cyapa, CYAPA_CMD_MIN_BASELINE); if (ret < 0) { dev_err(dev, "Failed to read min baseline. err = %d\n", ret); goto out; } min_baseline = ret; dev_dbg(dev, "Baseline report successful. Max: %d Min: %d\n", max_baseline, min_baseline); ret = scnprintf(buf, PAGE_SIZE, "%d %d\n", max_baseline, min_baseline); out: return ret; } /* * cyapa_get_wait_time_for_pwr_cmd * * Compute the amount of time we need to wait after updating the touchpad * power mode. The touchpad needs to consume the incoming power mode set * command at the current clock rate. */ static u16 cyapa_get_wait_time_for_pwr_cmd(u8 pwr_mode) { switch (pwr_mode) { case PWR_MODE_FULL_ACTIVE: return 20; case PWR_MODE_BTN_ONLY: return 20; case PWR_MODE_OFF: return 20; default: return cyapa_pwr_cmd_to_sleep_time(pwr_mode) + 50; } } /* * Set device power mode * * Write to the field to configure power state. Power states include : * Full : Max scans and report rate. * Idle : Report rate set by user specified time. * ButtonOnly : No scans for fingers. When the button is triggered, * a slave interrupt is asserted to notify host to wake up. * Off : Only awake for i2c commands from host. No function for button * or touch sensors. * * The power_mode command should conform to the following : * Full : 0x3f * Idle : Configurable from 20 to 1000ms. See note below for * cyapa_sleep_time_to_pwr_cmd and cyapa_pwr_cmd_to_sleep_time * ButtonOnly : 0x01 * Off : 0x00 * * Device power mode can only be set when device is in operational mode. */ static int cyapa_gen3_set_power_mode(struct cyapa *cyapa, u8 power_mode, u16 always_unused, enum cyapa_pm_stage pm_stage) { struct input_dev *input = cyapa->input; u8 power; int tries; int sleep_time; int interval; int ret; if (cyapa->state != CYAPA_STATE_OP) return 0; tries = SET_POWER_MODE_TRIES; while (tries--) { ret = cyapa_read_byte(cyapa, CYAPA_CMD_POWER_MODE); if (ret >= 0) break; usleep_range(SET_POWER_MODE_DELAY, 2 * SET_POWER_MODE_DELAY); } if (ret < 0) return ret; /* * Return early if the power mode to set is the same as the current * one. */ if ((ret & PWR_MODE_MASK) == power_mode) return 0; sleep_time = (int)cyapa_get_wait_time_for_pwr_cmd(ret & PWR_MODE_MASK); power = ret; power &= ~PWR_MODE_MASK; power |= power_mode & PWR_MODE_MASK; tries = SET_POWER_MODE_TRIES; while (tries--) { ret = cyapa_write_byte(cyapa, CYAPA_CMD_POWER_MODE, power); if (!ret) break; usleep_range(SET_POWER_MODE_DELAY, 2 * SET_POWER_MODE_DELAY); } /* * Wait for the newly set power command to go in at the previous * clock speed (scanrate) used by the touchpad firmware. Not * doing so before issuing the next command may result in errors * depending on the command's content. */ if (cyapa->operational && input && input_device_enabled(input) && (pm_stage == CYAPA_PM_RUNTIME_SUSPEND || pm_stage == CYAPA_PM_RUNTIME_RESUME)) { /* Try to polling in 120Hz, read may fail, just ignore it. */ interval = 1000 / 120; while (sleep_time > 0) { if (sleep_time > interval) msleep(interval); else msleep(sleep_time); sleep_time -= interval; cyapa_gen3_try_poll_handler(cyapa); } } else { msleep(sleep_time); } return ret; } static int cyapa_gen3_set_proximity(struct cyapa *cyapa, bool enable) { return -EOPNOTSUPP; } static int cyapa_gen3_get_query_data(struct cyapa *cyapa) { u8 query_data[QUERY_DATA_SIZE]; int ret; if (cyapa->state != CYAPA_STATE_OP) return -EBUSY; ret = cyapa_read_block(cyapa, CYAPA_CMD_GROUP_QUERY, query_data); if (ret != QUERY_DATA_SIZE) return (ret < 0) ? ret : -EIO; memcpy(&cyapa->product_id[0], &query_data[0], 5); cyapa->product_id[5] = '-'; memcpy(&cyapa->product_id[6], &query_data[5], 6); cyapa->product_id[12] = '-'; memcpy(&cyapa->product_id[13], &query_data[11], 2); cyapa->product_id[15] = '\0'; cyapa->fw_maj_ver = query_data[15]; cyapa->fw_min_ver = query_data[16]; cyapa->btn_capability = query_data[19] & CAPABILITY_BTN_MASK; cyapa->gen = query_data[20] & 0x0f; cyapa->max_abs_x = ((query_data[21] & 0xf0) << 4) | query_data[22]; cyapa->max_abs_y = ((query_data[21] & 0x0f) << 8) | query_data[23]; cyapa->physical_size_x = ((query_data[24] & 0xf0) << 4) | query_data[25]; cyapa->physical_size_y = ((query_data[24] & 0x0f) << 8) | query_data[26]; cyapa->max_z = 255; return 0; } static int cyapa_gen3_bl_query_data(struct cyapa *cyapa) { u8 bl_data[CYAPA_CMD_LEN]; int ret; ret = cyapa_i2c_reg_read_block(cyapa, 0, CYAPA_CMD_LEN, bl_data); if (ret != CYAPA_CMD_LEN) return (ret < 0) ? ret : -EIO; /* * This value will be updated again when entered application mode. * If TP failed to enter application mode, this fw version values * can be used as a reference. * This firmware version valid when fw image checksum is valid. */ if (bl_data[REG_BL_STATUS] == (BL_STATUS_RUNNING | BL_STATUS_CSUM_VALID)) { cyapa->fw_maj_ver = bl_data[GEN3_BL_IDLE_FW_MAJ_VER_OFFSET]; cyapa->fw_min_ver = bl_data[GEN3_BL_IDLE_FW_MIN_VER_OFFSET]; } return 0; } /* * Check if device is operational. * * An operational device is responding, has exited bootloader, and has * firmware supported by this driver. * * Returns: * -EBUSY no device or in bootloader * -EIO failure while reading from device * -EAGAIN device is still in bootloader * if ->state = CYAPA_STATE_BL_IDLE, device has invalid firmware * -EINVAL device is in operational mode, but not supported by this driver * 0 device is supported */ static int cyapa_gen3_do_operational_check(struct cyapa *cyapa) { struct device *dev = &cyapa->client->dev; int error; switch (cyapa->state) { case CYAPA_STATE_BL_ACTIVE: error = cyapa_gen3_bl_deactivate(cyapa); if (error) { dev_err(dev, "failed to bl_deactivate: %d\n", error); return error; } fallthrough; case CYAPA_STATE_BL_IDLE: /* Try to get firmware version in bootloader mode. */ cyapa_gen3_bl_query_data(cyapa); error = cyapa_gen3_bl_exit(cyapa); if (error) { dev_err(dev, "failed to bl_exit: %d\n", error); return error; } fallthrough; case CYAPA_STATE_OP: /* * Reading query data before going back to the full mode * may cause problems, so we set the power mode first here. */ error = cyapa_gen3_set_power_mode(cyapa, PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE); if (error) dev_err(dev, "%s: set full power mode failed: %d\n", __func__, error); error = cyapa_gen3_get_query_data(cyapa); if (error < 0) return error; /* Only support firmware protocol gen3 */ if (cyapa->gen != CYAPA_GEN3) { dev_err(dev, "unsupported protocol version (%d)", cyapa->gen); return -EINVAL; } /* Only support product ID starting with CYTRA */ if (memcmp(cyapa->product_id, product_id, strlen(product_id)) != 0) { dev_err(dev, "unsupported product ID (%s)\n", cyapa->product_id); return -EINVAL; } return 0; default: return -EIO; } return 0; } /* * Return false, do not continue process * Return true, continue process. */ static bool cyapa_gen3_irq_cmd_handler(struct cyapa *cyapa) { /* Not gen3 irq command response, skip for continue. */ if (cyapa->gen != CYAPA_GEN3) return true; if (cyapa->operational) return true; /* * Driver in detecting or other interface function processing, * so, stop cyapa_gen3_irq_handler to continue process to * avoid unwanted to error detecting and processing. * * And also, avoid the periodically asserted interrupts to be processed * as touch inputs when gen3 failed to launch into application mode, * which will cause gen3 stays in bootloader mode. */ return false; } static int cyapa_gen3_event_process(struct cyapa *cyapa, struct cyapa_reg_data *data) { struct input_dev *input = cyapa->input; int num_fingers; int i; num_fingers = (data->finger_btn >> 4) & 0x0f; for (i = 0; i < num_fingers; i++) { const struct cyapa_touch *touch = &data->touches[i]; /* Note: touch->id range is 1 to 15; slots are 0 to 14. */ int slot = touch->id - 1; input_mt_slot(input, slot); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); input_report_abs(input, ABS_MT_POSITION_X, ((touch->xy_hi & 0xf0) << 4) | touch->x_lo); input_report_abs(input, ABS_MT_POSITION_Y, ((touch->xy_hi & 0x0f) << 8) | touch->y_lo); input_report_abs(input, ABS_MT_PRESSURE, touch->pressure); } input_mt_sync_frame(input); if (cyapa->btn_capability & CAPABILITY_LEFT_BTN_MASK) input_report_key(input, BTN_LEFT, !!(data->finger_btn & OP_DATA_LEFT_BTN)); if (cyapa->btn_capability & CAPABILITY_MIDDLE_BTN_MASK) input_report_key(input, BTN_MIDDLE, !!(data->finger_btn & OP_DATA_MIDDLE_BTN)); if (cyapa->btn_capability & CAPABILITY_RIGHT_BTN_MASK) input_report_key(input, BTN_RIGHT, !!(data->finger_btn & OP_DATA_RIGHT_BTN)); input_sync(input); return 0; } static int cyapa_gen3_irq_handler(struct cyapa *cyapa) { struct device *dev = &cyapa->client->dev; struct cyapa_reg_data data; int ret; ret = cyapa_read_block(cyapa, CYAPA_CMD_GROUP_DATA, (u8 *)&data); if (ret != sizeof(data)) { dev_err(dev, "failed to read report data, (%d)\n", ret); return -EINVAL; } if ((data.device_status & OP_STATUS_SRC) != OP_STATUS_SRC || (data.device_status & OP_STATUS_DEV) != CYAPA_DEV_NORMAL || (data.finger_btn & OP_DATA_VALID) != OP_DATA_VALID) { dev_err(dev, "invalid device state bytes: %02x %02x\n", data.device_status, data.finger_btn); return -EINVAL; } return cyapa_gen3_event_process(cyapa, &data); } /* * This function will be called in the cyapa_gen3_set_power_mode function, * and it's known that it may failed in some situation after the set power * mode command was sent. So this function is aimed to avoid the knwon * and unwanted output I2C and data parse error messages. */ static int cyapa_gen3_try_poll_handler(struct cyapa *cyapa) { struct cyapa_reg_data data; int ret; ret = cyapa_read_block(cyapa, CYAPA_CMD_GROUP_DATA, (u8 *)&data); if (ret != sizeof(data)) return -EINVAL; if ((data.device_status & OP_STATUS_SRC) != OP_STATUS_SRC || (data.device_status & OP_STATUS_DEV) != CYAPA_DEV_NORMAL || (data.finger_btn & OP_DATA_VALID) != OP_DATA_VALID) return -EINVAL; return cyapa_gen3_event_process(cyapa, &data); } static int cyapa_gen3_initialize(struct cyapa *cyapa) { return 0; } static int cyapa_gen3_bl_initiate(struct cyapa *cyapa, const struct firmware *fw) { return 0; } static int cyapa_gen3_empty_output_data(struct cyapa *cyapa, u8 *buf, int *len, cb_sort func) { return 0; } const struct cyapa_dev_ops cyapa_gen3_ops = { .check_fw = cyapa_gen3_check_fw, .bl_enter = cyapa_gen3_bl_enter, .bl_activate = cyapa_gen3_bl_activate, .update_fw = cyapa_gen3_do_fw_update, .bl_deactivate = cyapa_gen3_bl_deactivate, .bl_initiate = cyapa_gen3_bl_initiate, .show_baseline = cyapa_gen3_show_baseline, .calibrate_store = cyapa_gen3_do_calibrate, .initialize = cyapa_gen3_initialize, .state_parse = cyapa_gen3_state_parse, .operational_check = cyapa_gen3_do_operational_check, .irq_handler = cyapa_gen3_irq_handler, .irq_cmd_handler = cyapa_gen3_irq_cmd_handler, .sort_empty_output_data = cyapa_gen3_empty_output_data, .set_power_mode = cyapa_gen3_set_power_mode, .set_proximity = cyapa_gen3_set_proximity, };
linux-master
drivers/input/mouse/cyapa_gen3.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Apple USB Touchpad (for post-February 2005 PowerBooks and MacBooks) driver * * Copyright (C) 2001-2004 Greg Kroah-Hartman ([email protected]) * Copyright (C) 2005-2008 Johannes Berg ([email protected]) * Copyright (C) 2005-2008 Stelian Pop ([email protected]) * Copyright (C) 2005 Frank Arnold ([email protected]) * Copyright (C) 2005 Peter Osterlund ([email protected]) * Copyright (C) 2005 Michael Hanselmann ([email protected]) * Copyright (C) 2006 Nicolas Boichat ([email protected]) * Copyright (C) 2007-2008 Sven Anders ([email protected]) * * Thanks to Alex Harper <[email protected]> for his inputs. */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> /* * Note: We try to keep the touchpad aspect ratio while still doing only * simple arithmetics: * 0 <= x <= (xsensors - 1) * xfact * 0 <= y <= (ysensors - 1) * yfact */ struct atp_info { int xsensors; /* number of X sensors */ int xsensors_17; /* 17" models have more sensors */ int ysensors; /* number of Y sensors */ int xfact; /* X multiplication factor */ int yfact; /* Y multiplication factor */ int datalen; /* size of USB transfers */ void (*callback)(struct urb *); /* callback function */ int fuzz; /* fuzz touchpad generates */ }; static void atp_complete_geyser_1_2(struct urb *urb); static void atp_complete_geyser_3_4(struct urb *urb); static const struct atp_info fountain_info = { .xsensors = 16, .xsensors_17 = 26, .ysensors = 16, .xfact = 64, .yfact = 43, .datalen = 81, .callback = atp_complete_geyser_1_2, .fuzz = 16, }; static const struct atp_info geyser1_info = { .xsensors = 16, .xsensors_17 = 26, .ysensors = 16, .xfact = 64, .yfact = 43, .datalen = 81, .callback = atp_complete_geyser_1_2, .fuzz = 16, }; static const struct atp_info geyser2_info = { .xsensors = 15, .xsensors_17 = 20, .ysensors = 9, .xfact = 64, .yfact = 43, .datalen = 64, .callback = atp_complete_geyser_1_2, .fuzz = 0, }; static const struct atp_info geyser3_info = { .xsensors = 20, .ysensors = 10, .xfact = 64, .yfact = 64, .datalen = 64, .callback = atp_complete_geyser_3_4, .fuzz = 0, }; static const struct atp_info geyser4_info = { .xsensors = 20, .ysensors = 10, .xfact = 64, .yfact = 64, .datalen = 64, .callback = atp_complete_geyser_3_4, .fuzz = 0, }; #define ATP_DEVICE(prod, info) \ { \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | \ USB_DEVICE_ID_MATCH_INT_CLASS | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL, \ .idVendor = 0x05ac, /* Apple */ \ .idProduct = (prod), \ .bInterfaceClass = 0x03, \ .bInterfaceProtocol = 0x02, \ .driver_info = (unsigned long) &info, \ } /* * Table of devices (Product IDs) that work with this driver. * (The names come from Info.plist in AppleUSBTrackpad.kext, * According to Info.plist Geyser IV is the same as Geyser III.) */ static const struct usb_device_id atp_table[] = { /* PowerBooks Feb 2005, iBooks G4 */ ATP_DEVICE(0x020e, fountain_info), /* FOUNTAIN ANSI */ ATP_DEVICE(0x020f, fountain_info), /* FOUNTAIN ISO */ ATP_DEVICE(0x030a, fountain_info), /* FOUNTAIN TP ONLY */ ATP_DEVICE(0x030b, geyser1_info), /* GEYSER 1 TP ONLY */ /* PowerBooks Oct 2005 */ ATP_DEVICE(0x0214, geyser2_info), /* GEYSER 2 ANSI */ ATP_DEVICE(0x0215, geyser2_info), /* GEYSER 2 ISO */ ATP_DEVICE(0x0216, geyser2_info), /* GEYSER 2 JIS */ /* Core Duo MacBook & MacBook Pro */ ATP_DEVICE(0x0217, geyser3_info), /* GEYSER 3 ANSI */ ATP_DEVICE(0x0218, geyser3_info), /* GEYSER 3 ISO */ ATP_DEVICE(0x0219, geyser3_info), /* GEYSER 3 JIS */ /* Core2 Duo MacBook & MacBook Pro */ ATP_DEVICE(0x021a, geyser4_info), /* GEYSER 4 ANSI */ ATP_DEVICE(0x021b, geyser4_info), /* GEYSER 4 ISO */ ATP_DEVICE(0x021c, geyser4_info), /* GEYSER 4 JIS */ /* Core2 Duo MacBook3,1 */ ATP_DEVICE(0x0229, geyser4_info), /* GEYSER 4 HF ANSI */ ATP_DEVICE(0x022a, geyser4_info), /* GEYSER 4 HF ISO */ ATP_DEVICE(0x022b, geyser4_info), /* GEYSER 4 HF JIS */ /* Terminating entry */ { } }; MODULE_DEVICE_TABLE(usb, atp_table); /* maximum number of sensors */ #define ATP_XSENSORS 26 #define ATP_YSENSORS 16 /* * The largest possible bank of sensors with additional buffer of 4 extra values * on either side, for an array of smoothed sensor values. */ #define ATP_SMOOTHSIZE 34 /* maximum pressure this driver will report */ #define ATP_PRESSURE 300 /* * Threshold for the touchpad sensors. Any change less than ATP_THRESHOLD is * ignored. */ #define ATP_THRESHOLD 5 /* * How far we'll bitshift our sensor values before averaging them. Mitigates * rounding errors. */ #define ATP_SCALE 12 /* Geyser initialization constants */ #define ATP_GEYSER_MODE_READ_REQUEST_ID 1 #define ATP_GEYSER_MODE_WRITE_REQUEST_ID 9 #define ATP_GEYSER_MODE_REQUEST_VALUE 0x300 #define ATP_GEYSER_MODE_REQUEST_INDEX 0 #define ATP_GEYSER_MODE_VENDOR_VALUE 0x04 /** * enum atp_status_bits - status bit meanings * * These constants represent the meaning of the status bits. * (only Geyser 3/4) * * @ATP_STATUS_BUTTON: The button was pressed * @ATP_STATUS_BASE_UPDATE: Update of the base values (untouched pad) * @ATP_STATUS_FROM_RESET: Reset previously performed */ enum atp_status_bits { ATP_STATUS_BUTTON = BIT(0), ATP_STATUS_BASE_UPDATE = BIT(2), ATP_STATUS_FROM_RESET = BIT(4), }; /* Structure to hold all of our device specific stuff */ struct atp { char phys[64]; struct usb_device *udev; /* usb device */ struct usb_interface *intf; /* usb interface */ struct urb *urb; /* usb request block */ u8 *data; /* transferred data */ struct input_dev *input; /* input dev */ const struct atp_info *info; /* touchpad model */ bool open; bool valid; /* are the samples valid? */ bool size_detect_done; bool overflow_warned; int fingers_old; /* last reported finger count */ int x_old; /* last reported x/y, */ int y_old; /* used for smoothing */ signed char xy_cur[ATP_XSENSORS + ATP_YSENSORS]; signed char xy_old[ATP_XSENSORS + ATP_YSENSORS]; int xy_acc[ATP_XSENSORS + ATP_YSENSORS]; int smooth[ATP_SMOOTHSIZE]; int smooth_tmp[ATP_SMOOTHSIZE]; int idlecount; /* number of empty packets */ struct work_struct work; }; #define dbg_dump(msg, tab) \ if (debug > 1) { \ int __i; \ printk(KERN_DEBUG "appletouch: %s", msg); \ for (__i = 0; __i < ATP_XSENSORS + ATP_YSENSORS; __i++) \ printk(" %02x", tab[__i]); \ printk("\n"); \ } #define dprintk(format, a...) \ do { \ if (debug) \ printk(KERN_DEBUG format, ##a); \ } while (0) MODULE_AUTHOR("Johannes Berg"); MODULE_AUTHOR("Stelian Pop"); MODULE_AUTHOR("Frank Arnold"); MODULE_AUTHOR("Michael Hanselmann"); MODULE_AUTHOR("Sven Anders"); MODULE_DESCRIPTION("Apple PowerBook and MacBook USB touchpad driver"); MODULE_LICENSE("GPL"); /* * Make the threshold a module parameter */ static int threshold = ATP_THRESHOLD; module_param(threshold, int, 0644); MODULE_PARM_DESC(threshold, "Discard any change in data from a sensor" " (the trackpad has many of these sensors)" " less than this value."); static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Activate debugging output"); /* * By default newer Geyser devices send standard USB HID mouse * packets (Report ID 2). This code changes device mode, so it * sends raw sensor reports (Report ID 5). */ static int atp_geyser_init(struct atp *dev) { struct usb_device *udev = dev->udev; char *data; int size; int i; int ret; data = kmalloc(8, GFP_KERNEL); if (!data) { dev_err(&dev->intf->dev, "Out of memory\n"); return -ENOMEM; } size = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), ATP_GEYSER_MODE_READ_REQUEST_ID, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE, ATP_GEYSER_MODE_REQUEST_VALUE, ATP_GEYSER_MODE_REQUEST_INDEX, data, 8, 5000); if (size != 8) { dprintk("atp_geyser_init: read error\n"); for (i = 0; i < 8; i++) dprintk("appletouch[%d]: %d\n", i, data[i]); dev_err(&dev->intf->dev, "Failed to read mode from device.\n"); ret = -EIO; goto out_free; } /* Apply the mode switch */ data[0] = ATP_GEYSER_MODE_VENDOR_VALUE; size = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), ATP_GEYSER_MODE_WRITE_REQUEST_ID, USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE, ATP_GEYSER_MODE_REQUEST_VALUE, ATP_GEYSER_MODE_REQUEST_INDEX, data, 8, 5000); if (size != 8) { dprintk("atp_geyser_init: write error\n"); for (i = 0; i < 8; i++) dprintk("appletouch[%d]: %d\n", i, data[i]); dev_err(&dev->intf->dev, "Failed to request geyser raw mode\n"); ret = -EIO; goto out_free; } ret = 0; out_free: kfree(data); return ret; } /* * Reinitialise the device. This usually stops stream of empty packets * coming from it. */ static void atp_reinit(struct work_struct *work) { struct atp *dev = container_of(work, struct atp, work); int retval; dprintk("appletouch: putting appletouch to sleep (reinit)\n"); atp_geyser_init(dev); retval = usb_submit_urb(dev->urb, GFP_ATOMIC); if (retval) dev_err(&dev->intf->dev, "atp_reinit: usb_submit_urb failed with error %d\n", retval); } static int atp_calculate_abs(struct atp *dev, int offset, int nb_sensors, int fact, int *z, int *fingers) { int i, pass; /* * Use offset to point xy_sensors at the first value in dev->xy_acc * for whichever dimension we're looking at this particular go-round. */ int *xy_sensors = dev->xy_acc + offset; /* values to calculate mean */ int pcum = 0, psum = 0; int is_increasing = 0; *fingers = 0; for (i = 0; i < nb_sensors; i++) { if (xy_sensors[i] < threshold) { if (is_increasing) is_increasing = 0; /* * Makes the finger detection more versatile. For example, * two fingers with no gap will be detected. Also, my * tests show it less likely to have intermittent loss * of multiple finger readings while moving around (scrolling). * * Changes the multiple finger detection to counting humps on * sensors (transitions from nonincreasing to increasing) * instead of counting transitions from low sensors (no * finger reading) to high sensors (finger above * sensor) * * - Jason Parekh <[email protected]> */ } else if (i < 1 || (!is_increasing && xy_sensors[i - 1] < xy_sensors[i])) { (*fingers)++; is_increasing = 1; } else if (i > 0 && (xy_sensors[i - 1] - xy_sensors[i] > threshold)) { is_increasing = 0; } } if (*fingers < 1) /* No need to continue if no fingers are found. */ return 0; /* * Use a smoothed version of sensor data for movement calculations, to * combat noise without needing to rely so heavily on a threshold. * This improves tracking. * * The smoothed array is bigger than the original so that the smoothing * doesn't result in edge values being truncated. */ memset(dev->smooth, 0, 4 * sizeof(dev->smooth[0])); /* Pull base values, scaled up to help avoid truncation errors. */ for (i = 0; i < nb_sensors; i++) dev->smooth[i + 4] = xy_sensors[i] << ATP_SCALE; memset(&dev->smooth[nb_sensors + 4], 0, 4 * sizeof(dev->smooth[0])); for (pass = 0; pass < 4; pass++) { /* Handle edge. */ dev->smooth_tmp[0] = (dev->smooth[0] + dev->smooth[1]) / 2; /* Average values with neighbors. */ for (i = 1; i < nb_sensors + 7; i++) dev->smooth_tmp[i] = (dev->smooth[i - 1] + dev->smooth[i] * 2 + dev->smooth[i + 1]) / 4; /* Handle other edge. */ dev->smooth_tmp[i] = (dev->smooth[i - 1] + dev->smooth[i]) / 2; memcpy(dev->smooth, dev->smooth_tmp, sizeof(dev->smooth)); } for (i = 0; i < nb_sensors + 8; i++) { /* * Skip values if they're small enough to be truncated to 0 * by scale. Mostly noise. */ if ((dev->smooth[i] >> ATP_SCALE) > 0) { pcum += dev->smooth[i] * i; psum += dev->smooth[i]; } } if (psum > 0) { *z = psum >> ATP_SCALE; /* Scale down pressure output. */ return pcum * fact / psum; } return 0; } static inline void atp_report_fingers(struct input_dev *input, int fingers) { input_report_key(input, BTN_TOOL_FINGER, fingers == 1); input_report_key(input, BTN_TOOL_DOUBLETAP, fingers == 2); input_report_key(input, BTN_TOOL_TRIPLETAP, fingers > 2); } /* Check URB status and for correct length of data package */ #define ATP_URB_STATUS_SUCCESS 0 #define ATP_URB_STATUS_ERROR 1 #define ATP_URB_STATUS_ERROR_FATAL 2 static int atp_status_check(struct urb *urb) { struct atp *dev = urb->context; struct usb_interface *intf = dev->intf; switch (urb->status) { case 0: /* success */ break; case -EOVERFLOW: if (!dev->overflow_warned) { dev_warn(&intf->dev, "appletouch: OVERFLOW with data length %d, actual length is %d\n", dev->info->datalen, dev->urb->actual_length); dev->overflow_warned = true; } fallthrough; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* This urb is terminated, clean up */ dev_dbg(&intf->dev, "atp_complete: urb shutting down with status: %d\n", urb->status); return ATP_URB_STATUS_ERROR_FATAL; default: dev_dbg(&intf->dev, "atp_complete: nonzero urb status received: %d\n", urb->status); return ATP_URB_STATUS_ERROR; } /* drop incomplete datasets */ if (dev->urb->actual_length != dev->info->datalen) { dprintk("appletouch: incomplete data package" " (first byte: %d, length: %d).\n", dev->data[0], dev->urb->actual_length); return ATP_URB_STATUS_ERROR; } return ATP_URB_STATUS_SUCCESS; } static void atp_detect_size(struct atp *dev) { int i; /* 17" Powerbooks have extra X sensors */ for (i = dev->info->xsensors; i < ATP_XSENSORS; i++) { if (dev->xy_cur[i]) { dev_info(&dev->intf->dev, "appletouch: 17\" model detected.\n"); input_set_abs_params(dev->input, ABS_X, 0, (dev->info->xsensors_17 - 1) * dev->info->xfact - 1, dev->info->fuzz, 0); break; } } } /* * USB interrupt callback functions */ /* Interrupt function for older touchpads: FOUNTAIN/GEYSER1/GEYSER2 */ static void atp_complete_geyser_1_2(struct urb *urb) { int x, y, x_z, y_z, x_f, y_f; int retval, i, j; int key, fingers; struct atp *dev = urb->context; int status = atp_status_check(urb); if (status == ATP_URB_STATUS_ERROR_FATAL) return; else if (status == ATP_URB_STATUS_ERROR) goto exit; /* reorder the sensors values */ if (dev->info == &geyser2_info) { memset(dev->xy_cur, 0, sizeof(dev->xy_cur)); /* * The values are laid out like this: * Y1, Y2, -, Y3, Y4, -, ..., X1, X2, -, X3, X4, -, ... * '-' is an unused value. */ /* read X values */ for (i = 0, j = 19; i < 20; i += 2, j += 3) { dev->xy_cur[i] = dev->data[j]; dev->xy_cur[i + 1] = dev->data[j + 1]; } /* read Y values */ for (i = 0, j = 1; i < 9; i += 2, j += 3) { dev->xy_cur[ATP_XSENSORS + i] = dev->data[j]; dev->xy_cur[ATP_XSENSORS + i + 1] = dev->data[j + 1]; } } else { for (i = 0; i < 8; i++) { /* X values */ dev->xy_cur[i + 0] = dev->data[5 * i + 2]; dev->xy_cur[i + 8] = dev->data[5 * i + 4]; dev->xy_cur[i + 16] = dev->data[5 * i + 42]; if (i < 2) dev->xy_cur[i + 24] = dev->data[5 * i + 44]; /* Y values */ dev->xy_cur[ATP_XSENSORS + i] = dev->data[5 * i + 1]; dev->xy_cur[ATP_XSENSORS + i + 8] = dev->data[5 * i + 3]; } } dbg_dump("sample", dev->xy_cur); if (!dev->valid) { /* first sample */ dev->valid = true; dev->x_old = dev->y_old = -1; /* Store first sample */ memcpy(dev->xy_old, dev->xy_cur, sizeof(dev->xy_old)); /* Perform size detection, if not done already */ if (unlikely(!dev->size_detect_done)) { atp_detect_size(dev); dev->size_detect_done = true; goto exit; } } for (i = 0; i < ATP_XSENSORS + ATP_YSENSORS; i++) { /* accumulate the change */ signed char change = dev->xy_old[i] - dev->xy_cur[i]; dev->xy_acc[i] -= change; /* prevent down drifting */ if (dev->xy_acc[i] < 0) dev->xy_acc[i] = 0; } memcpy(dev->xy_old, dev->xy_cur, sizeof(dev->xy_old)); dbg_dump("accumulator", dev->xy_acc); x = atp_calculate_abs(dev, 0, ATP_XSENSORS, dev->info->xfact, &x_z, &x_f); y = atp_calculate_abs(dev, ATP_XSENSORS, ATP_YSENSORS, dev->info->yfact, &y_z, &y_f); key = dev->data[dev->info->datalen - 1] & ATP_STATUS_BUTTON; fingers = max(x_f, y_f); if (x && y && fingers == dev->fingers_old) { if (dev->x_old != -1) { x = (dev->x_old * 7 + x) >> 3; y = (dev->y_old * 7 + y) >> 3; dev->x_old = x; dev->y_old = y; if (debug > 1) printk(KERN_DEBUG "appletouch: " "X: %3d Y: %3d Xz: %3d Yz: %3d\n", x, y, x_z, y_z); input_report_key(dev->input, BTN_TOUCH, 1); input_report_abs(dev->input, ABS_X, x); input_report_abs(dev->input, ABS_Y, y); input_report_abs(dev->input, ABS_PRESSURE, min(ATP_PRESSURE, x_z + y_z)); atp_report_fingers(dev->input, fingers); } dev->x_old = x; dev->y_old = y; } else if (!x && !y) { dev->x_old = dev->y_old = -1; dev->fingers_old = 0; input_report_key(dev->input, BTN_TOUCH, 0); input_report_abs(dev->input, ABS_PRESSURE, 0); atp_report_fingers(dev->input, 0); /* reset the accumulator on release */ memset(dev->xy_acc, 0, sizeof(dev->xy_acc)); } if (fingers != dev->fingers_old) dev->x_old = dev->y_old = -1; dev->fingers_old = fingers; input_report_key(dev->input, BTN_LEFT, key); input_sync(dev->input); exit: retval = usb_submit_urb(dev->urb, GFP_ATOMIC); if (retval) dev_err(&dev->intf->dev, "atp_complete: usb_submit_urb failed with result %d\n", retval); } /* Interrupt function for older touchpads: GEYSER3/GEYSER4 */ static void atp_complete_geyser_3_4(struct urb *urb) { int x, y, x_z, y_z, x_f, y_f; int retval, i, j; int key, fingers; struct atp *dev = urb->context; int status = atp_status_check(urb); if (status == ATP_URB_STATUS_ERROR_FATAL) return; else if (status == ATP_URB_STATUS_ERROR) goto exit; /* Reorder the sensors values: * * The values are laid out like this: * -, Y1, Y2, -, Y3, Y4, -, ..., -, X1, X2, -, X3, X4, ... * '-' is an unused value. */ /* read X values */ for (i = 0, j = 19; i < 20; i += 2, j += 3) { dev->xy_cur[i] = dev->data[j + 1]; dev->xy_cur[i + 1] = dev->data[j + 2]; } /* read Y values */ for (i = 0, j = 1; i < 9; i += 2, j += 3) { dev->xy_cur[ATP_XSENSORS + i] = dev->data[j + 1]; dev->xy_cur[ATP_XSENSORS + i + 1] = dev->data[j + 2]; } dbg_dump("sample", dev->xy_cur); /* Just update the base values (i.e. touchpad in untouched state) */ if (dev->data[dev->info->datalen - 1] & ATP_STATUS_BASE_UPDATE) { dprintk("appletouch: updated base values\n"); memcpy(dev->xy_old, dev->xy_cur, sizeof(dev->xy_old)); goto exit; } for (i = 0; i < ATP_XSENSORS + ATP_YSENSORS; i++) { /* calculate the change */ dev->xy_acc[i] = dev->xy_cur[i] - dev->xy_old[i]; /* this is a round-robin value, so couple with that */ if (dev->xy_acc[i] > 127) dev->xy_acc[i] -= 256; if (dev->xy_acc[i] < -127) dev->xy_acc[i] += 256; /* prevent down drifting */ if (dev->xy_acc[i] < 0) dev->xy_acc[i] = 0; } dbg_dump("accumulator", dev->xy_acc); x = atp_calculate_abs(dev, 0, ATP_XSENSORS, dev->info->xfact, &x_z, &x_f); y = atp_calculate_abs(dev, ATP_XSENSORS, ATP_YSENSORS, dev->info->yfact, &y_z, &y_f); key = dev->data[dev->info->datalen - 1] & ATP_STATUS_BUTTON; fingers = max(x_f, y_f); if (x && y && fingers == dev->fingers_old) { if (dev->x_old != -1) { x = (dev->x_old * 7 + x) >> 3; y = (dev->y_old * 7 + y) >> 3; dev->x_old = x; dev->y_old = y; if (debug > 1) printk(KERN_DEBUG "appletouch: X: %3d Y: %3d " "Xz: %3d Yz: %3d\n", x, y, x_z, y_z); input_report_key(dev->input, BTN_TOUCH, 1); input_report_abs(dev->input, ABS_X, x); input_report_abs(dev->input, ABS_Y, y); input_report_abs(dev->input, ABS_PRESSURE, min(ATP_PRESSURE, x_z + y_z)); atp_report_fingers(dev->input, fingers); } dev->x_old = x; dev->y_old = y; } else if (!x && !y) { dev->x_old = dev->y_old = -1; dev->fingers_old = 0; input_report_key(dev->input, BTN_TOUCH, 0); input_report_abs(dev->input, ABS_PRESSURE, 0); atp_report_fingers(dev->input, 0); /* reset the accumulator on release */ memset(dev->xy_acc, 0, sizeof(dev->xy_acc)); } if (fingers != dev->fingers_old) dev->x_old = dev->y_old = -1; dev->fingers_old = fingers; input_report_key(dev->input, BTN_LEFT, key); input_sync(dev->input); /* * Geysers 3/4 will continue to send packets continually after * the first touch unless reinitialised. Do so if it's been * idle for a while in order to avoid waking the kernel up * several hundred times a second. */ /* * Button must not be pressed when entering suspend, * otherwise we will never release the button. */ if (!x && !y && !key) { dev->idlecount++; if (dev->idlecount == 10) { dev->x_old = dev->y_old = -1; dev->idlecount = 0; schedule_work(&dev->work); /* Don't resubmit urb here, wait for reinit */ return; } } else dev->idlecount = 0; exit: retval = usb_submit_urb(dev->urb, GFP_ATOMIC); if (retval) dev_err(&dev->intf->dev, "atp_complete: usb_submit_urb failed with result %d\n", retval); } static int atp_open(struct input_dev *input) { struct atp *dev = input_get_drvdata(input); if (usb_submit_urb(dev->urb, GFP_KERNEL)) return -EIO; dev->open = true; return 0; } static void atp_close(struct input_dev *input) { struct atp *dev = input_get_drvdata(input); usb_kill_urb(dev->urb); cancel_work_sync(&dev->work); dev->open = false; } static int atp_handle_geyser(struct atp *dev) { if (dev->info != &fountain_info) { /* switch to raw sensor mode */ if (atp_geyser_init(dev)) return -EIO; dev_info(&dev->intf->dev, "Geyser mode initialized.\n"); } return 0; } static int atp_probe(struct usb_interface *iface, const struct usb_device_id *id) { struct atp *dev; struct input_dev *input_dev; struct usb_device *udev = interface_to_usbdev(iface); struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int int_in_endpointAddr = 0; int i, error = -ENOMEM; const struct atp_info *info = (const struct atp_info *)id->driver_info; /* set up the endpoint information */ /* use only the first interrupt-in endpoint */ iface_desc = iface->cur_altsetting; for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) { endpoint = &iface_desc->endpoint[i].desc; if (!int_in_endpointAddr && usb_endpoint_is_int_in(endpoint)) { /* we found an interrupt in endpoint */ int_in_endpointAddr = endpoint->bEndpointAddress; break; } } if (!int_in_endpointAddr) { dev_err(&iface->dev, "Could not find int-in endpoint\n"); return -EIO; } /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct atp), GFP_KERNEL); input_dev = input_allocate_device(); if (!dev || !input_dev) { dev_err(&iface->dev, "Out of memory\n"); goto err_free_devs; } dev->udev = udev; dev->intf = iface; dev->input = input_dev; dev->info = info; dev->overflow_warned = false; dev->urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->urb) goto err_free_devs; dev->data = usb_alloc_coherent(dev->udev, dev->info->datalen, GFP_KERNEL, &dev->urb->transfer_dma); if (!dev->data) goto err_free_urb; usb_fill_int_urb(dev->urb, udev, usb_rcvintpipe(udev, int_in_endpointAddr), dev->data, dev->info->datalen, dev->info->callback, dev, 1); error = atp_handle_geyser(dev); if (error) goto err_free_buffer; usb_make_path(udev, dev->phys, sizeof(dev->phys)); strlcat(dev->phys, "/input0", sizeof(dev->phys)); input_dev->name = "appletouch"; input_dev->phys = dev->phys; usb_to_input_id(dev->udev, &input_dev->id); input_dev->dev.parent = &iface->dev; input_set_drvdata(input_dev, dev); input_dev->open = atp_open; input_dev->close = atp_close; set_bit(EV_ABS, input_dev->evbit); input_set_abs_params(input_dev, ABS_X, 0, (dev->info->xsensors - 1) * dev->info->xfact - 1, dev->info->fuzz, 0); input_set_abs_params(input_dev, ABS_Y, 0, (dev->info->ysensors - 1) * dev->info->yfact - 1, dev->info->fuzz, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, ATP_PRESSURE, 0, 0); set_bit(EV_KEY, input_dev->evbit); set_bit(BTN_TOUCH, input_dev->keybit); set_bit(BTN_TOOL_FINGER, input_dev->keybit); set_bit(BTN_TOOL_DOUBLETAP, input_dev->keybit); set_bit(BTN_TOOL_TRIPLETAP, input_dev->keybit); set_bit(BTN_LEFT, input_dev->keybit); INIT_WORK(&dev->work, atp_reinit); error = input_register_device(dev->input); if (error) goto err_free_buffer; /* save our data pointer in this interface device */ usb_set_intfdata(iface, dev); return 0; err_free_buffer: usb_free_coherent(dev->udev, dev->info->datalen, dev->data, dev->urb->transfer_dma); err_free_urb: usb_free_urb(dev->urb); err_free_devs: usb_set_intfdata(iface, NULL); kfree(dev); input_free_device(input_dev); return error; } static void atp_disconnect(struct usb_interface *iface) { struct atp *dev = usb_get_intfdata(iface); usb_set_intfdata(iface, NULL); if (dev) { usb_kill_urb(dev->urb); input_unregister_device(dev->input); usb_free_coherent(dev->udev, dev->info->datalen, dev->data, dev->urb->transfer_dma); usb_free_urb(dev->urb); kfree(dev); } dev_info(&iface->dev, "input: appletouch disconnected\n"); } static int atp_recover(struct atp *dev) { int error; error = atp_handle_geyser(dev); if (error) return error; if (dev->open && usb_submit_urb(dev->urb, GFP_KERNEL)) return -EIO; return 0; } static int atp_suspend(struct usb_interface *iface, pm_message_t message) { struct atp *dev = usb_get_intfdata(iface); usb_kill_urb(dev->urb); return 0; } static int atp_resume(struct usb_interface *iface) { struct atp *dev = usb_get_intfdata(iface); if (dev->open && usb_submit_urb(dev->urb, GFP_KERNEL)) return -EIO; return 0; } static int atp_reset_resume(struct usb_interface *iface) { struct atp *dev = usb_get_intfdata(iface); return atp_recover(dev); } static struct usb_driver atp_driver = { .name = "appletouch", .probe = atp_probe, .disconnect = atp_disconnect, .suspend = atp_suspend, .resume = atp_resume, .reset_resume = atp_reset_resume, .id_table = atp_table, }; module_usb_driver(atp_driver);
linux-master
drivers/input/mouse/appletouch.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Apple USB BCM5974 (Macbook Air and Penryn Macbook Pro) multitouch driver * * Copyright (C) 2008 Henrik Rydberg ([email protected]) * Copyright (C) 2015 John Horan ([email protected]) * * The USB initialization and package decoding was made by * Scott Shawcroft as part of the touchd user-space driver project: * Copyright (C) 2008 Scott Shawcroft ([email protected]) * * The BCM5974 driver is based on the appletouch driver: * Copyright (C) 2001-2004 Greg Kroah-Hartman ([email protected]) * Copyright (C) 2005 Johannes Berg ([email protected]) * Copyright (C) 2005 Stelian Pop ([email protected]) * Copyright (C) 2005 Frank Arnold ([email protected]) * Copyright (C) 2005 Peter Osterlund ([email protected]) * Copyright (C) 2005 Michael Hanselmann ([email protected]) * Copyright (C) 2006 Nicolas Boichat ([email protected]) */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> #include <linux/hid.h> #include <linux/mutex.h> #include <linux/input/mt.h> #define USB_VENDOR_ID_APPLE 0x05ac /* MacbookAir, aka wellspring */ #define USB_DEVICE_ID_APPLE_WELLSPRING_ANSI 0x0223 #define USB_DEVICE_ID_APPLE_WELLSPRING_ISO 0x0224 #define USB_DEVICE_ID_APPLE_WELLSPRING_JIS 0x0225 /* MacbookProPenryn, aka wellspring2 */ #define USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI 0x0230 #define USB_DEVICE_ID_APPLE_WELLSPRING2_ISO 0x0231 #define USB_DEVICE_ID_APPLE_WELLSPRING2_JIS 0x0232 /* Macbook5,1 (unibody), aka wellspring3 */ #define USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI 0x0236 #define USB_DEVICE_ID_APPLE_WELLSPRING3_ISO 0x0237 #define USB_DEVICE_ID_APPLE_WELLSPRING3_JIS 0x0238 /* MacbookAir3,2 (unibody), aka wellspring5 */ #define USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI 0x023f #define USB_DEVICE_ID_APPLE_WELLSPRING4_ISO 0x0240 #define USB_DEVICE_ID_APPLE_WELLSPRING4_JIS 0x0241 /* MacbookAir3,1 (unibody), aka wellspring4 */ #define USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI 0x0242 #define USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO 0x0243 #define USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS 0x0244 /* Macbook8 (unibody, March 2011) */ #define USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI 0x0245 #define USB_DEVICE_ID_APPLE_WELLSPRING5_ISO 0x0246 #define USB_DEVICE_ID_APPLE_WELLSPRING5_JIS 0x0247 /* MacbookAir4,1 (unibody, July 2011) */ #define USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI 0x0249 #define USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO 0x024a #define USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS 0x024b /* MacbookAir4,2 (unibody, July 2011) */ #define USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI 0x024c #define USB_DEVICE_ID_APPLE_WELLSPRING6_ISO 0x024d #define USB_DEVICE_ID_APPLE_WELLSPRING6_JIS 0x024e /* Macbook8,2 (unibody) */ #define USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI 0x0252 #define USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO 0x0253 #define USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS 0x0254 /* MacbookPro10,1 (unibody, June 2012) */ #define USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI 0x0262 #define USB_DEVICE_ID_APPLE_WELLSPRING7_ISO 0x0263 #define USB_DEVICE_ID_APPLE_WELLSPRING7_JIS 0x0264 /* MacbookPro10,2 (unibody, October 2012) */ #define USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI 0x0259 #define USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO 0x025a #define USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS 0x025b /* MacbookAir6,2 (unibody, June 2013) */ #define USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI 0x0290 #define USB_DEVICE_ID_APPLE_WELLSPRING8_ISO 0x0291 #define USB_DEVICE_ID_APPLE_WELLSPRING8_JIS 0x0292 /* MacbookPro12,1 (2015) */ #define USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI 0x0272 #define USB_DEVICE_ID_APPLE_WELLSPRING9_ISO 0x0273 #define USB_DEVICE_ID_APPLE_WELLSPRING9_JIS 0x0274 #define BCM5974_DEVICE(prod) { \ .match_flags = (USB_DEVICE_ID_MATCH_DEVICE | \ USB_DEVICE_ID_MATCH_INT_CLASS | \ USB_DEVICE_ID_MATCH_INT_PROTOCOL), \ .idVendor = USB_VENDOR_ID_APPLE, \ .idProduct = (prod), \ .bInterfaceClass = USB_INTERFACE_CLASS_HID, \ .bInterfaceProtocol = USB_INTERFACE_PROTOCOL_MOUSE \ } /* table of devices that work with this driver */ static const struct usb_device_id bcm5974_table[] = { /* MacbookAir1.1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_JIS), /* MacbookProPenryn */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_JIS), /* Macbook5,1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_JIS), /* MacbookAir3,2 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_JIS), /* MacbookAir3,1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS), /* MacbookPro8 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_JIS), /* MacbookAir4,1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS), /* MacbookAir4,2 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING6_JIS), /* MacbookPro8,2 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS), /* MacbookPro10,1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7_JIS), /* MacbookPro10,2 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS), /* MacbookAir6,2 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING8_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING8_JIS), /* MacbookPro12,1 */ BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING9_ISO), BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING9_JIS), /* Terminating entry */ {} }; MODULE_DEVICE_TABLE(usb, bcm5974_table); MODULE_AUTHOR("Henrik Rydberg"); MODULE_DESCRIPTION("Apple USB BCM5974 multitouch driver"); MODULE_LICENSE("GPL"); #define dprintk(level, format, a...)\ { if (debug >= level) printk(KERN_DEBUG format, ##a); } static int debug = 1; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Activate debugging output"); /* button data structure */ struct bt_data { u8 unknown1; /* constant */ u8 button; /* left button */ u8 rel_x; /* relative x coordinate */ u8 rel_y; /* relative y coordinate */ }; /* trackpad header types */ enum tp_type { TYPE1, /* plain trackpad */ TYPE2, /* button integrated in trackpad */ TYPE3, /* additional header fields since June 2013 */ TYPE4 /* additional header field for pressure data */ }; /* trackpad finger data offsets, le16-aligned */ #define HEADER_TYPE1 (13 * sizeof(__le16)) #define HEADER_TYPE2 (15 * sizeof(__le16)) #define HEADER_TYPE3 (19 * sizeof(__le16)) #define HEADER_TYPE4 (23 * sizeof(__le16)) /* trackpad button data offsets */ #define BUTTON_TYPE1 0 #define BUTTON_TYPE2 15 #define BUTTON_TYPE3 23 #define BUTTON_TYPE4 31 /* list of device capability bits */ #define HAS_INTEGRATED_BUTTON 1 /* trackpad finger data block size */ #define FSIZE_TYPE1 (14 * sizeof(__le16)) #define FSIZE_TYPE2 (14 * sizeof(__le16)) #define FSIZE_TYPE3 (14 * sizeof(__le16)) #define FSIZE_TYPE4 (15 * sizeof(__le16)) /* offset from header to finger struct */ #define DELTA_TYPE1 (0 * sizeof(__le16)) #define DELTA_TYPE2 (0 * sizeof(__le16)) #define DELTA_TYPE3 (0 * sizeof(__le16)) #define DELTA_TYPE4 (1 * sizeof(__le16)) /* usb control message mode switch data */ #define USBMSG_TYPE1 8, 0x300, 0, 0, 0x1, 0x8 #define USBMSG_TYPE2 8, 0x300, 0, 0, 0x1, 0x8 #define USBMSG_TYPE3 8, 0x300, 0, 0, 0x1, 0x8 #define USBMSG_TYPE4 2, 0x302, 2, 1, 0x1, 0x0 /* Wellspring initialization constants */ #define BCM5974_WELLSPRING_MODE_READ_REQUEST_ID 1 #define BCM5974_WELLSPRING_MODE_WRITE_REQUEST_ID 9 /* trackpad finger structure, le16-aligned */ struct tp_finger { __le16 origin; /* zero when switching track finger */ __le16 abs_x; /* absolute x coodinate */ __le16 abs_y; /* absolute y coodinate */ __le16 rel_x; /* relative x coodinate */ __le16 rel_y; /* relative y coodinate */ __le16 tool_major; /* tool area, major axis */ __le16 tool_minor; /* tool area, minor axis */ __le16 orientation; /* 16384 when point, else 15 bit angle */ __le16 touch_major; /* touch area, major axis */ __le16 touch_minor; /* touch area, minor axis */ __le16 unused[2]; /* zeros */ __le16 pressure; /* pressure on forcetouch touchpad */ __le16 multi; /* one finger: varies, more fingers: constant */ } __attribute__((packed,aligned(2))); /* trackpad finger data size, empirically at least ten fingers */ #define MAX_FINGERS 16 #define MAX_FINGER_ORIENTATION 16384 /* device-specific parameters */ struct bcm5974_param { int snratio; /* signal-to-noise ratio */ int min; /* device minimum reading */ int max; /* device maximum reading */ }; /* device-specific configuration */ struct bcm5974_config { int ansi, iso, jis; /* the product id of this device */ int caps; /* device capability bitmask */ int bt_ep; /* the endpoint of the button interface */ int bt_datalen; /* data length of the button interface */ int tp_ep; /* the endpoint of the trackpad interface */ enum tp_type tp_type; /* type of trackpad interface */ int tp_header; /* bytes in header block */ int tp_datalen; /* data length of the trackpad interface */ int tp_button; /* offset to button data */ int tp_fsize; /* bytes in single finger block */ int tp_delta; /* offset from header to finger struct */ int um_size; /* usb control message length */ int um_req_val; /* usb control message value */ int um_req_idx; /* usb control message index */ int um_switch_idx; /* usb control message mode switch index */ int um_switch_on; /* usb control message mode switch on */ int um_switch_off; /* usb control message mode switch off */ struct bcm5974_param p; /* finger pressure limits */ struct bcm5974_param w; /* finger width limits */ struct bcm5974_param x; /* horizontal limits */ struct bcm5974_param y; /* vertical limits */ struct bcm5974_param o; /* orientation limits */ }; /* logical device structure */ struct bcm5974 { char phys[64]; struct usb_device *udev; /* usb device */ struct usb_interface *intf; /* our interface */ struct input_dev *input; /* input dev */ struct bcm5974_config cfg; /* device configuration */ struct mutex pm_mutex; /* serialize access to open/suspend */ int opened; /* 1: opened, 0: closed */ struct urb *bt_urb; /* button usb request block */ struct bt_data *bt_data; /* button transferred data */ struct urb *tp_urb; /* trackpad usb request block */ u8 *tp_data; /* trackpad transferred data */ const struct tp_finger *index[MAX_FINGERS]; /* finger index data */ struct input_mt_pos pos[MAX_FINGERS]; /* position array */ int slots[MAX_FINGERS]; /* slot assignments */ }; /* trackpad finger block data, le16-aligned */ static const struct tp_finger *get_tp_finger(const struct bcm5974 *dev, int i) { const struct bcm5974_config *c = &dev->cfg; u8 *f_base = dev->tp_data + c->tp_header + c->tp_delta; return (const struct tp_finger *)(f_base + i * c->tp_fsize); } #define DATAFORMAT(type) \ type, \ HEADER_##type, \ HEADER_##type + (MAX_FINGERS) * (FSIZE_##type), \ BUTTON_##type, \ FSIZE_##type, \ DELTA_##type, \ USBMSG_##type /* logical signal quality */ #define SN_PRESSURE 45 /* pressure signal-to-noise ratio */ #define SN_WIDTH 25 /* width signal-to-noise ratio */ #define SN_COORD 250 /* coordinate signal-to-noise ratio */ #define SN_ORIENT 10 /* orientation signal-to-noise ratio */ /* device constants */ static const struct bcm5974_config bcm5974_config_table[] = { { USB_DEVICE_ID_APPLE_WELLSPRING_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING_ISO, USB_DEVICE_ID_APPLE_WELLSPRING_JIS, 0, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE1), { SN_PRESSURE, 0, 256 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4824, 5342 }, { SN_COORD, -172, 5820 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING2_ISO, USB_DEVICE_ID_APPLE_WELLSPRING2_JIS, 0, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE1), { SN_PRESSURE, 0, 256 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4824, 4824 }, { SN_COORD, -172, 4290 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING3_ISO, USB_DEVICE_ID_APPLE_WELLSPRING3_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4460, 5166 }, { SN_COORD, -75, 6700 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING4_ISO, USB_DEVICE_ID_APPLE_WELLSPRING4_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4620, 5140 }, { SN_COORD, -150, 6600 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO, USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4616, 5112 }, { SN_COORD, -142, 5234 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING5_ISO, USB_DEVICE_ID_APPLE_WELLSPRING5_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4415, 5050 }, { SN_COORD, -55, 6680 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING6_ISO, USB_DEVICE_ID_APPLE_WELLSPRING6_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4620, 5140 }, { SN_COORD, -150, 6600 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO, USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4750, 5280 }, { SN_COORD, -150, 6730 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO, USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4620, 5140 }, { SN_COORD, -150, 6600 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING7_ISO, USB_DEVICE_ID_APPLE_WELLSPRING7_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4750, 5280 }, { SN_COORD, -150, 6730 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO, USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS, HAS_INTEGRATED_BUTTON, 0x84, sizeof(struct bt_data), 0x81, DATAFORMAT(TYPE2), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4750, 5280 }, { SN_COORD, -150, 6730 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING8_ISO, USB_DEVICE_ID_APPLE_WELLSPRING8_JIS, HAS_INTEGRATED_BUTTON, 0, sizeof(struct bt_data), 0x83, DATAFORMAT(TYPE3), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4620, 5140 }, { SN_COORD, -150, 6600 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, { USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI, USB_DEVICE_ID_APPLE_WELLSPRING9_ISO, USB_DEVICE_ID_APPLE_WELLSPRING9_JIS, HAS_INTEGRATED_BUTTON, 0, sizeof(struct bt_data), 0x83, DATAFORMAT(TYPE4), { SN_PRESSURE, 0, 300 }, { SN_WIDTH, 0, 2048 }, { SN_COORD, -4828, 5345 }, { SN_COORD, -203, 6803 }, { SN_ORIENT, -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION } }, {} }; /* return the device-specific configuration by device */ static const struct bcm5974_config *bcm5974_get_config(struct usb_device *udev) { u16 id = le16_to_cpu(udev->descriptor.idProduct); const struct bcm5974_config *cfg; for (cfg = bcm5974_config_table; cfg->ansi; ++cfg) if (cfg->ansi == id || cfg->iso == id || cfg->jis == id) return cfg; return bcm5974_config_table; } /* convert 16-bit little endian to signed integer */ static inline int raw2int(__le16 x) { return (signed short)le16_to_cpu(x); } static void set_abs(struct input_dev *input, unsigned int code, const struct bcm5974_param *p) { int fuzz = p->snratio ? (p->max - p->min) / p->snratio : 0; input_set_abs_params(input, code, p->min, p->max, fuzz, 0); } /* setup which logical events to report */ static void setup_events_to_report(struct input_dev *input_dev, const struct bcm5974_config *cfg) { __set_bit(EV_ABS, input_dev->evbit); /* for synaptics only */ input_set_abs_params(input_dev, ABS_PRESSURE, 0, 256, 5, 0); input_set_abs_params(input_dev, ABS_TOOL_WIDTH, 0, 16, 0, 0); /* finger touch area */ set_abs(input_dev, ABS_MT_TOUCH_MAJOR, &cfg->w); set_abs(input_dev, ABS_MT_TOUCH_MINOR, &cfg->w); /* finger approach area */ set_abs(input_dev, ABS_MT_WIDTH_MAJOR, &cfg->w); set_abs(input_dev, ABS_MT_WIDTH_MINOR, &cfg->w); /* finger orientation */ set_abs(input_dev, ABS_MT_ORIENTATION, &cfg->o); /* finger position */ set_abs(input_dev, ABS_MT_POSITION_X, &cfg->x); set_abs(input_dev, ABS_MT_POSITION_Y, &cfg->y); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_LEFT, input_dev->keybit); if (cfg->caps & HAS_INTEGRATED_BUTTON) __set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit); input_mt_init_slots(input_dev, MAX_FINGERS, INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED | INPUT_MT_TRACK); } /* report button data as logical button state */ static int report_bt_state(struct bcm5974 *dev, int size) { if (size != sizeof(struct bt_data)) return -EIO; dprintk(7, "bcm5974: button data: %x %x %x %x\n", dev->bt_data->unknown1, dev->bt_data->button, dev->bt_data->rel_x, dev->bt_data->rel_y); input_report_key(dev->input, BTN_LEFT, dev->bt_data->button); input_sync(dev->input); return 0; } static void report_finger_data(struct input_dev *input, int slot, const struct input_mt_pos *pos, const struct tp_finger *f) { input_mt_slot(input, slot); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); input_report_abs(input, ABS_MT_TOUCH_MAJOR, raw2int(f->touch_major) << 1); input_report_abs(input, ABS_MT_TOUCH_MINOR, raw2int(f->touch_minor) << 1); input_report_abs(input, ABS_MT_WIDTH_MAJOR, raw2int(f->tool_major) << 1); input_report_abs(input, ABS_MT_WIDTH_MINOR, raw2int(f->tool_minor) << 1); input_report_abs(input, ABS_MT_ORIENTATION, MAX_FINGER_ORIENTATION - raw2int(f->orientation)); input_report_abs(input, ABS_MT_POSITION_X, pos->x); input_report_abs(input, ABS_MT_POSITION_Y, pos->y); } static void report_synaptics_data(struct input_dev *input, const struct bcm5974_config *cfg, const struct tp_finger *f, int raw_n) { int abs_p = 0, abs_w = 0; if (raw_n) { int p = raw2int(f->touch_major); int w = raw2int(f->tool_major); if (p > 0 && raw2int(f->origin)) { abs_p = clamp_val(256 * p / cfg->p.max, 0, 255); abs_w = clamp_val(16 * w / cfg->w.max, 0, 15); } } input_report_abs(input, ABS_PRESSURE, abs_p); input_report_abs(input, ABS_TOOL_WIDTH, abs_w); } /* report trackpad data as logical trackpad state */ static int report_tp_state(struct bcm5974 *dev, int size) { const struct bcm5974_config *c = &dev->cfg; const struct tp_finger *f; struct input_dev *input = dev->input; int raw_n, i, n = 0; if (size < c->tp_header || (size - c->tp_header) % c->tp_fsize != 0) return -EIO; raw_n = (size - c->tp_header) / c->tp_fsize; for (i = 0; i < raw_n; i++) { f = get_tp_finger(dev, i); if (raw2int(f->touch_major) == 0) continue; dev->pos[n].x = raw2int(f->abs_x); dev->pos[n].y = c->y.min + c->y.max - raw2int(f->abs_y); dev->index[n++] = f; } input_mt_assign_slots(input, dev->slots, dev->pos, n, 0); for (i = 0; i < n; i++) report_finger_data(input, dev->slots[i], &dev->pos[i], dev->index[i]); input_mt_sync_frame(input); report_synaptics_data(input, c, get_tp_finger(dev, 0), raw_n); /* later types report button events via integrated button only */ if (c->caps & HAS_INTEGRATED_BUTTON) { int ibt = raw2int(dev->tp_data[c->tp_button]); input_report_key(input, BTN_LEFT, ibt); } input_sync(input); return 0; } static int bcm5974_wellspring_mode(struct bcm5974 *dev, bool on) { const struct bcm5974_config *c = &dev->cfg; int retval = 0, size; char *data; /* Type 3 does not require a mode switch */ if (c->tp_type == TYPE3) return 0; data = kmalloc(c->um_size, GFP_KERNEL); if (!data) { dev_err(&dev->intf->dev, "out of memory\n"); retval = -ENOMEM; goto out; } /* read configuration */ size = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), BCM5974_WELLSPRING_MODE_READ_REQUEST_ID, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE, c->um_req_val, c->um_req_idx, data, c->um_size, 5000); if (size != c->um_size) { dev_err(&dev->intf->dev, "could not read from device\n"); retval = -EIO; goto out; } /* apply the mode switch */ data[c->um_switch_idx] = on ? c->um_switch_on : c->um_switch_off; /* write configuration */ size = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), BCM5974_WELLSPRING_MODE_WRITE_REQUEST_ID, USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE, c->um_req_val, c->um_req_idx, data, c->um_size, 5000); if (size != c->um_size) { dev_err(&dev->intf->dev, "could not write to device\n"); retval = -EIO; goto out; } dprintk(2, "bcm5974: switched to %s mode.\n", on ? "wellspring" : "normal"); out: kfree(data); return retval; } static void bcm5974_irq_button(struct urb *urb) { struct bcm5974 *dev = urb->context; struct usb_interface *intf = dev->intf; int error; switch (urb->status) { case 0: break; case -EOVERFLOW: case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: dev_dbg(&intf->dev, "button urb shutting down: %d\n", urb->status); return; default: dev_dbg(&intf->dev, "button urb status: %d\n", urb->status); goto exit; } if (report_bt_state(dev, dev->bt_urb->actual_length)) dprintk(1, "bcm5974: bad button package, length: %d\n", dev->bt_urb->actual_length); exit: error = usb_submit_urb(dev->bt_urb, GFP_ATOMIC); if (error) dev_err(&intf->dev, "button urb failed: %d\n", error); } static void bcm5974_irq_trackpad(struct urb *urb) { struct bcm5974 *dev = urb->context; struct usb_interface *intf = dev->intf; int error; switch (urb->status) { case 0: break; case -EOVERFLOW: case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: dev_dbg(&intf->dev, "trackpad urb shutting down: %d\n", urb->status); return; default: dev_dbg(&intf->dev, "trackpad urb status: %d\n", urb->status); goto exit; } /* control response ignored */ if (dev->tp_urb->actual_length == 2) goto exit; if (report_tp_state(dev, dev->tp_urb->actual_length)) dprintk(1, "bcm5974: bad trackpad package, length: %d\n", dev->tp_urb->actual_length); exit: error = usb_submit_urb(dev->tp_urb, GFP_ATOMIC); if (error) dev_err(&intf->dev, "trackpad urb failed: %d\n", error); } /* * The Wellspring trackpad, like many recent Apple trackpads, share * the usb device with the keyboard. Since keyboards are usually * handled by the HID system, the device ends up being handled by two * modules. Setting up the device therefore becomes slightly * complicated. To enable multitouch features, a mode switch is * required, which is usually applied via the control interface of the * device. It can be argued where this switch should take place. In * some drivers, like appletouch, the switch is made during * probe. However, the hid module may also alter the state of the * device, resulting in trackpad malfunction under certain * circumstances. To get around this problem, there is at least one * example that utilizes the USB_QUIRK_RESET_RESUME quirk in order to * receive a reset_resume request rather than the normal resume. * Since the implementation of reset_resume is equal to mode switch * plus start_traffic, it seems easier to always do the switch when * starting traffic on the device. */ static int bcm5974_start_traffic(struct bcm5974 *dev) { int error; error = bcm5974_wellspring_mode(dev, true); if (error) { dprintk(1, "bcm5974: mode switch failed\n"); goto err_out; } if (dev->bt_urb) { error = usb_submit_urb(dev->bt_urb, GFP_KERNEL); if (error) goto err_reset_mode; } error = usb_submit_urb(dev->tp_urb, GFP_KERNEL); if (error) goto err_kill_bt; return 0; err_kill_bt: usb_kill_urb(dev->bt_urb); err_reset_mode: bcm5974_wellspring_mode(dev, false); err_out: return error; } static void bcm5974_pause_traffic(struct bcm5974 *dev) { usb_kill_urb(dev->tp_urb); usb_kill_urb(dev->bt_urb); bcm5974_wellspring_mode(dev, false); } /* * The code below implements open/close and manual suspend/resume. * All functions may be called in random order. * * Opening a suspended device fails with EACCES - permission denied. * * Failing a resume leaves the device resumed but closed. */ static int bcm5974_open(struct input_dev *input) { struct bcm5974 *dev = input_get_drvdata(input); int error; error = usb_autopm_get_interface(dev->intf); if (error) return error; mutex_lock(&dev->pm_mutex); error = bcm5974_start_traffic(dev); if (!error) dev->opened = 1; mutex_unlock(&dev->pm_mutex); if (error) usb_autopm_put_interface(dev->intf); return error; } static void bcm5974_close(struct input_dev *input) { struct bcm5974 *dev = input_get_drvdata(input); mutex_lock(&dev->pm_mutex); bcm5974_pause_traffic(dev); dev->opened = 0; mutex_unlock(&dev->pm_mutex); usb_autopm_put_interface(dev->intf); } static int bcm5974_suspend(struct usb_interface *iface, pm_message_t message) { struct bcm5974 *dev = usb_get_intfdata(iface); mutex_lock(&dev->pm_mutex); if (dev->opened) bcm5974_pause_traffic(dev); mutex_unlock(&dev->pm_mutex); return 0; } static int bcm5974_resume(struct usb_interface *iface) { struct bcm5974 *dev = usb_get_intfdata(iface); int error = 0; mutex_lock(&dev->pm_mutex); if (dev->opened) error = bcm5974_start_traffic(dev); mutex_unlock(&dev->pm_mutex); return error; } static int bcm5974_probe(struct usb_interface *iface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(iface); const struct bcm5974_config *cfg; struct bcm5974 *dev; struct input_dev *input_dev; int error = -ENOMEM; /* find the product index */ cfg = bcm5974_get_config(udev); /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct bcm5974), GFP_KERNEL); input_dev = input_allocate_device(); if (!dev || !input_dev) { dev_err(&iface->dev, "out of memory\n"); goto err_free_devs; } dev->udev = udev; dev->intf = iface; dev->input = input_dev; dev->cfg = *cfg; mutex_init(&dev->pm_mutex); /* setup urbs */ if (cfg->tp_type == TYPE1) { dev->bt_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->bt_urb) goto err_free_devs; } dev->tp_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->tp_urb) goto err_free_bt_urb; if (dev->bt_urb) { dev->bt_data = usb_alloc_coherent(dev->udev, dev->cfg.bt_datalen, GFP_KERNEL, &dev->bt_urb->transfer_dma); if (!dev->bt_data) goto err_free_urb; } dev->tp_data = usb_alloc_coherent(dev->udev, dev->cfg.tp_datalen, GFP_KERNEL, &dev->tp_urb->transfer_dma); if (!dev->tp_data) goto err_free_bt_buffer; if (dev->bt_urb) { usb_fill_int_urb(dev->bt_urb, udev, usb_rcvintpipe(udev, cfg->bt_ep), dev->bt_data, dev->cfg.bt_datalen, bcm5974_irq_button, dev, 1); dev->bt_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; } usb_fill_int_urb(dev->tp_urb, udev, usb_rcvintpipe(udev, cfg->tp_ep), dev->tp_data, dev->cfg.tp_datalen, bcm5974_irq_trackpad, dev, 1); dev->tp_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* create bcm5974 device */ usb_make_path(udev, dev->phys, sizeof(dev->phys)); strlcat(dev->phys, "/input0", sizeof(dev->phys)); input_dev->name = "bcm5974"; input_dev->phys = dev->phys; usb_to_input_id(dev->udev, &input_dev->id); /* report driver capabilities via the version field */ input_dev->id.version = cfg->caps; input_dev->dev.parent = &iface->dev; input_set_drvdata(input_dev, dev); input_dev->open = bcm5974_open; input_dev->close = bcm5974_close; setup_events_to_report(input_dev, cfg); error = input_register_device(dev->input); if (error) goto err_free_buffer; /* save our data pointer in this interface device */ usb_set_intfdata(iface, dev); return 0; err_free_buffer: usb_free_coherent(dev->udev, dev->cfg.tp_datalen, dev->tp_data, dev->tp_urb->transfer_dma); err_free_bt_buffer: if (dev->bt_urb) usb_free_coherent(dev->udev, dev->cfg.bt_datalen, dev->bt_data, dev->bt_urb->transfer_dma); err_free_urb: usb_free_urb(dev->tp_urb); err_free_bt_urb: usb_free_urb(dev->bt_urb); err_free_devs: usb_set_intfdata(iface, NULL); input_free_device(input_dev); kfree(dev); return error; } static void bcm5974_disconnect(struct usb_interface *iface) { struct bcm5974 *dev = usb_get_intfdata(iface); usb_set_intfdata(iface, NULL); input_unregister_device(dev->input); usb_free_coherent(dev->udev, dev->cfg.tp_datalen, dev->tp_data, dev->tp_urb->transfer_dma); if (dev->bt_urb) usb_free_coherent(dev->udev, dev->cfg.bt_datalen, dev->bt_data, dev->bt_urb->transfer_dma); usb_free_urb(dev->tp_urb); usb_free_urb(dev->bt_urb); kfree(dev); } static struct usb_driver bcm5974_driver = { .name = "bcm5974", .probe = bcm5974_probe, .disconnect = bcm5974_disconnect, .suspend = bcm5974_suspend, .resume = bcm5974_resume, .id_table = bcm5974_table, .supports_autosuspend = 1, }; module_usb_driver(bcm5974_driver);
linux-master
drivers/input/mouse/bcm5974.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 1999-2001 Vojtech Pavlik * * Based on the work of: * James Banks Matthew Dillon * David Giller Nathan Laredo * Linus Torvalds Johan Myreen * Cliff Matthews Philip Blundell * Russell King */ /* * Logitech Bus Mouse Driver for Linux */ #include <linux/module.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <asm/io.h> #include <asm/irq.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Logitech busmouse driver"); MODULE_LICENSE("GPL"); #define LOGIBM_BASE 0x23c #define LOGIBM_EXTENT 4 #define LOGIBM_DATA_PORT LOGIBM_BASE + 0 #define LOGIBM_SIGNATURE_PORT LOGIBM_BASE + 1 #define LOGIBM_CONTROL_PORT LOGIBM_BASE + 2 #define LOGIBM_CONFIG_PORT LOGIBM_BASE + 3 #define LOGIBM_ENABLE_IRQ 0x00 #define LOGIBM_DISABLE_IRQ 0x10 #define LOGIBM_READ_X_LOW 0x80 #define LOGIBM_READ_X_HIGH 0xa0 #define LOGIBM_READ_Y_LOW 0xc0 #define LOGIBM_READ_Y_HIGH 0xe0 #define LOGIBM_DEFAULT_MODE 0x90 #define LOGIBM_CONFIG_BYTE 0x91 #define LOGIBM_SIGNATURE_BYTE 0xa5 #define LOGIBM_IRQ 5 static int logibm_irq = LOGIBM_IRQ; module_param_hw_named(irq, logibm_irq, uint, irq, 0); MODULE_PARM_DESC(irq, "IRQ number (5=default)"); static struct input_dev *logibm_dev; static irqreturn_t logibm_interrupt(int irq, void *dev_id) { char dx, dy; unsigned char buttons; outb(LOGIBM_READ_X_LOW, LOGIBM_CONTROL_PORT); dx = (inb(LOGIBM_DATA_PORT) & 0xf); outb(LOGIBM_READ_X_HIGH, LOGIBM_CONTROL_PORT); dx |= (inb(LOGIBM_DATA_PORT) & 0xf) << 4; outb(LOGIBM_READ_Y_LOW, LOGIBM_CONTROL_PORT); dy = (inb(LOGIBM_DATA_PORT) & 0xf); outb(LOGIBM_READ_Y_HIGH, LOGIBM_CONTROL_PORT); buttons = inb(LOGIBM_DATA_PORT); dy |= (buttons & 0xf) << 4; buttons = ~buttons >> 5; input_report_rel(logibm_dev, REL_X, dx); input_report_rel(logibm_dev, REL_Y, dy); input_report_key(logibm_dev, BTN_RIGHT, buttons & 1); input_report_key(logibm_dev, BTN_MIDDLE, buttons & 2); input_report_key(logibm_dev, BTN_LEFT, buttons & 4); input_sync(logibm_dev); outb(LOGIBM_ENABLE_IRQ, LOGIBM_CONTROL_PORT); return IRQ_HANDLED; } static int logibm_open(struct input_dev *dev) { if (request_irq(logibm_irq, logibm_interrupt, 0, "logibm", NULL)) { printk(KERN_ERR "logibm.c: Can't allocate irq %d\n", logibm_irq); return -EBUSY; } outb(LOGIBM_ENABLE_IRQ, LOGIBM_CONTROL_PORT); return 0; } static void logibm_close(struct input_dev *dev) { outb(LOGIBM_DISABLE_IRQ, LOGIBM_CONTROL_PORT); free_irq(logibm_irq, NULL); } static int __init logibm_init(void) { int err; if (!request_region(LOGIBM_BASE, LOGIBM_EXTENT, "logibm")) { printk(KERN_ERR "logibm.c: Can't allocate ports at %#x\n", LOGIBM_BASE); return -EBUSY; } outb(LOGIBM_CONFIG_BYTE, LOGIBM_CONFIG_PORT); outb(LOGIBM_SIGNATURE_BYTE, LOGIBM_SIGNATURE_PORT); udelay(100); if (inb(LOGIBM_SIGNATURE_PORT) != LOGIBM_SIGNATURE_BYTE) { printk(KERN_INFO "logibm.c: Didn't find Logitech busmouse at %#x\n", LOGIBM_BASE); err = -ENODEV; goto err_release_region; } outb(LOGIBM_DEFAULT_MODE, LOGIBM_CONFIG_PORT); outb(LOGIBM_DISABLE_IRQ, LOGIBM_CONTROL_PORT); logibm_dev = input_allocate_device(); if (!logibm_dev) { printk(KERN_ERR "logibm.c: Not enough memory for input device\n"); err = -ENOMEM; goto err_release_region; } logibm_dev->name = "Logitech bus mouse"; logibm_dev->phys = "isa023c/input0"; logibm_dev->id.bustype = BUS_ISA; logibm_dev->id.vendor = 0x0003; logibm_dev->id.product = 0x0001; logibm_dev->id.version = 0x0100; logibm_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); logibm_dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT); logibm_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); logibm_dev->open = logibm_open; logibm_dev->close = logibm_close; err = input_register_device(logibm_dev); if (err) goto err_free_dev; return 0; err_free_dev: input_free_device(logibm_dev); err_release_region: release_region(LOGIBM_BASE, LOGIBM_EXTENT); return err; } static void __exit logibm_exit(void) { input_unregister_device(logibm_dev); release_region(LOGIBM_BASE, LOGIBM_EXTENT); } module_init(logibm_init); module_exit(logibm_exit);
linux-master
drivers/input/mouse/logibm.c
// SPDX-License-Identifier: GPL-2.0-only /* * Elan I2C/SMBus Touchpad driver - I2C interface * * Copyright (c) 2013 ELAN Microelectronics Corp. * * Author: 林政維 (Duson Lin) <[email protected]> * * Based on cyapa driver: * copyright (c) 2011-2012 Cypress Semiconductor, Inc. * copyright (c) 2011-2012 Google, Inc. * * Trademarks are the property of their respective owners. */ #include <linux/completion.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/sched.h> #include <asm/unaligned.h> #include "elan_i2c.h" /* Elan i2c commands */ #define ETP_I2C_RESET 0x0100 #define ETP_I2C_WAKE_UP 0x0800 #define ETP_I2C_SLEEP 0x0801 #define ETP_I2C_DESC_CMD 0x0001 #define ETP_I2C_REPORT_DESC_CMD 0x0002 #define ETP_I2C_STAND_CMD 0x0005 #define ETP_I2C_PATTERN_CMD 0x0100 #define ETP_I2C_UNIQUEID_CMD 0x0101 #define ETP_I2C_FW_VERSION_CMD 0x0102 #define ETP_I2C_IC_TYPE_CMD 0x0103 #define ETP_I2C_OSM_VERSION_CMD 0x0103 #define ETP_I2C_NSM_VERSION_CMD 0x0104 #define ETP_I2C_XY_TRACENUM_CMD 0x0105 #define ETP_I2C_MAX_X_AXIS_CMD 0x0106 #define ETP_I2C_MAX_Y_AXIS_CMD 0x0107 #define ETP_I2C_RESOLUTION_CMD 0x0108 #define ETP_I2C_PRESSURE_CMD 0x010A #define ETP_I2C_IAP_VERSION_CMD 0x0110 #define ETP_I2C_IC_TYPE_P0_CMD 0x0110 #define ETP_I2C_IAP_VERSION_P0_CMD 0x0111 #define ETP_I2C_SET_CMD 0x0300 #define ETP_I2C_POWER_CMD 0x0307 #define ETP_I2C_FW_CHECKSUM_CMD 0x030F #define ETP_I2C_IAP_CTRL_CMD 0x0310 #define ETP_I2C_IAP_CMD 0x0311 #define ETP_I2C_IAP_RESET_CMD 0x0314 #define ETP_I2C_IAP_CHECKSUM_CMD 0x0315 #define ETP_I2C_CALIBRATE_CMD 0x0316 #define ETP_I2C_MAX_BASELINE_CMD 0x0317 #define ETP_I2C_MIN_BASELINE_CMD 0x0318 #define ETP_I2C_IAP_TYPE_REG 0x0040 #define ETP_I2C_IAP_TYPE_CMD 0x0304 #define ETP_I2C_REPORT_LEN 34 #define ETP_I2C_REPORT_LEN_ID2 39 #define ETP_I2C_REPORT_MAX_LEN 39 #define ETP_I2C_DESC_LENGTH 30 #define ETP_I2C_REPORT_DESC_LENGTH 158 #define ETP_I2C_INF_LENGTH 2 #define ETP_I2C_IAP_PASSWORD 0x1EA5 #define ETP_I2C_IAP_RESET 0xF0F0 #define ETP_I2C_MAIN_MODE_ON (1 << 9) #define ETP_I2C_IAP_REG_L 0x01 #define ETP_I2C_IAP_REG_H 0x06 static int elan_i2c_read_block(struct i2c_client *client, u16 reg, u8 *val, u16 len) { __le16 buf[] = { cpu_to_le16(reg), }; struct i2c_msg msgs[] = { { .addr = client->addr, .flags = client->flags & I2C_M_TEN, .len = sizeof(buf), .buf = (u8 *)buf, }, { .addr = client->addr, .flags = (client->flags & I2C_M_TEN) | I2C_M_RD, .len = len, .buf = val, } }; int ret; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); return ret == ARRAY_SIZE(msgs) ? 0 : (ret < 0 ? ret : -EIO); } static int elan_i2c_read_cmd(struct i2c_client *client, u16 reg, u8 *val) { int retval; retval = elan_i2c_read_block(client, reg, val, ETP_I2C_INF_LENGTH); if (retval < 0) { dev_err(&client->dev, "reading cmd (0x%04x) fail.\n", reg); return retval; } return 0; } static int elan_i2c_write_cmd(struct i2c_client *client, u16 reg, u16 cmd) { __le16 buf[] = { cpu_to_le16(reg), cpu_to_le16(cmd), }; struct i2c_msg msg = { .addr = client->addr, .flags = client->flags & I2C_M_TEN, .len = sizeof(buf), .buf = (u8 *)buf, }; int ret; ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) { if (ret >= 0) ret = -EIO; dev_err(&client->dev, "writing cmd (0x%04x) failed: %d\n", reg, ret); return ret; } return 0; } static int elan_i2c_initialize(struct i2c_client *client) { struct device *dev = &client->dev; int error; u8 val[256]; error = elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, ETP_I2C_RESET); if (error) { dev_err(dev, "device reset failed: %d\n", error); return error; } /* Wait for the device to reset */ msleep(100); /* get reset acknowledgement 0000 */ error = i2c_master_recv(client, val, ETP_I2C_INF_LENGTH); if (error < 0) { dev_err(dev, "failed to read reset response: %d\n", error); return error; } error = elan_i2c_read_block(client, ETP_I2C_DESC_CMD, val, ETP_I2C_DESC_LENGTH); if (error) { dev_err(dev, "cannot get device descriptor: %d\n", error); return error; } error = elan_i2c_read_block(client, ETP_I2C_REPORT_DESC_CMD, val, ETP_I2C_REPORT_DESC_LENGTH); if (error) { dev_err(dev, "fetching report descriptor failed.: %d\n", error); return error; } return 0; } static int elan_i2c_sleep_control(struct i2c_client *client, bool sleep) { return elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, sleep ? ETP_I2C_SLEEP : ETP_I2C_WAKE_UP); } static int elan_i2c_power_control(struct i2c_client *client, bool enable) { u8 val[2]; u16 reg; int error; error = elan_i2c_read_cmd(client, ETP_I2C_POWER_CMD, val); if (error) { dev_err(&client->dev, "failed to read current power state: %d\n", error); return error; } reg = le16_to_cpup((__le16 *)val); if (enable) reg &= ~ETP_DISABLE_POWER; else reg |= ETP_DISABLE_POWER; error = elan_i2c_write_cmd(client, ETP_I2C_POWER_CMD, reg); if (error) { dev_err(&client->dev, "failed to write current power state: %d\n", error); return error; } return 0; } static int elan_i2c_set_mode(struct i2c_client *client, u8 mode) { return elan_i2c_write_cmd(client, ETP_I2C_SET_CMD, mode); } static int elan_i2c_calibrate(struct i2c_client *client) { return elan_i2c_write_cmd(client, ETP_I2C_CALIBRATE_CMD, 1); } static int elan_i2c_calibrate_result(struct i2c_client *client, u8 *val) { return elan_i2c_read_block(client, ETP_I2C_CALIBRATE_CMD, val, 1); } static int elan_i2c_get_baseline_data(struct i2c_client *client, bool max_baseline, u8 *value) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, max_baseline ? ETP_I2C_MAX_BASELINE_CMD : ETP_I2C_MIN_BASELINE_CMD, val); if (error) return error; *value = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_pattern(struct i2c_client *client, u8 *pattern) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_PATTERN_CMD, val); if (error) { dev_err(&client->dev, "failed to get pattern: %d\n", error); return error; } /* * Not all versions of firmware implement "get pattern" command. * When this command is not implemented the device will respond * with 0xFF 0xFF, which we will treat as "old" pattern 0. */ *pattern = val[0] == 0xFF && val[1] == 0xFF ? 0 : val[1]; return 0; } static int elan_i2c_get_version(struct i2c_client *client, u8 pattern, bool iap, u8 *version) { int error; u16 cmd; u8 val[3]; if (!iap) cmd = ETP_I2C_FW_VERSION_CMD; else if (pattern == 0) cmd = ETP_I2C_IAP_VERSION_P0_CMD; else cmd = ETP_I2C_IAP_VERSION_CMD; error = elan_i2c_read_cmd(client, cmd, val); if (error) { dev_err(&client->dev, "failed to get %s version: %d\n", iap ? "IAP" : "FW", error); return error; } if (pattern >= 0x01) *version = iap ? val[1] : val[0]; else *version = val[0]; return 0; } static int elan_i2c_get_sm_version(struct i2c_client *client, u8 pattern, u16 *ic_type, u8 *version, u8 *clickpad) { int error; u8 val[3]; if (pattern >= 0x01) { error = elan_i2c_read_cmd(client, ETP_I2C_IC_TYPE_CMD, val); if (error) { dev_err(&client->dev, "failed to get ic type: %d\n", error); return error; } *ic_type = be16_to_cpup((__be16 *)val); error = elan_i2c_read_cmd(client, ETP_I2C_NSM_VERSION_CMD, val); if (error) { dev_err(&client->dev, "failed to get SM version: %d\n", error); return error; } *version = val[1]; *clickpad = val[0] & 0x10; } else { error = elan_i2c_read_cmd(client, ETP_I2C_OSM_VERSION_CMD, val); if (error) { dev_err(&client->dev, "failed to get SM version: %d\n", error); return error; } *version = val[0]; error = elan_i2c_read_cmd(client, ETP_I2C_IC_TYPE_P0_CMD, val); if (error) { dev_err(&client->dev, "failed to get ic type: %d\n", error); return error; } *ic_type = val[0]; error = elan_i2c_read_cmd(client, ETP_I2C_NSM_VERSION_CMD, val); if (error) { dev_err(&client->dev, "failed to get SM version: %d\n", error); return error; } *clickpad = val[0] & 0x10; } return 0; } static int elan_i2c_get_product_id(struct i2c_client *client, u16 *id) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_UNIQUEID_CMD, val); if (error) { dev_err(&client->dev, "failed to get product ID: %d\n", error); return error; } *id = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_checksum(struct i2c_client *client, bool iap, u16 *csum) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, iap ? ETP_I2C_IAP_CHECKSUM_CMD : ETP_I2C_FW_CHECKSUM_CMD, val); if (error) { dev_err(&client->dev, "failed to get %s checksum: %d\n", iap ? "IAP" : "FW", error); return error; } *csum = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_max(struct i2c_client *client, unsigned int *max_x, unsigned int *max_y) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_MAX_X_AXIS_CMD, val); if (error) { dev_err(&client->dev, "failed to get X dimension: %d\n", error); return error; } *max_x = le16_to_cpup((__le16 *)val); error = elan_i2c_read_cmd(client, ETP_I2C_MAX_Y_AXIS_CMD, val); if (error) { dev_err(&client->dev, "failed to get Y dimension: %d\n", error); return error; } *max_y = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_resolution(struct i2c_client *client, u8 *hw_res_x, u8 *hw_res_y) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_RESOLUTION_CMD, val); if (error) { dev_err(&client->dev, "failed to get resolution: %d\n", error); return error; } *hw_res_x = val[0]; *hw_res_y = val[1]; return 0; } static int elan_i2c_get_num_traces(struct i2c_client *client, unsigned int *x_traces, unsigned int *y_traces) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_XY_TRACENUM_CMD, val); if (error) { dev_err(&client->dev, "failed to get trace info: %d\n", error); return error; } *x_traces = val[0]; *y_traces = val[1]; return 0; } static int elan_i2c_get_pressure_adjustment(struct i2c_client *client, int *adjustment) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_PRESSURE_CMD, val); if (error) { dev_err(&client->dev, "failed to get pressure format: %d\n", error); return error; } if ((val[0] >> 4) & 0x1) *adjustment = 0; else *adjustment = ETP_PRESSURE_OFFSET; return 0; } static int elan_i2c_iap_get_mode(struct i2c_client *client, enum tp_mode *mode) { int error; u16 constant; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CTRL_CMD, val); if (error) { dev_err(&client->dev, "failed to read iap control register: %d\n", error); return error; } constant = le16_to_cpup((__le16 *)val); dev_dbg(&client->dev, "iap control reg: 0x%04x.\n", constant); *mode = (constant & ETP_I2C_MAIN_MODE_ON) ? MAIN_MODE : IAP_MODE; return 0; } static int elan_i2c_iap_reset(struct i2c_client *client) { int error; error = elan_i2c_write_cmd(client, ETP_I2C_IAP_RESET_CMD, ETP_I2C_IAP_RESET); if (error) { dev_err(&client->dev, "cannot reset IC: %d\n", error); return error; } return 0; } static int elan_i2c_set_flash_key(struct i2c_client *client) { int error; error = elan_i2c_write_cmd(client, ETP_I2C_IAP_CMD, ETP_I2C_IAP_PASSWORD); if (error) { dev_err(&client->dev, "cannot set flash key: %d\n", error); return error; } return 0; } static int elan_read_write_iap_type(struct i2c_client *client, u16 fw_page_size) { int error; u16 constant; u8 val[3]; int retry = 3; do { error = elan_i2c_write_cmd(client, ETP_I2C_IAP_TYPE_CMD, fw_page_size / 2); if (error) { dev_err(&client->dev, "cannot write iap type: %d\n", error); return error; } error = elan_i2c_read_cmd(client, ETP_I2C_IAP_TYPE_CMD, val); if (error) { dev_err(&client->dev, "failed to read iap type register: %d\n", error); return error; } constant = le16_to_cpup((__le16 *)val); dev_dbg(&client->dev, "iap type reg: 0x%04x\n", constant); if (constant == fw_page_size / 2) return 0; } while (--retry > 0); dev_err(&client->dev, "cannot set iap type\n"); return -EIO; } static int elan_i2c_prepare_fw_update(struct i2c_client *client, u16 ic_type, u8 iap_version, u16 fw_page_size) { struct device *dev = &client->dev; int error; enum tp_mode mode; u8 val[3]; u16 password; /* Get FW in which mode (IAP_MODE/MAIN_MODE) */ error = elan_i2c_iap_get_mode(client, &mode); if (error) return error; if (mode == IAP_MODE) { /* Reset IC */ error = elan_i2c_iap_reset(client); if (error) return error; msleep(30); } /* Set flash key*/ error = elan_i2c_set_flash_key(client); if (error) return error; /* Wait for F/W IAP initialization */ msleep(mode == MAIN_MODE ? 100 : 30); /* Check if we are in IAP mode or not */ error = elan_i2c_iap_get_mode(client, &mode); if (error) return error; if (mode == MAIN_MODE) { dev_err(dev, "wrong mode: %d\n", mode); return -EIO; } if (ic_type >= 0x0D && iap_version >= 1) { error = elan_read_write_iap_type(client, fw_page_size); if (error) return error; } /* Set flash key again */ error = elan_i2c_set_flash_key(client); if (error) return error; /* Wait for F/W IAP initialization */ msleep(30); /* read back to check we actually enabled successfully. */ error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CMD, val); if (error) { dev_err(dev, "cannot read iap password: %d\n", error); return error; } password = le16_to_cpup((__le16 *)val); if (password != ETP_I2C_IAP_PASSWORD) { dev_err(dev, "wrong iap password: 0x%X\n", password); return -EIO; } return 0; } static int elan_i2c_write_fw_block(struct i2c_client *client, u16 fw_page_size, const u8 *page, u16 checksum, int idx) { struct device *dev = &client->dev; u8 *page_store; u8 val[3]; u16 result; int ret, error; page_store = kmalloc(fw_page_size + 4, GFP_KERNEL); if (!page_store) return -ENOMEM; page_store[0] = ETP_I2C_IAP_REG_L; page_store[1] = ETP_I2C_IAP_REG_H; memcpy(&page_store[2], page, fw_page_size); /* recode checksum at last two bytes */ put_unaligned_le16(checksum, &page_store[fw_page_size + 2]); ret = i2c_master_send(client, page_store, fw_page_size + 4); if (ret != fw_page_size + 4) { error = ret < 0 ? ret : -EIO; dev_err(dev, "Failed to write page %d: %d\n", idx, error); goto exit; } /* Wait for F/W to update one page ROM data. */ msleep(fw_page_size == ETP_FW_PAGE_SIZE_512 ? 50 : 35); error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CTRL_CMD, val); if (error) { dev_err(dev, "Failed to read IAP write result: %d\n", error); goto exit; } result = le16_to_cpup((__le16 *)val); if (result & (ETP_FW_IAP_PAGE_ERR | ETP_FW_IAP_INTF_ERR)) { dev_err(dev, "IAP reports failed write: %04hx\n", result); error = -EIO; goto exit; } exit: kfree(page_store); return error; } static int elan_i2c_finish_fw_update(struct i2c_client *client, struct completion *completion) { struct device *dev = &client->dev; int error = 0; int len; u8 buffer[ETP_I2C_REPORT_MAX_LEN]; len = i2c_master_recv(client, buffer, ETP_I2C_REPORT_MAX_LEN); if (len <= 0) { error = len < 0 ? len : -EIO; dev_warn(dev, "failed to read I2C data after FW WDT reset: %d (%d)\n", error, len); } reinit_completion(completion); enable_irq(client->irq); error = elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, ETP_I2C_RESET); if (error) { dev_err(dev, "device reset failed: %d\n", error); } else if (!wait_for_completion_timeout(completion, msecs_to_jiffies(300))) { dev_err(dev, "timeout waiting for device reset\n"); error = -ETIMEDOUT; } disable_irq(client->irq); if (error) return error; len = i2c_master_recv(client, buffer, ETP_I2C_INF_LENGTH); if (len != ETP_I2C_INF_LENGTH) { error = len < 0 ? len : -EIO; dev_err(dev, "failed to read INT signal: %d (%d)\n", error, len); return error; } return 0; } static int elan_i2c_get_report_features(struct i2c_client *client, u8 pattern, unsigned int *features, unsigned int *report_len) { *features = ETP_FEATURE_REPORT_MK; *report_len = pattern <= 0x01 ? ETP_I2C_REPORT_LEN : ETP_I2C_REPORT_LEN_ID2; return 0; } static int elan_i2c_get_report(struct i2c_client *client, u8 *report, unsigned int report_len) { int len; len = i2c_master_recv(client, report, report_len); if (len < 0) { dev_err(&client->dev, "failed to read report data: %d\n", len); return len; } if (len != report_len) { dev_err(&client->dev, "wrong report length (%d vs %d expected)\n", len, report_len); return -EIO; } return 0; } const struct elan_transport_ops elan_i2c_ops = { .initialize = elan_i2c_initialize, .sleep_control = elan_i2c_sleep_control, .power_control = elan_i2c_power_control, .set_mode = elan_i2c_set_mode, .calibrate = elan_i2c_calibrate, .calibrate_result = elan_i2c_calibrate_result, .get_baseline_data = elan_i2c_get_baseline_data, .get_version = elan_i2c_get_version, .get_sm_version = elan_i2c_get_sm_version, .get_product_id = elan_i2c_get_product_id, .get_checksum = elan_i2c_get_checksum, .get_pressure_adjustment = elan_i2c_get_pressure_adjustment, .get_max = elan_i2c_get_max, .get_resolution = elan_i2c_get_resolution, .get_num_traces = elan_i2c_get_num_traces, .iap_get_mode = elan_i2c_iap_get_mode, .iap_reset = elan_i2c_iap_reset, .prepare_fw_update = elan_i2c_prepare_fw_update, .write_fw_block = elan_i2c_write_fw_block, .finish_fw_update = elan_i2c_finish_fw_update, .get_pattern = elan_i2c_get_pattern, .get_report_features = elan_i2c_get_report_features, .get_report = elan_i2c_get_report, };
linux-master
drivers/input/mouse/elan_i2c_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Fujitsu B-series Lifebook PS/2 TouchScreen driver * * Copyright (c) 2005 Vojtech Pavlik <[email protected]> * Copyright (c) 2005 Kenan Esau <[email protected]> * * TouchScreen detection, absolute mode setting and packet layout is taken from * Harald Hoyer's description of the device. */ #include <linux/input.h> #include <linux/serio.h> #include <linux/libps2.h> #include <linux/dmi.h> #include <linux/slab.h> #include <linux/types.h> #include "psmouse.h" #include "lifebook.h" struct lifebook_data { struct input_dev *dev2; /* Relative device */ char phys[32]; }; static bool lifebook_present; static const char *desired_serio_phys; static int lifebook_limit_serio3(const struct dmi_system_id *d) { desired_serio_phys = "isa0060/serio3"; return 1; } static bool lifebook_use_6byte_proto; static int lifebook_set_6byte_proto(const struct dmi_system_id *d) { lifebook_use_6byte_proto = true; return 1; } static const struct dmi_system_id lifebook_dmi_table[] __initconst = { { /* FLORA-ie 55mi */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "FLORA-ie 55mi"), }, }, { /* LifeBook B */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "Lifebook B Series"), }, }, { /* LifeBook B */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "LifeBook B Series"), }, }, { /* Lifebook B */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK B Series"), }, }, { /* Lifebook B-2130 */ .matches = { DMI_MATCH(DMI_BOARD_NAME, "ZEPHYR"), }, }, { /* Lifebook B213x/B2150 */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "LifeBook B2131/B2133/B2150"), }, }, { /* Zephyr */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "ZEPHYR"), }, }, { /* Panasonic CF-18 */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "CF-18"), }, .callback = lifebook_limit_serio3, }, { /* Panasonic CF-28 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Matsushita"), DMI_MATCH(DMI_PRODUCT_NAME, "CF-28"), }, .callback = lifebook_set_6byte_proto, }, { /* Panasonic CF-29 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Matsushita"), DMI_MATCH(DMI_PRODUCT_NAME, "CF-29"), }, .callback = lifebook_set_6byte_proto, }, { /* Panasonic CF-72 */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "CF-72"), }, .callback = lifebook_set_6byte_proto, }, { /* Lifebook B142 */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "LifeBook B142"), }, }, { } }; void __init lifebook_module_init(void) { lifebook_present = dmi_check_system(lifebook_dmi_table); } static psmouse_ret_t lifebook_process_byte(struct psmouse *psmouse) { struct lifebook_data *priv = psmouse->private; struct input_dev *dev1 = psmouse->dev; struct input_dev *dev2 = priv ? priv->dev2 : NULL; u8 *packet = psmouse->packet; bool relative_packet = packet[0] & 0x08; if (relative_packet || !lifebook_use_6byte_proto) { if (psmouse->pktcnt != 3) return PSMOUSE_GOOD_DATA; } else { switch (psmouse->pktcnt) { case 1: return (packet[0] & 0xf8) == 0x00 ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; case 2: return PSMOUSE_GOOD_DATA; case 3: return ((packet[2] & 0x30) << 2) == (packet[2] & 0xc0) ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; case 4: return (packet[3] & 0xf8) == 0xc0 ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; case 5: return (packet[4] & 0xc0) == (packet[2] & 0xc0) ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; case 6: if (((packet[5] & 0x30) << 2) != (packet[5] & 0xc0)) return PSMOUSE_BAD_DATA; if ((packet[5] & 0xc0) != (packet[1] & 0xc0)) return PSMOUSE_BAD_DATA; break; /* report data */ } } if (relative_packet) { if (!dev2) psmouse_warn(psmouse, "got relative packet but no relative device set up\n"); } else { if (lifebook_use_6byte_proto) { input_report_abs(dev1, ABS_X, ((packet[1] & 0x3f) << 6) | (packet[2] & 0x3f)); input_report_abs(dev1, ABS_Y, 4096 - (((packet[4] & 0x3f) << 6) | (packet[5] & 0x3f))); } else { input_report_abs(dev1, ABS_X, (packet[1] | ((packet[0] & 0x30) << 4))); input_report_abs(dev1, ABS_Y, 1024 - (packet[2] | ((packet[0] & 0xC0) << 2))); } input_report_key(dev1, BTN_TOUCH, packet[0] & 0x04); input_sync(dev1); } if (dev2) { if (relative_packet) psmouse_report_standard_motion(dev2, packet); psmouse_report_standard_buttons(dev2, packet[0]); input_sync(dev2); } return PSMOUSE_FULL_PACKET; } static int lifebook_absolute_mode(struct psmouse *psmouse) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param; int error; error = psmouse_reset(psmouse); if (error) return error; /* * Enable absolute output -- ps2_command fails always but if * you leave this call out the touchscreen will never send * absolute coordinates */ param = lifebook_use_6byte_proto ? 0x08 : 0x07; ps2_command(ps2dev, &param, PSMOUSE_CMD_SETRES); return 0; } static void lifebook_relative_mode(struct psmouse *psmouse) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param = 0x06; ps2_command(ps2dev, &param, PSMOUSE_CMD_SETRES); } static void lifebook_set_resolution(struct psmouse *psmouse, unsigned int resolution) { static const u8 params[] = { 0, 1, 2, 2, 3 }; u8 p; if (resolution == 0 || resolution > 400) resolution = 400; p = params[resolution / 100]; ps2_command(&psmouse->ps2dev, &p, PSMOUSE_CMD_SETRES); psmouse->resolution = 50 << p; } static void lifebook_disconnect(struct psmouse *psmouse) { struct lifebook_data *priv = psmouse->private; psmouse_reset(psmouse); if (priv) { input_unregister_device(priv->dev2); kfree(priv); } psmouse->private = NULL; } int lifebook_detect(struct psmouse *psmouse, bool set_properties) { if (!lifebook_present) return -ENXIO; if (desired_serio_phys && strcmp(psmouse->ps2dev.serio->phys, desired_serio_phys)) return -ENXIO; if (set_properties) { psmouse->vendor = "Fujitsu"; psmouse->name = "Lifebook TouchScreen"; } return 0; } static int lifebook_create_relative_device(struct psmouse *psmouse) { struct input_dev *dev2; struct lifebook_data *priv; int error = -ENOMEM; priv = kzalloc(sizeof(struct lifebook_data), GFP_KERNEL); dev2 = input_allocate_device(); if (!priv || !dev2) goto err_out; priv->dev2 = dev2; snprintf(priv->phys, sizeof(priv->phys), "%s/input1", psmouse->ps2dev.serio->phys); dev2->phys = priv->phys; dev2->name = "LBPS/2 Fujitsu Lifebook Touchpad"; dev2->id.bustype = BUS_I8042; dev2->id.vendor = 0x0002; dev2->id.product = PSMOUSE_LIFEBOOK; dev2->id.version = 0x0000; dev2->dev.parent = &psmouse->ps2dev.serio->dev; input_set_capability(dev2, EV_REL, REL_X); input_set_capability(dev2, EV_REL, REL_Y); input_set_capability(dev2, EV_KEY, BTN_LEFT); input_set_capability(dev2, EV_KEY, BTN_RIGHT); error = input_register_device(priv->dev2); if (error) goto err_out; psmouse->private = priv; return 0; err_out: input_free_device(dev2); kfree(priv); return error; } int lifebook_init(struct psmouse *psmouse) { struct input_dev *dev1 = psmouse->dev; int max_coord = lifebook_use_6byte_proto ? 4096 : 1024; int error; error = lifebook_absolute_mode(psmouse); if (error) return error; /* Clear default capabilities */ bitmap_zero(dev1->evbit, EV_CNT); bitmap_zero(dev1->relbit, REL_CNT); bitmap_zero(dev1->keybit, KEY_CNT); input_set_capability(dev1, EV_KEY, BTN_TOUCH); input_set_abs_params(dev1, ABS_X, 0, max_coord, 0, 0); input_set_abs_params(dev1, ABS_Y, 0, max_coord, 0, 0); if (!desired_serio_phys) { error = lifebook_create_relative_device(psmouse); if (error) { lifebook_relative_mode(psmouse); return error; } } psmouse->protocol_handler = lifebook_process_byte; psmouse->set_resolution = lifebook_set_resolution; psmouse->disconnect = lifebook_disconnect; psmouse->reconnect = lifebook_absolute_mode; psmouse->model = lifebook_use_6byte_proto ? 6 : 3; /* * Use packet size = 3 even when using 6-byte protocol because * that's what POLL will return on Lifebooks (according to spec). */ psmouse->pktsize = 3; return 0; }
linux-master
drivers/input/mouse/lifebook.c
/* * Synaptics touchpad with I2C interface * * Copyright (C) 2009 Compulab, Ltd. * Mike Rapoport <[email protected]> * Igor Grinberg <[email protected]> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/slab.h> #include <linux/pm.h> #define DRIVER_NAME "synaptics_i2c" /* maximum product id is 15 characters */ #define PRODUCT_ID_LENGTH 15 #define REGISTER_LENGTH 8 /* * after soft reset, we should wait for 1 ms * before the device becomes operational */ #define SOFT_RESET_DELAY_US 3000 /* and after hard reset, we should wait for max 500ms */ #define HARD_RESET_DELAY_MS 500 /* Registers by SMBus address */ #define PAGE_SEL_REG 0xff #define DEVICE_STATUS_REG 0x09 /* Registers by RMI address */ #define DEV_CONTROL_REG 0x0000 #define INTERRUPT_EN_REG 0x0001 #define ERR_STAT_REG 0x0002 #define INT_REQ_STAT_REG 0x0003 #define DEV_COMMAND_REG 0x0004 #define RMI_PROT_VER_REG 0x0200 #define MANUFACT_ID_REG 0x0201 #define PHYS_INT_VER_REG 0x0202 #define PROD_PROPERTY_REG 0x0203 #define INFO_QUERY_REG0 0x0204 #define INFO_QUERY_REG1 (INFO_QUERY_REG0 + 1) #define INFO_QUERY_REG2 (INFO_QUERY_REG0 + 2) #define INFO_QUERY_REG3 (INFO_QUERY_REG0 + 3) #define PRODUCT_ID_REG0 0x0210 #define PRODUCT_ID_REG1 (PRODUCT_ID_REG0 + 1) #define PRODUCT_ID_REG2 (PRODUCT_ID_REG0 + 2) #define PRODUCT_ID_REG3 (PRODUCT_ID_REG0 + 3) #define PRODUCT_ID_REG4 (PRODUCT_ID_REG0 + 4) #define PRODUCT_ID_REG5 (PRODUCT_ID_REG0 + 5) #define PRODUCT_ID_REG6 (PRODUCT_ID_REG0 + 6) #define PRODUCT_ID_REG7 (PRODUCT_ID_REG0 + 7) #define PRODUCT_ID_REG8 (PRODUCT_ID_REG0 + 8) #define PRODUCT_ID_REG9 (PRODUCT_ID_REG0 + 9) #define PRODUCT_ID_REG10 (PRODUCT_ID_REG0 + 10) #define PRODUCT_ID_REG11 (PRODUCT_ID_REG0 + 11) #define PRODUCT_ID_REG12 (PRODUCT_ID_REG0 + 12) #define PRODUCT_ID_REG13 (PRODUCT_ID_REG0 + 13) #define PRODUCT_ID_REG14 (PRODUCT_ID_REG0 + 14) #define PRODUCT_ID_REG15 (PRODUCT_ID_REG0 + 15) #define DATA_REG0 0x0400 #define ABS_PRESSURE_REG 0x0401 #define ABS_MSB_X_REG 0x0402 #define ABS_LSB_X_REG (ABS_MSB_X_REG + 1) #define ABS_MSB_Y_REG 0x0404 #define ABS_LSB_Y_REG (ABS_MSB_Y_REG + 1) #define REL_X_REG 0x0406 #define REL_Y_REG 0x0407 #define DEV_QUERY_REG0 0x1000 #define DEV_QUERY_REG1 (DEV_QUERY_REG0 + 1) #define DEV_QUERY_REG2 (DEV_QUERY_REG0 + 2) #define DEV_QUERY_REG3 (DEV_QUERY_REG0 + 3) #define DEV_QUERY_REG4 (DEV_QUERY_REG0 + 4) #define DEV_QUERY_REG5 (DEV_QUERY_REG0 + 5) #define DEV_QUERY_REG6 (DEV_QUERY_REG0 + 6) #define DEV_QUERY_REG7 (DEV_QUERY_REG0 + 7) #define DEV_QUERY_REG8 (DEV_QUERY_REG0 + 8) #define GENERAL_2D_CONTROL_REG 0x1041 #define SENSOR_SENSITIVITY_REG 0x1044 #define SENS_MAX_POS_MSB_REG 0x1046 #define SENS_MAX_POS_LSB_REG (SENS_MAX_POS_UPPER_REG + 1) /* Register bits */ /* Device Control Register Bits */ #define REPORT_RATE_1ST_BIT 6 /* Interrupt Enable Register Bits (INTERRUPT_EN_REG) */ #define F10_ABS_INT_ENA 0 #define F10_REL_INT_ENA 1 #define F20_INT_ENA 2 /* Interrupt Request Register Bits (INT_REQ_STAT_REG | DEVICE_STATUS_REG) */ #define F10_ABS_INT_REQ 0 #define F10_REL_INT_REQ 1 #define F20_INT_REQ 2 /* Device Status Register Bits (DEVICE_STATUS_REG) */ #define STAT_CONFIGURED 6 #define STAT_ERROR 7 /* Device Command Register Bits (DEV_COMMAND_REG) */ #define RESET_COMMAND 0x01 #define REZERO_COMMAND 0x02 /* Data Register 0 Bits (DATA_REG0) */ #define GESTURE 3 /* Device Query Registers Bits */ /* DEV_QUERY_REG3 */ #define HAS_PALM_DETECT 1 #define HAS_MULTI_FING 2 #define HAS_SCROLLER 4 #define HAS_2D_SCROLL 5 /* General 2D Control Register Bits (GENERAL_2D_CONTROL_REG) */ #define NO_DECELERATION 1 #define REDUCE_REPORTING 3 #define NO_FILTER 5 /* Function Masks */ /* Device Control Register Masks (DEV_CONTROL_REG) */ #define REPORT_RATE_MSK 0xc0 #define SLEEP_MODE_MSK 0x07 /* Device Sleep Modes */ #define FULL_AWAKE 0x0 #define NORMAL_OP 0x1 #define LOW_PWR_OP 0x2 #define VERY_LOW_PWR_OP 0x3 #define SENS_SLEEP 0x4 #define SLEEP_MOD 0x5 #define DEEP_SLEEP 0x6 #define HIBERNATE 0x7 /* Interrupt Register Mask */ /* (INT_REQ_STAT_REG | DEVICE_STATUS_REG | INTERRUPT_EN_REG) */ #define INT_ENA_REQ_MSK 0x07 #define INT_ENA_ABS_MSK 0x01 #define INT_ENA_REL_MSK 0x02 #define INT_ENA_F20_MSK 0x04 /* Device Status Register Masks (DEVICE_STATUS_REG) */ #define CONFIGURED_MSK 0x40 #define ERROR_MSK 0x80 /* Data Register 0 Masks */ #define FINGER_WIDTH_MSK 0xf0 #define GESTURE_MSK 0x08 #define SENSOR_STATUS_MSK 0x07 /* * MSB Position Register Masks * ABS_MSB_X_REG | ABS_MSB_Y_REG | SENS_MAX_POS_MSB_REG | * DEV_QUERY_REG3 | DEV_QUERY_REG5 */ #define MSB_POSITION_MSK 0x1f /* Device Query Registers Masks */ /* DEV_QUERY_REG2 */ #define NUM_EXTRA_POS_MSK 0x07 /* When in IRQ mode read the device every THREAD_IRQ_SLEEP_SECS */ #define THREAD_IRQ_SLEEP_SECS 2 #define THREAD_IRQ_SLEEP_MSECS (THREAD_IRQ_SLEEP_SECS * MSEC_PER_SEC) /* * When in Polling mode and no data received for NO_DATA_THRES msecs * reduce the polling rate to NO_DATA_SLEEP_MSECS */ #define NO_DATA_THRES (MSEC_PER_SEC) #define NO_DATA_SLEEP_MSECS (MSEC_PER_SEC / 4) /* Control touchpad's No Deceleration option */ static bool no_decel = true; module_param(no_decel, bool, 0644); MODULE_PARM_DESC(no_decel, "No Deceleration. Default = 1 (on)"); /* Control touchpad's Reduced Reporting option */ static bool reduce_report; module_param(reduce_report, bool, 0644); MODULE_PARM_DESC(reduce_report, "Reduced Reporting. Default = 0 (off)"); /* Control touchpad's No Filter option */ static bool no_filter; module_param(no_filter, bool, 0644); MODULE_PARM_DESC(no_filter, "No Filter. Default = 0 (off)"); /* * touchpad Attention line is Active Low and Open Drain, * therefore should be connected to pulled up line * and the irq configuration should be set to Falling Edge Trigger */ /* Control IRQ / Polling option */ static bool polling_req; module_param(polling_req, bool, 0444); MODULE_PARM_DESC(polling_req, "Request Polling. Default = 0 (use irq)"); /* Control Polling Rate */ static int scan_rate = 80; module_param(scan_rate, int, 0644); MODULE_PARM_DESC(scan_rate, "Polling rate in times/sec. Default = 80"); /* The main device structure */ struct synaptics_i2c { struct i2c_client *client; struct input_dev *input; struct delayed_work dwork; int no_data_count; int no_decel_param; int reduce_report_param; int no_filter_param; int scan_rate_param; int scan_ms; }; static inline void set_scan_rate(struct synaptics_i2c *touch, int scan_rate) { touch->scan_ms = MSEC_PER_SEC / scan_rate; touch->scan_rate_param = scan_rate; } /* * Driver's initial design makes no race condition possible on i2c bus, * so there is no need in any locking. * Keep it in mind, while playing with the code. */ static s32 synaptics_i2c_reg_get(struct i2c_client *client, u16 reg) { int ret; ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8); if (ret == 0) ret = i2c_smbus_read_byte_data(client, reg & 0xff); return ret; } static s32 synaptics_i2c_reg_set(struct i2c_client *client, u16 reg, u8 val) { int ret; ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8); if (ret == 0) ret = i2c_smbus_write_byte_data(client, reg & 0xff, val); return ret; } static s32 synaptics_i2c_word_get(struct i2c_client *client, u16 reg) { int ret; ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8); if (ret == 0) ret = i2c_smbus_read_word_data(client, reg & 0xff); return ret; } static int synaptics_i2c_config(struct i2c_client *client) { int ret, control; u8 int_en; /* set Report Rate to Device Highest (>=80) and Sleep to normal */ ret = synaptics_i2c_reg_set(client, DEV_CONTROL_REG, 0xc1); if (ret) return ret; /* set Interrupt Disable to Func20 / Enable to Func10) */ int_en = (polling_req) ? 0 : INT_ENA_ABS_MSK | INT_ENA_REL_MSK; ret = synaptics_i2c_reg_set(client, INTERRUPT_EN_REG, int_en); if (ret) return ret; control = synaptics_i2c_reg_get(client, GENERAL_2D_CONTROL_REG); /* No Deceleration */ control |= no_decel ? 1 << NO_DECELERATION : 0; /* Reduced Reporting */ control |= reduce_report ? 1 << REDUCE_REPORTING : 0; /* No Filter */ control |= no_filter ? 1 << NO_FILTER : 0; ret = synaptics_i2c_reg_set(client, GENERAL_2D_CONTROL_REG, control); if (ret) return ret; return 0; } static int synaptics_i2c_reset_config(struct i2c_client *client) { int ret; /* Reset the Touchpad */ ret = synaptics_i2c_reg_set(client, DEV_COMMAND_REG, RESET_COMMAND); if (ret) { dev_err(&client->dev, "Unable to reset device\n"); } else { usleep_range(SOFT_RESET_DELAY_US, SOFT_RESET_DELAY_US + 100); ret = synaptics_i2c_config(client); if (ret) dev_err(&client->dev, "Unable to config device\n"); } return ret; } static int synaptics_i2c_check_error(struct i2c_client *client) { int status, ret = 0; status = i2c_smbus_read_byte_data(client, DEVICE_STATUS_REG) & (CONFIGURED_MSK | ERROR_MSK); if (status != CONFIGURED_MSK) ret = synaptics_i2c_reset_config(client); return ret; } static bool synaptics_i2c_get_input(struct synaptics_i2c *touch) { struct input_dev *input = touch->input; int xy_delta, gesture; s32 data; s8 x_delta, y_delta; /* Deal with spontaneous resets and errors */ if (synaptics_i2c_check_error(touch->client)) return false; /* Get Gesture Bit */ data = synaptics_i2c_reg_get(touch->client, DATA_REG0); gesture = (data >> GESTURE) & 0x1; /* * Get Relative axes. we have to get them in one shot, * so we get 2 bytes starting from REL_X_REG. */ xy_delta = synaptics_i2c_word_get(touch->client, REL_X_REG) & 0xffff; /* Separate X from Y */ x_delta = xy_delta & 0xff; y_delta = (xy_delta >> REGISTER_LENGTH) & 0xff; /* Report the button event */ input_report_key(input, BTN_LEFT, gesture); /* Report the deltas */ input_report_rel(input, REL_X, x_delta); input_report_rel(input, REL_Y, -y_delta); input_sync(input); return xy_delta || gesture; } static irqreturn_t synaptics_i2c_irq(int irq, void *dev_id) { struct synaptics_i2c *touch = dev_id; mod_delayed_work(system_wq, &touch->dwork, 0); return IRQ_HANDLED; } static void synaptics_i2c_check_params(struct synaptics_i2c *touch) { bool reset = false; if (scan_rate != touch->scan_rate_param) set_scan_rate(touch, scan_rate); if (no_decel != touch->no_decel_param) { touch->no_decel_param = no_decel; reset = true; } if (no_filter != touch->no_filter_param) { touch->no_filter_param = no_filter; reset = true; } if (reduce_report != touch->reduce_report_param) { touch->reduce_report_param = reduce_report; reset = true; } if (reset) synaptics_i2c_reset_config(touch->client); } /* Control the Device polling rate / Work Handler sleep time */ static unsigned long synaptics_i2c_adjust_delay(struct synaptics_i2c *touch, bool have_data) { unsigned long delay, nodata_count_thres; if (polling_req) { delay = touch->scan_ms; if (have_data) { touch->no_data_count = 0; } else { nodata_count_thres = NO_DATA_THRES / touch->scan_ms; if (touch->no_data_count < nodata_count_thres) touch->no_data_count++; else delay = NO_DATA_SLEEP_MSECS; } return msecs_to_jiffies(delay); } else { delay = msecs_to_jiffies(THREAD_IRQ_SLEEP_MSECS); return round_jiffies_relative(delay); } } /* Work Handler */ static void synaptics_i2c_work_handler(struct work_struct *work) { bool have_data; struct synaptics_i2c *touch = container_of(work, struct synaptics_i2c, dwork.work); unsigned long delay; synaptics_i2c_check_params(touch); have_data = synaptics_i2c_get_input(touch); delay = synaptics_i2c_adjust_delay(touch, have_data); /* * While interrupt driven, there is no real need to poll the device. * But touchpads are very sensitive, so there could be errors * related to physical environment and the attention line isn't * necessarily asserted. In such case we can lose the touchpad. * We poll the device once in THREAD_IRQ_SLEEP_SECS and * if error is detected, we try to reset and reconfigure the touchpad. */ mod_delayed_work(system_wq, &touch->dwork, delay); } static int synaptics_i2c_open(struct input_dev *input) { struct synaptics_i2c *touch = input_get_drvdata(input); int ret; ret = synaptics_i2c_reset_config(touch->client); if (ret) return ret; if (polling_req) mod_delayed_work(system_wq, &touch->dwork, msecs_to_jiffies(NO_DATA_SLEEP_MSECS)); return 0; } static void synaptics_i2c_close(struct input_dev *input) { struct synaptics_i2c *touch = input_get_drvdata(input); if (!polling_req) synaptics_i2c_reg_set(touch->client, INTERRUPT_EN_REG, 0); cancel_delayed_work_sync(&touch->dwork); /* Save some power */ synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP); } static void synaptics_i2c_set_input_params(struct synaptics_i2c *touch) { struct input_dev *input = touch->input; input->name = touch->client->name; input->phys = touch->client->adapter->name; input->id.bustype = BUS_I2C; input->id.version = synaptics_i2c_word_get(touch->client, INFO_QUERY_REG0); input->dev.parent = &touch->client->dev; input->open = synaptics_i2c_open; input->close = synaptics_i2c_close; input_set_drvdata(input, touch); /* Register the device as mouse */ __set_bit(EV_REL, input->evbit); __set_bit(REL_X, input->relbit); __set_bit(REL_Y, input->relbit); /* Register device's buttons and keys */ __set_bit(EV_KEY, input->evbit); __set_bit(BTN_LEFT, input->keybit); } static struct synaptics_i2c *synaptics_i2c_touch_create(struct i2c_client *client) { struct synaptics_i2c *touch; touch = kzalloc(sizeof(struct synaptics_i2c), GFP_KERNEL); if (!touch) return NULL; touch->client = client; touch->no_decel_param = no_decel; touch->scan_rate_param = scan_rate; set_scan_rate(touch, scan_rate); INIT_DELAYED_WORK(&touch->dwork, synaptics_i2c_work_handler); return touch; } static int synaptics_i2c_probe(struct i2c_client *client) { int ret; struct synaptics_i2c *touch; touch = synaptics_i2c_touch_create(client); if (!touch) return -ENOMEM; ret = synaptics_i2c_reset_config(client); if (ret) goto err_mem_free; if (client->irq < 1) polling_req = true; touch->input = input_allocate_device(); if (!touch->input) { ret = -ENOMEM; goto err_mem_free; } synaptics_i2c_set_input_params(touch); if (!polling_req) { dev_dbg(&touch->client->dev, "Requesting IRQ: %d\n", touch->client->irq); ret = request_irq(touch->client->irq, synaptics_i2c_irq, IRQ_TYPE_EDGE_FALLING, DRIVER_NAME, touch); if (ret) { dev_warn(&touch->client->dev, "IRQ request failed: %d, " "falling back to polling\n", ret); polling_req = true; synaptics_i2c_reg_set(touch->client, INTERRUPT_EN_REG, 0); } } if (polling_req) dev_dbg(&touch->client->dev, "Using polling at rate: %d times/sec\n", scan_rate); /* Register the device in input subsystem */ ret = input_register_device(touch->input); if (ret) { dev_err(&client->dev, "Input device register failed: %d\n", ret); goto err_input_free; } i2c_set_clientdata(client, touch); return 0; err_input_free: input_free_device(touch->input); err_mem_free: kfree(touch); return ret; } static void synaptics_i2c_remove(struct i2c_client *client) { struct synaptics_i2c *touch = i2c_get_clientdata(client); if (!polling_req) free_irq(client->irq, touch); input_unregister_device(touch->input); kfree(touch); } static int synaptics_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct synaptics_i2c *touch = i2c_get_clientdata(client); cancel_delayed_work_sync(&touch->dwork); /* Save some power */ synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP); return 0; } static int synaptics_i2c_resume(struct device *dev) { int ret; struct i2c_client *client = to_i2c_client(dev); struct synaptics_i2c *touch = i2c_get_clientdata(client); ret = synaptics_i2c_reset_config(client); if (ret) return ret; mod_delayed_work(system_wq, &touch->dwork, msecs_to_jiffies(NO_DATA_SLEEP_MSECS)); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(synaptics_i2c_pm, synaptics_i2c_suspend, synaptics_i2c_resume); static const struct i2c_device_id synaptics_i2c_id_table[] = { { "synaptics_i2c", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, synaptics_i2c_id_table); #ifdef CONFIG_OF static const struct of_device_id synaptics_i2c_of_match[] = { { .compatible = "synaptics,synaptics_i2c", }, { }, }; MODULE_DEVICE_TABLE(of, synaptics_i2c_of_match); #endif static struct i2c_driver synaptics_i2c_driver = { .driver = { .name = DRIVER_NAME, .of_match_table = of_match_ptr(synaptics_i2c_of_match), .pm = pm_sleep_ptr(&synaptics_i2c_pm), }, .probe = synaptics_i2c_probe, .remove = synaptics_i2c_remove, .id_table = synaptics_i2c_id_table, }; module_i2c_driver(synaptics_i2c_driver); MODULE_DESCRIPTION("Synaptics I2C touchpad driver"); MODULE_AUTHOR("Mike Rapoport, Igor Grinberg, Compulab"); MODULE_LICENSE("GPL");
linux-master
drivers/input/mouse/synaptics_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Amiga mouse driver for Linux/m68k * * Copyright (c) 2000-2002 Vojtech Pavlik * * Based on the work of: * Michael Rausch James Banks * Matther Dillon David Giller * Nathan Laredo Linus Torvalds * Johan Myreen Jes Sorensen * Russell King */ #include <linux/module.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <asm/irq.h> #include <asm/setup.h> #include <linux/uaccess.h> #include <asm/amigahw.h> #include <asm/amigaints.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Amiga mouse driver"); MODULE_LICENSE("GPL"); static int amimouse_lastx, amimouse_lasty; static irqreturn_t amimouse_interrupt(int irq, void *data) { struct input_dev *dev = data; unsigned short joy0dat, potgor; int nx, ny, dx, dy; joy0dat = amiga_custom.joy0dat; nx = joy0dat & 0xff; ny = joy0dat >> 8; dx = nx - amimouse_lastx; dy = ny - amimouse_lasty; if (dx < -127) dx = (256 + nx) - amimouse_lastx; if (dx > 127) dx = (nx - 256) - amimouse_lastx; if (dy < -127) dy = (256 + ny) - amimouse_lasty; if (dy > 127) dy = (ny - 256) - amimouse_lasty; amimouse_lastx = nx; amimouse_lasty = ny; potgor = amiga_custom.potgor; input_report_rel(dev, REL_X, dx); input_report_rel(dev, REL_Y, dy); input_report_key(dev, BTN_LEFT, ciaa.pra & 0x40); input_report_key(dev, BTN_MIDDLE, potgor & 0x0100); input_report_key(dev, BTN_RIGHT, potgor & 0x0400); input_sync(dev); return IRQ_HANDLED; } static int amimouse_open(struct input_dev *dev) { unsigned short joy0dat; int error; joy0dat = amiga_custom.joy0dat; amimouse_lastx = joy0dat & 0xff; amimouse_lasty = joy0dat >> 8; error = request_irq(IRQ_AMIGA_VERTB, amimouse_interrupt, 0, "amimouse", dev); if (error) dev_err(&dev->dev, "Can't allocate irq %d\n", IRQ_AMIGA_VERTB); return error; } static void amimouse_close(struct input_dev *dev) { free_irq(IRQ_AMIGA_VERTB, dev); } static int __init amimouse_probe(struct platform_device *pdev) { int err; struct input_dev *dev; dev = input_allocate_device(); if (!dev) return -ENOMEM; dev->name = pdev->name; dev->phys = "amimouse/input0"; dev->id.bustype = BUS_AMIGA; dev->id.vendor = 0x0001; dev->id.product = 0x0002; dev->id.version = 0x0100; dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT); dev->open = amimouse_open; dev->close = amimouse_close; dev->dev.parent = &pdev->dev; err = input_register_device(dev); if (err) { input_free_device(dev); return err; } platform_set_drvdata(pdev, dev); return 0; } static int __exit amimouse_remove(struct platform_device *pdev) { struct input_dev *dev = platform_get_drvdata(pdev); input_unregister_device(dev); return 0; } static struct platform_driver amimouse_driver = { .remove = __exit_p(amimouse_remove), .driver = { .name = "amiga-mouse", }, }; module_platform_driver_probe(amimouse_driver, amimouse_probe); MODULE_ALIAS("platform:amiga-mouse");
linux-master
drivers/input/mouse/amimouse.c
// SPDX-License-Identifier: GPL-2.0-only /* * Synaptics TouchPad PS/2 mouse driver * * 2003 Dmitry Torokhov <[email protected]> * Added support for pass-through port. Special thanks to Peter Berg Larsen * for explaining various Synaptics quirks. * * 2003 Peter Osterlund <[email protected]> * Ported to 2.5 input device infrastructure. * * Copyright (C) 2001 Stefan Gmeiner <[email protected]> * start merging tpconfig and gpm code to a xfree-input module * adding some changes and extensions (ex. 3rd and 4th button) * * Copyright (c) 1997 C. Scott Ananian <[email protected]> * Copyright (c) 1998-2000 Bruce Kalk <[email protected]> * code for the special synaptics commands (from the tpconfig-source) * * Trademarks are the property of their respective owners. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/dmi.h> #include <linux/input/mt.h> #include <linux/serio.h> #include <linux/libps2.h> #include <linux/rmi.h> #include <linux/i2c.h> #include <linux/slab.h> #include "psmouse.h" #include "synaptics.h" /* * The x/y limits are taken from the Synaptics TouchPad interfacing Guide, * section 2.3.2, which says that they should be valid regardless of the * actual size of the sensor. * Note that newer firmware allows querying device for maximum useable * coordinates. */ #define XMIN 0 #define XMAX 6143 #define YMIN 0 #define YMAX 6143 #define XMIN_NOMINAL 1472 #define XMAX_NOMINAL 5472 #define YMIN_NOMINAL 1408 #define YMAX_NOMINAL 4448 /* Size in bits of absolute position values reported by the hardware */ #define ABS_POS_BITS 13 /* * These values should represent the absolute maximum value that will * be reported for a positive position value. Some Synaptics firmware * uses this value to indicate a finger near the edge of the touchpad * whose precise position cannot be determined. * * At least one touchpad is known to report positions in excess of this * value which are actually negative values truncated to the 13-bit * reporting range. These values have never been observed to be lower * than 8184 (i.e. -8), so we treat all values greater than 8176 as * negative and any other value as positive. */ #define X_MAX_POSITIVE 8176 #define Y_MAX_POSITIVE 8176 /* maximum ABS_MT_POSITION displacement (in mm) */ #define DMAX 10 /***************************************************************************** * Stuff we need even when we do not want native Synaptics support ****************************************************************************/ /* * Set the synaptics touchpad mode byte by special commands */ static int synaptics_mode_cmd(struct psmouse *psmouse, u8 mode) { u8 param[1]; int error; error = ps2_sliced_command(&psmouse->ps2dev, mode); if (error) return error; param[0] = SYN_PS_SET_MODE2; error = ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_SETRATE); if (error) return error; return 0; } int synaptics_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; u8 param[4] = { 0 }; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES); ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO); if (param[1] != 0x47) return -ENODEV; if (set_properties) { psmouse->vendor = "Synaptics"; psmouse->name = "TouchPad"; } return 0; } void synaptics_reset(struct psmouse *psmouse) { /* reset touchpad back to relative mode, gestures enabled */ synaptics_mode_cmd(psmouse, 0); } #if defined(CONFIG_MOUSE_PS2_SYNAPTICS) || \ defined(CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS) /* This list has been kindly provided by Synaptics. */ static const char * const topbuttonpad_pnp_ids[] = { "LEN0017", "LEN0018", "LEN0019", "LEN0023", "LEN002A", "LEN002B", "LEN002C", "LEN002D", "LEN002E", "LEN0033", /* Helix */ "LEN0034", /* T431s, L440, L540, T540, W540, X1 Carbon 2nd */ "LEN0035", /* X240 */ "LEN0036", /* T440 */ "LEN0037", /* X1 Carbon 2nd */ "LEN0038", "LEN0039", /* T440s */ "LEN0041", "LEN0042", /* Yoga */ "LEN0045", "LEN0047", "LEN2000", /* S540 */ "LEN2001", /* Edge E431 */ "LEN2002", /* Edge E531 */ "LEN2003", "LEN2004", /* L440 */ "LEN2005", "LEN2006", /* Edge E440/E540 */ "LEN2007", "LEN2008", "LEN2009", "LEN200A", "LEN200B", NULL }; static const char * const smbus_pnp_ids[] = { /* all of the topbuttonpad_pnp_ids are valid, we just add some extras */ "LEN0048", /* X1 Carbon 3 */ "LEN0046", /* X250 */ "LEN0049", /* Yoga 11e */ "LEN004a", /* W541 */ "LEN005b", /* P50 */ "LEN005e", /* T560 */ "LEN006c", /* T470s */ "LEN007a", /* T470s */ "LEN0071", /* T480 */ "LEN0072", /* X1 Carbon Gen 5 (2017) - Elan/ALPS trackpoint */ "LEN0073", /* X1 Carbon G5 (Elantech) */ "LEN0091", /* X1 Carbon 6 */ "LEN0092", /* X1 Carbon 6 */ "LEN0093", /* T480 */ "LEN0096", /* X280 */ "LEN0097", /* X280 -> ALPS trackpoint */ "LEN0099", /* X1 Extreme Gen 1 / P1 Gen 1 */ "LEN009b", /* T580 */ "LEN0402", /* X1 Extreme Gen 2 / P1 Gen 2 */ "LEN040f", /* P1 Gen 3 */ "LEN200f", /* T450s */ "LEN2044", /* L470 */ "LEN2054", /* E480 */ "LEN2055", /* E580 */ "LEN2068", /* T14 Gen 1 */ "SYN3052", /* HP EliteBook 840 G4 */ "SYN3221", /* HP 15-ay000 */ "SYN323d", /* HP Spectre X360 13-w013dx */ "SYN3257", /* HP Envy 13-ad105ng */ NULL }; static const char * const forcepad_pnp_ids[] = { "SYN300D", "SYN3014", NULL }; /* * Send a command to the synaptics touchpad by special commands */ static int synaptics_send_cmd(struct psmouse *psmouse, u8 cmd, u8 *param) { int error; error = ps2_sliced_command(&psmouse->ps2dev, cmd); if (error) return error; error = ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_GETINFO); if (error) return error; return 0; } static int synaptics_query_int(struct psmouse *psmouse, u8 query_cmd, u32 *val) { int error; union { __be32 be_val; char buf[4]; } resp = { 0 }; error = synaptics_send_cmd(psmouse, query_cmd, resp.buf + 1); if (error) return error; *val = be32_to_cpu(resp.be_val); return 0; } /* * Identify Touchpad * See also the SYN_ID_* macros */ static int synaptics_identify(struct psmouse *psmouse, struct synaptics_device_info *info) { int error; error = synaptics_query_int(psmouse, SYN_QUE_IDENTIFY, &info->identity); if (error) return error; return SYN_ID_IS_SYNAPTICS(info->identity) ? 0 : -ENXIO; } /* * Read the model-id bytes from the touchpad * see also SYN_MODEL_* macros */ static int synaptics_model_id(struct psmouse *psmouse, struct synaptics_device_info *info) { return synaptics_query_int(psmouse, SYN_QUE_MODEL, &info->model_id); } /* * Read the firmware id from the touchpad */ static int synaptics_firmware_id(struct psmouse *psmouse, struct synaptics_device_info *info) { return synaptics_query_int(psmouse, SYN_QUE_FIRMWARE_ID, &info->firmware_id); } /* * Read the board id and the "More Extended Queries" from the touchpad * The board id is encoded in the "QUERY MODES" response */ static int synaptics_query_modes(struct psmouse *psmouse, struct synaptics_device_info *info) { u8 bid[3]; int error; /* firmwares prior 7.5 have no board_id encoded */ if (SYN_ID_FULL(info->identity) < 0x705) return 0; error = synaptics_send_cmd(psmouse, SYN_QUE_MODES, bid); if (error) return error; info->board_id = ((bid[0] & 0xfc) << 6) | bid[1]; if (SYN_MEXT_CAP_BIT(bid[0])) return synaptics_query_int(psmouse, SYN_QUE_MEXT_CAPAB_10, &info->ext_cap_10); return 0; } /* * Read the capability-bits from the touchpad * see also the SYN_CAP_* macros */ static int synaptics_capability(struct psmouse *psmouse, struct synaptics_device_info *info) { int error; error = synaptics_query_int(psmouse, SYN_QUE_CAPABILITIES, &info->capabilities); if (error) return error; info->ext_cap = info->ext_cap_0c = 0; /* * Older firmwares had submodel ID fixed to 0x47 */ if (SYN_ID_FULL(info->identity) < 0x705 && SYN_CAP_SUBMODEL_ID(info->capabilities) != 0x47) { return -ENXIO; } /* * Unless capExtended is set the rest of the flags should be ignored */ if (!SYN_CAP_EXTENDED(info->capabilities)) info->capabilities = 0; if (SYN_EXT_CAP_REQUESTS(info->capabilities) >= 1) { error = synaptics_query_int(psmouse, SYN_QUE_EXT_CAPAB, &info->ext_cap); if (error) { psmouse_warn(psmouse, "device claims to have extended capabilities, but I'm not able to read them.\n"); } else { /* * if nExtBtn is greater than 8 it should be considered * invalid and treated as 0 */ if (SYN_CAP_MULTI_BUTTON_NO(info->ext_cap) > 8) info->ext_cap &= ~SYN_CAP_MB_MASK; } } if (SYN_EXT_CAP_REQUESTS(info->capabilities) >= 4) { error = synaptics_query_int(psmouse, SYN_QUE_EXT_CAPAB_0C, &info->ext_cap_0c); if (error) psmouse_warn(psmouse, "device claims to have extended capability 0x0c, but I'm not able to read it.\n"); } return 0; } /* * Read touchpad resolution and maximum reported coordinates * Resolution is left zero if touchpad does not support the query */ static int synaptics_resolution(struct psmouse *psmouse, struct synaptics_device_info *info) { u8 resp[3]; int error; if (SYN_ID_MAJOR(info->identity) < 4) return 0; error = synaptics_send_cmd(psmouse, SYN_QUE_RESOLUTION, resp); if (!error) { if (resp[0] != 0 && (resp[1] & 0x80) && resp[2] != 0) { info->x_res = resp[0]; /* x resolution in units/mm */ info->y_res = resp[2]; /* y resolution in units/mm */ } } if (SYN_EXT_CAP_REQUESTS(info->capabilities) >= 5 && SYN_CAP_MAX_DIMENSIONS(info->ext_cap_0c)) { error = synaptics_send_cmd(psmouse, SYN_QUE_EXT_MAX_COORDS, resp); if (error) { psmouse_warn(psmouse, "device claims to have max coordinates query, but I'm not able to read it.\n"); } else { info->x_max = (resp[0] << 5) | ((resp[1] & 0x0f) << 1); info->y_max = (resp[2] << 5) | ((resp[1] & 0xf0) >> 3); psmouse_info(psmouse, "queried max coordinates: x [..%d], y [..%d]\n", info->x_max, info->y_max); } } if (SYN_CAP_MIN_DIMENSIONS(info->ext_cap_0c) && (SYN_EXT_CAP_REQUESTS(info->capabilities) >= 7 || /* * Firmware v8.1 does not report proper number of extended * capabilities, but has been proven to report correct min * coordinates. */ SYN_ID_FULL(info->identity) == 0x801)) { error = synaptics_send_cmd(psmouse, SYN_QUE_EXT_MIN_COORDS, resp); if (error) { psmouse_warn(psmouse, "device claims to have min coordinates query, but I'm not able to read it.\n"); } else { info->x_min = (resp[0] << 5) | ((resp[1] & 0x0f) << 1); info->y_min = (resp[2] << 5) | ((resp[1] & 0xf0) >> 3); psmouse_info(psmouse, "queried min coordinates: x [%d..], y [%d..]\n", info->x_min, info->y_min); } } return 0; } static int synaptics_query_hardware(struct psmouse *psmouse, struct synaptics_device_info *info) { int error; memset(info, 0, sizeof(*info)); error = synaptics_identify(psmouse, info); if (error) return error; error = synaptics_model_id(psmouse, info); if (error) return error; error = synaptics_firmware_id(psmouse, info); if (error) return error; error = synaptics_query_modes(psmouse, info); if (error) return error; error = synaptics_capability(psmouse, info); if (error) return error; error = synaptics_resolution(psmouse, info); if (error) return error; return 0; } #endif /* CONFIG_MOUSE_PS2_SYNAPTICS || CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS */ #ifdef CONFIG_MOUSE_PS2_SYNAPTICS static bool cr48_profile_sensor; #define ANY_BOARD_ID 0 struct min_max_quirk { const char * const *pnp_ids; struct { u32 min, max; } board_id; u32 x_min, x_max, y_min, y_max; }; static const struct min_max_quirk min_max_pnpid_table[] = { { (const char * const []){"LEN0033", NULL}, {ANY_BOARD_ID, ANY_BOARD_ID}, 1024, 5052, 2258, 4832 }, { (const char * const []){"LEN0042", NULL}, {ANY_BOARD_ID, ANY_BOARD_ID}, 1232, 5710, 1156, 4696 }, { (const char * const []){"LEN0034", "LEN0036", "LEN0037", "LEN0039", "LEN2002", "LEN2004", NULL}, {ANY_BOARD_ID, 2961}, 1024, 5112, 2024, 4832 }, { (const char * const []){"LEN2000", NULL}, {ANY_BOARD_ID, ANY_BOARD_ID}, 1024, 5113, 2021, 4832 }, { (const char * const []){"LEN2001", NULL}, {ANY_BOARD_ID, ANY_BOARD_ID}, 1024, 5022, 2508, 4832 }, { (const char * const []){"LEN2006", NULL}, {2691, 2691}, 1024, 5045, 2457, 4832 }, { (const char * const []){"LEN2006", NULL}, {ANY_BOARD_ID, ANY_BOARD_ID}, 1264, 5675, 1171, 4688 }, { } }; /***************************************************************************** * Synaptics communications functions ****************************************************************************/ /* * Synaptics touchpads report the y coordinate from bottom to top, which is * opposite from what userspace expects. * This function is used to invert y before reporting. */ static int synaptics_invert_y(int y) { return YMAX_NOMINAL + YMIN_NOMINAL - y; } /* * Apply quirk(s) if the hardware matches */ static void synaptics_apply_quirks(struct psmouse *psmouse, struct synaptics_device_info *info) { int i; for (i = 0; min_max_pnpid_table[i].pnp_ids; i++) { if (!psmouse_matches_pnp_id(psmouse, min_max_pnpid_table[i].pnp_ids)) continue; if (min_max_pnpid_table[i].board_id.min != ANY_BOARD_ID && info->board_id < min_max_pnpid_table[i].board_id.min) continue; if (min_max_pnpid_table[i].board_id.max != ANY_BOARD_ID && info->board_id > min_max_pnpid_table[i].board_id.max) continue; info->x_min = min_max_pnpid_table[i].x_min; info->x_max = min_max_pnpid_table[i].x_max; info->y_min = min_max_pnpid_table[i].y_min; info->y_max = min_max_pnpid_table[i].y_max; psmouse_info(psmouse, "quirked min/max coordinates: x [%d..%d], y [%d..%d]\n", info->x_min, info->x_max, info->y_min, info->y_max); break; } } static bool synaptics_has_agm(struct synaptics_data *priv) { return (SYN_CAP_ADV_GESTURE(priv->info.ext_cap_0c) || SYN_CAP_IMAGE_SENSOR(priv->info.ext_cap_0c)); } static int synaptics_set_advanced_gesture_mode(struct psmouse *psmouse) { static u8 param = 0xc8; int error; error = ps2_sliced_command(&psmouse->ps2dev, SYN_QUE_MODEL); if (error) return error; error = ps2_command(&psmouse->ps2dev, &param, PSMOUSE_CMD_SETRATE); if (error) return error; return 0; } static int synaptics_set_mode(struct psmouse *psmouse) { struct synaptics_data *priv = psmouse->private; int error; priv->mode = 0; if (priv->absolute_mode) priv->mode |= SYN_BIT_ABSOLUTE_MODE; if (priv->disable_gesture) priv->mode |= SYN_BIT_DISABLE_GESTURE; if (psmouse->rate >= 80) priv->mode |= SYN_BIT_HIGH_RATE; if (SYN_CAP_EXTENDED(priv->info.capabilities)) priv->mode |= SYN_BIT_W_MODE; error = synaptics_mode_cmd(psmouse, priv->mode); if (error) return error; if (priv->absolute_mode && synaptics_has_agm(priv)) { error = synaptics_set_advanced_gesture_mode(psmouse); if (error) { psmouse_err(psmouse, "Advanced gesture mode init failed: %d\n", error); return error; } } return 0; } static void synaptics_set_rate(struct psmouse *psmouse, unsigned int rate) { struct synaptics_data *priv = psmouse->private; if (rate >= 80) { priv->mode |= SYN_BIT_HIGH_RATE; psmouse->rate = 80; } else { priv->mode &= ~SYN_BIT_HIGH_RATE; psmouse->rate = 40; } synaptics_mode_cmd(psmouse, priv->mode); } /***************************************************************************** * Synaptics pass-through PS/2 port support ****************************************************************************/ static int synaptics_pt_write(struct serio *serio, u8 c) { struct psmouse *parent = psmouse_from_serio(serio->parent); u8 rate_param = SYN_PS_CLIENT_CMD; /* indicates that we want pass-through port */ int error; error = ps2_sliced_command(&parent->ps2dev, c); if (error) return error; error = ps2_command(&parent->ps2dev, &rate_param, PSMOUSE_CMD_SETRATE); if (error) return error; return 0; } static int synaptics_pt_start(struct serio *serio) { struct psmouse *parent = psmouse_from_serio(serio->parent); struct synaptics_data *priv = parent->private; serio_pause_rx(parent->ps2dev.serio); priv->pt_port = serio; serio_continue_rx(parent->ps2dev.serio); return 0; } static void synaptics_pt_stop(struct serio *serio) { struct psmouse *parent = psmouse_from_serio(serio->parent); struct synaptics_data *priv = parent->private; serio_pause_rx(parent->ps2dev.serio); priv->pt_port = NULL; serio_continue_rx(parent->ps2dev.serio); } static int synaptics_is_pt_packet(u8 *buf) { return (buf[0] & 0xFC) == 0x84 && (buf[3] & 0xCC) == 0xC4; } static void synaptics_pass_pt_packet(struct serio *ptport, u8 *packet) { struct psmouse *child = psmouse_from_serio(ptport); if (child && child->state == PSMOUSE_ACTIVATED) { serio_interrupt(ptport, packet[1], 0); serio_interrupt(ptport, packet[4], 0); serio_interrupt(ptport, packet[5], 0); if (child->pktsize == 4) serio_interrupt(ptport, packet[2], 0); } else { serio_interrupt(ptport, packet[1], 0); } } static void synaptics_pt_activate(struct psmouse *psmouse) { struct synaptics_data *priv = psmouse->private; struct psmouse *child = psmouse_from_serio(priv->pt_port); /* adjust the touchpad to child's choice of protocol */ if (child) { if (child->pktsize == 4) priv->mode |= SYN_BIT_FOUR_BYTE_CLIENT; else priv->mode &= ~SYN_BIT_FOUR_BYTE_CLIENT; if (synaptics_mode_cmd(psmouse, priv->mode)) psmouse_warn(psmouse, "failed to switch guest protocol\n"); } } static void synaptics_pt_create(struct psmouse *psmouse) { struct serio *serio; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) { psmouse_err(psmouse, "not enough memory for pass-through port\n"); return; } serio->id.type = SERIO_PS_PSTHRU; strscpy(serio->name, "Synaptics pass-through", sizeof(serio->name)); strscpy(serio->phys, "synaptics-pt/serio0", sizeof(serio->phys)); serio->write = synaptics_pt_write; serio->start = synaptics_pt_start; serio->stop = synaptics_pt_stop; serio->parent = psmouse->ps2dev.serio; psmouse->pt_activate = synaptics_pt_activate; psmouse_info(psmouse, "serio: %s port at %s\n", serio->name, psmouse->phys); serio_register_port(serio); } /***************************************************************************** * Functions to interpret the absolute mode packets ****************************************************************************/ static void synaptics_parse_agm(const u8 buf[], struct synaptics_data *priv, struct synaptics_hw_state *hw) { struct synaptics_hw_state *agm = &priv->agm; int agm_packet_type; agm_packet_type = (buf[5] & 0x30) >> 4; switch (agm_packet_type) { case 1: /* Gesture packet: (x, y, z) half resolution */ agm->w = hw->w; agm->x = (((buf[4] & 0x0f) << 8) | buf[1]) << 1; agm->y = (((buf[4] & 0xf0) << 4) | buf[2]) << 1; agm->z = ((buf[3] & 0x30) | (buf[5] & 0x0f)) << 1; break; case 2: /* AGM-CONTACT packet: we are only interested in the count */ priv->agm_count = buf[1]; break; default: break; } } static void synaptics_parse_ext_buttons(const u8 buf[], struct synaptics_data *priv, struct synaptics_hw_state *hw) { unsigned int ext_bits = (SYN_CAP_MULTI_BUTTON_NO(priv->info.ext_cap) + 1) >> 1; unsigned int ext_mask = GENMASK(ext_bits - 1, 0); hw->ext_buttons = buf[4] & ext_mask; hw->ext_buttons |= (buf[5] & ext_mask) << ext_bits; } static int synaptics_parse_hw_state(const u8 buf[], struct synaptics_data *priv, struct synaptics_hw_state *hw) { memset(hw, 0, sizeof(struct synaptics_hw_state)); if (SYN_MODEL_NEWABS(priv->info.model_id)) { hw->w = (((buf[0] & 0x30) >> 2) | ((buf[0] & 0x04) >> 1) | ((buf[3] & 0x04) >> 2)); if (synaptics_has_agm(priv) && hw->w == 2) { synaptics_parse_agm(buf, priv, hw); return 1; } hw->x = (((buf[3] & 0x10) << 8) | ((buf[1] & 0x0f) << 8) | buf[4]); hw->y = (((buf[3] & 0x20) << 7) | ((buf[1] & 0xf0) << 4) | buf[5]); hw->z = buf[2]; hw->left = (buf[0] & 0x01) ? 1 : 0; hw->right = (buf[0] & 0x02) ? 1 : 0; if (priv->is_forcepad) { /* * ForcePads, like Clickpads, use middle button * bits to report primary button clicks. * Unfortunately they report primary button not * only when user presses on the pad above certain * threshold, but also when there are more than one * finger on the touchpad, which interferes with * out multi-finger gestures. */ if (hw->z == 0) { /* No contacts */ priv->press = priv->report_press = false; } else if (hw->w >= 4 && ((buf[0] ^ buf[3]) & 0x01)) { /* * Single-finger touch with pressure above * the threshold. If pressure stays long * enough, we'll start reporting primary * button. We rely on the device continuing * sending data even if finger does not * move. */ if (!priv->press) { priv->press_start = jiffies; priv->press = true; } else if (time_after(jiffies, priv->press_start + msecs_to_jiffies(50))) { priv->report_press = true; } } else { priv->press = false; } hw->left = priv->report_press; } else if (SYN_CAP_CLICKPAD(priv->info.ext_cap_0c)) { /* * Clickpad's button is transmitted as middle button, * however, since it is primary button, we will report * it as BTN_LEFT. */ hw->left = ((buf[0] ^ buf[3]) & 0x01) ? 1 : 0; } else if (SYN_CAP_MIDDLE_BUTTON(priv->info.capabilities)) { hw->middle = ((buf[0] ^ buf[3]) & 0x01) ? 1 : 0; if (hw->w == 2) hw->scroll = (s8)buf[1]; } if (SYN_CAP_FOUR_BUTTON(priv->info.capabilities)) { hw->up = ((buf[0] ^ buf[3]) & 0x01) ? 1 : 0; hw->down = ((buf[0] ^ buf[3]) & 0x02) ? 1 : 0; } if (SYN_CAP_MULTI_BUTTON_NO(priv->info.ext_cap) > 0 && ((buf[0] ^ buf[3]) & 0x02)) { synaptics_parse_ext_buttons(buf, priv, hw); } } else { hw->x = (((buf[1] & 0x1f) << 8) | buf[2]); hw->y = (((buf[4] & 0x1f) << 8) | buf[5]); hw->z = (((buf[0] & 0x30) << 2) | (buf[3] & 0x3F)); hw->w = (((buf[1] & 0x80) >> 4) | ((buf[0] & 0x04) >> 1)); hw->left = (buf[0] & 0x01) ? 1 : 0; hw->right = (buf[0] & 0x02) ? 1 : 0; } /* * Convert wrap-around values to negative. (X|Y)_MAX_POSITIVE * is used by some firmware to indicate a finger at the edge of * the touchpad whose precise position cannot be determined, so * convert these values to the maximum axis value. */ if (hw->x > X_MAX_POSITIVE) hw->x -= 1 << ABS_POS_BITS; else if (hw->x == X_MAX_POSITIVE) hw->x = XMAX; if (hw->y > Y_MAX_POSITIVE) hw->y -= 1 << ABS_POS_BITS; else if (hw->y == Y_MAX_POSITIVE) hw->y = YMAX; return 0; } static void synaptics_report_semi_mt_slot(struct input_dev *dev, int slot, bool active, int x, int y) { input_mt_slot(dev, slot); input_mt_report_slot_state(dev, MT_TOOL_FINGER, active); if (active) { input_report_abs(dev, ABS_MT_POSITION_X, x); input_report_abs(dev, ABS_MT_POSITION_Y, synaptics_invert_y(y)); } } static void synaptics_report_semi_mt_data(struct input_dev *dev, const struct synaptics_hw_state *a, const struct synaptics_hw_state *b, int num_fingers) { if (num_fingers >= 2) { synaptics_report_semi_mt_slot(dev, 0, true, min(a->x, b->x), min(a->y, b->y)); synaptics_report_semi_mt_slot(dev, 1, true, max(a->x, b->x), max(a->y, b->y)); } else if (num_fingers == 1) { synaptics_report_semi_mt_slot(dev, 0, true, a->x, a->y); synaptics_report_semi_mt_slot(dev, 1, false, 0, 0); } else { synaptics_report_semi_mt_slot(dev, 0, false, 0, 0); synaptics_report_semi_mt_slot(dev, 1, false, 0, 0); } } static void synaptics_report_ext_buttons(struct psmouse *psmouse, const struct synaptics_hw_state *hw) { struct input_dev *dev = psmouse->dev; struct synaptics_data *priv = psmouse->private; int ext_bits = (SYN_CAP_MULTI_BUTTON_NO(priv->info.ext_cap) + 1) >> 1; int i; if (!SYN_CAP_MULTI_BUTTON_NO(priv->info.ext_cap)) return; /* Bug in FW 8.1 & 8.2, buttons are reported only when ExtBit is 1 */ if ((SYN_ID_FULL(priv->info.identity) == 0x801 || SYN_ID_FULL(priv->info.identity) == 0x802) && !((psmouse->packet[0] ^ psmouse->packet[3]) & 0x02)) return; if (!SYN_CAP_EXT_BUTTONS_STICK(priv->info.ext_cap_10)) { for (i = 0; i < ext_bits; i++) { input_report_key(dev, BTN_0 + 2 * i, hw->ext_buttons & BIT(i)); input_report_key(dev, BTN_1 + 2 * i, hw->ext_buttons & BIT(i + ext_bits)); } return; } /* * This generation of touchpads has the trackstick buttons * physically wired to the touchpad. Re-route them through * the pass-through interface. */ if (priv->pt_port) { u8 pt_buttons; /* The trackstick expects at most 3 buttons */ pt_buttons = SYN_EXT_BUTTON_STICK_L(hw->ext_buttons) | SYN_EXT_BUTTON_STICK_R(hw->ext_buttons) << 1 | SYN_EXT_BUTTON_STICK_M(hw->ext_buttons) << 2; serio_interrupt(priv->pt_port, PSMOUSE_OOB_EXTRA_BTNS, SERIO_OOB_DATA); serio_interrupt(priv->pt_port, pt_buttons, SERIO_OOB_DATA); } } static void synaptics_report_buttons(struct psmouse *psmouse, const struct synaptics_hw_state *hw) { struct input_dev *dev = psmouse->dev; struct synaptics_data *priv = psmouse->private; input_report_key(dev, BTN_LEFT, hw->left); input_report_key(dev, BTN_RIGHT, hw->right); if (SYN_CAP_MIDDLE_BUTTON(priv->info.capabilities)) input_report_key(dev, BTN_MIDDLE, hw->middle); if (SYN_CAP_FOUR_BUTTON(priv->info.capabilities)) { input_report_key(dev, BTN_FORWARD, hw->up); input_report_key(dev, BTN_BACK, hw->down); } synaptics_report_ext_buttons(psmouse, hw); } static void synaptics_report_mt_data(struct psmouse *psmouse, const struct synaptics_hw_state *sgm, int num_fingers) { struct input_dev *dev = psmouse->dev; struct synaptics_data *priv = psmouse->private; const struct synaptics_hw_state *hw[2] = { sgm, &priv->agm }; struct input_mt_pos pos[2]; int slot[2], nsemi, i; nsemi = clamp_val(num_fingers, 0, 2); for (i = 0; i < nsemi; i++) { pos[i].x = hw[i]->x; pos[i].y = synaptics_invert_y(hw[i]->y); } input_mt_assign_slots(dev, slot, pos, nsemi, DMAX * priv->info.x_res); for (i = 0; i < nsemi; i++) { input_mt_slot(dev, slot[i]); input_mt_report_slot_state(dev, MT_TOOL_FINGER, true); input_report_abs(dev, ABS_MT_POSITION_X, pos[i].x); input_report_abs(dev, ABS_MT_POSITION_Y, pos[i].y); input_report_abs(dev, ABS_MT_PRESSURE, hw[i]->z); } input_mt_drop_unused(dev); /* Don't use active slot count to generate BTN_TOOL events. */ input_mt_report_pointer_emulation(dev, false); /* Send the number of fingers reported by touchpad itself. */ input_mt_report_finger_count(dev, num_fingers); synaptics_report_buttons(psmouse, sgm); input_sync(dev); } static void synaptics_image_sensor_process(struct psmouse *psmouse, struct synaptics_hw_state *sgm) { struct synaptics_data *priv = psmouse->private; int num_fingers; /* * Update mt_state using the new finger count and current mt_state. */ if (sgm->z == 0) num_fingers = 0; else if (sgm->w >= 4) num_fingers = 1; else if (sgm->w == 0) num_fingers = 2; else if (sgm->w == 1) num_fingers = priv->agm_count ? priv->agm_count : 3; else num_fingers = 4; /* Send resulting input events to user space */ synaptics_report_mt_data(psmouse, sgm, num_fingers); } static bool synaptics_has_multifinger(struct synaptics_data *priv) { if (SYN_CAP_MULTIFINGER(priv->info.capabilities)) return true; /* Advanced gesture mode also sends multi finger data */ return synaptics_has_agm(priv); } /* * called for each full received packet from the touchpad */ static void synaptics_process_packet(struct psmouse *psmouse) { struct input_dev *dev = psmouse->dev; struct synaptics_data *priv = psmouse->private; struct synaptics_device_info *info = &priv->info; struct synaptics_hw_state hw; int num_fingers; int finger_width; if (synaptics_parse_hw_state(psmouse->packet, priv, &hw)) return; if (SYN_CAP_IMAGE_SENSOR(info->ext_cap_0c)) { synaptics_image_sensor_process(psmouse, &hw); return; } if (hw.scroll) { priv->scroll += hw.scroll; while (priv->scroll >= 4) { input_report_key(dev, BTN_BACK, !hw.down); input_sync(dev); input_report_key(dev, BTN_BACK, hw.down); input_sync(dev); priv->scroll -= 4; } while (priv->scroll <= -4) { input_report_key(dev, BTN_FORWARD, !hw.up); input_sync(dev); input_report_key(dev, BTN_FORWARD, hw.up); input_sync(dev); priv->scroll += 4; } return; } if (hw.z > 0 && hw.x > 1) { num_fingers = 1; finger_width = 5; if (SYN_CAP_EXTENDED(info->capabilities)) { switch (hw.w) { case 0 ... 1: if (synaptics_has_multifinger(priv)) num_fingers = hw.w + 2; break; case 2: /* * SYN_MODEL_PEN(info->model_id): even if * the device supports pen, we treat it as * a single finger. */ break; case 4 ... 15: if (SYN_CAP_PALMDETECT(info->capabilities)) finger_width = hw.w; break; } } } else { num_fingers = 0; finger_width = 0; } if (cr48_profile_sensor) { synaptics_report_mt_data(psmouse, &hw, num_fingers); return; } if (SYN_CAP_ADV_GESTURE(info->ext_cap_0c)) synaptics_report_semi_mt_data(dev, &hw, &priv->agm, num_fingers); /* Post events * BTN_TOUCH has to be first as mousedev relies on it when doing * absolute -> relative conversion */ if (hw.z > 30) input_report_key(dev, BTN_TOUCH, 1); if (hw.z < 25) input_report_key(dev, BTN_TOUCH, 0); if (num_fingers > 0) { input_report_abs(dev, ABS_X, hw.x); input_report_abs(dev, ABS_Y, synaptics_invert_y(hw.y)); } input_report_abs(dev, ABS_PRESSURE, hw.z); if (SYN_CAP_PALMDETECT(info->capabilities)) input_report_abs(dev, ABS_TOOL_WIDTH, finger_width); input_report_key(dev, BTN_TOOL_FINGER, num_fingers == 1); if (synaptics_has_multifinger(priv)) { input_report_key(dev, BTN_TOOL_DOUBLETAP, num_fingers == 2); input_report_key(dev, BTN_TOOL_TRIPLETAP, num_fingers == 3); } synaptics_report_buttons(psmouse, &hw); input_sync(dev); } static bool synaptics_validate_byte(struct psmouse *psmouse, int idx, enum synaptics_pkt_type pkt_type) { static const u8 newabs_mask[] = { 0xC8, 0x00, 0x00, 0xC8, 0x00 }; static const u8 newabs_rel_mask[] = { 0xC0, 0x00, 0x00, 0xC0, 0x00 }; static const u8 newabs_rslt[] = { 0x80, 0x00, 0x00, 0xC0, 0x00 }; static const u8 oldabs_mask[] = { 0xC0, 0x60, 0x00, 0xC0, 0x60 }; static const u8 oldabs_rslt[] = { 0xC0, 0x00, 0x00, 0x80, 0x00 }; const u8 *packet = psmouse->packet; if (idx < 0 || idx > 4) return false; switch (pkt_type) { case SYN_NEWABS: case SYN_NEWABS_RELAXED: return (packet[idx] & newabs_rel_mask[idx]) == newabs_rslt[idx]; case SYN_NEWABS_STRICT: return (packet[idx] & newabs_mask[idx]) == newabs_rslt[idx]; case SYN_OLDABS: return (packet[idx] & oldabs_mask[idx]) == oldabs_rslt[idx]; default: psmouse_err(psmouse, "unknown packet type %d\n", pkt_type); return false; } } static enum synaptics_pkt_type synaptics_detect_pkt_type(struct psmouse *psmouse) { int i; for (i = 0; i < 5; i++) { if (!synaptics_validate_byte(psmouse, i, SYN_NEWABS_STRICT)) { psmouse_info(psmouse, "using relaxed packet validation\n"); return SYN_NEWABS_RELAXED; } } return SYN_NEWABS_STRICT; } static psmouse_ret_t synaptics_process_byte(struct psmouse *psmouse) { struct synaptics_data *priv = psmouse->private; if (psmouse->pktcnt >= 6) { /* Full packet received */ if (unlikely(priv->pkt_type == SYN_NEWABS)) priv->pkt_type = synaptics_detect_pkt_type(psmouse); if (SYN_CAP_PASS_THROUGH(priv->info.capabilities) && synaptics_is_pt_packet(psmouse->packet)) { if (priv->pt_port) synaptics_pass_pt_packet(priv->pt_port, psmouse->packet); } else synaptics_process_packet(psmouse); return PSMOUSE_FULL_PACKET; } return synaptics_validate_byte(psmouse, psmouse->pktcnt - 1, priv->pkt_type) ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; } /***************************************************************************** * Driver initialization/cleanup functions ****************************************************************************/ static void set_abs_position_params(struct input_dev *dev, struct synaptics_device_info *info, int x_code, int y_code) { int x_min = info->x_min ?: XMIN_NOMINAL; int x_max = info->x_max ?: XMAX_NOMINAL; int y_min = info->y_min ?: YMIN_NOMINAL; int y_max = info->y_max ?: YMAX_NOMINAL; int fuzz = SYN_CAP_REDUCED_FILTERING(info->ext_cap_0c) ? SYN_REDUCED_FILTER_FUZZ : 0; input_set_abs_params(dev, x_code, x_min, x_max, fuzz, 0); input_set_abs_params(dev, y_code, y_min, y_max, fuzz, 0); input_abs_set_res(dev, x_code, info->x_res); input_abs_set_res(dev, y_code, info->y_res); } static int set_input_params(struct psmouse *psmouse, struct synaptics_data *priv) { struct input_dev *dev = psmouse->dev; struct synaptics_device_info *info = &priv->info; int i; int error; /* Reset default psmouse capabilities */ __clear_bit(EV_REL, dev->evbit); bitmap_zero(dev->relbit, REL_CNT); bitmap_zero(dev->keybit, KEY_CNT); /* Things that apply to both modes */ __set_bit(INPUT_PROP_POINTER, dev->propbit); input_set_capability(dev, EV_KEY, BTN_LEFT); /* Clickpads report only left button */ if (!SYN_CAP_CLICKPAD(info->ext_cap_0c)) { input_set_capability(dev, EV_KEY, BTN_RIGHT); if (SYN_CAP_MIDDLE_BUTTON(info->capabilities)) input_set_capability(dev, EV_KEY, BTN_MIDDLE); } if (!priv->absolute_mode) { /* Relative mode */ input_set_capability(dev, EV_REL, REL_X); input_set_capability(dev, EV_REL, REL_Y); return 0; } /* Absolute mode */ set_abs_position_params(dev, &priv->info, ABS_X, ABS_Y); input_set_abs_params(dev, ABS_PRESSURE, 0, 255, 0, 0); if (cr48_profile_sensor) input_set_abs_params(dev, ABS_MT_PRESSURE, 0, 255, 0, 0); if (SYN_CAP_IMAGE_SENSOR(info->ext_cap_0c)) { set_abs_position_params(dev, info, ABS_MT_POSITION_X, ABS_MT_POSITION_Y); /* Image sensors can report per-contact pressure */ input_set_abs_params(dev, ABS_MT_PRESSURE, 0, 255, 0, 0); error = input_mt_init_slots(dev, 2, INPUT_MT_POINTER | INPUT_MT_TRACK); if (error) return error; /* Image sensors can signal 4 and 5 finger clicks */ input_set_capability(dev, EV_KEY, BTN_TOOL_QUADTAP); input_set_capability(dev, EV_KEY, BTN_TOOL_QUINTTAP); } else if (SYN_CAP_ADV_GESTURE(info->ext_cap_0c)) { set_abs_position_params(dev, info, ABS_MT_POSITION_X, ABS_MT_POSITION_Y); /* * Profile sensor in CR-48 tracks contacts reasonably well, * other non-image sensors with AGM use semi-mt. */ error = input_mt_init_slots(dev, 2, INPUT_MT_POINTER | (cr48_profile_sensor ? INPUT_MT_TRACK : INPUT_MT_SEMI_MT)); if (error) return error; /* * For semi-mt devices we send ABS_X/Y ourselves instead of * input_mt_report_pointer_emulation. But * input_mt_init_slots() resets the fuzz to 0, leading to a * filtered ABS_MT_POSITION_X but an unfiltered ABS_X * position. Let's re-initialize ABS_X/Y here. */ if (!cr48_profile_sensor) set_abs_position_params(dev, &priv->info, ABS_X, ABS_Y); } if (SYN_CAP_PALMDETECT(info->capabilities)) input_set_abs_params(dev, ABS_TOOL_WIDTH, 0, 15, 0, 0); input_set_capability(dev, EV_KEY, BTN_TOUCH); input_set_capability(dev, EV_KEY, BTN_TOOL_FINGER); if (synaptics_has_multifinger(priv)) { input_set_capability(dev, EV_KEY, BTN_TOOL_DOUBLETAP); input_set_capability(dev, EV_KEY, BTN_TOOL_TRIPLETAP); } if (SYN_CAP_FOUR_BUTTON(info->capabilities) || SYN_CAP_MIDDLE_BUTTON(info->capabilities)) { input_set_capability(dev, EV_KEY, BTN_FORWARD); input_set_capability(dev, EV_KEY, BTN_BACK); } if (!SYN_CAP_EXT_BUTTONS_STICK(info->ext_cap_10)) for (i = 0; i < SYN_CAP_MULTI_BUTTON_NO(info->ext_cap); i++) input_set_capability(dev, EV_KEY, BTN_0 + i); if (SYN_CAP_CLICKPAD(info->ext_cap_0c)) { __set_bit(INPUT_PROP_BUTTONPAD, dev->propbit); if (psmouse_matches_pnp_id(psmouse, topbuttonpad_pnp_ids) && !SYN_CAP_EXT_BUTTONS_STICK(info->ext_cap_10)) __set_bit(INPUT_PROP_TOPBUTTONPAD, dev->propbit); } return 0; } static ssize_t synaptics_show_disable_gesture(struct psmouse *psmouse, void *data, char *buf) { struct synaptics_data *priv = psmouse->private; return sprintf(buf, "%c\n", priv->disable_gesture ? '1' : '0'); } static ssize_t synaptics_set_disable_gesture(struct psmouse *psmouse, void *data, const char *buf, size_t len) { struct synaptics_data *priv = psmouse->private; unsigned int value; int err; err = kstrtouint(buf, 10, &value); if (err) return err; if (value > 1) return -EINVAL; if (value == priv->disable_gesture) return len; priv->disable_gesture = value; if (value) priv->mode |= SYN_BIT_DISABLE_GESTURE; else priv->mode &= ~SYN_BIT_DISABLE_GESTURE; if (synaptics_mode_cmd(psmouse, priv->mode)) return -EIO; return len; } PSMOUSE_DEFINE_ATTR(disable_gesture, S_IWUSR | S_IRUGO, NULL, synaptics_show_disable_gesture, synaptics_set_disable_gesture); static void synaptics_disconnect(struct psmouse *psmouse) { struct synaptics_data *priv = psmouse->private; /* * We might have left a breadcrumb when trying to * set up SMbus companion. */ psmouse_smbus_cleanup(psmouse); if (!priv->absolute_mode && SYN_ID_DISGEST_SUPPORTED(priv->info.identity)) device_remove_file(&psmouse->ps2dev.serio->dev, &psmouse_attr_disable_gesture.dattr); synaptics_reset(psmouse); kfree(priv); psmouse->private = NULL; } static int synaptics_reconnect(struct psmouse *psmouse) { struct synaptics_data *priv = psmouse->private; struct synaptics_device_info info; u8 param[2]; int retry = 0; int error; do { psmouse_reset(psmouse); if (retry) { /* * On some boxes, right after resuming, the touchpad * needs some time to finish initializing (I assume * it needs time to calibrate) and start responding * to Synaptics-specific queries, so let's wait a * bit. */ ssleep(1); } ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_GETID); error = synaptics_detect(psmouse, 0); } while (error && ++retry < 3); if (error) return error; if (retry > 1) psmouse_dbg(psmouse, "reconnected after %d tries\n", retry); error = synaptics_query_hardware(psmouse, &info); if (error) { psmouse_err(psmouse, "Unable to query device.\n"); return error; } error = synaptics_set_mode(psmouse); if (error) { psmouse_err(psmouse, "Unable to initialize device.\n"); return error; } if (info.identity != priv->info.identity || info.model_id != priv->info.model_id || info.capabilities != priv->info.capabilities || info.ext_cap != priv->info.ext_cap) { psmouse_err(psmouse, "hardware appears to be different: id(%u-%u), model(%u-%u), caps(%x-%x), ext(%x-%x).\n", priv->info.identity, info.identity, priv->info.model_id, info.model_id, priv->info.capabilities, info.capabilities, priv->info.ext_cap, info.ext_cap); return -ENXIO; } return 0; } static bool impaired_toshiba_kbc; static const struct dmi_system_id toshiba_dmi_table[] __initconst = { #if defined(CONFIG_DMI) && defined(CONFIG_X86) { /* Toshiba Satellite */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Satellite"), }, }, { /* Toshiba Dynabook */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "dynabook"), }, }, { /* Toshiba Portege M300 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "PORTEGE M300"), }, }, { /* Toshiba Portege M300 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"), DMI_MATCH(DMI_PRODUCT_NAME, "Portable PC"), DMI_MATCH(DMI_PRODUCT_VERSION, "Version 1.0"), }, }, #endif { } }; static bool broken_olpc_ec; static const struct dmi_system_id olpc_dmi_table[] __initconst = { #if defined(CONFIG_DMI) && defined(CONFIG_OLPC) { /* OLPC XO-1 or XO-1.5 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "OLPC"), DMI_MATCH(DMI_PRODUCT_NAME, "XO"), }, }, #endif { } }; static const struct dmi_system_id __initconst cr48_dmi_table[] = { #if defined(CONFIG_DMI) && defined(CONFIG_X86) { /* Cr-48 Chromebook (Codename Mario) */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "IEC"), DMI_MATCH(DMI_PRODUCT_NAME, "Mario"), }, }, #endif { } }; void __init synaptics_module_init(void) { impaired_toshiba_kbc = dmi_check_system(toshiba_dmi_table); broken_olpc_ec = dmi_check_system(olpc_dmi_table); cr48_profile_sensor = dmi_check_system(cr48_dmi_table); } static int synaptics_init_ps2(struct psmouse *psmouse, struct synaptics_device_info *info, bool absolute_mode) { struct synaptics_data *priv; int err; synaptics_apply_quirks(psmouse, info); psmouse->private = priv = kzalloc(sizeof(struct synaptics_data), GFP_KERNEL); if (!priv) return -ENOMEM; priv->info = *info; priv->absolute_mode = absolute_mode; if (SYN_ID_DISGEST_SUPPORTED(info->identity)) priv->disable_gesture = true; /* * Unfortunately ForcePad capability is not exported over PS/2, * so we have to resort to checking PNP IDs. */ priv->is_forcepad = psmouse_matches_pnp_id(psmouse, forcepad_pnp_ids); err = synaptics_set_mode(psmouse); if (err) { psmouse_err(psmouse, "Unable to initialize device.\n"); goto init_fail; } priv->pkt_type = SYN_MODEL_NEWABS(info->model_id) ? SYN_NEWABS : SYN_OLDABS; psmouse_info(psmouse, "Touchpad model: %lu, fw: %lu.%lu, id: %#x, caps: %#x/%#x/%#x/%#x, board id: %u, fw id: %u\n", SYN_ID_MODEL(info->identity), SYN_ID_MAJOR(info->identity), SYN_ID_MINOR(info->identity), info->model_id, info->capabilities, info->ext_cap, info->ext_cap_0c, info->ext_cap_10, info->board_id, info->firmware_id); err = set_input_params(psmouse, priv); if (err) { psmouse_err(psmouse, "failed to set up capabilities: %d\n", err); goto init_fail; } /* * Encode touchpad model so that it can be used to set * input device->id.version and be visible to userspace. * Because version is __u16 we have to drop something. * Hardware info bits seem to be good candidates as they * are documented to be for Synaptics corp. internal use. */ psmouse->model = ((info->model_id & 0x00ff0000) >> 8) | (info->model_id & 0x000000ff); if (absolute_mode) { psmouse->protocol_handler = synaptics_process_byte; psmouse->pktsize = 6; } else { /* Relative mode follows standard PS/2 mouse protocol */ psmouse->protocol_handler = psmouse_process_byte; psmouse->pktsize = 3; } psmouse->set_rate = synaptics_set_rate; psmouse->disconnect = synaptics_disconnect; psmouse->reconnect = synaptics_reconnect; psmouse->cleanup = synaptics_reset; /* Synaptics can usually stay in sync without extra help */ psmouse->resync_time = 0; if (SYN_CAP_PASS_THROUGH(info->capabilities)) synaptics_pt_create(psmouse); /* * Toshiba's KBC seems to have trouble handling data from * Synaptics at full rate. Switch to a lower rate (roughly * the same rate as a standard PS/2 mouse). */ if (psmouse->rate >= 80 && impaired_toshiba_kbc) { psmouse_info(psmouse, "Toshiba %s detected, limiting rate to 40pps.\n", dmi_get_system_info(DMI_PRODUCT_NAME)); psmouse->rate = 40; } if (!priv->absolute_mode && SYN_ID_DISGEST_SUPPORTED(info->identity)) { err = device_create_file(&psmouse->ps2dev.serio->dev, &psmouse_attr_disable_gesture.dattr); if (err) { psmouse_err(psmouse, "Failed to create disable_gesture attribute (%d)", err); goto init_fail; } } return 0; init_fail: kfree(priv); return err; } static int __synaptics_init(struct psmouse *psmouse, bool absolute_mode) { struct synaptics_device_info info; int error; psmouse_reset(psmouse); error = synaptics_query_hardware(psmouse, &info); if (error) { psmouse_err(psmouse, "Unable to query device: %d\n", error); return error; } return synaptics_init_ps2(psmouse, &info, absolute_mode); } int synaptics_init_absolute(struct psmouse *psmouse) { return __synaptics_init(psmouse, true); } int synaptics_init_relative(struct psmouse *psmouse) { return __synaptics_init(psmouse, false); } static int synaptics_setup_ps2(struct psmouse *psmouse, struct synaptics_device_info *info) { bool absolute_mode = true; int error; /* * The OLPC XO has issues with Synaptics' absolute mode; the constant * packet spew overloads the EC such that key presses on the keyboard * are missed. Given that, don't even attempt to use Absolute mode. * Relative mode seems to work just fine. */ if (broken_olpc_ec) { psmouse_info(psmouse, "OLPC XO detected, forcing relative protocol.\n"); absolute_mode = false; } error = synaptics_init_ps2(psmouse, info, absolute_mode); if (error) return error; return absolute_mode ? PSMOUSE_SYNAPTICS : PSMOUSE_SYNAPTICS_RELATIVE; } #else /* CONFIG_MOUSE_PS2_SYNAPTICS */ void __init synaptics_module_init(void) { } static int __maybe_unused synaptics_setup_ps2(struct psmouse *psmouse, struct synaptics_device_info *info) { return -ENOSYS; } #endif /* CONFIG_MOUSE_PS2_SYNAPTICS */ #ifdef CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS /* * The newest Synaptics device can use a secondary bus (called InterTouch) which * provides a better bandwidth and allow a better control of the touchpads. * This is used to decide if we need to use this bus or not. */ enum { SYNAPTICS_INTERTOUCH_NOT_SET = -1, SYNAPTICS_INTERTOUCH_OFF, SYNAPTICS_INTERTOUCH_ON, }; static int synaptics_intertouch = IS_ENABLED(CONFIG_RMI4_SMB) ? SYNAPTICS_INTERTOUCH_NOT_SET : SYNAPTICS_INTERTOUCH_OFF; module_param_named(synaptics_intertouch, synaptics_intertouch, int, 0644); MODULE_PARM_DESC(synaptics_intertouch, "Use a secondary bus for the Synaptics device."); static int synaptics_create_intertouch(struct psmouse *psmouse, struct synaptics_device_info *info, bool leave_breadcrumbs) { bool topbuttonpad = psmouse_matches_pnp_id(psmouse, topbuttonpad_pnp_ids) && !SYN_CAP_EXT_BUTTONS_STICK(info->ext_cap_10); const struct rmi_device_platform_data pdata = { .sensor_pdata = { .sensor_type = rmi_sensor_touchpad, .axis_align.flip_y = true, .kernel_tracking = false, .topbuttonpad = topbuttonpad, }, .gpio_data = { .buttonpad = SYN_CAP_CLICKPAD(info->ext_cap_0c), .trackstick_buttons = !!SYN_CAP_EXT_BUTTONS_STICK(info->ext_cap_10), }, }; const struct i2c_board_info intertouch_board = { I2C_BOARD_INFO("rmi4_smbus", 0x2c), .flags = I2C_CLIENT_HOST_NOTIFY, }; return psmouse_smbus_init(psmouse, &intertouch_board, &pdata, sizeof(pdata), true, leave_breadcrumbs); } /* * synaptics_setup_intertouch - called once the PS/2 devices are enumerated * and decides to instantiate a SMBus InterTouch device. */ static int synaptics_setup_intertouch(struct psmouse *psmouse, struct synaptics_device_info *info, bool leave_breadcrumbs) { int error; if (synaptics_intertouch == SYNAPTICS_INTERTOUCH_OFF) return -ENXIO; if (synaptics_intertouch == SYNAPTICS_INTERTOUCH_NOT_SET) { if (!psmouse_matches_pnp_id(psmouse, topbuttonpad_pnp_ids) && !psmouse_matches_pnp_id(psmouse, smbus_pnp_ids)) { if (!psmouse_matches_pnp_id(psmouse, forcepad_pnp_ids)) psmouse_info(psmouse, "Your touchpad (%s) says it can support a different bus. " "If i2c-hid and hid-rmi are not used, you might want to try setting psmouse.synaptics_intertouch to 1 and report this to [email protected].\n", psmouse->ps2dev.serio->firmware_id); return -ENXIO; } } psmouse_info(psmouse, "Trying to set up SMBus access\n"); error = synaptics_create_intertouch(psmouse, info, leave_breadcrumbs); if (error) { if (error == -EAGAIN) psmouse_info(psmouse, "SMbus companion is not ready yet\n"); else psmouse_err(psmouse, "unable to create intertouch device\n"); return error; } return 0; } int synaptics_init_smbus(struct psmouse *psmouse) { struct synaptics_device_info info; int error; psmouse_reset(psmouse); error = synaptics_query_hardware(psmouse, &info); if (error) { psmouse_err(psmouse, "Unable to query device: %d\n", error); return error; } if (!SYN_CAP_INTERTOUCH(info.ext_cap_0c)) return -ENXIO; return synaptics_create_intertouch(psmouse, &info, false); } #else /* CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS */ static int __maybe_unused synaptics_setup_intertouch(struct psmouse *psmouse, struct synaptics_device_info *info, bool leave_breadcrumbs) { return -ENOSYS; } int synaptics_init_smbus(struct psmouse *psmouse) { return -ENOSYS; } #endif /* CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS */ #if defined(CONFIG_MOUSE_PS2_SYNAPTICS) || \ defined(CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS) int synaptics_init(struct psmouse *psmouse) { struct synaptics_device_info info; int error; int retval; psmouse_reset(psmouse); error = synaptics_query_hardware(psmouse, &info); if (error) { psmouse_err(psmouse, "Unable to query device: %d\n", error); return error; } if (SYN_CAP_INTERTOUCH(info.ext_cap_0c)) { if ((!IS_ENABLED(CONFIG_RMI4_SMB) || !IS_ENABLED(CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS)) && /* Forcepads need F21, which is not ready */ !psmouse_matches_pnp_id(psmouse, forcepad_pnp_ids)) { psmouse_warn(psmouse, "The touchpad can support a better bus than the too old PS/2 protocol. " "Make sure MOUSE_PS2_SYNAPTICS_SMBUS and RMI4_SMB are enabled to get a better touchpad experience.\n"); } error = synaptics_setup_intertouch(psmouse, &info, true); if (!error) return PSMOUSE_SYNAPTICS_SMBUS; } retval = synaptics_setup_ps2(psmouse, &info); if (retval < 0) { /* * Not using any flavor of Synaptics support, so clean up * SMbus breadcrumbs, if any. */ psmouse_smbus_cleanup(psmouse); } return retval; } #else /* CONFIG_MOUSE_PS2_SYNAPTICS || CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS */ int synaptics_init(struct psmouse *psmouse) { return -ENOSYS; } #endif /* CONFIG_MOUSE_PS2_SYNAPTICS || CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS */
linux-master
drivers/input/mouse/synaptics.c
// SPDX-License-Identifier: GPL-2.0-only /* * Stephen Evanchik <[email protected]> * * Trademarks are the property of their respective owners. */ #include <linux/slab.h> #include <linux/delay.h> #include <linux/serio.h> #include <linux/module.h> #include <linux/input.h> #include <linux/libps2.h> #include <linux/proc_fs.h> #include <linux/uaccess.h> #include "psmouse.h" #include "trackpoint.h" static const char * const trackpoint_variants[] = { [TP_VARIANT_IBM] = "IBM", [TP_VARIANT_ALPS] = "ALPS", [TP_VARIANT_ELAN] = "Elan", [TP_VARIANT_NXP] = "NXP", [TP_VARIANT_JYT_SYNAPTICS] = "JYT_Synaptics", [TP_VARIANT_SYNAPTICS] = "Synaptics", }; /* * Power-on Reset: Resets all trackpoint parameters, including RAM values, * to defaults. * Returns zero on success, non-zero on failure. */ static int trackpoint_power_on_reset(struct ps2dev *ps2dev) { u8 param[2] = { TP_POR }; int err; err = ps2_command(ps2dev, param, MAKE_PS2_CMD(1, 2, TP_COMMAND)); if (err) return err; /* Check for success response -- 0xAA00 */ if (param[0] != 0xAA || param[1] != 0x00) return -ENODEV; return 0; } /* * Device IO: read, write and toggle bit */ static int trackpoint_read(struct ps2dev *ps2dev, u8 loc, u8 *results) { results[0] = loc; return ps2_command(ps2dev, results, MAKE_PS2_CMD(1, 1, TP_COMMAND)); } static int trackpoint_write(struct ps2dev *ps2dev, u8 loc, u8 val) { u8 param[3] = { TP_WRITE_MEM, loc, val }; return ps2_command(ps2dev, param, MAKE_PS2_CMD(3, 0, TP_COMMAND)); } static int trackpoint_toggle_bit(struct ps2dev *ps2dev, u8 loc, u8 mask) { u8 param[3] = { TP_TOGGLE, loc, mask }; /* Bad things will happen if the loc param isn't in this range */ if (loc < 0x20 || loc >= 0x2F) return -EINVAL; return ps2_command(ps2dev, param, MAKE_PS2_CMD(3, 0, TP_COMMAND)); } static int trackpoint_update_bit(struct ps2dev *ps2dev, u8 loc, u8 mask, u8 value) { int retval; u8 data; retval = trackpoint_read(ps2dev, loc, &data); if (retval) return retval; if (((data & mask) == mask) != !!value) retval = trackpoint_toggle_bit(ps2dev, loc, mask); return retval; } /* * Trackpoint-specific attributes */ struct trackpoint_attr_data { size_t field_offset; u8 command; u8 mask; bool inverted; u8 power_on_default; }; static ssize_t trackpoint_show_int_attr(struct psmouse *psmouse, void *data, char *buf) { struct trackpoint_data *tp = psmouse->private; struct trackpoint_attr_data *attr = data; u8 value = *(u8 *)((void *)tp + attr->field_offset); if (attr->inverted) value = !value; return sprintf(buf, "%u\n", value); } static ssize_t trackpoint_set_int_attr(struct psmouse *psmouse, void *data, const char *buf, size_t count) { struct trackpoint_data *tp = psmouse->private; struct trackpoint_attr_data *attr = data; u8 *field = (void *)tp + attr->field_offset; u8 value; int err; err = kstrtou8(buf, 10, &value); if (err) return err; *field = value; err = trackpoint_write(&psmouse->ps2dev, attr->command, value); return err ?: count; } #define TRACKPOINT_INT_ATTR(_name, _command, _default) \ static struct trackpoint_attr_data trackpoint_attr_##_name = { \ .field_offset = offsetof(struct trackpoint_data, _name), \ .command = _command, \ .power_on_default = _default, \ }; \ PSMOUSE_DEFINE_ATTR(_name, S_IWUSR | S_IRUGO, \ &trackpoint_attr_##_name, \ trackpoint_show_int_attr, trackpoint_set_int_attr) static ssize_t trackpoint_set_bit_attr(struct psmouse *psmouse, void *data, const char *buf, size_t count) { struct trackpoint_data *tp = psmouse->private; struct trackpoint_attr_data *attr = data; bool *field = (void *)tp + attr->field_offset; bool value; int err; err = kstrtobool(buf, &value); if (err) return err; if (attr->inverted) value = !value; if (*field != value) { *field = value; err = trackpoint_toggle_bit(&psmouse->ps2dev, attr->command, attr->mask); } return err ?: count; } #define TRACKPOINT_BIT_ATTR(_name, _command, _mask, _inv, _default) \ static struct trackpoint_attr_data trackpoint_attr_##_name = { \ .field_offset = offsetof(struct trackpoint_data, \ _name), \ .command = _command, \ .mask = _mask, \ .inverted = _inv, \ .power_on_default = _default, \ }; \ PSMOUSE_DEFINE_ATTR(_name, S_IWUSR | S_IRUGO, \ &trackpoint_attr_##_name, \ trackpoint_show_int_attr, trackpoint_set_bit_attr) TRACKPOINT_INT_ATTR(sensitivity, TP_SENS, TP_DEF_SENS); TRACKPOINT_INT_ATTR(speed, TP_SPEED, TP_DEF_SPEED); TRACKPOINT_INT_ATTR(inertia, TP_INERTIA, TP_DEF_INERTIA); TRACKPOINT_INT_ATTR(reach, TP_REACH, TP_DEF_REACH); TRACKPOINT_INT_ATTR(draghys, TP_DRAGHYS, TP_DEF_DRAGHYS); TRACKPOINT_INT_ATTR(mindrag, TP_MINDRAG, TP_DEF_MINDRAG); TRACKPOINT_INT_ATTR(thresh, TP_THRESH, TP_DEF_THRESH); TRACKPOINT_INT_ATTR(upthresh, TP_UP_THRESH, TP_DEF_UP_THRESH); TRACKPOINT_INT_ATTR(ztime, TP_Z_TIME, TP_DEF_Z_TIME); TRACKPOINT_INT_ATTR(jenks, TP_JENKS_CURV, TP_DEF_JENKS_CURV); TRACKPOINT_INT_ATTR(drift_time, TP_DRIFT_TIME, TP_DEF_DRIFT_TIME); TRACKPOINT_BIT_ATTR(press_to_select, TP_TOGGLE_PTSON, TP_MASK_PTSON, false, TP_DEF_PTSON); TRACKPOINT_BIT_ATTR(skipback, TP_TOGGLE_SKIPBACK, TP_MASK_SKIPBACK, false, TP_DEF_SKIPBACK); TRACKPOINT_BIT_ATTR(ext_dev, TP_TOGGLE_EXT_DEV, TP_MASK_EXT_DEV, true, TP_DEF_EXT_DEV); static bool trackpoint_is_attr_available(struct psmouse *psmouse, struct attribute *attr) { struct trackpoint_data *tp = psmouse->private; return tp->variant_id == TP_VARIANT_IBM || attr == &psmouse_attr_sensitivity.dattr.attr || attr == &psmouse_attr_press_to_select.dattr.attr; } static umode_t trackpoint_is_attr_visible(struct kobject *kobj, struct attribute *attr, int n) { struct device *dev = kobj_to_dev(kobj); struct serio *serio = to_serio_port(dev); struct psmouse *psmouse = psmouse_from_serio(serio); return trackpoint_is_attr_available(psmouse, attr) ? attr->mode : 0; } static struct attribute *trackpoint_attrs[] = { &psmouse_attr_sensitivity.dattr.attr, &psmouse_attr_speed.dattr.attr, &psmouse_attr_inertia.dattr.attr, &psmouse_attr_reach.dattr.attr, &psmouse_attr_draghys.dattr.attr, &psmouse_attr_mindrag.dattr.attr, &psmouse_attr_thresh.dattr.attr, &psmouse_attr_upthresh.dattr.attr, &psmouse_attr_ztime.dattr.attr, &psmouse_attr_jenks.dattr.attr, &psmouse_attr_drift_time.dattr.attr, &psmouse_attr_press_to_select.dattr.attr, &psmouse_attr_skipback.dattr.attr, &psmouse_attr_ext_dev.dattr.attr, NULL }; static struct attribute_group trackpoint_attr_group = { .is_visible = trackpoint_is_attr_visible, .attrs = trackpoint_attrs, }; #define TRACKPOINT_UPDATE(_power_on, _psmouse, _tp, _name) \ do { \ struct trackpoint_attr_data *_attr = &trackpoint_attr_##_name; \ \ if ((!_power_on || _tp->_name != _attr->power_on_default) && \ trackpoint_is_attr_available(_psmouse, \ &psmouse_attr_##_name.dattr.attr)) { \ if (!_attr->mask) \ trackpoint_write(&_psmouse->ps2dev, \ _attr->command, _tp->_name); \ else \ trackpoint_update_bit(&_psmouse->ps2dev, \ _attr->command, _attr->mask, \ _tp->_name); \ } \ } while (0) #define TRACKPOINT_SET_POWER_ON_DEFAULT(_tp, _name) \ do { \ _tp->_name = trackpoint_attr_##_name.power_on_default; \ } while (0) static int trackpoint_start_protocol(struct psmouse *psmouse, u8 *variant_id, u8 *firmware_id) { u8 param[2] = { 0 }; int error; error = ps2_command(&psmouse->ps2dev, param, MAKE_PS2_CMD(0, 2, TP_READ_ID)); if (error) return error; switch (param[0]) { case TP_VARIANT_IBM: case TP_VARIANT_ALPS: case TP_VARIANT_ELAN: case TP_VARIANT_NXP: case TP_VARIANT_JYT_SYNAPTICS: case TP_VARIANT_SYNAPTICS: if (variant_id) *variant_id = param[0]; if (firmware_id) *firmware_id = param[1]; return 0; } return -ENODEV; } /* * Write parameters to trackpad. * in_power_on_state: Set to true if TP is in default / power-on state (ex. if * power-on reset was run). If so, values will only be * written to TP if they differ from power-on default. */ static int trackpoint_sync(struct psmouse *psmouse, bool in_power_on_state) { struct trackpoint_data *tp = psmouse->private; if (!in_power_on_state && tp->variant_id == TP_VARIANT_IBM) { /* * Disable features that may make device unusable * with this driver. */ trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_TWOHAND, TP_MASK_TWOHAND, TP_DEF_TWOHAND); trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_SOURCE_TAG, TP_MASK_SOURCE_TAG, TP_DEF_SOURCE_TAG); trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_MB, TP_MASK_MB, TP_DEF_MB); } /* * These properties can be changed in this driver. Only * configure them if the values are non-default or if the TP is in * an unknown state. */ TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, sensitivity); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, inertia); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, speed); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, reach); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, draghys); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, mindrag); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, thresh); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, upthresh); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, ztime); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, jenks); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, drift_time); /* toggles */ TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, press_to_select); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, skipback); TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, ext_dev); return 0; } static void trackpoint_defaults(struct trackpoint_data *tp) { TRACKPOINT_SET_POWER_ON_DEFAULT(tp, sensitivity); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, speed); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, reach); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, draghys); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, mindrag); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, thresh); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, upthresh); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, ztime); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, jenks); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, drift_time); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, inertia); /* toggles */ TRACKPOINT_SET_POWER_ON_DEFAULT(tp, press_to_select); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, skipback); TRACKPOINT_SET_POWER_ON_DEFAULT(tp, ext_dev); } static void trackpoint_disconnect(struct psmouse *psmouse) { device_remove_group(&psmouse->ps2dev.serio->dev, &trackpoint_attr_group); kfree(psmouse->private); psmouse->private = NULL; } static int trackpoint_reconnect(struct psmouse *psmouse) { struct trackpoint_data *tp = psmouse->private; int error; bool was_reset; error = trackpoint_start_protocol(psmouse, NULL, NULL); if (error) return error; was_reset = tp->variant_id == TP_VARIANT_IBM && trackpoint_power_on_reset(&psmouse->ps2dev) == 0; error = trackpoint_sync(psmouse, was_reset); if (error) return error; return 0; } int trackpoint_detect(struct psmouse *psmouse, bool set_properties) { struct ps2dev *ps2dev = &psmouse->ps2dev; struct trackpoint_data *tp; u8 variant_id; u8 firmware_id; u8 button_info; int error; error = trackpoint_start_protocol(psmouse, &variant_id, &firmware_id); if (error) return error; if (!set_properties) return 0; tp = kzalloc(sizeof(*tp), GFP_KERNEL); if (!tp) return -ENOMEM; trackpoint_defaults(tp); tp->variant_id = variant_id; tp->firmware_id = firmware_id; psmouse->private = tp; psmouse->vendor = trackpoint_variants[variant_id]; psmouse->name = "TrackPoint"; psmouse->reconnect = trackpoint_reconnect; psmouse->disconnect = trackpoint_disconnect; if (variant_id != TP_VARIANT_IBM) { /* Newer variants do not support extended button query. */ button_info = 0x33; } else { error = trackpoint_read(ps2dev, TP_EXT_BTN, &button_info); if (error) { psmouse_warn(psmouse, "failed to get extended button data, assuming 3 buttons\n"); button_info = 0x33; } else if (!button_info) { psmouse_warn(psmouse, "got 0 in extended button data, assuming 3 buttons\n"); button_info = 0x33; } } if ((button_info & 0x0f) >= 3) input_set_capability(psmouse->dev, EV_KEY, BTN_MIDDLE); __set_bit(INPUT_PROP_POINTER, psmouse->dev->propbit); __set_bit(INPUT_PROP_POINTING_STICK, psmouse->dev->propbit); if (variant_id != TP_VARIANT_IBM || trackpoint_power_on_reset(ps2dev) != 0) { /* * Write defaults to TP if we did not reset the trackpoint. */ trackpoint_sync(psmouse, false); } error = device_add_group(&ps2dev->serio->dev, &trackpoint_attr_group); if (error) { psmouse_err(psmouse, "failed to create sysfs attributes, error: %d\n", error); kfree(psmouse->private); psmouse->private = NULL; return -1; } psmouse_info(psmouse, "%s TrackPoint firmware: 0x%02x, buttons: %d/%d\n", psmouse->vendor, firmware_id, (button_info & 0xf0) >> 4, button_info & 0x0f); return 0; }
linux-master
drivers/input/mouse/trackpoint.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Virtual PS/2 Mouse on VMware and QEMU hypervisors. * * Copyright (C) 2014, VMware, Inc. All Rights Reserved. * * Twin device code is hugely inspired by the ALPS driver. * Authors: * Dmitry Torokhov <[email protected]> * Thomas Hellstrom <[email protected]> */ #include <linux/input.h> #include <linux/serio.h> #include <linux/libps2.h> #include <linux/slab.h> #include <linux/module.h> #include <asm/hypervisor.h> #include <asm/vmware.h> #include "psmouse.h" #include "vmmouse.h" #define VMMOUSE_PROTO_MAGIC 0x564D5868U /* * Main commands supported by the vmmouse hypervisor port. */ #define VMMOUSE_PROTO_CMD_GETVERSION 10 #define VMMOUSE_PROTO_CMD_ABSPOINTER_DATA 39 #define VMMOUSE_PROTO_CMD_ABSPOINTER_STATUS 40 #define VMMOUSE_PROTO_CMD_ABSPOINTER_COMMAND 41 #define VMMOUSE_PROTO_CMD_ABSPOINTER_RESTRICT 86 /* * Subcommands for VMMOUSE_PROTO_CMD_ABSPOINTER_COMMAND */ #define VMMOUSE_CMD_ENABLE 0x45414552U #define VMMOUSE_CMD_DISABLE 0x000000f5U #define VMMOUSE_CMD_REQUEST_RELATIVE 0x4c455252U #define VMMOUSE_CMD_REQUEST_ABSOLUTE 0x53424152U #define VMMOUSE_ERROR 0xffff0000U #define VMMOUSE_VERSION_ID 0x3442554aU #define VMMOUSE_RELATIVE_PACKET 0x00010000U #define VMMOUSE_LEFT_BUTTON 0x20 #define VMMOUSE_RIGHT_BUTTON 0x10 #define VMMOUSE_MIDDLE_BUTTON 0x08 /* * VMMouse Restrict command */ #define VMMOUSE_RESTRICT_ANY 0x00 #define VMMOUSE_RESTRICT_CPL0 0x01 #define VMMOUSE_RESTRICT_IOPL 0x02 #define VMMOUSE_MAX_X 0xFFFF #define VMMOUSE_MAX_Y 0xFFFF #define VMMOUSE_VENDOR "VMware" #define VMMOUSE_NAME "VMMouse" /** * struct vmmouse_data - private data structure for the vmmouse driver * * @abs_dev: "Absolute" device used to report absolute mouse movement. * @phys: Physical path for the absolute device. * @dev_name: Name attribute name for the absolute device. */ struct vmmouse_data { struct input_dev *abs_dev; char phys[32]; char dev_name[128]; }; /* * Hypervisor-specific bi-directional communication channel * implementing the vmmouse protocol. Should never execute on * bare metal hardware. */ #define VMMOUSE_CMD(cmd, in1, out1, out2, out3, out4) \ ({ \ unsigned long __dummy1, __dummy2; \ __asm__ __volatile__ (VMWARE_HYPERCALL : \ "=a"(out1), \ "=b"(out2), \ "=c"(out3), \ "=d"(out4), \ "=S"(__dummy1), \ "=D"(__dummy2) : \ "a"(VMMOUSE_PROTO_MAGIC), \ "b"(in1), \ "c"(VMMOUSE_PROTO_CMD_##cmd), \ "d"(0) : \ "memory"); \ }) /** * vmmouse_report_button - report button state on the correct input device * * @psmouse: Pointer to the psmouse struct * @abs_dev: The absolute input device * @rel_dev: The relative input device * @pref_dev: The preferred device for reporting * @code: Button code * @value: Button value * * Report @value and @code on @pref_dev, unless the button is already * pressed on the other device, in which case the state is reported on that * device. */ static void vmmouse_report_button(struct psmouse *psmouse, struct input_dev *abs_dev, struct input_dev *rel_dev, struct input_dev *pref_dev, unsigned int code, int value) { if (test_bit(code, abs_dev->key)) pref_dev = abs_dev; else if (test_bit(code, rel_dev->key)) pref_dev = rel_dev; input_report_key(pref_dev, code, value); } /** * vmmouse_report_events - process events on the vmmouse communications channel * * @psmouse: Pointer to the psmouse struct * * This function pulls events from the vmmouse communications channel and * reports them on the correct (absolute or relative) input device. When the * communications channel is drained, or if we've processed more than 255 * psmouse commands, the function returns PSMOUSE_FULL_PACKET. If there is a * host- or synchronization error, the function returns PSMOUSE_BAD_DATA in * the hope that the caller will reset the communications channel. */ static psmouse_ret_t vmmouse_report_events(struct psmouse *psmouse) { struct input_dev *rel_dev = psmouse->dev; struct vmmouse_data *priv = psmouse->private; struct input_dev *abs_dev = priv->abs_dev; struct input_dev *pref_dev; u32 status, x, y, z; u32 dummy1, dummy2, dummy3; unsigned int queue_length; unsigned int count = 255; while (count--) { /* See if we have motion data. */ VMMOUSE_CMD(ABSPOINTER_STATUS, 0, status, dummy1, dummy2, dummy3); if ((status & VMMOUSE_ERROR) == VMMOUSE_ERROR) { psmouse_err(psmouse, "failed to fetch status data\n"); /* * After a few attempts this will result in * reconnect. */ return PSMOUSE_BAD_DATA; } queue_length = status & 0xffff; if (queue_length == 0) break; if (queue_length % 4) { psmouse_err(psmouse, "invalid queue length\n"); return PSMOUSE_BAD_DATA; } /* Now get it */ VMMOUSE_CMD(ABSPOINTER_DATA, 4, status, x, y, z); /* * And report what we've got. Prefer to report button * events on the same device where we report motion events. * This doesn't work well with the mouse wheel, though. See * below. Ideally we would want to report that on the * preferred device as well. */ if (status & VMMOUSE_RELATIVE_PACKET) { pref_dev = rel_dev; input_report_rel(rel_dev, REL_X, (s32)x); input_report_rel(rel_dev, REL_Y, -(s32)y); } else { pref_dev = abs_dev; input_report_abs(abs_dev, ABS_X, x); input_report_abs(abs_dev, ABS_Y, y); } /* Xorg seems to ignore wheel events on absolute devices */ input_report_rel(rel_dev, REL_WHEEL, -(s8)((u8) z)); vmmouse_report_button(psmouse, abs_dev, rel_dev, pref_dev, BTN_LEFT, status & VMMOUSE_LEFT_BUTTON); vmmouse_report_button(psmouse, abs_dev, rel_dev, pref_dev, BTN_RIGHT, status & VMMOUSE_RIGHT_BUTTON); vmmouse_report_button(psmouse, abs_dev, rel_dev, pref_dev, BTN_MIDDLE, status & VMMOUSE_MIDDLE_BUTTON); input_sync(abs_dev); input_sync(rel_dev); } return PSMOUSE_FULL_PACKET; } /** * vmmouse_process_byte - process data on the ps/2 channel * * @psmouse: Pointer to the psmouse struct * * When the ps/2 channel indicates that there is vmmouse data available, * call vmmouse channel processing. Otherwise, continue to accept bytes. If * there is a synchronization or communication data error, return * PSMOUSE_BAD_DATA in the hope that the caller will reset the mouse. */ static psmouse_ret_t vmmouse_process_byte(struct psmouse *psmouse) { unsigned char *packet = psmouse->packet; switch (psmouse->pktcnt) { case 1: return (packet[0] & 0x8) == 0x8 ? PSMOUSE_GOOD_DATA : PSMOUSE_BAD_DATA; case 2: return PSMOUSE_GOOD_DATA; default: return vmmouse_report_events(psmouse); } } /** * vmmouse_disable - Disable vmmouse * * @psmouse: Pointer to the psmouse struct * * Tries to disable vmmouse mode. */ static void vmmouse_disable(struct psmouse *psmouse) { u32 status; u32 dummy1, dummy2, dummy3, dummy4; VMMOUSE_CMD(ABSPOINTER_COMMAND, VMMOUSE_CMD_DISABLE, dummy1, dummy2, dummy3, dummy4); VMMOUSE_CMD(ABSPOINTER_STATUS, 0, status, dummy1, dummy2, dummy3); if ((status & VMMOUSE_ERROR) != VMMOUSE_ERROR) psmouse_warn(psmouse, "failed to disable vmmouse device\n"); } /** * vmmouse_enable - Enable vmmouse and request absolute mode. * * @psmouse: Pointer to the psmouse struct * * Tries to enable vmmouse mode. Performs basic checks and requests * absolute vmmouse mode. * Returns 0 on success, -ENODEV on failure. */ static int vmmouse_enable(struct psmouse *psmouse) { u32 status, version; u32 dummy1, dummy2, dummy3, dummy4; /* * Try enabling the device. If successful, we should be able to * read valid version ID back from it. */ VMMOUSE_CMD(ABSPOINTER_COMMAND, VMMOUSE_CMD_ENABLE, dummy1, dummy2, dummy3, dummy4); /* * See if version ID can be retrieved. */ VMMOUSE_CMD(ABSPOINTER_STATUS, 0, status, dummy1, dummy2, dummy3); if ((status & 0x0000ffff) == 0) { psmouse_dbg(psmouse, "empty flags - assuming no device\n"); return -ENXIO; } VMMOUSE_CMD(ABSPOINTER_DATA, 1 /* single item */, version, dummy1, dummy2, dummy3); if (version != VMMOUSE_VERSION_ID) { psmouse_dbg(psmouse, "Unexpected version value: %u vs %u\n", (unsigned) version, VMMOUSE_VERSION_ID); vmmouse_disable(psmouse); return -ENXIO; } /* * Restrict ioport access, if possible. */ VMMOUSE_CMD(ABSPOINTER_RESTRICT, VMMOUSE_RESTRICT_CPL0, dummy1, dummy2, dummy3, dummy4); VMMOUSE_CMD(ABSPOINTER_COMMAND, VMMOUSE_CMD_REQUEST_ABSOLUTE, dummy1, dummy2, dummy3, dummy4); return 0; } /* * Array of supported hypervisors. */ static enum x86_hypervisor_type vmmouse_supported_hypervisors[] = { X86_HYPER_VMWARE, X86_HYPER_KVM, }; /** * vmmouse_check_hypervisor - Check if we're running on a supported hypervisor */ static bool vmmouse_check_hypervisor(void) { int i; for (i = 0; i < ARRAY_SIZE(vmmouse_supported_hypervisors); i++) if (vmmouse_supported_hypervisors[i] == x86_hyper_type) return true; return false; } /** * vmmouse_detect - Probe whether vmmouse is available * * @psmouse: Pointer to the psmouse struct * @set_properties: Whether to set psmouse name and vendor * * Returns 0 if vmmouse channel is available. Negative error code if not. */ int vmmouse_detect(struct psmouse *psmouse, bool set_properties) { u32 response, version, dummy1, dummy2; if (!vmmouse_check_hypervisor()) { psmouse_dbg(psmouse, "VMMouse not running on supported hypervisor.\n"); return -ENXIO; } /* Check if the device is present */ response = ~VMMOUSE_PROTO_MAGIC; VMMOUSE_CMD(GETVERSION, 0, version, response, dummy1, dummy2); if (response != VMMOUSE_PROTO_MAGIC || version == 0xffffffffU) return -ENXIO; if (set_properties) { psmouse->vendor = VMMOUSE_VENDOR; psmouse->name = VMMOUSE_NAME; psmouse->model = version; } return 0; } /** * vmmouse_reset - Disable vmmouse and reset * * @psmouse: Pointer to the psmouse struct * * Tries to disable vmmouse mode before enter suspend. */ static void vmmouse_reset(struct psmouse *psmouse) { vmmouse_disable(psmouse); psmouse_reset(psmouse); } /** * vmmouse_disconnect - Take down vmmouse driver * * @psmouse: Pointer to the psmouse struct * * Takes down vmmouse driver and frees resources set up in vmmouse_init(). */ static void vmmouse_disconnect(struct psmouse *psmouse) { struct vmmouse_data *priv = psmouse->private; vmmouse_disable(psmouse); psmouse_reset(psmouse); input_unregister_device(priv->abs_dev); kfree(priv); } /** * vmmouse_reconnect - Reset the ps/2 - and vmmouse connections * * @psmouse: Pointer to the psmouse struct * * Attempts to reset the mouse connections. Returns 0 on success and * -1 on failure. */ static int vmmouse_reconnect(struct psmouse *psmouse) { int error; psmouse_reset(psmouse); vmmouse_disable(psmouse); error = vmmouse_enable(psmouse); if (error) { psmouse_err(psmouse, "Unable to re-enable mouse when reconnecting, err: %d\n", error); return error; } return 0; } /** * vmmouse_init - Initialize the vmmouse driver * * @psmouse: Pointer to the psmouse struct * * Requests the device and tries to enable vmmouse mode. * If successful, sets up the input device for relative movement events. * It also allocates another input device and sets it up for absolute motion * events. Returns 0 on success and -1 on failure. */ int vmmouse_init(struct psmouse *psmouse) { struct vmmouse_data *priv; struct input_dev *rel_dev = psmouse->dev, *abs_dev; int error; psmouse_reset(psmouse); error = vmmouse_enable(psmouse); if (error) return error; priv = kzalloc(sizeof(*priv), GFP_KERNEL); abs_dev = input_allocate_device(); if (!priv || !abs_dev) { error = -ENOMEM; goto init_fail; } priv->abs_dev = abs_dev; psmouse->private = priv; /* Set up and register absolute device */ snprintf(priv->phys, sizeof(priv->phys), "%s/input1", psmouse->ps2dev.serio->phys); /* Mimic name setup for relative device in psmouse-base.c */ snprintf(priv->dev_name, sizeof(priv->dev_name), "%s %s %s", VMMOUSE_PSNAME, VMMOUSE_VENDOR, VMMOUSE_NAME); abs_dev->phys = priv->phys; abs_dev->name = priv->dev_name; abs_dev->id.bustype = BUS_I8042; abs_dev->id.vendor = 0x0002; abs_dev->id.product = PSMOUSE_VMMOUSE; abs_dev->id.version = psmouse->model; abs_dev->dev.parent = &psmouse->ps2dev.serio->dev; /* Set absolute device capabilities */ input_set_capability(abs_dev, EV_KEY, BTN_LEFT); input_set_capability(abs_dev, EV_KEY, BTN_RIGHT); input_set_capability(abs_dev, EV_KEY, BTN_MIDDLE); input_set_capability(abs_dev, EV_ABS, ABS_X); input_set_capability(abs_dev, EV_ABS, ABS_Y); input_set_abs_params(abs_dev, ABS_X, 0, VMMOUSE_MAX_X, 0, 0); input_set_abs_params(abs_dev, ABS_Y, 0, VMMOUSE_MAX_Y, 0, 0); error = input_register_device(priv->abs_dev); if (error) goto init_fail; /* Add wheel capability to the relative device */ input_set_capability(rel_dev, EV_REL, REL_WHEEL); psmouse->protocol_handler = vmmouse_process_byte; psmouse->disconnect = vmmouse_disconnect; psmouse->reconnect = vmmouse_reconnect; psmouse->cleanup = vmmouse_reset; return 0; init_fail: vmmouse_disable(psmouse); psmouse_reset(psmouse); input_free_device(abs_dev); kfree(priv); psmouse->private = NULL; return error; }
linux-master
drivers/input/mouse/vmmouse.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for simulating a mouse on GPIO lines. * * Copyright (C) 2007 Atmel Corporation * Copyright (C) 2017 Linus Walleij <[email protected]> */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/gpio/consumer.h> #include <linux/property.h> #include <linux/of.h> /** * struct gpio_mouse * @scan_ms: the scan interval in milliseconds. * @up: GPIO line for up value. * @down: GPIO line for down value. * @left: GPIO line for left value. * @right: GPIO line for right value. * @bleft: GPIO line for left button. * @bmiddle: GPIO line for middle button. * @bright: GPIO line for right button. * * This struct must be added to the platform_device in the board code. * It is used by the gpio_mouse driver to setup GPIO lines and to * calculate mouse movement. */ struct gpio_mouse { u32 scan_ms; struct gpio_desc *up; struct gpio_desc *down; struct gpio_desc *left; struct gpio_desc *right; struct gpio_desc *bleft; struct gpio_desc *bmiddle; struct gpio_desc *bright; }; /* * Timer function which is run every scan_ms ms when the device is opened. * The dev input variable is set to the input_dev pointer. */ static void gpio_mouse_scan(struct input_dev *input) { struct gpio_mouse *gpio = input_get_drvdata(input); int x, y; if (gpio->bleft) input_report_key(input, BTN_LEFT, gpiod_get_value(gpio->bleft)); if (gpio->bmiddle) input_report_key(input, BTN_MIDDLE, gpiod_get_value(gpio->bmiddle)); if (gpio->bright) input_report_key(input, BTN_RIGHT, gpiod_get_value(gpio->bright)); x = gpiod_get_value(gpio->right) - gpiod_get_value(gpio->left); y = gpiod_get_value(gpio->down) - gpiod_get_value(gpio->up); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); input_sync(input); } static int gpio_mouse_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct gpio_mouse *gmouse; struct input_dev *input; int error; gmouse = devm_kzalloc(dev, sizeof(*gmouse), GFP_KERNEL); if (!gmouse) return -ENOMEM; /* Assign some default scanning time */ error = device_property_read_u32(dev, "scan-interval-ms", &gmouse->scan_ms); if (error || gmouse->scan_ms == 0) { dev_warn(dev, "invalid scan time, set to 50 ms\n"); gmouse->scan_ms = 50; } gmouse->up = devm_gpiod_get(dev, "up", GPIOD_IN); if (IS_ERR(gmouse->up)) return PTR_ERR(gmouse->up); gmouse->down = devm_gpiod_get(dev, "down", GPIOD_IN); if (IS_ERR(gmouse->down)) return PTR_ERR(gmouse->down); gmouse->left = devm_gpiod_get(dev, "left", GPIOD_IN); if (IS_ERR(gmouse->left)) return PTR_ERR(gmouse->left); gmouse->right = devm_gpiod_get(dev, "right", GPIOD_IN); if (IS_ERR(gmouse->right)) return PTR_ERR(gmouse->right); gmouse->bleft = devm_gpiod_get_optional(dev, "button-left", GPIOD_IN); if (IS_ERR(gmouse->bleft)) return PTR_ERR(gmouse->bleft); gmouse->bmiddle = devm_gpiod_get_optional(dev, "button-middle", GPIOD_IN); if (IS_ERR(gmouse->bmiddle)) return PTR_ERR(gmouse->bmiddle); gmouse->bright = devm_gpiod_get_optional(dev, "button-right", GPIOD_IN); if (IS_ERR(gmouse->bright)) return PTR_ERR(gmouse->bright); input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = pdev->name; input->id.bustype = BUS_HOST; input_set_drvdata(input, gmouse); input_set_capability(input, EV_REL, REL_X); input_set_capability(input, EV_REL, REL_Y); if (gmouse->bleft) input_set_capability(input, EV_KEY, BTN_LEFT); if (gmouse->bmiddle) input_set_capability(input, EV_KEY, BTN_MIDDLE); if (gmouse->bright) input_set_capability(input, EV_KEY, BTN_RIGHT); error = input_setup_polling(input, gpio_mouse_scan); if (error) return error; input_set_poll_interval(input, gmouse->scan_ms); error = input_register_device(input); if (error) { dev_err(dev, "could not register input device\n"); return error; } dev_dbg(dev, "%d ms scan time, buttons: %s%s%s\n", gmouse->scan_ms, gmouse->bleft ? "" : "left ", gmouse->bmiddle ? "" : "middle ", gmouse->bright ? "" : "right"); return 0; } static const struct of_device_id gpio_mouse_of_match[] = { { .compatible = "gpio-mouse", }, { }, }; MODULE_DEVICE_TABLE(of, gpio_mouse_of_match); static struct platform_driver gpio_mouse_device_driver = { .probe = gpio_mouse_probe, .driver = { .name = "gpio_mouse", .of_match_table = gpio_mouse_of_match, } }; module_platform_driver(gpio_mouse_device_driver); MODULE_AUTHOR("Hans-Christian Egtvedt <[email protected]>"); MODULE_DESCRIPTION("GPIO mouse driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:gpio_mouse"); /* work with hotplug and coldplug */
linux-master
drivers/input/mouse/gpio_mouse.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2000-2001 Vojtech Pavlik * * Based on the work of: * Alan Cox Robin O'Leary */ /* * IBM PC110 touchpad driver for Linux */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/input.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/delay.h> #include <asm/io.h> #include <asm/irq.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("IBM PC110 touchpad driver"); MODULE_LICENSE("GPL"); #define PC110PAD_OFF 0x30 #define PC110PAD_ON 0x38 static int pc110pad_irq = 10; static int pc110pad_io = 0x15e0; static struct input_dev *pc110pad_dev; static int pc110pad_data[3]; static int pc110pad_count; static irqreturn_t pc110pad_interrupt(int irq, void *ptr) { int value = inb_p(pc110pad_io); int handshake = inb_p(pc110pad_io + 2); outb(handshake | 1, pc110pad_io + 2); udelay(2); outb(handshake & ~1, pc110pad_io + 2); udelay(2); inb_p(0x64); pc110pad_data[pc110pad_count++] = value; if (pc110pad_count < 3) return IRQ_HANDLED; input_report_key(pc110pad_dev, BTN_TOUCH, pc110pad_data[0] & 0x01); input_report_abs(pc110pad_dev, ABS_X, pc110pad_data[1] | ((pc110pad_data[0] << 3) & 0x80) | ((pc110pad_data[0] << 1) & 0x100)); input_report_abs(pc110pad_dev, ABS_Y, pc110pad_data[2] | ((pc110pad_data[0] << 4) & 0x80)); input_sync(pc110pad_dev); pc110pad_count = 0; return IRQ_HANDLED; } static void pc110pad_close(struct input_dev *dev) { outb(PC110PAD_OFF, pc110pad_io + 2); } static int pc110pad_open(struct input_dev *dev) { pc110pad_interrupt(0, NULL); pc110pad_interrupt(0, NULL); pc110pad_interrupt(0, NULL); outb(PC110PAD_ON, pc110pad_io + 2); pc110pad_count = 0; return 0; } /* * We try to avoid enabling the hardware if it's not * there, but we don't know how to test. But we do know * that the PC110 is not a PCI system. So if we find any * PCI devices in the machine, we don't have a PC110. */ static int __init pc110pad_init(void) { int err; if (!no_pci_devices()) return -ENODEV; if (!request_region(pc110pad_io, 4, "pc110pad")) { printk(KERN_ERR "pc110pad: I/O area %#x-%#x in use.\n", pc110pad_io, pc110pad_io + 4); return -EBUSY; } outb(PC110PAD_OFF, pc110pad_io + 2); if (request_irq(pc110pad_irq, pc110pad_interrupt, 0, "pc110pad", NULL)) { printk(KERN_ERR "pc110pad: Unable to get irq %d.\n", pc110pad_irq); err = -EBUSY; goto err_release_region; } pc110pad_dev = input_allocate_device(); if (!pc110pad_dev) { printk(KERN_ERR "pc110pad: Not enough memory.\n"); err = -ENOMEM; goto err_free_irq; } pc110pad_dev->name = "IBM PC110 TouchPad"; pc110pad_dev->phys = "isa15e0/input0"; pc110pad_dev->id.bustype = BUS_ISA; pc110pad_dev->id.vendor = 0x0003; pc110pad_dev->id.product = 0x0001; pc110pad_dev->id.version = 0x0100; pc110pad_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); pc110pad_dev->absbit[0] = BIT_MASK(ABS_X) | BIT_MASK(ABS_Y); pc110pad_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_abs_set_max(pc110pad_dev, ABS_X, 0x1ff); input_abs_set_max(pc110pad_dev, ABS_Y, 0x0ff); pc110pad_dev->open = pc110pad_open; pc110pad_dev->close = pc110pad_close; err = input_register_device(pc110pad_dev); if (err) goto err_free_dev; return 0; err_free_dev: input_free_device(pc110pad_dev); err_free_irq: free_irq(pc110pad_irq, NULL); err_release_region: release_region(pc110pad_io, 4); return err; } static void __exit pc110pad_exit(void) { outb(PC110PAD_OFF, pc110pad_io + 2); free_irq(pc110pad_irq, NULL); input_unregister_device(pc110pad_dev); release_region(pc110pad_io, 4); } module_init(pc110pad_init); module_exit(pc110pad_exit);
linux-master
drivers/input/mouse/pc110pad.c
// SPDX-License-Identifier: GPL-2.0-or-later /*- * Finger Sensing Pad PS/2 mouse driver. * * Copyright (C) 2005-2007 Asia Vital Components Co., Ltd. * Copyright (C) 2005-2012 Tai-hwa Liang, Sentelic Corporation. */ #include <linux/module.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/ctype.h> #include <linux/libps2.h> #include <linux/serio.h> #include <linux/jiffies.h> #include <linux/slab.h> #include "psmouse.h" #include "sentelic.h" /* * Timeout for FSP PS/2 command only (in milliseconds). */ #define FSP_CMD_TIMEOUT 200 #define FSP_CMD_TIMEOUT2 30 #define GET_ABS_X(packet) ((packet[1] << 2) | ((packet[3] >> 2) & 0x03)) #define GET_ABS_Y(packet) ((packet[2] << 2) | (packet[3] & 0x03)) /** Driver version. */ static const char fsp_drv_ver[] = "1.1.0-K"; /* * Make sure that the value being sent to FSP will not conflict with * possible sample rate values. */ static unsigned char fsp_test_swap_cmd(unsigned char reg_val) { switch (reg_val) { case 10: case 20: case 40: case 60: case 80: case 100: case 200: /* * The requested value being sent to FSP matched to possible * sample rates, swap the given value such that the hardware * wouldn't get confused. */ return (reg_val >> 4) | (reg_val << 4); default: return reg_val; /* swap isn't necessary */ } } /* * Make sure that the value being sent to FSP will not conflict with certain * commands. */ static unsigned char fsp_test_invert_cmd(unsigned char reg_val) { switch (reg_val) { case 0xe9: case 0xee: case 0xf2: case 0xff: /* * The requested value being sent to FSP matched to certain * commands, inverse the given value such that the hardware * wouldn't get confused. */ return ~reg_val; default: return reg_val; /* inversion isn't necessary */ } } static int fsp_reg_read(struct psmouse *psmouse, int reg_addr, int *reg_val) { struct ps2dev *ps2dev = &psmouse->ps2dev; unsigned char param[3]; unsigned char addr; int rc = -1; /* * We need to shut off the device and switch it into command * mode so we don't confuse our protocol handler. We don't need * to do that for writes because sysfs set helper does this for * us. */ psmouse_deactivate(psmouse); ps2_begin_command(ps2dev); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; /* should return 0xfe(request for resending) */ ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2); /* should return 0xfc(failed) */ ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; if ((addr = fsp_test_invert_cmd(reg_addr)) != reg_addr) { ps2_sendbyte(ps2dev, 0x68, FSP_CMD_TIMEOUT2); } else if ((addr = fsp_test_swap_cmd(reg_addr)) != reg_addr) { /* swapping is required */ ps2_sendbyte(ps2dev, 0xcc, FSP_CMD_TIMEOUT2); /* expect 0xfe */ } else { /* swapping isn't necessary */ ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2); /* expect 0xfe */ } /* should return 0xfc(failed) */ ps2_sendbyte(ps2dev, addr, FSP_CMD_TIMEOUT); if (__ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO) < 0) goto out; *reg_val = param[2]; rc = 0; out: ps2_end_command(ps2dev); psmouse_activate(psmouse); psmouse_dbg(psmouse, "READ REG: 0x%02x is 0x%02x (rc = %d)\n", reg_addr, *reg_val, rc); return rc; } static int fsp_reg_write(struct psmouse *psmouse, int reg_addr, int reg_val) { struct ps2dev *ps2dev = &psmouse->ps2dev; unsigned char v; int rc = -1; ps2_begin_command(ps2dev); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; if ((v = fsp_test_invert_cmd(reg_addr)) != reg_addr) { /* inversion is required */ ps2_sendbyte(ps2dev, 0x74, FSP_CMD_TIMEOUT2); } else { if ((v = fsp_test_swap_cmd(reg_addr)) != reg_addr) { /* swapping is required */ ps2_sendbyte(ps2dev, 0x77, FSP_CMD_TIMEOUT2); } else { /* swapping isn't necessary */ ps2_sendbyte(ps2dev, 0x55, FSP_CMD_TIMEOUT2); } } /* write the register address in correct order */ ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; if ((v = fsp_test_invert_cmd(reg_val)) != reg_val) { /* inversion is required */ ps2_sendbyte(ps2dev, 0x47, FSP_CMD_TIMEOUT2); } else if ((v = fsp_test_swap_cmd(reg_val)) != reg_val) { /* swapping is required */ ps2_sendbyte(ps2dev, 0x44, FSP_CMD_TIMEOUT2); } else { /* swapping isn't necessary */ ps2_sendbyte(ps2dev, 0x33, FSP_CMD_TIMEOUT2); } /* write the register value in correct order */ ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2); rc = 0; out: ps2_end_command(ps2dev); psmouse_dbg(psmouse, "WRITE REG: 0x%02x to 0x%02x (rc = %d)\n", reg_addr, reg_val, rc); return rc; } /* Enable register clock gating for writing certain registers */ static int fsp_reg_write_enable(struct psmouse *psmouse, bool enable) { int v, nv; if (fsp_reg_read(psmouse, FSP_REG_SYSCTL1, &v) == -1) return -1; if (enable) nv = v | FSP_BIT_EN_REG_CLK; else nv = v & ~FSP_BIT_EN_REG_CLK; /* only write if necessary */ if (nv != v) if (fsp_reg_write(psmouse, FSP_REG_SYSCTL1, nv) == -1) return -1; return 0; } static int fsp_page_reg_read(struct psmouse *psmouse, int *reg_val) { struct ps2dev *ps2dev = &psmouse->ps2dev; unsigned char param[3]; int rc = -1; psmouse_deactivate(psmouse); ps2_begin_command(ps2dev); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; ps2_sendbyte(ps2dev, 0x66, FSP_CMD_TIMEOUT2); ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; ps2_sendbyte(ps2dev, 0x83, FSP_CMD_TIMEOUT2); ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2); /* get the returned result */ if (__ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) goto out; *reg_val = param[2]; rc = 0; out: ps2_end_command(ps2dev); psmouse_activate(psmouse); psmouse_dbg(psmouse, "READ PAGE REG: 0x%02x (rc = %d)\n", *reg_val, rc); return rc; } static int fsp_page_reg_write(struct psmouse *psmouse, int reg_val) { struct ps2dev *ps2dev = &psmouse->ps2dev; unsigned char v; int rc = -1; ps2_begin_command(ps2dev); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; ps2_sendbyte(ps2dev, 0x38, FSP_CMD_TIMEOUT2); ps2_sendbyte(ps2dev, 0x88, FSP_CMD_TIMEOUT2); if (ps2_sendbyte(ps2dev, 0xf3, FSP_CMD_TIMEOUT) < 0) goto out; if ((v = fsp_test_invert_cmd(reg_val)) != reg_val) { ps2_sendbyte(ps2dev, 0x47, FSP_CMD_TIMEOUT2); } else if ((v = fsp_test_swap_cmd(reg_val)) != reg_val) { /* swapping is required */ ps2_sendbyte(ps2dev, 0x44, FSP_CMD_TIMEOUT2); } else { /* swapping isn't necessary */ ps2_sendbyte(ps2dev, 0x33, FSP_CMD_TIMEOUT2); } ps2_sendbyte(ps2dev, v, FSP_CMD_TIMEOUT2); rc = 0; out: ps2_end_command(ps2dev); psmouse_dbg(psmouse, "WRITE PAGE REG: to 0x%02x (rc = %d)\n", reg_val, rc); return rc; } static int fsp_get_version(struct psmouse *psmouse, int *version) { if (fsp_reg_read(psmouse, FSP_REG_VERSION, version)) return -EIO; return 0; } static int fsp_get_revision(struct psmouse *psmouse, int *rev) { if (fsp_reg_read(psmouse, FSP_REG_REVISION, rev)) return -EIO; return 0; } static int fsp_get_sn(struct psmouse *psmouse, int *sn) { int v0, v1, v2; int rc = -EIO; /* production number since Cx is available at: 0x0b40 ~ 0x0b42 */ if (fsp_page_reg_write(psmouse, FSP_PAGE_0B)) goto out; if (fsp_reg_read(psmouse, FSP_REG_SN0, &v0)) goto out; if (fsp_reg_read(psmouse, FSP_REG_SN1, &v1)) goto out; if (fsp_reg_read(psmouse, FSP_REG_SN2, &v2)) goto out; *sn = (v0 << 16) | (v1 << 8) | v2; rc = 0; out: fsp_page_reg_write(psmouse, FSP_PAGE_DEFAULT); return rc; } static int fsp_get_buttons(struct psmouse *psmouse, int *btn) { static const int buttons[] = { 0x16, /* Left/Middle/Right/Forward/Backward & Scroll Up/Down */ 0x06, /* Left/Middle/Right & Scroll Up/Down/Right/Left */ 0x04, /* Left/Middle/Right & Scroll Up/Down */ 0x02, /* Left/Middle/Right */ }; int val; if (fsp_reg_read(psmouse, FSP_REG_TMOD_STATUS, &val) == -1) return -EIO; *btn = buttons[(val & 0x30) >> 4]; return 0; } /* Enable on-pad command tag output */ static int fsp_opc_tag_enable(struct psmouse *psmouse, bool enable) { int v, nv; int res = 0; if (fsp_reg_read(psmouse, FSP_REG_OPC_QDOWN, &v) == -1) { psmouse_err(psmouse, "Unable get OPC state.\n"); return -EIO; } if (enable) nv = v | FSP_BIT_EN_OPC_TAG; else nv = v & ~FSP_BIT_EN_OPC_TAG; /* only write if necessary */ if (nv != v) { fsp_reg_write_enable(psmouse, true); res = fsp_reg_write(psmouse, FSP_REG_OPC_QDOWN, nv); fsp_reg_write_enable(psmouse, false); } if (res != 0) { psmouse_err(psmouse, "Unable to enable OPC tag.\n"); res = -EIO; } return res; } static int fsp_onpad_vscr(struct psmouse *psmouse, bool enable) { struct fsp_data *pad = psmouse->private; int val; if (fsp_reg_read(psmouse, FSP_REG_ONPAD_CTL, &val)) return -EIO; pad->vscroll = enable; if (enable) val |= (FSP_BIT_FIX_VSCR | FSP_BIT_ONPAD_ENABLE); else val &= ~FSP_BIT_FIX_VSCR; if (fsp_reg_write(psmouse, FSP_REG_ONPAD_CTL, val)) return -EIO; return 0; } static int fsp_onpad_hscr(struct psmouse *psmouse, bool enable) { struct fsp_data *pad = psmouse->private; int val, v2; if (fsp_reg_read(psmouse, FSP_REG_ONPAD_CTL, &val)) return -EIO; if (fsp_reg_read(psmouse, FSP_REG_SYSCTL5, &v2)) return -EIO; pad->hscroll = enable; if (enable) { val |= (FSP_BIT_FIX_HSCR | FSP_BIT_ONPAD_ENABLE); v2 |= FSP_BIT_EN_MSID6; } else { val &= ~FSP_BIT_FIX_HSCR; v2 &= ~(FSP_BIT_EN_MSID6 | FSP_BIT_EN_MSID7 | FSP_BIT_EN_MSID8); } if (fsp_reg_write(psmouse, FSP_REG_ONPAD_CTL, val)) return -EIO; /* reconfigure horizontal scrolling packet output */ if (fsp_reg_write(psmouse, FSP_REG_SYSCTL5, v2)) return -EIO; return 0; } /* * Write device specific initial parameters. * * ex: 0xab 0xcd - write oxcd into register 0xab */ static ssize_t fsp_attr_set_setreg(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int reg, val; char *rest; ssize_t retval; reg = simple_strtoul(buf, &rest, 16); if (rest == buf || *rest != ' ' || reg > 0xff) return -EINVAL; retval = kstrtouint(rest + 1, 16, &val); if (retval) return retval; if (val > 0xff) return -EINVAL; if (fsp_reg_write_enable(psmouse, true)) return -EIO; retval = fsp_reg_write(psmouse, reg, val) < 0 ? -EIO : count; fsp_reg_write_enable(psmouse, false); return retval; } PSMOUSE_DEFINE_WO_ATTR(setreg, S_IWUSR, NULL, fsp_attr_set_setreg); static ssize_t fsp_attr_show_getreg(struct psmouse *psmouse, void *data, char *buf) { struct fsp_data *pad = psmouse->private; return sprintf(buf, "%02x%02x\n", pad->last_reg, pad->last_val); } /* * Read a register from device. * * ex: 0xab -- read content from register 0xab */ static ssize_t fsp_attr_set_getreg(struct psmouse *psmouse, void *data, const char *buf, size_t count) { struct fsp_data *pad = psmouse->private; unsigned int reg, val; int err; err = kstrtouint(buf, 16, &reg); if (err) return err; if (reg > 0xff) return -EINVAL; if (fsp_reg_read(psmouse, reg, &val)) return -EIO; pad->last_reg = reg; pad->last_val = val; return count; } PSMOUSE_DEFINE_ATTR(getreg, S_IWUSR | S_IRUGO, NULL, fsp_attr_show_getreg, fsp_attr_set_getreg); static ssize_t fsp_attr_show_pagereg(struct psmouse *psmouse, void *data, char *buf) { int val = 0; if (fsp_page_reg_read(psmouse, &val)) return -EIO; return sprintf(buf, "%02x\n", val); } static ssize_t fsp_attr_set_pagereg(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int val; int err; err = kstrtouint(buf, 16, &val); if (err) return err; if (val > 0xff) return -EINVAL; if (fsp_page_reg_write(psmouse, val)) return -EIO; return count; } PSMOUSE_DEFINE_ATTR(page, S_IWUSR | S_IRUGO, NULL, fsp_attr_show_pagereg, fsp_attr_set_pagereg); static ssize_t fsp_attr_show_vscroll(struct psmouse *psmouse, void *data, char *buf) { struct fsp_data *pad = psmouse->private; return sprintf(buf, "%d\n", pad->vscroll); } static ssize_t fsp_attr_set_vscroll(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int val; int err; err = kstrtouint(buf, 10, &val); if (err) return err; if (val > 1) return -EINVAL; fsp_onpad_vscr(psmouse, val); return count; } PSMOUSE_DEFINE_ATTR(vscroll, S_IWUSR | S_IRUGO, NULL, fsp_attr_show_vscroll, fsp_attr_set_vscroll); static ssize_t fsp_attr_show_hscroll(struct psmouse *psmouse, void *data, char *buf) { struct fsp_data *pad = psmouse->private; return sprintf(buf, "%d\n", pad->hscroll); } static ssize_t fsp_attr_set_hscroll(struct psmouse *psmouse, void *data, const char *buf, size_t count) { unsigned int val; int err; err = kstrtouint(buf, 10, &val); if (err) return err; if (val > 1) return -EINVAL; fsp_onpad_hscr(psmouse, val); return count; } PSMOUSE_DEFINE_ATTR(hscroll, S_IWUSR | S_IRUGO, NULL, fsp_attr_show_hscroll, fsp_attr_set_hscroll); static ssize_t fsp_attr_show_flags(struct psmouse *psmouse, void *data, char *buf) { struct fsp_data *pad = psmouse->private; return sprintf(buf, "%c\n", pad->flags & FSPDRV_FLAG_EN_OPC ? 'C' : 'c'); } static ssize_t fsp_attr_set_flags(struct psmouse *psmouse, void *data, const char *buf, size_t count) { struct fsp_data *pad = psmouse->private; size_t i; for (i = 0; i < count; i++) { switch (buf[i]) { case 'C': pad->flags |= FSPDRV_FLAG_EN_OPC; break; case 'c': pad->flags &= ~FSPDRV_FLAG_EN_OPC; break; default: return -EINVAL; } } return count; } PSMOUSE_DEFINE_ATTR(flags, S_IWUSR | S_IRUGO, NULL, fsp_attr_show_flags, fsp_attr_set_flags); static ssize_t fsp_attr_show_ver(struct psmouse *psmouse, void *data, char *buf) { return sprintf(buf, "Sentelic FSP kernel module %s\n", fsp_drv_ver); } PSMOUSE_DEFINE_RO_ATTR(ver, S_IRUGO, NULL, fsp_attr_show_ver); static struct attribute *fsp_attributes[] = { &psmouse_attr_setreg.dattr.attr, &psmouse_attr_getreg.dattr.attr, &psmouse_attr_page.dattr.attr, &psmouse_attr_vscroll.dattr.attr, &psmouse_attr_hscroll.dattr.attr, &psmouse_attr_flags.dattr.attr, &psmouse_attr_ver.dattr.attr, NULL }; static struct attribute_group fsp_attribute_group = { .attrs = fsp_attributes, }; #ifdef FSP_DEBUG static void fsp_packet_debug(struct psmouse *psmouse, unsigned char packet[]) { static unsigned int ps2_packet_cnt; static unsigned int ps2_last_second; unsigned int jiffies_msec; const char *packet_type = "UNKNOWN"; unsigned short abs_x = 0, abs_y = 0; /* Interpret & dump the packet data. */ switch (packet[0] >> FSP_PKT_TYPE_SHIFT) { case FSP_PKT_TYPE_ABS: packet_type = "Absolute"; abs_x = GET_ABS_X(packet); abs_y = GET_ABS_Y(packet); break; case FSP_PKT_TYPE_NORMAL: packet_type = "Normal"; break; case FSP_PKT_TYPE_NOTIFY: packet_type = "Notify"; break; case FSP_PKT_TYPE_NORMAL_OPC: packet_type = "Normal-OPC"; break; } ps2_packet_cnt++; jiffies_msec = jiffies_to_msecs(jiffies); psmouse_dbg(psmouse, "%08dms %s packets: %02x, %02x, %02x, %02x; " "abs_x: %d, abs_y: %d\n", jiffies_msec, packet_type, packet[0], packet[1], packet[2], packet[3], abs_x, abs_y); if (jiffies_msec - ps2_last_second > 1000) { psmouse_dbg(psmouse, "PS/2 packets/sec = %d\n", ps2_packet_cnt); ps2_packet_cnt = 0; ps2_last_second = jiffies_msec; } } #else static void fsp_packet_debug(struct psmouse *psmouse, unsigned char packet[]) { } #endif static void fsp_set_slot(struct input_dev *dev, int slot, bool active, unsigned int x, unsigned int y) { input_mt_slot(dev, slot); input_mt_report_slot_state(dev, MT_TOOL_FINGER, active); if (active) { input_report_abs(dev, ABS_MT_POSITION_X, x); input_report_abs(dev, ABS_MT_POSITION_Y, y); } } static psmouse_ret_t fsp_process_byte(struct psmouse *psmouse) { struct input_dev *dev = psmouse->dev; struct fsp_data *ad = psmouse->private; unsigned char *packet = psmouse->packet; unsigned char button_status = 0, lscroll = 0, rscroll = 0; unsigned short abs_x, abs_y, fgrs = 0; if (psmouse->pktcnt < 4) return PSMOUSE_GOOD_DATA; /* * Full packet accumulated, process it */ fsp_packet_debug(psmouse, packet); switch (psmouse->packet[0] >> FSP_PKT_TYPE_SHIFT) { case FSP_PKT_TYPE_ABS: if ((packet[0] == 0x48 || packet[0] == 0x49) && packet[1] == 0 && packet[2] == 0) { /* * Ignore coordinate noise when finger leaving the * surface, otherwise cursor may jump to upper-left * corner. */ packet[3] &= 0xf0; } abs_x = GET_ABS_X(packet); abs_y = GET_ABS_Y(packet); if (packet[0] & FSP_PB0_MFMC) { /* * MFMC packet: assume that there are two fingers on * pad */ fgrs = 2; /* MFMC packet */ if (packet[0] & FSP_PB0_MFMC_FGR2) { /* 2nd finger */ if (ad->last_mt_fgr == 2) { /* * workaround for buggy firmware * which doesn't clear MFMC bit if * the 1st finger is up */ fgrs = 1; fsp_set_slot(dev, 0, false, 0, 0); } ad->last_mt_fgr = 2; fsp_set_slot(dev, 1, fgrs == 2, abs_x, abs_y); } else { /* 1st finger */ if (ad->last_mt_fgr == 1) { /* * workaround for buggy firmware * which doesn't clear MFMC bit if * the 2nd finger is up */ fgrs = 1; fsp_set_slot(dev, 1, false, 0, 0); } ad->last_mt_fgr = 1; fsp_set_slot(dev, 0, fgrs != 0, abs_x, abs_y); } } else { /* SFAC packet */ if ((packet[0] & (FSP_PB0_LBTN|FSP_PB0_PHY_BTN)) == FSP_PB0_LBTN) { /* On-pad click in SFAC mode should be handled * by userspace. On-pad clicks in MFMC mode * are real clickpad clicks, and not ignored. */ packet[0] &= ~FSP_PB0_LBTN; } /* no multi-finger information */ ad->last_mt_fgr = 0; if (abs_x != 0 && abs_y != 0) fgrs = 1; fsp_set_slot(dev, 0, fgrs > 0, abs_x, abs_y); fsp_set_slot(dev, 1, false, 0, 0); } if (fgrs == 1 || (fgrs == 2 && !(packet[0] & FSP_PB0_MFMC_FGR2))) { input_report_abs(dev, ABS_X, abs_x); input_report_abs(dev, ABS_Y, abs_y); } input_report_key(dev, BTN_LEFT, packet[0] & 0x01); input_report_key(dev, BTN_RIGHT, packet[0] & 0x02); input_report_key(dev, BTN_TOUCH, fgrs); input_report_key(dev, BTN_TOOL_FINGER, fgrs == 1); input_report_key(dev, BTN_TOOL_DOUBLETAP, fgrs == 2); break; case FSP_PKT_TYPE_NORMAL_OPC: /* on-pad click, filter it if necessary */ if ((ad->flags & FSPDRV_FLAG_EN_OPC) != FSPDRV_FLAG_EN_OPC) packet[0] &= ~FSP_PB0_LBTN; fallthrough; case FSP_PKT_TYPE_NORMAL: /* normal packet */ /* special packet data translation from on-pad packets */ if (packet[3] != 0) { if (packet[3] & BIT(0)) button_status |= 0x01; /* wheel down */ if (packet[3] & BIT(1)) button_status |= 0x0f; /* wheel up */ if (packet[3] & BIT(2)) button_status |= BIT(4);/* horizontal left */ if (packet[3] & BIT(3)) button_status |= BIT(5);/* horizontal right */ /* push back to packet queue */ if (button_status != 0) packet[3] = button_status; rscroll = (packet[3] >> 4) & 1; lscroll = (packet[3] >> 5) & 1; } /* * Processing wheel up/down and extra button events */ input_report_rel(dev, REL_WHEEL, (int)(packet[3] & 8) - (int)(packet[3] & 7)); input_report_rel(dev, REL_HWHEEL, lscroll - rscroll); input_report_key(dev, BTN_BACK, lscroll); input_report_key(dev, BTN_FORWARD, rscroll); /* * Standard PS/2 Mouse */ psmouse_report_standard_packet(dev, packet); break; } input_sync(dev); return PSMOUSE_FULL_PACKET; } static int fsp_activate_protocol(struct psmouse *psmouse) { struct fsp_data *pad = psmouse->private; struct ps2dev *ps2dev = &psmouse->ps2dev; unsigned char param[2]; int val; /* * Standard procedure to enter FSP Intellimouse mode * (scrolling wheel, 4th and 5th buttons) */ param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 200; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); param[0] = 80; ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE); ps2_command(ps2dev, param, PSMOUSE_CMD_GETID); if (param[0] != 0x04) { psmouse_err(psmouse, "Unable to enable 4 bytes packet format.\n"); return -EIO; } if (pad->ver < FSP_VER_STL3888_C0) { /* Preparing relative coordinates output for older hardware */ if (fsp_reg_read(psmouse, FSP_REG_SYSCTL5, &val)) { psmouse_err(psmouse, "Unable to read SYSCTL5 register.\n"); return -EIO; } if (fsp_get_buttons(psmouse, &pad->buttons)) { psmouse_err(psmouse, "Unable to retrieve number of buttons.\n"); return -EIO; } val &= ~(FSP_BIT_EN_MSID7 | FSP_BIT_EN_MSID8 | FSP_BIT_EN_AUTO_MSID8); /* Ensure we are not in absolute mode */ val &= ~FSP_BIT_EN_PKT_G0; if (pad->buttons == 0x06) { /* Left/Middle/Right & Scroll Up/Down/Right/Left */ val |= FSP_BIT_EN_MSID6; } if (fsp_reg_write(psmouse, FSP_REG_SYSCTL5, val)) { psmouse_err(psmouse, "Unable to set up required mode bits.\n"); return -EIO; } /* * Enable OPC tags such that driver can tell the difference * between on-pad and real button click */ if (fsp_opc_tag_enable(psmouse, true)) psmouse_warn(psmouse, "Failed to enable OPC tag mode.\n"); /* enable on-pad click by default */ pad->flags |= FSPDRV_FLAG_EN_OPC; /* Enable on-pad vertical and horizontal scrolling */ fsp_onpad_vscr(psmouse, true); fsp_onpad_hscr(psmouse, true); } else { /* Enable absolute coordinates output for Cx/Dx hardware */ if (fsp_reg_write(psmouse, FSP_REG_SWC1, FSP_BIT_SWC1_EN_ABS_1F | FSP_BIT_SWC1_EN_ABS_2F | FSP_BIT_SWC1_EN_FUP_OUT | FSP_BIT_SWC1_EN_ABS_CON)) { psmouse_err(psmouse, "Unable to enable absolute coordinates output.\n"); return -EIO; } } return 0; } static int fsp_set_input_params(struct psmouse *psmouse) { struct input_dev *dev = psmouse->dev; struct fsp_data *pad = psmouse->private; if (pad->ver < FSP_VER_STL3888_C0) { __set_bit(BTN_MIDDLE, dev->keybit); __set_bit(BTN_BACK, dev->keybit); __set_bit(BTN_FORWARD, dev->keybit); __set_bit(REL_WHEEL, dev->relbit); __set_bit(REL_HWHEEL, dev->relbit); } else { /* * Hardware prior to Cx performs much better in relative mode; * hence, only enable absolute coordinates output as well as * multi-touch output for the newer hardware. * * Maximum coordinates can be computed as: * * number of scanlines * 64 - 57 * * where number of X/Y scanline lines are 16/12. */ int abs_x = 967, abs_y = 711; __set_bit(EV_ABS, dev->evbit); __clear_bit(EV_REL, dev->evbit); __set_bit(BTN_TOUCH, dev->keybit); __set_bit(BTN_TOOL_FINGER, dev->keybit); __set_bit(BTN_TOOL_DOUBLETAP, dev->keybit); __set_bit(INPUT_PROP_SEMI_MT, dev->propbit); input_set_abs_params(dev, ABS_X, 0, abs_x, 0, 0); input_set_abs_params(dev, ABS_Y, 0, abs_y, 0, 0); input_mt_init_slots(dev, 2, 0); input_set_abs_params(dev, ABS_MT_POSITION_X, 0, abs_x, 0, 0); input_set_abs_params(dev, ABS_MT_POSITION_Y, 0, abs_y, 0, 0); } return 0; } int fsp_detect(struct psmouse *psmouse, bool set_properties) { int id; if (fsp_reg_read(psmouse, FSP_REG_DEVICE_ID, &id)) return -EIO; if (id != 0x01) return -ENODEV; if (set_properties) { psmouse->vendor = "Sentelic"; psmouse->name = "FingerSensingPad"; } return 0; } static void fsp_reset(struct psmouse *psmouse) { fsp_opc_tag_enable(psmouse, false); fsp_onpad_vscr(psmouse, false); fsp_onpad_hscr(psmouse, false); } static void fsp_disconnect(struct psmouse *psmouse) { sysfs_remove_group(&psmouse->ps2dev.serio->dev.kobj, &fsp_attribute_group); fsp_reset(psmouse); kfree(psmouse->private); } static int fsp_reconnect(struct psmouse *psmouse) { int version; if (fsp_detect(psmouse, 0)) return -ENODEV; if (fsp_get_version(psmouse, &version)) return -ENODEV; if (fsp_activate_protocol(psmouse)) return -EIO; return 0; } int fsp_init(struct psmouse *psmouse) { struct fsp_data *priv; int ver, rev, sn = 0; int error; if (fsp_get_version(psmouse, &ver) || fsp_get_revision(psmouse, &rev)) { return -ENODEV; } if (ver >= FSP_VER_STL3888_C0) { /* firmware information is only available since C0 */ fsp_get_sn(psmouse, &sn); } psmouse_info(psmouse, "Finger Sensing Pad, hw: %d.%d.%d, sn: %x, sw: %s\n", ver >> 4, ver & 0x0F, rev, sn, fsp_drv_ver); psmouse->private = priv = kzalloc(sizeof(struct fsp_data), GFP_KERNEL); if (!priv) return -ENOMEM; priv->ver = ver; priv->rev = rev; psmouse->protocol_handler = fsp_process_byte; psmouse->disconnect = fsp_disconnect; psmouse->reconnect = fsp_reconnect; psmouse->cleanup = fsp_reset; psmouse->pktsize = 4; error = fsp_activate_protocol(psmouse); if (error) goto err_out; /* Set up various supported input event bits */ error = fsp_set_input_params(psmouse); if (error) goto err_out; error = sysfs_create_group(&psmouse->ps2dev.serio->dev.kobj, &fsp_attribute_group); if (error) { psmouse_err(psmouse, "Failed to create sysfs attributes (%d)", error); goto err_out; } return 0; err_out: kfree(psmouse->private); psmouse->private = NULL; return error; }
linux-master
drivers/input/mouse/sentelic.c
// SPDX-License-Identifier: GPL-2.0-only /* * Synaptics NavPoint (PXA27x SSP/SPI) driver. * * Copyright (C) 2012 Paul Parsons <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio.h> #include <linux/input.h> #include <linux/input/navpoint.h> #include <linux/interrupt.h> #include <linux/mutex.h> #include <linux/pxa2xx_ssp.h> #include <linux/slab.h> /* * Synaptics Modular Embedded Protocol: Module Packet Format. * Module header byte 2:0 = Length (# bytes that follow) * Module header byte 4:3 = Control * Module header byte 7:5 = Module Address */ #define HEADER_LENGTH(byte) ((byte) & 0x07) #define HEADER_CONTROL(byte) (((byte) >> 3) & 0x03) #define HEADER_ADDRESS(byte) ((byte) >> 5) struct navpoint { struct ssp_device *ssp; struct input_dev *input; struct device *dev; int gpio; int index; u8 data[1 + HEADER_LENGTH(0xff)]; }; /* * Initialization values for SSCR0_x, SSCR1_x, SSSR_x. */ static const u32 sscr0 = 0 | SSCR0_TUM /* TIM = 1; No TUR interrupts */ | SSCR0_RIM /* RIM = 1; No ROR interrupts */ | SSCR0_SSE /* SSE = 1; SSP enabled */ | SSCR0_Motorola /* FRF = 0; Motorola SPI */ | SSCR0_DataSize(16) /* DSS = 15; Data size = 16-bit */ ; static const u32 sscr1 = 0 | SSCR1_SCFR /* SCFR = 1; SSPSCLK only during transfers */ | SSCR1_SCLKDIR /* SCLKDIR = 1; Slave mode */ | SSCR1_SFRMDIR /* SFRMDIR = 1; Slave mode */ | SSCR1_RWOT /* RWOT = 1; Receive without transmit mode */ | SSCR1_RxTresh(1) /* RFT = 0; Receive FIFO threshold = 1 */ | SSCR1_SPH /* SPH = 1; SSPSCLK inactive 0.5 + 1 cycles */ | SSCR1_RIE /* RIE = 1; Receive FIFO interrupt enabled */ ; static const u32 sssr = 0 | SSSR_BCE /* BCE = 1; Clear BCE */ | SSSR_TUR /* TUR = 1; Clear TUR */ | SSSR_EOC /* EOC = 1; Clear EOC */ | SSSR_TINT /* TINT = 1; Clear TINT */ | SSSR_PINT /* PINT = 1; Clear PINT */ | SSSR_ROR /* ROR = 1; Clear ROR */ ; /* * MEP Query $22: Touchpad Coordinate Range Query is not supported by * the NavPoint module, so sampled values provide the default limits. */ #define NAVPOINT_X_MIN 1278 #define NAVPOINT_X_MAX 5340 #define NAVPOINT_Y_MIN 1572 #define NAVPOINT_Y_MAX 4396 #define NAVPOINT_PRESSURE_MIN 0 #define NAVPOINT_PRESSURE_MAX 255 static void navpoint_packet(struct navpoint *navpoint) { int finger; int gesture; int x, y, z; switch (navpoint->data[0]) { case 0xff: /* Garbage (packet?) between reset and Hello packet */ case 0x00: /* Module 0, NULL packet */ break; case 0x0e: /* Module 0, Absolute packet */ finger = (navpoint->data[1] & 0x01); gesture = (navpoint->data[1] & 0x02); x = ((navpoint->data[2] & 0x1f) << 8) | navpoint->data[3]; y = ((navpoint->data[4] & 0x1f) << 8) | navpoint->data[5]; z = navpoint->data[6]; input_report_key(navpoint->input, BTN_TOUCH, finger); input_report_abs(navpoint->input, ABS_X, x); input_report_abs(navpoint->input, ABS_Y, y); input_report_abs(navpoint->input, ABS_PRESSURE, z); input_report_key(navpoint->input, BTN_TOOL_FINGER, finger); input_report_key(navpoint->input, BTN_LEFT, gesture); input_sync(navpoint->input); break; case 0x19: /* Module 0, Hello packet */ if ((navpoint->data[1] & 0xf0) == 0x10) break; fallthrough; default: dev_warn(navpoint->dev, "spurious packet: data=0x%02x,0x%02x,...\n", navpoint->data[0], navpoint->data[1]); break; } } static irqreturn_t navpoint_irq(int irq, void *dev_id) { struct navpoint *navpoint = dev_id; struct ssp_device *ssp = navpoint->ssp; irqreturn_t ret = IRQ_NONE; u32 status; status = pxa_ssp_read_reg(ssp, SSSR); if (status & sssr) { dev_warn(navpoint->dev, "unexpected interrupt: status=0x%08x\n", status); pxa_ssp_write_reg(ssp, SSSR, (status & sssr)); ret = IRQ_HANDLED; } while (status & SSSR_RNE) { u32 data; data = pxa_ssp_read_reg(ssp, SSDR); navpoint->data[navpoint->index + 0] = (data >> 8); navpoint->data[navpoint->index + 1] = data; navpoint->index += 2; if (HEADER_LENGTH(navpoint->data[0]) < navpoint->index) { navpoint_packet(navpoint); navpoint->index = 0; } status = pxa_ssp_read_reg(ssp, SSSR); ret = IRQ_HANDLED; } return ret; } static void navpoint_up(struct navpoint *navpoint) { struct ssp_device *ssp = navpoint->ssp; int timeout; clk_prepare_enable(ssp->clk); pxa_ssp_write_reg(ssp, SSCR1, sscr1); pxa_ssp_write_reg(ssp, SSSR, sssr); pxa_ssp_write_reg(ssp, SSTO, 0); pxa_ssp_write_reg(ssp, SSCR0, sscr0); /* SSCR0_SSE written last */ /* Wait until SSP port is ready for slave clock operations */ for (timeout = 100; timeout != 0; --timeout) { if (!(pxa_ssp_read_reg(ssp, SSSR) & SSSR_CSS)) break; msleep(1); } if (timeout == 0) dev_err(navpoint->dev, "timeout waiting for SSSR[CSS] to clear\n"); if (gpio_is_valid(navpoint->gpio)) gpio_set_value(navpoint->gpio, 1); } static void navpoint_down(struct navpoint *navpoint) { struct ssp_device *ssp = navpoint->ssp; if (gpio_is_valid(navpoint->gpio)) gpio_set_value(navpoint->gpio, 0); pxa_ssp_write_reg(ssp, SSCR0, 0); clk_disable_unprepare(ssp->clk); } static int navpoint_open(struct input_dev *input) { struct navpoint *navpoint = input_get_drvdata(input); navpoint_up(navpoint); return 0; } static void navpoint_close(struct input_dev *input) { struct navpoint *navpoint = input_get_drvdata(input); navpoint_down(navpoint); } static int navpoint_probe(struct platform_device *pdev) { const struct navpoint_platform_data *pdata = dev_get_platdata(&pdev->dev); struct ssp_device *ssp; struct input_dev *input; struct navpoint *navpoint; int error; if (!pdata) { dev_err(&pdev->dev, "no platform data\n"); return -EINVAL; } if (gpio_is_valid(pdata->gpio)) { error = gpio_request_one(pdata->gpio, GPIOF_OUT_INIT_LOW, "SYNAPTICS_ON"); if (error) return error; } ssp = pxa_ssp_request(pdata->port, pdev->name); if (!ssp) { error = -ENODEV; goto err_free_gpio; } /* HaRET does not disable devices before jumping into Linux */ if (pxa_ssp_read_reg(ssp, SSCR0) & SSCR0_SSE) { pxa_ssp_write_reg(ssp, SSCR0, 0); dev_warn(&pdev->dev, "ssp%d already enabled\n", pdata->port); } navpoint = kzalloc(sizeof(*navpoint), GFP_KERNEL); input = input_allocate_device(); if (!navpoint || !input) { error = -ENOMEM; goto err_free_mem; } navpoint->ssp = ssp; navpoint->input = input; navpoint->dev = &pdev->dev; navpoint->gpio = pdata->gpio; input->name = pdev->name; input->dev.parent = &pdev->dev; __set_bit(EV_KEY, input->evbit); __set_bit(EV_ABS, input->evbit); __set_bit(BTN_LEFT, input->keybit); __set_bit(BTN_TOUCH, input->keybit); __set_bit(BTN_TOOL_FINGER, input->keybit); input_set_abs_params(input, ABS_X, NAVPOINT_X_MIN, NAVPOINT_X_MAX, 0, 0); input_set_abs_params(input, ABS_Y, NAVPOINT_Y_MIN, NAVPOINT_Y_MAX, 0, 0); input_set_abs_params(input, ABS_PRESSURE, NAVPOINT_PRESSURE_MIN, NAVPOINT_PRESSURE_MAX, 0, 0); input->open = navpoint_open; input->close = navpoint_close; input_set_drvdata(input, navpoint); error = request_irq(ssp->irq, navpoint_irq, 0, pdev->name, navpoint); if (error) goto err_free_mem; error = input_register_device(input); if (error) goto err_free_irq; platform_set_drvdata(pdev, navpoint); dev_dbg(&pdev->dev, "ssp%d, irq %d\n", pdata->port, ssp->irq); return 0; err_free_irq: free_irq(ssp->irq, navpoint); err_free_mem: input_free_device(input); kfree(navpoint); pxa_ssp_free(ssp); err_free_gpio: if (gpio_is_valid(pdata->gpio)) gpio_free(pdata->gpio); return error; } static int navpoint_remove(struct platform_device *pdev) { const struct navpoint_platform_data *pdata = dev_get_platdata(&pdev->dev); struct navpoint *navpoint = platform_get_drvdata(pdev); struct ssp_device *ssp = navpoint->ssp; free_irq(ssp->irq, navpoint); input_unregister_device(navpoint->input); kfree(navpoint); pxa_ssp_free(ssp); if (gpio_is_valid(pdata->gpio)) gpio_free(pdata->gpio); return 0; } static int navpoint_suspend(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct navpoint *navpoint = platform_get_drvdata(pdev); struct input_dev *input = navpoint->input; mutex_lock(&input->mutex); if (input_device_enabled(input)) navpoint_down(navpoint); mutex_unlock(&input->mutex); return 0; } static int navpoint_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct navpoint *navpoint = platform_get_drvdata(pdev); struct input_dev *input = navpoint->input; mutex_lock(&input->mutex); if (input_device_enabled(input)) navpoint_up(navpoint); mutex_unlock(&input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(navpoint_pm_ops, navpoint_suspend, navpoint_resume); static struct platform_driver navpoint_driver = { .probe = navpoint_probe, .remove = navpoint_remove, .driver = { .name = "navpoint", .pm = pm_sleep_ptr(&navpoint_pm_ops), }, }; module_platform_driver(navpoint_driver); MODULE_AUTHOR("Paul Parsons <[email protected]>"); MODULE_DESCRIPTION("Synaptics NavPoint (PXA27x SSP/SPI) driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:navpoint");
linux-master
drivers/input/mouse/navpoint.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * USB Synaptics device driver * * Copyright (c) 2002 Rob Miller (rob@inpharmatica . co . uk) * Copyright (c) 2003 Ron Lee ([email protected]) * cPad driver for kernel 2.4 * * Copyright (c) 2004 Jan Steinhoff (cpad@jan-steinhoff . de) * Copyright (c) 2004 Ron Lee ([email protected]) * rewritten for kernel 2.6 * * cPad display character device part is not included. It can be found at * http://jan-steinhoff.de/linux/synaptics-usb.html * * Bases on: usb_skeleton.c v2.2 by Greg Kroah-Hartman * drivers/hid/usbhid/usbmouse.c by Vojtech Pavlik * drivers/input/mouse/synaptics.c by Peter Osterlund * * Trademarks are the property of their respective owners. */ /* * There are three different types of Synaptics USB devices: Touchpads, * touchsticks (or trackpoints), and touchscreens. Touchpads are well supported * by this driver, touchstick support has not been tested much yet, and * touchscreens have not been tested at all. * * Up to three alternate settings are possible: * setting 0: one int endpoint for relative movement (used by usbhid.ko) * setting 1: one int endpoint for absolute finger position * setting 2 (cPad only): one int endpoint for absolute finger position and * two bulk endpoints for the display (in/out) * This driver uses setting 1. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/usb.h> #include <linux/input.h> #include <linux/usb/input.h> #define USB_VENDOR_ID_SYNAPTICS 0x06cb #define USB_DEVICE_ID_SYNAPTICS_TP 0x0001 /* Synaptics USB TouchPad */ #define USB_DEVICE_ID_SYNAPTICS_INT_TP 0x0002 /* Integrated USB TouchPad */ #define USB_DEVICE_ID_SYNAPTICS_CPAD 0x0003 /* Synaptics cPad */ #define USB_DEVICE_ID_SYNAPTICS_TS 0x0006 /* Synaptics TouchScreen */ #define USB_DEVICE_ID_SYNAPTICS_STICK 0x0007 /* Synaptics USB Styk */ #define USB_DEVICE_ID_SYNAPTICS_WP 0x0008 /* Synaptics USB WheelPad */ #define USB_DEVICE_ID_SYNAPTICS_COMP_TP 0x0009 /* Composite USB TouchPad */ #define USB_DEVICE_ID_SYNAPTICS_WTP 0x0010 /* Wireless TouchPad */ #define USB_DEVICE_ID_SYNAPTICS_DPAD 0x0013 /* DisplayPad */ #define SYNUSB_TOUCHPAD (1 << 0) #define SYNUSB_STICK (1 << 1) #define SYNUSB_TOUCHSCREEN (1 << 2) #define SYNUSB_AUXDISPLAY (1 << 3) /* For cPad */ #define SYNUSB_COMBO (1 << 4) /* Composite device (TP + stick) */ #define SYNUSB_IO_ALWAYS (1 << 5) #define USB_DEVICE_SYNAPTICS(prod, kind) \ USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, \ USB_DEVICE_ID_SYNAPTICS_##prod), \ .driver_info = (kind), #define SYNUSB_RECV_SIZE 8 #define XMIN_NOMINAL 1472 #define XMAX_NOMINAL 5472 #define YMIN_NOMINAL 1408 #define YMAX_NOMINAL 4448 struct synusb { struct usb_device *udev; struct usb_interface *intf; struct urb *urb; unsigned char *data; /* serialize access to open/suspend */ struct mutex pm_mutex; bool is_open; /* input device related data structures */ struct input_dev *input; char name[128]; char phys[64]; /* characteristics of the device */ unsigned long flags; }; static void synusb_report_buttons(struct synusb *synusb) { struct input_dev *input_dev = synusb->input; input_report_key(input_dev, BTN_LEFT, synusb->data[1] & 0x04); input_report_key(input_dev, BTN_RIGHT, synusb->data[1] & 0x01); input_report_key(input_dev, BTN_MIDDLE, synusb->data[1] & 0x02); } static void synusb_report_stick(struct synusb *synusb) { struct input_dev *input_dev = synusb->input; int x, y; unsigned int pressure; pressure = synusb->data[6]; x = (s16)(be16_to_cpup((__be16 *)&synusb->data[2]) << 3) >> 7; y = (s16)(be16_to_cpup((__be16 *)&synusb->data[4]) << 3) >> 7; if (pressure > 0) { input_report_rel(input_dev, REL_X, x); input_report_rel(input_dev, REL_Y, -y); } input_report_abs(input_dev, ABS_PRESSURE, pressure); synusb_report_buttons(synusb); input_sync(input_dev); } static void synusb_report_touchpad(struct synusb *synusb) { struct input_dev *input_dev = synusb->input; unsigned int num_fingers, tool_width; unsigned int x, y; unsigned int pressure, w; pressure = synusb->data[6]; x = be16_to_cpup((__be16 *)&synusb->data[2]); y = be16_to_cpup((__be16 *)&synusb->data[4]); w = synusb->data[0] & 0x0f; if (pressure > 0) { num_fingers = 1; tool_width = 5; switch (w) { case 0 ... 1: num_fingers = 2 + w; break; case 2: /* pen, pretend its a finger */ break; case 4 ... 15: tool_width = w; break; } } else { num_fingers = 0; tool_width = 0; } /* * Post events * BTN_TOUCH has to be first as mousedev relies on it when doing * absolute -> relative conversion */ if (pressure > 30) input_report_key(input_dev, BTN_TOUCH, 1); if (pressure < 25) input_report_key(input_dev, BTN_TOUCH, 0); if (num_fingers > 0) { input_report_abs(input_dev, ABS_X, x); input_report_abs(input_dev, ABS_Y, YMAX_NOMINAL + YMIN_NOMINAL - y); } input_report_abs(input_dev, ABS_PRESSURE, pressure); input_report_abs(input_dev, ABS_TOOL_WIDTH, tool_width); input_report_key(input_dev, BTN_TOOL_FINGER, num_fingers == 1); input_report_key(input_dev, BTN_TOOL_DOUBLETAP, num_fingers == 2); input_report_key(input_dev, BTN_TOOL_TRIPLETAP, num_fingers == 3); synusb_report_buttons(synusb); if (synusb->flags & SYNUSB_AUXDISPLAY) input_report_key(input_dev, BTN_MIDDLE, synusb->data[1] & 0x08); input_sync(input_dev); } static void synusb_irq(struct urb *urb) { struct synusb *synusb = urb->context; int error; /* Check our status in case we need to bail out early. */ switch (urb->status) { case 0: usb_mark_last_busy(synusb->udev); break; /* Device went away so don't keep trying to read from it. */ case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: return; default: goto resubmit; break; } if (synusb->flags & SYNUSB_STICK) synusb_report_stick(synusb); else synusb_report_touchpad(synusb); resubmit: error = usb_submit_urb(urb, GFP_ATOMIC); if (error && error != -EPERM) dev_err(&synusb->intf->dev, "%s - usb_submit_urb failed with result: %d", __func__, error); } static struct usb_endpoint_descriptor * synusb_get_in_endpoint(struct usb_host_interface *iface) { struct usb_endpoint_descriptor *endpoint; int i; for (i = 0; i < iface->desc.bNumEndpoints; ++i) { endpoint = &iface->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) { /* we found our interrupt in endpoint */ return endpoint; } } return NULL; } static int synusb_open(struct input_dev *dev) { struct synusb *synusb = input_get_drvdata(dev); int retval; retval = usb_autopm_get_interface(synusb->intf); if (retval) { dev_err(&synusb->intf->dev, "%s - usb_autopm_get_interface failed, error: %d\n", __func__, retval); return retval; } mutex_lock(&synusb->pm_mutex); retval = usb_submit_urb(synusb->urb, GFP_KERNEL); if (retval) { dev_err(&synusb->intf->dev, "%s - usb_submit_urb failed, error: %d\n", __func__, retval); retval = -EIO; goto out; } synusb->intf->needs_remote_wakeup = 1; synusb->is_open = true; out: mutex_unlock(&synusb->pm_mutex); usb_autopm_put_interface(synusb->intf); return retval; } static void synusb_close(struct input_dev *dev) { struct synusb *synusb = input_get_drvdata(dev); int autopm_error; autopm_error = usb_autopm_get_interface(synusb->intf); mutex_lock(&synusb->pm_mutex); usb_kill_urb(synusb->urb); synusb->intf->needs_remote_wakeup = 0; synusb->is_open = false; mutex_unlock(&synusb->pm_mutex); if (!autopm_error) usb_autopm_put_interface(synusb->intf); } static int synusb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *ep; struct synusb *synusb; struct input_dev *input_dev; unsigned int intf_num = intf->cur_altsetting->desc.bInterfaceNumber; unsigned int altsetting = min(intf->num_altsetting, 1U); int error; error = usb_set_interface(udev, intf_num, altsetting); if (error) { dev_err(&udev->dev, "Can not set alternate setting to %i, error: %i", altsetting, error); return error; } ep = synusb_get_in_endpoint(intf->cur_altsetting); if (!ep) return -ENODEV; synusb = kzalloc(sizeof(*synusb), GFP_KERNEL); input_dev = input_allocate_device(); if (!synusb || !input_dev) { error = -ENOMEM; goto err_free_mem; } synusb->udev = udev; synusb->intf = intf; synusb->input = input_dev; mutex_init(&synusb->pm_mutex); synusb->flags = id->driver_info; if (synusb->flags & SYNUSB_COMBO) { /* * This is a combo device, we need to set proper * capability, depending on the interface. */ synusb->flags |= intf_num == 1 ? SYNUSB_STICK : SYNUSB_TOUCHPAD; } synusb->urb = usb_alloc_urb(0, GFP_KERNEL); if (!synusb->urb) { error = -ENOMEM; goto err_free_mem; } synusb->data = usb_alloc_coherent(udev, SYNUSB_RECV_SIZE, GFP_KERNEL, &synusb->urb->transfer_dma); if (!synusb->data) { error = -ENOMEM; goto err_free_urb; } usb_fill_int_urb(synusb->urb, udev, usb_rcvintpipe(udev, ep->bEndpointAddress), synusb->data, SYNUSB_RECV_SIZE, synusb_irq, synusb, ep->bInterval); synusb->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (udev->manufacturer) strscpy(synusb->name, udev->manufacturer, sizeof(synusb->name)); if (udev->product) { if (udev->manufacturer) strlcat(synusb->name, " ", sizeof(synusb->name)); strlcat(synusb->name, udev->product, sizeof(synusb->name)); } if (!strlen(synusb->name)) snprintf(synusb->name, sizeof(synusb->name), "USB Synaptics Device %04x:%04x", le16_to_cpu(udev->descriptor.idVendor), le16_to_cpu(udev->descriptor.idProduct)); if (synusb->flags & SYNUSB_STICK) strlcat(synusb->name, " (Stick)", sizeof(synusb->name)); usb_make_path(udev, synusb->phys, sizeof(synusb->phys)); strlcat(synusb->phys, "/input0", sizeof(synusb->phys)); input_dev->name = synusb->name; input_dev->phys = synusb->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &synusb->intf->dev; if (!(synusb->flags & SYNUSB_IO_ALWAYS)) { input_dev->open = synusb_open; input_dev->close = synusb_close; } input_set_drvdata(input_dev, synusb); __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); if (synusb->flags & SYNUSB_STICK) { __set_bit(EV_REL, input_dev->evbit); __set_bit(REL_X, input_dev->relbit); __set_bit(REL_Y, input_dev->relbit); __set_bit(INPUT_PROP_POINTING_STICK, input_dev->propbit); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 127, 0, 0); } else { input_set_abs_params(input_dev, ABS_X, XMIN_NOMINAL, XMAX_NOMINAL, 0, 0); input_set_abs_params(input_dev, ABS_Y, YMIN_NOMINAL, YMAX_NOMINAL, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 255, 0, 0); input_set_abs_params(input_dev, ABS_TOOL_WIDTH, 0, 15, 0, 0); __set_bit(BTN_TOUCH, input_dev->keybit); __set_bit(BTN_TOOL_FINGER, input_dev->keybit); __set_bit(BTN_TOOL_DOUBLETAP, input_dev->keybit); __set_bit(BTN_TOOL_TRIPLETAP, input_dev->keybit); } if (synusb->flags & SYNUSB_TOUCHSCREEN) __set_bit(INPUT_PROP_DIRECT, input_dev->propbit); else __set_bit(INPUT_PROP_POINTER, input_dev->propbit); __set_bit(BTN_LEFT, input_dev->keybit); __set_bit(BTN_RIGHT, input_dev->keybit); __set_bit(BTN_MIDDLE, input_dev->keybit); usb_set_intfdata(intf, synusb); if (synusb->flags & SYNUSB_IO_ALWAYS) { error = synusb_open(input_dev); if (error) goto err_free_dma; } error = input_register_device(input_dev); if (error) { dev_err(&udev->dev, "Failed to register input device, error %d\n", error); goto err_stop_io; } return 0; err_stop_io: if (synusb->flags & SYNUSB_IO_ALWAYS) synusb_close(synusb->input); err_free_dma: usb_free_coherent(udev, SYNUSB_RECV_SIZE, synusb->data, synusb->urb->transfer_dma); err_free_urb: usb_free_urb(synusb->urb); err_free_mem: input_free_device(input_dev); kfree(synusb); usb_set_intfdata(intf, NULL); return error; } static void synusb_disconnect(struct usb_interface *intf) { struct synusb *synusb = usb_get_intfdata(intf); struct usb_device *udev = interface_to_usbdev(intf); if (synusb->flags & SYNUSB_IO_ALWAYS) synusb_close(synusb->input); input_unregister_device(synusb->input); usb_free_coherent(udev, SYNUSB_RECV_SIZE, synusb->data, synusb->urb->transfer_dma); usb_free_urb(synusb->urb); kfree(synusb); usb_set_intfdata(intf, NULL); } static int synusb_suspend(struct usb_interface *intf, pm_message_t message) { struct synusb *synusb = usb_get_intfdata(intf); mutex_lock(&synusb->pm_mutex); usb_kill_urb(synusb->urb); mutex_unlock(&synusb->pm_mutex); return 0; } static int synusb_resume(struct usb_interface *intf) { struct synusb *synusb = usb_get_intfdata(intf); int retval = 0; mutex_lock(&synusb->pm_mutex); if ((synusb->is_open || (synusb->flags & SYNUSB_IO_ALWAYS)) && usb_submit_urb(synusb->urb, GFP_NOIO) < 0) { retval = -EIO; } mutex_unlock(&synusb->pm_mutex); return retval; } static int synusb_pre_reset(struct usb_interface *intf) { struct synusb *synusb = usb_get_intfdata(intf); mutex_lock(&synusb->pm_mutex); usb_kill_urb(synusb->urb); return 0; } static int synusb_post_reset(struct usb_interface *intf) { struct synusb *synusb = usb_get_intfdata(intf); int retval = 0; if ((synusb->is_open || (synusb->flags & SYNUSB_IO_ALWAYS)) && usb_submit_urb(synusb->urb, GFP_NOIO) < 0) { retval = -EIO; } mutex_unlock(&synusb->pm_mutex); return retval; } static int synusb_reset_resume(struct usb_interface *intf) { return synusb_resume(intf); } static const struct usb_device_id synusb_idtable[] = { { USB_DEVICE_SYNAPTICS(TP, SYNUSB_TOUCHPAD) }, { USB_DEVICE_SYNAPTICS(INT_TP, SYNUSB_TOUCHPAD) }, { USB_DEVICE_SYNAPTICS(CPAD, SYNUSB_TOUCHPAD | SYNUSB_AUXDISPLAY | SYNUSB_IO_ALWAYS) }, { USB_DEVICE_SYNAPTICS(TS, SYNUSB_TOUCHSCREEN) }, { USB_DEVICE_SYNAPTICS(STICK, SYNUSB_STICK) }, { USB_DEVICE_SYNAPTICS(WP, SYNUSB_TOUCHPAD) }, { USB_DEVICE_SYNAPTICS(COMP_TP, SYNUSB_COMBO) }, { USB_DEVICE_SYNAPTICS(WTP, SYNUSB_TOUCHPAD) }, { USB_DEVICE_SYNAPTICS(DPAD, SYNUSB_TOUCHPAD) }, { } }; MODULE_DEVICE_TABLE(usb, synusb_idtable); static struct usb_driver synusb_driver = { .name = "synaptics_usb", .probe = synusb_probe, .disconnect = synusb_disconnect, .id_table = synusb_idtable, .suspend = synusb_suspend, .resume = synusb_resume, .pre_reset = synusb_pre_reset, .post_reset = synusb_post_reset, .reset_resume = synusb_reset_resume, .supports_autosuspend = 1, }; module_usb_driver(synusb_driver); MODULE_AUTHOR("Rob Miller <[email protected]>, " "Ron Lee <[email protected]>, " "Jan Steinhoff <[email protected]>"); MODULE_DESCRIPTION("Synaptics USB device driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/mouse/synaptics_usb.c
// SPDX-License-Identifier: GPL-2.0-only /* * Cypress Trackpad PS/2 mouse driver * * Copyright (c) 2012 Cypress Semiconductor Corporation. * * Author: * Dudley Du <[email protected]> * * Additional contributors include: * Kamal Mostafa <[email protected]> * Kyle Fazzari <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/serio.h> #include <linux/libps2.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/sched.h> #include <linux/wait.h> #include "cypress_ps2.h" #undef CYTP_DEBUG_VERBOSE /* define this and DEBUG for more verbose dump */ static void cypress_set_packet_size(struct psmouse *psmouse, unsigned int n) { struct cytp_data *cytp = psmouse->private; cytp->pkt_size = n; } static const unsigned char cytp_rate[] = {10, 20, 40, 60, 100, 200}; static const unsigned char cytp_resolution[] = {0x00, 0x01, 0x02, 0x03}; static int cypress_ps2_sendbyte(struct psmouse *psmouse, int value) { struct ps2dev *ps2dev = &psmouse->ps2dev; if (ps2_sendbyte(ps2dev, value & 0xff, CYTP_CMD_TIMEOUT) < 0) { psmouse_dbg(psmouse, "sending command 0x%02x failed, resp 0x%02x\n", value & 0xff, ps2dev->nak); if (ps2dev->nak == CYTP_PS2_RETRY) return CYTP_PS2_RETRY; else return CYTP_PS2_ERROR; } #ifdef CYTP_DEBUG_VERBOSE psmouse_dbg(psmouse, "sending command 0x%02x succeeded, resp 0xfa\n", value & 0xff); #endif return 0; } static int cypress_ps2_ext_cmd(struct psmouse *psmouse, unsigned short cmd, unsigned char data) { struct ps2dev *ps2dev = &psmouse->ps2dev; int tries = CYTP_PS2_CMD_TRIES; int rc; ps2_begin_command(ps2dev); do { /* * Send extension command byte (0xE8 or 0xF3). * If sending the command fails, send recovery command * to make the device return to the ready state. */ rc = cypress_ps2_sendbyte(psmouse, cmd & 0xff); if (rc == CYTP_PS2_RETRY) { rc = cypress_ps2_sendbyte(psmouse, 0x00); if (rc == CYTP_PS2_RETRY) rc = cypress_ps2_sendbyte(psmouse, 0x0a); } if (rc == CYTP_PS2_ERROR) continue; rc = cypress_ps2_sendbyte(psmouse, data); if (rc == CYTP_PS2_RETRY) rc = cypress_ps2_sendbyte(psmouse, data); if (rc == CYTP_PS2_ERROR) continue; else break; } while (--tries > 0); ps2_end_command(ps2dev); return rc; } static int cypress_ps2_read_cmd_status(struct psmouse *psmouse, unsigned char cmd, unsigned char *param) { int rc; struct ps2dev *ps2dev = &psmouse->ps2dev; enum psmouse_state old_state; int pktsize; ps2_begin_command(ps2dev); old_state = psmouse->state; psmouse->state = PSMOUSE_CMD_MODE; psmouse->pktcnt = 0; pktsize = (cmd == CYTP_CMD_READ_TP_METRICS) ? 8 : 3; memset(param, 0, pktsize); rc = cypress_ps2_sendbyte(psmouse, 0xe9); if (rc < 0) goto out; wait_event_timeout(ps2dev->wait, (psmouse->pktcnt >= pktsize), msecs_to_jiffies(CYTP_CMD_TIMEOUT)); memcpy(param, psmouse->packet, pktsize); psmouse_dbg(psmouse, "Command 0x%02x response data (0x): %*ph\n", cmd, pktsize, param); out: psmouse->state = old_state; psmouse->pktcnt = 0; ps2_end_command(ps2dev); return rc; } static bool cypress_verify_cmd_state(struct psmouse *psmouse, unsigned char cmd, unsigned char *param) { bool rate_match = false; bool resolution_match = false; int i; /* callers will do further checking. */ if (cmd == CYTP_CMD_READ_CYPRESS_ID || cmd == CYTP_CMD_STANDARD_MODE || cmd == CYTP_CMD_READ_TP_METRICS) return true; if ((~param[0] & DFLT_RESP_BITS_VALID) == DFLT_RESP_BITS_VALID && (param[0] & DFLT_RESP_BIT_MODE) == DFLT_RESP_STREAM_MODE) { for (i = 0; i < sizeof(cytp_resolution); i++) if (cytp_resolution[i] == param[1]) resolution_match = true; for (i = 0; i < sizeof(cytp_rate); i++) if (cytp_rate[i] == param[2]) rate_match = true; if (resolution_match && rate_match) return true; } psmouse_dbg(psmouse, "verify cmd state failed.\n"); return false; } static int cypress_send_ext_cmd(struct psmouse *psmouse, unsigned char cmd, unsigned char *param) { int tries = CYTP_PS2_CMD_TRIES; int rc; psmouse_dbg(psmouse, "send extension cmd 0x%02x, [%d %d %d %d]\n", cmd, DECODE_CMD_AA(cmd), DECODE_CMD_BB(cmd), DECODE_CMD_CC(cmd), DECODE_CMD_DD(cmd)); do { cypress_ps2_ext_cmd(psmouse, PSMOUSE_CMD_SETRES, DECODE_CMD_DD(cmd)); cypress_ps2_ext_cmd(psmouse, PSMOUSE_CMD_SETRES, DECODE_CMD_CC(cmd)); cypress_ps2_ext_cmd(psmouse, PSMOUSE_CMD_SETRES, DECODE_CMD_BB(cmd)); cypress_ps2_ext_cmd(psmouse, PSMOUSE_CMD_SETRES, DECODE_CMD_AA(cmd)); rc = cypress_ps2_read_cmd_status(psmouse, cmd, param); if (rc) continue; if (cypress_verify_cmd_state(psmouse, cmd, param)) return 0; } while (--tries > 0); return -EIO; } int cypress_detect(struct psmouse *psmouse, bool set_properties) { unsigned char param[3]; if (cypress_send_ext_cmd(psmouse, CYTP_CMD_READ_CYPRESS_ID, param)) return -ENODEV; /* Check for Cypress Trackpad signature bytes: 0x33 0xCC */ if (param[0] != 0x33 || param[1] != 0xCC) return -ENODEV; if (set_properties) { psmouse->vendor = "Cypress"; psmouse->name = "Trackpad"; } return 0; } static int cypress_read_fw_version(struct psmouse *psmouse) { struct cytp_data *cytp = psmouse->private; unsigned char param[3]; if (cypress_send_ext_cmd(psmouse, CYTP_CMD_READ_CYPRESS_ID, param)) return -ENODEV; /* Check for Cypress Trackpad signature bytes: 0x33 0xCC */ if (param[0] != 0x33 || param[1] != 0xCC) return -ENODEV; cytp->fw_version = param[2] & FW_VERSION_MASX; cytp->tp_metrics_supported = (param[2] & TP_METRICS_MASK) ? 1 : 0; /* * Trackpad fw_version 11 (in Dell XPS12) yields a bogus response to * CYTP_CMD_READ_TP_METRICS so do not try to use it. LP: #1103594. */ if (cytp->fw_version >= 11) cytp->tp_metrics_supported = 0; psmouse_dbg(psmouse, "cytp->fw_version = %d\n", cytp->fw_version); psmouse_dbg(psmouse, "cytp->tp_metrics_supported = %d\n", cytp->tp_metrics_supported); return 0; } static int cypress_read_tp_metrics(struct psmouse *psmouse) { struct cytp_data *cytp = psmouse->private; unsigned char param[8]; /* set default values for tp metrics. */ cytp->tp_width = CYTP_DEFAULT_WIDTH; cytp->tp_high = CYTP_DEFAULT_HIGH; cytp->tp_max_abs_x = CYTP_ABS_MAX_X; cytp->tp_max_abs_y = CYTP_ABS_MAX_Y; cytp->tp_min_pressure = CYTP_MIN_PRESSURE; cytp->tp_max_pressure = CYTP_MAX_PRESSURE; cytp->tp_res_x = cytp->tp_max_abs_x / cytp->tp_width; cytp->tp_res_y = cytp->tp_max_abs_y / cytp->tp_high; if (!cytp->tp_metrics_supported) return 0; memset(param, 0, sizeof(param)); if (cypress_send_ext_cmd(psmouse, CYTP_CMD_READ_TP_METRICS, param) == 0) { /* Update trackpad parameters. */ cytp->tp_max_abs_x = (param[1] << 8) | param[0]; cytp->tp_max_abs_y = (param[3] << 8) | param[2]; cytp->tp_min_pressure = param[4]; cytp->tp_max_pressure = param[5]; } if (!cytp->tp_max_pressure || cytp->tp_max_pressure < cytp->tp_min_pressure || !cytp->tp_width || !cytp->tp_high || !cytp->tp_max_abs_x || cytp->tp_max_abs_x < cytp->tp_width || !cytp->tp_max_abs_y || cytp->tp_max_abs_y < cytp->tp_high) return -EINVAL; cytp->tp_res_x = cytp->tp_max_abs_x / cytp->tp_width; cytp->tp_res_y = cytp->tp_max_abs_y / cytp->tp_high; #ifdef CYTP_DEBUG_VERBOSE psmouse_dbg(psmouse, "Dump trackpad hardware configuration as below:\n"); psmouse_dbg(psmouse, "cytp->tp_width = %d\n", cytp->tp_width); psmouse_dbg(psmouse, "cytp->tp_high = %d\n", cytp->tp_high); psmouse_dbg(psmouse, "cytp->tp_max_abs_x = %d\n", cytp->tp_max_abs_x); psmouse_dbg(psmouse, "cytp->tp_max_abs_y = %d\n", cytp->tp_max_abs_y); psmouse_dbg(psmouse, "cytp->tp_min_pressure = %d\n", cytp->tp_min_pressure); psmouse_dbg(psmouse, "cytp->tp_max_pressure = %d\n", cytp->tp_max_pressure); psmouse_dbg(psmouse, "cytp->tp_res_x = %d\n", cytp->tp_res_x); psmouse_dbg(psmouse, "cytp->tp_res_y = %d\n", cytp->tp_res_y); psmouse_dbg(psmouse, "tp_type_APA = %d\n", (param[6] & TP_METRICS_BIT_APA) ? 1 : 0); psmouse_dbg(psmouse, "tp_type_MTG = %d\n", (param[6] & TP_METRICS_BIT_MTG) ? 1 : 0); psmouse_dbg(psmouse, "tp_palm = %d\n", (param[6] & TP_METRICS_BIT_PALM) ? 1 : 0); psmouse_dbg(psmouse, "tp_stubborn = %d\n", (param[6] & TP_METRICS_BIT_STUBBORN) ? 1 : 0); psmouse_dbg(psmouse, "tp_1f_jitter = %d\n", (param[6] & TP_METRICS_BIT_1F_JITTER) >> 2); psmouse_dbg(psmouse, "tp_2f_jitter = %d\n", (param[6] & TP_METRICS_BIT_2F_JITTER) >> 4); psmouse_dbg(psmouse, "tp_1f_spike = %d\n", param[7] & TP_METRICS_BIT_1F_SPIKE); psmouse_dbg(psmouse, "tp_2f_spike = %d\n", (param[7] & TP_METRICS_BIT_2F_SPIKE) >> 2); psmouse_dbg(psmouse, "tp_abs_packet_format_set = %d\n", (param[7] & TP_METRICS_BIT_ABS_PKT_FORMAT_SET) >> 4); #endif return 0; } static int cypress_query_hardware(struct psmouse *psmouse) { int ret; ret = cypress_read_fw_version(psmouse); if (ret) return ret; ret = cypress_read_tp_metrics(psmouse); if (ret) return ret; return 0; } static int cypress_set_absolute_mode(struct psmouse *psmouse) { struct cytp_data *cytp = psmouse->private; unsigned char param[3]; if (cypress_send_ext_cmd(psmouse, CYTP_CMD_ABS_WITH_PRESSURE_MODE, param) < 0) return -1; cytp->mode = (cytp->mode & ~CYTP_BIT_ABS_REL_MASK) | CYTP_BIT_ABS_PRESSURE; cypress_set_packet_size(psmouse, 5); return 0; } /* * Reset trackpad device. * This is also the default mode when trackpad powered on. */ static void cypress_reset(struct psmouse *psmouse) { struct cytp_data *cytp = psmouse->private; cytp->mode = 0; psmouse_reset(psmouse); } static int cypress_set_input_params(struct input_dev *input, struct cytp_data *cytp) { int ret; if (!cytp->tp_res_x || !cytp->tp_res_y) return -EINVAL; __set_bit(EV_ABS, input->evbit); input_set_abs_params(input, ABS_X, 0, cytp->tp_max_abs_x, 0, 0); input_set_abs_params(input, ABS_Y, 0, cytp->tp_max_abs_y, 0, 0); input_set_abs_params(input, ABS_PRESSURE, cytp->tp_min_pressure, cytp->tp_max_pressure, 0, 0); input_set_abs_params(input, ABS_TOOL_WIDTH, 0, 255, 0, 0); /* finger position */ input_set_abs_params(input, ABS_MT_POSITION_X, 0, cytp->tp_max_abs_x, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, cytp->tp_max_abs_y, 0, 0); input_set_abs_params(input, ABS_MT_PRESSURE, 0, 255, 0, 0); ret = input_mt_init_slots(input, CYTP_MAX_MT_SLOTS, INPUT_MT_DROP_UNUSED|INPUT_MT_TRACK); if (ret < 0) return ret; __set_bit(INPUT_PROP_SEMI_MT, input->propbit); input_abs_set_res(input, ABS_X, cytp->tp_res_x); input_abs_set_res(input, ABS_Y, cytp->tp_res_y); input_abs_set_res(input, ABS_MT_POSITION_X, cytp->tp_res_x); input_abs_set_res(input, ABS_MT_POSITION_Y, cytp->tp_res_y); __set_bit(BTN_TOUCH, input->keybit); __set_bit(BTN_TOOL_FINGER, input->keybit); __set_bit(BTN_TOOL_DOUBLETAP, input->keybit); __set_bit(BTN_TOOL_TRIPLETAP, input->keybit); __set_bit(BTN_TOOL_QUADTAP, input->keybit); __set_bit(BTN_TOOL_QUINTTAP, input->keybit); __clear_bit(EV_REL, input->evbit); __clear_bit(REL_X, input->relbit); __clear_bit(REL_Y, input->relbit); __set_bit(EV_KEY, input->evbit); __set_bit(BTN_LEFT, input->keybit); __set_bit(BTN_RIGHT, input->keybit); __set_bit(BTN_MIDDLE, input->keybit); return 0; } static int cypress_get_finger_count(unsigned char header_byte) { unsigned char bits6_7; int finger_count; bits6_7 = header_byte >> 6; finger_count = bits6_7 & 0x03; if (finger_count == 1) return 1; if (header_byte & ABS_HSCROLL_BIT) { /* HSCROLL gets added on to 0 finger count. */ switch (finger_count) { case 0: return 4; case 2: return 5; default: /* Invalid contact (e.g. palm). Ignore it. */ return 0; } } return finger_count; } static int cypress_parse_packet(struct psmouse *psmouse, struct cytp_data *cytp, struct cytp_report_data *report_data) { unsigned char *packet = psmouse->packet; unsigned char header_byte = packet[0]; memset(report_data, 0, sizeof(struct cytp_report_data)); report_data->contact_cnt = cypress_get_finger_count(header_byte); report_data->tap = (header_byte & ABS_MULTIFINGER_TAP) ? 1 : 0; if (report_data->contact_cnt == 1) { report_data->contacts[0].x = ((packet[1] & 0x70) << 4) | packet[2]; report_data->contacts[0].y = ((packet[1] & 0x07) << 8) | packet[3]; if (cytp->mode & CYTP_BIT_ABS_PRESSURE) report_data->contacts[0].z = packet[4]; } else if (report_data->contact_cnt >= 2) { report_data->contacts[0].x = ((packet[1] & 0x70) << 4) | packet[2]; report_data->contacts[0].y = ((packet[1] & 0x07) << 8) | packet[3]; if (cytp->mode & CYTP_BIT_ABS_PRESSURE) report_data->contacts[0].z = packet[4]; report_data->contacts[1].x = ((packet[5] & 0xf0) << 4) | packet[6]; report_data->contacts[1].y = ((packet[5] & 0x0f) << 8) | packet[7]; if (cytp->mode & CYTP_BIT_ABS_PRESSURE) report_data->contacts[1].z = report_data->contacts[0].z; } report_data->left = (header_byte & BTN_LEFT_BIT) ? 1 : 0; report_data->right = (header_byte & BTN_RIGHT_BIT) ? 1 : 0; /* * This is only true if one of the mouse buttons were tapped. Make * sure it doesn't turn into a click. The regular tap-to-click * functionality will handle that on its own. If we don't do this, * disabling tap-to-click won't affect the mouse button zones. */ if (report_data->tap) report_data->left = 0; #ifdef CYTP_DEBUG_VERBOSE { int i; int n = report_data->contact_cnt; psmouse_dbg(psmouse, "Dump parsed report data as below:\n"); psmouse_dbg(psmouse, "contact_cnt = %d\n", report_data->contact_cnt); if (n > CYTP_MAX_MT_SLOTS) n = CYTP_MAX_MT_SLOTS; for (i = 0; i < n; i++) psmouse_dbg(psmouse, "contacts[%d] = {%d, %d, %d}\n", i, report_data->contacts[i].x, report_data->contacts[i].y, report_data->contacts[i].z); psmouse_dbg(psmouse, "left = %d\n", report_data->left); psmouse_dbg(psmouse, "right = %d\n", report_data->right); psmouse_dbg(psmouse, "middle = %d\n", report_data->middle); } #endif return 0; } static void cypress_process_packet(struct psmouse *psmouse, bool zero_pkt) { int i; struct input_dev *input = psmouse->dev; struct cytp_data *cytp = psmouse->private; struct cytp_report_data report_data; struct cytp_contact *contact; struct input_mt_pos pos[CYTP_MAX_MT_SLOTS]; int slots[CYTP_MAX_MT_SLOTS]; int n; cypress_parse_packet(psmouse, cytp, &report_data); n = report_data.contact_cnt; if (n > CYTP_MAX_MT_SLOTS) n = CYTP_MAX_MT_SLOTS; for (i = 0; i < n; i++) { contact = &report_data.contacts[i]; pos[i].x = contact->x; pos[i].y = contact->y; } input_mt_assign_slots(input, slots, pos, n, 0); for (i = 0; i < n; i++) { contact = &report_data.contacts[i]; input_mt_slot(input, slots[i]); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); input_report_abs(input, ABS_MT_POSITION_X, contact->x); input_report_abs(input, ABS_MT_POSITION_Y, contact->y); input_report_abs(input, ABS_MT_PRESSURE, contact->z); } input_mt_sync_frame(input); input_mt_report_finger_count(input, report_data.contact_cnt); input_report_key(input, BTN_LEFT, report_data.left); input_report_key(input, BTN_RIGHT, report_data.right); input_report_key(input, BTN_MIDDLE, report_data.middle); input_sync(input); } static psmouse_ret_t cypress_validate_byte(struct psmouse *psmouse) { int contact_cnt; int index = psmouse->pktcnt - 1; unsigned char *packet = psmouse->packet; struct cytp_data *cytp = psmouse->private; if (index < 0 || index > cytp->pkt_size) return PSMOUSE_BAD_DATA; if (index == 0 && (packet[0] & 0xfc) == 0) { /* call packet process for reporting finger leave. */ cypress_process_packet(psmouse, 1); return PSMOUSE_FULL_PACKET; } /* * Perform validation (and adjust packet size) based only on the * first byte; allow all further bytes through. */ if (index != 0) return PSMOUSE_GOOD_DATA; /* * If absolute/relative mode bit has not been set yet, just pass * the byte through. */ if ((cytp->mode & CYTP_BIT_ABS_REL_MASK) == 0) return PSMOUSE_GOOD_DATA; if ((packet[0] & 0x08) == 0x08) return PSMOUSE_BAD_DATA; contact_cnt = cypress_get_finger_count(packet[0]); if (cytp->mode & CYTP_BIT_ABS_NO_PRESSURE) cypress_set_packet_size(psmouse, contact_cnt == 2 ? 7 : 4); else cypress_set_packet_size(psmouse, contact_cnt == 2 ? 8 : 5); return PSMOUSE_GOOD_DATA; } static psmouse_ret_t cypress_protocol_handler(struct psmouse *psmouse) { struct cytp_data *cytp = psmouse->private; if (psmouse->pktcnt >= cytp->pkt_size) { cypress_process_packet(psmouse, 0); return PSMOUSE_FULL_PACKET; } return cypress_validate_byte(psmouse); } static void cypress_set_rate(struct psmouse *psmouse, unsigned int rate) { struct cytp_data *cytp = psmouse->private; if (rate >= 80) { psmouse->rate = 80; cytp->mode |= CYTP_BIT_HIGH_RATE; } else { psmouse->rate = 40; cytp->mode &= ~CYTP_BIT_HIGH_RATE; } ps2_command(&psmouse->ps2dev, (unsigned char *)&psmouse->rate, PSMOUSE_CMD_SETRATE); } static void cypress_disconnect(struct psmouse *psmouse) { cypress_reset(psmouse); kfree(psmouse->private); psmouse->private = NULL; } static int cypress_reconnect(struct psmouse *psmouse) { int tries = CYTP_PS2_CMD_TRIES; int rc; do { cypress_reset(psmouse); rc = cypress_detect(psmouse, false); } while (rc && (--tries > 0)); if (rc) { psmouse_err(psmouse, "Reconnect: unable to detect trackpad.\n"); return -1; } if (cypress_set_absolute_mode(psmouse)) { psmouse_err(psmouse, "Reconnect: Unable to initialize Cypress absolute mode.\n"); return -1; } return 0; } int cypress_init(struct psmouse *psmouse) { struct cytp_data *cytp; cytp = kzalloc(sizeof(struct cytp_data), GFP_KERNEL); if (!cytp) return -ENOMEM; psmouse->private = cytp; psmouse->pktsize = 8; cypress_reset(psmouse); if (cypress_query_hardware(psmouse)) { psmouse_err(psmouse, "Unable to query Trackpad hardware.\n"); goto err_exit; } if (cypress_set_absolute_mode(psmouse)) { psmouse_err(psmouse, "init: Unable to initialize Cypress absolute mode.\n"); goto err_exit; } if (cypress_set_input_params(psmouse->dev, cytp) < 0) { psmouse_err(psmouse, "init: Unable to set input params.\n"); goto err_exit; } psmouse->model = 1; psmouse->protocol_handler = cypress_protocol_handler; psmouse->set_rate = cypress_set_rate; psmouse->disconnect = cypress_disconnect; psmouse->reconnect = cypress_reconnect; psmouse->cleanup = cypress_reset; psmouse->resync_time = 0; return 0; err_exit: /* * Reset Cypress Trackpad as a standard mouse. Then * let psmouse driver communicating with it as default PS2 mouse. */ cypress_reset(psmouse); psmouse->private = NULL; kfree(cytp); return -1; }
linux-master
drivers/input/mouse/cypress_ps2.c