python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0-only /* * ati_remote2 - ATI/Philips USB RF remote driver * * Copyright (C) 2005-2008 Ville Syrjala <[email protected]> * Copyright (C) 2007-2008 Peter Stokes <[email protected]> */ #include <linux/usb/input.h> #include <linux/slab.h> #include <linux/module.h> #define DRIVER_DESC "ATI/Philips USB RF remote driver" MODULE_DESCRIPTION(DRIVER_DESC); MODULE_AUTHOR("Ville Syrjala <[email protected]>"); MODULE_LICENSE("GPL"); /* * ATI Remote Wonder II Channel Configuration * * The remote control can be assigned one of sixteen "channels" in order to facilitate * the use of multiple remote controls within range of each other. * A remote's "channel" may be altered by pressing and holding the "PC" button for * approximately 3 seconds, after which the button will slowly flash the count of the * currently configured "channel", using the numeric keypad enter a number between 1 and * 16 and then press the "PC" button again, the button will slowly flash the count of the * newly configured "channel". */ enum { ATI_REMOTE2_MAX_CHANNEL_MASK = 0xFFFF, ATI_REMOTE2_MAX_MODE_MASK = 0x1F, }; static int ati_remote2_set_mask(const char *val, const struct kernel_param *kp, unsigned int max) { unsigned int mask; int ret; if (!val) return -EINVAL; ret = kstrtouint(val, 0, &mask); if (ret) return ret; if (mask & ~max) return -EINVAL; *(unsigned int *)kp->arg = mask; return 0; } static int ati_remote2_set_channel_mask(const char *val, const struct kernel_param *kp) { pr_debug("%s()\n", __func__); return ati_remote2_set_mask(val, kp, ATI_REMOTE2_MAX_CHANNEL_MASK); } static int ati_remote2_get_channel_mask(char *buffer, const struct kernel_param *kp) { pr_debug("%s()\n", __func__); return sprintf(buffer, "0x%04x\n", *(unsigned int *)kp->arg); } static int ati_remote2_set_mode_mask(const char *val, const struct kernel_param *kp) { pr_debug("%s()\n", __func__); return ati_remote2_set_mask(val, kp, ATI_REMOTE2_MAX_MODE_MASK); } static int ati_remote2_get_mode_mask(char *buffer, const struct kernel_param *kp) { pr_debug("%s()\n", __func__); return sprintf(buffer, "0x%02x\n", *(unsigned int *)kp->arg); } static unsigned int channel_mask = ATI_REMOTE2_MAX_CHANNEL_MASK; #define param_check_channel_mask(name, p) __param_check(name, p, unsigned int) static const struct kernel_param_ops param_ops_channel_mask = { .set = ati_remote2_set_channel_mask, .get = ati_remote2_get_channel_mask, }; module_param(channel_mask, channel_mask, 0644); MODULE_PARM_DESC(channel_mask, "Bitmask of channels to accept <15:Channel16>...<1:Channel2><0:Channel1>"); static unsigned int mode_mask = ATI_REMOTE2_MAX_MODE_MASK; #define param_check_mode_mask(name, p) __param_check(name, p, unsigned int) static const struct kernel_param_ops param_ops_mode_mask = { .set = ati_remote2_set_mode_mask, .get = ati_remote2_get_mode_mask, }; module_param(mode_mask, mode_mask, 0644); MODULE_PARM_DESC(mode_mask, "Bitmask of modes to accept <4:PC><3:AUX4><2:AUX3><1:AUX2><0:AUX1>"); static const struct usb_device_id ati_remote2_id_table[] = { { USB_DEVICE(0x0471, 0x0602) }, /* ATI Remote Wonder II */ { } }; MODULE_DEVICE_TABLE(usb, ati_remote2_id_table); static DEFINE_MUTEX(ati_remote2_mutex); enum { ATI_REMOTE2_OPENED = 0x1, ATI_REMOTE2_SUSPENDED = 0x2, }; enum { ATI_REMOTE2_AUX1, ATI_REMOTE2_AUX2, ATI_REMOTE2_AUX3, ATI_REMOTE2_AUX4, ATI_REMOTE2_PC, ATI_REMOTE2_MODES, }; static const struct { u8 hw_code; u16 keycode; } ati_remote2_key_table[] = { { 0x00, KEY_0 }, { 0x01, KEY_1 }, { 0x02, KEY_2 }, { 0x03, KEY_3 }, { 0x04, KEY_4 }, { 0x05, KEY_5 }, { 0x06, KEY_6 }, { 0x07, KEY_7 }, { 0x08, KEY_8 }, { 0x09, KEY_9 }, { 0x0c, KEY_POWER }, { 0x0d, KEY_MUTE }, { 0x10, KEY_VOLUMEUP }, { 0x11, KEY_VOLUMEDOWN }, { 0x20, KEY_CHANNELUP }, { 0x21, KEY_CHANNELDOWN }, { 0x28, KEY_FORWARD }, { 0x29, KEY_REWIND }, { 0x2c, KEY_PLAY }, { 0x30, KEY_PAUSE }, { 0x31, KEY_STOP }, { 0x37, KEY_RECORD }, { 0x38, KEY_DVD }, { 0x39, KEY_TV }, { 0x3f, KEY_PROG1 }, /* AUX1-AUX4 and PC */ { 0x54, KEY_MENU }, { 0x58, KEY_UP }, { 0x59, KEY_DOWN }, { 0x5a, KEY_LEFT }, { 0x5b, KEY_RIGHT }, { 0x5c, KEY_OK }, { 0x78, KEY_A }, { 0x79, KEY_B }, { 0x7a, KEY_C }, { 0x7b, KEY_D }, { 0x7c, KEY_E }, { 0x7d, KEY_F }, { 0x82, KEY_ENTER }, { 0x8e, KEY_VENDOR }, { 0x96, KEY_COFFEE }, { 0xa9, BTN_LEFT }, { 0xaa, BTN_RIGHT }, { 0xbe, KEY_QUESTION }, { 0xd0, KEY_EDIT }, { 0xd5, KEY_FRONT }, { 0xf9, KEY_INFO }, }; struct ati_remote2 { struct input_dev *idev; struct usb_device *udev; struct usb_interface *intf[2]; struct usb_endpoint_descriptor *ep[2]; struct urb *urb[2]; void *buf[2]; dma_addr_t buf_dma[2]; unsigned long jiffies; int mode; char name[64]; char phys[64]; /* Each mode (AUX1-AUX4 and PC) can have an independent keymap. */ u16 keycode[ATI_REMOTE2_MODES][ARRAY_SIZE(ati_remote2_key_table)]; unsigned int flags; unsigned int channel_mask; unsigned int mode_mask; }; static int ati_remote2_probe(struct usb_interface *interface, const struct usb_device_id *id); static void ati_remote2_disconnect(struct usb_interface *interface); static int ati_remote2_suspend(struct usb_interface *interface, pm_message_t message); static int ati_remote2_resume(struct usb_interface *interface); static int ati_remote2_reset_resume(struct usb_interface *interface); static int ati_remote2_pre_reset(struct usb_interface *interface); static int ati_remote2_post_reset(struct usb_interface *interface); static struct usb_driver ati_remote2_driver = { .name = "ati_remote2", .probe = ati_remote2_probe, .disconnect = ati_remote2_disconnect, .id_table = ati_remote2_id_table, .suspend = ati_remote2_suspend, .resume = ati_remote2_resume, .reset_resume = ati_remote2_reset_resume, .pre_reset = ati_remote2_pre_reset, .post_reset = ati_remote2_post_reset, .supports_autosuspend = 1, }; static int ati_remote2_submit_urbs(struct ati_remote2 *ar2) { int r; r = usb_submit_urb(ar2->urb[0], GFP_KERNEL); if (r) { dev_err(&ar2->intf[0]->dev, "%s(): usb_submit_urb() = %d\n", __func__, r); return r; } r = usb_submit_urb(ar2->urb[1], GFP_KERNEL); if (r) { usb_kill_urb(ar2->urb[0]); dev_err(&ar2->intf[1]->dev, "%s(): usb_submit_urb() = %d\n", __func__, r); return r; } return 0; } static void ati_remote2_kill_urbs(struct ati_remote2 *ar2) { usb_kill_urb(ar2->urb[1]); usb_kill_urb(ar2->urb[0]); } static int ati_remote2_open(struct input_dev *idev) { struct ati_remote2 *ar2 = input_get_drvdata(idev); int r; dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); r = usb_autopm_get_interface(ar2->intf[0]); if (r) { dev_err(&ar2->intf[0]->dev, "%s(): usb_autopm_get_interface() = %d\n", __func__, r); goto fail1; } mutex_lock(&ati_remote2_mutex); if (!(ar2->flags & ATI_REMOTE2_SUSPENDED)) { r = ati_remote2_submit_urbs(ar2); if (r) goto fail2; } ar2->flags |= ATI_REMOTE2_OPENED; mutex_unlock(&ati_remote2_mutex); usb_autopm_put_interface(ar2->intf[0]); return 0; fail2: mutex_unlock(&ati_remote2_mutex); usb_autopm_put_interface(ar2->intf[0]); fail1: return r; } static void ati_remote2_close(struct input_dev *idev) { struct ati_remote2 *ar2 = input_get_drvdata(idev); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); if (!(ar2->flags & ATI_REMOTE2_SUSPENDED)) ati_remote2_kill_urbs(ar2); ar2->flags &= ~ATI_REMOTE2_OPENED; mutex_unlock(&ati_remote2_mutex); } static void ati_remote2_input_mouse(struct ati_remote2 *ar2) { struct input_dev *idev = ar2->idev; u8 *data = ar2->buf[0]; int channel, mode; channel = data[0] >> 4; if (!((1 << channel) & ar2->channel_mask)) return; mode = data[0] & 0x0F; if (mode > ATI_REMOTE2_PC) { dev_err(&ar2->intf[0]->dev, "Unknown mode byte (%02x %02x %02x %02x)\n", data[3], data[2], data[1], data[0]); return; } if (!((1 << mode) & ar2->mode_mask)) return; input_event(idev, EV_REL, REL_X, (s8) data[1]); input_event(idev, EV_REL, REL_Y, (s8) data[2]); input_sync(idev); } static int ati_remote2_lookup(unsigned int hw_code) { int i; for (i = 0; i < ARRAY_SIZE(ati_remote2_key_table); i++) if (ati_remote2_key_table[i].hw_code == hw_code) return i; return -1; } static void ati_remote2_input_key(struct ati_remote2 *ar2) { struct input_dev *idev = ar2->idev; u8 *data = ar2->buf[1]; int channel, mode, hw_code, index; channel = data[0] >> 4; if (!((1 << channel) & ar2->channel_mask)) return; mode = data[0] & 0x0F; if (mode > ATI_REMOTE2_PC) { dev_err(&ar2->intf[1]->dev, "Unknown mode byte (%02x %02x %02x %02x)\n", data[3], data[2], data[1], data[0]); return; } hw_code = data[2]; if (hw_code == 0x3f) { /* * For some incomprehensible reason the mouse pad generates * events which look identical to the events from the last * pressed mode key. Naturally we don't want to generate key * events for the mouse pad so we filter out any subsequent * events from the same mode key. */ if (ar2->mode == mode) return; if (data[1] == 0) ar2->mode = mode; } if (!((1 << mode) & ar2->mode_mask)) return; index = ati_remote2_lookup(hw_code); if (index < 0) { dev_err(&ar2->intf[1]->dev, "Unknown code byte (%02x %02x %02x %02x)\n", data[3], data[2], data[1], data[0]); return; } switch (data[1]) { case 0: /* release */ break; case 1: /* press */ ar2->jiffies = jiffies + msecs_to_jiffies(idev->rep[REP_DELAY]); break; case 2: /* repeat */ /* No repeat for mouse buttons. */ if (ar2->keycode[mode][index] == BTN_LEFT || ar2->keycode[mode][index] == BTN_RIGHT) return; if (!time_after_eq(jiffies, ar2->jiffies)) return; ar2->jiffies = jiffies + msecs_to_jiffies(idev->rep[REP_PERIOD]); break; default: dev_err(&ar2->intf[1]->dev, "Unknown state byte (%02x %02x %02x %02x)\n", data[3], data[2], data[1], data[0]); return; } input_event(idev, EV_KEY, ar2->keycode[mode][index], data[1]); input_sync(idev); } static void ati_remote2_complete_mouse(struct urb *urb) { struct ati_remote2 *ar2 = urb->context; int r; switch (urb->status) { case 0: usb_mark_last_busy(ar2->udev); ati_remote2_input_mouse(ar2); break; case -ENOENT: case -EILSEQ: case -ECONNRESET: case -ESHUTDOWN: dev_dbg(&ar2->intf[0]->dev, "%s(): urb status = %d\n", __func__, urb->status); return; default: usb_mark_last_busy(ar2->udev); dev_err(&ar2->intf[0]->dev, "%s(): urb status = %d\n", __func__, urb->status); } r = usb_submit_urb(urb, GFP_ATOMIC); if (r) dev_err(&ar2->intf[0]->dev, "%s(): usb_submit_urb() = %d\n", __func__, r); } static void ati_remote2_complete_key(struct urb *urb) { struct ati_remote2 *ar2 = urb->context; int r; switch (urb->status) { case 0: usb_mark_last_busy(ar2->udev); ati_remote2_input_key(ar2); break; case -ENOENT: case -EILSEQ: case -ECONNRESET: case -ESHUTDOWN: dev_dbg(&ar2->intf[1]->dev, "%s(): urb status = %d\n", __func__, urb->status); return; default: usb_mark_last_busy(ar2->udev); dev_err(&ar2->intf[1]->dev, "%s(): urb status = %d\n", __func__, urb->status); } r = usb_submit_urb(urb, GFP_ATOMIC); if (r) dev_err(&ar2->intf[1]->dev, "%s(): usb_submit_urb() = %d\n", __func__, r); } static int ati_remote2_getkeycode(struct input_dev *idev, struct input_keymap_entry *ke) { struct ati_remote2 *ar2 = input_get_drvdata(idev); unsigned int mode; int offset; unsigned int index; unsigned int scancode; if (ke->flags & INPUT_KEYMAP_BY_INDEX) { index = ke->index; if (index >= ATI_REMOTE2_MODES * ARRAY_SIZE(ati_remote2_key_table)) return -EINVAL; mode = ke->index / ARRAY_SIZE(ati_remote2_key_table); offset = ke->index % ARRAY_SIZE(ati_remote2_key_table); scancode = (mode << 8) + ati_remote2_key_table[offset].hw_code; } else { if (input_scancode_to_scalar(ke, &scancode)) return -EINVAL; mode = scancode >> 8; if (mode > ATI_REMOTE2_PC) return -EINVAL; offset = ati_remote2_lookup(scancode & 0xff); if (offset < 0) return -EINVAL; index = mode * ARRAY_SIZE(ati_remote2_key_table) + offset; } ke->keycode = ar2->keycode[mode][offset]; ke->len = sizeof(scancode); memcpy(&ke->scancode, &scancode, sizeof(scancode)); ke->index = index; return 0; } static int ati_remote2_setkeycode(struct input_dev *idev, const struct input_keymap_entry *ke, unsigned int *old_keycode) { struct ati_remote2 *ar2 = input_get_drvdata(idev); unsigned int mode; int offset; unsigned int index; unsigned int scancode; if (ke->flags & INPUT_KEYMAP_BY_INDEX) { if (ke->index >= ATI_REMOTE2_MODES * ARRAY_SIZE(ati_remote2_key_table)) return -EINVAL; mode = ke->index / ARRAY_SIZE(ati_remote2_key_table); offset = ke->index % ARRAY_SIZE(ati_remote2_key_table); } else { if (input_scancode_to_scalar(ke, &scancode)) return -EINVAL; mode = scancode >> 8; if (mode > ATI_REMOTE2_PC) return -EINVAL; offset = ati_remote2_lookup(scancode & 0xff); if (offset < 0) return -EINVAL; } *old_keycode = ar2->keycode[mode][offset]; ar2->keycode[mode][offset] = ke->keycode; __set_bit(ke->keycode, idev->keybit); for (mode = 0; mode < ATI_REMOTE2_MODES; mode++) { for (index = 0; index < ARRAY_SIZE(ati_remote2_key_table); index++) { if (ar2->keycode[mode][index] == *old_keycode) return 0; } } __clear_bit(*old_keycode, idev->keybit); return 0; } static int ati_remote2_input_init(struct ati_remote2 *ar2) { struct input_dev *idev; int index, mode, retval; idev = input_allocate_device(); if (!idev) return -ENOMEM; ar2->idev = idev; input_set_drvdata(idev, ar2); idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) | BIT_MASK(EV_REL); idev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT); idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); for (mode = 0; mode < ATI_REMOTE2_MODES; mode++) { for (index = 0; index < ARRAY_SIZE(ati_remote2_key_table); index++) { ar2->keycode[mode][index] = ati_remote2_key_table[index].keycode; __set_bit(ar2->keycode[mode][index], idev->keybit); } } /* AUX1-AUX4 and PC generate the same scancode. */ index = ati_remote2_lookup(0x3f); ar2->keycode[ATI_REMOTE2_AUX1][index] = KEY_PROG1; ar2->keycode[ATI_REMOTE2_AUX2][index] = KEY_PROG2; ar2->keycode[ATI_REMOTE2_AUX3][index] = KEY_PROG3; ar2->keycode[ATI_REMOTE2_AUX4][index] = KEY_PROG4; ar2->keycode[ATI_REMOTE2_PC][index] = KEY_PC; __set_bit(KEY_PROG1, idev->keybit); __set_bit(KEY_PROG2, idev->keybit); __set_bit(KEY_PROG3, idev->keybit); __set_bit(KEY_PROG4, idev->keybit); __set_bit(KEY_PC, idev->keybit); idev->rep[REP_DELAY] = 250; idev->rep[REP_PERIOD] = 33; idev->open = ati_remote2_open; idev->close = ati_remote2_close; idev->getkeycode = ati_remote2_getkeycode; idev->setkeycode = ati_remote2_setkeycode; idev->name = ar2->name; idev->phys = ar2->phys; usb_to_input_id(ar2->udev, &idev->id); idev->dev.parent = &ar2->udev->dev; retval = input_register_device(idev); if (retval) input_free_device(idev); return retval; } static int ati_remote2_urb_init(struct ati_remote2 *ar2) { struct usb_device *udev = ar2->udev; int i, pipe, maxp; for (i = 0; i < 2; i++) { ar2->buf[i] = usb_alloc_coherent(udev, 4, GFP_KERNEL, &ar2->buf_dma[i]); if (!ar2->buf[i]) return -ENOMEM; ar2->urb[i] = usb_alloc_urb(0, GFP_KERNEL); if (!ar2->urb[i]) return -ENOMEM; pipe = usb_rcvintpipe(udev, ar2->ep[i]->bEndpointAddress); maxp = usb_maxpacket(udev, pipe); maxp = maxp > 4 ? 4 : maxp; usb_fill_int_urb(ar2->urb[i], udev, pipe, ar2->buf[i], maxp, i ? ati_remote2_complete_key : ati_remote2_complete_mouse, ar2, ar2->ep[i]->bInterval); ar2->urb[i]->transfer_dma = ar2->buf_dma[i]; ar2->urb[i]->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; } return 0; } static void ati_remote2_urb_cleanup(struct ati_remote2 *ar2) { int i; for (i = 0; i < 2; i++) { usb_free_urb(ar2->urb[i]); usb_free_coherent(ar2->udev, 4, ar2->buf[i], ar2->buf_dma[i]); } } static int ati_remote2_setup(struct ati_remote2 *ar2, unsigned int ch_mask) { int r, i, channel; /* * Configure receiver to only accept input from remote "channel" * channel == 0 -> Accept input from any remote channel * channel == 1 -> Only accept input from remote channel 1 * channel == 2 -> Only accept input from remote channel 2 * ... * channel == 16 -> Only accept input from remote channel 16 */ channel = 0; for (i = 0; i < 16; i++) { if ((1 << i) & ch_mask) { if (!(~(1 << i) & ch_mask)) channel = i + 1; break; } } r = usb_control_msg(ar2->udev, usb_sndctrlpipe(ar2->udev, 0), 0x20, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, channel, 0x0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (r) { dev_err(&ar2->udev->dev, "%s - failed to set channel due to error: %d\n", __func__, r); return r; } return 0; } static ssize_t ati_remote2_show_channel_mask(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_device *udev = to_usb_device(dev); struct usb_interface *intf = usb_ifnum_to_if(udev, 0); struct ati_remote2 *ar2 = usb_get_intfdata(intf); return sprintf(buf, "0x%04x\n", ar2->channel_mask); } static ssize_t ati_remote2_store_channel_mask(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct usb_device *udev = to_usb_device(dev); struct usb_interface *intf = usb_ifnum_to_if(udev, 0); struct ati_remote2 *ar2 = usb_get_intfdata(intf); unsigned int mask; int r; r = kstrtouint(buf, 0, &mask); if (r) return r; if (mask & ~ATI_REMOTE2_MAX_CHANNEL_MASK) return -EINVAL; r = usb_autopm_get_interface(ar2->intf[0]); if (r) { dev_err(&ar2->intf[0]->dev, "%s(): usb_autopm_get_interface() = %d\n", __func__, r); return r; } mutex_lock(&ati_remote2_mutex); if (mask != ar2->channel_mask) { r = ati_remote2_setup(ar2, mask); if (!r) ar2->channel_mask = mask; } mutex_unlock(&ati_remote2_mutex); usb_autopm_put_interface(ar2->intf[0]); return r ? r : count; } static ssize_t ati_remote2_show_mode_mask(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_device *udev = to_usb_device(dev); struct usb_interface *intf = usb_ifnum_to_if(udev, 0); struct ati_remote2 *ar2 = usb_get_intfdata(intf); return sprintf(buf, "0x%02x\n", ar2->mode_mask); } static ssize_t ati_remote2_store_mode_mask(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct usb_device *udev = to_usb_device(dev); struct usb_interface *intf = usb_ifnum_to_if(udev, 0); struct ati_remote2 *ar2 = usb_get_intfdata(intf); unsigned int mask; int err; err = kstrtouint(buf, 0, &mask); if (err) return err; if (mask & ~ATI_REMOTE2_MAX_MODE_MASK) return -EINVAL; ar2->mode_mask = mask; return count; } static DEVICE_ATTR(channel_mask, 0644, ati_remote2_show_channel_mask, ati_remote2_store_channel_mask); static DEVICE_ATTR(mode_mask, 0644, ati_remote2_show_mode_mask, ati_remote2_store_mode_mask); static struct attribute *ati_remote2_attrs[] = { &dev_attr_channel_mask.attr, &dev_attr_mode_mask.attr, NULL, }; static struct attribute_group ati_remote2_attr_group = { .attrs = ati_remote2_attrs, }; static int ati_remote2_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct usb_host_interface *alt = interface->cur_altsetting; struct ati_remote2 *ar2; int r; if (alt->desc.bInterfaceNumber) return -ENODEV; ar2 = kzalloc(sizeof (struct ati_remote2), GFP_KERNEL); if (!ar2) return -ENOMEM; ar2->udev = udev; /* Sanity check, first interface must have an endpoint */ if (alt->desc.bNumEndpoints < 1 || !alt->endpoint) { dev_err(&interface->dev, "%s(): interface 0 must have an endpoint\n", __func__); r = -ENODEV; goto fail1; } ar2->intf[0] = interface; ar2->ep[0] = &alt->endpoint[0].desc; /* Sanity check, the device must have two interfaces */ ar2->intf[1] = usb_ifnum_to_if(udev, 1); if ((udev->actconfig->desc.bNumInterfaces < 2) || !ar2->intf[1]) { dev_err(&interface->dev, "%s(): need 2 interfaces, found %d\n", __func__, udev->actconfig->desc.bNumInterfaces); r = -ENODEV; goto fail1; } r = usb_driver_claim_interface(&ati_remote2_driver, ar2->intf[1], ar2); if (r) goto fail1; /* Sanity check, second interface must have an endpoint */ alt = ar2->intf[1]->cur_altsetting; if (alt->desc.bNumEndpoints < 1 || !alt->endpoint) { dev_err(&interface->dev, "%s(): interface 1 must have an endpoint\n", __func__); r = -ENODEV; goto fail2; } ar2->ep[1] = &alt->endpoint[0].desc; r = ati_remote2_urb_init(ar2); if (r) goto fail3; ar2->channel_mask = channel_mask; ar2->mode_mask = mode_mask; r = ati_remote2_setup(ar2, ar2->channel_mask); if (r) goto fail3; usb_make_path(udev, ar2->phys, sizeof(ar2->phys)); strlcat(ar2->phys, "/input0", sizeof(ar2->phys)); strlcat(ar2->name, "ATI Remote Wonder II", sizeof(ar2->name)); r = sysfs_create_group(&udev->dev.kobj, &ati_remote2_attr_group); if (r) goto fail3; r = ati_remote2_input_init(ar2); if (r) goto fail4; usb_set_intfdata(interface, ar2); interface->needs_remote_wakeup = 1; return 0; fail4: sysfs_remove_group(&udev->dev.kobj, &ati_remote2_attr_group); fail3: ati_remote2_urb_cleanup(ar2); fail2: usb_driver_release_interface(&ati_remote2_driver, ar2->intf[1]); fail1: kfree(ar2); return r; } static void ati_remote2_disconnect(struct usb_interface *interface) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; if (alt->desc.bInterfaceNumber) return; ar2 = usb_get_intfdata(interface); usb_set_intfdata(interface, NULL); input_unregister_device(ar2->idev); sysfs_remove_group(&ar2->udev->dev.kobj, &ati_remote2_attr_group); ati_remote2_urb_cleanup(ar2); usb_driver_release_interface(&ati_remote2_driver, ar2->intf[1]); kfree(ar2); } static int ati_remote2_suspend(struct usb_interface *interface, pm_message_t message) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); if (ar2->flags & ATI_REMOTE2_OPENED) ati_remote2_kill_urbs(ar2); ar2->flags |= ATI_REMOTE2_SUSPENDED; mutex_unlock(&ati_remote2_mutex); return 0; } static int ati_remote2_resume(struct usb_interface *interface) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; int r = 0; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); if (ar2->flags & ATI_REMOTE2_OPENED) r = ati_remote2_submit_urbs(ar2); if (!r) ar2->flags &= ~ATI_REMOTE2_SUSPENDED; mutex_unlock(&ati_remote2_mutex); return r; } static int ati_remote2_reset_resume(struct usb_interface *interface) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; int r = 0; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); r = ati_remote2_setup(ar2, ar2->channel_mask); if (r) goto out; if (ar2->flags & ATI_REMOTE2_OPENED) r = ati_remote2_submit_urbs(ar2); if (!r) ar2->flags &= ~ATI_REMOTE2_SUSPENDED; out: mutex_unlock(&ati_remote2_mutex); return r; } static int ati_remote2_pre_reset(struct usb_interface *interface) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); if (ar2->flags == ATI_REMOTE2_OPENED) ati_remote2_kill_urbs(ar2); return 0; } static int ati_remote2_post_reset(struct usb_interface *interface) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; int r = 0; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); if (ar2->flags == ATI_REMOTE2_OPENED) r = ati_remote2_submit_urbs(ar2); mutex_unlock(&ati_remote2_mutex); return r; } module_usb_driver(ati_remote2_driver);
linux-master
drivers/input/misc/ati_remote2.c
/* * Hisilicon PMIC powerkey driver * * Copyright (C) 2013 Hisilicon Ltd. * Copyright (C) 2015, 2016 Linaro Ltd. * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/reboot.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of_irq.h> #include <linux/input.h> #include <linux/slab.h> /* the held interrupt will trigger after 4 seconds */ #define MAX_HELD_TIME (4 * MSEC_PER_SEC) static irqreturn_t hi65xx_power_press_isr(int irq, void *q) { struct input_dev *input = q; pm_wakeup_event(input->dev.parent, MAX_HELD_TIME); input_report_key(input, KEY_POWER, 1); input_sync(input); return IRQ_HANDLED; } static irqreturn_t hi65xx_power_release_isr(int irq, void *q) { struct input_dev *input = q; pm_wakeup_event(input->dev.parent, MAX_HELD_TIME); input_report_key(input, KEY_POWER, 0); input_sync(input); return IRQ_HANDLED; } static irqreturn_t hi65xx_restart_toggle_isr(int irq, void *q) { struct input_dev *input = q; int value = test_bit(KEY_RESTART, input->key); pm_wakeup_event(input->dev.parent, MAX_HELD_TIME); input_report_key(input, KEY_RESTART, !value); input_sync(input); return IRQ_HANDLED; } static const struct { const char *name; irqreturn_t (*handler)(int irq, void *q); } hi65xx_irq_info[] = { { "down", hi65xx_power_press_isr }, { "up", hi65xx_power_release_isr }, { "hold 4s", hi65xx_restart_toggle_isr }, }; static int hi65xx_powerkey_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct input_dev *input; int irq, i, error; input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "failed to allocate input device\n"); return -ENOMEM; } input->phys = "hisi_on/input0"; input->name = "HISI 65xx PowerOn Key"; input_set_capability(input, EV_KEY, KEY_POWER); input_set_capability(input, EV_KEY, KEY_RESTART); for (i = 0; i < ARRAY_SIZE(hi65xx_irq_info); i++) { irq = platform_get_irq_byname(pdev, hi65xx_irq_info[i].name); if (irq < 0) return irq; error = devm_request_any_context_irq(dev, irq, hi65xx_irq_info[i].handler, IRQF_ONESHOT, hi65xx_irq_info[i].name, input); if (error < 0) { dev_err(dev, "couldn't request irq %s: %d\n", hi65xx_irq_info[i].name, error); return error; } } error = input_register_device(input); if (error) { dev_err(dev, "failed to register input device: %d\n", error); return error; } device_init_wakeup(dev, 1); return 0; } static struct platform_driver hi65xx_powerkey_driver = { .driver = { .name = "hi65xx-powerkey", }, .probe = hi65xx_powerkey_probe, }; module_platform_driver(hi65xx_powerkey_driver); MODULE_AUTHOR("Zhiliang Xue <[email protected]"); MODULE_DESCRIPTION("Hisi PMIC Power key driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/misc/hisi_powerkey.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * ON pin driver for Dialog DA9055 PMICs * * Copyright(c) 2012 Dialog Semiconductor Ltd. * * Author: David Dajun Chen <[email protected]> */ #include <linux/input.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/mfd/da9055/core.h> #include <linux/mfd/da9055/reg.h> struct da9055_onkey { struct da9055 *da9055; struct input_dev *input; struct delayed_work work; }; static void da9055_onkey_query(struct da9055_onkey *onkey) { int key_stat; key_stat = da9055_reg_read(onkey->da9055, DA9055_REG_STATUS_A); if (key_stat < 0) { dev_err(onkey->da9055->dev, "Failed to read onkey event %d\n", key_stat); } else { key_stat &= DA9055_NOKEY_STS; /* * Onkey status bit is cleared when onkey button is released. */ if (!key_stat) { input_report_key(onkey->input, KEY_POWER, 0); input_sync(onkey->input); } } /* * Interrupt is generated only when the ONKEY pin is asserted. * Hence the deassertion of the pin is simulated through work queue. */ if (key_stat) schedule_delayed_work(&onkey->work, msecs_to_jiffies(10)); } static void da9055_onkey_work(struct work_struct *work) { struct da9055_onkey *onkey = container_of(work, struct da9055_onkey, work.work); da9055_onkey_query(onkey); } static irqreturn_t da9055_onkey_irq(int irq, void *data) { struct da9055_onkey *onkey = data; input_report_key(onkey->input, KEY_POWER, 1); input_sync(onkey->input); da9055_onkey_query(onkey); return IRQ_HANDLED; } static int da9055_onkey_probe(struct platform_device *pdev) { struct da9055 *da9055 = dev_get_drvdata(pdev->dev.parent); struct da9055_onkey *onkey; struct input_dev *input_dev; int irq, err; irq = platform_get_irq_byname(pdev, "ONKEY"); if (irq < 0) return -EINVAL; onkey = devm_kzalloc(&pdev->dev, sizeof(*onkey), GFP_KERNEL); if (!onkey) { dev_err(&pdev->dev, "Failed to allocate memory\n"); return -ENOMEM; } input_dev = input_allocate_device(); if (!input_dev) { dev_err(&pdev->dev, "Failed to allocate memory\n"); return -ENOMEM; } onkey->input = input_dev; onkey->da9055 = da9055; input_dev->name = "da9055-onkey"; input_dev->phys = "da9055-onkey/input0"; input_dev->dev.parent = &pdev->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY); __set_bit(KEY_POWER, input_dev->keybit); INIT_DELAYED_WORK(&onkey->work, da9055_onkey_work); err = request_threaded_irq(irq, NULL, da9055_onkey_irq, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, "ONKEY", onkey); if (err < 0) { dev_err(&pdev->dev, "Failed to register ONKEY IRQ %d, error = %d\n", irq, err); goto err_free_input; } err = input_register_device(input_dev); if (err) { dev_err(&pdev->dev, "Unable to register input device, %d\n", err); goto err_free_irq; } platform_set_drvdata(pdev, onkey); return 0; err_free_irq: free_irq(irq, onkey); cancel_delayed_work_sync(&onkey->work); err_free_input: input_free_device(input_dev); return err; } static int da9055_onkey_remove(struct platform_device *pdev) { struct da9055_onkey *onkey = platform_get_drvdata(pdev); int irq = platform_get_irq_byname(pdev, "ONKEY"); irq = regmap_irq_get_virq(onkey->da9055->irq_data, irq); free_irq(irq, onkey); cancel_delayed_work_sync(&onkey->work); input_unregister_device(onkey->input); return 0; } static struct platform_driver da9055_onkey_driver = { .probe = da9055_onkey_probe, .remove = da9055_onkey_remove, .driver = { .name = "da9055-onkey", }, }; module_platform_driver(da9055_onkey_driver); MODULE_AUTHOR("David Dajun Chen <[email protected]>"); MODULE_DESCRIPTION("Onkey driver for DA9055"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:da9055-onkey");
linux-master
drivers/input/misc/da9055_onkey.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2018 Spreadtrum Communications Inc. */ #include <linux/device.h> #include <linux/input.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/property.h> #include <linux/regmap.h> #include <linux/workqueue.h> #define CUR_DRV_CAL_SEL GENMASK(13, 12) #define SLP_LDOVIBR_PD_EN BIT(9) #define LDO_VIBR_PD BIT(8) #define SC2730_CUR_DRV_CAL_SEL 0 #define SC2730_SLP_LDOVIBR_PD_EN BIT(14) #define SC2730_LDO_VIBR_PD BIT(13) struct sc27xx_vibra_data { u32 cur_drv_cal_sel; u32 slp_pd_en; u32 ldo_pd; }; struct vibra_info { struct input_dev *input_dev; struct work_struct play_work; struct regmap *regmap; const struct sc27xx_vibra_data *data; u32 base; u32 strength; bool enabled; }; static const struct sc27xx_vibra_data sc2731_data = { .cur_drv_cal_sel = CUR_DRV_CAL_SEL, .slp_pd_en = SLP_LDOVIBR_PD_EN, .ldo_pd = LDO_VIBR_PD, }; static const struct sc27xx_vibra_data sc2730_data = { .cur_drv_cal_sel = SC2730_CUR_DRV_CAL_SEL, .slp_pd_en = SC2730_SLP_LDOVIBR_PD_EN, .ldo_pd = SC2730_LDO_VIBR_PD, }; static const struct sc27xx_vibra_data sc2721_data = { .cur_drv_cal_sel = CUR_DRV_CAL_SEL, .slp_pd_en = SLP_LDOVIBR_PD_EN, .ldo_pd = LDO_VIBR_PD, }; static void sc27xx_vibra_set(struct vibra_info *info, bool on) { const struct sc27xx_vibra_data *data = info->data; if (on) { regmap_update_bits(info->regmap, info->base, data->ldo_pd, 0); regmap_update_bits(info->regmap, info->base, data->slp_pd_en, 0); info->enabled = true; } else { regmap_update_bits(info->regmap, info->base, data->ldo_pd, data->ldo_pd); regmap_update_bits(info->regmap, info->base, data->slp_pd_en, data->slp_pd_en); info->enabled = false; } } static int sc27xx_vibra_hw_init(struct vibra_info *info) { const struct sc27xx_vibra_data *data = info->data; if (!data->cur_drv_cal_sel) return 0; return regmap_update_bits(info->regmap, info->base, data->cur_drv_cal_sel, 0); } static void sc27xx_vibra_play_work(struct work_struct *work) { struct vibra_info *info = container_of(work, struct vibra_info, play_work); if (info->strength && !info->enabled) sc27xx_vibra_set(info, true); else if (info->strength == 0 && info->enabled) sc27xx_vibra_set(info, false); } static int sc27xx_vibra_play(struct input_dev *input, void *data, struct ff_effect *effect) { struct vibra_info *info = input_get_drvdata(input); info->strength = effect->u.rumble.weak_magnitude; schedule_work(&info->play_work); return 0; } static void sc27xx_vibra_close(struct input_dev *input) { struct vibra_info *info = input_get_drvdata(input); cancel_work_sync(&info->play_work); if (info->enabled) sc27xx_vibra_set(info, false); } static int sc27xx_vibra_probe(struct platform_device *pdev) { struct vibra_info *info; const struct sc27xx_vibra_data *data; int error; data = device_get_match_data(&pdev->dev); if (!data) { dev_err(&pdev->dev, "no matching driver data found\n"); return -EINVAL; } info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; info->regmap = dev_get_regmap(pdev->dev.parent, NULL); if (!info->regmap) { dev_err(&pdev->dev, "failed to get vibrator regmap.\n"); return -ENODEV; } error = device_property_read_u32(&pdev->dev, "reg", &info->base); if (error) { dev_err(&pdev->dev, "failed to get vibrator base address.\n"); return error; } info->input_dev = devm_input_allocate_device(&pdev->dev); if (!info->input_dev) { dev_err(&pdev->dev, "failed to allocate input device.\n"); return -ENOMEM; } info->input_dev->name = "sc27xx:vibrator"; info->input_dev->id.version = 0; info->input_dev->close = sc27xx_vibra_close; info->data = data; input_set_drvdata(info->input_dev, info); input_set_capability(info->input_dev, EV_FF, FF_RUMBLE); INIT_WORK(&info->play_work, sc27xx_vibra_play_work); info->enabled = false; error = sc27xx_vibra_hw_init(info); if (error) { dev_err(&pdev->dev, "failed to initialize the vibrator.\n"); return error; } error = input_ff_create_memless(info->input_dev, NULL, sc27xx_vibra_play); if (error) { dev_err(&pdev->dev, "failed to register vibrator to FF.\n"); return error; } error = input_register_device(info->input_dev); if (error) { dev_err(&pdev->dev, "failed to register input device.\n"); return error; } return 0; } static const struct of_device_id sc27xx_vibra_of_match[] = { { .compatible = "sprd,sc2721-vibrator", .data = &sc2721_data }, { .compatible = "sprd,sc2730-vibrator", .data = &sc2730_data }, { .compatible = "sprd,sc2731-vibrator", .data = &sc2731_data }, {} }; MODULE_DEVICE_TABLE(of, sc27xx_vibra_of_match); static struct platform_driver sc27xx_vibra_driver = { .driver = { .name = "sc27xx-vibrator", .of_match_table = sc27xx_vibra_of_match, }, .probe = sc27xx_vibra_probe, }; module_platform_driver(sc27xx_vibra_driver); MODULE_DESCRIPTION("Spreadtrum SC27xx Vibrator Driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Xiaotong Lu <[email protected]>");
linux-master
drivers/input/misc/sc27xx-vibra.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AD714X CapTouch Programmable Controller driver supporting AD7142/3/7/8/7A * * Copyright 2009-2011 Analog Devices Inc. */ #include <linux/device.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/input/ad714x.h> #include <linux/module.h> #include "ad714x.h" #define AD714X_PWR_CTRL 0x0 #define AD714X_STG_CAL_EN_REG 0x1 #define AD714X_AMB_COMP_CTRL0_REG 0x2 #define AD714X_PARTID_REG 0x17 #define AD7142_PARTID 0xE620 #define AD7143_PARTID 0xE630 #define AD7147_PARTID 0x1470 #define AD7148_PARTID 0x1480 #define AD714X_STAGECFG_REG 0x80 #define AD714X_SYSCFG_REG 0x0 #define STG_LOW_INT_EN_REG 0x5 #define STG_HIGH_INT_EN_REG 0x6 #define STG_COM_INT_EN_REG 0x7 #define STG_LOW_INT_STA_REG 0x8 #define STG_HIGH_INT_STA_REG 0x9 #define STG_COM_INT_STA_REG 0xA #define CDC_RESULT_S0 0xB #define CDC_RESULT_S1 0xC #define CDC_RESULT_S2 0xD #define CDC_RESULT_S3 0xE #define CDC_RESULT_S4 0xF #define CDC_RESULT_S5 0x10 #define CDC_RESULT_S6 0x11 #define CDC_RESULT_S7 0x12 #define CDC_RESULT_S8 0x13 #define CDC_RESULT_S9 0x14 #define CDC_RESULT_S10 0x15 #define CDC_RESULT_S11 0x16 #define STAGE0_AMBIENT 0xF1 #define STAGE1_AMBIENT 0x115 #define STAGE2_AMBIENT 0x139 #define STAGE3_AMBIENT 0x15D #define STAGE4_AMBIENT 0x181 #define STAGE5_AMBIENT 0x1A5 #define STAGE6_AMBIENT 0x1C9 #define STAGE7_AMBIENT 0x1ED #define STAGE8_AMBIENT 0x211 #define STAGE9_AMBIENT 0x234 #define STAGE10_AMBIENT 0x259 #define STAGE11_AMBIENT 0x27D #define PER_STAGE_REG_NUM 36 #define STAGE_CFGREG_NUM 8 #define SYS_CFGREG_NUM 8 /* * driver information which will be used to maintain the software flow */ enum ad714x_device_state { IDLE, JITTER, ACTIVE, SPACE }; struct ad714x_slider_drv { int highest_stage; int abs_pos; int flt_pos; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_wheel_drv { int abs_pos; int flt_pos; int pre_highest_stage; int highest_stage; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_touchpad_drv { int x_highest_stage; int x_flt_pos; int x_abs_pos; int y_highest_stage; int y_flt_pos; int y_abs_pos; int left_ep; int left_ep_val; int right_ep; int right_ep_val; int top_ep; int top_ep_val; int bottom_ep; int bottom_ep_val; enum ad714x_device_state state; struct input_dev *input; }; struct ad714x_button_drv { enum ad714x_device_state state; /* * Unlike slider/wheel/touchpad, all buttons point to * same input_dev instance */ struct input_dev *input; }; struct ad714x_driver_data { struct ad714x_slider_drv *slider; struct ad714x_wheel_drv *wheel; struct ad714x_touchpad_drv *touchpad; struct ad714x_button_drv *button; }; /* * information to integrate all things which will be private data * of spi/i2c device */ static void ad714x_use_com_int(struct ad714x_chip *ad714x, int start_stage, int end_stage) { unsigned short data; unsigned short mask; mask = ((1 << (end_stage + 1)) - 1) - ((1 << start_stage) - 1); ad714x->read(ad714x, STG_COM_INT_EN_REG, &data, 1); data |= 1 << end_stage; ad714x->write(ad714x, STG_COM_INT_EN_REG, data); ad714x->read(ad714x, STG_HIGH_INT_EN_REG, &data, 1); data &= ~mask; ad714x->write(ad714x, STG_HIGH_INT_EN_REG, data); } static void ad714x_use_thr_int(struct ad714x_chip *ad714x, int start_stage, int end_stage) { unsigned short data; unsigned short mask; mask = ((1 << (end_stage + 1)) - 1) - ((1 << start_stage) - 1); ad714x->read(ad714x, STG_COM_INT_EN_REG, &data, 1); data &= ~(1 << end_stage); ad714x->write(ad714x, STG_COM_INT_EN_REG, data); ad714x->read(ad714x, STG_HIGH_INT_EN_REG, &data, 1); data |= mask; ad714x->write(ad714x, STG_HIGH_INT_EN_REG, data); } static int ad714x_cal_highest_stage(struct ad714x_chip *ad714x, int start_stage, int end_stage) { int max_res = 0; int max_idx = 0; int i; for (i = start_stage; i <= end_stage; i++) { if (ad714x->sensor_val[i] > max_res) { max_res = ad714x->sensor_val[i]; max_idx = i; } } return max_idx; } static int ad714x_cal_abs_pos(struct ad714x_chip *ad714x, int start_stage, int end_stage, int highest_stage, int max_coord) { int a_param, b_param; if (highest_stage == start_stage) { a_param = ad714x->sensor_val[start_stage + 1]; b_param = ad714x->sensor_val[start_stage] + ad714x->sensor_val[start_stage + 1]; } else if (highest_stage == end_stage) { a_param = ad714x->sensor_val[end_stage] * (end_stage - start_stage) + ad714x->sensor_val[end_stage - 1] * (end_stage - start_stage - 1); b_param = ad714x->sensor_val[end_stage] + ad714x->sensor_val[end_stage - 1]; } else { a_param = ad714x->sensor_val[highest_stage] * (highest_stage - start_stage) + ad714x->sensor_val[highest_stage - 1] * (highest_stage - start_stage - 1) + ad714x->sensor_val[highest_stage + 1] * (highest_stage - start_stage + 1); b_param = ad714x->sensor_val[highest_stage] + ad714x->sensor_val[highest_stage - 1] + ad714x->sensor_val[highest_stage + 1]; } return (max_coord / (end_stage - start_stage)) * a_param / b_param; } /* * One button can connect to multi positive and negative of CDCs * Multi-buttons can connect to same positive/negative of one CDC */ static void ad714x_button_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_button_plat *hw = &ad714x->hw->button[idx]; struct ad714x_button_drv *sw = &ad714x->sw->button[idx]; switch (sw->state) { case IDLE: if (((ad714x->h_state & hw->h_mask) == hw->h_mask) && ((ad714x->l_state & hw->l_mask) == hw->l_mask)) { dev_dbg(ad714x->dev, "button %d touched\n", idx); input_report_key(sw->input, hw->keycode, 1); input_sync(sw->input); sw->state = ACTIVE; } break; case ACTIVE: if (((ad714x->h_state & hw->h_mask) != hw->h_mask) || ((ad714x->l_state & hw->l_mask) != hw->l_mask)) { dev_dbg(ad714x->dev, "button %d released\n", idx); input_report_key(sw->input, hw->keycode, 0); input_sync(sw->input); sw->state = IDLE; } break; default: break; } } /* * The response of a sensor is defined by the absolute number of codes * between the current CDC value and the ambient value. */ static void ad714x_slider_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->start_stage, &ad714x->adc_reg[hw->start_stage], hw->end_stage - hw->start_stage + 1); for (i = hw->start_stage; i <= hw->end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); ad714x->sensor_val[i] = abs(ad714x->adc_reg[i] - ad714x->amb_reg[i]); } } static void ad714x_slider_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->highest_stage = ad714x_cal_highest_stage(ad714x, hw->start_stage, hw->end_stage); dev_dbg(ad714x->dev, "slider %d highest_stage:%d\n", idx, sw->highest_stage); } /* * The formulae are very straight forward. It uses the sensor with the * highest response and the 2 adjacent ones. * When Sensor 0 has the highest response, only sensor 0 and sensor 1 * are used in the calculations. Similarly when the last sensor has the * highest response, only the last sensor and the second last sensors * are used in the calculations. * * For i= idx_of_peak_Sensor-1 to i= idx_of_peak_Sensor+1 * v += Sensor response(i)*i * w += Sensor response(i) * POS=(Number_of_Positions_Wanted/(Number_of_Sensors_Used-1)) *(v/w) */ static void ad714x_slider_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->abs_pos = ad714x_cal_abs_pos(ad714x, hw->start_stage, hw->end_stage, sw->highest_stage, hw->max_coord); dev_dbg(ad714x->dev, "slider %d absolute position:%d\n", idx, sw->abs_pos); } /* * To minimise the Impact of the noise on the algorithm, ADI developed a * routine that filters the CDC results after they have been read by the * host processor. * The filter used is an Infinite Input Response(IIR) filter implemented * in firmware and attenuates the noise on the CDC results after they've * been read by the host processor. * Filtered_CDC_result = (Filtered_CDC_result * (10 - Coefficient) + * Latest_CDC_result * Coefficient)/10 */ static void ad714x_slider_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; sw->flt_pos = (sw->flt_pos * (10 - 4) + sw->abs_pos * 4)/10; dev_dbg(ad714x->dev, "slider %d filter position:%d\n", idx, sw->flt_pos); } static void ad714x_slider_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; ad714x_use_com_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_slider_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; ad714x_use_thr_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_slider_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_slider_plat *hw = &ad714x->hw->slider[idx]; struct ad714x_slider_drv *sw = &ad714x->sw->slider[idx]; unsigned short h_state, c_state; unsigned short mask; mask = ((1 << (hw->end_stage + 1)) - 1) - ((1 << hw->start_stage) - 1); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ ad714x_slider_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "slider %d touched\n", idx); } break; case JITTER: if (c_state == mask) { ad714x_slider_cal_sensor_val(ad714x, idx); ad714x_slider_cal_highest_stage(ad714x, idx); ad714x_slider_cal_abs_pos(ad714x, idx); sw->flt_pos = sw->abs_pos; sw->state = ACTIVE; } break; case ACTIVE: if (c_state == mask) { if (h_state) { ad714x_slider_cal_sensor_val(ad714x, idx); ad714x_slider_cal_highest_stage(ad714x, idx); ad714x_slider_cal_abs_pos(ad714x, idx); ad714x_slider_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_X, sw->flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ ad714x_slider_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "slider %d released\n", idx); } input_sync(sw->input); } break; default: break; } } /* * When the scroll wheel is activated, we compute the absolute position based * on the sensor values. To calculate the position, we first determine the * sensor that has the greatest response among the 8 sensors that constitutes * the scrollwheel. Then we determined the 2 sensors on either sides of the * sensor with the highest response and we apply weights to these sensors. */ static void ad714x_wheel_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; sw->pre_highest_stage = sw->highest_stage; sw->highest_stage = ad714x_cal_highest_stage(ad714x, hw->start_stage, hw->end_stage); dev_dbg(ad714x->dev, "wheel %d highest_stage:%d\n", idx, sw->highest_stage); } static void ad714x_wheel_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->start_stage, &ad714x->adc_reg[hw->start_stage], hw->end_stage - hw->start_stage + 1); for (i = hw->start_stage; i <= hw->end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); if (ad714x->adc_reg[i] > ad714x->amb_reg[i]) ad714x->sensor_val[i] = ad714x->adc_reg[i] - ad714x->amb_reg[i]; else ad714x->sensor_val[i] = 0; } } /* * When the scroll wheel is activated, we compute the absolute position based * on the sensor values. To calculate the position, we first determine the * sensor that has the greatest response among the sensors that constitutes * the scrollwheel. Then we determined the sensors on either sides of the * sensor with the highest response and we apply weights to these sensors. The * result of this computation gives us the mean value. */ static void ad714x_wheel_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; int stage_num = hw->end_stage - hw->start_stage + 1; int first_before, highest, first_after; int a_param, b_param; first_before = (sw->highest_stage + stage_num - 1) % stage_num; highest = sw->highest_stage; first_after = (sw->highest_stage + stage_num + 1) % stage_num; a_param = ad714x->sensor_val[highest] * (highest - hw->start_stage) + ad714x->sensor_val[first_before] * (highest - hw->start_stage - 1) + ad714x->sensor_val[first_after] * (highest - hw->start_stage + 1); b_param = ad714x->sensor_val[highest] + ad714x->sensor_val[first_before] + ad714x->sensor_val[first_after]; sw->abs_pos = ((hw->max_coord / (hw->end_stage - hw->start_stage)) * a_param) / b_param; if (sw->abs_pos > hw->max_coord) sw->abs_pos = hw->max_coord; else if (sw->abs_pos < 0) sw->abs_pos = 0; } static void ad714x_wheel_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; if (((sw->pre_highest_stage == hw->end_stage) && (sw->highest_stage == hw->start_stage)) || ((sw->pre_highest_stage == hw->start_stage) && (sw->highest_stage == hw->end_stage))) sw->flt_pos = sw->abs_pos; else sw->flt_pos = ((sw->flt_pos * 30) + (sw->abs_pos * 71)) / 100; if (sw->flt_pos > hw->max_coord) sw->flt_pos = hw->max_coord; } static void ad714x_wheel_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; ad714x_use_com_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_wheel_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; ad714x_use_thr_int(ad714x, hw->start_stage, hw->end_stage); } static void ad714x_wheel_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_wheel_plat *hw = &ad714x->hw->wheel[idx]; struct ad714x_wheel_drv *sw = &ad714x->sw->wheel[idx]; unsigned short h_state, c_state; unsigned short mask; mask = ((1 << (hw->end_stage + 1)) - 1) - ((1 << hw->start_stage) - 1); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ ad714x_wheel_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "wheel %d touched\n", idx); } break; case JITTER: if (c_state == mask) { ad714x_wheel_cal_sensor_val(ad714x, idx); ad714x_wheel_cal_highest_stage(ad714x, idx); ad714x_wheel_cal_abs_pos(ad714x, idx); sw->flt_pos = sw->abs_pos; sw->state = ACTIVE; } break; case ACTIVE: if (c_state == mask) { if (h_state) { ad714x_wheel_cal_sensor_val(ad714x, idx); ad714x_wheel_cal_highest_stage(ad714x, idx); ad714x_wheel_cal_abs_pos(ad714x, idx); ad714x_wheel_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_WHEEL, sw->flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ ad714x_wheel_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "wheel %d released\n", idx); } input_sync(sw->input); } break; default: break; } } static void touchpad_cal_sensor_val(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; int i; ad714x->read(ad714x, CDC_RESULT_S0 + hw->x_start_stage, &ad714x->adc_reg[hw->x_start_stage], hw->x_end_stage - hw->x_start_stage + 1); for (i = hw->x_start_stage; i <= hw->x_end_stage; i++) { ad714x->read(ad714x, STAGE0_AMBIENT + i * PER_STAGE_REG_NUM, &ad714x->amb_reg[i], 1); if (ad714x->adc_reg[i] > ad714x->amb_reg[i]) ad714x->sensor_val[i] = ad714x->adc_reg[i] - ad714x->amb_reg[i]; else ad714x->sensor_val[i] = 0; } } static void touchpad_cal_highest_stage(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_highest_stage = ad714x_cal_highest_stage(ad714x, hw->x_start_stage, hw->x_end_stage); sw->y_highest_stage = ad714x_cal_highest_stage(ad714x, hw->y_start_stage, hw->y_end_stage); dev_dbg(ad714x->dev, "touchpad %d x_highest_stage:%d, y_highest_stage:%d\n", idx, sw->x_highest_stage, sw->y_highest_stage); } /* * If 2 fingers are touching the sensor then 2 peaks can be observed in the * distribution. * The arithmetic doesn't support to get absolute coordinates for multi-touch * yet. */ static int touchpad_check_second_peak(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; int i; for (i = hw->x_start_stage; i < sw->x_highest_stage; i++) { if ((ad714x->sensor_val[i] - ad714x->sensor_val[i + 1]) > (ad714x->sensor_val[i + 1] / 10)) return 1; } for (i = sw->x_highest_stage; i < hw->x_end_stage; i++) { if ((ad714x->sensor_val[i + 1] - ad714x->sensor_val[i]) > (ad714x->sensor_val[i] / 10)) return 1; } for (i = hw->y_start_stage; i < sw->y_highest_stage; i++) { if ((ad714x->sensor_val[i] - ad714x->sensor_val[i + 1]) > (ad714x->sensor_val[i + 1] / 10)) return 1; } for (i = sw->y_highest_stage; i < hw->y_end_stage; i++) { if ((ad714x->sensor_val[i + 1] - ad714x->sensor_val[i]) > (ad714x->sensor_val[i] / 10)) return 1; } return 0; } /* * If only one finger is used to activate the touch pad then only 1 peak will be * registered in the distribution. This peak and the 2 adjacent sensors will be * used in the calculation of the absolute position. This will prevent hand * shadows to affect the absolute position calculation. */ static void touchpad_cal_abs_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_abs_pos = ad714x_cal_abs_pos(ad714x, hw->x_start_stage, hw->x_end_stage, sw->x_highest_stage, hw->x_max_coord); sw->y_abs_pos = ad714x_cal_abs_pos(ad714x, hw->y_start_stage, hw->y_end_stage, sw->y_highest_stage, hw->y_max_coord); dev_dbg(ad714x->dev, "touchpad %d absolute position:(%d, %d)\n", idx, sw->x_abs_pos, sw->y_abs_pos); } static void touchpad_cal_flt_pos(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; sw->x_flt_pos = (sw->x_flt_pos * (10 - 4) + sw->x_abs_pos * 4)/10; sw->y_flt_pos = (sw->y_flt_pos * (10 - 4) + sw->y_abs_pos * 4)/10; dev_dbg(ad714x->dev, "touchpad %d filter position:(%d, %d)\n", idx, sw->x_flt_pos, sw->y_flt_pos); } /* * To prevent distortion from showing in the absolute position, it is * necessary to detect the end points. When endpoints are detected, the * driver stops updating the status variables with absolute positions. * End points are detected on the 4 edges of the touchpad sensor. The * method to detect them is the same for all 4. * To detect the end points, the firmware computes the difference in * percent between the sensor on the edge and the adjacent one. The * difference is calculated in percent in order to make the end point * detection independent of the pressure. */ #define LEFT_END_POINT_DETECTION_LEVEL 550 #define RIGHT_END_POINT_DETECTION_LEVEL 750 #define LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL 850 #define TOP_END_POINT_DETECTION_LEVEL 550 #define BOTTOM_END_POINT_DETECTION_LEVEL 950 #define TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL 700 static int touchpad_check_endpoint(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; int percent_sensor_diff; /* left endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->x_start_stage] - ad714x->sensor_val[hw->x_start_stage + 1]) * 100 / ad714x->sensor_val[hw->x_start_stage + 1]; if (!sw->left_ep) { if (percent_sensor_diff >= LEFT_END_POINT_DETECTION_LEVEL) { sw->left_ep = 1; sw->left_ep_val = ad714x->sensor_val[hw->x_start_stage + 1]; } } else { if ((percent_sensor_diff < LEFT_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->x_start_stage + 1] > LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL + sw->left_ep_val)) sw->left_ep = 0; } /* right endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->x_end_stage] - ad714x->sensor_val[hw->x_end_stage - 1]) * 100 / ad714x->sensor_val[hw->x_end_stage - 1]; if (!sw->right_ep) { if (percent_sensor_diff >= RIGHT_END_POINT_DETECTION_LEVEL) { sw->right_ep = 1; sw->right_ep_val = ad714x->sensor_val[hw->x_end_stage - 1]; } } else { if ((percent_sensor_diff < RIGHT_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->x_end_stage - 1] > LEFT_RIGHT_END_POINT_DEAVTIVALION_LEVEL + sw->right_ep_val)) sw->right_ep = 0; } /* top endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->y_start_stage] - ad714x->sensor_val[hw->y_start_stage + 1]) * 100 / ad714x->sensor_val[hw->y_start_stage + 1]; if (!sw->top_ep) { if (percent_sensor_diff >= TOP_END_POINT_DETECTION_LEVEL) { sw->top_ep = 1; sw->top_ep_val = ad714x->sensor_val[hw->y_start_stage + 1]; } } else { if ((percent_sensor_diff < TOP_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->y_start_stage + 1] > TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL + sw->top_ep_val)) sw->top_ep = 0; } /* bottom endpoint detect */ percent_sensor_diff = (ad714x->sensor_val[hw->y_end_stage] - ad714x->sensor_val[hw->y_end_stage - 1]) * 100 / ad714x->sensor_val[hw->y_end_stage - 1]; if (!sw->bottom_ep) { if (percent_sensor_diff >= BOTTOM_END_POINT_DETECTION_LEVEL) { sw->bottom_ep = 1; sw->bottom_ep_val = ad714x->sensor_val[hw->y_end_stage - 1]; } } else { if ((percent_sensor_diff < BOTTOM_END_POINT_DETECTION_LEVEL) && (ad714x->sensor_val[hw->y_end_stage - 1] > TOP_BOTTOM_END_POINT_DEAVTIVALION_LEVEL + sw->bottom_ep_val)) sw->bottom_ep = 0; } return sw->left_ep || sw->right_ep || sw->top_ep || sw->bottom_ep; } static void touchpad_use_com_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; ad714x_use_com_int(ad714x, hw->x_start_stage, hw->x_end_stage); } static void touchpad_use_thr_int(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; ad714x_use_thr_int(ad714x, hw->x_start_stage, hw->x_end_stage); ad714x_use_thr_int(ad714x, hw->y_start_stage, hw->y_end_stage); } static void ad714x_touchpad_state_machine(struct ad714x_chip *ad714x, int idx) { struct ad714x_touchpad_plat *hw = &ad714x->hw->touchpad[idx]; struct ad714x_touchpad_drv *sw = &ad714x->sw->touchpad[idx]; unsigned short h_state, c_state; unsigned short mask; mask = (((1 << (hw->x_end_stage + 1)) - 1) - ((1 << hw->x_start_stage) - 1)) + (((1 << (hw->y_end_stage + 1)) - 1) - ((1 << hw->y_start_stage) - 1)); h_state = ad714x->h_state & mask; c_state = ad714x->c_state & mask; switch (sw->state) { case IDLE: if (h_state) { sw->state = JITTER; /* In End of Conversion interrupt mode, the AD714X * continuously generates hardware interrupts. */ touchpad_use_com_int(ad714x, idx); dev_dbg(ad714x->dev, "touchpad %d touched\n", idx); } break; case JITTER: if (c_state == mask) { touchpad_cal_sensor_val(ad714x, idx); touchpad_cal_highest_stage(ad714x, idx); if ((!touchpad_check_second_peak(ad714x, idx)) && (!touchpad_check_endpoint(ad714x, idx))) { dev_dbg(ad714x->dev, "touchpad%d, 2 fingers or endpoint\n", idx); touchpad_cal_abs_pos(ad714x, idx); sw->x_flt_pos = sw->x_abs_pos; sw->y_flt_pos = sw->y_abs_pos; sw->state = ACTIVE; } } break; case ACTIVE: if (c_state == mask) { if (h_state) { touchpad_cal_sensor_val(ad714x, idx); touchpad_cal_highest_stage(ad714x, idx); if ((!touchpad_check_second_peak(ad714x, idx)) && (!touchpad_check_endpoint(ad714x, idx))) { touchpad_cal_abs_pos(ad714x, idx); touchpad_cal_flt_pos(ad714x, idx); input_report_abs(sw->input, ABS_X, sw->x_flt_pos); input_report_abs(sw->input, ABS_Y, sw->y_flt_pos); input_report_key(sw->input, BTN_TOUCH, 1); } } else { /* When the user lifts off the sensor, configure * the AD714X back to threshold interrupt mode. */ touchpad_use_thr_int(ad714x, idx); sw->state = IDLE; input_report_key(sw->input, BTN_TOUCH, 0); dev_dbg(ad714x->dev, "touchpad %d released\n", idx); } input_sync(sw->input); } break; default: break; } } static int ad714x_hw_detect(struct ad714x_chip *ad714x) { unsigned short data; ad714x->read(ad714x, AD714X_PARTID_REG, &data, 1); switch (data & 0xFFF0) { case AD7142_PARTID: ad714x->product = 0x7142; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7142 captouch, rev:%d\n", ad714x->version); return 0; case AD7143_PARTID: ad714x->product = 0x7143; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7143 captouch, rev:%d\n", ad714x->version); return 0; case AD7147_PARTID: ad714x->product = 0x7147; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7147(A) captouch, rev:%d\n", ad714x->version); return 0; case AD7148_PARTID: ad714x->product = 0x7148; ad714x->version = data & 0xF; dev_info(ad714x->dev, "found AD7148 captouch, rev:%d\n", ad714x->version); return 0; default: dev_err(ad714x->dev, "fail to detect AD714X captouch, read ID is %04x\n", data); return -ENODEV; } } static void ad714x_hw_init(struct ad714x_chip *ad714x) { int i, j; unsigned short reg_base; unsigned short data; /* configuration CDC and interrupts */ for (i = 0; i < STAGE_NUM; i++) { reg_base = AD714X_STAGECFG_REG + i * STAGE_CFGREG_NUM; for (j = 0; j < STAGE_CFGREG_NUM; j++) ad714x->write(ad714x, reg_base + j, ad714x->hw->stage_cfg_reg[i][j]); } for (i = 0; i < SYS_CFGREG_NUM; i++) ad714x->write(ad714x, AD714X_SYSCFG_REG + i, ad714x->hw->sys_cfg_reg[i]); for (i = 0; i < SYS_CFGREG_NUM; i++) ad714x->read(ad714x, AD714X_SYSCFG_REG + i, &data, 1); ad714x->write(ad714x, AD714X_STG_CAL_EN_REG, 0xFFF); /* clear all interrupts */ ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); } static irqreturn_t ad714x_interrupt_thread(int irq, void *data) { struct ad714x_chip *ad714x = data; int i; mutex_lock(&ad714x->mutex); ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); for (i = 0; i < ad714x->hw->button_num; i++) ad714x_button_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->slider_num; i++) ad714x_slider_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->wheel_num; i++) ad714x_wheel_state_machine(ad714x, i); for (i = 0; i < ad714x->hw->touchpad_num; i++) ad714x_touchpad_state_machine(ad714x, i); mutex_unlock(&ad714x->mutex); return IRQ_HANDLED; } struct ad714x_chip *ad714x_probe(struct device *dev, u16 bus_type, int irq, ad714x_read_t read, ad714x_write_t write) { int i; int error; struct input_dev *input; struct ad714x_platform_data *plat_data = dev_get_platdata(dev); struct ad714x_chip *ad714x; void *drv_mem; unsigned long irqflags; struct ad714x_button_drv *bt_drv; struct ad714x_slider_drv *sd_drv; struct ad714x_wheel_drv *wl_drv; struct ad714x_touchpad_drv *tp_drv; if (irq <= 0) { dev_err(dev, "IRQ not configured!\n"); error = -EINVAL; return ERR_PTR(error); } if (dev_get_platdata(dev) == NULL) { dev_err(dev, "platform data for ad714x doesn't exist\n"); error = -EINVAL; return ERR_PTR(error); } ad714x = devm_kzalloc(dev, sizeof(*ad714x) + sizeof(*ad714x->sw) + sizeof(*sd_drv) * plat_data->slider_num + sizeof(*wl_drv) * plat_data->wheel_num + sizeof(*tp_drv) * plat_data->touchpad_num + sizeof(*bt_drv) * plat_data->button_num, GFP_KERNEL); if (!ad714x) { error = -ENOMEM; return ERR_PTR(error); } ad714x->hw = plat_data; drv_mem = ad714x + 1; ad714x->sw = drv_mem; drv_mem += sizeof(*ad714x->sw); ad714x->sw->slider = sd_drv = drv_mem; drv_mem += sizeof(*sd_drv) * ad714x->hw->slider_num; ad714x->sw->wheel = wl_drv = drv_mem; drv_mem += sizeof(*wl_drv) * ad714x->hw->wheel_num; ad714x->sw->touchpad = tp_drv = drv_mem; drv_mem += sizeof(*tp_drv) * ad714x->hw->touchpad_num; ad714x->sw->button = bt_drv = drv_mem; drv_mem += sizeof(*bt_drv) * ad714x->hw->button_num; ad714x->read = read; ad714x->write = write; ad714x->irq = irq; ad714x->dev = dev; error = ad714x_hw_detect(ad714x); if (error) return ERR_PTR(error); /* initialize and request sw/hw resources */ ad714x_hw_init(ad714x); mutex_init(&ad714x->mutex); /* a slider uses one input_dev instance */ if (ad714x->hw->slider_num > 0) { struct ad714x_slider_plat *sd_plat = ad714x->hw->slider; for (i = 0; i < ad714x->hw->slider_num; i++) { input = devm_input_allocate_device(dev); if (!input) return ERR_PTR(-ENOMEM); __set_bit(EV_ABS, input->evbit); __set_bit(EV_KEY, input->evbit); __set_bit(ABS_X, input->absbit); __set_bit(BTN_TOUCH, input->keybit); input_set_abs_params(input, ABS_X, 0, sd_plat->max_coord, 0, 0); input->id.bustype = bus_type; input->id.product = ad714x->product; input->id.version = ad714x->version; input->name = "ad714x_captouch_slider"; input->dev.parent = dev; error = input_register_device(input); if (error) return ERR_PTR(error); sd_drv[i].input = input; } } /* a wheel uses one input_dev instance */ if (ad714x->hw->wheel_num > 0) { struct ad714x_wheel_plat *wl_plat = ad714x->hw->wheel; for (i = 0; i < ad714x->hw->wheel_num; i++) { input = devm_input_allocate_device(dev); if (!input) return ERR_PTR(-ENOMEM); __set_bit(EV_KEY, input->evbit); __set_bit(EV_ABS, input->evbit); __set_bit(ABS_WHEEL, input->absbit); __set_bit(BTN_TOUCH, input->keybit); input_set_abs_params(input, ABS_WHEEL, 0, wl_plat->max_coord, 0, 0); input->id.bustype = bus_type; input->id.product = ad714x->product; input->id.version = ad714x->version; input->name = "ad714x_captouch_wheel"; input->dev.parent = dev; error = input_register_device(input); if (error) return ERR_PTR(error); wl_drv[i].input = input; } } /* a touchpad uses one input_dev instance */ if (ad714x->hw->touchpad_num > 0) { struct ad714x_touchpad_plat *tp_plat = ad714x->hw->touchpad; for (i = 0; i < ad714x->hw->touchpad_num; i++) { input = devm_input_allocate_device(dev); if (!input) return ERR_PTR(-ENOMEM); __set_bit(EV_ABS, input->evbit); __set_bit(EV_KEY, input->evbit); __set_bit(ABS_X, input->absbit); __set_bit(ABS_Y, input->absbit); __set_bit(BTN_TOUCH, input->keybit); input_set_abs_params(input, ABS_X, 0, tp_plat->x_max_coord, 0, 0); input_set_abs_params(input, ABS_Y, 0, tp_plat->y_max_coord, 0, 0); input->id.bustype = bus_type; input->id.product = ad714x->product; input->id.version = ad714x->version; input->name = "ad714x_captouch_pad"; input->dev.parent = dev; error = input_register_device(input); if (error) return ERR_PTR(error); tp_drv[i].input = input; } } /* all buttons use one input node */ if (ad714x->hw->button_num > 0) { struct ad714x_button_plat *bt_plat = ad714x->hw->button; input = devm_input_allocate_device(dev); if (!input) { error = -ENOMEM; return ERR_PTR(error); } __set_bit(EV_KEY, input->evbit); for (i = 0; i < ad714x->hw->button_num; i++) { bt_drv[i].input = input; __set_bit(bt_plat[i].keycode, input->keybit); } input->id.bustype = bus_type; input->id.product = ad714x->product; input->id.version = ad714x->version; input->name = "ad714x_captouch_button"; input->dev.parent = dev; error = input_register_device(input); if (error) return ERR_PTR(error); } irqflags = plat_data->irqflags ?: IRQF_TRIGGER_FALLING; irqflags |= IRQF_ONESHOT; error = devm_request_threaded_irq(dev, ad714x->irq, NULL, ad714x_interrupt_thread, irqflags, "ad714x_captouch", ad714x); if (error) { dev_err(dev, "can't allocate irq %d\n", ad714x->irq); return ERR_PTR(error); } return ad714x; } EXPORT_SYMBOL(ad714x_probe); static int ad714x_suspend(struct device *dev) { struct ad714x_chip *ad714x = dev_get_drvdata(dev); unsigned short data; dev_dbg(ad714x->dev, "%s enter\n", __func__); mutex_lock(&ad714x->mutex); data = ad714x->hw->sys_cfg_reg[AD714X_PWR_CTRL] | 0x3; ad714x->write(ad714x, AD714X_PWR_CTRL, data); mutex_unlock(&ad714x->mutex); return 0; } static int ad714x_resume(struct device *dev) { struct ad714x_chip *ad714x = dev_get_drvdata(dev); dev_dbg(ad714x->dev, "%s enter\n", __func__); mutex_lock(&ad714x->mutex); /* resume to non-shutdown mode */ ad714x->write(ad714x, AD714X_PWR_CTRL, ad714x->hw->sys_cfg_reg[AD714X_PWR_CTRL]); /* make sure the interrupt output line is not low level after resume, * otherwise we will get no chance to enter falling-edge irq again */ ad714x->read(ad714x, STG_LOW_INT_STA_REG, &ad714x->l_state, 3); mutex_unlock(&ad714x->mutex); return 0; } EXPORT_SIMPLE_DEV_PM_OPS(ad714x_pm, ad714x_suspend, ad714x_resume); MODULE_DESCRIPTION("Analog Devices AD714X Capacitance Touch Sensor Driver"); MODULE_AUTHOR("Barry Song <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/misc/ad714x.c
// SPDX-License-Identifier: GPL-2.0-only /* * Input driver for PCAP events: * * Power key * * Headphone button * * Copyright (c) 2008,2009 Ilya Petrov <[email protected]> */ #include <linux/module.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/mfd/ezx-pcap.h> #include <linux/slab.h> struct pcap_keys { struct pcap_chip *pcap; struct input_dev *input; }; /* PCAP2 interrupts us on keypress */ static irqreturn_t pcap_keys_handler(int irq, void *_pcap_keys) { struct pcap_keys *pcap_keys = _pcap_keys; int pirq = irq_to_pcap(pcap_keys->pcap, irq); u32 pstat; ezx_pcap_read(pcap_keys->pcap, PCAP_REG_PSTAT, &pstat); pstat &= 1 << pirq; switch (pirq) { case PCAP_IRQ_ONOFF: input_report_key(pcap_keys->input, KEY_POWER, !pstat); break; case PCAP_IRQ_MIC: input_report_key(pcap_keys->input, KEY_HP, !pstat); break; } input_sync(pcap_keys->input); return IRQ_HANDLED; } static int pcap_keys_probe(struct platform_device *pdev) { int err = -ENOMEM; struct pcap_keys *pcap_keys; struct input_dev *input_dev; pcap_keys = kmalloc(sizeof(struct pcap_keys), GFP_KERNEL); if (!pcap_keys) return err; pcap_keys->pcap = dev_get_drvdata(pdev->dev.parent); input_dev = input_allocate_device(); if (!input_dev) goto fail; pcap_keys->input = input_dev; platform_set_drvdata(pdev, pcap_keys); input_dev->name = pdev->name; input_dev->phys = "pcap-keys/input0"; input_dev->id.bustype = BUS_HOST; input_dev->dev.parent = &pdev->dev; __set_bit(EV_KEY, input_dev->evbit); __set_bit(KEY_POWER, input_dev->keybit); __set_bit(KEY_HP, input_dev->keybit); err = input_register_device(input_dev); if (err) goto fail_allocate; err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys_handler, 0, "Power key", pcap_keys); if (err) goto fail_register; err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC), pcap_keys_handler, 0, "Headphone button", pcap_keys); if (err) goto fail_pwrkey; return 0; fail_pwrkey: free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys); fail_register: input_unregister_device(input_dev); goto fail; fail_allocate: input_free_device(input_dev); fail: kfree(pcap_keys); return err; } static int pcap_keys_remove(struct platform_device *pdev) { struct pcap_keys *pcap_keys = platform_get_drvdata(pdev); free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys); free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC), pcap_keys); input_unregister_device(pcap_keys->input); kfree(pcap_keys); return 0; } static struct platform_driver pcap_keys_device_driver = { .probe = pcap_keys_probe, .remove = pcap_keys_remove, .driver = { .name = "pcap-keys", } }; module_platform_driver(pcap_keys_device_driver); MODULE_DESCRIPTION("Motorola PCAP2 input events driver"); MODULE_AUTHOR("Ilya Petrov <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pcap_keys");
linux-master
drivers/input/misc/pcap_keys.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Generic GPIO beeper driver * * Copyright (C) 2013-2014 Alexander Shiyan <[email protected]> */ #include <linux/input.h> #include <linux/module.h> #include <linux/gpio/consumer.h> #include <linux/of.h> #include <linux/workqueue.h> #include <linux/platform_device.h> #define BEEPER_MODNAME "gpio-beeper" struct gpio_beeper { struct work_struct work; struct gpio_desc *desc; bool beeping; }; static void gpio_beeper_toggle(struct gpio_beeper *beep, bool on) { gpiod_set_value_cansleep(beep->desc, on); } static void gpio_beeper_work(struct work_struct *work) { struct gpio_beeper *beep = container_of(work, struct gpio_beeper, work); gpio_beeper_toggle(beep, beep->beeping); } static int gpio_beeper_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct gpio_beeper *beep = input_get_drvdata(dev); if (type != EV_SND || code != SND_BELL) return -ENOTSUPP; if (value < 0) return -EINVAL; beep->beeping = value; /* Schedule work to actually turn the beeper on or off */ schedule_work(&beep->work); return 0; } static void gpio_beeper_close(struct input_dev *input) { struct gpio_beeper *beep = input_get_drvdata(input); cancel_work_sync(&beep->work); gpio_beeper_toggle(beep, false); } static int gpio_beeper_probe(struct platform_device *pdev) { struct gpio_beeper *beep; struct input_dev *input; beep = devm_kzalloc(&pdev->dev, sizeof(*beep), GFP_KERNEL); if (!beep) return -ENOMEM; beep->desc = devm_gpiod_get(&pdev->dev, NULL, GPIOD_OUT_LOW); if (IS_ERR(beep->desc)) return PTR_ERR(beep->desc); input = devm_input_allocate_device(&pdev->dev); if (!input) return -ENOMEM; INIT_WORK(&beep->work, gpio_beeper_work); input->name = pdev->name; input->id.bustype = BUS_HOST; input->id.vendor = 0x0001; input->id.product = 0x0001; input->id.version = 0x0100; input->close = gpio_beeper_close; input->event = gpio_beeper_event; input_set_capability(input, EV_SND, SND_BELL); input_set_drvdata(input, beep); return input_register_device(input); } #ifdef CONFIG_OF static const struct of_device_id gpio_beeper_of_match[] = { { .compatible = BEEPER_MODNAME, }, { } }; MODULE_DEVICE_TABLE(of, gpio_beeper_of_match); #endif static struct platform_driver gpio_beeper_platform_driver = { .driver = { .name = BEEPER_MODNAME, .of_match_table = of_match_ptr(gpio_beeper_of_match), }, .probe = gpio_beeper_probe, }; module_platform_driver(gpio_beeper_platform_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alexander Shiyan <[email protected]>"); MODULE_DESCRIPTION("Generic GPIO beeper driver");
linux-master
drivers/input/misc/gpio-beeper.c
/* * Marvell 88PM80x ONKEY driver * * Copyright (C) 2012 Marvell International Ltd. * Haojian Zhuang <[email protected]> * Qiao Zhou <[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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/mfd/88pm80x.h> #include <linux/regmap.h> #include <linux/slab.h> #define PM800_LONG_ONKEY_EN (1 << 0) #define PM800_LONG_KEY_DELAY (8) /* 1 .. 16 seconds */ #define PM800_LONKEY_PRESS_TIME ((PM800_LONG_KEY_DELAY-1) << 4) #define PM800_LONKEY_PRESS_TIME_MASK (0xF0) #define PM800_SW_PDOWN (1 << 5) struct pm80x_onkey_info { struct input_dev *idev; struct pm80x_chip *pm80x; struct regmap *map; int irq; }; /* 88PM80x gives us an interrupt when ONKEY is held */ static irqreturn_t pm80x_onkey_handler(int irq, void *data) { struct pm80x_onkey_info *info = data; int ret = 0; unsigned int val; ret = regmap_read(info->map, PM800_STATUS_1, &val); if (ret < 0) { dev_err(info->idev->dev.parent, "failed to read status: %d\n", ret); return IRQ_NONE; } val &= PM800_ONKEY_STS1; input_report_key(info->idev, KEY_POWER, val); input_sync(info->idev); return IRQ_HANDLED; } static SIMPLE_DEV_PM_OPS(pm80x_onkey_pm_ops, pm80x_dev_suspend, pm80x_dev_resume); static int pm80x_onkey_probe(struct platform_device *pdev) { struct pm80x_chip *chip = dev_get_drvdata(pdev->dev.parent); struct pm80x_onkey_info *info; int err; info = kzalloc(sizeof(struct pm80x_onkey_info), GFP_KERNEL); if (!info) return -ENOMEM; info->pm80x = chip; info->irq = platform_get_irq(pdev, 0); if (info->irq < 0) { err = -EINVAL; goto out; } info->map = info->pm80x->regmap; if (!info->map) { dev_err(&pdev->dev, "no regmap!\n"); err = -EINVAL; goto out; } info->idev = input_allocate_device(); if (!info->idev) { dev_err(&pdev->dev, "Failed to allocate input dev\n"); err = -ENOMEM; goto out; } info->idev->name = "88pm80x_on"; info->idev->phys = "88pm80x_on/input0"; info->idev->id.bustype = BUS_I2C; info->idev->dev.parent = &pdev->dev; info->idev->evbit[0] = BIT_MASK(EV_KEY); __set_bit(KEY_POWER, info->idev->keybit); err = pm80x_request_irq(info->pm80x, info->irq, pm80x_onkey_handler, IRQF_ONESHOT, "onkey", info); if (err < 0) { dev_err(&pdev->dev, "Failed to request IRQ: #%d: %d\n", info->irq, err); goto out_reg; } err = input_register_device(info->idev); if (err) { dev_err(&pdev->dev, "Can't register input device: %d\n", err); goto out_irq; } platform_set_drvdata(pdev, info); /* Enable long onkey detection */ regmap_update_bits(info->map, PM800_RTC_MISC4, PM800_LONG_ONKEY_EN, PM800_LONG_ONKEY_EN); /* Set 8-second interval */ regmap_update_bits(info->map, PM800_RTC_MISC3, PM800_LONKEY_PRESS_TIME_MASK, PM800_LONKEY_PRESS_TIME); device_init_wakeup(&pdev->dev, 1); return 0; out_irq: pm80x_free_irq(info->pm80x, info->irq, info); out_reg: input_free_device(info->idev); out: kfree(info); return err; } static int pm80x_onkey_remove(struct platform_device *pdev) { struct pm80x_onkey_info *info = platform_get_drvdata(pdev); pm80x_free_irq(info->pm80x, info->irq, info); input_unregister_device(info->idev); kfree(info); return 0; } static struct platform_driver pm80x_onkey_driver = { .driver = { .name = "88pm80x-onkey", .pm = &pm80x_onkey_pm_ops, }, .probe = pm80x_onkey_probe, .remove = pm80x_onkey_remove, }; module_platform_driver(pm80x_onkey_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Marvell 88PM80x ONKEY driver"); MODULE_AUTHOR("Qiao Zhou <[email protected]>"); MODULE_ALIAS("platform:88pm80x-onkey");
linux-master
drivers/input/misc/88pm80x_onkey.c
/* * axp20x power button driver. * * Copyright (C) 2013 Carlo Caione <[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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/acpi.h> #include <linux/errno.h> #include <linux/irq.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/mfd/axp20x.h> #include <linux/module.h> #include <linux/platform_data/x86/soc.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/slab.h> #define AXP20X_PEK_STARTUP_MASK (0xc0) #define AXP20X_PEK_SHUTDOWN_MASK (0x03) struct axp20x_info { const struct axp20x_time *startup_time; unsigned int startup_mask; const struct axp20x_time *shutdown_time; unsigned int shutdown_mask; }; struct axp20x_pek { struct axp20x_dev *axp20x; struct input_dev *input; struct axp20x_info *info; int irq_dbr; int irq_dbf; }; struct axp20x_time { unsigned int time; unsigned int idx; }; static const struct axp20x_time startup_time[] = { { .time = 128, .idx = 0 }, { .time = 1000, .idx = 2 }, { .time = 3000, .idx = 1 }, { .time = 2000, .idx = 3 }, }; static const struct axp20x_time axp221_startup_time[] = { { .time = 128, .idx = 0 }, { .time = 1000, .idx = 1 }, { .time = 2000, .idx = 2 }, { .time = 3000, .idx = 3 }, }; static const struct axp20x_time shutdown_time[] = { { .time = 4000, .idx = 0 }, { .time = 6000, .idx = 1 }, { .time = 8000, .idx = 2 }, { .time = 10000, .idx = 3 }, }; static const struct axp20x_info axp20x_info = { .startup_time = startup_time, .startup_mask = AXP20X_PEK_STARTUP_MASK, .shutdown_time = shutdown_time, .shutdown_mask = AXP20X_PEK_SHUTDOWN_MASK, }; static const struct axp20x_info axp221_info = { .startup_time = axp221_startup_time, .startup_mask = AXP20X_PEK_STARTUP_MASK, .shutdown_time = shutdown_time, .shutdown_mask = AXP20X_PEK_SHUTDOWN_MASK, }; static ssize_t axp20x_show_attr(struct device *dev, const struct axp20x_time *time, unsigned int mask, char *buf) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); unsigned int val; int ret, i; ret = regmap_read(axp20x_pek->axp20x->regmap, AXP20X_PEK_KEY, &val); if (ret != 0) return ret; val &= mask; val >>= ffs(mask) - 1; for (i = 0; i < 4; i++) if (val == time[i].idx) val = time[i].time; return sprintf(buf, "%u\n", val); } static ssize_t axp20x_show_attr_startup(struct device *dev, struct device_attribute *attr, char *buf) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); return axp20x_show_attr(dev, axp20x_pek->info->startup_time, axp20x_pek->info->startup_mask, buf); } static ssize_t axp20x_show_attr_shutdown(struct device *dev, struct device_attribute *attr, char *buf) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); return axp20x_show_attr(dev, axp20x_pek->info->shutdown_time, axp20x_pek->info->shutdown_mask, buf); } static ssize_t axp20x_store_attr(struct device *dev, const struct axp20x_time *time, unsigned int mask, const char *buf, size_t count) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); char val_str[20]; size_t len; int ret, i; unsigned int val, idx = 0; unsigned int best_err = UINT_MAX; val_str[sizeof(val_str) - 1] = '\0'; strncpy(val_str, buf, sizeof(val_str) - 1); len = strlen(val_str); if (len && val_str[len - 1] == '\n') val_str[len - 1] = '\0'; ret = kstrtouint(val_str, 10, &val); if (ret) return ret; for (i = 3; i >= 0; i--) { unsigned int err; err = abs(time[i].time - val); if (err < best_err) { best_err = err; idx = time[i].idx; } if (!err) break; } idx <<= ffs(mask) - 1; ret = regmap_update_bits(axp20x_pek->axp20x->regmap, AXP20X_PEK_KEY, mask, idx); if (ret != 0) return -EINVAL; return count; } static ssize_t axp20x_store_attr_startup(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); return axp20x_store_attr(dev, axp20x_pek->info->startup_time, axp20x_pek->info->startup_mask, buf, count); } static ssize_t axp20x_store_attr_shutdown(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); return axp20x_store_attr(dev, axp20x_pek->info->shutdown_time, axp20x_pek->info->shutdown_mask, buf, count); } static DEVICE_ATTR(startup, 0644, axp20x_show_attr_startup, axp20x_store_attr_startup); static DEVICE_ATTR(shutdown, 0644, axp20x_show_attr_shutdown, axp20x_store_attr_shutdown); static struct attribute *axp20x_attrs[] = { &dev_attr_startup.attr, &dev_attr_shutdown.attr, NULL, }; ATTRIBUTE_GROUPS(axp20x); static irqreturn_t axp20x_pek_irq(int irq, void *pwr) { struct input_dev *idev = pwr; struct axp20x_pek *axp20x_pek = input_get_drvdata(idev); /* * The power-button is connected to ground so a falling edge (dbf) * means it is pressed. */ if (irq == axp20x_pek->irq_dbf) input_report_key(idev, KEY_POWER, true); else if (irq == axp20x_pek->irq_dbr) input_report_key(idev, KEY_POWER, false); input_sync(idev); return IRQ_HANDLED; } static int axp20x_pek_probe_input_device(struct axp20x_pek *axp20x_pek, struct platform_device *pdev) { struct axp20x_dev *axp20x = axp20x_pek->axp20x; struct input_dev *idev; int error; axp20x_pek->irq_dbr = platform_get_irq_byname(pdev, "PEK_DBR"); if (axp20x_pek->irq_dbr < 0) return axp20x_pek->irq_dbr; axp20x_pek->irq_dbr = regmap_irq_get_virq(axp20x->regmap_irqc, axp20x_pek->irq_dbr); axp20x_pek->irq_dbf = platform_get_irq_byname(pdev, "PEK_DBF"); if (axp20x_pek->irq_dbf < 0) return axp20x_pek->irq_dbf; axp20x_pek->irq_dbf = regmap_irq_get_virq(axp20x->regmap_irqc, axp20x_pek->irq_dbf); axp20x_pek->input = devm_input_allocate_device(&pdev->dev); if (!axp20x_pek->input) return -ENOMEM; idev = axp20x_pek->input; idev->name = "axp20x-pek"; idev->phys = "m1kbd/input2"; idev->dev.parent = &pdev->dev; input_set_capability(idev, EV_KEY, KEY_POWER); input_set_drvdata(idev, axp20x_pek); error = devm_request_any_context_irq(&pdev->dev, axp20x_pek->irq_dbr, axp20x_pek_irq, 0, "axp20x-pek-dbr", idev); if (error < 0) { dev_err(&pdev->dev, "Failed to request dbr IRQ#%d: %d\n", axp20x_pek->irq_dbr, error); return error; } error = devm_request_any_context_irq(&pdev->dev, axp20x_pek->irq_dbf, axp20x_pek_irq, 0, "axp20x-pek-dbf", idev); if (error < 0) { dev_err(&pdev->dev, "Failed to request dbf IRQ#%d: %d\n", axp20x_pek->irq_dbf, error); return error; } error = input_register_device(idev); if (error) { dev_err(&pdev->dev, "Can't register input device: %d\n", error); return error; } device_init_wakeup(&pdev->dev, true); return 0; } static bool axp20x_pek_should_register_input(struct axp20x_pek *axp20x_pek) { if (IS_ENABLED(CONFIG_INPUT_SOC_BUTTON_ARRAY) && axp20x_pek->axp20x->variant == AXP288_ID) { /* * On Cherry Trail platforms (hrv == 3), do not register the * input device if there is an "INTCFD9" or "ACPI0011" gpio * button ACPI device, as that handles the power button too, * and otherwise we end up reporting all presses twice. */ if (soc_intel_is_cht() && (acpi_dev_present("INTCFD9", NULL, -1) || acpi_dev_present("ACPI0011", NULL, -1))) return false; } return true; } static int axp20x_pek_probe(struct platform_device *pdev) { struct axp20x_pek *axp20x_pek; const struct platform_device_id *match = platform_get_device_id(pdev); int error; if (!match) { dev_err(&pdev->dev, "Failed to get platform_device_id\n"); return -EINVAL; } axp20x_pek = devm_kzalloc(&pdev->dev, sizeof(struct axp20x_pek), GFP_KERNEL); if (!axp20x_pek) return -ENOMEM; axp20x_pek->axp20x = dev_get_drvdata(pdev->dev.parent); if (axp20x_pek_should_register_input(axp20x_pek)) { error = axp20x_pek_probe_input_device(axp20x_pek, pdev); if (error) return error; } axp20x_pek->info = (struct axp20x_info *)match->driver_data; platform_set_drvdata(pdev, axp20x_pek); return 0; } static int axp20x_pek_suspend(struct device *dev) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); /* * As nested threaded IRQs are not automatically disabled during * suspend, we must explicitly disable non-wakeup IRQs. */ if (device_may_wakeup(dev)) { enable_irq_wake(axp20x_pek->irq_dbf); enable_irq_wake(axp20x_pek->irq_dbr); } else { disable_irq(axp20x_pek->irq_dbf); disable_irq(axp20x_pek->irq_dbr); } return 0; } static int axp20x_pek_resume(struct device *dev) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); if (device_may_wakeup(dev)) { disable_irq_wake(axp20x_pek->irq_dbf); disable_irq_wake(axp20x_pek->irq_dbr); } else { enable_irq(axp20x_pek->irq_dbf); enable_irq(axp20x_pek->irq_dbr); } return 0; } static int __maybe_unused axp20x_pek_resume_noirq(struct device *dev) { struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev); if (axp20x_pek->axp20x->variant != AXP288_ID) return 0; /* * Clear interrupts from button presses during suspend, to avoid * a wakeup power-button press getting reported to userspace. */ regmap_write(axp20x_pek->axp20x->regmap, AXP20X_IRQ1_STATE + AXP288_IRQ_POKN / 8, BIT(AXP288_IRQ_POKN % 8)); return 0; } static const struct dev_pm_ops axp20x_pek_pm_ops = { SYSTEM_SLEEP_PM_OPS(axp20x_pek_suspend, axp20x_pek_resume) .resume_noirq = pm_sleep_ptr(axp20x_pek_resume_noirq), }; static const struct platform_device_id axp_pek_id_match[] = { { .name = "axp20x-pek", .driver_data = (kernel_ulong_t)&axp20x_info, }, { .name = "axp221-pek", .driver_data = (kernel_ulong_t)&axp221_info, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(platform, axp_pek_id_match); static struct platform_driver axp20x_pek_driver = { .probe = axp20x_pek_probe, .id_table = axp_pek_id_match, .driver = { .name = "axp20x-pek", .pm = pm_sleep_ptr(&axp20x_pek_pm_ops), .dev_groups = axp20x_groups, }, }; module_platform_driver(axp20x_pek_driver); MODULE_DESCRIPTION("axp20x Power Button"); MODULE_AUTHOR("Carlo Caione <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/misc/axp20x-pek.c
// SPDX-License-Identifier: GPL-2.0 // // Copyright (C) 2018 BayLibre SAS // Author: Bartosz Golaszewski <[email protected]> // // ONKEY driver for MAXIM 77650/77651 charger/power-supply. #include <linux/i2c.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/mfd/max77650.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/regmap.h> #define MAX77650_ONKEY_MODE_MASK BIT(3) #define MAX77650_ONKEY_MODE_PUSH 0x00 #define MAX77650_ONKEY_MODE_SLIDE BIT(3) struct max77650_onkey { struct input_dev *input; unsigned int code; }; static irqreturn_t max77650_onkey_falling(int irq, void *data) { struct max77650_onkey *onkey = data; input_report_key(onkey->input, onkey->code, 0); input_sync(onkey->input); return IRQ_HANDLED; } static irqreturn_t max77650_onkey_rising(int irq, void *data) { struct max77650_onkey *onkey = data; input_report_key(onkey->input, onkey->code, 1); input_sync(onkey->input); return IRQ_HANDLED; } static int max77650_onkey_probe(struct platform_device *pdev) { int irq_r, irq_f, error, mode; struct max77650_onkey *onkey; struct device *dev, *parent; struct regmap *map; unsigned int type; dev = &pdev->dev; parent = dev->parent; map = dev_get_regmap(parent, NULL); if (!map) return -ENODEV; onkey = devm_kzalloc(dev, sizeof(*onkey), GFP_KERNEL); if (!onkey) return -ENOMEM; error = device_property_read_u32(dev, "linux,code", &onkey->code); if (error) onkey->code = KEY_POWER; if (device_property_read_bool(dev, "maxim,onkey-slide")) { mode = MAX77650_ONKEY_MODE_SLIDE; type = EV_SW; } else { mode = MAX77650_ONKEY_MODE_PUSH; type = EV_KEY; } error = regmap_update_bits(map, MAX77650_REG_CNFG_GLBL, MAX77650_ONKEY_MODE_MASK, mode); if (error) return error; irq_f = platform_get_irq_byname(pdev, "nEN_F"); if (irq_f < 0) return irq_f; irq_r = platform_get_irq_byname(pdev, "nEN_R"); if (irq_r < 0) return irq_r; onkey->input = devm_input_allocate_device(dev); if (!onkey->input) return -ENOMEM; onkey->input->name = "max77650_onkey"; onkey->input->phys = "max77650_onkey/input0"; onkey->input->id.bustype = BUS_I2C; input_set_capability(onkey->input, type, onkey->code); error = devm_request_any_context_irq(dev, irq_f, max77650_onkey_falling, IRQF_ONESHOT, "onkey-down", onkey); if (error < 0) return error; error = devm_request_any_context_irq(dev, irq_r, max77650_onkey_rising, IRQF_ONESHOT, "onkey-up", onkey); if (error < 0) return error; return input_register_device(onkey->input); } static const struct of_device_id max77650_onkey_of_match[] = { { .compatible = "maxim,max77650-onkey" }, { } }; MODULE_DEVICE_TABLE(of, max77650_onkey_of_match); static struct platform_driver max77650_onkey_driver = { .driver = { .name = "max77650-onkey", .of_match_table = max77650_onkey_of_match, }, .probe = max77650_onkey_probe, }; module_platform_driver(max77650_onkey_driver); MODULE_DESCRIPTION("MAXIM 77650/77651 ONKEY driver"); MODULE_AUTHOR("Bartosz Golaszewski <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:max77650-onkey");
linux-master
drivers/input/misc/max77650-onkey.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Azoteq IQS7222A/B/C/D Capacitive Touch Controller * * Copyright (C) 2022 Jeff LaBundy <[email protected]> */ #include <linux/bits.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/ktime.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/property.h> #include <linux/slab.h> #include <asm/unaligned.h> #define IQS7222_PROD_NUM 0x00 #define IQS7222_PROD_NUM_A 840 #define IQS7222_PROD_NUM_B 698 #define IQS7222_PROD_NUM_C 863 #define IQS7222_PROD_NUM_D 1046 #define IQS7222_SYS_STATUS 0x10 #define IQS7222_SYS_STATUS_RESET BIT(3) #define IQS7222_SYS_STATUS_ATI_ERROR BIT(1) #define IQS7222_SYS_STATUS_ATI_ACTIVE BIT(0) #define IQS7222_CHAN_SETUP_0_REF_MODE_MASK GENMASK(15, 14) #define IQS7222_CHAN_SETUP_0_REF_MODE_FOLLOW BIT(15) #define IQS7222_CHAN_SETUP_0_REF_MODE_REF BIT(14) #define IQS7222_CHAN_SETUP_0_CHAN_EN BIT(8) #define IQS7222_SLDR_SETUP_0_CHAN_CNT_MASK GENMASK(2, 0) #define IQS7222_SLDR_SETUP_2_RES_MASK GENMASK(15, 8) #define IQS7222_SLDR_SETUP_2_RES_SHIFT 8 #define IQS7222_SLDR_SETUP_2_TOP_SPEED_MASK GENMASK(7, 0) #define IQS7222_GPIO_SETUP_0_GPIO_EN BIT(0) #define IQS7222_SYS_SETUP 0xD0 #define IQS7222_SYS_SETUP_INTF_MODE_MASK GENMASK(7, 6) #define IQS7222_SYS_SETUP_INTF_MODE_TOUCH BIT(7) #define IQS7222_SYS_SETUP_INTF_MODE_EVENT BIT(6) #define IQS7222_SYS_SETUP_PWR_MODE_MASK GENMASK(5, 4) #define IQS7222_SYS_SETUP_PWR_MODE_AUTO IQS7222_SYS_SETUP_PWR_MODE_MASK #define IQS7222_SYS_SETUP_REDO_ATI BIT(2) #define IQS7222_SYS_SETUP_ACK_RESET BIT(0) #define IQS7222_EVENT_MASK_ATI BIT(12) #define IQS7222_EVENT_MASK_SLDR BIT(10) #define IQS7222_EVENT_MASK_TPAD IQS7222_EVENT_MASK_SLDR #define IQS7222_EVENT_MASK_TOUCH BIT(1) #define IQS7222_EVENT_MASK_PROX BIT(0) #define IQS7222_COMMS_HOLD BIT(0) #define IQS7222_COMMS_ERROR 0xEEEE #define IQS7222_COMMS_RETRY_MS 50 #define IQS7222_COMMS_TIMEOUT_MS 100 #define IQS7222_RESET_TIMEOUT_MS 250 #define IQS7222_ATI_TIMEOUT_MS 2000 #define IQS7222_MAX_COLS_STAT 8 #define IQS7222_MAX_COLS_CYCLE 3 #define IQS7222_MAX_COLS_GLBL 3 #define IQS7222_MAX_COLS_BTN 3 #define IQS7222_MAX_COLS_CHAN 6 #define IQS7222_MAX_COLS_FILT 2 #define IQS7222_MAX_COLS_SLDR 11 #define IQS7222_MAX_COLS_TPAD 24 #define IQS7222_MAX_COLS_GPIO 3 #define IQS7222_MAX_COLS_SYS 13 #define IQS7222_MAX_CHAN 20 #define IQS7222_MAX_SLDR 2 #define IQS7222_NUM_RETRIES 5 #define IQS7222_REG_OFFSET 0x100 enum iqs7222_reg_key_id { IQS7222_REG_KEY_NONE, IQS7222_REG_KEY_PROX, IQS7222_REG_KEY_TOUCH, IQS7222_REG_KEY_DEBOUNCE, IQS7222_REG_KEY_TAP, IQS7222_REG_KEY_TAP_LEGACY, IQS7222_REG_KEY_AXIAL, IQS7222_REG_KEY_AXIAL_LEGACY, IQS7222_REG_KEY_WHEEL, IQS7222_REG_KEY_NO_WHEEL, IQS7222_REG_KEY_RESERVED }; enum iqs7222_reg_grp_id { IQS7222_REG_GRP_STAT, IQS7222_REG_GRP_FILT, IQS7222_REG_GRP_CYCLE, IQS7222_REG_GRP_GLBL, IQS7222_REG_GRP_BTN, IQS7222_REG_GRP_CHAN, IQS7222_REG_GRP_SLDR, IQS7222_REG_GRP_TPAD, IQS7222_REG_GRP_GPIO, IQS7222_REG_GRP_SYS, IQS7222_NUM_REG_GRPS }; static const char * const iqs7222_reg_grp_names[IQS7222_NUM_REG_GRPS] = { [IQS7222_REG_GRP_CYCLE] = "cycle-%d", [IQS7222_REG_GRP_CHAN] = "channel-%d", [IQS7222_REG_GRP_SLDR] = "slider-%d", [IQS7222_REG_GRP_TPAD] = "trackpad", [IQS7222_REG_GRP_GPIO] = "gpio-%d", }; static const unsigned int iqs7222_max_cols[IQS7222_NUM_REG_GRPS] = { [IQS7222_REG_GRP_STAT] = IQS7222_MAX_COLS_STAT, [IQS7222_REG_GRP_CYCLE] = IQS7222_MAX_COLS_CYCLE, [IQS7222_REG_GRP_GLBL] = IQS7222_MAX_COLS_GLBL, [IQS7222_REG_GRP_BTN] = IQS7222_MAX_COLS_BTN, [IQS7222_REG_GRP_CHAN] = IQS7222_MAX_COLS_CHAN, [IQS7222_REG_GRP_FILT] = IQS7222_MAX_COLS_FILT, [IQS7222_REG_GRP_SLDR] = IQS7222_MAX_COLS_SLDR, [IQS7222_REG_GRP_TPAD] = IQS7222_MAX_COLS_TPAD, [IQS7222_REG_GRP_GPIO] = IQS7222_MAX_COLS_GPIO, [IQS7222_REG_GRP_SYS] = IQS7222_MAX_COLS_SYS, }; static const unsigned int iqs7222_gpio_links[] = { 2, 5, 6, }; struct iqs7222_event_desc { const char *name; u16 link; u16 mask; u16 val; u16 strict; u16 enable; enum iqs7222_reg_key_id reg_key; }; static const struct iqs7222_event_desc iqs7222_kp_events[] = { { .name = "event-prox", .enable = IQS7222_EVENT_MASK_PROX, .reg_key = IQS7222_REG_KEY_PROX, }, { .name = "event-touch", .enable = IQS7222_EVENT_MASK_TOUCH, .reg_key = IQS7222_REG_KEY_TOUCH, }, }; static const struct iqs7222_event_desc iqs7222_sl_events[] = { { .name = "event-press", }, { .name = "event-tap", .mask = BIT(0), .val = BIT(0), .enable = BIT(0), .reg_key = IQS7222_REG_KEY_TAP, }, { .name = "event-swipe-pos", .mask = BIT(5) | BIT(1), .val = BIT(1), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-swipe-neg", .mask = BIT(5) | BIT(1), .val = BIT(5) | BIT(1), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-pos", .mask = BIT(5) | BIT(2), .val = BIT(2), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-neg", .mask = BIT(5) | BIT(2), .val = BIT(5) | BIT(2), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, }; static const struct iqs7222_event_desc iqs7222_tp_events[] = { { .name = "event-press", .link = BIT(7), }, { .name = "event-tap", .link = BIT(0), .mask = BIT(0), .val = BIT(0), .enable = BIT(0), .reg_key = IQS7222_REG_KEY_TAP, }, { .name = "event-swipe-x-pos", .link = BIT(2), .mask = BIT(2) | BIT(1), .val = BIT(2), .strict = BIT(4), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-swipe-y-pos", .link = BIT(3), .mask = BIT(3) | BIT(1), .val = BIT(3), .strict = BIT(3), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-swipe-x-neg", .link = BIT(4), .mask = BIT(4) | BIT(1), .val = BIT(4), .strict = BIT(4), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-swipe-y-neg", .link = BIT(5), .mask = BIT(5) | BIT(1), .val = BIT(5), .strict = BIT(3), .enable = BIT(1), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-x-pos", .link = BIT(2), .mask = BIT(2) | BIT(1), .val = BIT(2) | BIT(1), .strict = BIT(4), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-y-pos", .link = BIT(3), .mask = BIT(3) | BIT(1), .val = BIT(3) | BIT(1), .strict = BIT(3), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-x-neg", .link = BIT(4), .mask = BIT(4) | BIT(1), .val = BIT(4) | BIT(1), .strict = BIT(4), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, { .name = "event-flick-y-neg", .link = BIT(5), .mask = BIT(5) | BIT(1), .val = BIT(5) | BIT(1), .strict = BIT(3), .enable = BIT(2), .reg_key = IQS7222_REG_KEY_AXIAL, }, }; struct iqs7222_reg_grp_desc { u16 base; int num_row; int num_col; }; struct iqs7222_dev_desc { u16 prod_num; u16 fw_major; u16 fw_minor; u16 sldr_res; u16 touch_link; u16 wheel_enable; int allow_offset; int event_offset; int comms_offset; bool legacy_gesture; struct iqs7222_reg_grp_desc reg_grps[IQS7222_NUM_REG_GRPS]; }; static const struct iqs7222_dev_desc iqs7222_devs[] = { { .prod_num = IQS7222_PROD_NUM_A, .fw_major = 1, .fw_minor = 13, .sldr_res = U8_MAX * 16, .touch_link = 1768, .allow_offset = 9, .event_offset = 10, .comms_offset = 12, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 8, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 7, .num_col = 3, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8700, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 12, .num_col = 3, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xA000, .num_row = 12, .num_col = 6, }, [IQS7222_REG_GRP_FILT] = { .base = 0xAC00, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SLDR] = { .base = 0xB000, .num_row = 2, .num_col = 11, }, [IQS7222_REG_GRP_GPIO] = { .base = 0xC000, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 13, }, }, }, { .prod_num = IQS7222_PROD_NUM_A, .fw_major = 1, .fw_minor = 12, .sldr_res = U8_MAX * 16, .touch_link = 1768, .allow_offset = 9, .event_offset = 10, .comms_offset = 12, .legacy_gesture = true, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 8, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 7, .num_col = 3, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8700, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 12, .num_col = 3, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xA000, .num_row = 12, .num_col = 6, }, [IQS7222_REG_GRP_FILT] = { .base = 0xAC00, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SLDR] = { .base = 0xB000, .num_row = 2, .num_col = 11, }, [IQS7222_REG_GRP_GPIO] = { .base = 0xC000, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 13, }, }, }, { .prod_num = IQS7222_PROD_NUM_B, .fw_major = 1, .fw_minor = 43, .event_offset = 10, .comms_offset = 11, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 6, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 10, .num_col = 2, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8A00, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 20, .num_col = 2, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xB000, .num_row = 20, .num_col = 4, }, [IQS7222_REG_GRP_FILT] = { .base = 0xC400, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 13, }, }, }, { .prod_num = IQS7222_PROD_NUM_B, .fw_major = 1, .fw_minor = 27, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 6, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 10, .num_col = 2, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8A00, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 20, .num_col = 2, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xB000, .num_row = 20, .num_col = 4, }, [IQS7222_REG_GRP_FILT] = { .base = 0xC400, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 10, }, }, }, { .prod_num = IQS7222_PROD_NUM_C, .fw_major = 2, .fw_minor = 6, .sldr_res = U16_MAX, .touch_link = 1686, .wheel_enable = BIT(3), .event_offset = 9, .comms_offset = 10, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 6, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 5, .num_col = 3, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8500, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 10, .num_col = 3, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xA000, .num_row = 10, .num_col = 6, }, [IQS7222_REG_GRP_FILT] = { .base = 0xAA00, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SLDR] = { .base = 0xB000, .num_row = 2, .num_col = 10, }, [IQS7222_REG_GRP_GPIO] = { .base = 0xC000, .num_row = 3, .num_col = 3, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 12, }, }, }, { .prod_num = IQS7222_PROD_NUM_C, .fw_major = 1, .fw_minor = 13, .sldr_res = U16_MAX, .touch_link = 1674, .wheel_enable = BIT(3), .event_offset = 9, .comms_offset = 10, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 6, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 5, .num_col = 3, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8500, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 10, .num_col = 3, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xA000, .num_row = 10, .num_col = 6, }, [IQS7222_REG_GRP_FILT] = { .base = 0xAA00, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_SLDR] = { .base = 0xB000, .num_row = 2, .num_col = 10, }, [IQS7222_REG_GRP_GPIO] = { .base = 0xC000, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 11, }, }, }, { .prod_num = IQS7222_PROD_NUM_D, .fw_major = 0, .fw_minor = 37, .touch_link = 1770, .allow_offset = 9, .event_offset = 10, .comms_offset = 11, .reg_grps = { [IQS7222_REG_GRP_STAT] = { .base = IQS7222_SYS_STATUS, .num_row = 1, .num_col = 7, }, [IQS7222_REG_GRP_CYCLE] = { .base = 0x8000, .num_row = 7, .num_col = 2, }, [IQS7222_REG_GRP_GLBL] = { .base = 0x8700, .num_row = 1, .num_col = 3, }, [IQS7222_REG_GRP_BTN] = { .base = 0x9000, .num_row = 14, .num_col = 3, }, [IQS7222_REG_GRP_CHAN] = { .base = 0xA000, .num_row = 14, .num_col = 4, }, [IQS7222_REG_GRP_FILT] = { .base = 0xAE00, .num_row = 1, .num_col = 2, }, [IQS7222_REG_GRP_TPAD] = { .base = 0xB000, .num_row = 1, .num_col = 24, }, [IQS7222_REG_GRP_GPIO] = { .base = 0xC000, .num_row = 3, .num_col = 3, }, [IQS7222_REG_GRP_SYS] = { .base = IQS7222_SYS_SETUP, .num_row = 1, .num_col = 12, }, }, }, }; struct iqs7222_prop_desc { const char *name; enum iqs7222_reg_grp_id reg_grp; enum iqs7222_reg_key_id reg_key; int reg_offset; int reg_shift; int reg_width; int val_pitch; int val_min; int val_max; bool invert; const char *label; }; static const struct iqs7222_prop_desc iqs7222_props[] = { { .name = "azoteq,conv-period", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 0, .reg_shift = 8, .reg_width = 8, .label = "conversion period", }, { .name = "azoteq,conv-frac", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 0, .reg_shift = 0, .reg_width = 8, .label = "conversion frequency fractional divider", }, { .name = "azoteq,rx-float-inactive", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 1, .reg_shift = 6, .reg_width = 1, .invert = true, }, { .name = "azoteq,dead-time-enable", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 1, .reg_shift = 5, .reg_width = 1, }, { .name = "azoteq,tx-freq-fosc", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 1, .reg_shift = 4, .reg_width = 1, }, { .name = "azoteq,vbias-enable", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 1, .reg_shift = 3, .reg_width = 1, }, { .name = "azoteq,sense-mode", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 1, .reg_shift = 0, .reg_width = 3, .val_max = 3, .label = "sensing mode", }, { .name = "azoteq,iref-enable", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 2, .reg_shift = 10, .reg_width = 1, }, { .name = "azoteq,iref-level", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 2, .reg_shift = 4, .reg_width = 4, .label = "current reference level", }, { .name = "azoteq,iref-trim", .reg_grp = IQS7222_REG_GRP_CYCLE, .reg_offset = 2, .reg_shift = 0, .reg_width = 4, .label = "current reference trim", }, { .name = "azoteq,max-counts", .reg_grp = IQS7222_REG_GRP_GLBL, .reg_offset = 0, .reg_shift = 13, .reg_width = 2, .label = "maximum counts", }, { .name = "azoteq,auto-mode", .reg_grp = IQS7222_REG_GRP_GLBL, .reg_offset = 0, .reg_shift = 2, .reg_width = 2, .label = "number of conversions", }, { .name = "azoteq,ati-frac-div-fine", .reg_grp = IQS7222_REG_GRP_GLBL, .reg_offset = 1, .reg_shift = 9, .reg_width = 5, .label = "ATI fine fractional divider", }, { .name = "azoteq,ati-frac-div-coarse", .reg_grp = IQS7222_REG_GRP_GLBL, .reg_offset = 1, .reg_shift = 0, .reg_width = 5, .label = "ATI coarse fractional divider", }, { .name = "azoteq,ati-comp-select", .reg_grp = IQS7222_REG_GRP_GLBL, .reg_offset = 2, .reg_shift = 0, .reg_width = 10, .label = "ATI compensation selection", }, { .name = "azoteq,ati-band", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 12, .reg_width = 2, .label = "ATI band", }, { .name = "azoteq,global-halt", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 11, .reg_width = 1, }, { .name = "azoteq,invert-enable", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 10, .reg_width = 1, }, { .name = "azoteq,dual-direction", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 9, .reg_width = 1, }, { .name = "azoteq,samp-cap-double", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 3, .reg_width = 1, }, { .name = "azoteq,vref-half", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 2, .reg_width = 1, }, { .name = "azoteq,proj-bias", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 0, .reg_shift = 0, .reg_width = 2, .label = "projected bias current", }, { .name = "azoteq,ati-target", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 1, .reg_shift = 8, .reg_width = 8, .val_pitch = 8, .label = "ATI target", }, { .name = "azoteq,ati-base", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 1, .reg_shift = 3, .reg_width = 5, .val_pitch = 16, .label = "ATI base", }, { .name = "azoteq,ati-mode", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 1, .reg_shift = 0, .reg_width = 3, .val_max = 5, .label = "ATI mode", }, { .name = "azoteq,ati-frac-div-fine", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 2, .reg_shift = 9, .reg_width = 5, .label = "ATI fine fractional divider", }, { .name = "azoteq,ati-frac-mult-coarse", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 2, .reg_shift = 5, .reg_width = 4, .label = "ATI coarse fractional multiplier", }, { .name = "azoteq,ati-frac-div-coarse", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 2, .reg_shift = 0, .reg_width = 5, .label = "ATI coarse fractional divider", }, { .name = "azoteq,ati-comp-div", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 3, .reg_shift = 11, .reg_width = 5, .label = "ATI compensation divider", }, { .name = "azoteq,ati-comp-select", .reg_grp = IQS7222_REG_GRP_CHAN, .reg_offset = 3, .reg_shift = 0, .reg_width = 10, .label = "ATI compensation selection", }, { .name = "azoteq,debounce-exit", .reg_grp = IQS7222_REG_GRP_BTN, .reg_key = IQS7222_REG_KEY_DEBOUNCE, .reg_offset = 0, .reg_shift = 12, .reg_width = 4, .label = "debounce exit factor", }, { .name = "azoteq,debounce-enter", .reg_grp = IQS7222_REG_GRP_BTN, .reg_key = IQS7222_REG_KEY_DEBOUNCE, .reg_offset = 0, .reg_shift = 8, .reg_width = 4, .label = "debounce entrance factor", }, { .name = "azoteq,thresh", .reg_grp = IQS7222_REG_GRP_BTN, .reg_key = IQS7222_REG_KEY_PROX, .reg_offset = 0, .reg_shift = 0, .reg_width = 8, .val_max = 127, .label = "threshold", }, { .name = "azoteq,thresh", .reg_grp = IQS7222_REG_GRP_BTN, .reg_key = IQS7222_REG_KEY_TOUCH, .reg_offset = 1, .reg_shift = 0, .reg_width = 8, .label = "threshold", }, { .name = "azoteq,hyst", .reg_grp = IQS7222_REG_GRP_BTN, .reg_key = IQS7222_REG_KEY_TOUCH, .reg_offset = 1, .reg_shift = 8, .reg_width = 8, .label = "hysteresis", }, { .name = "azoteq,lta-beta-lp", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 0, .reg_shift = 12, .reg_width = 4, .label = "low-power mode long-term average beta", }, { .name = "azoteq,lta-beta-np", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 0, .reg_shift = 8, .reg_width = 4, .label = "normal-power mode long-term average beta", }, { .name = "azoteq,counts-beta-lp", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 0, .reg_shift = 4, .reg_width = 4, .label = "low-power mode counts beta", }, { .name = "azoteq,counts-beta-np", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 0, .reg_shift = 0, .reg_width = 4, .label = "normal-power mode counts beta", }, { .name = "azoteq,lta-fast-beta-lp", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 1, .reg_shift = 4, .reg_width = 4, .label = "low-power mode long-term average fast beta", }, { .name = "azoteq,lta-fast-beta-np", .reg_grp = IQS7222_REG_GRP_FILT, .reg_offset = 1, .reg_shift = 0, .reg_width = 4, .label = "normal-power mode long-term average fast beta", }, { .name = "azoteq,lower-cal", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_offset = 0, .reg_shift = 8, .reg_width = 8, .label = "lower calibration", }, { .name = "azoteq,static-beta", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_NO_WHEEL, .reg_offset = 0, .reg_shift = 6, .reg_width = 1, }, { .name = "azoteq,bottom-beta", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_NO_WHEEL, .reg_offset = 0, .reg_shift = 3, .reg_width = 3, .label = "bottom beta", }, { .name = "azoteq,static-beta", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_WHEEL, .reg_offset = 0, .reg_shift = 7, .reg_width = 1, }, { .name = "azoteq,bottom-beta", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_WHEEL, .reg_offset = 0, .reg_shift = 4, .reg_width = 3, .label = "bottom beta", }, { .name = "azoteq,bottom-speed", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_offset = 1, .reg_shift = 8, .reg_width = 8, .label = "bottom speed", }, { .name = "azoteq,upper-cal", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_offset = 1, .reg_shift = 0, .reg_width = 8, .label = "upper calibration", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_TAP, .reg_offset = 9, .reg_shift = 8, .reg_width = 8, .val_pitch = 16, .label = "maximum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_TAP_LEGACY, .reg_offset = 9, .reg_shift = 8, .reg_width = 8, .val_pitch = 4, .label = "maximum gesture time", }, { .name = "azoteq,gesture-min-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_TAP, .reg_offset = 9, .reg_shift = 3, .reg_width = 5, .val_pitch = 16, .label = "minimum gesture time", }, { .name = "azoteq,gesture-min-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_TAP_LEGACY, .reg_offset = 9, .reg_shift = 3, .reg_width = 5, .val_pitch = 4, .label = "minimum gesture time", }, { .name = "azoteq,gesture-dist", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_AXIAL, .reg_offset = 10, .reg_shift = 8, .reg_width = 8, .val_pitch = 16, .label = "gesture distance", }, { .name = "azoteq,gesture-dist", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_AXIAL_LEGACY, .reg_offset = 10, .reg_shift = 8, .reg_width = 8, .val_pitch = 16, .label = "gesture distance", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_AXIAL, .reg_offset = 10, .reg_shift = 0, .reg_width = 8, .val_pitch = 16, .label = "maximum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_SLDR, .reg_key = IQS7222_REG_KEY_AXIAL_LEGACY, .reg_offset = 10, .reg_shift = 0, .reg_width = 8, .val_pitch = 4, .label = "maximum gesture time", }, { .name = "azoteq,num-rows", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 0, .reg_shift = 4, .reg_width = 4, .val_min = 1, .val_max = 12, .label = "number of rows", }, { .name = "azoteq,num-cols", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 0, .reg_shift = 0, .reg_width = 4, .val_min = 1, .val_max = 12, .label = "number of columns", }, { .name = "azoteq,lower-cal-y", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 1, .reg_shift = 8, .reg_width = 8, .label = "lower vertical calibration", }, { .name = "azoteq,lower-cal-x", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 1, .reg_shift = 0, .reg_width = 8, .label = "lower horizontal calibration", }, { .name = "azoteq,upper-cal-y", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 2, .reg_shift = 8, .reg_width = 8, .label = "upper vertical calibration", }, { .name = "azoteq,upper-cal-x", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 2, .reg_shift = 0, .reg_width = 8, .label = "upper horizontal calibration", }, { .name = "azoteq,top-speed", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 3, .reg_shift = 8, .reg_width = 8, .val_pitch = 4, .label = "top speed", }, { .name = "azoteq,bottom-speed", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_offset = 3, .reg_shift = 0, .reg_width = 8, .label = "bottom speed", }, { .name = "azoteq,gesture-min-ms", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_key = IQS7222_REG_KEY_TAP, .reg_offset = 20, .reg_shift = 8, .reg_width = 8, .val_pitch = 16, .label = "minimum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_key = IQS7222_REG_KEY_AXIAL, .reg_offset = 21, .reg_shift = 8, .reg_width = 8, .val_pitch = 16, .label = "maximum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_key = IQS7222_REG_KEY_TAP, .reg_offset = 21, .reg_shift = 0, .reg_width = 8, .val_pitch = 16, .label = "maximum gesture time", }, { .name = "azoteq,gesture-dist", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_key = IQS7222_REG_KEY_TAP, .reg_offset = 22, .reg_shift = 0, .reg_width = 16, .label = "gesture distance", }, { .name = "azoteq,gesture-dist", .reg_grp = IQS7222_REG_GRP_TPAD, .reg_key = IQS7222_REG_KEY_AXIAL, .reg_offset = 23, .reg_shift = 0, .reg_width = 16, .label = "gesture distance", }, { .name = "drive-open-drain", .reg_grp = IQS7222_REG_GRP_GPIO, .reg_offset = 0, .reg_shift = 1, .reg_width = 1, }, { .name = "azoteq,timeout-ati-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 1, .reg_shift = 0, .reg_width = 16, .val_pitch = 500, .label = "ATI error timeout", }, { .name = "azoteq,rate-ati-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 2, .reg_shift = 0, .reg_width = 16, .label = "ATI report rate", }, { .name = "azoteq,timeout-np-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 3, .reg_shift = 0, .reg_width = 16, .label = "normal-power mode timeout", }, { .name = "azoteq,rate-np-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 4, .reg_shift = 0, .reg_width = 16, .val_max = 3000, .label = "normal-power mode report rate", }, { .name = "azoteq,timeout-lp-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 5, .reg_shift = 0, .reg_width = 16, .label = "low-power mode timeout", }, { .name = "azoteq,rate-lp-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 6, .reg_shift = 0, .reg_width = 16, .val_max = 3000, .label = "low-power mode report rate", }, { .name = "azoteq,timeout-ulp-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 7, .reg_shift = 0, .reg_width = 16, .label = "ultra-low-power mode timeout", }, { .name = "azoteq,rate-ulp-ms", .reg_grp = IQS7222_REG_GRP_SYS, .reg_offset = 8, .reg_shift = 0, .reg_width = 16, .val_max = 3000, .label = "ultra-low-power mode report rate", }, }; struct iqs7222_private { const struct iqs7222_dev_desc *dev_desc; struct gpio_desc *reset_gpio; struct gpio_desc *irq_gpio; struct i2c_client *client; struct input_dev *keypad; struct touchscreen_properties prop; unsigned int kp_type[IQS7222_MAX_CHAN][ARRAY_SIZE(iqs7222_kp_events)]; unsigned int kp_code[IQS7222_MAX_CHAN][ARRAY_SIZE(iqs7222_kp_events)]; unsigned int sl_code[IQS7222_MAX_SLDR][ARRAY_SIZE(iqs7222_sl_events)]; unsigned int sl_axis[IQS7222_MAX_SLDR]; unsigned int tp_code[ARRAY_SIZE(iqs7222_tp_events)]; u16 cycle_setup[IQS7222_MAX_CHAN / 2][IQS7222_MAX_COLS_CYCLE]; u16 glbl_setup[IQS7222_MAX_COLS_GLBL]; u16 btn_setup[IQS7222_MAX_CHAN][IQS7222_MAX_COLS_BTN]; u16 chan_setup[IQS7222_MAX_CHAN][IQS7222_MAX_COLS_CHAN]; u16 filt_setup[IQS7222_MAX_COLS_FILT]; u16 sldr_setup[IQS7222_MAX_SLDR][IQS7222_MAX_COLS_SLDR]; u16 tpad_setup[IQS7222_MAX_COLS_TPAD]; u16 gpio_setup[ARRAY_SIZE(iqs7222_gpio_links)][IQS7222_MAX_COLS_GPIO]; u16 sys_setup[IQS7222_MAX_COLS_SYS]; }; static u16 *iqs7222_setup(struct iqs7222_private *iqs7222, enum iqs7222_reg_grp_id reg_grp, int row) { switch (reg_grp) { case IQS7222_REG_GRP_CYCLE: return iqs7222->cycle_setup[row]; case IQS7222_REG_GRP_GLBL: return iqs7222->glbl_setup; case IQS7222_REG_GRP_BTN: return iqs7222->btn_setup[row]; case IQS7222_REG_GRP_CHAN: return iqs7222->chan_setup[row]; case IQS7222_REG_GRP_FILT: return iqs7222->filt_setup; case IQS7222_REG_GRP_SLDR: return iqs7222->sldr_setup[row]; case IQS7222_REG_GRP_TPAD: return iqs7222->tpad_setup; case IQS7222_REG_GRP_GPIO: return iqs7222->gpio_setup[row]; case IQS7222_REG_GRP_SYS: return iqs7222->sys_setup; default: return NULL; } } static int iqs7222_irq_poll(struct iqs7222_private *iqs7222, u16 timeout_ms) { ktime_t irq_timeout = ktime_add_ms(ktime_get(), timeout_ms); int ret; do { usleep_range(1000, 1100); ret = gpiod_get_value_cansleep(iqs7222->irq_gpio); if (ret < 0) return ret; else if (ret > 0) return 0; } while (ktime_compare(ktime_get(), irq_timeout) < 0); return -EBUSY; } static int iqs7222_hard_reset(struct iqs7222_private *iqs7222) { struct i2c_client *client = iqs7222->client; int error; if (!iqs7222->reset_gpio) return 0; gpiod_set_value_cansleep(iqs7222->reset_gpio, 1); usleep_range(1000, 1100); gpiod_set_value_cansleep(iqs7222->reset_gpio, 0); error = iqs7222_irq_poll(iqs7222, IQS7222_RESET_TIMEOUT_MS); if (error) dev_err(&client->dev, "Failed to reset device: %d\n", error); return error; } static int iqs7222_force_comms(struct iqs7222_private *iqs7222) { u8 msg_buf[] = { 0xFF, }; int ret; /* * The device cannot communicate until it asserts its interrupt (RDY) * pin. Attempts to do so while RDY is deasserted return an ACK; how- * ever all write data is ignored, and all read data returns 0xEE. * * Unsolicited communication must be preceded by a special force com- * munication command, after which the device eventually asserts its * RDY pin and agrees to communicate. * * Regardless of whether communication is forced or the result of an * interrupt, the device automatically deasserts its RDY pin once it * detects an I2C stop condition, or a timeout expires. */ ret = gpiod_get_value_cansleep(iqs7222->irq_gpio); if (ret < 0) return ret; else if (ret > 0) return 0; ret = i2c_master_send(iqs7222->client, msg_buf, sizeof(msg_buf)); if (ret < (int)sizeof(msg_buf)) { if (ret >= 0) ret = -EIO; /* * The datasheet states that the host must wait to retry any * failed attempt to communicate over I2C. */ msleep(IQS7222_COMMS_RETRY_MS); return ret; } return iqs7222_irq_poll(iqs7222, IQS7222_COMMS_TIMEOUT_MS); } static int iqs7222_read_burst(struct iqs7222_private *iqs7222, u16 reg, void *val, u16 num_val) { u8 reg_buf[sizeof(__be16)]; int ret, i; struct i2c_client *client = iqs7222->client; struct i2c_msg msg[] = { { .addr = client->addr, .flags = 0, .len = reg > U8_MAX ? sizeof(reg) : sizeof(u8), .buf = reg_buf, }, { .addr = client->addr, .flags = I2C_M_RD, .len = num_val * sizeof(__le16), .buf = (u8 *)val, }, }; if (reg > U8_MAX) put_unaligned_be16(reg, reg_buf); else *reg_buf = (u8)reg; /* * The following loop protects against an edge case in which the RDY * pin is automatically deasserted just as the read is initiated. In * that case, the read must be retried using forced communication. */ for (i = 0; i < IQS7222_NUM_RETRIES; i++) { ret = iqs7222_force_comms(iqs7222); if (ret < 0) continue; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret < (int)ARRAY_SIZE(msg)) { if (ret >= 0) ret = -EIO; msleep(IQS7222_COMMS_RETRY_MS); continue; } if (get_unaligned_le16(msg[1].buf) == IQS7222_COMMS_ERROR) { ret = -ENODATA; continue; } ret = 0; break; } /* * The following delay ensures the device has deasserted the RDY pin * following the I2C stop condition. */ usleep_range(50, 100); if (ret < 0) dev_err(&client->dev, "Failed to read from address 0x%04X: %d\n", reg, ret); return ret; } static int iqs7222_read_word(struct iqs7222_private *iqs7222, u16 reg, u16 *val) { __le16 val_buf; int error; error = iqs7222_read_burst(iqs7222, reg, &val_buf, 1); if (error) return error; *val = le16_to_cpu(val_buf); return 0; } static int iqs7222_write_burst(struct iqs7222_private *iqs7222, u16 reg, const void *val, u16 num_val) { int reg_len = reg > U8_MAX ? sizeof(reg) : sizeof(u8); int val_len = num_val * sizeof(__le16); int msg_len = reg_len + val_len; int ret, i; struct i2c_client *client = iqs7222->client; u8 *msg_buf; msg_buf = kzalloc(msg_len, GFP_KERNEL); if (!msg_buf) return -ENOMEM; if (reg > U8_MAX) put_unaligned_be16(reg, msg_buf); else *msg_buf = (u8)reg; memcpy(msg_buf + reg_len, val, val_len); /* * The following loop protects against an edge case in which the RDY * pin is automatically asserted just before the force communication * command is sent. * * In that case, the subsequent I2C stop condition tricks the device * into preemptively deasserting the RDY pin and the command must be * sent again. */ for (i = 0; i < IQS7222_NUM_RETRIES; i++) { ret = iqs7222_force_comms(iqs7222); if (ret < 0) continue; ret = i2c_master_send(client, msg_buf, msg_len); if (ret < msg_len) { if (ret >= 0) ret = -EIO; msleep(IQS7222_COMMS_RETRY_MS); continue; } ret = 0; break; } kfree(msg_buf); usleep_range(50, 100); if (ret < 0) dev_err(&client->dev, "Failed to write to address 0x%04X: %d\n", reg, ret); return ret; } static int iqs7222_write_word(struct iqs7222_private *iqs7222, u16 reg, u16 val) { __le16 val_buf = cpu_to_le16(val); return iqs7222_write_burst(iqs7222, reg, &val_buf, 1); } static int iqs7222_ati_trigger(struct iqs7222_private *iqs7222) { struct i2c_client *client = iqs7222->client; ktime_t ati_timeout; u16 sys_status = 0; u16 sys_setup; int error, i; /* * The reserved fields of the system setup register may have changed * as a result of other registers having been written. As such, read * the register's latest value to avoid unexpected behavior when the * register is written in the loop that follows. */ error = iqs7222_read_word(iqs7222, IQS7222_SYS_SETUP, &sys_setup); if (error) return error; for (i = 0; i < IQS7222_NUM_RETRIES; i++) { /* * Trigger ATI from streaming and normal-power modes so that * the RDY pin continues to be asserted during ATI. */ error = iqs7222_write_word(iqs7222, IQS7222_SYS_SETUP, sys_setup | IQS7222_SYS_SETUP_REDO_ATI); if (error) return error; ati_timeout = ktime_add_ms(ktime_get(), IQS7222_ATI_TIMEOUT_MS); do { error = iqs7222_irq_poll(iqs7222, IQS7222_COMMS_TIMEOUT_MS); if (error) continue; error = iqs7222_read_word(iqs7222, IQS7222_SYS_STATUS, &sys_status); if (error) return error; if (sys_status & IQS7222_SYS_STATUS_RESET) return 0; if (sys_status & IQS7222_SYS_STATUS_ATI_ERROR) break; if (sys_status & IQS7222_SYS_STATUS_ATI_ACTIVE) continue; /* * Use stream-in-touch mode if either slider reports * absolute position. */ sys_setup |= test_bit(EV_ABS, iqs7222->keypad->evbit) ? IQS7222_SYS_SETUP_INTF_MODE_TOUCH : IQS7222_SYS_SETUP_INTF_MODE_EVENT; sys_setup |= IQS7222_SYS_SETUP_PWR_MODE_AUTO; return iqs7222_write_word(iqs7222, IQS7222_SYS_SETUP, sys_setup); } while (ktime_compare(ktime_get(), ati_timeout) < 0); dev_err(&client->dev, "ATI attempt %d of %d failed with status 0x%02X, %s\n", i + 1, IQS7222_NUM_RETRIES, (u8)sys_status, i + 1 < IQS7222_NUM_RETRIES ? "retrying" : "stopping"); } return -ETIMEDOUT; } static int iqs7222_dev_init(struct iqs7222_private *iqs7222, int dir) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; int comms_offset = dev_desc->comms_offset; int error, i, j, k; /* * Acknowledge reset before writing any registers in case the device * suffers a spurious reset during initialization. Because this step * may change the reserved fields of the second filter beta register, * its cache must be updated. * * Writing the second filter beta register, in turn, may clobber the * system status register. As such, the filter beta register pair is * written first to protect against this hazard. */ if (dir == WRITE) { u16 reg = dev_desc->reg_grps[IQS7222_REG_GRP_FILT].base + 1; u16 filt_setup; error = iqs7222_write_word(iqs7222, IQS7222_SYS_SETUP, iqs7222->sys_setup[0] | IQS7222_SYS_SETUP_ACK_RESET); if (error) return error; error = iqs7222_read_word(iqs7222, reg, &filt_setup); if (error) return error; iqs7222->filt_setup[1] &= GENMASK(7, 0); iqs7222->filt_setup[1] |= (filt_setup & ~GENMASK(7, 0)); } /* * Take advantage of the stop-bit disable function, if available, to * save the trouble of having to reopen a communication window after * each burst read or write. */ if (comms_offset) { u16 comms_setup; error = iqs7222_read_word(iqs7222, IQS7222_SYS_SETUP + comms_offset, &comms_setup); if (error) return error; error = iqs7222_write_word(iqs7222, IQS7222_SYS_SETUP + comms_offset, comms_setup | IQS7222_COMMS_HOLD); if (error) return error; } for (i = 0; i < IQS7222_NUM_REG_GRPS; i++) { int num_row = dev_desc->reg_grps[i].num_row; int num_col = dev_desc->reg_grps[i].num_col; u16 reg = dev_desc->reg_grps[i].base; __le16 *val_buf; u16 *val; if (!num_col) continue; val = iqs7222_setup(iqs7222, i, 0); if (!val) continue; val_buf = kcalloc(num_col, sizeof(__le16), GFP_KERNEL); if (!val_buf) return -ENOMEM; for (j = 0; j < num_row; j++) { switch (dir) { case READ: error = iqs7222_read_burst(iqs7222, reg, val_buf, num_col); for (k = 0; k < num_col; k++) val[k] = le16_to_cpu(val_buf[k]); break; case WRITE: for (k = 0; k < num_col; k++) val_buf[k] = cpu_to_le16(val[k]); error = iqs7222_write_burst(iqs7222, reg, val_buf, num_col); break; default: error = -EINVAL; } if (error) break; reg += IQS7222_REG_OFFSET; val += iqs7222_max_cols[i]; } kfree(val_buf); if (error) return error; } if (comms_offset) { u16 comms_setup; error = iqs7222_read_word(iqs7222, IQS7222_SYS_SETUP + comms_offset, &comms_setup); if (error) return error; error = iqs7222_write_word(iqs7222, IQS7222_SYS_SETUP + comms_offset, comms_setup & ~IQS7222_COMMS_HOLD); if (error) return error; } if (dir == READ) { iqs7222->sys_setup[0] &= ~IQS7222_SYS_SETUP_INTF_MODE_MASK; iqs7222->sys_setup[0] &= ~IQS7222_SYS_SETUP_PWR_MODE_MASK; return 0; } return iqs7222_ati_trigger(iqs7222); } static int iqs7222_dev_info(struct iqs7222_private *iqs7222) { struct i2c_client *client = iqs7222->client; bool prod_num_valid = false; __le16 dev_id[3]; int error, i; error = iqs7222_read_burst(iqs7222, IQS7222_PROD_NUM, dev_id, ARRAY_SIZE(dev_id)); if (error) return error; for (i = 0; i < ARRAY_SIZE(iqs7222_devs); i++) { if (le16_to_cpu(dev_id[0]) != iqs7222_devs[i].prod_num) continue; prod_num_valid = true; if (le16_to_cpu(dev_id[1]) < iqs7222_devs[i].fw_major) continue; if (le16_to_cpu(dev_id[2]) < iqs7222_devs[i].fw_minor) continue; iqs7222->dev_desc = &iqs7222_devs[i]; return 0; } if (prod_num_valid) dev_err(&client->dev, "Unsupported firmware revision: %u.%u\n", le16_to_cpu(dev_id[1]), le16_to_cpu(dev_id[2])); else dev_err(&client->dev, "Unrecognized product number: %u\n", le16_to_cpu(dev_id[0])); return -EINVAL; } static int iqs7222_gpio_select(struct iqs7222_private *iqs7222, struct fwnode_handle *child_node, int child_enable, u16 child_link) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; struct i2c_client *client = iqs7222->client; int num_gpio = dev_desc->reg_grps[IQS7222_REG_GRP_GPIO].num_row; int error, count, i; unsigned int gpio_sel[ARRAY_SIZE(iqs7222_gpio_links)]; if (!num_gpio) return 0; if (!fwnode_property_present(child_node, "azoteq,gpio-select")) return 0; count = fwnode_property_count_u32(child_node, "azoteq,gpio-select"); if (count > num_gpio) { dev_err(&client->dev, "Invalid number of %s GPIOs\n", fwnode_get_name(child_node)); return -EINVAL; } else if (count < 0) { dev_err(&client->dev, "Failed to count %s GPIOs: %d\n", fwnode_get_name(child_node), count); return count; } error = fwnode_property_read_u32_array(child_node, "azoteq,gpio-select", gpio_sel, count); if (error) { dev_err(&client->dev, "Failed to read %s GPIOs: %d\n", fwnode_get_name(child_node), error); return error; } for (i = 0; i < count; i++) { u16 *gpio_setup; if (gpio_sel[i] >= num_gpio) { dev_err(&client->dev, "Invalid %s GPIO: %u\n", fwnode_get_name(child_node), gpio_sel[i]); return -EINVAL; } gpio_setup = iqs7222->gpio_setup[gpio_sel[i]]; if (gpio_setup[2] && child_link != gpio_setup[2]) { dev_err(&client->dev, "Conflicting GPIO %u event types\n", gpio_sel[i]); return -EINVAL; } gpio_setup[0] |= IQS7222_GPIO_SETUP_0_GPIO_EN; gpio_setup[1] |= child_enable; gpio_setup[2] = child_link; } return 0; } static int iqs7222_parse_props(struct iqs7222_private *iqs7222, struct fwnode_handle *reg_grp_node, int reg_grp_index, enum iqs7222_reg_grp_id reg_grp, enum iqs7222_reg_key_id reg_key) { u16 *setup = iqs7222_setup(iqs7222, reg_grp, reg_grp_index); struct i2c_client *client = iqs7222->client; int i; if (!setup) return 0; for (i = 0; i < ARRAY_SIZE(iqs7222_props); i++) { const char *name = iqs7222_props[i].name; int reg_offset = iqs7222_props[i].reg_offset; int reg_shift = iqs7222_props[i].reg_shift; int reg_width = iqs7222_props[i].reg_width; int val_pitch = iqs7222_props[i].val_pitch ? : 1; int val_min = iqs7222_props[i].val_min; int val_max = iqs7222_props[i].val_max; bool invert = iqs7222_props[i].invert; const char *label = iqs7222_props[i].label ? : name; unsigned int val; int error; if (iqs7222_props[i].reg_grp != reg_grp || iqs7222_props[i].reg_key != reg_key) continue; /* * Boolean register fields are one bit wide; they are forcibly * reset to provide a means to undo changes by a bootloader if * necessary. * * Scalar fields, on the other hand, are left untouched unless * their corresponding properties are present. */ if (reg_width == 1) { if (invert) setup[reg_offset] |= BIT(reg_shift); else setup[reg_offset] &= ~BIT(reg_shift); } if (!fwnode_property_present(reg_grp_node, name)) continue; if (reg_width == 1) { if (invert) setup[reg_offset] &= ~BIT(reg_shift); else setup[reg_offset] |= BIT(reg_shift); continue; } error = fwnode_property_read_u32(reg_grp_node, name, &val); if (error) { dev_err(&client->dev, "Failed to read %s %s: %d\n", fwnode_get_name(reg_grp_node), label, error); return error; } if (!val_max) val_max = GENMASK(reg_width - 1, 0) * val_pitch; if (val < val_min || val > val_max) { dev_err(&client->dev, "Invalid %s %s: %u\n", fwnode_get_name(reg_grp_node), label, val); return -EINVAL; } setup[reg_offset] &= ~GENMASK(reg_shift + reg_width - 1, reg_shift); setup[reg_offset] |= (val / val_pitch << reg_shift); } return 0; } static int iqs7222_parse_event(struct iqs7222_private *iqs7222, struct fwnode_handle *event_node, int reg_grp_index, enum iqs7222_reg_grp_id reg_grp, enum iqs7222_reg_key_id reg_key, u16 event_enable, u16 event_link, unsigned int *event_type, unsigned int *event_code) { struct i2c_client *client = iqs7222->client; int error; error = iqs7222_parse_props(iqs7222, event_node, reg_grp_index, reg_grp, reg_key); if (error) return error; error = iqs7222_gpio_select(iqs7222, event_node, event_enable, event_link); if (error) return error; error = fwnode_property_read_u32(event_node, "linux,code", event_code); if (error == -EINVAL) { return 0; } else if (error) { dev_err(&client->dev, "Failed to read %s code: %d\n", fwnode_get_name(event_node), error); return error; } if (!event_type) { input_set_capability(iqs7222->keypad, EV_KEY, *event_code); return 0; } error = fwnode_property_read_u32(event_node, "linux,input-type", event_type); if (error == -EINVAL) { *event_type = EV_KEY; } else if (error) { dev_err(&client->dev, "Failed to read %s input type: %d\n", fwnode_get_name(event_node), error); return error; } else if (*event_type != EV_KEY && *event_type != EV_SW) { dev_err(&client->dev, "Invalid %s input type: %d\n", fwnode_get_name(event_node), *event_type); return -EINVAL; } input_set_capability(iqs7222->keypad, *event_type, *event_code); return 0; } static int iqs7222_parse_cycle(struct iqs7222_private *iqs7222, struct fwnode_handle *cycle_node, int cycle_index) { u16 *cycle_setup = iqs7222->cycle_setup[cycle_index]; struct i2c_client *client = iqs7222->client; unsigned int pins[9]; int error, count, i; /* * Each channel shares a cycle with one other channel; the mapping of * channels to cycles is fixed. Properties defined for a cycle impact * both channels tied to the cycle. * * Unlike channels which are restricted to a select range of CRx pins * based on channel number, any cycle can claim any of the device's 9 * CTx pins (CTx0-8). */ if (!fwnode_property_present(cycle_node, "azoteq,tx-enable")) return 0; count = fwnode_property_count_u32(cycle_node, "azoteq,tx-enable"); if (count < 0) { dev_err(&client->dev, "Failed to count %s CTx pins: %d\n", fwnode_get_name(cycle_node), count); return count; } else if (count > ARRAY_SIZE(pins)) { dev_err(&client->dev, "Invalid number of %s CTx pins\n", fwnode_get_name(cycle_node)); return -EINVAL; } error = fwnode_property_read_u32_array(cycle_node, "azoteq,tx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read %s CTx pins: %d\n", fwnode_get_name(cycle_node), error); return error; } cycle_setup[1] &= ~GENMASK(7 + ARRAY_SIZE(pins) - 1, 7); for (i = 0; i < count; i++) { if (pins[i] > 8) { dev_err(&client->dev, "Invalid %s CTx pin: %u\n", fwnode_get_name(cycle_node), pins[i]); return -EINVAL; } cycle_setup[1] |= BIT(pins[i] + 7); } return 0; } static int iqs7222_parse_chan(struct iqs7222_private *iqs7222, struct fwnode_handle *chan_node, int chan_index) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; struct i2c_client *client = iqs7222->client; int num_chan = dev_desc->reg_grps[IQS7222_REG_GRP_CHAN].num_row; int ext_chan = rounddown(num_chan, 10); int error, i; u16 *chan_setup = iqs7222->chan_setup[chan_index]; u16 *sys_setup = iqs7222->sys_setup; unsigned int val; if (dev_desc->allow_offset && fwnode_property_present(chan_node, "azoteq,ulp-allow")) sys_setup[dev_desc->allow_offset] &= ~BIT(chan_index); chan_setup[0] |= IQS7222_CHAN_SETUP_0_CHAN_EN; /* * The reference channel function allows for differential measurements * and is only available in the case of IQS7222A or IQS7222C. */ if (dev_desc->reg_grps[IQS7222_REG_GRP_CHAN].num_col > 4 && fwnode_property_present(chan_node, "azoteq,ref-select")) { u16 *ref_setup; error = fwnode_property_read_u32(chan_node, "azoteq,ref-select", &val); if (error) { dev_err(&client->dev, "Failed to read %s reference channel: %d\n", fwnode_get_name(chan_node), error); return error; } if (val >= ext_chan) { dev_err(&client->dev, "Invalid %s reference channel: %u\n", fwnode_get_name(chan_node), val); return -EINVAL; } ref_setup = iqs7222->chan_setup[val]; /* * Configure the current channel as a follower of the selected * reference channel. */ chan_setup[0] |= IQS7222_CHAN_SETUP_0_REF_MODE_FOLLOW; chan_setup[4] = val * 42 + 1048; error = fwnode_property_read_u32(chan_node, "azoteq,ref-weight", &val); if (!error) { if (val > U16_MAX) { dev_err(&client->dev, "Invalid %s reference weight: %u\n", fwnode_get_name(chan_node), val); return -EINVAL; } chan_setup[5] = val; } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s reference weight: %d\n", fwnode_get_name(chan_node), error); return error; } /* * Configure the selected channel as a reference channel which * serves the current channel. */ ref_setup[0] |= IQS7222_CHAN_SETUP_0_REF_MODE_REF; ref_setup[5] |= BIT(chan_index); ref_setup[4] = dev_desc->touch_link; if (fwnode_property_present(chan_node, "azoteq,use-prox")) ref_setup[4] -= 2; } else if (dev_desc->reg_grps[IQS7222_REG_GRP_TPAD].num_row && fwnode_property_present(chan_node, "azoteq,counts-filt-enable")) { /* * In the case of IQS7222D, however, the reference mode field * is partially repurposed as a counts filter enable control. */ chan_setup[0] |= IQS7222_CHAN_SETUP_0_REF_MODE_REF; } if (fwnode_property_present(chan_node, "azoteq,rx-enable")) { /* * Each channel can claim up to 4 CRx pins. The first half of * the channels can use CRx0-3, while the second half can use * CRx4-7. */ unsigned int pins[4]; int count; count = fwnode_property_count_u32(chan_node, "azoteq,rx-enable"); if (count < 0) { dev_err(&client->dev, "Failed to count %s CRx pins: %d\n", fwnode_get_name(chan_node), count); return count; } else if (count > ARRAY_SIZE(pins)) { dev_err(&client->dev, "Invalid number of %s CRx pins\n", fwnode_get_name(chan_node)); return -EINVAL; } error = fwnode_property_read_u32_array(chan_node, "azoteq,rx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read %s CRx pins: %d\n", fwnode_get_name(chan_node), error); return error; } chan_setup[0] &= ~GENMASK(4 + ARRAY_SIZE(pins) - 1, 4); for (i = 0; i < count; i++) { int min_crx = chan_index < ext_chan / 2 ? 0 : 4; if (pins[i] < min_crx || pins[i] > min_crx + 3) { dev_err(&client->dev, "Invalid %s CRx pin: %u\n", fwnode_get_name(chan_node), pins[i]); return -EINVAL; } chan_setup[0] |= BIT(pins[i] + 4 - min_crx); } } for (i = 0; i < ARRAY_SIZE(iqs7222_kp_events); i++) { const char *event_name = iqs7222_kp_events[i].name; u16 event_enable = iqs7222_kp_events[i].enable; struct fwnode_handle *event_node; event_node = fwnode_get_named_child_node(chan_node, event_name); if (!event_node) continue; error = fwnode_property_read_u32(event_node, "azoteq,timeout-press-ms", &val); if (!error) { /* * The IQS7222B employs a global pair of press timeout * registers as opposed to channel-specific registers. */ u16 *setup = dev_desc->reg_grps [IQS7222_REG_GRP_BTN].num_col > 2 ? &iqs7222->btn_setup[chan_index][2] : &sys_setup[9]; if (val > U8_MAX * 500) { dev_err(&client->dev, "Invalid %s press timeout: %u\n", fwnode_get_name(event_node), val); fwnode_handle_put(event_node); return -EINVAL; } *setup &= ~(U8_MAX << i * 8); *setup |= (val / 500 << i * 8); } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s press timeout: %d\n", fwnode_get_name(event_node), error); fwnode_handle_put(event_node); return error; } error = iqs7222_parse_event(iqs7222, event_node, chan_index, IQS7222_REG_GRP_BTN, iqs7222_kp_events[i].reg_key, BIT(chan_index), dev_desc->touch_link - (i ? 0 : 2), &iqs7222->kp_type[chan_index][i], &iqs7222->kp_code[chan_index][i]); fwnode_handle_put(event_node); if (error) return error; if (!dev_desc->event_offset) continue; sys_setup[dev_desc->event_offset] |= event_enable; } /* * The following call handles a special pair of properties that apply * to a channel node, but reside within the button (event) group. */ return iqs7222_parse_props(iqs7222, chan_node, chan_index, IQS7222_REG_GRP_BTN, IQS7222_REG_KEY_DEBOUNCE); } static int iqs7222_parse_sldr(struct iqs7222_private *iqs7222, struct fwnode_handle *sldr_node, int sldr_index) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; struct i2c_client *client = iqs7222->client; int num_chan = dev_desc->reg_grps[IQS7222_REG_GRP_CHAN].num_row; int ext_chan = rounddown(num_chan, 10); int count, error, reg_offset, i; u16 *event_mask = &iqs7222->sys_setup[dev_desc->event_offset]; u16 *sldr_setup = iqs7222->sldr_setup[sldr_index]; unsigned int chan_sel[4], val; /* * Each slider can be spread across 3 to 4 channels. It is possible to * select only 2 channels, but doing so prevents the slider from using * the specified resolution. */ count = fwnode_property_count_u32(sldr_node, "azoteq,channel-select"); if (count < 0) { dev_err(&client->dev, "Failed to count %s channels: %d\n", fwnode_get_name(sldr_node), count); return count; } else if (count < 3 || count > ARRAY_SIZE(chan_sel)) { dev_err(&client->dev, "Invalid number of %s channels\n", fwnode_get_name(sldr_node)); return -EINVAL; } error = fwnode_property_read_u32_array(sldr_node, "azoteq,channel-select", chan_sel, count); if (error) { dev_err(&client->dev, "Failed to read %s channels: %d\n", fwnode_get_name(sldr_node), error); return error; } /* * Resolution and top speed, if small enough, are packed into a single * register. Otherwise, each occupies its own register and the rest of * the slider-related register addresses are offset by one. */ reg_offset = dev_desc->sldr_res < U16_MAX ? 0 : 1; sldr_setup[0] |= count; sldr_setup[3 + reg_offset] &= ~GENMASK(ext_chan - 1, 0); for (i = 0; i < ARRAY_SIZE(chan_sel); i++) { sldr_setup[5 + reg_offset + i] = 0; if (i >= count) continue; if (chan_sel[i] >= ext_chan) { dev_err(&client->dev, "Invalid %s channel: %u\n", fwnode_get_name(sldr_node), chan_sel[i]); return -EINVAL; } /* * The following fields indicate which channels participate in * the slider, as well as each channel's relative placement. */ sldr_setup[3 + reg_offset] |= BIT(chan_sel[i]); sldr_setup[5 + reg_offset + i] = chan_sel[i] * 42 + 1080; } sldr_setup[4 + reg_offset] = dev_desc->touch_link; if (fwnode_property_present(sldr_node, "azoteq,use-prox")) sldr_setup[4 + reg_offset] -= 2; error = fwnode_property_read_u32(sldr_node, "azoteq,slider-size", &val); if (!error) { if (val > dev_desc->sldr_res) { dev_err(&client->dev, "Invalid %s size: %u\n", fwnode_get_name(sldr_node), val); return -EINVAL; } if (reg_offset) { sldr_setup[3] = val; } else { sldr_setup[2] &= ~IQS7222_SLDR_SETUP_2_RES_MASK; sldr_setup[2] |= (val / 16 << IQS7222_SLDR_SETUP_2_RES_SHIFT); } } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s size: %d\n", fwnode_get_name(sldr_node), error); return error; } if (!(reg_offset ? sldr_setup[3] : sldr_setup[2] & IQS7222_SLDR_SETUP_2_RES_MASK)) { dev_err(&client->dev, "Undefined %s size\n", fwnode_get_name(sldr_node)); return -EINVAL; } error = fwnode_property_read_u32(sldr_node, "azoteq,top-speed", &val); if (!error) { if (val > (reg_offset ? U16_MAX : U8_MAX * 4)) { dev_err(&client->dev, "Invalid %s top speed: %u\n", fwnode_get_name(sldr_node), val); return -EINVAL; } if (reg_offset) { sldr_setup[2] = val; } else { sldr_setup[2] &= ~IQS7222_SLDR_SETUP_2_TOP_SPEED_MASK; sldr_setup[2] |= (val / 4); } } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s top speed: %d\n", fwnode_get_name(sldr_node), error); return error; } error = fwnode_property_read_u32(sldr_node, "linux,axis", &val); if (!error) { u16 sldr_max = sldr_setup[3] - 1; if (!reg_offset) { sldr_max = sldr_setup[2]; sldr_max &= IQS7222_SLDR_SETUP_2_RES_MASK; sldr_max >>= IQS7222_SLDR_SETUP_2_RES_SHIFT; sldr_max = sldr_max * 16 - 1; } input_set_abs_params(iqs7222->keypad, val, 0, sldr_max, 0, 0); iqs7222->sl_axis[sldr_index] = val; } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s axis: %d\n", fwnode_get_name(sldr_node), error); return error; } if (dev_desc->wheel_enable) { sldr_setup[0] &= ~dev_desc->wheel_enable; if (iqs7222->sl_axis[sldr_index] == ABS_WHEEL) sldr_setup[0] |= dev_desc->wheel_enable; } /* * The absence of a register offset makes it safe to assume the device * supports gestures, each of which is first disabled until explicitly * enabled. */ if (!reg_offset) for (i = 0; i < ARRAY_SIZE(iqs7222_sl_events); i++) sldr_setup[9] &= ~iqs7222_sl_events[i].enable; for (i = 0; i < ARRAY_SIZE(iqs7222_sl_events); i++) { const char *event_name = iqs7222_sl_events[i].name; struct fwnode_handle *event_node; enum iqs7222_reg_key_id reg_key; event_node = fwnode_get_named_child_node(sldr_node, event_name); if (!event_node) continue; /* * Depending on the device, gestures are either offered using * one of two timing resolutions, or are not supported at all. */ if (reg_offset) reg_key = IQS7222_REG_KEY_RESERVED; else if (dev_desc->legacy_gesture && iqs7222_sl_events[i].reg_key == IQS7222_REG_KEY_TAP) reg_key = IQS7222_REG_KEY_TAP_LEGACY; else if (dev_desc->legacy_gesture && iqs7222_sl_events[i].reg_key == IQS7222_REG_KEY_AXIAL) reg_key = IQS7222_REG_KEY_AXIAL_LEGACY; else reg_key = iqs7222_sl_events[i].reg_key; /* * The press/release event does not expose a direct GPIO link, * but one can be emulated by tying each of the participating * channels to the same GPIO. */ error = iqs7222_parse_event(iqs7222, event_node, sldr_index, IQS7222_REG_GRP_SLDR, reg_key, i ? iqs7222_sl_events[i].enable : sldr_setup[3 + reg_offset], i ? 1568 + sldr_index * 30 : sldr_setup[4 + reg_offset], NULL, &iqs7222->sl_code[sldr_index][i]); fwnode_handle_put(event_node); if (error) return error; if (!reg_offset) sldr_setup[9] |= iqs7222_sl_events[i].enable; if (!dev_desc->event_offset) continue; /* * The press/release event is determined based on whether the * coordinate field reports 0xFFFF and solely relies on touch * or proximity interrupts to be unmasked. */ if (i && !reg_offset) *event_mask |= (IQS7222_EVENT_MASK_SLDR << sldr_index); else if (sldr_setup[4 + reg_offset] == dev_desc->touch_link) *event_mask |= IQS7222_EVENT_MASK_TOUCH; else *event_mask |= IQS7222_EVENT_MASK_PROX; } /* * The following call handles a special pair of properties that shift * to make room for a wheel enable control in the case of IQS7222C. */ return iqs7222_parse_props(iqs7222, sldr_node, sldr_index, IQS7222_REG_GRP_SLDR, dev_desc->wheel_enable ? IQS7222_REG_KEY_WHEEL : IQS7222_REG_KEY_NO_WHEEL); } static int iqs7222_parse_tpad(struct iqs7222_private *iqs7222, struct fwnode_handle *tpad_node, int tpad_index) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; struct touchscreen_properties *prop = &iqs7222->prop; struct i2c_client *client = iqs7222->client; int num_chan = dev_desc->reg_grps[IQS7222_REG_GRP_CHAN].num_row; int count, error, i; u16 *event_mask = &iqs7222->sys_setup[dev_desc->event_offset]; u16 *tpad_setup = iqs7222->tpad_setup; unsigned int chan_sel[12]; error = iqs7222_parse_props(iqs7222, tpad_node, tpad_index, IQS7222_REG_GRP_TPAD, IQS7222_REG_KEY_NONE); if (error) return error; count = fwnode_property_count_u32(tpad_node, "azoteq,channel-select"); if (count < 0) { dev_err(&client->dev, "Failed to count %s channels: %d\n", fwnode_get_name(tpad_node), count); return count; } else if (!count || count > ARRAY_SIZE(chan_sel)) { dev_err(&client->dev, "Invalid number of %s channels\n", fwnode_get_name(tpad_node)); return -EINVAL; } error = fwnode_property_read_u32_array(tpad_node, "azoteq,channel-select", chan_sel, count); if (error) { dev_err(&client->dev, "Failed to read %s channels: %d\n", fwnode_get_name(tpad_node), error); return error; } tpad_setup[6] &= ~GENMASK(num_chan - 1, 0); for (i = 0; i < ARRAY_SIZE(chan_sel); i++) { tpad_setup[8 + i] = 0; if (i >= count || chan_sel[i] == U8_MAX) continue; if (chan_sel[i] >= num_chan) { dev_err(&client->dev, "Invalid %s channel: %u\n", fwnode_get_name(tpad_node), chan_sel[i]); return -EINVAL; } /* * The following fields indicate which channels participate in * the trackpad, as well as each channel's relative placement. */ tpad_setup[6] |= BIT(chan_sel[i]); tpad_setup[8 + i] = chan_sel[i] * 34 + 1072; } tpad_setup[7] = dev_desc->touch_link; if (fwnode_property_present(tpad_node, "azoteq,use-prox")) tpad_setup[7] -= 2; for (i = 0; i < ARRAY_SIZE(iqs7222_tp_events); i++) tpad_setup[20] &= ~(iqs7222_tp_events[i].strict | iqs7222_tp_events[i].enable); for (i = 0; i < ARRAY_SIZE(iqs7222_tp_events); i++) { const char *event_name = iqs7222_tp_events[i].name; struct fwnode_handle *event_node; event_node = fwnode_get_named_child_node(tpad_node, event_name); if (!event_node) continue; if (fwnode_property_present(event_node, "azoteq,gesture-angle-tighten")) tpad_setup[20] |= iqs7222_tp_events[i].strict; tpad_setup[20] |= iqs7222_tp_events[i].enable; error = iqs7222_parse_event(iqs7222, event_node, tpad_index, IQS7222_REG_GRP_TPAD, iqs7222_tp_events[i].reg_key, iqs7222_tp_events[i].link, 1566, NULL, &iqs7222->tp_code[i]); fwnode_handle_put(event_node); if (error) return error; if (!dev_desc->event_offset) continue; /* * The press/release event is determined based on whether the * coordinate fields report 0xFFFF and solely relies on touch * or proximity interrupts to be unmasked. */ if (i) *event_mask |= IQS7222_EVENT_MASK_TPAD; else if (tpad_setup[7] == dev_desc->touch_link) *event_mask |= IQS7222_EVENT_MASK_TOUCH; else *event_mask |= IQS7222_EVENT_MASK_PROX; } if (!iqs7222->tp_code[0]) return 0; input_set_abs_params(iqs7222->keypad, ABS_X, 0, (tpad_setup[4] ? : 1) - 1, 0, 0); input_set_abs_params(iqs7222->keypad, ABS_Y, 0, (tpad_setup[5] ? : 1) - 1, 0, 0); touchscreen_parse_properties(iqs7222->keypad, false, prop); if (prop->max_x >= U16_MAX || prop->max_y >= U16_MAX) { dev_err(&client->dev, "Invalid trackpad size: %u*%u\n", prop->max_x, prop->max_y); return -EINVAL; } tpad_setup[4] = prop->max_x + 1; tpad_setup[5] = prop->max_y + 1; return 0; } static int (*iqs7222_parse_extra[IQS7222_NUM_REG_GRPS]) (struct iqs7222_private *iqs7222, struct fwnode_handle *reg_grp_node, int reg_grp_index) = { [IQS7222_REG_GRP_CYCLE] = iqs7222_parse_cycle, [IQS7222_REG_GRP_CHAN] = iqs7222_parse_chan, [IQS7222_REG_GRP_SLDR] = iqs7222_parse_sldr, [IQS7222_REG_GRP_TPAD] = iqs7222_parse_tpad, }; static int iqs7222_parse_reg_grp(struct iqs7222_private *iqs7222, enum iqs7222_reg_grp_id reg_grp, int reg_grp_index) { struct i2c_client *client = iqs7222->client; struct fwnode_handle *reg_grp_node; int error; if (iqs7222_reg_grp_names[reg_grp]) { char reg_grp_name[16]; snprintf(reg_grp_name, sizeof(reg_grp_name), iqs7222_reg_grp_names[reg_grp], reg_grp_index); reg_grp_node = device_get_named_child_node(&client->dev, reg_grp_name); } else { reg_grp_node = fwnode_handle_get(dev_fwnode(&client->dev)); } if (!reg_grp_node) return 0; error = iqs7222_parse_props(iqs7222, reg_grp_node, reg_grp_index, reg_grp, IQS7222_REG_KEY_NONE); if (!error && iqs7222_parse_extra[reg_grp]) error = iqs7222_parse_extra[reg_grp](iqs7222, reg_grp_node, reg_grp_index); fwnode_handle_put(reg_grp_node); return error; } static int iqs7222_parse_all(struct iqs7222_private *iqs7222) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; const struct iqs7222_reg_grp_desc *reg_grps = dev_desc->reg_grps; u16 *sys_setup = iqs7222->sys_setup; int error, i, j; if (dev_desc->allow_offset) sys_setup[dev_desc->allow_offset] = U16_MAX; if (dev_desc->event_offset) sys_setup[dev_desc->event_offset] = IQS7222_EVENT_MASK_ATI; for (i = 0; i < reg_grps[IQS7222_REG_GRP_GPIO].num_row; i++) { u16 *gpio_setup = iqs7222->gpio_setup[i]; gpio_setup[0] &= ~IQS7222_GPIO_SETUP_0_GPIO_EN; gpio_setup[1] = 0; gpio_setup[2] = 0; if (reg_grps[IQS7222_REG_GRP_GPIO].num_row == 1) continue; /* * The IQS7222C and IQS7222D expose multiple GPIO and must be * informed as to which GPIO this group represents. */ for (j = 0; j < ARRAY_SIZE(iqs7222_gpio_links); j++) gpio_setup[0] &= ~BIT(iqs7222_gpio_links[j]); gpio_setup[0] |= BIT(iqs7222_gpio_links[i]); } for (i = 0; i < reg_grps[IQS7222_REG_GRP_CHAN].num_row; i++) { u16 *chan_setup = iqs7222->chan_setup[i]; chan_setup[0] &= ~IQS7222_CHAN_SETUP_0_REF_MODE_MASK; chan_setup[0] &= ~IQS7222_CHAN_SETUP_0_CHAN_EN; chan_setup[5] = 0; } for (i = 0; i < reg_grps[IQS7222_REG_GRP_SLDR].num_row; i++) { u16 *sldr_setup = iqs7222->sldr_setup[i]; sldr_setup[0] &= ~IQS7222_SLDR_SETUP_0_CHAN_CNT_MASK; } for (i = 0; i < IQS7222_NUM_REG_GRPS; i++) { for (j = 0; j < reg_grps[i].num_row; j++) { error = iqs7222_parse_reg_grp(iqs7222, i, j); if (error) return error; } } return 0; } static int iqs7222_report(struct iqs7222_private *iqs7222) { const struct iqs7222_dev_desc *dev_desc = iqs7222->dev_desc; struct i2c_client *client = iqs7222->client; int num_chan = dev_desc->reg_grps[IQS7222_REG_GRP_CHAN].num_row; int num_stat = dev_desc->reg_grps[IQS7222_REG_GRP_STAT].num_col; int error, i, j; __le16 status[IQS7222_MAX_COLS_STAT]; error = iqs7222_read_burst(iqs7222, IQS7222_SYS_STATUS, status, num_stat); if (error) return error; if (le16_to_cpu(status[0]) & IQS7222_SYS_STATUS_RESET) { dev_err(&client->dev, "Unexpected device reset\n"); return iqs7222_dev_init(iqs7222, WRITE); } if (le16_to_cpu(status[0]) & IQS7222_SYS_STATUS_ATI_ERROR) { dev_err(&client->dev, "Unexpected ATI error\n"); return iqs7222_ati_trigger(iqs7222); } if (le16_to_cpu(status[0]) & IQS7222_SYS_STATUS_ATI_ACTIVE) return 0; for (i = 0; i < num_chan; i++) { u16 *chan_setup = iqs7222->chan_setup[i]; if (!(chan_setup[0] & IQS7222_CHAN_SETUP_0_CHAN_EN)) continue; for (j = 0; j < ARRAY_SIZE(iqs7222_kp_events); j++) { /* * Proximity state begins at offset 2 and spills into * offset 3 for devices with more than 16 channels. * * Touch state begins at the first offset immediately * following proximity state. */ int k = 2 + j * (num_chan > 16 ? 2 : 1); u16 state = le16_to_cpu(status[k + i / 16]); if (!iqs7222->kp_type[i][j]) continue; input_event(iqs7222->keypad, iqs7222->kp_type[i][j], iqs7222->kp_code[i][j], !!(state & BIT(i % 16))); } } for (i = 0; i < dev_desc->reg_grps[IQS7222_REG_GRP_SLDR].num_row; i++) { u16 *sldr_setup = iqs7222->sldr_setup[i]; u16 sldr_pos = le16_to_cpu(status[4 + i]); u16 state = le16_to_cpu(status[6 + i]); if (!(sldr_setup[0] & IQS7222_SLDR_SETUP_0_CHAN_CNT_MASK)) continue; if (sldr_pos < dev_desc->sldr_res) input_report_abs(iqs7222->keypad, iqs7222->sl_axis[i], sldr_pos); input_report_key(iqs7222->keypad, iqs7222->sl_code[i][0], sldr_pos < dev_desc->sldr_res); /* * A maximum resolution indicates the device does not support * gestures, in which case the remaining fields are ignored. */ if (dev_desc->sldr_res == U16_MAX) continue; if (!(le16_to_cpu(status[1]) & IQS7222_EVENT_MASK_SLDR << i)) continue; /* * Skip the press/release event, as it does not have separate * status fields and is handled separately. */ for (j = 1; j < ARRAY_SIZE(iqs7222_sl_events); j++) { u16 mask = iqs7222_sl_events[j].mask; u16 val = iqs7222_sl_events[j].val; input_report_key(iqs7222->keypad, iqs7222->sl_code[i][j], (state & mask) == val); } input_sync(iqs7222->keypad); for (j = 1; j < ARRAY_SIZE(iqs7222_sl_events); j++) input_report_key(iqs7222->keypad, iqs7222->sl_code[i][j], 0); } for (i = 0; i < dev_desc->reg_grps[IQS7222_REG_GRP_TPAD].num_row; i++) { u16 tpad_pos_x = le16_to_cpu(status[4]); u16 tpad_pos_y = le16_to_cpu(status[5]); u16 state = le16_to_cpu(status[6]); input_report_key(iqs7222->keypad, iqs7222->tp_code[0], tpad_pos_x < U16_MAX); if (tpad_pos_x < U16_MAX) touchscreen_report_pos(iqs7222->keypad, &iqs7222->prop, tpad_pos_x, tpad_pos_y, false); if (!(le16_to_cpu(status[1]) & IQS7222_EVENT_MASK_TPAD)) continue; /* * Skip the press/release event, as it does not have separate * status fields and is handled separately. */ for (j = 1; j < ARRAY_SIZE(iqs7222_tp_events); j++) { u16 mask = iqs7222_tp_events[j].mask; u16 val = iqs7222_tp_events[j].val; input_report_key(iqs7222->keypad, iqs7222->tp_code[j], (state & mask) == val); } input_sync(iqs7222->keypad); for (j = 1; j < ARRAY_SIZE(iqs7222_tp_events); j++) input_report_key(iqs7222->keypad, iqs7222->tp_code[j], 0); } input_sync(iqs7222->keypad); return 0; } static irqreturn_t iqs7222_irq(int irq, void *context) { struct iqs7222_private *iqs7222 = context; return iqs7222_report(iqs7222) ? IRQ_NONE : IRQ_HANDLED; } static int iqs7222_probe(struct i2c_client *client) { struct iqs7222_private *iqs7222; unsigned long irq_flags; int error, irq; iqs7222 = devm_kzalloc(&client->dev, sizeof(*iqs7222), GFP_KERNEL); if (!iqs7222) return -ENOMEM; i2c_set_clientdata(client, iqs7222); iqs7222->client = client; iqs7222->keypad = devm_input_allocate_device(&client->dev); if (!iqs7222->keypad) return -ENOMEM; iqs7222->keypad->name = client->name; iqs7222->keypad->id.bustype = BUS_I2C; /* * The RDY pin behaves as an interrupt, but must also be polled ahead * of unsolicited I2C communication. As such, it is first opened as a * GPIO and then passed to gpiod_to_irq() to register the interrupt. */ iqs7222->irq_gpio = devm_gpiod_get(&client->dev, "irq", GPIOD_IN); if (IS_ERR(iqs7222->irq_gpio)) { error = PTR_ERR(iqs7222->irq_gpio); dev_err(&client->dev, "Failed to request IRQ GPIO: %d\n", error); return error; } iqs7222->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(iqs7222->reset_gpio)) { error = PTR_ERR(iqs7222->reset_gpio); dev_err(&client->dev, "Failed to request reset GPIO: %d\n", error); return error; } error = iqs7222_hard_reset(iqs7222); if (error) return error; error = iqs7222_dev_info(iqs7222); if (error) return error; error = iqs7222_dev_init(iqs7222, READ); if (error) return error; error = iqs7222_parse_all(iqs7222); if (error) return error; error = iqs7222_dev_init(iqs7222, WRITE); if (error) return error; error = iqs7222_report(iqs7222); if (error) return error; error = input_register_device(iqs7222->keypad); if (error) { dev_err(&client->dev, "Failed to register device: %d\n", error); return error; } irq = gpiod_to_irq(iqs7222->irq_gpio); if (irq < 0) return irq; irq_flags = gpiod_is_active_low(iqs7222->irq_gpio) ? IRQF_TRIGGER_LOW : IRQF_TRIGGER_HIGH; irq_flags |= IRQF_ONESHOT; error = devm_request_threaded_irq(&client->dev, irq, NULL, iqs7222_irq, irq_flags, client->name, iqs7222); if (error) dev_err(&client->dev, "Failed to request IRQ: %d\n", error); return error; } static const struct of_device_id iqs7222_of_match[] = { { .compatible = "azoteq,iqs7222a" }, { .compatible = "azoteq,iqs7222b" }, { .compatible = "azoteq,iqs7222c" }, { .compatible = "azoteq,iqs7222d" }, { } }; MODULE_DEVICE_TABLE(of, iqs7222_of_match); static struct i2c_driver iqs7222_i2c_driver = { .driver = { .name = "iqs7222", .of_match_table = iqs7222_of_match, }, .probe = iqs7222_probe, }; module_i2c_driver(iqs7222_i2c_driver); MODULE_AUTHOR("Jeff LaBundy <[email protected]>"); MODULE_DESCRIPTION("Azoteq IQS7222A/B/C/D Capacitive Touch Controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/misc/iqs7222.c
// SPDX-License-Identifier: GPL-2.0-only /* * VTI CMA3000_D0x Accelerometer driver * * Copyright (C) 2010 Texas Instruments * Author: Hemanth V <[email protected]> */ #include <linux/types.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/input/cma3000.h> #include <linux/module.h> #include "cma3000_d0x.h" #define CMA3000_WHOAMI 0x00 #define CMA3000_REVID 0x01 #define CMA3000_CTRL 0x02 #define CMA3000_STATUS 0x03 #define CMA3000_RSTR 0x04 #define CMA3000_INTSTATUS 0x05 #define CMA3000_DOUTX 0x06 #define CMA3000_DOUTY 0x07 #define CMA3000_DOUTZ 0x08 #define CMA3000_MDTHR 0x09 #define CMA3000_MDFFTMR 0x0A #define CMA3000_FFTHR 0x0B #define CMA3000_RANGE2G (1 << 7) #define CMA3000_RANGE8G (0 << 7) #define CMA3000_BUSI2C (0 << 4) #define CMA3000_MODEMASK (7 << 1) #define CMA3000_GRANGEMASK (1 << 7) #define CMA3000_STATUS_PERR 1 #define CMA3000_INTSTATUS_FFDET (1 << 2) /* Settling time delay in ms */ #define CMA3000_SETDELAY 30 /* Delay for clearing interrupt in us */ #define CMA3000_INTDELAY 44 /* * Bit weights in mg for bit 0, other bits need * multiply factor 2^n. Eight bit is the sign bit. */ #define BIT_TO_2G 18 #define BIT_TO_8G 71 struct cma3000_accl_data { const struct cma3000_bus_ops *bus_ops; const struct cma3000_platform_data *pdata; struct device *dev; struct input_dev *input_dev; int bit_to_mg; int irq; int g_range; u8 mode; struct mutex mutex; bool opened; bool suspended; }; #define CMA3000_READ(data, reg, msg) \ (data->bus_ops->read(data->dev, reg, msg)) #define CMA3000_SET(data, reg, val, msg) \ ((data)->bus_ops->write(data->dev, reg, val, msg)) /* * Conversion for each of the eight modes to g, depending * on G range i.e 2G or 8G. Some modes always operate in * 8G. */ static int mode_to_mg[8][2] = { { 0, 0 }, { BIT_TO_8G, BIT_TO_2G }, { BIT_TO_8G, BIT_TO_2G }, { BIT_TO_8G, BIT_TO_8G }, { BIT_TO_8G, BIT_TO_8G }, { BIT_TO_8G, BIT_TO_2G }, { BIT_TO_8G, BIT_TO_2G }, { 0, 0}, }; static void decode_mg(struct cma3000_accl_data *data, int *datax, int *datay, int *dataz) { /* Data in 2's complement, convert to mg */ *datax = ((s8)*datax) * data->bit_to_mg; *datay = ((s8)*datay) * data->bit_to_mg; *dataz = ((s8)*dataz) * data->bit_to_mg; } static irqreturn_t cma3000_thread_irq(int irq, void *dev_id) { struct cma3000_accl_data *data = dev_id; int datax, datay, dataz, intr_status; u8 ctrl, mode, range; intr_status = CMA3000_READ(data, CMA3000_INTSTATUS, "interrupt status"); if (intr_status < 0) return IRQ_NONE; /* Check if free fall is detected, report immediately */ if (intr_status & CMA3000_INTSTATUS_FFDET) { input_report_abs(data->input_dev, ABS_MISC, 1); input_sync(data->input_dev); } else { input_report_abs(data->input_dev, ABS_MISC, 0); } datax = CMA3000_READ(data, CMA3000_DOUTX, "X"); datay = CMA3000_READ(data, CMA3000_DOUTY, "Y"); dataz = CMA3000_READ(data, CMA3000_DOUTZ, "Z"); ctrl = CMA3000_READ(data, CMA3000_CTRL, "ctrl"); mode = (ctrl & CMA3000_MODEMASK) >> 1; range = (ctrl & CMA3000_GRANGEMASK) >> 7; data->bit_to_mg = mode_to_mg[mode][range]; /* Interrupt not for this device */ if (data->bit_to_mg == 0) return IRQ_NONE; /* Decode register values to milli g */ decode_mg(data, &datax, &datay, &dataz); input_report_abs(data->input_dev, ABS_X, datax); input_report_abs(data->input_dev, ABS_Y, datay); input_report_abs(data->input_dev, ABS_Z, dataz); input_sync(data->input_dev); return IRQ_HANDLED; } static int cma3000_reset(struct cma3000_accl_data *data) { int val; /* Reset sequence */ CMA3000_SET(data, CMA3000_RSTR, 0x02, "Reset"); CMA3000_SET(data, CMA3000_RSTR, 0x0A, "Reset"); CMA3000_SET(data, CMA3000_RSTR, 0x04, "Reset"); /* Settling time delay */ mdelay(10); val = CMA3000_READ(data, CMA3000_STATUS, "Status"); if (val < 0) { dev_err(data->dev, "Reset failed\n"); return val; } if (val & CMA3000_STATUS_PERR) { dev_err(data->dev, "Parity Error\n"); return -EIO; } return 0; } static int cma3000_poweron(struct cma3000_accl_data *data) { const struct cma3000_platform_data *pdata = data->pdata; u8 ctrl = 0; int ret; if (data->g_range == CMARANGE_2G) { ctrl = (data->mode << 1) | CMA3000_RANGE2G; } else if (data->g_range == CMARANGE_8G) { ctrl = (data->mode << 1) | CMA3000_RANGE8G; } else { dev_info(data->dev, "Invalid G range specified, assuming 8G\n"); ctrl = (data->mode << 1) | CMA3000_RANGE8G; } ctrl |= data->bus_ops->ctrl_mod; CMA3000_SET(data, CMA3000_MDTHR, pdata->mdthr, "Motion Detect Threshold"); CMA3000_SET(data, CMA3000_MDFFTMR, pdata->mdfftmr, "Time register"); CMA3000_SET(data, CMA3000_FFTHR, pdata->ffthr, "Free fall threshold"); ret = CMA3000_SET(data, CMA3000_CTRL, ctrl, "Mode setting"); if (ret < 0) return -EIO; msleep(CMA3000_SETDELAY); return 0; } static int cma3000_poweroff(struct cma3000_accl_data *data) { int ret; ret = CMA3000_SET(data, CMA3000_CTRL, CMAMODE_POFF, "Mode setting"); msleep(CMA3000_SETDELAY); return ret; } static int cma3000_open(struct input_dev *input_dev) { struct cma3000_accl_data *data = input_get_drvdata(input_dev); mutex_lock(&data->mutex); if (!data->suspended) cma3000_poweron(data); data->opened = true; mutex_unlock(&data->mutex); return 0; } static void cma3000_close(struct input_dev *input_dev) { struct cma3000_accl_data *data = input_get_drvdata(input_dev); mutex_lock(&data->mutex); if (!data->suspended) cma3000_poweroff(data); data->opened = false; mutex_unlock(&data->mutex); } void cma3000_suspend(struct cma3000_accl_data *data) { mutex_lock(&data->mutex); if (!data->suspended && data->opened) cma3000_poweroff(data); data->suspended = true; mutex_unlock(&data->mutex); } EXPORT_SYMBOL(cma3000_suspend); void cma3000_resume(struct cma3000_accl_data *data) { mutex_lock(&data->mutex); if (data->suspended && data->opened) cma3000_poweron(data); data->suspended = false; mutex_unlock(&data->mutex); } EXPORT_SYMBOL(cma3000_resume); struct cma3000_accl_data *cma3000_init(struct device *dev, int irq, const struct cma3000_bus_ops *bops) { const struct cma3000_platform_data *pdata = dev_get_platdata(dev); struct cma3000_accl_data *data; struct input_dev *input_dev; int rev; int error; if (!pdata) { dev_err(dev, "platform data not found\n"); error = -EINVAL; goto err_out; } /* if no IRQ return error */ if (irq == 0) { error = -EINVAL; goto err_out; } data = kzalloc(sizeof(struct cma3000_accl_data), GFP_KERNEL); input_dev = input_allocate_device(); if (!data || !input_dev) { error = -ENOMEM; goto err_free_mem; } data->dev = dev; data->input_dev = input_dev; data->bus_ops = bops; data->pdata = pdata; data->irq = irq; mutex_init(&data->mutex); data->mode = pdata->mode; if (data->mode > CMAMODE_POFF) { data->mode = CMAMODE_MOTDET; dev_warn(dev, "Invalid mode specified, assuming Motion Detect\n"); } data->g_range = pdata->g_range; if (data->g_range != CMARANGE_2G && data->g_range != CMARANGE_8G) { dev_info(dev, "Invalid G range specified, assuming 8G\n"); data->g_range = CMARANGE_8G; } input_dev->name = "cma3000-accelerometer"; input_dev->id.bustype = bops->bustype; input_dev->open = cma3000_open; input_dev->close = cma3000_close; input_set_abs_params(input_dev, ABS_X, -data->g_range, data->g_range, pdata->fuzz_x, 0); input_set_abs_params(input_dev, ABS_Y, -data->g_range, data->g_range, pdata->fuzz_y, 0); input_set_abs_params(input_dev, ABS_Z, -data->g_range, data->g_range, pdata->fuzz_z, 0); input_set_abs_params(input_dev, ABS_MISC, 0, 1, 0, 0); input_set_drvdata(input_dev, data); error = cma3000_reset(data); if (error) goto err_free_mem; rev = CMA3000_READ(data, CMA3000_REVID, "Revid"); if (rev < 0) { error = rev; goto err_free_mem; } pr_info("CMA3000 Accelerometer: Revision %x\n", rev); error = request_threaded_irq(irq, NULL, cma3000_thread_irq, pdata->irqflags | IRQF_ONESHOT, "cma3000_d0x", data); if (error) { dev_err(dev, "request_threaded_irq failed\n"); goto err_free_mem; } error = input_register_device(data->input_dev); if (error) { dev_err(dev, "Unable to register input device\n"); goto err_free_irq; } return data; err_free_irq: free_irq(irq, data); err_free_mem: input_free_device(input_dev); kfree(data); err_out: return ERR_PTR(error); } EXPORT_SYMBOL(cma3000_init); void cma3000_exit(struct cma3000_accl_data *data) { free_irq(data->irq, data); input_unregister_device(data->input_dev); kfree(data); } EXPORT_SYMBOL(cma3000_exit); MODULE_DESCRIPTION("CMA3000-D0x Accelerometer Driver"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Hemanth V <[email protected]>");
linux-master
drivers/input/misc/cma3000_d0x.c
// SPDX-License-Identifier: GPL-2.0-only /* * Wistron laptop button driver * Copyright (C) 2005 Miloslav Trmac <[email protected]> * Copyright (C) 2005 Bernhard Rosenkraenzer <[email protected]> * Copyright (C) 2005 Dmitry Torokhov <[email protected]> */ #include <linux/io.h> #include <linux/dmi.h> #include <linux/init.h> #include <linux/input.h> #include <linux/input/sparse-keymap.h> #include <linux/interrupt.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/mc146818rtc.h> #include <linux/module.h> #include <linux/preempt.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/platform_device.h> #include <linux/leds.h> /* How often we poll keys - msecs */ #define POLL_INTERVAL_DEFAULT 500 /* when idle */ #define POLL_INTERVAL_BURST 100 /* when a key was recently pressed */ /* BIOS subsystem IDs */ #define WIFI 0x35 #define BLUETOOTH 0x34 #define MAIL_LED 0x31 MODULE_AUTHOR("Miloslav Trmac <[email protected]>"); MODULE_DESCRIPTION("Wistron laptop button driver"); MODULE_LICENSE("GPL v2"); static bool force; /* = 0; */ module_param(force, bool, 0); MODULE_PARM_DESC(force, "Load even if computer is not in database"); static char *keymap_name; /* = NULL; */ module_param_named(keymap, keymap_name, charp, 0); MODULE_PARM_DESC(keymap, "Keymap name, if it can't be autodetected [generic, 1557/MS2141]"); static struct platform_device *wistron_device; /* BIOS interface implementation */ static void __iomem *bios_entry_point; /* BIOS routine entry point */ static void __iomem *bios_code_map_base; static void __iomem *bios_data_map_base; static u8 cmos_address; struct regs { u32 eax, ebx, ecx; }; static void call_bios(struct regs *regs) { unsigned long flags; preempt_disable(); local_irq_save(flags); asm volatile ("pushl %%ebp;" "movl %7, %%ebp;" "call *%6;" "popl %%ebp" : "=a" (regs->eax), "=b" (regs->ebx), "=c" (regs->ecx) : "0" (regs->eax), "1" (regs->ebx), "2" (regs->ecx), "m" (bios_entry_point), "m" (bios_data_map_base) : "edx", "edi", "esi", "memory"); local_irq_restore(flags); preempt_enable(); } static ssize_t __init locate_wistron_bios(void __iomem *base) { static unsigned char __initdata signature[] = { 0x42, 0x21, 0x55, 0x30 }; ssize_t offset; for (offset = 0; offset < 0x10000; offset += 0x10) { if (check_signature(base + offset, signature, sizeof(signature)) != 0) return offset; } return -1; } static int __init map_bios(void) { void __iomem *base; ssize_t offset; u32 entry_point; base = ioremap(0xF0000, 0x10000); /* Can't fail */ offset = locate_wistron_bios(base); if (offset < 0) { printk(KERN_ERR "wistron_btns: BIOS entry point not found\n"); iounmap(base); return -ENODEV; } entry_point = readl(base + offset + 5); printk(KERN_DEBUG "wistron_btns: BIOS signature found at %p, entry point %08X\n", base + offset, entry_point); if (entry_point >= 0xF0000) { bios_code_map_base = base; bios_entry_point = bios_code_map_base + (entry_point & 0xFFFF); } else { iounmap(base); bios_code_map_base = ioremap(entry_point & ~0x3FFF, 0x4000); if (bios_code_map_base == NULL) { printk(KERN_ERR "wistron_btns: Can't map BIOS code at %08X\n", entry_point & ~0x3FFF); goto err; } bios_entry_point = bios_code_map_base + (entry_point & 0x3FFF); } /* The Windows driver maps 0x10000 bytes, we keep only one page... */ bios_data_map_base = ioremap(0x400, 0xc00); if (bios_data_map_base == NULL) { printk(KERN_ERR "wistron_btns: Can't map BIOS data\n"); goto err_code; } return 0; err_code: iounmap(bios_code_map_base); err: return -ENOMEM; } static inline void unmap_bios(void) { iounmap(bios_code_map_base); iounmap(bios_data_map_base); } /* BIOS calls */ static u16 bios_pop_queue(void) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = 0x061C; regs.ecx = 0x0000; call_bios(&regs); return regs.eax; } static void bios_attach(void) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = 0x012E; call_bios(&regs); } static void bios_detach(void) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = 0x002E; call_bios(&regs); } static u8 bios_get_cmos_address(void) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = 0x051C; call_bios(&regs); return regs.ecx; } static u16 bios_get_default_setting(u8 subsys) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = 0x0200 | subsys; call_bios(&regs); return regs.eax; } static void bios_set_state(u8 subsys, int enable) { struct regs regs; memset(&regs, 0, sizeof (regs)); regs.eax = 0x9610; regs.ebx = (enable ? 0x0100 : 0x0000) | subsys; call_bios(&regs); } /* Hardware database */ #define KE_WIFI (KE_LAST + 1) #define KE_BLUETOOTH (KE_LAST + 2) #define FE_MAIL_LED 0x01 #define FE_WIFI_LED 0x02 #define FE_UNTESTED 0x80 static struct key_entry *keymap; /* = NULL; Current key map */ static bool have_wifi; static bool have_bluetooth; static int leds_present; /* bitmask of leds present */ static int __init dmi_matched(const struct dmi_system_id *dmi) { const struct key_entry *key; keymap = dmi->driver_data; for (key = keymap; key->type != KE_END; key++) { if (key->type == KE_WIFI) have_wifi = true; else if (key->type == KE_BLUETOOTH) have_bluetooth = true; } leds_present = key->code & (FE_MAIL_LED | FE_WIFI_LED); return 1; } static struct key_entry keymap_empty[] __initdata = { { KE_END, 0 } }; static struct key_entry keymap_fs_amilo_pro_v2000[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, 0 } }; static struct key_entry keymap_fs_amilo_pro_v3505[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, /* Fn+F1 */ { KE_KEY, 0x06, {KEY_DISPLAYTOGGLE} }, /* Fn+F4 */ { KE_BLUETOOTH, 0x30 }, /* Fn+F10 */ { KE_KEY, 0x31, {KEY_MAIL} }, /* mail button */ { KE_KEY, 0x36, {KEY_WWW} }, /* www button */ { KE_WIFI, 0x78 }, /* satellite dish button */ { KE_END, 0 } }; static struct key_entry keymap_fs_amilo_pro_v8210[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, /* Fn+F1 */ { KE_KEY, 0x06, {KEY_DISPLAYTOGGLE} }, /* Fn+F4 */ { KE_BLUETOOTH, 0x30 }, /* Fn+F10 */ { KE_KEY, 0x31, {KEY_MAIL} }, /* mail button */ { KE_KEY, 0x36, {KEY_WWW} }, /* www button */ { KE_WIFI, 0x78 }, /* satelite dish button */ { KE_END, FE_WIFI_LED } }; static struct key_entry keymap_fujitsu_n3510[] __initdata = { { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x71, {KEY_STOPCD} }, { KE_KEY, 0x72, {KEY_PLAYPAUSE} }, { KE_KEY, 0x74, {KEY_REWIND} }, { KE_KEY, 0x78, {KEY_FORWARD} }, { KE_END, 0 } }; static struct key_entry keymap_wistron_ms2111[] __initdata = { { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, FE_MAIL_LED } }; static struct key_entry keymap_wistron_md40100[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x37, {KEY_DISPLAYTOGGLE} }, /* Display on/off */ { KE_END, FE_MAIL_LED | FE_WIFI_LED | FE_UNTESTED } }; static struct key_entry keymap_wistron_ms2141[] __initdata = { { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x22, {KEY_REWIND} }, { KE_KEY, 0x23, {KEY_FORWARD} }, { KE_KEY, 0x24, {KEY_PLAYPAUSE} }, { KE_KEY, 0x25, {KEY_STOPCD} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, 0 } }; static struct key_entry keymap_acer_aspire_1500[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x49, {KEY_CONFIG} }, { KE_BLUETOOTH, 0x44 }, { KE_END, FE_UNTESTED } }; static struct key_entry keymap_acer_aspire_1600[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x49, {KEY_CONFIG} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; /* 3020 has been tested */ static struct key_entry keymap_acer_aspire_5020[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x05, {KEY_SWITCHVIDEOMODE} }, /* Display selection */ { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x6a, {KEY_CONFIG} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_2410[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x6d, {KEY_POWER} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x6a, {KEY_CONFIG} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_110[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x20, {KEY_VOLUMEUP} }, { KE_KEY, 0x21, {KEY_VOLUMEDOWN} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_SW, 0x4a, {.sw = {SW_LID, 1}} }, /* lid close */ { KE_SW, 0x4b, {.sw = {SW_LID, 0}} }, /* lid open */ { KE_WIFI, 0x30 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_300[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x20, {KEY_VOLUMEUP} }, { KE_KEY, 0x21, {KEY_VOLUMEDOWN} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_380[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, /* not 370 */ { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_WIFI, 0x30 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; /* unusual map */ static struct key_entry keymap_acer_travelmate_220[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_MAIL} }, { KE_KEY, 0x12, {KEY_WWW} }, { KE_KEY, 0x13, {KEY_PROG2} }, { KE_KEY, 0x31, {KEY_PROG1} }, { KE_END, FE_WIFI_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_230[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, FE_WIFI_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_240[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_BLUETOOTH, 0x44 }, { KE_WIFI, 0x30 }, { KE_END, FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_350[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_MAIL} }, { KE_KEY, 0x14, {KEY_PROG3} }, { KE_KEY, 0x15, {KEY_WWW} }, { KE_END, FE_MAIL_LED | FE_WIFI_LED | FE_UNTESTED } }; static struct key_entry keymap_acer_travelmate_360[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_MAIL} }, { KE_KEY, 0x14, {KEY_PROG3} }, { KE_KEY, 0x15, {KEY_WWW} }, { KE_KEY, 0x40, {KEY_WLAN} }, { KE_END, FE_WIFI_LED | FE_UNTESTED } /* no mail led */ }; /* Wifi subsystem only activates the led. Therefore we need to pass * wifi event as a normal key, then userspace can really change the wifi state. * TODO we need to export led state to userspace (wifi and mail) */ static struct key_entry keymap_acer_travelmate_610[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x14, {KEY_MAIL} }, { KE_KEY, 0x15, {KEY_WWW} }, { KE_KEY, 0x40, {KEY_WLAN} }, { KE_END, FE_MAIL_LED | FE_WIFI_LED } }; static struct key_entry keymap_acer_travelmate_630[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x08, {KEY_MUTE} }, /* not 620 */ { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x20, {KEY_VOLUMEUP} }, { KE_KEY, 0x21, {KEY_VOLUMEDOWN} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_WIFI, 0x30 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_aopen_1559as[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x06, {KEY_PROG3} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, 0 }, }; static struct key_entry keymap_fs_amilo_d88x0[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_END, FE_MAIL_LED | FE_WIFI_LED | FE_UNTESTED } }; static struct key_entry keymap_wistron_md2900[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_WIFI, 0x30 }, { KE_END, FE_MAIL_LED | FE_UNTESTED } }; static struct key_entry keymap_wistron_md96500[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x05, {KEY_SWITCHVIDEOMODE} }, /* Display selection */ { KE_KEY, 0x06, {KEY_DISPLAYTOGGLE} }, /* Display on/off */ { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x20, {KEY_VOLUMEUP} }, { KE_KEY, 0x21, {KEY_VOLUMEDOWN} }, { KE_KEY, 0x22, {KEY_REWIND} }, { KE_KEY, 0x23, {KEY_FORWARD} }, { KE_KEY, 0x24, {KEY_PLAYPAUSE} }, { KE_KEY, 0x25, {KEY_STOPCD} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, 0 } }; static struct key_entry keymap_wistron_generic[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x02, {KEY_CONFIG} }, { KE_KEY, 0x03, {KEY_POWER} }, { KE_KEY, 0x05, {KEY_SWITCHVIDEOMODE} }, /* Display selection */ { KE_KEY, 0x06, {KEY_DISPLAYTOGGLE} }, /* Display on/off */ { KE_KEY, 0x08, {KEY_MUTE} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_KEY, 0x13, {KEY_PROG3} }, { KE_KEY, 0x14, {KEY_MAIL} }, { KE_KEY, 0x15, {KEY_WWW} }, { KE_KEY, 0x20, {KEY_VOLUMEUP} }, { KE_KEY, 0x21, {KEY_VOLUMEDOWN} }, { KE_KEY, 0x22, {KEY_REWIND} }, { KE_KEY, 0x23, {KEY_FORWARD} }, { KE_KEY, 0x24, {KEY_PLAYPAUSE} }, { KE_KEY, 0x25, {KEY_STOPCD} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_KEY, 0x37, {KEY_DISPLAYTOGGLE} }, /* Display on/off */ { KE_KEY, 0x40, {KEY_WLAN} }, { KE_KEY, 0x49, {KEY_CONFIG} }, { KE_SW, 0x4a, {.sw = {SW_LID, 1}} }, /* lid close */ { KE_SW, 0x4b, {.sw = {SW_LID, 0}} }, /* lid open */ { KE_KEY, 0x6a, {KEY_CONFIG} }, { KE_KEY, 0x6d, {KEY_POWER} }, { KE_KEY, 0x71, {KEY_STOPCD} }, { KE_KEY, 0x72, {KEY_PLAYPAUSE} }, { KE_KEY, 0x74, {KEY_REWIND} }, { KE_KEY, 0x78, {KEY_FORWARD} }, { KE_WIFI, 0x30 }, { KE_BLUETOOTH, 0x44 }, { KE_END, 0 } }; static struct key_entry keymap_aopen_1557[] __initdata = { { KE_KEY, 0x01, {KEY_HELP} }, { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x22, {KEY_REWIND} }, { KE_KEY, 0x23, {KEY_FORWARD} }, { KE_KEY, 0x24, {KEY_PLAYPAUSE} }, { KE_KEY, 0x25, {KEY_STOPCD} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, 0 } }; static struct key_entry keymap_prestigio[] __initdata = { { KE_KEY, 0x11, {KEY_PROG1} }, { KE_KEY, 0x12, {KEY_PROG2} }, { KE_WIFI, 0x30 }, { KE_KEY, 0x22, {KEY_REWIND} }, { KE_KEY, 0x23, {KEY_FORWARD} }, { KE_KEY, 0x24, {KEY_PLAYPAUSE} }, { KE_KEY, 0x25, {KEY_STOPCD} }, { KE_KEY, 0x31, {KEY_MAIL} }, { KE_KEY, 0x36, {KEY_WWW} }, { KE_END, 0 } }; /* * If your machine is not here (which is currently rather likely), please send * a list of buttons and their key codes (reported when loading this module * with force=1) and the output of dmidecode to $MODULE_AUTHOR. */ static const struct dmi_system_id dmi_ids[] __initconst = { { /* Fujitsu-Siemens Amilo Pro V2000 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pro V2000"), }, .driver_data = keymap_fs_amilo_pro_v2000 }, { /* Fujitsu-Siemens Amilo Pro Edition V3505 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pro Edition V3505"), }, .driver_data = keymap_fs_amilo_pro_v3505 }, { /* Fujitsu-Siemens Amilo Pro Edition V8210 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pro Series V8210"), }, .driver_data = keymap_fs_amilo_pro_v8210 }, { /* Fujitsu-Siemens Amilo M7400 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), DMI_MATCH(DMI_PRODUCT_NAME, "AMILO M "), }, .driver_data = keymap_fs_amilo_pro_v2000 }, { /* Maxdata Pro 7000 DX */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MAXDATA"), DMI_MATCH(DMI_PRODUCT_NAME, "Pro 7000"), }, .driver_data = keymap_fs_amilo_pro_v2000 }, { /* Fujitsu N3510 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"), DMI_MATCH(DMI_PRODUCT_NAME, "N3510"), }, .driver_data = keymap_fujitsu_n3510 }, { /* Acer Aspire 1500 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 1500"), }, .driver_data = keymap_acer_aspire_1500 }, { /* Acer Aspire 1600 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 1600"), }, .driver_data = keymap_acer_aspire_1600 }, { /* Acer Aspire 3020 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 3020"), }, .driver_data = keymap_acer_aspire_5020 }, { /* Acer Aspire 5020 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 5020"), }, .driver_data = keymap_acer_aspire_5020 }, { /* Acer TravelMate 2100 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 2100"), }, .driver_data = keymap_acer_aspire_5020 }, { /* Acer TravelMate 2410 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 2410"), }, .driver_data = keymap_acer_travelmate_2410 }, { /* Acer TravelMate C300 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate C300"), }, .driver_data = keymap_acer_travelmate_300 }, { /* Acer TravelMate C100 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate C100"), }, .driver_data = keymap_acer_travelmate_300 }, { /* Acer TravelMate C110 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate C110"), }, .driver_data = keymap_acer_travelmate_110 }, { /* Acer TravelMate 380 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 380"), }, .driver_data = keymap_acer_travelmate_380 }, { /* Acer TravelMate 370 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 370"), }, .driver_data = keymap_acer_travelmate_380 /* keyboard minus 1 key */ }, { /* Acer TravelMate 220 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 220"), }, .driver_data = keymap_acer_travelmate_220 }, { /* Acer TravelMate 260 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 260"), }, .driver_data = keymap_acer_travelmate_220 }, { /* Acer TravelMate 230 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 230"), /* acerhk looks for "TravelMate F4..." ?! */ }, .driver_data = keymap_acer_travelmate_230 }, { /* Acer TravelMate 280 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 280"), }, .driver_data = keymap_acer_travelmate_230 }, { /* Acer TravelMate 240 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 240"), }, .driver_data = keymap_acer_travelmate_240 }, { /* Acer TravelMate 250 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 250"), }, .driver_data = keymap_acer_travelmate_240 }, { /* Acer TravelMate 2424NWXCi */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 2420"), }, .driver_data = keymap_acer_travelmate_240 }, { /* Acer TravelMate 350 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 350"), }, .driver_data = keymap_acer_travelmate_350 }, { /* Acer TravelMate 360 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 360"), }, .driver_data = keymap_acer_travelmate_360 }, { /* Acer TravelMate 610 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "ACER"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 610"), }, .driver_data = keymap_acer_travelmate_610 }, { /* Acer TravelMate 620 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 620"), }, .driver_data = keymap_acer_travelmate_630 }, { /* Acer TravelMate 630 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 630"), }, .driver_data = keymap_acer_travelmate_630 }, { /* AOpen 1559AS */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "E2U"), DMI_MATCH(DMI_BOARD_NAME, "E2U"), }, .driver_data = keymap_aopen_1559as }, { /* Medion MD 9783 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONNB"), DMI_MATCH(DMI_PRODUCT_NAME, "MD 9783"), }, .driver_data = keymap_wistron_ms2111 }, { /* Medion MD 40100 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONNB"), DMI_MATCH(DMI_PRODUCT_NAME, "WID2000"), }, .driver_data = keymap_wistron_md40100 }, { /* Medion MD 2900 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONNB"), DMI_MATCH(DMI_PRODUCT_NAME, "WIM 2000"), }, .driver_data = keymap_wistron_md2900 }, { /* Medion MD 42200 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Medion"), DMI_MATCH(DMI_PRODUCT_NAME, "WIM 2030"), }, .driver_data = keymap_fs_amilo_pro_v2000 }, { /* Medion MD 96500 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONPC"), DMI_MATCH(DMI_PRODUCT_NAME, "WIM 2040"), }, .driver_data = keymap_wistron_md96500 }, { /* Medion MD 95400 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONPC"), DMI_MATCH(DMI_PRODUCT_NAME, "WIM 2050"), }, .driver_data = keymap_wistron_md96500 }, { /* Fujitsu Siemens Amilo D7820 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), /* not sure */ DMI_MATCH(DMI_PRODUCT_NAME, "Amilo D"), }, .driver_data = keymap_fs_amilo_d88x0 }, { /* Fujitsu Siemens Amilo D88x0 */ .callback = dmi_matched, .matches = { DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"), DMI_MATCH(DMI_PRODUCT_NAME, "AMILO D"), }, .driver_data = keymap_fs_amilo_d88x0 }, { NULL, } }; MODULE_DEVICE_TABLE(dmi, dmi_ids); /* Copy the good keymap, as the original ones are free'd */ static int __init copy_keymap(void) { const struct key_entry *key; struct key_entry *new_keymap; unsigned int length = 1; for (key = keymap; key->type != KE_END; key++) length++; new_keymap = kmemdup(keymap, length * sizeof(struct key_entry), GFP_KERNEL); if (!new_keymap) return -ENOMEM; keymap = new_keymap; return 0; } static int __init select_keymap(void) { dmi_check_system(dmi_ids); if (keymap_name != NULL) { if (strcmp (keymap_name, "1557/MS2141") == 0) keymap = keymap_wistron_ms2141; else if (strcmp (keymap_name, "aopen1557") == 0) keymap = keymap_aopen_1557; else if (strcmp (keymap_name, "prestigio") == 0) keymap = keymap_prestigio; else if (strcmp (keymap_name, "generic") == 0) keymap = keymap_wistron_generic; else { printk(KERN_ERR "wistron_btns: Keymap unknown\n"); return -EINVAL; } } if (keymap == NULL) { if (!force) { printk(KERN_ERR "wistron_btns: System unknown\n"); return -ENODEV; } keymap = keymap_empty; } return copy_keymap(); } /* Input layer interface */ static struct input_dev *wistron_idev; static unsigned long jiffies_last_press; static bool wifi_enabled; static bool bluetooth_enabled; /* led management */ static void wistron_mail_led_set(struct led_classdev *led_cdev, enum led_brightness value) { bios_set_state(MAIL_LED, (value != LED_OFF) ? 1 : 0); } /* same as setting up wifi card, but for laptops on which the led is managed */ static void wistron_wifi_led_set(struct led_classdev *led_cdev, enum led_brightness value) { bios_set_state(WIFI, (value != LED_OFF) ? 1 : 0); } static struct led_classdev wistron_mail_led = { .name = "wistron:green:mail", .brightness_set = wistron_mail_led_set, }; static struct led_classdev wistron_wifi_led = { .name = "wistron:red:wifi", .brightness_set = wistron_wifi_led_set, }; static void wistron_led_init(struct device *parent) { if (leds_present & FE_WIFI_LED) { u16 wifi = bios_get_default_setting(WIFI); if (wifi & 1) { wistron_wifi_led.brightness = (wifi & 2) ? LED_FULL : LED_OFF; if (led_classdev_register(parent, &wistron_wifi_led)) leds_present &= ~FE_WIFI_LED; else bios_set_state(WIFI, wistron_wifi_led.brightness); } else leds_present &= ~FE_WIFI_LED; } if (leds_present & FE_MAIL_LED) { /* bios_get_default_setting(MAIL) always retuns 0, so just turn the led off */ wistron_mail_led.brightness = LED_OFF; if (led_classdev_register(parent, &wistron_mail_led)) leds_present &= ~FE_MAIL_LED; else bios_set_state(MAIL_LED, wistron_mail_led.brightness); } } static void wistron_led_remove(void) { if (leds_present & FE_MAIL_LED) led_classdev_unregister(&wistron_mail_led); if (leds_present & FE_WIFI_LED) led_classdev_unregister(&wistron_wifi_led); } static inline void wistron_led_suspend(void) { if (leds_present & FE_MAIL_LED) led_classdev_suspend(&wistron_mail_led); if (leds_present & FE_WIFI_LED) led_classdev_suspend(&wistron_wifi_led); } static inline void wistron_led_resume(void) { if (leds_present & FE_MAIL_LED) led_classdev_resume(&wistron_mail_led); if (leds_present & FE_WIFI_LED) led_classdev_resume(&wistron_wifi_led); } static void handle_key(u8 code) { const struct key_entry *key = sparse_keymap_entry_from_scancode(wistron_idev, code); if (key) { switch (key->type) { case KE_WIFI: if (have_wifi) { wifi_enabled = !wifi_enabled; bios_set_state(WIFI, wifi_enabled); } break; case KE_BLUETOOTH: if (have_bluetooth) { bluetooth_enabled = !bluetooth_enabled; bios_set_state(BLUETOOTH, bluetooth_enabled); } break; default: sparse_keymap_report_entry(wistron_idev, key, 1, true); break; } jiffies_last_press = jiffies; } else { printk(KERN_NOTICE "wistron_btns: Unknown key code %02X\n", code); } } static void poll_bios(bool discard) { u8 qlen; u16 val; for (;;) { qlen = CMOS_READ(cmos_address); if (qlen == 0) break; val = bios_pop_queue(); if (val != 0 && !discard) handle_key((u8)val); } } static int wistron_flush(struct input_dev *dev) { /* Flush stale event queue */ poll_bios(true); return 0; } static void wistron_poll(struct input_dev *dev) { poll_bios(false); /* Increase poll frequency if user is currently pressing keys (< 2s ago) */ if (time_before(jiffies, jiffies_last_press + 2 * HZ)) input_set_poll_interval(dev, POLL_INTERVAL_BURST); else input_set_poll_interval(dev, POLL_INTERVAL_DEFAULT); } static int wistron_setup_keymap(struct input_dev *dev, struct key_entry *entry) { switch (entry->type) { /* if wifi or bluetooth are not available, create normal keys */ case KE_WIFI: if (!have_wifi) { entry->type = KE_KEY; entry->keycode = KEY_WLAN; } break; case KE_BLUETOOTH: if (!have_bluetooth) { entry->type = KE_KEY; entry->keycode = KEY_BLUETOOTH; } break; case KE_END: if (entry->code & FE_UNTESTED) printk(KERN_WARNING "Untested laptop multimedia keys, " "please report success or failure to " "[email protected]\n"); break; } return 0; } static int setup_input_dev(void) { int error; wistron_idev = input_allocate_device(); if (!wistron_idev) return -ENOMEM; wistron_idev->name = "Wistron laptop buttons"; wistron_idev->phys = "wistron/input0"; wistron_idev->id.bustype = BUS_HOST; wistron_idev->dev.parent = &wistron_device->dev; wistron_idev->open = wistron_flush; error = sparse_keymap_setup(wistron_idev, keymap, wistron_setup_keymap); if (error) goto err_free_dev; error = input_setup_polling(wistron_idev, wistron_poll); if (error) goto err_free_dev; input_set_poll_interval(wistron_idev, POLL_INTERVAL_DEFAULT); error = input_register_device(wistron_idev); if (error) goto err_free_dev; return 0; err_free_dev: input_free_device(wistron_idev); return error; } /* Driver core */ static int wistron_probe(struct platform_device *dev) { int err; bios_attach(); cmos_address = bios_get_cmos_address(); if (have_wifi) { u16 wifi = bios_get_default_setting(WIFI); if (wifi & 1) wifi_enabled = wifi & 2; else have_wifi = 0; if (have_wifi) bios_set_state(WIFI, wifi_enabled); } if (have_bluetooth) { u16 bt = bios_get_default_setting(BLUETOOTH); if (bt & 1) bluetooth_enabled = bt & 2; else have_bluetooth = false; if (have_bluetooth) bios_set_state(BLUETOOTH, bluetooth_enabled); } wistron_led_init(&dev->dev); err = setup_input_dev(); if (err) { bios_detach(); return err; } return 0; } static int wistron_remove(struct platform_device *dev) { wistron_led_remove(); input_unregister_device(wistron_idev); bios_detach(); return 0; } static int wistron_suspend(struct device *dev) { if (have_wifi) bios_set_state(WIFI, 0); if (have_bluetooth) bios_set_state(BLUETOOTH, 0); wistron_led_suspend(); return 0; } static int wistron_resume(struct device *dev) { if (have_wifi) bios_set_state(WIFI, wifi_enabled); if (have_bluetooth) bios_set_state(BLUETOOTH, bluetooth_enabled); wistron_led_resume(); poll_bios(true); return 0; } static const struct dev_pm_ops wistron_pm_ops = { .suspend = wistron_suspend, .resume = wistron_resume, .poweroff = wistron_suspend, .restore = wistron_resume, }; static struct platform_driver wistron_driver = { .driver = { .name = "wistron-bios", .pm = pm_sleep_ptr(&wistron_pm_ops), }, .probe = wistron_probe, .remove = wistron_remove, }; static int __init wb_module_init(void) { int err; err = select_keymap(); if (err) return err; err = map_bios(); if (err) goto err_free_keymap; err = platform_driver_register(&wistron_driver); if (err) goto err_unmap_bios; wistron_device = platform_device_alloc("wistron-bios", -1); if (!wistron_device) { err = -ENOMEM; goto err_unregister_driver; } err = platform_device_add(wistron_device); if (err) goto err_free_device; return 0; err_free_device: platform_device_put(wistron_device); err_unregister_driver: platform_driver_unregister(&wistron_driver); err_unmap_bios: unmap_bios(); err_free_keymap: kfree(keymap); return err; } static void __exit wb_module_exit(void) { platform_device_unregister(wistron_device); platform_driver_unregister(&wistron_driver); unmap_bios(); kfree(keymap); } module_init(wb_module_init); module_exit(wb_module_exit);
linux-master
drivers/input/misc/wistron_btns.c
/* * HP i8042 SDC + MSM-58321 BBRTC driver. * * Copyright (c) 2001 Brian S. Julin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL"). * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * References: * System Device Controller Microprocessor Firmware Theory of Operation * for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2 * efirtc.c by Stephane Eranian/Hewlett Packard * */ #include <linux/hp_sdc.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/init.h> #include <linux/module.h> #include <linux/time.h> #include <linux/miscdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/poll.h> #include <linux/rtc.h> #include <linux/mutex.h> #include <linux/semaphore.h> MODULE_AUTHOR("Brian S. Julin <[email protected]>"); MODULE_DESCRIPTION("HP i8042 SDC + MSM-58321 RTC Driver"); MODULE_LICENSE("Dual BSD/GPL"); #define RTC_VERSION "1.10d" static unsigned long epoch = 2000; static struct semaphore i8042tregs; static void hp_sdc_rtc_isr (int irq, void *dev_id, uint8_t status, uint8_t data) { return; } static int hp_sdc_rtc_do_read_bbrtc (struct rtc_time *rtctm) { struct semaphore tsem; hp_sdc_transaction t; uint8_t tseq[91]; int i; i = 0; while (i < 91) { tseq[i++] = HP_SDC_ACT_DATAREG | HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN; tseq[i++] = 0x01; /* write i8042[0x70] */ tseq[i] = i / 7; /* BBRTC reg address */ i++; tseq[i++] = HP_SDC_CMD_DO_RTCR; /* Trigger command */ tseq[i++] = 2; /* expect 1 stat/dat pair back. */ i++; i++; /* buffer for stat/dat pair */ } tseq[84] |= HP_SDC_ACT_SEMAPHORE; t.endidx = 91; t.seq = tseq; t.act.semaphore = &tsem; sema_init(&tsem, 0); if (hp_sdc_enqueue_transaction(&t)) return -1; /* Put ourselves to sleep for results. */ if (WARN_ON(down_interruptible(&tsem))) return -1; /* Check for nonpresence of BBRTC */ if (!((tseq[83] | tseq[90] | tseq[69] | tseq[76] | tseq[55] | tseq[62] | tseq[34] | tseq[41] | tseq[20] | tseq[27] | tseq[6] | tseq[13]) & 0x0f)) return -1; memset(rtctm, 0, sizeof(struct rtc_time)); rtctm->tm_year = (tseq[83] & 0x0f) + (tseq[90] & 0x0f) * 10; rtctm->tm_mon = (tseq[69] & 0x0f) + (tseq[76] & 0x0f) * 10; rtctm->tm_mday = (tseq[55] & 0x0f) + (tseq[62] & 0x0f) * 10; rtctm->tm_wday = (tseq[48] & 0x0f); rtctm->tm_hour = (tseq[34] & 0x0f) + (tseq[41] & 0x0f) * 10; rtctm->tm_min = (tseq[20] & 0x0f) + (tseq[27] & 0x0f) * 10; rtctm->tm_sec = (tseq[6] & 0x0f) + (tseq[13] & 0x0f) * 10; return 0; } static int hp_sdc_rtc_read_bbrtc (struct rtc_time *rtctm) { struct rtc_time tm, tm_last; int i = 0; /* MSM-58321 has no read latch, so must read twice and compare. */ if (hp_sdc_rtc_do_read_bbrtc(&tm_last)) return -1; if (hp_sdc_rtc_do_read_bbrtc(&tm)) return -1; while (memcmp(&tm, &tm_last, sizeof(struct rtc_time))) { if (i++ > 4) return -1; memcpy(&tm_last, &tm, sizeof(struct rtc_time)); if (hp_sdc_rtc_do_read_bbrtc(&tm)) return -1; } memcpy(rtctm, &tm, sizeof(struct rtc_time)); return 0; } static int64_t hp_sdc_rtc_read_i8042timer (uint8_t loadcmd, int numreg) { hp_sdc_transaction t; uint8_t tseq[26] = { HP_SDC_ACT_PRECMD | HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN, 0, HP_SDC_CMD_READ_T1, 2, 0, 0, HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN, HP_SDC_CMD_READ_T2, 2, 0, 0, HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN, HP_SDC_CMD_READ_T3, 2, 0, 0, HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN, HP_SDC_CMD_READ_T4, 2, 0, 0, HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN, HP_SDC_CMD_READ_T5, 2, 0, 0 }; t.endidx = numreg * 5; tseq[1] = loadcmd; tseq[t.endidx - 4] |= HP_SDC_ACT_SEMAPHORE; /* numreg assumed > 1 */ t.seq = tseq; t.act.semaphore = &i8042tregs; /* Sleep if output regs in use. */ if (WARN_ON(down_interruptible(&i8042tregs))) return -1; if (hp_sdc_enqueue_transaction(&t)) { up(&i8042tregs); return -1; } /* Sleep until results come back. */ if (WARN_ON(down_interruptible(&i8042tregs))) return -1; up(&i8042tregs); return (tseq[5] | ((uint64_t)(tseq[10]) << 8) | ((uint64_t)(tseq[15]) << 16) | ((uint64_t)(tseq[20]) << 24) | ((uint64_t)(tseq[25]) << 32)); } /* Read the i8042 real-time clock */ static inline int hp_sdc_rtc_read_rt(struct timespec64 *res) { int64_t raw; uint32_t tenms; unsigned int days; raw = hp_sdc_rtc_read_i8042timer(HP_SDC_CMD_LOAD_RT, 5); if (raw < 0) return -1; tenms = (uint32_t)raw & 0xffffff; days = (unsigned int)(raw >> 24) & 0xffff; res->tv_nsec = (long)(tenms % 100) * 10000 * 1000; res->tv_sec = (tenms / 100) + (time64_t)days * 86400; return 0; } /* Read the i8042 fast handshake timer */ static inline int hp_sdc_rtc_read_fhs(struct timespec64 *res) { int64_t raw; unsigned int tenms; raw = hp_sdc_rtc_read_i8042timer(HP_SDC_CMD_LOAD_FHS, 2); if (raw < 0) return -1; tenms = (unsigned int)raw & 0xffff; res->tv_nsec = (long)(tenms % 100) * 10000 * 1000; res->tv_sec = (time64_t)(tenms / 100); return 0; } /* Read the i8042 match timer (a.k.a. alarm) */ static inline int hp_sdc_rtc_read_mt(struct timespec64 *res) { int64_t raw; uint32_t tenms; raw = hp_sdc_rtc_read_i8042timer(HP_SDC_CMD_LOAD_MT, 3); if (raw < 0) return -1; tenms = (uint32_t)raw & 0xffffff; res->tv_nsec = (long)(tenms % 100) * 10000 * 1000; res->tv_sec = (time64_t)(tenms / 100); return 0; } /* Read the i8042 delay timer */ static inline int hp_sdc_rtc_read_dt(struct timespec64 *res) { int64_t raw; uint32_t tenms; raw = hp_sdc_rtc_read_i8042timer(HP_SDC_CMD_LOAD_DT, 3); if (raw < 0) return -1; tenms = (uint32_t)raw & 0xffffff; res->tv_nsec = (long)(tenms % 100) * 10000 * 1000; res->tv_sec = (time64_t)(tenms / 100); return 0; } /* Read the i8042 cycle timer (a.k.a. periodic) */ static inline int hp_sdc_rtc_read_ct(struct timespec64 *res) { int64_t raw; uint32_t tenms; raw = hp_sdc_rtc_read_i8042timer(HP_SDC_CMD_LOAD_CT, 3); if (raw < 0) return -1; tenms = (uint32_t)raw & 0xffffff; res->tv_nsec = (long)(tenms % 100) * 10000 * 1000; res->tv_sec = (time64_t)(tenms / 100); return 0; } static int __maybe_unused hp_sdc_rtc_proc_show(struct seq_file *m, void *v) { #define YN(bit) ("no") #define NY(bit) ("yes") struct rtc_time tm; struct timespec64 tv; memset(&tm, 0, sizeof(struct rtc_time)); if (hp_sdc_rtc_read_bbrtc(&tm)) { seq_puts(m, "BBRTC\t\t: READ FAILED!\n"); } else { seq_printf(m, "rtc_time\t: %ptRt\n" "rtc_date\t: %ptRd\n" "rtc_epoch\t: %04lu\n", &tm, &tm, epoch); } if (hp_sdc_rtc_read_rt(&tv)) { seq_puts(m, "i8042 rtc\t: READ FAILED!\n"); } else { seq_printf(m, "i8042 rtc\t: %lld.%02ld seconds\n", (s64)tv.tv_sec, (long)tv.tv_nsec/1000000L); } if (hp_sdc_rtc_read_fhs(&tv)) { seq_puts(m, "handshake\t: READ FAILED!\n"); } else { seq_printf(m, "handshake\t: %lld.%02ld seconds\n", (s64)tv.tv_sec, (long)tv.tv_nsec/1000000L); } if (hp_sdc_rtc_read_mt(&tv)) { seq_puts(m, "alarm\t\t: READ FAILED!\n"); } else { seq_printf(m, "alarm\t\t: %lld.%02ld seconds\n", (s64)tv.tv_sec, (long)tv.tv_nsec/1000000L); } if (hp_sdc_rtc_read_dt(&tv)) { seq_puts(m, "delay\t\t: READ FAILED!\n"); } else { seq_printf(m, "delay\t\t: %lld.%02ld seconds\n", (s64)tv.tv_sec, (long)tv.tv_nsec/1000000L); } if (hp_sdc_rtc_read_ct(&tv)) { seq_puts(m, "periodic\t: READ FAILED!\n"); } else { seq_printf(m, "periodic\t: %lld.%02ld seconds\n", (s64)tv.tv_sec, (long)tv.tv_nsec/1000000L); } seq_printf(m, "DST_enable\t: %s\n" "BCD\t\t: %s\n" "24hr\t\t: %s\n" "square_wave\t: %s\n" "alarm_IRQ\t: %s\n" "update_IRQ\t: %s\n" "periodic_IRQ\t: %s\n" "periodic_freq\t: %ld\n" "batt_status\t: %s\n", YN(RTC_DST_EN), NY(RTC_DM_BINARY), YN(RTC_24H), YN(RTC_SQWE), YN(RTC_AIE), YN(RTC_UIE), YN(RTC_PIE), 1UL, 1 ? "okay" : "dead"); return 0; #undef YN #undef NY } static int __init hp_sdc_rtc_init(void) { int ret; #ifdef __mc68000__ if (!MACH_IS_HP300) return -ENODEV; #endif sema_init(&i8042tregs, 1); if ((ret = hp_sdc_request_timer_irq(&hp_sdc_rtc_isr))) return ret; proc_create_single("driver/rtc", 0, NULL, hp_sdc_rtc_proc_show); printk(KERN_INFO "HP i8042 SDC + MSM-58321 RTC support loaded " "(RTC v " RTC_VERSION ")\n"); return 0; } static void __exit hp_sdc_rtc_exit(void) { remove_proc_entry ("driver/rtc", NULL); hp_sdc_release_timer_irq(hp_sdc_rtc_isr); printk(KERN_INFO "HP i8042 SDC + MSM-58321 RTC support unloaded\n"); } module_init(hp_sdc_rtc_init); module_exit(hp_sdc_rtc_exit);
linux-master
drivers/input/misc/hp_sdc_rtc.c
// SPDX-License-Identifier: GPL-2.0+ /* * DA7280 Haptic device driver * * Copyright (c) 2020 Dialog Semiconductor. * Author: Roy Im <[email protected]> */ #include <linux/bitfield.h> #include <linux/bitops.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/pwm.h> #include <linux/regmap.h> #include <linux/workqueue.h> #include <linux/uaccess.h> /* Registers */ #define DA7280_IRQ_EVENT1 0x03 #define DA7280_IRQ_EVENT_WARNING_DIAG 0x04 #define DA7280_IRQ_EVENT_SEQ_DIAG 0x05 #define DA7280_IRQ_STATUS1 0x06 #define DA7280_IRQ_MASK1 0x07 #define DA7280_FRQ_LRA_PER_H 0x0A #define DA7280_FRQ_LRA_PER_L 0x0B #define DA7280_ACTUATOR1 0x0C #define DA7280_ACTUATOR2 0x0D #define DA7280_ACTUATOR3 0x0E #define DA7280_CALIB_V2I_H 0x0F #define DA7280_CALIB_V2I_L 0x10 #define DA7280_TOP_CFG1 0x13 #define DA7280_TOP_CFG2 0x14 #define DA7280_TOP_CFG4 0x16 #define DA7280_TOP_INT_CFG1 0x17 #define DA7280_TOP_CTL1 0x22 #define DA7280_TOP_CTL2 0x23 #define DA7280_SEQ_CTL2 0x28 #define DA7280_GPI_0_CTL 0x29 #define DA7280_GPI_1_CTL 0x2A #define DA7280_GPI_2_CTL 0x2B #define DA7280_MEM_CTL1 0x2C #define DA7280_MEM_CTL2 0x2D #define DA7280_TOP_CFG5 0x6E #define DA7280_IRQ_MASK2 0x83 #define DA7280_SNP_MEM_99 0xE7 /* Register field */ /* DA7280_IRQ_EVENT1 (Address 0x03) */ #define DA7280_E_SEQ_CONTINUE_MASK BIT(0) #define DA7280_E_UVLO_MASK BIT(1) #define DA7280_E_SEQ_DONE_MASK BIT(2) #define DA7280_E_OVERTEMP_CRIT_MASK BIT(3) #define DA7280_E_SEQ_FAULT_MASK BIT(4) #define DA7280_E_WARNING_MASK BIT(5) #define DA7280_E_ACTUATOR_FAULT_MASK BIT(6) #define DA7280_E_OC_FAULT_MASK BIT(7) /* DA7280_IRQ_EVENT_WARNING_DIAG (Address 0x04) */ #define DA7280_E_OVERTEMP_WARN_MASK BIT(3) #define DA7280_E_MEM_TYPE_MASK BIT(4) #define DA7280_E_LIM_DRIVE_ACC_MASK BIT(6) #define DA7280_E_LIM_DRIVE_MASK BIT(7) /* DA7280_IRQ_EVENT_PAT_DIAG (Address 0x05) */ #define DA7280_E_PWM_FAULT_MASK BIT(5) #define DA7280_E_MEM_FAULT_MASK BIT(6) #define DA7280_E_SEQ_ID_FAULT_MASK BIT(7) /* DA7280_IRQ_STATUS1 (Address 0x06) */ #define DA7280_STA_SEQ_CONTINUE_MASK BIT(0) #define DA7280_STA_UVLO_VBAT_OK_MASK BIT(1) #define DA7280_STA_SEQ_DONE_MASK BIT(2) #define DA7280_STA_OVERTEMP_CRIT_MASK BIT(3) #define DA7280_STA_SEQ_FAULT_MASK BIT(4) #define DA7280_STA_WARNING_MASK BIT(5) #define DA7280_STA_ACTUATOR_MASK BIT(6) #define DA7280_STA_OC_MASK BIT(7) /* DA7280_IRQ_MASK1 (Address 0x07) */ #define DA7280_SEQ_CONTINUE_M_MASK BIT(0) #define DA7280_E_UVLO_M_MASK BIT(1) #define DA7280_SEQ_DONE_M_MASK BIT(2) #define DA7280_OVERTEMP_CRIT_M_MASK BIT(3) #define DA7280_SEQ_FAULT_M_MASK BIT(4) #define DA7280_WARNING_M_MASK BIT(5) #define DA7280_ACTUATOR_M_MASK BIT(6) #define DA7280_OC_M_MASK BIT(7) /* DA7280_ACTUATOR3 (Address 0x0e) */ #define DA7280_IMAX_MASK GENMASK(4, 0) /* DA7280_TOP_CFG1 (Address 0x13) */ #define DA7280_AMP_PID_EN_MASK BIT(0) #define DA7280_RAPID_STOP_EN_MASK BIT(1) #define DA7280_ACCELERATION_EN_MASK BIT(2) #define DA7280_FREQ_TRACK_EN_MASK BIT(3) #define DA7280_BEMF_SENSE_EN_MASK BIT(4) #define DA7280_ACTUATOR_TYPE_MASK BIT(5) /* DA7280_TOP_CFG2 (Address 0x14) */ #define DA7280_FULL_BRAKE_THR_MASK GENMASK(3, 0) #define DA7280_MEM_DATA_SIGNED_MASK BIT(4) /* DA7280_TOP_CFG4 (Address 0x16) */ #define DA7280_TST_CALIB_IMPEDANCE_DIS_MASK BIT(6) #define DA7280_V2I_FACTOR_FREEZE_MASK BIT(7) /* DA7280_TOP_INT_CFG1 (Address 0x17) */ #define DA7280_BEMF_FAULT_LIM_MASK GENMASK(1, 0) /* DA7280_TOP_CTL1 (Address 0x22) */ #define DA7280_OPERATION_MODE_MASK GENMASK(2, 0) #define DA7280_STANDBY_EN_MASK BIT(3) #define DA7280_SEQ_START_MASK BIT(4) /* DA7280_SEQ_CTL2 (Address 0x28) */ #define DA7280_PS_SEQ_ID_MASK GENMASK(3, 0) #define DA7280_PS_SEQ_LOOP_MASK GENMASK(7, 4) /* DA7280_GPIO_0_CTL (Address 0x29) */ #define DA7280_GPI0_POLARITY_MASK GENMASK(1, 0) #define DA7280_GPI0_MODE_MASK BIT(2) #define DA7280_GPI0_SEQUENCE_ID_MASK GENMASK(6, 3) /* DA7280_GPIO_1_CTL (Address 0x2a) */ #define DA7280_GPI1_POLARITY_MASK GENMASK(1, 0) #define DA7280_GPI1_MODE_MASK BIT(2) #define DA7280_GPI1_SEQUENCE_ID_MASK GENMASK(6, 3) /* DA7280_GPIO_2_CTL (Address 0x2b) */ #define DA7280_GPI2_POLARITY_MASK GENMASK(1, 0) #define DA7280_GPI2_MODE_MASK BIT(2) #define DA7280_GPI2_SEQUENCE_ID_MASK GENMASK(6, 3) /* DA7280_MEM_CTL2 (Address 0x2d) */ #define DA7280_WAV_MEM_LOCK_MASK BIT(7) /* DA7280_TOP_CFG5 (Address 0x6e) */ #define DA7280_V2I_FACTOR_OFFSET_EN_MASK BIT(0) /* DA7280_IRQ_MASK2 (Address 0x83) */ #define DA7280_ADC_SAT_M_MASK BIT(7) /* Controls */ #define DA7280_VOLTAGE_RATE_MAX 6000000 #define DA7280_VOLTAGE_RATE_STEP 23400 #define DA7280_NOMMAX_DFT 0x6B #define DA7280_ABSMAX_DFT 0x78 #define DA7280_IMPD_MAX 1500000000 #define DA7280_IMPD_DEFAULT 22000000 #define DA7280_IMAX_DEFAULT 0x0E #define DA7280_IMAX_STEP 7200 #define DA7280_IMAX_LIMIT 252000 #define DA7280_RESONT_FREQH_DFT 0x39 #define DA7280_RESONT_FREQL_DFT 0x32 #define DA7280_MIN_RESONAT_FREQ_HZ 50 #define DA7280_MAX_RESONAT_FREQ_HZ 300 #define DA7280_SEQ_ID_MAX 15 #define DA7280_SEQ_LOOP_MAX 15 #define DA7280_GPI_SEQ_ID_DFT 0 #define DA7280_GPI_SEQ_ID_MAX 2 #define DA7280_SNP_MEM_SIZE 100 #define DA7280_SNP_MEM_MAX DA7280_SNP_MEM_99 #define DA7280_IRQ_NUM 3 #define DA7280_SKIP_INIT 0x100 #define DA7280_FF_EFFECT_COUNT_MAX 15 /* Maximum gain is 0x7fff for PWM mode */ #define DA7280_MAX_MAGNITUDE_SHIFT 15 enum da7280_haptic_dev_t { DA7280_LRA = 0, DA7280_ERM_BAR = 1, DA7280_ERM_COIN = 2, DA7280_DEV_MAX, }; enum da7280_op_mode { DA7280_INACTIVE = 0, DA7280_DRO_MODE = 1, DA7280_PWM_MODE = 2, DA7280_RTWM_MODE = 3, DA7280_ETWM_MODE = 4, DA7280_OPMODE_MAX, }; #define DA7280_FF_CONSTANT_DRO 1 #define DA7280_FF_PERIODIC_PWM 2 #define DA7280_FF_PERIODIC_RTWM 1 #define DA7280_FF_PERIODIC_ETWM 2 #define DA7280_FF_PERIODIC_MODE DA7280_RTWM_MODE #define DA7280_FF_CONSTANT_MODE DA7280_DRO_MODE enum da7280_custom_effect_param { DA7280_CUSTOM_SEQ_ID_IDX = 0, DA7280_CUSTOM_SEQ_LOOP_IDX = 1, DA7280_CUSTOM_DATA_LEN = 2, }; enum da7280_custom_gpi_effect_param { DA7280_CUSTOM_GPI_SEQ_ID_IDX = 0, DA7280_CUSTOM_GPI_NUM_IDX = 2, DA7280_CUSTOM_GP_DATA_LEN = 3, }; struct da7280_gpi_ctl { u8 seq_id; u8 mode; u8 polarity; }; struct da7280_haptic { struct regmap *regmap; struct input_dev *input_dev; struct device *dev; struct i2c_client *client; struct pwm_device *pwm_dev; bool legacy; struct work_struct work; int val; u16 gain; s16 level; u8 dev_type; u8 op_mode; u8 const_op_mode; u8 periodic_op_mode; u16 nommax; u16 absmax; u32 imax; u32 impd; u32 resonant_freq_h; u32 resonant_freq_l; bool bemf_sense_en; bool freq_track_en; bool acc_en; bool rapid_stop_en; bool amp_pid_en; u8 ps_seq_id; u8 ps_seq_loop; struct da7280_gpi_ctl gpi_ctl[3]; bool mem_update; u8 snp_mem[DA7280_SNP_MEM_SIZE]; bool active; bool suspended; }; static bool da7280_volatile_register(struct device *dev, unsigned int reg) { switch (reg) { case DA7280_IRQ_EVENT1: case DA7280_IRQ_EVENT_WARNING_DIAG: case DA7280_IRQ_EVENT_SEQ_DIAG: case DA7280_IRQ_STATUS1: case DA7280_TOP_CTL1: return true; default: return false; } } static const struct regmap_config da7280_haptic_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = DA7280_SNP_MEM_MAX, .volatile_reg = da7280_volatile_register, }; static int da7280_haptic_mem_update(struct da7280_haptic *haptics) { unsigned int val; int error; /* The patterns should be updated when haptic is not working */ error = regmap_read(haptics->regmap, DA7280_IRQ_STATUS1, &val); if (error) return error; if (val & DA7280_STA_WARNING_MASK) { dev_warn(haptics->dev, "Warning! Please check HAPTIC status.\n"); return -EBUSY; } /* Patterns are not updated if the lock bit is enabled */ val = 0; error = regmap_read(haptics->regmap, DA7280_MEM_CTL2, &val); if (error) return error; if (~val & DA7280_WAV_MEM_LOCK_MASK) { dev_warn(haptics->dev, "Please unlock the bit first\n"); return -EACCES; } /* Set to Inactive mode to make sure safety */ error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_OPERATION_MODE_MASK, 0); if (error) return error; error = regmap_read(haptics->regmap, DA7280_MEM_CTL1, &val); if (error) return error; return regmap_bulk_write(haptics->regmap, val, haptics->snp_mem, DA7280_SNP_MEM_MAX - val + 1); } static int da7280_haptic_set_pwm(struct da7280_haptic *haptics, bool enabled) { struct pwm_state state; u64 period_mag_multi; int error; if (!haptics->gain && enabled) { dev_err(haptics->dev, "Unable to enable pwm with 0 gain\n"); return -EINVAL; } pwm_get_state(haptics->pwm_dev, &state); state.enabled = enabled; if (enabled) { period_mag_multi = (u64)state.period * haptics->gain; period_mag_multi >>= DA7280_MAX_MAGNITUDE_SHIFT; /* * The interpretation of duty cycle depends on the acc_en, * it should be between 50% and 100% for acc_en = 0. * See datasheet 'PWM mode' section. */ if (!haptics->acc_en) { period_mag_multi += state.period; period_mag_multi /= 2; } state.duty_cycle = period_mag_multi; } error = pwm_apply_state(haptics->pwm_dev, &state); if (error) dev_err(haptics->dev, "Failed to apply pwm state: %d\n", error); return error; } static void da7280_haptic_activate(struct da7280_haptic *haptics) { int error; if (haptics->active) return; switch (haptics->op_mode) { case DA7280_DRO_MODE: /* the valid range check when acc_en is enabled */ if (haptics->acc_en && haptics->level > 0x7F) haptics->level = 0x7F; else if (haptics->level > 0xFF) haptics->level = 0xFF; /* Set level as a % of ACTUATOR_NOMMAX (nommax) */ error = regmap_write(haptics->regmap, DA7280_TOP_CTL2, haptics->level); if (error) { dev_err(haptics->dev, "Failed to set level to %d: %d\n", haptics->level, error); return; } break; case DA7280_PWM_MODE: if (da7280_haptic_set_pwm(haptics, true)) return; break; case DA7280_RTWM_MODE: /* * The pattern will be played by the PS_SEQ_ID and the * PS_SEQ_LOOP */ break; case DA7280_ETWM_MODE: /* * The pattern will be played by the GPI[N] state, * GPI(N)_SEQUENCE_ID and the PS_SEQ_LOOP. See the * datasheet for the details. */ break; default: dev_err(haptics->dev, "Invalid op mode %d\n", haptics->op_mode); return; } error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_OPERATION_MODE_MASK, haptics->op_mode); if (error) { dev_err(haptics->dev, "Failed to set operation mode: %d", error); return; } if (haptics->op_mode == DA7280_PWM_MODE || haptics->op_mode == DA7280_RTWM_MODE) { error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_SEQ_START_MASK, DA7280_SEQ_START_MASK); if (error) { dev_err(haptics->dev, "Failed to start sequence: %d\n", error); return; } } haptics->active = true; } static void da7280_haptic_deactivate(struct da7280_haptic *haptics) { int error; if (!haptics->active) return; /* Set to Inactive mode */ error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_OPERATION_MODE_MASK, 0); if (error) { dev_err(haptics->dev, "Failed to clear operation mode: %d", error); return; } switch (haptics->op_mode) { case DA7280_DRO_MODE: error = regmap_write(haptics->regmap, DA7280_TOP_CTL2, 0); if (error) { dev_err(haptics->dev, "Failed to disable DRO mode: %d\n", error); return; } break; case DA7280_PWM_MODE: if (da7280_haptic_set_pwm(haptics, false)) return; break; case DA7280_RTWM_MODE: case DA7280_ETWM_MODE: error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_SEQ_START_MASK, 0); if (error) { dev_err(haptics->dev, "Failed to disable RTWM/ETWM mode: %d\n", error); return; } break; default: dev_err(haptics->dev, "Invalid op mode %d\n", haptics->op_mode); return; } haptics->active = false; } static void da7280_haptic_work(struct work_struct *work) { struct da7280_haptic *haptics = container_of(work, struct da7280_haptic, work); int val = haptics->val; if (val) da7280_haptic_activate(haptics); else da7280_haptic_deactivate(haptics); } static int da7280_haptics_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old) { struct da7280_haptic *haptics = input_get_drvdata(dev); s16 data[DA7280_SNP_MEM_SIZE] = { 0 }; unsigned int val; int tmp, i, num; int error; /* The effect should be uploaded when haptic is not working */ if (haptics->active) return -EBUSY; switch (effect->type) { /* DRO/PWM modes support this type */ case FF_CONSTANT: haptics->op_mode = haptics->const_op_mode; if (haptics->op_mode == DA7280_DRO_MODE) { tmp = effect->u.constant.level * 254; haptics->level = tmp / 0x7FFF; break; } haptics->gain = effect->u.constant.level <= 0 ? 0 : effect->u.constant.level; break; /* RTWM/ETWM modes support this type */ case FF_PERIODIC: if (effect->u.periodic.waveform != FF_CUSTOM) { dev_err(haptics->dev, "Device can only accept FF_CUSTOM waveform\n"); return -EINVAL; } /* * Load the data and check the length. * the data will be patterns in this case: 4 < X <= 100, * and will be saved into the waveform memory inside DA728x. * If X = 2, the data will be PS_SEQ_ID and PS_SEQ_LOOP. * If X = 3, the 1st data will be GPIX_SEQUENCE_ID . */ if (effect->u.periodic.custom_len == DA7280_CUSTOM_DATA_LEN) goto set_seq_id_loop; if (effect->u.periodic.custom_len == DA7280_CUSTOM_GP_DATA_LEN) goto set_gpix_seq_id; if (effect->u.periodic.custom_len < DA7280_CUSTOM_DATA_LEN || effect->u.periodic.custom_len > DA7280_SNP_MEM_SIZE) { dev_err(haptics->dev, "Invalid waveform data size\n"); return -EINVAL; } if (copy_from_user(data, effect->u.periodic.custom_data, sizeof(s16) * effect->u.periodic.custom_len)) return -EFAULT; memset(haptics->snp_mem, 0, DA7280_SNP_MEM_SIZE); for (i = 0; i < effect->u.periodic.custom_len; i++) { if (data[i] < 0 || data[i] > 0xff) { dev_err(haptics->dev, "Invalid waveform data %d at offset %d\n", data[i], i); return -EINVAL; } haptics->snp_mem[i] = (u8)data[i]; } error = da7280_haptic_mem_update(haptics); if (error) { dev_err(haptics->dev, "Failed to upload waveform: %d\n", error); return error; } break; set_seq_id_loop: if (copy_from_user(data, effect->u.periodic.custom_data, sizeof(s16) * DA7280_CUSTOM_DATA_LEN)) return -EFAULT; if (data[DA7280_CUSTOM_SEQ_ID_IDX] < 0 || data[DA7280_CUSTOM_SEQ_ID_IDX] > DA7280_SEQ_ID_MAX || data[DA7280_CUSTOM_SEQ_LOOP_IDX] < 0 || data[DA7280_CUSTOM_SEQ_LOOP_IDX] > DA7280_SEQ_LOOP_MAX) { dev_err(haptics->dev, "Invalid custom id (%d) or loop (%d)\n", data[DA7280_CUSTOM_SEQ_ID_IDX], data[DA7280_CUSTOM_SEQ_LOOP_IDX]); return -EINVAL; } haptics->ps_seq_id = data[DA7280_CUSTOM_SEQ_ID_IDX] & 0x0f; haptics->ps_seq_loop = data[DA7280_CUSTOM_SEQ_LOOP_IDX] & 0x0f; haptics->op_mode = haptics->periodic_op_mode; val = FIELD_PREP(DA7280_PS_SEQ_ID_MASK, haptics->ps_seq_id) | FIELD_PREP(DA7280_PS_SEQ_LOOP_MASK, haptics->ps_seq_loop); error = regmap_write(haptics->regmap, DA7280_SEQ_CTL2, val); if (error) { dev_err(haptics->dev, "Failed to update PS sequence: %d\n", error); return error; } break; set_gpix_seq_id: if (copy_from_user(data, effect->u.periodic.custom_data, sizeof(s16) * DA7280_CUSTOM_GP_DATA_LEN)) return -EFAULT; if (data[DA7280_CUSTOM_GPI_SEQ_ID_IDX] < 0 || data[DA7280_CUSTOM_GPI_SEQ_ID_IDX] > DA7280_SEQ_ID_MAX || data[DA7280_CUSTOM_GPI_NUM_IDX] < 0 || data[DA7280_CUSTOM_GPI_NUM_IDX] > DA7280_GPI_SEQ_ID_MAX) { dev_err(haptics->dev, "Invalid custom GPI id (%d) or num (%d)\n", data[DA7280_CUSTOM_GPI_SEQ_ID_IDX], data[DA7280_CUSTOM_GPI_NUM_IDX]); return -EINVAL; } num = data[DA7280_CUSTOM_GPI_NUM_IDX] & 0x0f; haptics->gpi_ctl[num].seq_id = data[DA7280_CUSTOM_GPI_SEQ_ID_IDX] & 0x0f; haptics->op_mode = haptics->periodic_op_mode; val = FIELD_PREP(DA7280_GPI0_SEQUENCE_ID_MASK, haptics->gpi_ctl[num].seq_id); error = regmap_update_bits(haptics->regmap, DA7280_GPI_0_CTL + num, DA7280_GPI0_SEQUENCE_ID_MASK, val); if (error) { dev_err(haptics->dev, "Failed to update GPI sequence: %d\n", error); return error; } break; default: dev_err(haptics->dev, "Unsupported effect type: %d\n", effect->type); return -EINVAL; } return 0; } static int da7280_haptics_playback(struct input_dev *dev, int effect_id, int val) { struct da7280_haptic *haptics = input_get_drvdata(dev); if (!haptics->op_mode) { dev_warn(haptics->dev, "No effects have been uploaded\n"); return -EINVAL; } if (likely(!haptics->suspended)) { haptics->val = val; schedule_work(&haptics->work); } return 0; } static int da7280_haptic_start(struct da7280_haptic *haptics) { int error; error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_STANDBY_EN_MASK, DA7280_STANDBY_EN_MASK); if (error) { dev_err(haptics->dev, "Unable to enable device: %d\n", error); return error; } return 0; } static void da7280_haptic_stop(struct da7280_haptic *haptics) { int error; cancel_work_sync(&haptics->work); da7280_haptic_deactivate(haptics); error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_STANDBY_EN_MASK, 0); if (error) dev_err(haptics->dev, "Failed to disable device: %d\n", error); } static int da7280_haptic_open(struct input_dev *dev) { struct da7280_haptic *haptics = input_get_drvdata(dev); return da7280_haptic_start(haptics); } static void da7280_haptic_close(struct input_dev *dev) { struct da7280_haptic *haptics = input_get_drvdata(dev); da7280_haptic_stop(haptics); } static u8 da7280_haptic_of_mode_str(struct device *dev, const char *str) { if (!strcmp(str, "LRA")) { return DA7280_LRA; } else if (!strcmp(str, "ERM-bar")) { return DA7280_ERM_BAR; } else if (!strcmp(str, "ERM-coin")) { return DA7280_ERM_COIN; } else { dev_warn(dev, "Invalid string - set to LRA\n"); return DA7280_LRA; } } static u8 da7280_haptic_of_gpi_mode_str(struct device *dev, const char *str) { if (!strcmp(str, "Single-pattern")) { return 0; } else if (!strcmp(str, "Multi-pattern")) { return 1; } else { dev_warn(dev, "Invalid string - set to Single-pattern\n"); return 0; } } static u8 da7280_haptic_of_gpi_pol_str(struct device *dev, const char *str) { if (!strcmp(str, "Rising-edge")) { return 0; } else if (!strcmp(str, "Falling-edge")) { return 1; } else if (!strcmp(str, "Both-edge")) { return 2; } else { dev_warn(dev, "Invalid string - set to Rising-edge\n"); return 0; } } static u8 da7280_haptic_of_volt_rating_set(u32 val) { u32 voltage = val / DA7280_VOLTAGE_RATE_STEP + 1; return min_t(u32, voltage, 0xff); } static void da7280_parse_properties(struct device *dev, struct da7280_haptic *haptics) { unsigned int i, mem[DA7280_SNP_MEM_SIZE]; char gpi_str1[] = "dlg,gpi0-seq-id"; char gpi_str2[] = "dlg,gpi0-mode"; char gpi_str3[] = "dlg,gpi0-polarity"; const char *str; u32 val; int error; /* * If there is no property, then use the mode programmed into the chip. */ haptics->dev_type = DA7280_DEV_MAX; error = device_property_read_string(dev, "dlg,actuator-type", &str); if (!error) haptics->dev_type = da7280_haptic_of_mode_str(dev, str); haptics->const_op_mode = DA7280_DRO_MODE; error = device_property_read_u32(dev, "dlg,const-op-mode", &val); if (!error && val == DA7280_FF_PERIODIC_PWM) haptics->const_op_mode = DA7280_PWM_MODE; haptics->periodic_op_mode = DA7280_RTWM_MODE; error = device_property_read_u32(dev, "dlg,periodic-op-mode", &val); if (!error && val == DA7280_FF_PERIODIC_ETWM) haptics->periodic_op_mode = DA7280_ETWM_MODE; haptics->nommax = DA7280_SKIP_INIT; error = device_property_read_u32(dev, "dlg,nom-microvolt", &val); if (!error && val < DA7280_VOLTAGE_RATE_MAX) haptics->nommax = da7280_haptic_of_volt_rating_set(val); haptics->absmax = DA7280_SKIP_INIT; error = device_property_read_u32(dev, "dlg,abs-max-microvolt", &val); if (!error && val < DA7280_VOLTAGE_RATE_MAX) haptics->absmax = da7280_haptic_of_volt_rating_set(val); haptics->imax = DA7280_IMAX_DEFAULT; error = device_property_read_u32(dev, "dlg,imax-microamp", &val); if (!error && val < DA7280_IMAX_LIMIT) haptics->imax = (val - 28600) / DA7280_IMAX_STEP + 1; haptics->impd = DA7280_IMPD_DEFAULT; error = device_property_read_u32(dev, "dlg,impd-micro-ohms", &val); if (!error && val <= DA7280_IMPD_MAX) haptics->impd = val; haptics->resonant_freq_h = DA7280_SKIP_INIT; haptics->resonant_freq_l = DA7280_SKIP_INIT; error = device_property_read_u32(dev, "dlg,resonant-freq-hz", &val); if (!error) { if (val < DA7280_MAX_RESONAT_FREQ_HZ && val > DA7280_MIN_RESONAT_FREQ_HZ) { haptics->resonant_freq_h = ((1000000000 / (val * 1333)) >> 7) & 0xFF; haptics->resonant_freq_l = (1000000000 / (val * 1333)) & 0x7F; } else { haptics->resonant_freq_h = DA7280_RESONT_FREQH_DFT; haptics->resonant_freq_l = DA7280_RESONT_FREQL_DFT; } } /* If no property, set to zero as default is to do nothing. */ haptics->ps_seq_id = 0; error = device_property_read_u32(dev, "dlg,ps-seq-id", &val); if (!error && val <= DA7280_SEQ_ID_MAX) haptics->ps_seq_id = val; haptics->ps_seq_loop = 0; error = device_property_read_u32(dev, "dlg,ps-seq-loop", &val); if (!error && val <= DA7280_SEQ_LOOP_MAX) haptics->ps_seq_loop = val; /* GPI0~2 Control */ for (i = 0; i <= DA7280_GPI_SEQ_ID_MAX; i++) { gpi_str1[7] = '0' + i; haptics->gpi_ctl[i].seq_id = DA7280_GPI_SEQ_ID_DFT + i; error = device_property_read_u32 (dev, gpi_str1, &val); if (!error && val <= DA7280_SEQ_ID_MAX) haptics->gpi_ctl[i].seq_id = val; gpi_str2[7] = '0' + i; haptics->gpi_ctl[i].mode = 0; error = device_property_read_string(dev, gpi_str2, &str); if (!error) haptics->gpi_ctl[i].mode = da7280_haptic_of_gpi_mode_str(dev, str); gpi_str3[7] = '0' + i; haptics->gpi_ctl[i].polarity = 0; error = device_property_read_string(dev, gpi_str3, &str); if (!error) haptics->gpi_ctl[i].polarity = da7280_haptic_of_gpi_pol_str(dev, str); } haptics->bemf_sense_en = device_property_read_bool(dev, "dlg,bemf-sens-enable"); haptics->freq_track_en = device_property_read_bool(dev, "dlg,freq-track-enable"); haptics->acc_en = device_property_read_bool(dev, "dlg,acc-enable"); haptics->rapid_stop_en = device_property_read_bool(dev, "dlg,rapid-stop-enable"); haptics->amp_pid_en = device_property_read_bool(dev, "dlg,amp-pid-enable"); haptics->mem_update = false; error = device_property_read_u32_array(dev, "dlg,mem-array", &mem[0], DA7280_SNP_MEM_SIZE); if (!error) { haptics->mem_update = true; memset(haptics->snp_mem, 0, DA7280_SNP_MEM_SIZE); for (i = 0; i < DA7280_SNP_MEM_SIZE; i++) { if (mem[i] <= 0xff) { haptics->snp_mem[i] = (u8)mem[i]; } else { dev_err(haptics->dev, "Invalid data in mem-array at %d: %x\n", i, mem[i]); haptics->mem_update = false; break; } } } } static irqreturn_t da7280_irq_handler(int irq, void *data) { struct da7280_haptic *haptics = data; struct device *dev = haptics->dev; u8 events[DA7280_IRQ_NUM]; int error; /* Check what events have happened */ error = regmap_bulk_read(haptics->regmap, DA7280_IRQ_EVENT1, events, sizeof(events)); if (error) { dev_err(dev, "failed to read interrupt data: %d\n", error); goto out; } /* Clear events */ error = regmap_write(haptics->regmap, DA7280_IRQ_EVENT1, events[0]); if (error) { dev_err(dev, "failed to clear interrupts: %d\n", error); goto out; } if (events[0] & DA7280_E_SEQ_FAULT_MASK) { /* * Stop first if haptic is active, otherwise, the fault may * happen continually even though the bit is cleared. */ error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_OPERATION_MODE_MASK, 0); if (error) dev_err(dev, "failed to clear op mode on fault: %d\n", error); } if (events[0] & DA7280_E_SEQ_DONE_MASK) haptics->active = false; if (events[0] & DA7280_E_WARNING_MASK) { if (events[1] & DA7280_E_LIM_DRIVE_MASK || events[1] & DA7280_E_LIM_DRIVE_ACC_MASK) dev_warn(dev, "Please reduce the driver level\n"); if (events[1] & DA7280_E_MEM_TYPE_MASK) dev_warn(dev, "Please check the mem data format\n"); if (events[1] & DA7280_E_OVERTEMP_WARN_MASK) dev_warn(dev, "Over-temperature warning\n"); } if (events[0] & DA7280_E_SEQ_FAULT_MASK) { if (events[2] & DA7280_E_SEQ_ID_FAULT_MASK) dev_info(dev, "Please reload PS_SEQ_ID & mem data\n"); if (events[2] & DA7280_E_MEM_FAULT_MASK) dev_info(dev, "Please reload the mem data\n"); if (events[2] & DA7280_E_PWM_FAULT_MASK) dev_info(dev, "Please restart PWM interface\n"); } out: return IRQ_HANDLED; } static int da7280_init(struct da7280_haptic *haptics) { unsigned int val = 0; u32 v2i_factor; int error, i; u8 mask = 0; /* * If device type is DA7280_DEV_MAX then simply use currently * programmed mode. */ if (haptics->dev_type == DA7280_DEV_MAX) { error = regmap_read(haptics->regmap, DA7280_TOP_CFG1, &val); if (error) goto out_err; haptics->dev_type = val & DA7280_ACTUATOR_TYPE_MASK ? DA7280_ERM_COIN : DA7280_LRA; } /* Apply user settings */ if (haptics->dev_type == DA7280_LRA && haptics->resonant_freq_l != DA7280_SKIP_INIT) { error = regmap_write(haptics->regmap, DA7280_FRQ_LRA_PER_H, haptics->resonant_freq_h); if (error) goto out_err; error = regmap_write(haptics->regmap, DA7280_FRQ_LRA_PER_L, haptics->resonant_freq_l); if (error) goto out_err; } else if (haptics->dev_type == DA7280_ERM_COIN) { error = regmap_update_bits(haptics->regmap, DA7280_TOP_INT_CFG1, DA7280_BEMF_FAULT_LIM_MASK, 0); if (error) goto out_err; mask = DA7280_TST_CALIB_IMPEDANCE_DIS_MASK | DA7280_V2I_FACTOR_FREEZE_MASK; val = DA7280_TST_CALIB_IMPEDANCE_DIS_MASK | DA7280_V2I_FACTOR_FREEZE_MASK; error = regmap_update_bits(haptics->regmap, DA7280_TOP_CFG4, mask, val); if (error) goto out_err; haptics->acc_en = false; haptics->rapid_stop_en = false; haptics->amp_pid_en = false; } mask = DA7280_ACTUATOR_TYPE_MASK | DA7280_BEMF_SENSE_EN_MASK | DA7280_FREQ_TRACK_EN_MASK | DA7280_ACCELERATION_EN_MASK | DA7280_RAPID_STOP_EN_MASK | DA7280_AMP_PID_EN_MASK; val = FIELD_PREP(DA7280_ACTUATOR_TYPE_MASK, (haptics->dev_type ? 1 : 0)) | FIELD_PREP(DA7280_BEMF_SENSE_EN_MASK, (haptics->bemf_sense_en ? 1 : 0)) | FIELD_PREP(DA7280_FREQ_TRACK_EN_MASK, (haptics->freq_track_en ? 1 : 0)) | FIELD_PREP(DA7280_ACCELERATION_EN_MASK, (haptics->acc_en ? 1 : 0)) | FIELD_PREP(DA7280_RAPID_STOP_EN_MASK, (haptics->rapid_stop_en ? 1 : 0)) | FIELD_PREP(DA7280_AMP_PID_EN_MASK, (haptics->amp_pid_en ? 1 : 0)); error = regmap_update_bits(haptics->regmap, DA7280_TOP_CFG1, mask, val); if (error) goto out_err; error = regmap_update_bits(haptics->regmap, DA7280_TOP_CFG5, DA7280_V2I_FACTOR_OFFSET_EN_MASK, haptics->acc_en ? DA7280_V2I_FACTOR_OFFSET_EN_MASK : 0); if (error) goto out_err; error = regmap_update_bits(haptics->regmap, DA7280_TOP_CFG2, DA7280_MEM_DATA_SIGNED_MASK, haptics->acc_en ? 0 : DA7280_MEM_DATA_SIGNED_MASK); if (error) goto out_err; if (haptics->nommax != DA7280_SKIP_INIT) { error = regmap_write(haptics->regmap, DA7280_ACTUATOR1, haptics->nommax); if (error) goto out_err; } if (haptics->absmax != DA7280_SKIP_INIT) { error = regmap_write(haptics->regmap, DA7280_ACTUATOR2, haptics->absmax); if (error) goto out_err; } error = regmap_update_bits(haptics->regmap, DA7280_ACTUATOR3, DA7280_IMAX_MASK, haptics->imax); if (error) goto out_err; v2i_factor = haptics->impd * (haptics->imax + 4) / 1610400; error = regmap_write(haptics->regmap, DA7280_CALIB_V2I_L, v2i_factor & 0xff); if (error) goto out_err; error = regmap_write(haptics->regmap, DA7280_CALIB_V2I_H, v2i_factor >> 8); if (error) goto out_err; error = regmap_update_bits(haptics->regmap, DA7280_TOP_CTL1, DA7280_STANDBY_EN_MASK, DA7280_STANDBY_EN_MASK); if (error) goto out_err; if (haptics->mem_update) { error = da7280_haptic_mem_update(haptics); if (error) goto out_err; } /* Set PS_SEQ_ID and PS_SEQ_LOOP */ val = FIELD_PREP(DA7280_PS_SEQ_ID_MASK, haptics->ps_seq_id) | FIELD_PREP(DA7280_PS_SEQ_LOOP_MASK, haptics->ps_seq_loop); error = regmap_write(haptics->regmap, DA7280_SEQ_CTL2, val); if (error) goto out_err; /* GPI(N) CTL */ for (i = 0; i < 3; i++) { val = FIELD_PREP(DA7280_GPI0_SEQUENCE_ID_MASK, haptics->gpi_ctl[i].seq_id) | FIELD_PREP(DA7280_GPI0_MODE_MASK, haptics->gpi_ctl[i].mode) | FIELD_PREP(DA7280_GPI0_POLARITY_MASK, haptics->gpi_ctl[i].polarity); error = regmap_write(haptics->regmap, DA7280_GPI_0_CTL + i, val); if (error) goto out_err; } /* Mask ADC_SAT_M bit as default */ error = regmap_update_bits(haptics->regmap, DA7280_IRQ_MASK2, DA7280_ADC_SAT_M_MASK, DA7280_ADC_SAT_M_MASK); if (error) goto out_err; /* Clear Interrupts */ error = regmap_write(haptics->regmap, DA7280_IRQ_EVENT1, 0xff); if (error) goto out_err; error = regmap_update_bits(haptics->regmap, DA7280_IRQ_MASK1, DA7280_SEQ_FAULT_M_MASK | DA7280_SEQ_DONE_M_MASK, 0); if (error) goto out_err; haptics->active = false; return 0; out_err: dev_err(haptics->dev, "chip initialization error: %d\n", error); return error; } static int da7280_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct da7280_haptic *haptics; struct input_dev *input_dev; struct pwm_state state; struct ff_device *ff; int error; if (!client->irq) { dev_err(dev, "No IRQ configured\n"); return -EINVAL; } haptics = devm_kzalloc(dev, sizeof(*haptics), GFP_KERNEL); if (!haptics) return -ENOMEM; haptics->dev = dev; da7280_parse_properties(dev, haptics); if (haptics->const_op_mode == DA7280_PWM_MODE) { haptics->pwm_dev = devm_pwm_get(dev, NULL); error = PTR_ERR_OR_ZERO(haptics->pwm_dev); if (error) { if (error != -EPROBE_DEFER) dev_err(dev, "Unable to request PWM: %d\n", error); return error; } /* Sync up PWM state and ensure it is off. */ pwm_init_state(haptics->pwm_dev, &state); state.enabled = false; error = pwm_apply_state(haptics->pwm_dev, &state); if (error) { dev_err(dev, "Failed to apply PWM state: %d\n", error); return error; } /* * Check PWM period, PWM freq = 1000000 / state.period. * The valid PWM freq range: 10k ~ 250kHz. */ if (state.period > 100000 || state.period < 4000) { dev_err(dev, "Unsupported PWM period: %lld\n", state.period); return -EINVAL; } } INIT_WORK(&haptics->work, da7280_haptic_work); haptics->client = client; i2c_set_clientdata(client, haptics); haptics->regmap = devm_regmap_init_i2c(client, &da7280_haptic_regmap_config); error = PTR_ERR_OR_ZERO(haptics->regmap); if (error) { dev_err(dev, "Failed to allocate register map: %d\n", error); return error; } error = da7280_init(haptics); if (error) { dev_err(dev, "Failed to initialize device: %d\n", error); return error; } /* Initialize input device for haptic device */ input_dev = devm_input_allocate_device(dev); if (!input_dev) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } input_dev->name = "da7280-haptic"; input_dev->dev.parent = client->dev.parent; input_dev->open = da7280_haptic_open; input_dev->close = da7280_haptic_close; input_set_drvdata(input_dev, haptics); haptics->input_dev = input_dev; input_set_capability(haptics->input_dev, EV_FF, FF_PERIODIC); input_set_capability(haptics->input_dev, EV_FF, FF_CUSTOM); input_set_capability(haptics->input_dev, EV_FF, FF_CONSTANT); input_set_capability(haptics->input_dev, EV_FF, FF_GAIN); error = input_ff_create(haptics->input_dev, DA7280_FF_EFFECT_COUNT_MAX); if (error) { dev_err(dev, "Failed to create FF input device: %d\n", error); return error; } ff = input_dev->ff; ff->upload = da7280_haptics_upload_effect; ff->playback = da7280_haptics_playback; error = input_register_device(input_dev); if (error) { dev_err(dev, "Failed to register input device: %d\n", error); return error; } error = devm_request_threaded_irq(dev, client->irq, NULL, da7280_irq_handler, IRQF_ONESHOT, "da7280-haptics", haptics); if (error) { dev_err(dev, "Failed to request IRQ %d: %d\n", client->irq, error); return error; } return 0; } static int da7280_suspend(struct device *dev) { struct da7280_haptic *haptics = dev_get_drvdata(dev); mutex_lock(&haptics->input_dev->mutex); /* * Make sure no new requests will be submitted while device is * suspended. */ spin_lock_irq(&haptics->input_dev->event_lock); haptics->suspended = true; spin_unlock_irq(&haptics->input_dev->event_lock); da7280_haptic_stop(haptics); mutex_unlock(&haptics->input_dev->mutex); return 0; } static int da7280_resume(struct device *dev) { struct da7280_haptic *haptics = dev_get_drvdata(dev); int retval; mutex_lock(&haptics->input_dev->mutex); retval = da7280_haptic_start(haptics); if (!retval) { spin_lock_irq(&haptics->input_dev->event_lock); haptics->suspended = false; spin_unlock_irq(&haptics->input_dev->event_lock); } mutex_unlock(&haptics->input_dev->mutex); return retval; } #ifdef CONFIG_OF static const struct of_device_id da7280_of_match[] = { { .compatible = "dlg,da7280", }, { } }; MODULE_DEVICE_TABLE(of, da7280_of_match); #endif static const struct i2c_device_id da7280_i2c_id[] = { { "da7280", }, { } }; MODULE_DEVICE_TABLE(i2c, da7280_i2c_id); static DEFINE_SIMPLE_DEV_PM_OPS(da7280_pm_ops, da7280_suspend, da7280_resume); static struct i2c_driver da7280_driver = { .driver = { .name = "da7280", .of_match_table = of_match_ptr(da7280_of_match), .pm = pm_sleep_ptr(&da7280_pm_ops), }, .probe = da7280_probe, .id_table = da7280_i2c_id, }; module_i2c_driver(da7280_driver); MODULE_DESCRIPTION("DA7280 haptics driver"); MODULE_AUTHOR("Roy Im <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/misc/da7280.c
/** * twl4030-pwrbutton.c - TWL4030 Power Button Input Driver * * Copyright (C) 2008-2009 Nokia Corporation * * Written by Peter De Schrijver <[email protected]> * Several fixes by Felipe Balbi <[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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/mfd/twl.h> #define PWR_PWRON_IRQ (1 << 0) #define STS_HW_CONDITIONS 0xf static irqreturn_t powerbutton_irq(int irq, void *_pwr) { struct input_dev *pwr = _pwr; int err; u8 value; err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &value, STS_HW_CONDITIONS); if (!err) { pm_wakeup_event(pwr->dev.parent, 0); input_report_key(pwr, KEY_POWER, value & PWR_PWRON_IRQ); input_sync(pwr); } else { dev_err(pwr->dev.parent, "twl4030: i2c error %d while reading" " TWL4030 PM_MASTER STS_HW_CONDITIONS register\n", err); } return IRQ_HANDLED; } static int twl4030_pwrbutton_probe(struct platform_device *pdev) { struct input_dev *pwr; int irq = platform_get_irq(pdev, 0); int err; pwr = devm_input_allocate_device(&pdev->dev); if (!pwr) { dev_err(&pdev->dev, "Can't allocate power button\n"); return -ENOMEM; } input_set_capability(pwr, EV_KEY, KEY_POWER); pwr->name = "twl4030_pwrbutton"; pwr->phys = "twl4030_pwrbutton/input0"; pwr->dev.parent = &pdev->dev; err = devm_request_threaded_irq(&pdev->dev, irq, NULL, powerbutton_irq, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT, "twl4030_pwrbutton", pwr); if (err < 0) { dev_err(&pdev->dev, "Can't get IRQ for pwrbutton: %d\n", err); return err; } err = input_register_device(pwr); if (err) { dev_err(&pdev->dev, "Can't register power button: %d\n", err); return err; } device_init_wakeup(&pdev->dev, true); return 0; } #ifdef CONFIG_OF static const struct of_device_id twl4030_pwrbutton_dt_match_table[] = { { .compatible = "ti,twl4030-pwrbutton" }, {}, }; MODULE_DEVICE_TABLE(of, twl4030_pwrbutton_dt_match_table); #endif static struct platform_driver twl4030_pwrbutton_driver = { .probe = twl4030_pwrbutton_probe, .driver = { .name = "twl4030_pwrbutton", .of_match_table = of_match_ptr(twl4030_pwrbutton_dt_match_table), }, }; module_platform_driver(twl4030_pwrbutton_driver); MODULE_ALIAS("platform:twl4030_pwrbutton"); MODULE_DESCRIPTION("Triton2 Power Button"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Peter De Schrijver <[email protected]>"); MODULE_AUTHOR("Felipe Balbi <[email protected]>");
linux-master
drivers/input/misc/twl4030-pwrbutton.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2004, 2007-2010, 2011-2012 Synopsys, Inc. (www.synopsys.com) * * Driver is originally developed by Pavel Sokolov <[email protected]> */ #include <linux/err.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/serio.h> #include <linux/platform_device.h> #include <linux/of.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/slab.h> #define ARC_PS2_PORTS 2 #define ARC_ARC_PS2_ID 0x0001f609 #define STAT_TIMEOUT 128 #define PS2_STAT_RX_FRM_ERR (1) #define PS2_STAT_RX_BUF_OVER (1 << 1) #define PS2_STAT_RX_INT_EN (1 << 2) #define PS2_STAT_RX_VAL (1 << 3) #define PS2_STAT_TX_ISNOT_FUL (1 << 4) #define PS2_STAT_TX_INT_EN (1 << 5) struct arc_ps2_port { void __iomem *data_addr; void __iomem *status_addr; struct serio *io; }; struct arc_ps2_data { struct arc_ps2_port port[ARC_PS2_PORTS]; void __iomem *addr; unsigned int frame_error; unsigned int buf_overflow; unsigned int total_int; }; static void arc_ps2_check_rx(struct arc_ps2_data *arc_ps2, struct arc_ps2_port *port) { unsigned int timeout = 1000; unsigned int flag, status; unsigned char data; do { status = ioread32(port->status_addr); if (!(status & PS2_STAT_RX_VAL)) return; data = ioread32(port->data_addr) & 0xff; flag = 0; arc_ps2->total_int++; if (status & PS2_STAT_RX_FRM_ERR) { arc_ps2->frame_error++; flag |= SERIO_PARITY; } else if (status & PS2_STAT_RX_BUF_OVER) { arc_ps2->buf_overflow++; flag |= SERIO_FRAME; } serio_interrupt(port->io, data, flag); } while (--timeout); dev_err(&port->io->dev, "PS/2 hardware stuck\n"); } static irqreturn_t arc_ps2_interrupt(int irq, void *dev) { struct arc_ps2_data *arc_ps2 = dev; int i; for (i = 0; i < ARC_PS2_PORTS; i++) arc_ps2_check_rx(arc_ps2, &arc_ps2->port[i]); return IRQ_HANDLED; } static int arc_ps2_write(struct serio *io, unsigned char val) { unsigned status; struct arc_ps2_port *port = io->port_data; int timeout = STAT_TIMEOUT; do { status = ioread32(port->status_addr); cpu_relax(); if (status & PS2_STAT_TX_ISNOT_FUL) { iowrite32(val & 0xff, port->data_addr); return 0; } } while (--timeout); dev_err(&io->dev, "write timeout\n"); return -ETIMEDOUT; } static int arc_ps2_open(struct serio *io) { struct arc_ps2_port *port = io->port_data; iowrite32(PS2_STAT_RX_INT_EN, port->status_addr); return 0; } static void arc_ps2_close(struct serio *io) { struct arc_ps2_port *port = io->port_data; iowrite32(ioread32(port->status_addr) & ~PS2_STAT_RX_INT_EN, port->status_addr); } static void __iomem *arc_ps2_calc_addr(struct arc_ps2_data *arc_ps2, int index, bool status) { void __iomem *addr; addr = arc_ps2->addr + 4 + 4 * index; if (status) addr += ARC_PS2_PORTS * 4; return addr; } static void arc_ps2_inhibit_ports(struct arc_ps2_data *arc_ps2) { void __iomem *addr; u32 val; int i; for (i = 0; i < ARC_PS2_PORTS; i++) { addr = arc_ps2_calc_addr(arc_ps2, i, true); val = ioread32(addr); val &= ~(PS2_STAT_RX_INT_EN | PS2_STAT_TX_INT_EN); iowrite32(val, addr); } } static int arc_ps2_create_port(struct platform_device *pdev, struct arc_ps2_data *arc_ps2, int index) { struct arc_ps2_port *port = &arc_ps2->port[index]; struct serio *io; io = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!io) return -ENOMEM; io->id.type = SERIO_8042; io->write = arc_ps2_write; io->open = arc_ps2_open; io->close = arc_ps2_close; snprintf(io->name, sizeof(io->name), "ARC PS/2 port%d", index); snprintf(io->phys, sizeof(io->phys), "arc/serio%d", index); io->port_data = port; port->io = io; port->data_addr = arc_ps2_calc_addr(arc_ps2, index, false); port->status_addr = arc_ps2_calc_addr(arc_ps2, index, true); dev_dbg(&pdev->dev, "port%d is allocated (data = 0x%p, status = 0x%p)\n", index, port->data_addr, port->status_addr); serio_register_port(port->io); return 0; } static int arc_ps2_probe(struct platform_device *pdev) { struct arc_ps2_data *arc_ps2; int irq; int error, id, i; irq = platform_get_irq_byname(pdev, "arc_ps2_irq"); if (irq < 0) return -EINVAL; arc_ps2 = devm_kzalloc(&pdev->dev, sizeof(struct arc_ps2_data), GFP_KERNEL); if (!arc_ps2) { dev_err(&pdev->dev, "out of memory\n"); return -ENOMEM; } arc_ps2->addr = devm_platform_get_and_ioremap_resource(pdev, 0, NULL); if (IS_ERR(arc_ps2->addr)) return PTR_ERR(arc_ps2->addr); dev_info(&pdev->dev, "irq = %d, address = 0x%p, ports = %i\n", irq, arc_ps2->addr, ARC_PS2_PORTS); id = ioread32(arc_ps2->addr); if (id != ARC_ARC_PS2_ID) { dev_err(&pdev->dev, "device id does not match\n"); return -ENXIO; } arc_ps2_inhibit_ports(arc_ps2); error = devm_request_irq(&pdev->dev, irq, arc_ps2_interrupt, 0, "arc_ps2", arc_ps2); if (error) { dev_err(&pdev->dev, "Could not allocate IRQ\n"); return error; } for (i = 0; i < ARC_PS2_PORTS; i++) { error = arc_ps2_create_port(pdev, arc_ps2, i); if (error) { while (--i >= 0) serio_unregister_port(arc_ps2->port[i].io); return error; } } platform_set_drvdata(pdev, arc_ps2); return 0; } static int arc_ps2_remove(struct platform_device *pdev) { struct arc_ps2_data *arc_ps2 = platform_get_drvdata(pdev); int i; for (i = 0; i < ARC_PS2_PORTS; i++) serio_unregister_port(arc_ps2->port[i].io); dev_dbg(&pdev->dev, "interrupt count = %i\n", arc_ps2->total_int); dev_dbg(&pdev->dev, "frame error count = %i\n", arc_ps2->frame_error); dev_dbg(&pdev->dev, "buffer overflow count = %i\n", arc_ps2->buf_overflow); return 0; } #ifdef CONFIG_OF static const struct of_device_id arc_ps2_match[] = { { .compatible = "snps,arc_ps2" }, { }, }; MODULE_DEVICE_TABLE(of, arc_ps2_match); #endif static struct platform_driver arc_ps2_driver = { .driver = { .name = "arc_ps2", .of_match_table = of_match_ptr(arc_ps2_match), }, .probe = arc_ps2_probe, .remove = arc_ps2_remove, }; module_platform_driver(arc_ps2_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Pavel Sokolov <[email protected]>"); MODULE_DESCRIPTION("ARC PS/2 Driver");
linux-master
drivers/input/serio/arc_ps2.c
// SPDX-License-Identifier: GPL-2.0-only /* * PS/2 driver library * * Copyright (c) 1999-2002 Vojtech Pavlik * Copyright (c) 2004 Dmitry Torokhov */ #include <linux/delay.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/kmsan-checks.h> #include <linux/serio.h> #include <linux/i8042.h> #include <linux/libps2.h> #define DRIVER_DESC "PS/2 driver library" #define PS2_CMD_SETSCALE11 0x00e6 #define PS2_CMD_SETRES 0x10e8 #define PS2_CMD_EX_SETLEDS 0x20eb #define PS2_CMD_SETLEDS 0x10ed #define PS2_CMD_GETID 0x02f2 #define PS2_CMD_SETREP 0x10f3 /* Set repeat rate/set report rate */ #define PS2_CMD_RESET_BAT 0x02ff #define PS2_RET_BAT 0xaa #define PS2_RET_ID 0x00 #define PS2_RET_ACK 0xfa #define PS2_RET_NAK 0xfe #define PS2_RET_ERR 0xfc #define PS2_FLAG_ACK BIT(0) /* Waiting for ACK/NAK */ #define PS2_FLAG_CMD BIT(1) /* Waiting for a command to finish */ #define PS2_FLAG_CMD1 BIT(2) /* Waiting for the first byte of command response */ #define PS2_FLAG_WAITID BIT(3) /* Command executing is GET ID */ #define PS2_FLAG_NAK BIT(4) /* Last transmission was NAKed */ #define PS2_FLAG_PASS_NOACK BIT(5) /* Pass non-ACK byte to receive handler */ static int ps2_do_sendbyte(struct ps2dev *ps2dev, u8 byte, unsigned int timeout, unsigned int max_attempts) __releases(&ps2dev->serio->lock) __acquires(&ps2dev->serio->lock) { int attempt = 0; int error; lockdep_assert_held(&ps2dev->serio->lock); do { ps2dev->nak = 1; ps2dev->flags |= PS2_FLAG_ACK; serio_continue_rx(ps2dev->serio); error = serio_write(ps2dev->serio, byte); if (error) dev_dbg(&ps2dev->serio->dev, "failed to write %#02x: %d\n", byte, error); else wait_event_timeout(ps2dev->wait, !(ps2dev->flags & PS2_FLAG_ACK), msecs_to_jiffies(timeout)); serio_pause_rx(ps2dev->serio); } while (ps2dev->nak == PS2_RET_NAK && ++attempt < max_attempts); ps2dev->flags &= ~PS2_FLAG_ACK; if (!error) { switch (ps2dev->nak) { case 0: break; case PS2_RET_NAK: error = -EAGAIN; break; case PS2_RET_ERR: error = -EPROTO; break; default: error = -EIO; break; } } if (error || attempt > 1) dev_dbg(&ps2dev->serio->dev, "%02x - %d (%x), attempt %d\n", byte, error, ps2dev->nak, attempt); return error; } /** * ps2_sendbyte - sends a byte to the device and wait for acknowledgement * @ps2dev: a PS/2 device to send the data to * @byte: data to be sent to the device * @timeout: timeout for sending the data and receiving an acknowledge * * The function doesn't handle retransmission, the caller is expected to handle * it when needed. * * ps2_sendbyte() can only be called from a process context. */ int ps2_sendbyte(struct ps2dev *ps2dev, u8 byte, unsigned int timeout) { int retval; serio_pause_rx(ps2dev->serio); retval = ps2_do_sendbyte(ps2dev, byte, timeout, 1); dev_dbg(&ps2dev->serio->dev, "%02x - %x\n", byte, ps2dev->nak); serio_continue_rx(ps2dev->serio); return retval; } EXPORT_SYMBOL(ps2_sendbyte); /** * ps2_begin_command - mark beginning of execution of a complex command * @ps2dev: a PS/2 device executing the command * * Serializes a complex/compound command. Once command is finished * ps2_end_command() should be called. */ void ps2_begin_command(struct ps2dev *ps2dev) { struct mutex *m = ps2dev->serio->ps2_cmd_mutex ?: &ps2dev->cmd_mutex; mutex_lock(m); } EXPORT_SYMBOL(ps2_begin_command); /** * ps2_end_command - mark end of execution of a complex command * @ps2dev: a PS/2 device executing the command */ void ps2_end_command(struct ps2dev *ps2dev) { struct mutex *m = ps2dev->serio->ps2_cmd_mutex ?: &ps2dev->cmd_mutex; mutex_unlock(m); } EXPORT_SYMBOL(ps2_end_command); /** * ps2_drain - waits for device to transmit requested number of bytes * and discards them * @ps2dev: the PS/2 device that should be drained * @maxbytes: maximum number of bytes to be drained * @timeout: time to drain the device */ void ps2_drain(struct ps2dev *ps2dev, size_t maxbytes, unsigned int timeout) { if (maxbytes > sizeof(ps2dev->cmdbuf)) { WARN_ON(1); maxbytes = sizeof(ps2dev->cmdbuf); } ps2_begin_command(ps2dev); serio_pause_rx(ps2dev->serio); ps2dev->flags = PS2_FLAG_CMD; ps2dev->cmdcnt = maxbytes; serio_continue_rx(ps2dev->serio); wait_event_timeout(ps2dev->wait, !(ps2dev->flags & PS2_FLAG_CMD), msecs_to_jiffies(timeout)); ps2_end_command(ps2dev); } EXPORT_SYMBOL(ps2_drain); /** * ps2_is_keyboard_id - checks received ID byte against the list of * known keyboard IDs * @id_byte: data byte that should be checked */ bool ps2_is_keyboard_id(u8 id_byte) { static const u8 keyboard_ids[] = { 0xab, /* Regular keyboards */ 0xac, /* NCD Sun keyboard */ 0x2b, /* Trust keyboard, translated */ 0x5d, /* Trust keyboard */ 0x60, /* NMB SGI keyboard, translated */ 0x47, /* NMB SGI keyboard */ }; return memchr(keyboard_ids, id_byte, sizeof(keyboard_ids)) != NULL; } EXPORT_SYMBOL(ps2_is_keyboard_id); /* * ps2_adjust_timeout() is called after receiving 1st byte of command * response and tries to reduce remaining timeout to speed up command * completion. */ static int ps2_adjust_timeout(struct ps2dev *ps2dev, unsigned int command, unsigned int timeout) { switch (command) { case PS2_CMD_RESET_BAT: /* * Device has sent the first response byte after * reset command, reset is thus done, so we can * shorten the timeout. * The next byte will come soon (keyboard) or not * at all (mouse). */ if (timeout > msecs_to_jiffies(100)) timeout = msecs_to_jiffies(100); break; case PS2_CMD_GETID: /* * Microsoft Natural Elite keyboard responds to * the GET ID command as it were a mouse, with * a single byte. Fail the command so atkbd will * use alternative probe to detect it. */ if (ps2dev->cmdbuf[1] == 0xaa) { serio_pause_rx(ps2dev->serio); ps2dev->flags = 0; serio_continue_rx(ps2dev->serio); timeout = 0; } /* * If device behind the port is not a keyboard there * won't be 2nd byte of ID response. */ if (!ps2_is_keyboard_id(ps2dev->cmdbuf[1])) { serio_pause_rx(ps2dev->serio); ps2dev->flags = ps2dev->cmdcnt = 0; serio_continue_rx(ps2dev->serio); timeout = 0; } break; default: break; } return timeout; } /** * __ps2_command - send a command to PS/2 device * @ps2dev: the PS/2 device that should execute the command * @param: a buffer containing parameters to be sent along with the command, * or place where the results of the command execution will be deposited, * or both * @command: command word that encodes the command itself, as well as number of * additional parameter bytes that should be sent to the device and expected * length of the command response * * Not serialized. Callers should use ps2_begin_command() and ps2_end_command() * to ensure proper serialization for complex commands. */ int __ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command) { unsigned int timeout; unsigned int send = (command >> 12) & 0xf; unsigned int receive = (command >> 8) & 0xf; int rc; int i; u8 send_param[16]; if (receive > sizeof(ps2dev->cmdbuf)) { WARN_ON(1); return -EINVAL; } if (send && !param) { WARN_ON(1); return -EINVAL; } memcpy(send_param, param, send); serio_pause_rx(ps2dev->serio); ps2dev->cmdcnt = receive; switch (command) { case PS2_CMD_GETID: /* * Some mice do not ACK the "get ID" command, prepare to * handle this. */ ps2dev->flags = PS2_FLAG_WAITID; break; case PS2_CMD_SETLEDS: case PS2_CMD_EX_SETLEDS: case PS2_CMD_SETREP: ps2dev->flags = PS2_FLAG_PASS_NOACK; break; default: ps2dev->flags = 0; break; } if (receive) { /* Indicate that we expect response to the command. */ ps2dev->flags |= PS2_FLAG_CMD | PS2_FLAG_CMD1; if (param) for (i = 0; i < receive; i++) ps2dev->cmdbuf[(receive - 1) - i] = param[i]; } /* * Some devices (Synaptics) perform the reset before * ACKing the reset command, and so it can take a long * time before the ACK arrives. */ timeout = command == PS2_CMD_RESET_BAT ? 1000 : 200; rc = ps2_do_sendbyte(ps2dev, command & 0xff, timeout, 2); if (rc) goto out_reset_flags; /* Send command parameters, if any. */ for (i = 0; i < send; i++) { rc = ps2_do_sendbyte(ps2dev, param[i], 200, 2); if (rc) goto out_reset_flags; } serio_continue_rx(ps2dev->serio); /* * The reset command takes a long time to execute. */ timeout = msecs_to_jiffies(command == PS2_CMD_RESET_BAT ? 4000 : 500); timeout = wait_event_timeout(ps2dev->wait, !(ps2dev->flags & PS2_FLAG_CMD1), timeout); if (ps2dev->cmdcnt && !(ps2dev->flags & PS2_FLAG_CMD1)) { timeout = ps2_adjust_timeout(ps2dev, command, timeout); wait_event_timeout(ps2dev->wait, !(ps2dev->flags & PS2_FLAG_CMD), timeout); } serio_pause_rx(ps2dev->serio); if (param) { for (i = 0; i < receive; i++) param[i] = ps2dev->cmdbuf[(receive - 1) - i]; kmsan_unpoison_memory(param, receive); } if (ps2dev->cmdcnt && (command != PS2_CMD_RESET_BAT || ps2dev->cmdcnt != 1)) { rc = -EPROTO; goto out_reset_flags; } rc = 0; out_reset_flags: ps2dev->flags = 0; serio_continue_rx(ps2dev->serio); dev_dbg(&ps2dev->serio->dev, "%02x [%*ph] - %x/%08lx [%*ph]\n", command & 0xff, send, send_param, ps2dev->nak, ps2dev->flags, receive, param ?: send_param); /* * ps_command() handles resends itself, so do not leak -EAGAIN * to the callers. */ return rc != -EAGAIN ? rc : -EPROTO; } EXPORT_SYMBOL(__ps2_command); /** * ps2_command - send a command to PS/2 device * @ps2dev: the PS/2 device that should execute the command * @param: a buffer containing parameters to be sent along with the command, * or place where the results of the command execution will be deposited, * or both * @command: command word that encodes the command itself, as well as number of * additional parameter bytes that should be sent to the device and expected * length of the command response * * Note: ps2_command() serializes the command execution so that only one * command can be executed at a time for either individual port or the entire * 8042 controller. */ int ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command) { int rc; ps2_begin_command(ps2dev); rc = __ps2_command(ps2dev, param, command); ps2_end_command(ps2dev); return rc; } EXPORT_SYMBOL(ps2_command); /** * ps2_sliced_command - sends an extended PS/2 command to a mouse * @ps2dev: the PS/2 device that should execute the command * @command: command byte * * The command is sent using "sliced" syntax understood by advanced devices, * such as Logitech or Synaptics touchpads. The command is encoded as: * 0xE6 0xE8 rr 0xE8 ss 0xE8 tt 0xE8 uu where (rr*64)+(ss*16)+(tt*4)+uu * is the command. */ int ps2_sliced_command(struct ps2dev *ps2dev, u8 command) { int i; int retval; ps2_begin_command(ps2dev); retval = __ps2_command(ps2dev, NULL, PS2_CMD_SETSCALE11); if (retval) goto out; for (i = 6; i >= 0; i -= 2) { u8 d = (command >> i) & 3; retval = __ps2_command(ps2dev, &d, PS2_CMD_SETRES); if (retval) break; } out: dev_dbg(&ps2dev->serio->dev, "%02x - %d\n", command, retval); ps2_end_command(ps2dev); return retval; } EXPORT_SYMBOL(ps2_sliced_command); /** * ps2_init - initializes ps2dev structure * @ps2dev: structure to be initialized * @serio: serio port associated with the PS/2 device * @pre_receive_handler: validation handler to check basic communication state * @receive_handler: main protocol handler * * Prepares ps2dev structure for use in drivers for PS/2 devices. */ void ps2_init(struct ps2dev *ps2dev, struct serio *serio, ps2_pre_receive_handler_t pre_receive_handler, ps2_receive_handler_t receive_handler) { ps2dev->pre_receive_handler = pre_receive_handler; ps2dev->receive_handler = receive_handler; mutex_init(&ps2dev->cmd_mutex); lockdep_set_subclass(&ps2dev->cmd_mutex, serio->depth); init_waitqueue_head(&ps2dev->wait); ps2dev->serio = serio; serio_set_drvdata(serio, ps2dev); } EXPORT_SYMBOL(ps2_init); /* * ps2_handle_response() stores device's response to a command and notifies * the process waiting for completion of the command. Note that there is a * distinction between waiting for the first byte of the response, and * waiting for subsequent bytes. It is done so that callers could shorten * timeouts once first byte of response is received. */ static void ps2_handle_response(struct ps2dev *ps2dev, u8 data) { if (ps2dev->cmdcnt) ps2dev->cmdbuf[--ps2dev->cmdcnt] = data; if (ps2dev->flags & PS2_FLAG_CMD1) { ps2dev->flags &= ~PS2_FLAG_CMD1; if (ps2dev->cmdcnt) wake_up(&ps2dev->wait); } if (!ps2dev->cmdcnt) { ps2dev->flags &= ~PS2_FLAG_CMD; wake_up(&ps2dev->wait); } } /* * ps2_handle_ack() processes ACK/NAK of a command from a PS/2 device, * possibly applying workarounds for mice not acknowledging the "get ID" * command. */ static void ps2_handle_ack(struct ps2dev *ps2dev, u8 data) { switch (data) { case PS2_RET_ACK: ps2dev->nak = 0; break; case PS2_RET_NAK: ps2dev->flags |= PS2_FLAG_NAK; ps2dev->nak = PS2_RET_NAK; break; case PS2_RET_ERR: if (ps2dev->flags & PS2_FLAG_NAK) { ps2dev->flags &= ~PS2_FLAG_NAK; ps2dev->nak = PS2_RET_ERR; break; } fallthrough; /* * Workaround for mice which don't ACK the Get ID command. * These are valid mouse IDs that we recognize. */ case 0x00: case 0x03: case 0x04: if (ps2dev->flags & PS2_FLAG_WAITID) { ps2dev->nak = 0; break; } fallthrough; default: /* * Do not signal errors if we get unexpected reply while * waiting for an ACK to the initial (first) command byte: * the device might not be quiesced yet and continue * delivering data. For certain commands (such as set leds and * set repeat rate) that can be used during normal device * operation, we even pass this data byte to the normal receive * handler. * Note that we reset PS2_FLAG_WAITID flag, so the workaround * for mice not acknowledging the Get ID command only triggers * on the 1st byte; if device spews data we really want to see * a real ACK from it. */ dev_dbg(&ps2dev->serio->dev, "unexpected %#02x\n", data); if (ps2dev->flags & PS2_FLAG_PASS_NOACK) ps2dev->receive_handler(ps2dev, data); ps2dev->flags &= ~(PS2_FLAG_WAITID | PS2_FLAG_PASS_NOACK); return; } if (!ps2dev->nak) ps2dev->flags &= ~PS2_FLAG_NAK; ps2dev->flags &= ~PS2_FLAG_ACK; if (!ps2dev->nak && data != PS2_RET_ACK) ps2_handle_response(ps2dev, data); else wake_up(&ps2dev->wait); } /* * Clears state of PS/2 device after communication error by resetting majority * of flags and waking up waiters, if any. */ static void ps2_cleanup(struct ps2dev *ps2dev) { unsigned long old_flags = ps2dev->flags; /* reset all flags except last nak */ ps2dev->flags &= PS2_FLAG_NAK; if (old_flags & PS2_FLAG_ACK) ps2dev->nak = 1; if (old_flags & (PS2_FLAG_ACK | PS2_FLAG_CMD)) wake_up(&ps2dev->wait); } /** * ps2_interrupt - common interrupt handler for PS/2 devices * @serio: serio port for the device * @data: a data byte received from the device * @flags: flags such as %SERIO_PARITY or %SERIO_TIMEOUT indicating state of * the data transfer * * ps2_interrupt() invokes pre-receive handler, optionally handles command * acknowledgement and response from the device, and finally passes the data * to the main protocol handler for future processing. */ irqreturn_t ps2_interrupt(struct serio *serio, u8 data, unsigned int flags) { struct ps2dev *ps2dev = serio_get_drvdata(serio); enum ps2_disposition rc; rc = ps2dev->pre_receive_handler(ps2dev, data, flags); switch (rc) { case PS2_ERROR: ps2_cleanup(ps2dev); break; case PS2_IGNORE: break; case PS2_PROCESS: if (ps2dev->flags & PS2_FLAG_ACK) ps2_handle_ack(ps2dev, data); else if (ps2dev->flags & PS2_FLAG_CMD) ps2_handle_response(ps2dev, data); else ps2dev->receive_handler(ps2dev, data); break; } return IRQ_HANDLED; } EXPORT_SYMBOL(ps2_interrupt); MODULE_AUTHOR("Dmitry Torokhov <[email protected]>"); MODULE_DESCRIPTION("PS/2 driver library"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/libps2.c
/* * userio kernel serio device emulation module * Copyright (C) 2015 Red Hat * Copyright (C) 2015 Stephen Chandler Paul <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. */ #include <linux/circ_buf.h> #include <linux/mutex.h> #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/serio.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/sched.h> #include <linux/poll.h> #include <uapi/linux/userio.h> #define USERIO_NAME "userio" #define USERIO_BUFSIZE 16 static struct miscdevice userio_misc; struct userio_device { struct serio *serio; struct mutex mutex; bool running; u8 head; u8 tail; spinlock_t buf_lock; unsigned char buf[USERIO_BUFSIZE]; wait_queue_head_t waitq; }; /** * userio_device_write - Write data from serio to a userio device in userspace * @id: The serio port for the userio device * @val: The data to write to the device */ static int userio_device_write(struct serio *id, unsigned char val) { struct userio_device *userio = id->port_data; unsigned long flags; spin_lock_irqsave(&userio->buf_lock, flags); userio->buf[userio->head] = val; userio->head = (userio->head + 1) % USERIO_BUFSIZE; if (userio->head == userio->tail) dev_warn(userio_misc.this_device, "Buffer overflowed, userio client isn't keeping up"); spin_unlock_irqrestore(&userio->buf_lock, flags); wake_up_interruptible(&userio->waitq); return 0; } static int userio_char_open(struct inode *inode, struct file *file) { struct userio_device *userio; userio = kzalloc(sizeof(struct userio_device), GFP_KERNEL); if (!userio) return -ENOMEM; mutex_init(&userio->mutex); spin_lock_init(&userio->buf_lock); init_waitqueue_head(&userio->waitq); userio->serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!userio->serio) { kfree(userio); return -ENOMEM; } userio->serio->write = userio_device_write; userio->serio->port_data = userio; file->private_data = userio; return 0; } static int userio_char_release(struct inode *inode, struct file *file) { struct userio_device *userio = file->private_data; if (userio->running) { /* * Don't free the serio port here, serio_unregister_port() * does it for us. */ serio_unregister_port(userio->serio); } else { kfree(userio->serio); } kfree(userio); return 0; } static ssize_t userio_char_read(struct file *file, char __user *user_buffer, size_t count, loff_t *ppos) { struct userio_device *userio = file->private_data; int error; size_t nonwrap_len, copylen; unsigned char buf[USERIO_BUFSIZE]; unsigned long flags; /* * By the time we get here, the data that was waiting might have * been taken by another thread. Grab the buffer lock and check if * there's still any data waiting, otherwise repeat this process * until we have data (unless the file descriptor is non-blocking * of course). */ for (;;) { spin_lock_irqsave(&userio->buf_lock, flags); nonwrap_len = CIRC_CNT_TO_END(userio->head, userio->tail, USERIO_BUFSIZE); copylen = min(nonwrap_len, count); if (copylen) { memcpy(buf, &userio->buf[userio->tail], copylen); userio->tail = (userio->tail + copylen) % USERIO_BUFSIZE; } spin_unlock_irqrestore(&userio->buf_lock, flags); if (nonwrap_len) break; /* buffer was/is empty */ if (file->f_flags & O_NONBLOCK) return -EAGAIN; /* * count == 0 is special - no IO is done but we check * for error conditions (see above). */ if (count == 0) return 0; error = wait_event_interruptible(userio->waitq, userio->head != userio->tail); if (error) return error; } if (copylen) if (copy_to_user(user_buffer, buf, copylen)) return -EFAULT; return copylen; } static ssize_t userio_char_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct userio_device *userio = file->private_data; struct userio_cmd cmd; int error; if (count != sizeof(cmd)) { dev_warn(userio_misc.this_device, "Invalid payload size\n"); return -EINVAL; } if (copy_from_user(&cmd, buffer, sizeof(cmd))) return -EFAULT; error = mutex_lock_interruptible(&userio->mutex); if (error) return error; switch (cmd.type) { case USERIO_CMD_REGISTER: if (!userio->serio->id.type) { dev_warn(userio_misc.this_device, "No port type given on /dev/userio\n"); error = -EINVAL; goto out; } if (userio->running) { dev_warn(userio_misc.this_device, "Begin command sent, but we're already running\n"); error = -EBUSY; goto out; } userio->running = true; serio_register_port(userio->serio); break; case USERIO_CMD_SET_PORT_TYPE: if (userio->running) { dev_warn(userio_misc.this_device, "Can't change port type on an already running userio instance\n"); error = -EBUSY; goto out; } userio->serio->id.type = cmd.data; break; case USERIO_CMD_SEND_INTERRUPT: if (!userio->running) { dev_warn(userio_misc.this_device, "The device must be registered before sending interrupts\n"); error = -ENODEV; goto out; } serio_interrupt(userio->serio, cmd.data, 0); break; default: error = -EOPNOTSUPP; goto out; } out: mutex_unlock(&userio->mutex); return error ?: count; } static __poll_t userio_char_poll(struct file *file, poll_table *wait) { struct userio_device *userio = file->private_data; poll_wait(file, &userio->waitq, wait); if (userio->head != userio->tail) return EPOLLIN | EPOLLRDNORM; return 0; } static const struct file_operations userio_fops = { .owner = THIS_MODULE, .open = userio_char_open, .release = userio_char_release, .read = userio_char_read, .write = userio_char_write, .poll = userio_char_poll, .llseek = no_llseek, }; static struct miscdevice userio_misc = { .fops = &userio_fops, .minor = USERIO_MINOR, .name = USERIO_NAME, }; module_driver(userio_misc, misc_register, misc_deregister); MODULE_ALIAS_MISCDEV(USERIO_MINOR); MODULE_ALIAS("devname:" USERIO_NAME); MODULE_AUTHOR("Stephen Chandler Paul <[email protected]>"); MODULE_DESCRIPTION("Virtual Serio Device Support"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/userio.c
// SPDX-License-Identifier: GPL-2.0 /* * SGI IOC3 PS/2 controller driver for linux * * Copyright (C) 2019 Thomas Bogendoerfer <[email protected]> * * Based on code Copyright (C) 2005 Stanislaw Skowronek <[email protected]> * Copyright (C) 2009 Johannes Dickgreber <[email protected]> */ #include <linux/delay.h> #include <linux/init.h> #include <linux/io.h> #include <linux/serio.h> #include <linux/module.h> #include <linux/platform_device.h> #include <asm/sn/ioc3.h> struct ioc3kbd_data { struct ioc3_serioregs __iomem *regs; struct serio *kbd, *aux; bool kbd_exists, aux_exists; int irq; }; static int ioc3kbd_wait(struct ioc3_serioregs __iomem *regs, u32 mask) { unsigned long timeout = 0; while ((readl(&regs->km_csr) & mask) && (timeout < 250)) { udelay(50); timeout++; } return (timeout >= 250) ? -ETIMEDOUT : 0; } static int ioc3kbd_write(struct serio *dev, u8 val) { struct ioc3kbd_data *d = dev->port_data; int ret; ret = ioc3kbd_wait(d->regs, KM_CSR_K_WRT_PEND); if (ret) return ret; writel(val, &d->regs->k_wd); return 0; } static int ioc3kbd_start(struct serio *dev) { struct ioc3kbd_data *d = dev->port_data; d->kbd_exists = true; return 0; } static void ioc3kbd_stop(struct serio *dev) { struct ioc3kbd_data *d = dev->port_data; d->kbd_exists = false; } static int ioc3aux_write(struct serio *dev, u8 val) { struct ioc3kbd_data *d = dev->port_data; int ret; ret = ioc3kbd_wait(d->regs, KM_CSR_M_WRT_PEND); if (ret) return ret; writel(val, &d->regs->m_wd); return 0; } static int ioc3aux_start(struct serio *dev) { struct ioc3kbd_data *d = dev->port_data; d->aux_exists = true; return 0; } static void ioc3aux_stop(struct serio *dev) { struct ioc3kbd_data *d = dev->port_data; d->aux_exists = false; } static void ioc3kbd_process_data(struct serio *dev, u32 data) { if (data & KM_RD_VALID_0) serio_interrupt(dev, (data >> KM_RD_DATA_0_SHIFT) & 0xff, 0); if (data & KM_RD_VALID_1) serio_interrupt(dev, (data >> KM_RD_DATA_1_SHIFT) & 0xff, 0); if (data & KM_RD_VALID_2) serio_interrupt(dev, (data >> KM_RD_DATA_2_SHIFT) & 0xff, 0); } static irqreturn_t ioc3kbd_intr(int itq, void *dev_id) { struct ioc3kbd_data *d = dev_id; u32 data_k, data_m; data_k = readl(&d->regs->k_rd); if (d->kbd_exists) ioc3kbd_process_data(d->kbd, data_k); data_m = readl(&d->regs->m_rd); if (d->aux_exists) ioc3kbd_process_data(d->aux, data_m); return IRQ_HANDLED; } static int ioc3kbd_probe(struct platform_device *pdev) { struct ioc3_serioregs __iomem *regs; struct device *dev = &pdev->dev; struct ioc3kbd_data *d; struct serio *sk, *sa; int irq, ret; regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(regs)) return PTR_ERR(regs); irq = platform_get_irq(pdev, 0); if (irq < 0) return -ENXIO; d = devm_kzalloc(dev, sizeof(*d), GFP_KERNEL); if (!d) return -ENOMEM; sk = kzalloc(sizeof(*sk), GFP_KERNEL); if (!sk) return -ENOMEM; sa = kzalloc(sizeof(*sa), GFP_KERNEL); if (!sa) { kfree(sk); return -ENOMEM; } sk->id.type = SERIO_8042; sk->write = ioc3kbd_write; sk->start = ioc3kbd_start; sk->stop = ioc3kbd_stop; snprintf(sk->name, sizeof(sk->name), "IOC3 keyboard %d", pdev->id); snprintf(sk->phys, sizeof(sk->phys), "ioc3/serio%dkbd", pdev->id); sk->port_data = d; sk->dev.parent = dev; sa->id.type = SERIO_8042; sa->write = ioc3aux_write; sa->start = ioc3aux_start; sa->stop = ioc3aux_stop; snprintf(sa->name, sizeof(sa->name), "IOC3 auxiliary %d", pdev->id); snprintf(sa->phys, sizeof(sa->phys), "ioc3/serio%daux", pdev->id); sa->port_data = d; sa->dev.parent = dev; d->regs = regs; d->kbd = sk; d->aux = sa; d->irq = irq; platform_set_drvdata(pdev, d); serio_register_port(d->kbd); serio_register_port(d->aux); ret = request_irq(irq, ioc3kbd_intr, IRQF_SHARED, "ioc3-kbd", d); if (ret) { dev_err(dev, "could not request IRQ %d\n", irq); serio_unregister_port(d->kbd); serio_unregister_port(d->aux); return ret; } /* enable ports */ writel(KM_CSR_K_CLAMP_3 | KM_CSR_M_CLAMP_3, &regs->km_csr); return 0; } static int ioc3kbd_remove(struct platform_device *pdev) { struct ioc3kbd_data *d = platform_get_drvdata(pdev); free_irq(d->irq, d); serio_unregister_port(d->kbd); serio_unregister_port(d->aux); return 0; } static struct platform_driver ioc3kbd_driver = { .probe = ioc3kbd_probe, .remove = ioc3kbd_remove, .driver = { .name = "ioc3-kbd", }, }; module_platform_driver(ioc3kbd_driver); MODULE_AUTHOR("Thomas Bogendoerfer <[email protected]>"); MODULE_DESCRIPTION("SGI IOC3 serio driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/ioc3kbd.c
// SPDX-License-Identifier: GPL-2.0-only /* * GPIO based serio bus driver for bit banging the PS/2 protocol * * Author: Danilo Krummrich <[email protected]> */ #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/serio.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/workqueue.h> #include <linux/completion.h> #include <linux/mutex.h> #include <linux/preempt.h> #include <linux/property.h> #include <linux/of.h> #include <linux/jiffies.h> #include <linux/delay.h> #include <linux/timekeeping.h> #define DRIVER_NAME "ps2-gpio" #define PS2_MODE_RX 0 #define PS2_MODE_TX 1 #define PS2_START_BIT 0 #define PS2_DATA_BIT0 1 #define PS2_DATA_BIT1 2 #define PS2_DATA_BIT2 3 #define PS2_DATA_BIT3 4 #define PS2_DATA_BIT4 5 #define PS2_DATA_BIT5 6 #define PS2_DATA_BIT6 7 #define PS2_DATA_BIT7 8 #define PS2_PARITY_BIT 9 #define PS2_STOP_BIT 10 #define PS2_ACK_BIT 11 #define PS2_DEV_RET_ACK 0xfa #define PS2_DEV_RET_NACK 0xfe #define PS2_CMD_RESEND 0xfe /* * The PS2 protocol specifies a clock frequency between 10kHz and 16.7kHz, * therefore the maximal interrupt interval should be 100us and the minimum * interrupt interval should be ~60us. Let's allow +/- 20us for frequency * deviations and interrupt latency. * * The data line must be samples after ~30us to 50us after the falling edge, * since the device updates the data line at the rising edge. * * ___ ______ ______ ______ ___ * \ / \ / \ / \ / * \ / \ / \ / \ / * \______/ \______/ \______/ \______/ * * |-----------------| |--------| * 60us/100us 30us/50us */ #define PS2_CLK_FREQ_MIN_HZ 10000 #define PS2_CLK_FREQ_MAX_HZ 16700 #define PS2_CLK_MIN_INTERVAL_US ((1000 * 1000) / PS2_CLK_FREQ_MAX_HZ) #define PS2_CLK_MAX_INTERVAL_US ((1000 * 1000) / PS2_CLK_FREQ_MIN_HZ) #define PS2_IRQ_MIN_INTERVAL_US (PS2_CLK_MIN_INTERVAL_US - 20) #define PS2_IRQ_MAX_INTERVAL_US (PS2_CLK_MAX_INTERVAL_US + 20) struct ps2_gpio_data { struct device *dev; struct serio *serio; unsigned char mode; struct gpio_desc *gpio_clk; struct gpio_desc *gpio_data; bool write_enable; int irq; ktime_t t_irq_now; ktime_t t_irq_last; struct { unsigned char cnt; unsigned char byte; } rx; struct { unsigned char cnt; unsigned char byte; ktime_t t_xfer_start; ktime_t t_xfer_end; struct completion complete; struct mutex mutex; struct delayed_work work; } tx; }; static int ps2_gpio_open(struct serio *serio) { struct ps2_gpio_data *drvdata = serio->port_data; drvdata->t_irq_last = 0; drvdata->tx.t_xfer_end = 0; enable_irq(drvdata->irq); return 0; } static void ps2_gpio_close(struct serio *serio) { struct ps2_gpio_data *drvdata = serio->port_data; flush_delayed_work(&drvdata->tx.work); disable_irq(drvdata->irq); } static int __ps2_gpio_write(struct serio *serio, unsigned char val) { struct ps2_gpio_data *drvdata = serio->port_data; disable_irq_nosync(drvdata->irq); gpiod_direction_output(drvdata->gpio_clk, 0); drvdata->mode = PS2_MODE_TX; drvdata->tx.byte = val; schedule_delayed_work(&drvdata->tx.work, usecs_to_jiffies(200)); return 0; } static int ps2_gpio_write(struct serio *serio, unsigned char val) { struct ps2_gpio_data *drvdata = serio->port_data; int ret = 0; if (in_task()) { mutex_lock(&drvdata->tx.mutex); __ps2_gpio_write(serio, val); if (!wait_for_completion_timeout(&drvdata->tx.complete, msecs_to_jiffies(10000))) ret = SERIO_TIMEOUT; mutex_unlock(&drvdata->tx.mutex); } else { __ps2_gpio_write(serio, val); } return ret; } static void ps2_gpio_tx_work_fn(struct work_struct *work) { struct delayed_work *dwork = to_delayed_work(work); struct ps2_gpio_data *drvdata = container_of(dwork, struct ps2_gpio_data, tx.work); drvdata->tx.t_xfer_start = ktime_get(); enable_irq(drvdata->irq); gpiod_direction_output(drvdata->gpio_data, 0); gpiod_direction_input(drvdata->gpio_clk); } static irqreturn_t ps2_gpio_irq_rx(struct ps2_gpio_data *drvdata) { unsigned char byte, cnt; int data; int rxflags = 0; s64 us_delta; byte = drvdata->rx.byte; cnt = drvdata->rx.cnt; drvdata->t_irq_now = ktime_get(); /* * We need to consider spurious interrupts happening right after * a TX xfer finished. */ us_delta = ktime_us_delta(drvdata->t_irq_now, drvdata->tx.t_xfer_end); if (unlikely(us_delta < PS2_IRQ_MIN_INTERVAL_US)) goto end; us_delta = ktime_us_delta(drvdata->t_irq_now, drvdata->t_irq_last); if (us_delta > PS2_IRQ_MAX_INTERVAL_US && cnt) { dev_err(drvdata->dev, "RX: timeout, probably we missed an interrupt\n"); goto err; } else if (unlikely(us_delta < PS2_IRQ_MIN_INTERVAL_US)) { /* Ignore spurious IRQs. */ goto end; } drvdata->t_irq_last = drvdata->t_irq_now; data = gpiod_get_value(drvdata->gpio_data); if (unlikely(data < 0)) { dev_err(drvdata->dev, "RX: failed to get data gpio val: %d\n", data); goto err; } switch (cnt) { case PS2_START_BIT: /* start bit should be low */ if (unlikely(data)) { dev_err(drvdata->dev, "RX: start bit should be low\n"); goto err; } break; case PS2_DATA_BIT0: case PS2_DATA_BIT1: case PS2_DATA_BIT2: case PS2_DATA_BIT3: case PS2_DATA_BIT4: case PS2_DATA_BIT5: case PS2_DATA_BIT6: case PS2_DATA_BIT7: /* processing data bits */ if (data) byte |= (data << (cnt - 1)); break; case PS2_PARITY_BIT: /* check odd parity */ if (!((hweight8(byte) & 1) ^ data)) { rxflags |= SERIO_PARITY; dev_warn(drvdata->dev, "RX: parity error\n"); if (!drvdata->write_enable) goto err; } break; case PS2_STOP_BIT: /* stop bit should be high */ if (unlikely(!data)) { dev_err(drvdata->dev, "RX: stop bit should be high\n"); goto err; } /* * Do not send spurious ACK's and NACK's when write fn is * not provided. */ if (!drvdata->write_enable) { if (byte == PS2_DEV_RET_NACK) goto err; else if (byte == PS2_DEV_RET_ACK) break; } serio_interrupt(drvdata->serio, byte, rxflags); dev_dbg(drvdata->dev, "RX: sending byte 0x%x\n", byte); cnt = byte = 0; goto end; /* success */ default: dev_err(drvdata->dev, "RX: got out of sync with the device\n"); goto err; } cnt++; goto end; /* success */ err: cnt = byte = 0; __ps2_gpio_write(drvdata->serio, PS2_CMD_RESEND); end: drvdata->rx.cnt = cnt; drvdata->rx.byte = byte; return IRQ_HANDLED; } static irqreturn_t ps2_gpio_irq_tx(struct ps2_gpio_data *drvdata) { unsigned char byte, cnt; int data; s64 us_delta; cnt = drvdata->tx.cnt; byte = drvdata->tx.byte; drvdata->t_irq_now = ktime_get(); /* * There might be pending IRQs since we disabled IRQs in * __ps2_gpio_write(). We can expect at least one clock period until * the device generates the first falling edge after releasing the * clock line. */ us_delta = ktime_us_delta(drvdata->t_irq_now, drvdata->tx.t_xfer_start); if (unlikely(us_delta < PS2_CLK_MIN_INTERVAL_US)) goto end; us_delta = ktime_us_delta(drvdata->t_irq_now, drvdata->t_irq_last); if (us_delta > PS2_IRQ_MAX_INTERVAL_US && cnt > 1) { dev_err(drvdata->dev, "TX: timeout, probably we missed an interrupt\n"); goto err; } else if (unlikely(us_delta < PS2_IRQ_MIN_INTERVAL_US)) { /* Ignore spurious IRQs. */ goto end; } drvdata->t_irq_last = drvdata->t_irq_now; switch (cnt) { case PS2_START_BIT: /* should never happen */ dev_err(drvdata->dev, "TX: start bit should have been sent already\n"); goto err; case PS2_DATA_BIT0: case PS2_DATA_BIT1: case PS2_DATA_BIT2: case PS2_DATA_BIT3: case PS2_DATA_BIT4: case PS2_DATA_BIT5: case PS2_DATA_BIT6: case PS2_DATA_BIT7: data = byte & BIT(cnt - 1); gpiod_set_value(drvdata->gpio_data, data); break; case PS2_PARITY_BIT: /* do odd parity */ data = !(hweight8(byte) & 1); gpiod_set_value(drvdata->gpio_data, data); break; case PS2_STOP_BIT: /* release data line to generate stop bit */ gpiod_direction_input(drvdata->gpio_data); break; case PS2_ACK_BIT: data = gpiod_get_value(drvdata->gpio_data); if (data) { dev_warn(drvdata->dev, "TX: received NACK, retry\n"); goto err; } drvdata->tx.t_xfer_end = ktime_get(); drvdata->mode = PS2_MODE_RX; complete(&drvdata->tx.complete); cnt = 1; goto end; /* success */ default: /* * Probably we missed the stop bit. Therefore we release data * line and try again. */ gpiod_direction_input(drvdata->gpio_data); dev_err(drvdata->dev, "TX: got out of sync with the device\n"); goto err; } cnt++; goto end; /* success */ err: cnt = 1; gpiod_direction_input(drvdata->gpio_data); __ps2_gpio_write(drvdata->serio, drvdata->tx.byte); end: drvdata->tx.cnt = cnt; return IRQ_HANDLED; } static irqreturn_t ps2_gpio_irq(int irq, void *dev_id) { struct ps2_gpio_data *drvdata = dev_id; return drvdata->mode ? ps2_gpio_irq_tx(drvdata) : ps2_gpio_irq_rx(drvdata); } static int ps2_gpio_get_props(struct device *dev, struct ps2_gpio_data *drvdata) { enum gpiod_flags gflags; /* Enforce open drain, since this is required by the PS/2 bus. */ gflags = GPIOD_IN | GPIOD_FLAGS_BIT_OPEN_DRAIN; drvdata->gpio_data = devm_gpiod_get(dev, "data", gflags); if (IS_ERR(drvdata->gpio_data)) { dev_err(dev, "failed to request data gpio: %ld", PTR_ERR(drvdata->gpio_data)); return PTR_ERR(drvdata->gpio_data); } drvdata->gpio_clk = devm_gpiod_get(dev, "clk", gflags); if (IS_ERR(drvdata->gpio_clk)) { dev_err(dev, "failed to request clock gpio: %ld", PTR_ERR(drvdata->gpio_clk)); return PTR_ERR(drvdata->gpio_clk); } drvdata->write_enable = device_property_read_bool(dev, "write-enable"); return 0; } static int ps2_gpio_probe(struct platform_device *pdev) { struct ps2_gpio_data *drvdata; struct serio *serio; struct device *dev = &pdev->dev; int error; drvdata = devm_kzalloc(dev, sizeof(struct ps2_gpio_data), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!drvdata || !serio) { error = -ENOMEM; goto err_free_serio; } error = ps2_gpio_get_props(dev, drvdata); if (error) goto err_free_serio; if (gpiod_cansleep(drvdata->gpio_data) || gpiod_cansleep(drvdata->gpio_clk)) { dev_err(dev, "GPIO data or clk are connected via slow bus\n"); error = -EINVAL; goto err_free_serio; } drvdata->irq = platform_get_irq(pdev, 0); if (drvdata->irq < 0) { error = drvdata->irq; goto err_free_serio; } error = devm_request_irq(dev, drvdata->irq, ps2_gpio_irq, IRQF_NO_THREAD, DRIVER_NAME, drvdata); if (error) { dev_err(dev, "failed to request irq %d: %d\n", drvdata->irq, error); goto err_free_serio; } /* Keep irq disabled until serio->open is called. */ disable_irq(drvdata->irq); serio->id.type = SERIO_8042; serio->open = ps2_gpio_open; serio->close = ps2_gpio_close; /* * Write can be enabled in platform/dt data, but possibly it will not * work because of the tough timings. */ serio->write = drvdata->write_enable ? ps2_gpio_write : NULL; serio->port_data = drvdata; serio->dev.parent = dev; strscpy(serio->name, dev_name(dev), sizeof(serio->name)); strscpy(serio->phys, dev_name(dev), sizeof(serio->phys)); drvdata->serio = serio; drvdata->dev = dev; drvdata->mode = PS2_MODE_RX; /* * Tx count always starts at 1, as the start bit is sent implicitly by * host-to-device communication initialization. */ drvdata->tx.cnt = 1; INIT_DELAYED_WORK(&drvdata->tx.work, ps2_gpio_tx_work_fn); init_completion(&drvdata->tx.complete); mutex_init(&drvdata->tx.mutex); serio_register_port(serio); platform_set_drvdata(pdev, drvdata); return 0; /* success */ err_free_serio: kfree(serio); return error; } static int ps2_gpio_remove(struct platform_device *pdev) { struct ps2_gpio_data *drvdata = platform_get_drvdata(pdev); serio_unregister_port(drvdata->serio); return 0; } #if defined(CONFIG_OF) static const struct of_device_id ps2_gpio_match[] = { { .compatible = "ps2-gpio", }, { }, }; MODULE_DEVICE_TABLE(of, ps2_gpio_match); #endif static struct platform_driver ps2_gpio_driver = { .probe = ps2_gpio_probe, .remove = ps2_gpio_remove, .driver = { .name = DRIVER_NAME, .of_match_table = of_match_ptr(ps2_gpio_match), }, }; module_platform_driver(ps2_gpio_driver); MODULE_AUTHOR("Danilo Krummrich <[email protected]>"); MODULE_DESCRIPTION("GPIO PS2 driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/serio/ps2-gpio.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * OLPC serio driver for multiplexed input from Marvell MMP security processor * * Copyright (C) 2011-2013 One Laptop Per Child */ #include <linux/module.h> #include <linux/interrupt.h> #include <linux/serio.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/of.h> #include <linux/slab.h> #include <linux/delay.h> /* * The OLPC XO-1.75 and XO-4 laptops do not have a hardware PS/2 controller. * Instead, the OLPC firmware runs a bit-banging PS/2 implementation on an * otherwise-unused slow processor which is included in the Marvell MMP2/MMP3 * SoC, known as the "Security Processor" (SP) or "Wireless Trusted Module" * (WTM). This firmware then reports its results via the WTM registers, * which we read from the Application Processor (AP, i.e. main CPU) in this * driver. * * On the hardware side we have a PS/2 mouse and an AT keyboard, the data * is multiplexed through this system. We create a serio port for each one, * and demultiplex the data accordingly. */ /* WTM register offsets */ #define SECURE_PROCESSOR_COMMAND 0x40 #define COMMAND_RETURN_STATUS 0x80 #define COMMAND_FIFO_STATUS 0xc4 #define PJ_RST_INTERRUPT 0xc8 #define PJ_INTERRUPT_MASK 0xcc /* * The upper byte of SECURE_PROCESSOR_COMMAND and COMMAND_RETURN_STATUS is * used to identify which port (device) is being talked to. The lower byte * is the data being sent/received. */ #define PORT_MASK 0xff00 #define DATA_MASK 0x00ff #define PORT_SHIFT 8 #define KEYBOARD_PORT 0 #define TOUCHPAD_PORT 1 /* COMMAND_FIFO_STATUS */ #define CMD_CNTR_MASK 0x7 /* Number of pending/unprocessed commands */ #define MAX_PENDING_CMDS 4 /* from device specs */ /* PJ_RST_INTERRUPT */ #define SP_COMMAND_COMPLETE_RESET 0x1 /* PJ_INTERRUPT_MASK */ #define INT_0 (1 << 0) /* COMMAND_FIFO_STATUS */ #define CMD_STS_MASK 0x100 struct olpc_apsp { struct device *dev; struct serio *kbio; struct serio *padio; void __iomem *base; int open_count; int irq; }; static int olpc_apsp_write(struct serio *port, unsigned char val) { struct olpc_apsp *priv = port->port_data; unsigned int i; u32 which = 0; if (port == priv->padio) which = TOUCHPAD_PORT << PORT_SHIFT; else which = KEYBOARD_PORT << PORT_SHIFT; dev_dbg(priv->dev, "olpc_apsp_write which=%x val=%x\n", which, val); for (i = 0; i < 50; i++) { u32 sts = readl(priv->base + COMMAND_FIFO_STATUS); if ((sts & CMD_CNTR_MASK) < MAX_PENDING_CMDS) { writel(which | val, priv->base + SECURE_PROCESSOR_COMMAND); return 0; } /* SP busy. This has not been seen in practice. */ mdelay(1); } dev_dbg(priv->dev, "olpc_apsp_write timeout, status=%x\n", readl(priv->base + COMMAND_FIFO_STATUS)); return -ETIMEDOUT; } static irqreturn_t olpc_apsp_rx(int irq, void *dev_id) { struct olpc_apsp *priv = dev_id; unsigned int w, tmp; struct serio *serio; /* * Write 1 to PJ_RST_INTERRUPT to acknowledge and clear the interrupt * Write 0xff00 to SECURE_PROCESSOR_COMMAND. */ tmp = readl(priv->base + PJ_RST_INTERRUPT); if (!(tmp & SP_COMMAND_COMPLETE_RESET)) { dev_warn(priv->dev, "spurious interrupt?\n"); return IRQ_NONE; } w = readl(priv->base + COMMAND_RETURN_STATUS); dev_dbg(priv->dev, "olpc_apsp_rx %x\n", w); if (w >> PORT_SHIFT == KEYBOARD_PORT) serio = priv->kbio; else serio = priv->padio; serio_interrupt(serio, w & DATA_MASK, 0); /* Ack and clear interrupt */ writel(tmp | SP_COMMAND_COMPLETE_RESET, priv->base + PJ_RST_INTERRUPT); writel(PORT_MASK, priv->base + SECURE_PROCESSOR_COMMAND); pm_wakeup_event(priv->dev, 1000); return IRQ_HANDLED; } static int olpc_apsp_open(struct serio *port) { struct olpc_apsp *priv = port->port_data; unsigned int tmp; unsigned long l; if (priv->open_count++ == 0) { l = readl(priv->base + COMMAND_FIFO_STATUS); if (!(l & CMD_STS_MASK)) { dev_err(priv->dev, "SP cannot accept commands.\n"); return -EIO; } /* Enable interrupt 0 by clearing its bit */ tmp = readl(priv->base + PJ_INTERRUPT_MASK); writel(tmp & ~INT_0, priv->base + PJ_INTERRUPT_MASK); } return 0; } static void olpc_apsp_close(struct serio *port) { struct olpc_apsp *priv = port->port_data; unsigned int tmp; if (--priv->open_count == 0) { /* Disable interrupt 0 */ tmp = readl(priv->base + PJ_INTERRUPT_MASK); writel(tmp | INT_0, priv->base + PJ_INTERRUPT_MASK); } } static int olpc_apsp_probe(struct platform_device *pdev) { struct serio *kb_serio, *pad_serio; struct olpc_apsp *priv; int error; priv = devm_kzalloc(&pdev->dev, sizeof(struct olpc_apsp), GFP_KERNEL); if (!priv) return -ENOMEM; priv->dev = &pdev->dev; priv->base = devm_platform_get_and_ioremap_resource(pdev, 0, NULL); if (IS_ERR(priv->base)) { dev_err(&pdev->dev, "Failed to map WTM registers\n"); return PTR_ERR(priv->base); } priv->irq = platform_get_irq(pdev, 0); if (priv->irq < 0) return priv->irq; /* KEYBOARD */ kb_serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!kb_serio) return -ENOMEM; kb_serio->id.type = SERIO_8042_XL; kb_serio->write = olpc_apsp_write; kb_serio->open = olpc_apsp_open; kb_serio->close = olpc_apsp_close; kb_serio->port_data = priv; kb_serio->dev.parent = &pdev->dev; strscpy(kb_serio->name, "sp keyboard", sizeof(kb_serio->name)); strscpy(kb_serio->phys, "sp/serio0", sizeof(kb_serio->phys)); priv->kbio = kb_serio; serio_register_port(kb_serio); /* TOUCHPAD */ pad_serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!pad_serio) { error = -ENOMEM; goto err_pad; } pad_serio->id.type = SERIO_8042; pad_serio->write = olpc_apsp_write; pad_serio->open = olpc_apsp_open; pad_serio->close = olpc_apsp_close; pad_serio->port_data = priv; pad_serio->dev.parent = &pdev->dev; strscpy(pad_serio->name, "sp touchpad", sizeof(pad_serio->name)); strscpy(pad_serio->phys, "sp/serio1", sizeof(pad_serio->phys)); priv->padio = pad_serio; serio_register_port(pad_serio); error = request_irq(priv->irq, olpc_apsp_rx, 0, "olpc-apsp", priv); if (error) { dev_err(&pdev->dev, "Failed to request IRQ\n"); goto err_irq; } device_init_wakeup(priv->dev, 1); platform_set_drvdata(pdev, priv); dev_dbg(&pdev->dev, "probed successfully.\n"); return 0; err_irq: serio_unregister_port(pad_serio); err_pad: serio_unregister_port(kb_serio); return error; } static int olpc_apsp_remove(struct platform_device *pdev) { struct olpc_apsp *priv = platform_get_drvdata(pdev); free_irq(priv->irq, priv); serio_unregister_port(priv->kbio); serio_unregister_port(priv->padio); return 0; } static const struct of_device_id olpc_apsp_dt_ids[] = { { .compatible = "olpc,ap-sp", }, {} }; MODULE_DEVICE_TABLE(of, olpc_apsp_dt_ids); static struct platform_driver olpc_apsp_driver = { .probe = olpc_apsp_probe, .remove = olpc_apsp_remove, .driver = { .name = "olpc-apsp", .of_match_table = olpc_apsp_dt_ids, }, }; MODULE_DESCRIPTION("OLPC AP-SP serio driver"); MODULE_LICENSE("GPL"); module_platform_driver(olpc_apsp_driver);
linux-master
drivers/input/serio/olpc_apsp.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Allwinner A10 PS2 host controller * * Author: Vishnu Patekar <[email protected]> * Aaron.maoye <[email protected]> */ #include <linux/module.h> #include <linux/serio.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/mod_devicetable.h> #include <linux/platform_device.h> #define DRIVER_NAME "sun4i-ps2" /* register offset definitions */ #define PS2_REG_GCTL 0x00 /* PS2 Module Global Control Reg */ #define PS2_REG_DATA 0x04 /* PS2 Module Data Reg */ #define PS2_REG_LCTL 0x08 /* PS2 Module Line Control Reg */ #define PS2_REG_LSTS 0x0C /* PS2 Module Line Status Reg */ #define PS2_REG_FCTL 0x10 /* PS2 Module FIFO Control Reg */ #define PS2_REG_FSTS 0x14 /* PS2 Module FIFO Status Reg */ #define PS2_REG_CLKDR 0x18 /* PS2 Module Clock Divider Reg*/ /* PS2 GLOBAL CONTROL REGISTER PS2_GCTL */ #define PS2_GCTL_INTFLAG BIT(4) #define PS2_GCTL_INTEN BIT(3) #define PS2_GCTL_RESET BIT(2) #define PS2_GCTL_MASTER BIT(1) #define PS2_GCTL_BUSEN BIT(0) /* PS2 LINE CONTROL REGISTER */ #define PS2_LCTL_NOACK BIT(18) #define PS2_LCTL_TXDTOEN BIT(8) #define PS2_LCTL_STOPERREN BIT(3) #define PS2_LCTL_ACKERREN BIT(2) #define PS2_LCTL_PARERREN BIT(1) #define PS2_LCTL_RXDTOEN BIT(0) /* PS2 LINE STATUS REGISTER */ #define PS2_LSTS_TXTDO BIT(8) #define PS2_LSTS_STOPERR BIT(3) #define PS2_LSTS_ACKERR BIT(2) #define PS2_LSTS_PARERR BIT(1) #define PS2_LSTS_RXTDO BIT(0) #define PS2_LINE_ERROR_BIT \ (PS2_LSTS_TXTDO | PS2_LSTS_STOPERR | PS2_LSTS_ACKERR | \ PS2_LSTS_PARERR | PS2_LSTS_RXTDO) /* PS2 FIFO CONTROL REGISTER */ #define PS2_FCTL_TXRST BIT(17) #define PS2_FCTL_RXRST BIT(16) #define PS2_FCTL_TXUFIEN BIT(10) #define PS2_FCTL_TXOFIEN BIT(9) #define PS2_FCTL_TXRDYIEN BIT(8) #define PS2_FCTL_RXUFIEN BIT(2) #define PS2_FCTL_RXOFIEN BIT(1) #define PS2_FCTL_RXRDYIEN BIT(0) /* PS2 FIFO STATUS REGISTER */ #define PS2_FSTS_TXUF BIT(10) #define PS2_FSTS_TXOF BIT(9) #define PS2_FSTS_TXRDY BIT(8) #define PS2_FSTS_RXUF BIT(2) #define PS2_FSTS_RXOF BIT(1) #define PS2_FSTS_RXRDY BIT(0) #define PS2_FIFO_ERROR_BIT \ (PS2_FSTS_TXUF | PS2_FSTS_TXOF | PS2_FSTS_RXUF | PS2_FSTS_RXOF) #define PS2_SAMPLE_CLK 1000000 #define PS2_SCLK 125000 struct sun4i_ps2data { struct serio *serio; struct device *dev; /* IO mapping base */ void __iomem *reg_base; /* clock management */ struct clk *clk; /* irq */ spinlock_t lock; int irq; }; static irqreturn_t sun4i_ps2_interrupt(int irq, void *dev_id) { struct sun4i_ps2data *drvdata = dev_id; u32 intr_status; u32 fifo_status; unsigned char byte; unsigned int rxflags = 0; u32 rval; spin_lock(&drvdata->lock); /* Get the PS/2 interrupts and clear them */ intr_status = readl(drvdata->reg_base + PS2_REG_LSTS); fifo_status = readl(drvdata->reg_base + PS2_REG_FSTS); /* Check line status register */ if (intr_status & PS2_LINE_ERROR_BIT) { rxflags = (intr_status & PS2_LINE_ERROR_BIT) ? SERIO_FRAME : 0; rxflags |= (intr_status & PS2_LSTS_PARERR) ? SERIO_PARITY : 0; rxflags |= (intr_status & PS2_LSTS_PARERR) ? SERIO_TIMEOUT : 0; rval = PS2_LSTS_TXTDO | PS2_LSTS_STOPERR | PS2_LSTS_ACKERR | PS2_LSTS_PARERR | PS2_LSTS_RXTDO; writel(rval, drvdata->reg_base + PS2_REG_LSTS); } /* Check FIFO status register */ if (fifo_status & PS2_FIFO_ERROR_BIT) { rval = PS2_FSTS_TXUF | PS2_FSTS_TXOF | PS2_FSTS_TXRDY | PS2_FSTS_RXUF | PS2_FSTS_RXOF | PS2_FSTS_RXRDY; writel(rval, drvdata->reg_base + PS2_REG_FSTS); } rval = (fifo_status >> 16) & 0x3; while (rval--) { byte = readl(drvdata->reg_base + PS2_REG_DATA) & 0xff; serio_interrupt(drvdata->serio, byte, rxflags); } writel(intr_status, drvdata->reg_base + PS2_REG_LSTS); writel(fifo_status, drvdata->reg_base + PS2_REG_FSTS); spin_unlock(&drvdata->lock); return IRQ_HANDLED; } static int sun4i_ps2_open(struct serio *serio) { struct sun4i_ps2data *drvdata = serio->port_data; u32 src_clk = 0; u32 clk_scdf; u32 clk_pcdf; u32 rval; unsigned long flags; /* Set line control and enable interrupt */ rval = PS2_LCTL_STOPERREN | PS2_LCTL_ACKERREN | PS2_LCTL_PARERREN | PS2_LCTL_RXDTOEN; writel(rval, drvdata->reg_base + PS2_REG_LCTL); /* Reset FIFO */ rval = PS2_FCTL_TXRST | PS2_FCTL_RXRST | PS2_FCTL_TXUFIEN | PS2_FCTL_TXOFIEN | PS2_FCTL_RXUFIEN | PS2_FCTL_RXOFIEN | PS2_FCTL_RXRDYIEN; writel(rval, drvdata->reg_base + PS2_REG_FCTL); src_clk = clk_get_rate(drvdata->clk); /* Set clock divider register */ clk_scdf = src_clk / PS2_SAMPLE_CLK - 1; clk_pcdf = PS2_SAMPLE_CLK / PS2_SCLK - 1; rval = (clk_scdf << 8) | clk_pcdf; writel(rval, drvdata->reg_base + PS2_REG_CLKDR); /* Set global control register */ rval = PS2_GCTL_RESET | PS2_GCTL_INTEN | PS2_GCTL_MASTER | PS2_GCTL_BUSEN; spin_lock_irqsave(&drvdata->lock, flags); writel(rval, drvdata->reg_base + PS2_REG_GCTL); spin_unlock_irqrestore(&drvdata->lock, flags); return 0; } static void sun4i_ps2_close(struct serio *serio) { struct sun4i_ps2data *drvdata = serio->port_data; u32 rval; /* Shut off the interrupt */ rval = readl(drvdata->reg_base + PS2_REG_GCTL); writel(rval & ~(PS2_GCTL_INTEN), drvdata->reg_base + PS2_REG_GCTL); synchronize_irq(drvdata->irq); } static int sun4i_ps2_write(struct serio *serio, unsigned char val) { unsigned long expire = jiffies + msecs_to_jiffies(10000); struct sun4i_ps2data *drvdata = serio->port_data; do { if (readl(drvdata->reg_base + PS2_REG_FSTS) & PS2_FSTS_TXRDY) { writel(val, drvdata->reg_base + PS2_REG_DATA); return 0; } } while (time_before(jiffies, expire)); return SERIO_TIMEOUT; } static int sun4i_ps2_probe(struct platform_device *pdev) { struct resource *res; /* IO mem resources */ struct sun4i_ps2data *drvdata; struct serio *serio; struct device *dev = &pdev->dev; int error; drvdata = kzalloc(sizeof(struct sun4i_ps2data), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!drvdata || !serio) { error = -ENOMEM; goto err_free_mem; } spin_lock_init(&drvdata->lock); /* IO */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(dev, "failed to locate registers\n"); error = -ENXIO; goto err_free_mem; } drvdata->reg_base = ioremap(res->start, resource_size(res)); if (!drvdata->reg_base) { dev_err(dev, "failed to map registers\n"); error = -ENOMEM; goto err_free_mem; } drvdata->clk = clk_get(dev, NULL); if (IS_ERR(drvdata->clk)) { error = PTR_ERR(drvdata->clk); dev_err(dev, "couldn't get clock %d\n", error); goto err_ioremap; } error = clk_prepare_enable(drvdata->clk); if (error) { dev_err(dev, "failed to enable clock %d\n", error); goto err_clk; } serio->id.type = SERIO_8042; serio->write = sun4i_ps2_write; serio->open = sun4i_ps2_open; serio->close = sun4i_ps2_close; serio->port_data = drvdata; serio->dev.parent = dev; strscpy(serio->name, dev_name(dev), sizeof(serio->name)); strscpy(serio->phys, dev_name(dev), sizeof(serio->phys)); /* shutoff interrupt */ writel(0, drvdata->reg_base + PS2_REG_GCTL); /* Get IRQ for the device */ drvdata->irq = platform_get_irq(pdev, 0); if (drvdata->irq < 0) { error = drvdata->irq; goto err_disable_clk; } drvdata->serio = serio; drvdata->dev = dev; error = request_irq(drvdata->irq, sun4i_ps2_interrupt, 0, DRIVER_NAME, drvdata); if (error) { dev_err(drvdata->dev, "failed to allocate interrupt %d: %d\n", drvdata->irq, error); goto err_disable_clk; } serio_register_port(serio); platform_set_drvdata(pdev, drvdata); return 0; /* success */ err_disable_clk: clk_disable_unprepare(drvdata->clk); err_clk: clk_put(drvdata->clk); err_ioremap: iounmap(drvdata->reg_base); err_free_mem: kfree(serio); kfree(drvdata); return error; } static int sun4i_ps2_remove(struct platform_device *pdev) { struct sun4i_ps2data *drvdata = platform_get_drvdata(pdev); serio_unregister_port(drvdata->serio); free_irq(drvdata->irq, drvdata); clk_disable_unprepare(drvdata->clk); clk_put(drvdata->clk); iounmap(drvdata->reg_base); kfree(drvdata); return 0; } static const struct of_device_id sun4i_ps2_match[] = { { .compatible = "allwinner,sun4i-a10-ps2", }, { }, }; MODULE_DEVICE_TABLE(of, sun4i_ps2_match); static struct platform_driver sun4i_ps2_driver = { .probe = sun4i_ps2_probe, .remove = sun4i_ps2_remove, .driver = { .name = DRIVER_NAME, .of_match_table = sun4i_ps2_match, }, }; module_platform_driver(sun4i_ps2_driver); MODULE_AUTHOR("Vishnu Patekar <[email protected]>"); MODULE_AUTHOR("Aaron.maoye <[email protected]>"); MODULE_DESCRIPTION("Allwinner A10/Sun4i PS/2 driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/serio/sun4i-ps2.c
// SPDX-License-Identifier: GPL-2.0-only /* * Amstrad E3 (Delta) keyboard port driver * * Copyright (c) 2006 Matt Callow * Copyright (c) 2010 Janusz Krzysztofik * * Thanks to Cliff Lawson for his help * * The Amstrad Delta keyboard (aka mailboard) uses normal PC-AT style serial * transmission. The keyboard port is formed of two GPIO lines, for clock * and data. Due to strict timing requirements of the interface, * the serial data stream is read and processed by a FIQ handler. * The resulting words are fetched by this driver from a circular buffer. * * Standard AT keyboard driver (atkbd) is used for handling the keyboard data. * However, when used with the E3 mailboard that producecs non-standard * scancodes, a custom key table must be prepared and loaded from userspace. */ #include <linux/irq.h> #include <linux/platform_data/ams-delta-fiq.h> #include <linux/platform_device.h> #include <linux/regulator/consumer.h> #include <linux/serio.h> #include <linux/slab.h> #include <linux/module.h> #define DRIVER_NAME "ams-delta-serio" MODULE_AUTHOR("Matt Callow"); MODULE_DESCRIPTION("AMS Delta (E3) keyboard port driver"); MODULE_LICENSE("GPL"); struct ams_delta_serio { struct serio *serio; struct regulator *vcc; unsigned int *fiq_buffer; }; static int check_data(struct serio *serio, int data) { int i, parity = 0; /* check valid stop bit */ if (!(data & 0x400)) { dev_warn(&serio->dev, "invalid stop bit, data=0x%X\n", data); return SERIO_FRAME; } /* calculate the parity */ for (i = 1; i < 10; i++) { if (data & (1 << i)) parity++; } /* it should be odd */ if (!(parity & 0x01)) { dev_warn(&serio->dev, "parity check failed, data=0x%X parity=0x%X\n", data, parity); return SERIO_PARITY; } return 0; } static irqreturn_t ams_delta_serio_interrupt(int irq, void *dev_id) { struct ams_delta_serio *priv = dev_id; int *circ_buff = &priv->fiq_buffer[FIQ_CIRC_BUFF]; int data, dfl; u8 scancode; priv->fiq_buffer[FIQ_IRQ_PEND] = 0; /* * Read data from the circular buffer, check it * and then pass it on the serio */ while (priv->fiq_buffer[FIQ_KEYS_CNT] > 0) { data = circ_buff[priv->fiq_buffer[FIQ_HEAD_OFFSET]++]; priv->fiq_buffer[FIQ_KEYS_CNT]--; if (priv->fiq_buffer[FIQ_HEAD_OFFSET] == priv->fiq_buffer[FIQ_BUF_LEN]) priv->fiq_buffer[FIQ_HEAD_OFFSET] = 0; dfl = check_data(priv->serio, data); scancode = (u8) (data >> 1) & 0xFF; serio_interrupt(priv->serio, scancode, dfl); } return IRQ_HANDLED; } static int ams_delta_serio_open(struct serio *serio) { struct ams_delta_serio *priv = serio->port_data; /* enable keyboard */ return regulator_enable(priv->vcc); } static void ams_delta_serio_close(struct serio *serio) { struct ams_delta_serio *priv = serio->port_data; /* disable keyboard */ regulator_disable(priv->vcc); } static int ams_delta_serio_init(struct platform_device *pdev) { struct ams_delta_serio *priv; struct serio *serio; int irq, err; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->fiq_buffer = pdev->dev.platform_data; if (!priv->fiq_buffer) return -EINVAL; priv->vcc = devm_regulator_get(&pdev->dev, "vcc"); if (IS_ERR(priv->vcc)) { err = PTR_ERR(priv->vcc); dev_err(&pdev->dev, "regulator request failed (%d)\n", err); /* * When running on a non-dt platform and requested regulator * is not available, devm_regulator_get() never returns * -EPROBE_DEFER as it is not able to justify if the regulator * may still appear later. On the other hand, the board can * still set full constriants flag at late_initcall in order * to instruct devm_regulator_get() to returnn a dummy one * if sufficient. Hence, if we get -ENODEV here, let's convert * it to -EPROBE_DEFER and wait for the board to decide or * let Deferred Probe infrastructure handle this error. */ if (err == -ENODEV) err = -EPROBE_DEFER; return err; } irq = platform_get_irq(pdev, 0); if (irq < 0) return -ENXIO; err = devm_request_irq(&pdev->dev, irq, ams_delta_serio_interrupt, IRQ_TYPE_EDGE_RISING, DRIVER_NAME, priv); if (err < 0) { dev_err(&pdev->dev, "IRQ request failed (%d)\n", err); return err; } serio = kzalloc(sizeof(*serio), GFP_KERNEL); if (!serio) return -ENOMEM; priv->serio = serio; serio->id.type = SERIO_8042; serio->open = ams_delta_serio_open; serio->close = ams_delta_serio_close; strscpy(serio->name, "AMS DELTA keyboard adapter", sizeof(serio->name)); strscpy(serio->phys, dev_name(&pdev->dev), sizeof(serio->phys)); serio->dev.parent = &pdev->dev; serio->port_data = priv; serio_register_port(serio); platform_set_drvdata(pdev, priv); dev_info(&serio->dev, "%s\n", serio->name); return 0; } static int ams_delta_serio_exit(struct platform_device *pdev) { struct ams_delta_serio *priv = platform_get_drvdata(pdev); serio_unregister_port(priv->serio); return 0; } static struct platform_driver ams_delta_serio_driver = { .probe = ams_delta_serio_init, .remove = ams_delta_serio_exit, .driver = { .name = DRIVER_NAME }, }; module_platform_driver(ams_delta_serio_driver);
linux-master
drivers/input/serio/ams_delta_serio.c
// SPDX-License-Identifier: GPL-2.0-only /* * Input device TTY line discipline * * Copyright (c) 1999-2002 Vojtech Pavlik * * This is a module that converts a tty line into a much simpler * 'serial io port' abstraction that the input device drivers use. */ #include <linux/uaccess.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/serio.h> #include <linux/tty.h> #include <linux/compat.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Input device TTY line discipline"); MODULE_LICENSE("GPL"); MODULE_ALIAS_LDISC(N_MOUSE); #define SERPORT_BUSY 1 #define SERPORT_ACTIVE 2 #define SERPORT_DEAD 3 struct serport { struct tty_struct *tty; wait_queue_head_t wait; struct serio *serio; struct serio_device_id id; spinlock_t lock; unsigned long flags; }; /* * Callback functions from the serio code. */ static int serport_serio_write(struct serio *serio, unsigned char data) { struct serport *serport = serio->port_data; return -(serport->tty->ops->write(serport->tty, &data, 1) != 1); } static int serport_serio_open(struct serio *serio) { struct serport *serport = serio->port_data; unsigned long flags; spin_lock_irqsave(&serport->lock, flags); set_bit(SERPORT_ACTIVE, &serport->flags); spin_unlock_irqrestore(&serport->lock, flags); return 0; } static void serport_serio_close(struct serio *serio) { struct serport *serport = serio->port_data; unsigned long flags; spin_lock_irqsave(&serport->lock, flags); clear_bit(SERPORT_ACTIVE, &serport->flags); spin_unlock_irqrestore(&serport->lock, flags); } /* * serport_ldisc_open() is the routine that is called upon setting our line * discipline on a tty. It prepares the serio struct. */ static int serport_ldisc_open(struct tty_struct *tty) { struct serport *serport; if (!capable(CAP_SYS_ADMIN)) return -EPERM; serport = kzalloc(sizeof(struct serport), GFP_KERNEL); if (!serport) return -ENOMEM; serport->tty = tty; spin_lock_init(&serport->lock); init_waitqueue_head(&serport->wait); tty->disc_data = serport; tty->receive_room = 256; set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); return 0; } /* * serport_ldisc_close() is the opposite of serport_ldisc_open() */ static void serport_ldisc_close(struct tty_struct *tty) { struct serport *serport = tty->disc_data; kfree(serport); } /* * serport_ldisc_receive() is called by the low level tty driver when characters * are ready for us. We forward the characters and flags, one by one to the * 'interrupt' routine. */ static void serport_ldisc_receive(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count) { struct serport *serport = tty->disc_data; unsigned long flags; unsigned int ch_flags = 0; int i; spin_lock_irqsave(&serport->lock, flags); if (!test_bit(SERPORT_ACTIVE, &serport->flags)) goto out; for (i = 0; i < count; i++) { if (fp) { switch (fp[i]) { case TTY_FRAME: ch_flags = SERIO_FRAME; break; case TTY_PARITY: ch_flags = SERIO_PARITY; break; default: ch_flags = 0; break; } } serio_interrupt(serport->serio, cp[i], ch_flags); } out: spin_unlock_irqrestore(&serport->lock, flags); } /* * serport_ldisc_read() just waits indefinitely if everything goes well. * However, when the serio driver closes the serio port, it finishes, * returning 0 characters. */ static ssize_t serport_ldisc_read(struct tty_struct * tty, struct file * file, u8 *kbuf, size_t nr, void **cookie, unsigned long offset) { struct serport *serport = tty->disc_data; struct serio *serio; if (test_and_set_bit(SERPORT_BUSY, &serport->flags)) return -EBUSY; serport->serio = serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; strscpy(serio->name, "Serial port", sizeof(serio->name)); snprintf(serio->phys, sizeof(serio->phys), "%s/serio0", tty_name(tty)); serio->id = serport->id; serio->id.type = SERIO_RS232; serio->write = serport_serio_write; serio->open = serport_serio_open; serio->close = serport_serio_close; serio->port_data = serport; serio->dev.parent = tty->dev; serio_register_port(serport->serio); printk(KERN_INFO "serio: Serial port %s\n", tty_name(tty)); wait_event_interruptible(serport->wait, test_bit(SERPORT_DEAD, &serport->flags)); serio_unregister_port(serport->serio); serport->serio = NULL; clear_bit(SERPORT_DEAD, &serport->flags); clear_bit(SERPORT_BUSY, &serport->flags); return 0; } static void serport_set_type(struct tty_struct *tty, unsigned long type) { struct serport *serport = tty->disc_data; serport->id.proto = type & 0x000000ff; serport->id.id = (type & 0x0000ff00) >> 8; serport->id.extra = (type & 0x00ff0000) >> 16; } /* * serport_ldisc_ioctl() allows to set the port protocol, and device ID */ static int serport_ldisc_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { if (cmd == SPIOCSTYPE) { unsigned long type; if (get_user(type, (unsigned long __user *) arg)) return -EFAULT; serport_set_type(tty, type); return 0; } return -EINVAL; } #ifdef CONFIG_COMPAT #define COMPAT_SPIOCSTYPE _IOW('q', 0x01, compat_ulong_t) static int serport_ldisc_compat_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { if (cmd == COMPAT_SPIOCSTYPE) { void __user *uarg = compat_ptr(arg); compat_ulong_t compat_type; if (get_user(compat_type, (compat_ulong_t __user *)uarg)) return -EFAULT; serport_set_type(tty, compat_type); return 0; } return -EINVAL; } #endif static void serport_ldisc_hangup(struct tty_struct *tty) { struct serport *serport = tty->disc_data; unsigned long flags; spin_lock_irqsave(&serport->lock, flags); set_bit(SERPORT_DEAD, &serport->flags); spin_unlock_irqrestore(&serport->lock, flags); wake_up_interruptible(&serport->wait); } static void serport_ldisc_write_wakeup(struct tty_struct * tty) { struct serport *serport = tty->disc_data; unsigned long flags; spin_lock_irqsave(&serport->lock, flags); if (test_bit(SERPORT_ACTIVE, &serport->flags)) serio_drv_write_wakeup(serport->serio); spin_unlock_irqrestore(&serport->lock, flags); } /* * The line discipline structure. */ static struct tty_ldisc_ops serport_ldisc = { .owner = THIS_MODULE, .num = N_MOUSE, .name = "input", .open = serport_ldisc_open, .close = serport_ldisc_close, .read = serport_ldisc_read, .ioctl = serport_ldisc_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = serport_ldisc_compat_ioctl, #endif .receive_buf = serport_ldisc_receive, .hangup = serport_ldisc_hangup, .write_wakeup = serport_ldisc_write_wakeup }; /* * The functions for insering/removing us as a module. */ static int __init serport_init(void) { int retval; retval = tty_register_ldisc(&serport_ldisc); if (retval) printk(KERN_ERR "serport.c: Error registering line discipline.\n"); return retval; } static void __exit serport_exit(void) { tty_unregister_ldisc(&serport_ldisc); } module_init(serport_init); module_exit(serport_exit);
linux-master
drivers/input/serio/serport.c
// SPDX-License-Identifier: GPL-2.0-only /* * Raw serio device providing access to a raw byte stream from underlying * serio port. Closely emulates behavior of pre-2.6 /dev/psaux device * * Copyright (c) 2004 Dmitry Torokhov */ #include <linux/kref.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/module.h> #include <linux/serio.h> #include <linux/major.h> #include <linux/device.h> #include <linux/miscdevice.h> #include <linux/wait.h> #include <linux/mutex.h> #define DRIVER_DESC "Raw serio driver" MODULE_AUTHOR("Dmitry Torokhov <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); #define SERIO_RAW_QUEUE_LEN 64 struct serio_raw { unsigned char queue[SERIO_RAW_QUEUE_LEN]; unsigned int tail, head; char name[16]; struct kref kref; struct serio *serio; struct miscdevice dev; wait_queue_head_t wait; struct list_head client_list; struct list_head node; bool dead; }; struct serio_raw_client { struct fasync_struct *fasync; struct serio_raw *serio_raw; struct list_head node; }; static DEFINE_MUTEX(serio_raw_mutex); static LIST_HEAD(serio_raw_list); /********************************************************************* * Interface with userspace (file operations) * *********************************************************************/ static int serio_raw_fasync(int fd, struct file *file, int on) { struct serio_raw_client *client = file->private_data; return fasync_helper(fd, file, on, &client->fasync); } static struct serio_raw *serio_raw_locate(int minor) { struct serio_raw *serio_raw; list_for_each_entry(serio_raw, &serio_raw_list, node) { if (serio_raw->dev.minor == minor) return serio_raw; } return NULL; } static int serio_raw_open(struct inode *inode, struct file *file) { struct serio_raw *serio_raw; struct serio_raw_client *client; int retval; retval = mutex_lock_interruptible(&serio_raw_mutex); if (retval) return retval; serio_raw = serio_raw_locate(iminor(inode)); if (!serio_raw) { retval = -ENODEV; goto out; } if (serio_raw->dead) { retval = -ENODEV; goto out; } client = kzalloc(sizeof(struct serio_raw_client), GFP_KERNEL); if (!client) { retval = -ENOMEM; goto out; } client->serio_raw = serio_raw; file->private_data = client; kref_get(&serio_raw->kref); serio_pause_rx(serio_raw->serio); list_add_tail(&client->node, &serio_raw->client_list); serio_continue_rx(serio_raw->serio); out: mutex_unlock(&serio_raw_mutex); return retval; } static void serio_raw_free(struct kref *kref) { struct serio_raw *serio_raw = container_of(kref, struct serio_raw, kref); put_device(&serio_raw->serio->dev); kfree(serio_raw); } static int serio_raw_release(struct inode *inode, struct file *file) { struct serio_raw_client *client = file->private_data; struct serio_raw *serio_raw = client->serio_raw; serio_pause_rx(serio_raw->serio); list_del(&client->node); serio_continue_rx(serio_raw->serio); kfree(client); kref_put(&serio_raw->kref, serio_raw_free); return 0; } static bool serio_raw_fetch_byte(struct serio_raw *serio_raw, char *c) { bool empty; serio_pause_rx(serio_raw->serio); empty = serio_raw->head == serio_raw->tail; if (!empty) { *c = serio_raw->queue[serio_raw->tail]; serio_raw->tail = (serio_raw->tail + 1) % SERIO_RAW_QUEUE_LEN; } serio_continue_rx(serio_raw->serio); return !empty; } static ssize_t serio_raw_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct serio_raw_client *client = file->private_data; struct serio_raw *serio_raw = client->serio_raw; char c; ssize_t read = 0; int error; for (;;) { if (serio_raw->dead) return -ENODEV; if (serio_raw->head == serio_raw->tail && (file->f_flags & O_NONBLOCK)) return -EAGAIN; if (count == 0) break; while (read < count && serio_raw_fetch_byte(serio_raw, &c)) { if (put_user(c, buffer++)) return -EFAULT; read++; } if (read) break; if (!(file->f_flags & O_NONBLOCK)) { error = wait_event_interruptible(serio_raw->wait, serio_raw->head != serio_raw->tail || serio_raw->dead); if (error) return error; } } return read; } static ssize_t serio_raw_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct serio_raw_client *client = file->private_data; struct serio_raw *serio_raw = client->serio_raw; int retval = 0; unsigned char c; retval = mutex_lock_interruptible(&serio_raw_mutex); if (retval) return retval; if (serio_raw->dead) { retval = -ENODEV; goto out; } if (count > 32) count = 32; while (count--) { if (get_user(c, buffer++)) { retval = -EFAULT; goto out; } if (serio_write(serio_raw->serio, c)) { /* Either signal error or partial write */ if (retval == 0) retval = -EIO; goto out; } retval++; } out: mutex_unlock(&serio_raw_mutex); return retval; } static __poll_t serio_raw_poll(struct file *file, poll_table *wait) { struct serio_raw_client *client = file->private_data; struct serio_raw *serio_raw = client->serio_raw; __poll_t mask; poll_wait(file, &serio_raw->wait, wait); mask = serio_raw->dead ? EPOLLHUP | EPOLLERR : EPOLLOUT | EPOLLWRNORM; if (serio_raw->head != serio_raw->tail) mask |= EPOLLIN | EPOLLRDNORM; return mask; } static const struct file_operations serio_raw_fops = { .owner = THIS_MODULE, .open = serio_raw_open, .release = serio_raw_release, .read = serio_raw_read, .write = serio_raw_write, .poll = serio_raw_poll, .fasync = serio_raw_fasync, .llseek = noop_llseek, }; /********************************************************************* * Interface with serio port * *********************************************************************/ static irqreturn_t serio_raw_interrupt(struct serio *serio, unsigned char data, unsigned int dfl) { struct serio_raw *serio_raw = serio_get_drvdata(serio); struct serio_raw_client *client; unsigned int head = serio_raw->head; /* we are holding serio->lock here so we are protected */ serio_raw->queue[head] = data; head = (head + 1) % SERIO_RAW_QUEUE_LEN; if (likely(head != serio_raw->tail)) { serio_raw->head = head; list_for_each_entry(client, &serio_raw->client_list, node) kill_fasync(&client->fasync, SIGIO, POLL_IN); wake_up_interruptible(&serio_raw->wait); } return IRQ_HANDLED; } static int serio_raw_connect(struct serio *serio, struct serio_driver *drv) { static atomic_t serio_raw_no = ATOMIC_INIT(-1); struct serio_raw *serio_raw; int err; serio_raw = kzalloc(sizeof(struct serio_raw), GFP_KERNEL); if (!serio_raw) { dev_dbg(&serio->dev, "can't allocate memory for a device\n"); return -ENOMEM; } snprintf(serio_raw->name, sizeof(serio_raw->name), "serio_raw%ld", (long)atomic_inc_return(&serio_raw_no)); kref_init(&serio_raw->kref); INIT_LIST_HEAD(&serio_raw->client_list); init_waitqueue_head(&serio_raw->wait); serio_raw->serio = serio; get_device(&serio->dev); serio_set_drvdata(serio, serio_raw); err = serio_open(serio, drv); if (err) goto err_free; err = mutex_lock_killable(&serio_raw_mutex); if (err) goto err_close; list_add_tail(&serio_raw->node, &serio_raw_list); mutex_unlock(&serio_raw_mutex); serio_raw->dev.minor = PSMOUSE_MINOR; serio_raw->dev.name = serio_raw->name; serio_raw->dev.parent = &serio->dev; serio_raw->dev.fops = &serio_raw_fops; err = misc_register(&serio_raw->dev); if (err) { serio_raw->dev.minor = MISC_DYNAMIC_MINOR; err = misc_register(&serio_raw->dev); } if (err) { dev_err(&serio->dev, "failed to register raw access device for %s\n", serio->phys); goto err_unlink; } dev_info(&serio->dev, "raw access enabled on %s (%s, minor %d)\n", serio->phys, serio_raw->name, serio_raw->dev.minor); return 0; err_unlink: list_del_init(&serio_raw->node); err_close: serio_close(serio); err_free: serio_set_drvdata(serio, NULL); kref_put(&serio_raw->kref, serio_raw_free); return err; } static int serio_raw_reconnect(struct serio *serio) { struct serio_raw *serio_raw = serio_get_drvdata(serio); struct serio_driver *drv = serio->drv; if (!drv || !serio_raw) { dev_dbg(&serio->dev, "reconnect request, but serio is disconnected, ignoring...\n"); return -1; } /* * Nothing needs to be done here, we just need this method to * keep the same device. */ return 0; } /* * Wake up users waiting for IO so they can disconnect from * dead device. */ static void serio_raw_hangup(struct serio_raw *serio_raw) { struct serio_raw_client *client; serio_pause_rx(serio_raw->serio); list_for_each_entry(client, &serio_raw->client_list, node) kill_fasync(&client->fasync, SIGIO, POLL_HUP); serio_continue_rx(serio_raw->serio); wake_up_interruptible(&serio_raw->wait); } static void serio_raw_disconnect(struct serio *serio) { struct serio_raw *serio_raw = serio_get_drvdata(serio); misc_deregister(&serio_raw->dev); mutex_lock(&serio_raw_mutex); serio_raw->dead = true; list_del_init(&serio_raw->node); mutex_unlock(&serio_raw_mutex); serio_raw_hangup(serio_raw); serio_close(serio); kref_put(&serio_raw->kref, serio_raw_free); serio_set_drvdata(serio, NULL); } static const struct serio_device_id serio_raw_serio_ids[] = { { .type = SERIO_8042, .proto = SERIO_ANY, .id = SERIO_ANY, .extra = SERIO_ANY, }, { .type = SERIO_8042_XL, .proto = SERIO_ANY, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, serio_raw_serio_ids); static struct serio_driver serio_raw_drv = { .driver = { .name = "serio_raw", }, .description = DRIVER_DESC, .id_table = serio_raw_serio_ids, .interrupt = serio_raw_interrupt, .connect = serio_raw_connect, .reconnect = serio_raw_reconnect, .disconnect = serio_raw_disconnect, .manual_bind = true, }; module_serio_driver(serio_raw_drv);
linux-master
drivers/input/serio/serio_raw.c
// SPDX-License-Identifier: GPL-2.0-only /* * SGI O2 MACE PS2 controller driver for linux * * Copyright (C) 2002 Vivien Chappelier */ #include <linux/module.h> #include <linux/init.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/err.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/ip32/mace.h> #include <asm/ip32/ip32_ints.h> MODULE_AUTHOR("Vivien Chappelier <[email protected]"); MODULE_DESCRIPTION("SGI O2 MACE PS2 controller driver"); MODULE_LICENSE("GPL"); #define MACE_PS2_TIMEOUT 10000 /* in 50us unit */ #define PS2_STATUS_CLOCK_SIGNAL BIT(0) /* external clock signal */ #define PS2_STATUS_CLOCK_INHIBIT BIT(1) /* clken output signal */ #define PS2_STATUS_TX_INPROGRESS BIT(2) /* transmission in progress */ #define PS2_STATUS_TX_EMPTY BIT(3) /* empty transmit buffer */ #define PS2_STATUS_RX_FULL BIT(4) /* full receive buffer */ #define PS2_STATUS_RX_INPROGRESS BIT(5) /* reception in progress */ #define PS2_STATUS_ERROR_PARITY BIT(6) /* parity error */ #define PS2_STATUS_ERROR_FRAMING BIT(7) /* framing error */ #define PS2_CONTROL_TX_CLOCK_DISABLE BIT(0) /* inhibit clock signal after TX */ #define PS2_CONTROL_TX_ENABLE BIT(1) /* transmit enable */ #define PS2_CONTROL_TX_INT_ENABLE BIT(2) /* enable transmit interrupt */ #define PS2_CONTROL_RX_INT_ENABLE BIT(3) /* enable receive interrupt */ #define PS2_CONTROL_RX_CLOCK_ENABLE BIT(4) /* pause reception if set to 0 */ #define PS2_CONTROL_RESET BIT(5) /* reset */ struct maceps2_data { struct mace_ps2port *port; int irq; }; static struct maceps2_data port_data[2]; static struct serio *maceps2_port[2]; static struct platform_device *maceps2_device; static int maceps2_write(struct serio *dev, unsigned char val) { struct mace_ps2port *port = ((struct maceps2_data *)dev->port_data)->port; unsigned int timeout = MACE_PS2_TIMEOUT; do { if (port->status & PS2_STATUS_TX_EMPTY) { port->tx = val; return 0; } udelay(50); } while (timeout--); return -1; } static irqreturn_t maceps2_interrupt(int irq, void *dev_id) { struct serio *dev = dev_id; struct mace_ps2port *port = ((struct maceps2_data *)dev->port_data)->port; unsigned long byte; if (port->status & PS2_STATUS_RX_FULL) { byte = port->rx; serio_interrupt(dev, byte & 0xff, 0); } return IRQ_HANDLED; } static int maceps2_open(struct serio *dev) { struct maceps2_data *data = (struct maceps2_data *)dev->port_data; if (request_irq(data->irq, maceps2_interrupt, 0, "PS2 port", dev)) { printk(KERN_ERR "Could not allocate PS/2 IRQ\n"); return -EBUSY; } /* Reset port */ data->port->control = PS2_CONTROL_TX_CLOCK_DISABLE | PS2_CONTROL_RESET; udelay(100); /* Enable interrupts */ data->port->control = PS2_CONTROL_RX_CLOCK_ENABLE | PS2_CONTROL_TX_ENABLE | PS2_CONTROL_RX_INT_ENABLE; return 0; } static void maceps2_close(struct serio *dev) { struct maceps2_data *data = (struct maceps2_data *)dev->port_data; data->port->control = PS2_CONTROL_TX_CLOCK_DISABLE | PS2_CONTROL_RESET; udelay(100); free_irq(data->irq, dev); } static struct serio *maceps2_allocate_port(int idx) { struct serio *serio; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (serio) { serio->id.type = SERIO_8042; serio->write = maceps2_write; serio->open = maceps2_open; serio->close = maceps2_close; snprintf(serio->name, sizeof(serio->name), "MACE PS/2 port%d", idx); snprintf(serio->phys, sizeof(serio->phys), "mace/serio%d", idx); serio->port_data = &port_data[idx]; serio->dev.parent = &maceps2_device->dev; } return serio; } static int maceps2_probe(struct platform_device *dev) { maceps2_port[0] = maceps2_allocate_port(0); maceps2_port[1] = maceps2_allocate_port(1); if (!maceps2_port[0] || !maceps2_port[1]) { kfree(maceps2_port[0]); kfree(maceps2_port[1]); return -ENOMEM; } serio_register_port(maceps2_port[0]); serio_register_port(maceps2_port[1]); return 0; } static int maceps2_remove(struct platform_device *dev) { serio_unregister_port(maceps2_port[0]); serio_unregister_port(maceps2_port[1]); return 0; } static struct platform_driver maceps2_driver = { .driver = { .name = "maceps2", }, .probe = maceps2_probe, .remove = maceps2_remove, }; static int __init maceps2_init(void) { int error; error = platform_driver_register(&maceps2_driver); if (error) return error; maceps2_device = platform_device_alloc("maceps2", -1); if (!maceps2_device) { error = -ENOMEM; goto err_unregister_driver; } port_data[0].port = &mace->perif.ps2.keyb; port_data[0].irq = MACEISA_KEYB_IRQ; port_data[1].port = &mace->perif.ps2.mouse; port_data[1].irq = MACEISA_MOUSE_IRQ; error = platform_device_add(maceps2_device); if (error) goto err_free_device; return 0; err_free_device: platform_device_put(maceps2_device); err_unregister_driver: platform_driver_unregister(&maceps2_driver); return error; } static void __exit maceps2_exit(void) { platform_device_unregister(maceps2_device); platform_driver_unregister(&maceps2_driver); } module_init(maceps2_init); module_exit(maceps2_exit);
linux-master
drivers/input/serio/maceps2.c
/* * Access to HP-HIL MLC through HP System Device Controller. * * Copyright (c) 2001 Brian S. Julin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL"). * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * References: * HP-HIL Technical Reference Manual. Hewlett Packard Product No. 45918A * System Device Controller Microprocessor Firmware Theory of Operation * for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2 * */ #include <linux/hil_mlc.h> #include <linux/hp_sdc.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/string.h> #include <linux/semaphore.h> #define PREFIX "HP SDC MLC: " static hil_mlc hp_sdc_mlc; MODULE_AUTHOR("Brian S. Julin <[email protected]>"); MODULE_DESCRIPTION("Glue for onboard HIL MLC in HP-PARISC machines"); MODULE_LICENSE("Dual BSD/GPL"); static struct hp_sdc_mlc_priv_s { int emtestmode; hp_sdc_transaction trans; u8 tseq[16]; int got5x; } hp_sdc_mlc_priv; /************************* Interrupt context ******************************/ static void hp_sdc_mlc_isr (int irq, void *dev_id, uint8_t status, uint8_t data) { int idx; hil_mlc *mlc = &hp_sdc_mlc; write_lock(&mlc->lock); if (mlc->icount < 0) { printk(KERN_WARNING PREFIX "HIL Overflow!\n"); up(&mlc->isem); goto out; } idx = 15 - mlc->icount; if ((status & HP_SDC_STATUS_IRQMASK) == HP_SDC_STATUS_HILDATA) { mlc->ipacket[idx] |= data | HIL_ERR_INT; mlc->icount--; if (hp_sdc_mlc_priv.got5x || !idx) goto check; if ((mlc->ipacket[idx - 1] & HIL_PKT_ADDR_MASK) != (mlc->ipacket[idx] & HIL_PKT_ADDR_MASK)) { mlc->ipacket[idx] &= ~HIL_PKT_ADDR_MASK; mlc->ipacket[idx] |= (mlc->ipacket[idx - 1] & HIL_PKT_ADDR_MASK); } goto check; } /* We know status is 5X */ if (data & HP_SDC_HIL_ISERR) goto err; mlc->ipacket[idx] = (data & HP_SDC_HIL_R1MASK) << HIL_PKT_ADDR_SHIFT; hp_sdc_mlc_priv.got5x = 1; goto out; check: hp_sdc_mlc_priv.got5x = 0; if (mlc->imatch == 0) goto done; if ((mlc->imatch == (HIL_ERR_INT | HIL_PKT_CMD | HIL_CMD_POL)) && (mlc->ipacket[idx] == (mlc->imatch | idx))) goto done; if (mlc->ipacket[idx] == mlc->imatch) goto done; goto out; err: printk(KERN_DEBUG PREFIX "err code %x\n", data); switch (data) { case HP_SDC_HIL_RC_DONE: printk(KERN_WARNING PREFIX "Bastard SDC reconfigured loop!\n"); break; case HP_SDC_HIL_ERR: mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_PERR | HIL_ERR_FERR | HIL_ERR_FOF; break; case HP_SDC_HIL_TO: mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_LERR; break; case HP_SDC_HIL_RC: printk(KERN_WARNING PREFIX "Bastard SDC decided to reconfigure loop!\n"); break; default: printk(KERN_WARNING PREFIX "Unknown HIL Error status (%x)!\n", data); break; } /* No more data will be coming due to an error. */ done: tasklet_schedule(mlc->tasklet); up(&mlc->isem); out: write_unlock(&mlc->lock); } /******************** Tasklet or userspace context functions ****************/ static int hp_sdc_mlc_in(hil_mlc *mlc, suseconds_t timeout) { struct hp_sdc_mlc_priv_s *priv; int rc = 2; priv = mlc->priv; /* Try to down the semaphore */ if (down_trylock(&mlc->isem)) { if (priv->emtestmode) { mlc->ipacket[0] = HIL_ERR_INT | (mlc->opacket & (HIL_PKT_CMD | HIL_PKT_ADDR_MASK | HIL_PKT_DATA_MASK)); mlc->icount = 14; /* printk(KERN_DEBUG PREFIX ">[%x]\n", mlc->ipacket[0]); */ goto wasup; } if (time_after(jiffies, mlc->instart + mlc->intimeout)) { /* printk("!%i %i", tv.tv_usec - mlc->instart.tv_usec, mlc->intimeout); */ rc = 1; up(&mlc->isem); } goto done; } wasup: up(&mlc->isem); rc = 0; done: return rc; } static int hp_sdc_mlc_cts(hil_mlc *mlc) { struct hp_sdc_mlc_priv_s *priv; priv = mlc->priv; /* Try to down the semaphores -- they should be up. */ BUG_ON(down_trylock(&mlc->isem)); BUG_ON(down_trylock(&mlc->osem)); up(&mlc->isem); up(&mlc->osem); if (down_trylock(&mlc->csem)) { if (priv->trans.act.semaphore != &mlc->csem) goto poll; else goto busy; } if (!(priv->tseq[4] & HP_SDC_USE_LOOP)) goto done; poll: priv->trans.act.semaphore = &mlc->csem; priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.endidx = 5; priv->tseq[0] = HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = HP_SDC_CMD_READ_USE; priv->tseq[2] = 1; priv->tseq[3] = 0; priv->tseq[4] = 0; return __hp_sdc_enqueue_transaction(&priv->trans); busy: return 1; done: priv->trans.act.semaphore = &mlc->osem; up(&mlc->csem); return 0; } static int hp_sdc_mlc_out(hil_mlc *mlc) { struct hp_sdc_mlc_priv_s *priv; priv = mlc->priv; /* Try to down the semaphore -- it should be up. */ BUG_ON(down_trylock(&mlc->osem)); if (mlc->opacket & HIL_DO_ALTER_CTRL) goto do_control; do_data: if (priv->emtestmode) { up(&mlc->osem); return 0; } /* Shouldn't be sending commands when loop may be busy */ BUG_ON(down_trylock(&mlc->csem)); up(&mlc->csem); priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.act.semaphore = &mlc->osem; priv->trans.endidx = 6; priv->tseq[0] = HP_SDC_ACT_DATAREG | HP_SDC_ACT_POSTCMD | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = 0x7; priv->tseq[2] = (mlc->opacket & (HIL_PKT_ADDR_MASK | HIL_PKT_CMD)) >> HIL_PKT_ADDR_SHIFT; priv->tseq[3] = (mlc->opacket & HIL_PKT_DATA_MASK) >> HIL_PKT_DATA_SHIFT; priv->tseq[4] = 0; /* No timeout */ if (priv->tseq[3] == HIL_CMD_DHR) priv->tseq[4] = 1; priv->tseq[5] = HP_SDC_CMD_DO_HIL; goto enqueue; do_control: priv->emtestmode = mlc->opacket & HIL_CTRL_TEST; /* we cannot emulate this, it should not be used. */ BUG_ON((mlc->opacket & (HIL_CTRL_APE | HIL_CTRL_IPF)) == HIL_CTRL_APE); if ((mlc->opacket & HIL_CTRL_ONLY) == HIL_CTRL_ONLY) goto control_only; /* Should not send command/data after engaging APE */ BUG_ON(mlc->opacket & HIL_CTRL_APE); /* Disengaging APE this way would not be valid either since * the loop must be allowed to idle. * * So, it works out that we really never actually send control * and data when using SDC, we just send the data. */ goto do_data; control_only: priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.act.semaphore = &mlc->osem; priv->trans.endidx = 4; priv->tseq[0] = HP_SDC_ACT_PRECMD | HP_SDC_ACT_DATAOUT | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = HP_SDC_CMD_SET_LPC; priv->tseq[2] = 1; /* priv->tseq[3] = (mlc->ddc + 1) | HP_SDC_LPS_ACSUCC; */ priv->tseq[3] = 0; if (mlc->opacket & HIL_CTRL_APE) { priv->tseq[3] |= HP_SDC_LPC_APE_IPF; BUG_ON(down_trylock(&mlc->csem)); } enqueue: return hp_sdc_enqueue_transaction(&priv->trans); } static int __init hp_sdc_mlc_init(void) { hil_mlc *mlc = &hp_sdc_mlc; int err; #ifdef __mc68000__ if (!MACH_IS_HP300) return -ENODEV; #endif printk(KERN_INFO PREFIX "Registering the System Domain Controller's HIL MLC.\n"); hp_sdc_mlc_priv.emtestmode = 0; hp_sdc_mlc_priv.trans.seq = hp_sdc_mlc_priv.tseq; hp_sdc_mlc_priv.trans.act.semaphore = &mlc->osem; hp_sdc_mlc_priv.got5x = 0; mlc->cts = &hp_sdc_mlc_cts; mlc->in = &hp_sdc_mlc_in; mlc->out = &hp_sdc_mlc_out; mlc->priv = &hp_sdc_mlc_priv; err = hil_mlc_register(mlc); if (err) { printk(KERN_WARNING PREFIX "Failed to register MLC structure with hil_mlc\n"); return err; } if (hp_sdc_request_hil_irq(&hp_sdc_mlc_isr)) { printk(KERN_WARNING PREFIX "Request for raw HIL ISR hook denied\n"); if (hil_mlc_unregister(mlc)) printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n" "This is bad. Could cause an oops.\n"); return -EBUSY; } return 0; } static void __exit hp_sdc_mlc_exit(void) { hil_mlc *mlc = &hp_sdc_mlc; if (hp_sdc_release_hil_irq(&hp_sdc_mlc_isr)) printk(KERN_ERR PREFIX "Failed to release the raw HIL ISR hook.\n" "This is bad. Could cause an oops.\n"); if (hil_mlc_unregister(mlc)) printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n" "This is bad. Could cause an oops.\n"); } module_init(hp_sdc_mlc_init); module_exit(hp_sdc_mlc_exit);
linux-master
drivers/input/serio/hp_sdc_mlc.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2013, Microsoft Corporation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/completion.h> #include <linux/hyperv.h> #include <linux/serio.h> #include <linux/slab.h> /* * Current version 1.0 * */ #define SYNTH_KBD_VERSION_MAJOR 1 #define SYNTH_KBD_VERSION_MINOR 0 #define SYNTH_KBD_VERSION (SYNTH_KBD_VERSION_MINOR | \ (SYNTH_KBD_VERSION_MAJOR << 16)) /* * Message types in the synthetic input protocol */ enum synth_kbd_msg_type { SYNTH_KBD_PROTOCOL_REQUEST = 1, SYNTH_KBD_PROTOCOL_RESPONSE = 2, SYNTH_KBD_EVENT = 3, SYNTH_KBD_LED_INDICATORS = 4, }; /* * Basic message structures. */ struct synth_kbd_msg_hdr { __le32 type; }; struct synth_kbd_msg { struct synth_kbd_msg_hdr header; char data[]; /* Enclosed message */ }; union synth_kbd_version { __le32 version; }; /* * Protocol messages */ struct synth_kbd_protocol_request { struct synth_kbd_msg_hdr header; union synth_kbd_version version_requested; }; #define PROTOCOL_ACCEPTED BIT(0) struct synth_kbd_protocol_response { struct synth_kbd_msg_hdr header; __le32 proto_status; }; #define IS_UNICODE BIT(0) #define IS_BREAK BIT(1) #define IS_E0 BIT(2) #define IS_E1 BIT(3) struct synth_kbd_keystroke { struct synth_kbd_msg_hdr header; __le16 make_code; __le16 reserved0; __le32 info; /* Additional information */ }; #define HK_MAXIMUM_MESSAGE_SIZE 256 #define KBD_VSC_SEND_RING_BUFFER_SIZE VMBUS_RING_SIZE(36 * 1024) #define KBD_VSC_RECV_RING_BUFFER_SIZE VMBUS_RING_SIZE(36 * 1024) #define XTKBD_EMUL0 0xe0 #define XTKBD_EMUL1 0xe1 #define XTKBD_RELEASE 0x80 /* * Represents a keyboard device */ struct hv_kbd_dev { struct hv_device *hv_dev; struct serio *hv_serio; struct synth_kbd_protocol_request protocol_req; struct synth_kbd_protocol_response protocol_resp; /* Synchronize the request/response if needed */ struct completion wait_event; spinlock_t lock; /* protects 'started' field */ bool started; }; static void hv_kbd_on_receive(struct hv_device *hv_dev, struct synth_kbd_msg *msg, u32 msg_length) { struct hv_kbd_dev *kbd_dev = hv_get_drvdata(hv_dev); struct synth_kbd_keystroke *ks_msg; unsigned long flags; u32 msg_type = __le32_to_cpu(msg->header.type); u32 info; u16 scan_code; switch (msg_type) { case SYNTH_KBD_PROTOCOL_RESPONSE: /* * Validate the information provided by the host. * If the host is giving us a bogus packet, * drop the packet (hoping the problem * goes away). */ if (msg_length < sizeof(struct synth_kbd_protocol_response)) { dev_err(&hv_dev->device, "Illegal protocol response packet (len: %d)\n", msg_length); break; } memcpy(&kbd_dev->protocol_resp, msg, sizeof(struct synth_kbd_protocol_response)); complete(&kbd_dev->wait_event); break; case SYNTH_KBD_EVENT: /* * Validate the information provided by the host. * If the host is giving us a bogus packet, * drop the packet (hoping the problem * goes away). */ if (msg_length < sizeof(struct synth_kbd_keystroke)) { dev_err(&hv_dev->device, "Illegal keyboard event packet (len: %d)\n", msg_length); break; } ks_msg = (struct synth_kbd_keystroke *)msg; info = __le32_to_cpu(ks_msg->info); /* * Inject the information through the serio interrupt. */ spin_lock_irqsave(&kbd_dev->lock, flags); if (kbd_dev->started) { if (info & IS_E0) serio_interrupt(kbd_dev->hv_serio, XTKBD_EMUL0, 0); if (info & IS_E1) serio_interrupt(kbd_dev->hv_serio, XTKBD_EMUL1, 0); scan_code = __le16_to_cpu(ks_msg->make_code); if (info & IS_BREAK) scan_code |= XTKBD_RELEASE; serio_interrupt(kbd_dev->hv_serio, scan_code, 0); } spin_unlock_irqrestore(&kbd_dev->lock, flags); /* * Only trigger a wakeup on key down, otherwise * "echo freeze > /sys/power/state" can't really enter the * state because the Enter-UP can trigger a wakeup at once. */ if (!(info & IS_BREAK)) pm_wakeup_hard_event(&hv_dev->device); break; default: dev_err(&hv_dev->device, "unhandled message type %d\n", msg_type); } } static void hv_kbd_handle_received_packet(struct hv_device *hv_dev, struct vmpacket_descriptor *desc, u32 bytes_recvd, u64 req_id) { struct synth_kbd_msg *msg; u32 msg_sz; switch (desc->type) { case VM_PKT_COMP: break; case VM_PKT_DATA_INBAND: /* * We have a packet that has "inband" data. The API used * for retrieving the packet guarantees that the complete * packet is read. So, minimally, we should be able to * parse the payload header safely (assuming that the host * can be trusted. Trusting the host seems to be a * reasonable assumption because in a virtualized * environment there is not whole lot you can do if you * don't trust the host. * * Nonetheless, let us validate if the host can be trusted * (in a trivial way). The interesting aspect of this * validation is how do you recover if we discover that the * host is not to be trusted? Simply dropping the packet, I * don't think is an appropriate recovery. In the interest * of failing fast, it may be better to crash the guest. * For now, I will just drop the packet! */ msg_sz = bytes_recvd - (desc->offset8 << 3); if (msg_sz <= sizeof(struct synth_kbd_msg_hdr)) { /* * Drop the packet and hope * the problem magically goes away. */ dev_err(&hv_dev->device, "Illegal packet (type: %d, tid: %llx, size: %d)\n", desc->type, req_id, msg_sz); break; } msg = (void *)desc + (desc->offset8 << 3); hv_kbd_on_receive(hv_dev, msg, msg_sz); break; default: dev_err(&hv_dev->device, "unhandled packet type %d, tid %llx len %d\n", desc->type, req_id, bytes_recvd); break; } } static void hv_kbd_on_channel_callback(void *context) { struct vmpacket_descriptor *desc; struct hv_device *hv_dev = context; u32 bytes_recvd; u64 req_id; foreach_vmbus_pkt(desc, hv_dev->channel) { bytes_recvd = desc->len8 * 8; req_id = desc->trans_id; hv_kbd_handle_received_packet(hv_dev, desc, bytes_recvd, req_id); } } static int hv_kbd_connect_to_vsp(struct hv_device *hv_dev) { struct hv_kbd_dev *kbd_dev = hv_get_drvdata(hv_dev); struct synth_kbd_protocol_request *request; struct synth_kbd_protocol_response *response; u32 proto_status; int error; reinit_completion(&kbd_dev->wait_event); request = &kbd_dev->protocol_req; memset(request, 0, sizeof(struct synth_kbd_protocol_request)); request->header.type = __cpu_to_le32(SYNTH_KBD_PROTOCOL_REQUEST); request->version_requested.version = __cpu_to_le32(SYNTH_KBD_VERSION); error = vmbus_sendpacket(hv_dev->channel, request, sizeof(struct synth_kbd_protocol_request), (unsigned long)request, VM_PKT_DATA_INBAND, VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED); if (error) return error; if (!wait_for_completion_timeout(&kbd_dev->wait_event, 10 * HZ)) return -ETIMEDOUT; response = &kbd_dev->protocol_resp; proto_status = __le32_to_cpu(response->proto_status); if (!(proto_status & PROTOCOL_ACCEPTED)) { dev_err(&hv_dev->device, "synth_kbd protocol request failed (version %d)\n", SYNTH_KBD_VERSION); return -ENODEV; } return 0; } static int hv_kbd_start(struct serio *serio) { struct hv_kbd_dev *kbd_dev = serio->port_data; unsigned long flags; spin_lock_irqsave(&kbd_dev->lock, flags); kbd_dev->started = true; spin_unlock_irqrestore(&kbd_dev->lock, flags); return 0; } static void hv_kbd_stop(struct serio *serio) { struct hv_kbd_dev *kbd_dev = serio->port_data; unsigned long flags; spin_lock_irqsave(&kbd_dev->lock, flags); kbd_dev->started = false; spin_unlock_irqrestore(&kbd_dev->lock, flags); } static int hv_kbd_probe(struct hv_device *hv_dev, const struct hv_vmbus_device_id *dev_id) { struct hv_kbd_dev *kbd_dev; struct serio *hv_serio; int error; kbd_dev = kzalloc(sizeof(struct hv_kbd_dev), GFP_KERNEL); hv_serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!kbd_dev || !hv_serio) { error = -ENOMEM; goto err_free_mem; } kbd_dev->hv_dev = hv_dev; kbd_dev->hv_serio = hv_serio; spin_lock_init(&kbd_dev->lock); init_completion(&kbd_dev->wait_event); hv_set_drvdata(hv_dev, kbd_dev); hv_serio->dev.parent = &hv_dev->device; hv_serio->id.type = SERIO_8042_XL; hv_serio->port_data = kbd_dev; strscpy(hv_serio->name, dev_name(&hv_dev->device), sizeof(hv_serio->name)); strscpy(hv_serio->phys, dev_name(&hv_dev->device), sizeof(hv_serio->phys)); hv_serio->start = hv_kbd_start; hv_serio->stop = hv_kbd_stop; error = vmbus_open(hv_dev->channel, KBD_VSC_SEND_RING_BUFFER_SIZE, KBD_VSC_RECV_RING_BUFFER_SIZE, NULL, 0, hv_kbd_on_channel_callback, hv_dev); if (error) goto err_free_mem; error = hv_kbd_connect_to_vsp(hv_dev); if (error) goto err_close_vmbus; serio_register_port(kbd_dev->hv_serio); device_init_wakeup(&hv_dev->device, true); return 0; err_close_vmbus: vmbus_close(hv_dev->channel); err_free_mem: kfree(hv_serio); kfree(kbd_dev); return error; } static void hv_kbd_remove(struct hv_device *hv_dev) { struct hv_kbd_dev *kbd_dev = hv_get_drvdata(hv_dev); serio_unregister_port(kbd_dev->hv_serio); vmbus_close(hv_dev->channel); kfree(kbd_dev); hv_set_drvdata(hv_dev, NULL); } static int hv_kbd_suspend(struct hv_device *hv_dev) { vmbus_close(hv_dev->channel); return 0; } static int hv_kbd_resume(struct hv_device *hv_dev) { int ret; ret = vmbus_open(hv_dev->channel, KBD_VSC_SEND_RING_BUFFER_SIZE, KBD_VSC_RECV_RING_BUFFER_SIZE, NULL, 0, hv_kbd_on_channel_callback, hv_dev); if (ret == 0) ret = hv_kbd_connect_to_vsp(hv_dev); return ret; } static const struct hv_vmbus_device_id id_table[] = { /* Keyboard guid */ { HV_KBD_GUID, }, { }, }; MODULE_DEVICE_TABLE(vmbus, id_table); static struct hv_driver hv_kbd_drv = { .name = KBUILD_MODNAME, .id_table = id_table, .probe = hv_kbd_probe, .remove = hv_kbd_remove, .suspend = hv_kbd_suspend, .resume = hv_kbd_resume, .driver = { .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, }; static int __init hv_kbd_init(void) { return vmbus_driver_register(&hv_kbd_drv); } static void __exit hv_kbd_exit(void) { vmbus_driver_unregister(&hv_kbd_drv); } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Microsoft Hyper-V Synthetic Keyboard Driver"); module_init(hv_kbd_init); module_exit(hv_kbd_exit);
linux-master
drivers/input/serio/hyperv-keyboard.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2013 Aeroflex Gaisler * * This driver supports the APBPS2 PS/2 core available in the GRLIB * VHDL IP core library. * * Full documentation of the APBPS2 core can be found here: * http://www.gaisler.com/products/grlib/grip.pdf * * See "Documentation/devicetree/bindings/input/ps2keyb-mouse-apbps2.txt" for * information on open firmware properties. * * Contributors: Daniel Hellstrom <[email protected]> */ #include <linux/platform_device.h> #include <linux/module.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/io.h> struct apbps2_regs { u32 __iomem data; /* 0x00 */ u32 __iomem status; /* 0x04 */ u32 __iomem ctrl; /* 0x08 */ u32 __iomem reload; /* 0x0c */ }; #define APBPS2_STATUS_DR (1<<0) #define APBPS2_STATUS_PE (1<<1) #define APBPS2_STATUS_FE (1<<2) #define APBPS2_STATUS_KI (1<<3) #define APBPS2_STATUS_RF (1<<4) #define APBPS2_STATUS_TF (1<<5) #define APBPS2_STATUS_TCNT (0x1f<<22) #define APBPS2_STATUS_RCNT (0x1f<<27) #define APBPS2_CTRL_RE (1<<0) #define APBPS2_CTRL_TE (1<<1) #define APBPS2_CTRL_RI (1<<2) #define APBPS2_CTRL_TI (1<<3) struct apbps2_priv { struct serio *io; struct apbps2_regs __iomem *regs; }; static int apbps2_idx; static irqreturn_t apbps2_isr(int irq, void *dev_id) { struct apbps2_priv *priv = dev_id; unsigned long status, data, rxflags; irqreturn_t ret = IRQ_NONE; while ((status = ioread32be(&priv->regs->status)) & APBPS2_STATUS_DR) { data = ioread32be(&priv->regs->data); rxflags = (status & APBPS2_STATUS_PE) ? SERIO_PARITY : 0; rxflags |= (status & APBPS2_STATUS_FE) ? SERIO_FRAME : 0; /* clear error bits? */ if (rxflags) iowrite32be(0, &priv->regs->status); serio_interrupt(priv->io, data, rxflags); ret = IRQ_HANDLED; } return ret; } static int apbps2_write(struct serio *io, unsigned char val) { struct apbps2_priv *priv = io->port_data; unsigned int tleft = 10000; /* timeout in 100ms */ /* delay until PS/2 controller has room for more chars */ while ((ioread32be(&priv->regs->status) & APBPS2_STATUS_TF) && tleft--) udelay(10); if ((ioread32be(&priv->regs->status) & APBPS2_STATUS_TF) == 0) { iowrite32be(val, &priv->regs->data); iowrite32be(APBPS2_CTRL_RE | APBPS2_CTRL_RI | APBPS2_CTRL_TE, &priv->regs->ctrl); return 0; } return -ETIMEDOUT; } static int apbps2_open(struct serio *io) { struct apbps2_priv *priv = io->port_data; int limit; /* clear error flags */ iowrite32be(0, &priv->regs->status); /* Clear old data if available (unlikely) */ limit = 1024; while ((ioread32be(&priv->regs->status) & APBPS2_STATUS_DR) && --limit) ioread32be(&priv->regs->data); /* Enable reciever and it's interrupt */ iowrite32be(APBPS2_CTRL_RE | APBPS2_CTRL_RI, &priv->regs->ctrl); return 0; } static void apbps2_close(struct serio *io) { struct apbps2_priv *priv = io->port_data; /* stop interrupts at PS/2 HW level */ iowrite32be(0, &priv->regs->ctrl); } /* Initialize one APBPS2 PS/2 core */ static int apbps2_of_probe(struct platform_device *ofdev) { struct apbps2_priv *priv; int irq, err; u32 freq_hz; priv = devm_kzalloc(&ofdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) { dev_err(&ofdev->dev, "memory allocation failed\n"); return -ENOMEM; } /* Find Device Address */ priv->regs = devm_platform_get_and_ioremap_resource(ofdev, 0, NULL); if (IS_ERR(priv->regs)) return PTR_ERR(priv->regs); /* Reset hardware, disable interrupt */ iowrite32be(0, &priv->regs->ctrl); /* IRQ */ irq = irq_of_parse_and_map(ofdev->dev.of_node, 0); err = devm_request_irq(&ofdev->dev, irq, apbps2_isr, IRQF_SHARED, "apbps2", priv); if (err) { dev_err(&ofdev->dev, "request IRQ%d failed\n", irq); return err; } /* Get core frequency */ if (of_property_read_u32(ofdev->dev.of_node, "freq", &freq_hz)) { dev_err(&ofdev->dev, "unable to get core frequency\n"); return -EINVAL; } /* Set reload register to core freq in kHz/10 */ iowrite32be(freq_hz / 10000, &priv->regs->reload); priv->io = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!priv->io) return -ENOMEM; priv->io->id.type = SERIO_8042; priv->io->open = apbps2_open; priv->io->close = apbps2_close; priv->io->write = apbps2_write; priv->io->port_data = priv; strscpy(priv->io->name, "APBPS2 PS/2", sizeof(priv->io->name)); snprintf(priv->io->phys, sizeof(priv->io->phys), "apbps2_%d", apbps2_idx++); dev_info(&ofdev->dev, "irq = %d, base = 0x%p\n", irq, priv->regs); serio_register_port(priv->io); platform_set_drvdata(ofdev, priv); return 0; } static int apbps2_of_remove(struct platform_device *of_dev) { struct apbps2_priv *priv = platform_get_drvdata(of_dev); serio_unregister_port(priv->io); return 0; } static const struct of_device_id apbps2_of_match[] = { { .name = "GAISLER_APBPS2", }, { .name = "01_060", }, {} }; MODULE_DEVICE_TABLE(of, apbps2_of_match); static struct platform_driver apbps2_of_driver = { .driver = { .name = "grlib-apbps2", .of_match_table = apbps2_of_match, }, .probe = apbps2_of_probe, .remove = apbps2_of_remove, }; module_platform_driver(apbps2_of_driver); MODULE_AUTHOR("Aeroflex Gaisler AB."); MODULE_DESCRIPTION("GRLIB APBPS2 PS/2 serial I/O"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/apbps2.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2000-2001 Vojtech Pavlik * Copyright (c) 2002 Russell King */ /* * Acorn RiscPC PS/2 keyboard controller driver for Linux/ARM */ #include <linux/module.h> #include <linux/interrupt.h> #include <linux/serio.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/slab.h> #include <mach/hardware.h> #include <asm/hardware/iomd.h> MODULE_AUTHOR("Vojtech Pavlik, Russell King"); MODULE_DESCRIPTION("Acorn RiscPC PS/2 keyboard controller driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:kart"); struct rpckbd_data { int tx_irq; int rx_irq; }; static int rpckbd_write(struct serio *port, unsigned char val) { while (!(iomd_readb(IOMD_KCTRL) & (1 << 7))) cpu_relax(); iomd_writeb(val, IOMD_KARTTX); return 0; } static irqreturn_t rpckbd_rx(int irq, void *dev_id) { struct serio *port = dev_id; unsigned int byte; int handled = IRQ_NONE; while (iomd_readb(IOMD_KCTRL) & (1 << 5)) { byte = iomd_readb(IOMD_KARTRX); serio_interrupt(port, byte, 0); handled = IRQ_HANDLED; } return handled; } static irqreturn_t rpckbd_tx(int irq, void *dev_id) { return IRQ_HANDLED; } static int rpckbd_open(struct serio *port) { struct rpckbd_data *rpckbd = port->port_data; /* Reset the keyboard state machine. */ iomd_writeb(0, IOMD_KCTRL); iomd_writeb(8, IOMD_KCTRL); iomd_readb(IOMD_KARTRX); if (request_irq(rpckbd->rx_irq, rpckbd_rx, 0, "rpckbd", port) != 0) { printk(KERN_ERR "rpckbd.c: Could not allocate keyboard receive IRQ\n"); return -EBUSY; } if (request_irq(rpckbd->tx_irq, rpckbd_tx, 0, "rpckbd", port) != 0) { printk(KERN_ERR "rpckbd.c: Could not allocate keyboard transmit IRQ\n"); free_irq(rpckbd->rx_irq, port); return -EBUSY; } return 0; } static void rpckbd_close(struct serio *port) { struct rpckbd_data *rpckbd = port->port_data; free_irq(rpckbd->rx_irq, port); free_irq(rpckbd->tx_irq, port); } /* * Allocate and initialize serio structure for subsequent registration * with serio core. */ static int rpckbd_probe(struct platform_device *dev) { struct rpckbd_data *rpckbd; struct serio *serio; int tx_irq, rx_irq; rx_irq = platform_get_irq(dev, 0); if (rx_irq < 0) return rx_irq; tx_irq = platform_get_irq(dev, 1); if (tx_irq < 0) return tx_irq; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); rpckbd = kzalloc(sizeof(*rpckbd), GFP_KERNEL); if (!serio || !rpckbd) { kfree(rpckbd); kfree(serio); return -ENOMEM; } rpckbd->rx_irq = rx_irq; rpckbd->tx_irq = tx_irq; serio->id.type = SERIO_8042; serio->write = rpckbd_write; serio->open = rpckbd_open; serio->close = rpckbd_close; serio->dev.parent = &dev->dev; serio->port_data = rpckbd; strscpy(serio->name, "RiscPC PS/2 kbd port", sizeof(serio->name)); strscpy(serio->phys, "rpckbd/serio0", sizeof(serio->phys)); platform_set_drvdata(dev, serio); serio_register_port(serio); return 0; } static int rpckbd_remove(struct platform_device *dev) { struct serio *serio = platform_get_drvdata(dev); struct rpckbd_data *rpckbd = serio->port_data; serio_unregister_port(serio); kfree(rpckbd); return 0; } static struct platform_driver rpckbd_driver = { .probe = rpckbd_probe, .remove = rpckbd_remove, .driver = { .name = "kart", }, }; module_platform_driver(rpckbd_driver);
linux-master
drivers/input/serio/rpckbd.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 1999-2001 Vojtech Pavlik */ /* * 82C710 C&T mouse port chip driver for Linux */ #include <linux/delay.h> #include <linux/module.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <asm/io.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("82C710 C&T mouse port chip driver"); MODULE_LICENSE("GPL"); /* * ct82c710 interface */ #define CT82C710_DEV_IDLE 0x01 /* Device Idle */ #define CT82C710_RX_FULL 0x02 /* Device Char received */ #define CT82C710_TX_IDLE 0x04 /* Device XMIT Idle */ #define CT82C710_RESET 0x08 /* Device Reset */ #define CT82C710_INTS_ON 0x10 /* Device Interrupt On */ #define CT82C710_ERROR_FLAG 0x20 /* Device Error */ #define CT82C710_CLEAR 0x40 /* Device Clear */ #define CT82C710_ENABLE 0x80 /* Device Enable */ #define CT82C710_IRQ 12 #define CT82C710_DATA ct82c710_iores.start #define CT82C710_STATUS (ct82c710_iores.start + 1) static struct serio *ct82c710_port; static struct platform_device *ct82c710_device; static struct resource ct82c710_iores; /* * Interrupt handler for the 82C710 mouse port. A character * is waiting in the 82C710. */ static irqreturn_t ct82c710_interrupt(int cpl, void *dev_id) { return serio_interrupt(ct82c710_port, inb(CT82C710_DATA), 0); } /* * Wait for device to send output char and flush any input char. */ static int ct82c170_wait(void) { int timeout = 60000; while ((inb(CT82C710_STATUS) & (CT82C710_RX_FULL | CT82C710_TX_IDLE | CT82C710_DEV_IDLE)) != (CT82C710_DEV_IDLE | CT82C710_TX_IDLE) && timeout) { if (inb_p(CT82C710_STATUS) & CT82C710_RX_FULL) inb_p(CT82C710_DATA); udelay(1); timeout--; } return !timeout; } static void ct82c710_close(struct serio *serio) { if (ct82c170_wait()) printk(KERN_WARNING "ct82c710.c: Device busy in close()\n"); outb_p(inb_p(CT82C710_STATUS) & ~(CT82C710_ENABLE | CT82C710_INTS_ON), CT82C710_STATUS); if (ct82c170_wait()) printk(KERN_WARNING "ct82c710.c: Device busy in close()\n"); free_irq(CT82C710_IRQ, NULL); } static int ct82c710_open(struct serio *serio) { unsigned char status; int err; err = request_irq(CT82C710_IRQ, ct82c710_interrupt, 0, "ct82c710", NULL); if (err) return err; status = inb_p(CT82C710_STATUS); status |= (CT82C710_ENABLE | CT82C710_RESET); outb_p(status, CT82C710_STATUS); status &= ~(CT82C710_RESET); outb_p(status, CT82C710_STATUS); status |= CT82C710_INTS_ON; outb_p(status, CT82C710_STATUS); /* Enable interrupts */ while (ct82c170_wait()) { printk(KERN_ERR "ct82c710: Device busy in open()\n"); status &= ~(CT82C710_ENABLE | CT82C710_INTS_ON); outb_p(status, CT82C710_STATUS); free_irq(CT82C710_IRQ, NULL); return -EBUSY; } return 0; } /* * Write to the 82C710 mouse device. */ static int ct82c710_write(struct serio *port, unsigned char c) { if (ct82c170_wait()) return -1; outb_p(c, CT82C710_DATA); return 0; } /* * See if we can find a 82C710 device. Read mouse address. */ static int __init ct82c710_detect(void) { outb_p(0x55, 0x2fa); /* Any value except 9, ff or 36 */ outb_p(0xaa, 0x3fa); /* Inverse of 55 */ outb_p(0x36, 0x3fa); /* Address the chip */ outb_p(0xe4, 0x3fa); /* 390/4; 390 = config address */ outb_p(0x1b, 0x2fa); /* Inverse of e4 */ outb_p(0x0f, 0x390); /* Write index */ if (inb_p(0x391) != 0xe4) /* Config address found? */ return -ENODEV; /* No: no 82C710 here */ outb_p(0x0d, 0x390); /* Write index */ ct82c710_iores.start = inb_p(0x391) << 2; /* Get mouse I/O address */ ct82c710_iores.end = ct82c710_iores.start + 1; ct82c710_iores.flags = IORESOURCE_IO; outb_p(0x0f, 0x390); outb_p(0x0f, 0x391); /* Close config mode */ return 0; } static int ct82c710_probe(struct platform_device *dev) { ct82c710_port = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!ct82c710_port) return -ENOMEM; ct82c710_port->id.type = SERIO_8042; ct82c710_port->dev.parent = &dev->dev; ct82c710_port->open = ct82c710_open; ct82c710_port->close = ct82c710_close; ct82c710_port->write = ct82c710_write; strscpy(ct82c710_port->name, "C&T 82c710 mouse port", sizeof(ct82c710_port->name)); snprintf(ct82c710_port->phys, sizeof(ct82c710_port->phys), "isa%16llx/serio0", (unsigned long long)CT82C710_DATA); serio_register_port(ct82c710_port); printk(KERN_INFO "serio: C&T 82c710 mouse port at %#llx irq %d\n", (unsigned long long)CT82C710_DATA, CT82C710_IRQ); return 0; } static int ct82c710_remove(struct platform_device *dev) { serio_unregister_port(ct82c710_port); return 0; } static struct platform_driver ct82c710_driver = { .driver = { .name = "ct82c710", }, .probe = ct82c710_probe, .remove = ct82c710_remove, }; static int __init ct82c710_init(void) { int error; error = ct82c710_detect(); if (error) return error; error = platform_driver_register(&ct82c710_driver); if (error) return error; ct82c710_device = platform_device_alloc("ct82c710", -1); if (!ct82c710_device) { error = -ENOMEM; goto err_unregister_driver; } error = platform_device_add_resources(ct82c710_device, &ct82c710_iores, 1); if (error) goto err_free_device; error = platform_device_add(ct82c710_device); if (error) goto err_free_device; return 0; err_free_device: platform_device_put(ct82c710_device); err_unregister_driver: platform_driver_unregister(&ct82c710_driver); return error; } static void __exit ct82c710_exit(void) { platform_device_unregister(ct82c710_device); platform_driver_unregister(&ct82c710_driver); } module_init(ct82c710_init); module_exit(ct82c710_exit);
linux-master
drivers/input/serio/ct82c710.c
/* * HP i8042-based System Device Controller driver. * * Copyright (c) 2001 Brian S. Julin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL"). * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * References: * System Device Controller Microprocessor Firmware Theory of Operation * for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2 * Helge Deller's original hilkbd.c port for PA-RISC. * * * Driver theory of operation: * * hp_sdc_put does all writing to the SDC. ISR can run on a different * CPU than hp_sdc_put, but only one CPU runs hp_sdc_put at a time * (it cannot really benefit from SMP anyway.) A tasket fit this perfectly. * * All data coming back from the SDC is sent via interrupt and can be read * fully in the ISR, so there are no latency/throughput problems there. * The problem is with output, due to the slow clock speed of the SDC * compared to the CPU. This should not be too horrible most of the time, * but if used with HIL devices that support the multibyte transfer command, * keeping outbound throughput flowing at the 6500KBps that the HIL is * capable of is more than can be done at HZ=100. * * Busy polling for IBF clear wastes CPU cycles and bus cycles. hp_sdc.ibf * is set to 0 when the IBF flag in the status register has cleared. ISR * may do this, and may also access the parts of queued transactions related * to reading data back from the SDC, but otherwise will not touch the * hp_sdc state. Whenever a register is written hp_sdc.ibf is set to 1. * * The i8042 write index and the values in the 4-byte input buffer * starting at 0x70 are kept track of in hp_sdc.wi, and .r7[], respectively, * to minimize the amount of IO needed to the SDC. However these values * do not need to be locked since they are only ever accessed by hp_sdc_put. * * A timer task schedules the tasklet once per second just to make * sure it doesn't freeze up and to allow for bad reads to time out. */ #include <linux/hp_sdc.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/module.h> #include <linux/ioport.h> #include <linux/time.h> #include <linux/semaphore.h> #include <linux/slab.h> #include <linux/hil.h> #include <asm/io.h> /* Machine-specific abstraction */ #if defined(__hppa__) # include <asm/parisc-device.h> # define sdc_readb(p) gsc_readb(p) # define sdc_writeb(v,p) gsc_writeb((v),(p)) #elif defined(__mc68000__) #include <linux/uaccess.h> # define sdc_readb(p) in_8(p) # define sdc_writeb(v,p) out_8((p),(v)) #else # error "HIL is not supported on this platform" #endif #define PREFIX "HP SDC: " MODULE_AUTHOR("Brian S. Julin <[email protected]>"); MODULE_DESCRIPTION("HP i8042-based SDC Driver"); MODULE_LICENSE("Dual BSD/GPL"); EXPORT_SYMBOL(hp_sdc_request_timer_irq); EXPORT_SYMBOL(hp_sdc_request_hil_irq); EXPORT_SYMBOL(hp_sdc_request_cooked_irq); EXPORT_SYMBOL(hp_sdc_release_timer_irq); EXPORT_SYMBOL(hp_sdc_release_hil_irq); EXPORT_SYMBOL(hp_sdc_release_cooked_irq); EXPORT_SYMBOL(__hp_sdc_enqueue_transaction); EXPORT_SYMBOL(hp_sdc_enqueue_transaction); EXPORT_SYMBOL(hp_sdc_dequeue_transaction); static bool hp_sdc_disabled; module_param_named(no_hpsdc, hp_sdc_disabled, bool, 0); MODULE_PARM_DESC(no_hpsdc, "Do not enable HP SDC driver."); static hp_i8042_sdc hp_sdc; /* All driver state is kept in here. */ /*************** primitives for use in any context *********************/ static inline uint8_t hp_sdc_status_in8(void) { uint8_t status; unsigned long flags; write_lock_irqsave(&hp_sdc.ibf_lock, flags); status = sdc_readb(hp_sdc.status_io); if (!(status & HP_SDC_STATUS_IBF)) hp_sdc.ibf = 0; write_unlock_irqrestore(&hp_sdc.ibf_lock, flags); return status; } static inline uint8_t hp_sdc_data_in8(void) { return sdc_readb(hp_sdc.data_io); } static inline void hp_sdc_status_out8(uint8_t val) { unsigned long flags; write_lock_irqsave(&hp_sdc.ibf_lock, flags); hp_sdc.ibf = 1; if ((val & 0xf0) == 0xe0) hp_sdc.wi = 0xff; sdc_writeb(val, hp_sdc.status_io); write_unlock_irqrestore(&hp_sdc.ibf_lock, flags); } static inline void hp_sdc_data_out8(uint8_t val) { unsigned long flags; write_lock_irqsave(&hp_sdc.ibf_lock, flags); hp_sdc.ibf = 1; sdc_writeb(val, hp_sdc.data_io); write_unlock_irqrestore(&hp_sdc.ibf_lock, flags); } /* Care must be taken to only invoke hp_sdc_spin_ibf when * absolutely needed, or in rarely invoked subroutines. * Not only does it waste CPU cycles, it also wastes bus cycles. */ static inline void hp_sdc_spin_ibf(void) { unsigned long flags; rwlock_t *lock; lock = &hp_sdc.ibf_lock; read_lock_irqsave(lock, flags); if (!hp_sdc.ibf) { read_unlock_irqrestore(lock, flags); return; } read_unlock(lock); write_lock(lock); while (sdc_readb(hp_sdc.status_io) & HP_SDC_STATUS_IBF) { } hp_sdc.ibf = 0; write_unlock_irqrestore(lock, flags); } /************************ Interrupt context functions ************************/ static void hp_sdc_take(int irq, void *dev_id, uint8_t status, uint8_t data) { hp_sdc_transaction *curr; read_lock(&hp_sdc.rtq_lock); if (hp_sdc.rcurr < 0) { read_unlock(&hp_sdc.rtq_lock); return; } curr = hp_sdc.tq[hp_sdc.rcurr]; read_unlock(&hp_sdc.rtq_lock); curr->seq[curr->idx++] = status; curr->seq[curr->idx++] = data; hp_sdc.rqty -= 2; hp_sdc.rtime = ktime_get(); if (hp_sdc.rqty <= 0) { /* All data has been gathered. */ if (curr->seq[curr->actidx] & HP_SDC_ACT_SEMAPHORE) if (curr->act.semaphore) up(curr->act.semaphore); if (curr->seq[curr->actidx] & HP_SDC_ACT_CALLBACK) if (curr->act.irqhook) curr->act.irqhook(irq, dev_id, status, data); curr->actidx = curr->idx; curr->idx++; /* Return control of this transaction */ write_lock(&hp_sdc.rtq_lock); hp_sdc.rcurr = -1; hp_sdc.rqty = 0; write_unlock(&hp_sdc.rtq_lock); tasklet_schedule(&hp_sdc.task); } } static irqreturn_t hp_sdc_isr(int irq, void *dev_id) { uint8_t status, data; status = hp_sdc_status_in8(); /* Read data unconditionally to advance i8042. */ data = hp_sdc_data_in8(); /* For now we are ignoring these until we get the SDC to behave. */ if (((status & 0xf1) == 0x51) && data == 0x82) return IRQ_HANDLED; switch (status & HP_SDC_STATUS_IRQMASK) { case 0: /* This case is not documented. */ break; case HP_SDC_STATUS_USERTIMER: case HP_SDC_STATUS_PERIODIC: case HP_SDC_STATUS_TIMER: read_lock(&hp_sdc.hook_lock); if (hp_sdc.timer != NULL) hp_sdc.timer(irq, dev_id, status, data); read_unlock(&hp_sdc.hook_lock); break; case HP_SDC_STATUS_REG: hp_sdc_take(irq, dev_id, status, data); break; case HP_SDC_STATUS_HILCMD: case HP_SDC_STATUS_HILDATA: read_lock(&hp_sdc.hook_lock); if (hp_sdc.hil != NULL) hp_sdc.hil(irq, dev_id, status, data); read_unlock(&hp_sdc.hook_lock); break; case HP_SDC_STATUS_PUP: read_lock(&hp_sdc.hook_lock); if (hp_sdc.pup != NULL) hp_sdc.pup(irq, dev_id, status, data); else printk(KERN_INFO PREFIX "HP SDC reports successful PUP.\n"); read_unlock(&hp_sdc.hook_lock); break; default: read_lock(&hp_sdc.hook_lock); if (hp_sdc.cooked != NULL) hp_sdc.cooked(irq, dev_id, status, data); read_unlock(&hp_sdc.hook_lock); break; } return IRQ_HANDLED; } static irqreturn_t hp_sdc_nmisr(int irq, void *dev_id) { int status; status = hp_sdc_status_in8(); printk(KERN_WARNING PREFIX "NMI !\n"); #if 0 if (status & HP_SDC_NMISTATUS_FHS) { read_lock(&hp_sdc.hook_lock); if (hp_sdc.timer != NULL) hp_sdc.timer(irq, dev_id, status, 0); read_unlock(&hp_sdc.hook_lock); } else { /* TODO: pass this on to the HIL handler, or do SAK here? */ printk(KERN_WARNING PREFIX "HIL NMI\n"); } #endif return IRQ_HANDLED; } /***************** Kernel (tasklet) context functions ****************/ unsigned long hp_sdc_put(void); static void hp_sdc_tasklet(unsigned long foo) { write_lock_irq(&hp_sdc.rtq_lock); if (hp_sdc.rcurr >= 0) { ktime_t now = ktime_get(); if (ktime_after(now, ktime_add_us(hp_sdc.rtime, HP_SDC_MAX_REG_DELAY))) { hp_sdc_transaction *curr; uint8_t tmp; curr = hp_sdc.tq[hp_sdc.rcurr]; /* If this turns out to be a normal failure mode * we'll need to figure out a way to communicate * it back to the application. and be less verbose. */ printk(KERN_WARNING PREFIX "read timeout (%lldus)!\n", ktime_us_delta(now, hp_sdc.rtime)); curr->idx += hp_sdc.rqty; hp_sdc.rqty = 0; tmp = curr->seq[curr->actidx]; curr->seq[curr->actidx] |= HP_SDC_ACT_DEAD; if (tmp & HP_SDC_ACT_SEMAPHORE) if (curr->act.semaphore) up(curr->act.semaphore); if (tmp & HP_SDC_ACT_CALLBACK) { /* Note this means that irqhooks may be called * in tasklet/bh context. */ if (curr->act.irqhook) curr->act.irqhook(0, NULL, 0, 0); } curr->actidx = curr->idx; curr->idx++; hp_sdc.rcurr = -1; } } write_unlock_irq(&hp_sdc.rtq_lock); hp_sdc_put(); } unsigned long hp_sdc_put(void) { hp_sdc_transaction *curr; uint8_t act; int idx, curridx; int limit = 0; write_lock(&hp_sdc.lock); /* If i8042 buffers are full, we cannot do anything that requires output, so we skip to the administrativa. */ if (hp_sdc.ibf) { hp_sdc_status_in8(); if (hp_sdc.ibf) goto finish; } anew: /* See if we are in the middle of a sequence. */ if (hp_sdc.wcurr < 0) hp_sdc.wcurr = 0; read_lock_irq(&hp_sdc.rtq_lock); if (hp_sdc.rcurr == hp_sdc.wcurr) hp_sdc.wcurr++; read_unlock_irq(&hp_sdc.rtq_lock); if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN) hp_sdc.wcurr = 0; curridx = hp_sdc.wcurr; if (hp_sdc.tq[curridx] != NULL) goto start; while (++curridx != hp_sdc.wcurr) { if (curridx >= HP_SDC_QUEUE_LEN) { curridx = -1; /* Wrap to top */ continue; } read_lock_irq(&hp_sdc.rtq_lock); if (hp_sdc.rcurr == curridx) { read_unlock_irq(&hp_sdc.rtq_lock); continue; } read_unlock_irq(&hp_sdc.rtq_lock); if (hp_sdc.tq[curridx] != NULL) break; /* Found one. */ } if (curridx == hp_sdc.wcurr) { /* There's nothing queued to do. */ curridx = -1; } hp_sdc.wcurr = curridx; start: /* Check to see if the interrupt mask needs to be set. */ if (hp_sdc.set_im) { hp_sdc_status_out8(hp_sdc.im | HP_SDC_CMD_SET_IM); hp_sdc.set_im = 0; goto finish; } if (hp_sdc.wcurr == -1) goto done; curr = hp_sdc.tq[curridx]; idx = curr->actidx; if (curr->actidx >= curr->endidx) { hp_sdc.tq[curridx] = NULL; /* Interleave outbound data between the transactions. */ hp_sdc.wcurr++; if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN) hp_sdc.wcurr = 0; goto finish; } act = curr->seq[idx]; idx++; if (curr->idx >= curr->endidx) { if (act & HP_SDC_ACT_DEALLOC) kfree(curr); hp_sdc.tq[curridx] = NULL; /* Interleave outbound data between the transactions. */ hp_sdc.wcurr++; if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN) hp_sdc.wcurr = 0; goto finish; } while (act & HP_SDC_ACT_PRECMD) { if (curr->idx != idx) { idx++; act &= ~HP_SDC_ACT_PRECMD; break; } hp_sdc_status_out8(curr->seq[idx]); curr->idx++; /* act finished? */ if ((act & HP_SDC_ACT_DURING) == HP_SDC_ACT_PRECMD) goto actdone; /* skip quantity field if data-out sequence follows. */ if (act & HP_SDC_ACT_DATAOUT) curr->idx++; goto finish; } if (act & HP_SDC_ACT_DATAOUT) { int qty; qty = curr->seq[idx]; idx++; if (curr->idx - idx < qty) { hp_sdc_data_out8(curr->seq[curr->idx]); curr->idx++; /* act finished? */ if (curr->idx - idx >= qty && (act & HP_SDC_ACT_DURING) == HP_SDC_ACT_DATAOUT) goto actdone; goto finish; } idx += qty; act &= ~HP_SDC_ACT_DATAOUT; } else while (act & HP_SDC_ACT_DATAREG) { int mask; uint8_t w7[4]; mask = curr->seq[idx]; if (idx != curr->idx) { idx++; idx += !!(mask & 1); idx += !!(mask & 2); idx += !!(mask & 4); idx += !!(mask & 8); act &= ~HP_SDC_ACT_DATAREG; break; } w7[0] = (mask & 1) ? curr->seq[++idx] : hp_sdc.r7[0]; w7[1] = (mask & 2) ? curr->seq[++idx] : hp_sdc.r7[1]; w7[2] = (mask & 4) ? curr->seq[++idx] : hp_sdc.r7[2]; w7[3] = (mask & 8) ? curr->seq[++idx] : hp_sdc.r7[3]; if (hp_sdc.wi > 0x73 || hp_sdc.wi < 0x70 || w7[hp_sdc.wi - 0x70] == hp_sdc.r7[hp_sdc.wi - 0x70]) { int i = 0; /* Need to point the write index register */ while (i < 4 && w7[i] == hp_sdc.r7[i]) i++; if (i < 4) { hp_sdc_status_out8(HP_SDC_CMD_SET_D0 + i); hp_sdc.wi = 0x70 + i; goto finish; } idx++; if ((act & HP_SDC_ACT_DURING) == HP_SDC_ACT_DATAREG) goto actdone; curr->idx = idx; act &= ~HP_SDC_ACT_DATAREG; break; } hp_sdc_data_out8(w7[hp_sdc.wi - 0x70]); hp_sdc.r7[hp_sdc.wi - 0x70] = w7[hp_sdc.wi - 0x70]; hp_sdc.wi++; /* write index register autoincrements */ { int i = 0; while ((i < 4) && w7[i] == hp_sdc.r7[i]) i++; if (i >= 4) { curr->idx = idx + 1; if ((act & HP_SDC_ACT_DURING) == HP_SDC_ACT_DATAREG) goto actdone; } } goto finish; } /* We don't go any further in the command if there is a pending read, because we don't want interleaved results. */ read_lock_irq(&hp_sdc.rtq_lock); if (hp_sdc.rcurr >= 0) { read_unlock_irq(&hp_sdc.rtq_lock); goto finish; } read_unlock_irq(&hp_sdc.rtq_lock); if (act & HP_SDC_ACT_POSTCMD) { uint8_t postcmd; /* curr->idx should == idx at this point. */ postcmd = curr->seq[idx]; curr->idx++; if (act & HP_SDC_ACT_DATAIN) { /* Start a new read */ hp_sdc.rqty = curr->seq[curr->idx]; hp_sdc.rtime = ktime_get(); curr->idx++; /* Still need to lock here in case of spurious irq. */ write_lock_irq(&hp_sdc.rtq_lock); hp_sdc.rcurr = curridx; write_unlock_irq(&hp_sdc.rtq_lock); hp_sdc_status_out8(postcmd); goto finish; } hp_sdc_status_out8(postcmd); goto actdone; } actdone: if (act & HP_SDC_ACT_SEMAPHORE) up(curr->act.semaphore); else if (act & HP_SDC_ACT_CALLBACK) curr->act.irqhook(0,NULL,0,0); if (curr->idx >= curr->endidx) { /* This transaction is over. */ if (act & HP_SDC_ACT_DEALLOC) kfree(curr); hp_sdc.tq[curridx] = NULL; } else { curr->actidx = idx + 1; curr->idx = idx + 2; } /* Interleave outbound data between the transactions. */ hp_sdc.wcurr++; if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN) hp_sdc.wcurr = 0; finish: /* If by some quirk IBF has cleared and our ISR has run to see that that has happened, do it all again. */ if (!hp_sdc.ibf && limit++ < 20) goto anew; done: if (hp_sdc.wcurr >= 0) tasklet_schedule(&hp_sdc.task); write_unlock(&hp_sdc.lock); return 0; } /******* Functions called in either user or kernel context ****/ int __hp_sdc_enqueue_transaction(hp_sdc_transaction *this) { int i; if (this == NULL) { BUG(); return -EINVAL; } /* Can't have same transaction on queue twice */ for (i = 0; i < HP_SDC_QUEUE_LEN; i++) if (hp_sdc.tq[i] == this) goto fail; this->actidx = 0; this->idx = 1; /* Search for empty slot */ for (i = 0; i < HP_SDC_QUEUE_LEN; i++) if (hp_sdc.tq[i] == NULL) { hp_sdc.tq[i] = this; tasklet_schedule(&hp_sdc.task); return 0; } printk(KERN_WARNING PREFIX "No free slot to add transaction.\n"); return -EBUSY; fail: printk(KERN_WARNING PREFIX "Transaction add failed: transaction already queued?\n"); return -EINVAL; } int hp_sdc_enqueue_transaction(hp_sdc_transaction *this) { unsigned long flags; int ret; write_lock_irqsave(&hp_sdc.lock, flags); ret = __hp_sdc_enqueue_transaction(this); write_unlock_irqrestore(&hp_sdc.lock,flags); return ret; } int hp_sdc_dequeue_transaction(hp_sdc_transaction *this) { unsigned long flags; int i; write_lock_irqsave(&hp_sdc.lock, flags); /* TODO: don't remove it if it's not done. */ for (i = 0; i < HP_SDC_QUEUE_LEN; i++) if (hp_sdc.tq[i] == this) hp_sdc.tq[i] = NULL; write_unlock_irqrestore(&hp_sdc.lock, flags); return 0; } /********************** User context functions **************************/ int hp_sdc_request_timer_irq(hp_sdc_irqhook *callback) { if (callback == NULL || hp_sdc.dev == NULL) return -EINVAL; write_lock_irq(&hp_sdc.hook_lock); if (hp_sdc.timer != NULL) { write_unlock_irq(&hp_sdc.hook_lock); return -EBUSY; } hp_sdc.timer = callback; /* Enable interrupts from the timers */ hp_sdc.im &= ~HP_SDC_IM_FH; hp_sdc.im &= ~HP_SDC_IM_PT; hp_sdc.im &= ~HP_SDC_IM_TIMERS; hp_sdc.set_im = 1; write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } int hp_sdc_request_hil_irq(hp_sdc_irqhook *callback) { if (callback == NULL || hp_sdc.dev == NULL) return -EINVAL; write_lock_irq(&hp_sdc.hook_lock); if (hp_sdc.hil != NULL) { write_unlock_irq(&hp_sdc.hook_lock); return -EBUSY; } hp_sdc.hil = callback; hp_sdc.im &= ~(HP_SDC_IM_HIL | HP_SDC_IM_RESET); hp_sdc.set_im = 1; write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } int hp_sdc_request_cooked_irq(hp_sdc_irqhook *callback) { if (callback == NULL || hp_sdc.dev == NULL) return -EINVAL; write_lock_irq(&hp_sdc.hook_lock); if (hp_sdc.cooked != NULL) { write_unlock_irq(&hp_sdc.hook_lock); return -EBUSY; } /* Enable interrupts from the HIL MLC */ hp_sdc.cooked = callback; hp_sdc.im &= ~(HP_SDC_IM_HIL | HP_SDC_IM_RESET); hp_sdc.set_im = 1; write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } int hp_sdc_release_timer_irq(hp_sdc_irqhook *callback) { write_lock_irq(&hp_sdc.hook_lock); if ((callback != hp_sdc.timer) || (hp_sdc.timer == NULL)) { write_unlock_irq(&hp_sdc.hook_lock); return -EINVAL; } /* Disable interrupts from the timers */ hp_sdc.timer = NULL; hp_sdc.im |= HP_SDC_IM_TIMERS; hp_sdc.im |= HP_SDC_IM_FH; hp_sdc.im |= HP_SDC_IM_PT; hp_sdc.set_im = 1; write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } int hp_sdc_release_hil_irq(hp_sdc_irqhook *callback) { write_lock_irq(&hp_sdc.hook_lock); if ((callback != hp_sdc.hil) || (hp_sdc.hil == NULL)) { write_unlock_irq(&hp_sdc.hook_lock); return -EINVAL; } hp_sdc.hil = NULL; /* Disable interrupts from HIL only if there is no cooked driver. */ if(hp_sdc.cooked == NULL) { hp_sdc.im |= (HP_SDC_IM_HIL | HP_SDC_IM_RESET); hp_sdc.set_im = 1; } write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } int hp_sdc_release_cooked_irq(hp_sdc_irqhook *callback) { write_lock_irq(&hp_sdc.hook_lock); if ((callback != hp_sdc.cooked) || (hp_sdc.cooked == NULL)) { write_unlock_irq(&hp_sdc.hook_lock); return -EINVAL; } hp_sdc.cooked = NULL; /* Disable interrupts from HIL only if there is no raw HIL driver. */ if(hp_sdc.hil == NULL) { hp_sdc.im |= (HP_SDC_IM_HIL | HP_SDC_IM_RESET); hp_sdc.set_im = 1; } write_unlock_irq(&hp_sdc.hook_lock); tasklet_schedule(&hp_sdc.task); return 0; } /************************* Keepalive timer task *********************/ static void hp_sdc_kicker(struct timer_list *unused) { tasklet_schedule(&hp_sdc.task); /* Re-insert the periodic task. */ mod_timer(&hp_sdc.kicker, jiffies + HZ); } /************************** Module Initialization ***************************/ #if defined(__hppa__) static const struct parisc_device_id hp_sdc_tbl[] __initconst = { { .hw_type = HPHW_FIO, .hversion_rev = HVERSION_REV_ANY_ID, .hversion = HVERSION_ANY_ID, .sversion = 0x73, }, { 0, } }; MODULE_DEVICE_TABLE(parisc, hp_sdc_tbl); static int __init hp_sdc_init_hppa(struct parisc_device *d); static struct delayed_work moduleloader_work; static struct parisc_driver hp_sdc_driver __refdata = { .name = "hp_sdc", .id_table = hp_sdc_tbl, .probe = hp_sdc_init_hppa, }; #endif /* __hppa__ */ static int __init hp_sdc_init(void) { char *errstr; hp_sdc_transaction t_sync; uint8_t ts_sync[6]; struct semaphore s_sync; rwlock_init(&hp_sdc.lock); rwlock_init(&hp_sdc.ibf_lock); rwlock_init(&hp_sdc.rtq_lock); rwlock_init(&hp_sdc.hook_lock); hp_sdc.timer = NULL; hp_sdc.hil = NULL; hp_sdc.pup = NULL; hp_sdc.cooked = NULL; hp_sdc.im = HP_SDC_IM_MASK; /* Mask maskable irqs */ hp_sdc.set_im = 1; hp_sdc.wi = 0xff; hp_sdc.r7[0] = 0xff; hp_sdc.r7[1] = 0xff; hp_sdc.r7[2] = 0xff; hp_sdc.r7[3] = 0xff; hp_sdc.ibf = 1; memset(&hp_sdc.tq, 0, sizeof(hp_sdc.tq)); hp_sdc.wcurr = -1; hp_sdc.rcurr = -1; hp_sdc.rqty = 0; hp_sdc.dev_err = -ENODEV; errstr = "IO not found for"; if (!hp_sdc.base_io) goto err0; errstr = "IRQ not found for"; if (!hp_sdc.irq) goto err0; hp_sdc.dev_err = -EBUSY; #if defined(__hppa__) errstr = "IO not available for"; if (request_region(hp_sdc.data_io, 2, hp_sdc_driver.name)) goto err0; #endif errstr = "IRQ not available for"; if (request_irq(hp_sdc.irq, &hp_sdc_isr, IRQF_SHARED, "HP SDC", &hp_sdc)) goto err1; errstr = "NMI not available for"; if (request_irq(hp_sdc.nmi, &hp_sdc_nmisr, IRQF_SHARED, "HP SDC NMI", &hp_sdc)) goto err2; pr_info(PREFIX "HP SDC at 0x%08lx, IRQ %d (NMI IRQ %d)\n", hp_sdc.base_io, hp_sdc.irq, hp_sdc.nmi); hp_sdc_status_in8(); hp_sdc_data_in8(); tasklet_init(&hp_sdc.task, hp_sdc_tasklet, 0); /* Sync the output buffer registers, thus scheduling hp_sdc_tasklet. */ t_sync.actidx = 0; t_sync.idx = 1; t_sync.endidx = 6; t_sync.seq = ts_sync; ts_sync[0] = HP_SDC_ACT_DATAREG | HP_SDC_ACT_SEMAPHORE; ts_sync[1] = 0x0f; ts_sync[2] = ts_sync[3] = ts_sync[4] = ts_sync[5] = 0; t_sync.act.semaphore = &s_sync; sema_init(&s_sync, 0); hp_sdc_enqueue_transaction(&t_sync); down(&s_sync); /* Wait for t_sync to complete */ /* Create the keepalive task */ timer_setup(&hp_sdc.kicker, hp_sdc_kicker, 0); hp_sdc.kicker.expires = jiffies + HZ; add_timer(&hp_sdc.kicker); hp_sdc.dev_err = 0; return 0; err2: free_irq(hp_sdc.irq, &hp_sdc); err1: release_region(hp_sdc.data_io, 2); err0: printk(KERN_WARNING PREFIX ": %s SDC IO=0x%p IRQ=0x%x NMI=0x%x\n", errstr, (void *)hp_sdc.base_io, hp_sdc.irq, hp_sdc.nmi); hp_sdc.dev = NULL; return hp_sdc.dev_err; } #if defined(__hppa__) static void request_module_delayed(struct work_struct *work) { request_module("hp_sdc_mlc"); } static int __init hp_sdc_init_hppa(struct parisc_device *d) { int ret; if (!d) return 1; if (hp_sdc.dev != NULL) return 1; /* We only expect one SDC */ hp_sdc.dev = d; hp_sdc.irq = d->irq; hp_sdc.nmi = d->aux_irq; hp_sdc.base_io = d->hpa.start; hp_sdc.data_io = d->hpa.start + 0x800; hp_sdc.status_io = d->hpa.start + 0x801; INIT_DELAYED_WORK(&moduleloader_work, request_module_delayed); ret = hp_sdc_init(); /* after successful initialization give SDC some time to settle * and then load the hp_sdc_mlc upper layer driver */ if (!ret) schedule_delayed_work(&moduleloader_work, msecs_to_jiffies(2000)); return ret; } #endif /* __hppa__ */ static void hp_sdc_exit(void) { /* do nothing if we don't have a SDC */ if (!hp_sdc.dev) return; write_lock_irq(&hp_sdc.lock); /* Turn off all maskable "sub-function" irq's. */ hp_sdc_spin_ibf(); sdc_writeb(HP_SDC_CMD_SET_IM | HP_SDC_IM_MASK, hp_sdc.status_io); /* Wait until we know this has been processed by the i8042 */ hp_sdc_spin_ibf(); free_irq(hp_sdc.nmi, &hp_sdc); free_irq(hp_sdc.irq, &hp_sdc); write_unlock_irq(&hp_sdc.lock); del_timer_sync(&hp_sdc.kicker); tasklet_kill(&hp_sdc.task); #if defined(__hppa__) cancel_delayed_work_sync(&moduleloader_work); if (unregister_parisc_driver(&hp_sdc_driver)) printk(KERN_WARNING PREFIX "Error unregistering HP SDC"); #endif } static int __init hp_sdc_register(void) { hp_sdc_transaction tq_init; uint8_t tq_init_seq[5]; struct semaphore tq_init_sem; #if defined(__mc68000__) unsigned char i; #endif if (hp_sdc_disabled) { printk(KERN_WARNING PREFIX "HP SDC driver disabled by no_hpsdc=1.\n"); return -ENODEV; } hp_sdc.dev = NULL; hp_sdc.dev_err = 0; #if defined(__hppa__) if (register_parisc_driver(&hp_sdc_driver)) { printk(KERN_WARNING PREFIX "Error registering SDC with system bus tree.\n"); return -ENODEV; } #elif defined(__mc68000__) if (!MACH_IS_HP300) return -ENODEV; hp_sdc.irq = 1; hp_sdc.nmi = 7; hp_sdc.base_io = (unsigned long) 0xf0428000; hp_sdc.data_io = (unsigned long) hp_sdc.base_io + 1; hp_sdc.status_io = (unsigned long) hp_sdc.base_io + 3; if (!copy_from_kernel_nofault(&i, (unsigned char *)hp_sdc.data_io, 1)) hp_sdc.dev = (void *)1; hp_sdc.dev_err = hp_sdc_init(); #endif if (hp_sdc.dev == NULL) { printk(KERN_WARNING PREFIX "No SDC found.\n"); return hp_sdc.dev_err; } sema_init(&tq_init_sem, 0); tq_init.actidx = 0; tq_init.idx = 1; tq_init.endidx = 5; tq_init.seq = tq_init_seq; tq_init.act.semaphore = &tq_init_sem; tq_init_seq[0] = HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN | HP_SDC_ACT_SEMAPHORE; tq_init_seq[1] = HP_SDC_CMD_READ_KCC; tq_init_seq[2] = 1; tq_init_seq[3] = 0; tq_init_seq[4] = 0; hp_sdc_enqueue_transaction(&tq_init); down(&tq_init_sem); up(&tq_init_sem); if ((tq_init_seq[0] & HP_SDC_ACT_DEAD) == HP_SDC_ACT_DEAD) { printk(KERN_WARNING PREFIX "Error reading config byte.\n"); hp_sdc_exit(); return -ENODEV; } hp_sdc.r11 = tq_init_seq[4]; if (hp_sdc.r11 & HP_SDC_CFG_NEW) { const char *str; printk(KERN_INFO PREFIX "New style SDC\n"); tq_init_seq[1] = HP_SDC_CMD_READ_XTD; tq_init.actidx = 0; tq_init.idx = 1; down(&tq_init_sem); hp_sdc_enqueue_transaction(&tq_init); down(&tq_init_sem); up(&tq_init_sem); if ((tq_init_seq[0] & HP_SDC_ACT_DEAD) == HP_SDC_ACT_DEAD) { printk(KERN_WARNING PREFIX "Error reading extended config byte.\n"); return -ENODEV; } hp_sdc.r7e = tq_init_seq[4]; HP_SDC_XTD_REV_STRINGS(hp_sdc.r7e & HP_SDC_XTD_REV, str) printk(KERN_INFO PREFIX "Revision: %s\n", str); if (hp_sdc.r7e & HP_SDC_XTD_BEEPER) printk(KERN_INFO PREFIX "TI SN76494 beeper present\n"); if (hp_sdc.r7e & HP_SDC_XTD_BBRTC) printk(KERN_INFO PREFIX "OKI MSM-58321 BBRTC present\n"); printk(KERN_INFO PREFIX "Spunking the self test register to force PUP " "on next firmware reset.\n"); tq_init_seq[0] = HP_SDC_ACT_PRECMD | HP_SDC_ACT_DATAOUT | HP_SDC_ACT_SEMAPHORE; tq_init_seq[1] = HP_SDC_CMD_SET_STR; tq_init_seq[2] = 1; tq_init_seq[3] = 0; tq_init.actidx = 0; tq_init.idx = 1; tq_init.endidx = 4; down(&tq_init_sem); hp_sdc_enqueue_transaction(&tq_init); down(&tq_init_sem); up(&tq_init_sem); } else printk(KERN_INFO PREFIX "Old style SDC (1820-%s).\n", (hp_sdc.r11 & HP_SDC_CFG_REV) ? "3300" : "2564/3087"); return 0; } module_init(hp_sdc_register); module_exit(hp_sdc_exit); /* Timing notes: These measurements taken on my 64MHz 7100-LC (715/64) * cycles cycles-adj time * between two consecutive mfctl(16)'s: 4 n/a 63ns * hp_sdc_spin_ibf when idle: 119 115 1.7us * gsc_writeb status register: 83 79 1.2us * IBF to clear after sending SET_IM: 6204 6006 93us * IBF to clear after sending LOAD_RT: 4467 4352 68us * IBF to clear after sending two LOAD_RTs: 18974 18859 295us * READ_T1, read status/data, IRQ, call handler: 35564 n/a 556us * cmd to ~IBF READ_T1 2nd time right after: 5158403 n/a 81ms * between IRQ received and ~IBF for above: 2578877 n/a 40ms * * Performance stats after a run of this module configuring HIL and * receiving a few mouse events: * * status in8 282508 cycles 7128 calls * status out8 8404 cycles 341 calls * data out8 1734 cycles 78 calls * isr 174324 cycles 617 calls (includes take) * take 1241 cycles 2 calls * put 1411504 cycles 6937 calls * task 1655209 cycles 6937 calls (includes put) * */
linux-master
drivers/input/serio/hp_sdc.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2000-2001 Vojtech Pavlik * * Based on the work of: * Richard Zidlicky <[email protected]> */ /* * Q40 PS/2 keyboard controller driver for Linux/m68k */ #include <linux/module.h> #include <linux/serio.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/bitops.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <asm/io.h> #include <linux/uaccess.h> #include <asm/q40_master.h> #include <asm/irq.h> #include <asm/q40ints.h> #define DRV_NAME "q40kbd" MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Q40 PS/2 keyboard controller driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRV_NAME); struct q40kbd { struct serio *port; spinlock_t lock; }; static irqreturn_t q40kbd_interrupt(int irq, void *dev_id) { struct q40kbd *q40kbd = dev_id; unsigned long flags; spin_lock_irqsave(&q40kbd->lock, flags); if (Q40_IRQ_KEYB_MASK & master_inb(INTERRUPT_REG)) serio_interrupt(q40kbd->port, master_inb(KEYCODE_REG), 0); master_outb(-1, KEYBOARD_UNLOCK_REG); spin_unlock_irqrestore(&q40kbd->lock, flags); return IRQ_HANDLED; } /* * q40kbd_flush() flushes all data that may be in the keyboard buffers */ static void q40kbd_flush(struct q40kbd *q40kbd) { int maxread = 100; unsigned long flags; spin_lock_irqsave(&q40kbd->lock, flags); while (maxread-- && (Q40_IRQ_KEYB_MASK & master_inb(INTERRUPT_REG))) master_inb(KEYCODE_REG); spin_unlock_irqrestore(&q40kbd->lock, flags); } static void q40kbd_stop(void) { master_outb(0, KEY_IRQ_ENABLE_REG); master_outb(-1, KEYBOARD_UNLOCK_REG); } /* * q40kbd_open() is called when a port is open by the higher layer. * It allocates the interrupt and enables in in the chip. */ static int q40kbd_open(struct serio *port) { struct q40kbd *q40kbd = port->port_data; q40kbd_flush(q40kbd); /* off we go */ master_outb(-1, KEYBOARD_UNLOCK_REG); master_outb(1, KEY_IRQ_ENABLE_REG); return 0; } static void q40kbd_close(struct serio *port) { struct q40kbd *q40kbd = port->port_data; q40kbd_stop(); q40kbd_flush(q40kbd); } static int q40kbd_probe(struct platform_device *pdev) { struct q40kbd *q40kbd; struct serio *port; int error; q40kbd = kzalloc(sizeof(struct q40kbd), GFP_KERNEL); port = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!q40kbd || !port) { error = -ENOMEM; goto err_free_mem; } q40kbd->port = port; spin_lock_init(&q40kbd->lock); port->id.type = SERIO_8042; port->open = q40kbd_open; port->close = q40kbd_close; port->port_data = q40kbd; port->dev.parent = &pdev->dev; strscpy(port->name, "Q40 Kbd Port", sizeof(port->name)); strscpy(port->phys, "Q40", sizeof(port->phys)); q40kbd_stop(); error = request_irq(Q40_IRQ_KEYBOARD, q40kbd_interrupt, 0, DRV_NAME, q40kbd); if (error) { dev_err(&pdev->dev, "Can't get irq %d.\n", Q40_IRQ_KEYBOARD); goto err_free_mem; } serio_register_port(q40kbd->port); platform_set_drvdata(pdev, q40kbd); printk(KERN_INFO "serio: Q40 kbd registered\n"); return 0; err_free_mem: kfree(port); kfree(q40kbd); return error; } static int q40kbd_remove(struct platform_device *pdev) { struct q40kbd *q40kbd = platform_get_drvdata(pdev); /* * q40kbd_close() will be called as part of unregistering * and will ensure that IRQ is turned off, so it is safe * to unregister port first and free IRQ later. */ serio_unregister_port(q40kbd->port); free_irq(Q40_IRQ_KEYBOARD, q40kbd); kfree(q40kbd); return 0; } static struct platform_driver q40kbd_driver = { .driver = { .name = "q40kbd", }, .remove = q40kbd_remove, }; module_platform_driver_probe(q40kbd_driver, q40kbd_probe);
linux-master
drivers/input/serio/q40kbd.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Xilinx XPS PS/2 device driver * * (c) 2005 MontaVista Software, Inc. * (c) 2008 Xilinx, Inc. */ #include <linux/module.h> #include <linux/serio.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/io.h> #include <linux/mod_devicetable.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/platform_device.h> #define DRIVER_NAME "xilinx_ps2" /* Register offsets for the xps2 device */ #define XPS2_SRST_OFFSET 0x00000000 /* Software Reset register */ #define XPS2_STATUS_OFFSET 0x00000004 /* Status register */ #define XPS2_RX_DATA_OFFSET 0x00000008 /* Receive Data register */ #define XPS2_TX_DATA_OFFSET 0x0000000C /* Transmit Data register */ #define XPS2_GIER_OFFSET 0x0000002C /* Global Interrupt Enable reg */ #define XPS2_IPISR_OFFSET 0x00000030 /* Interrupt Status register */ #define XPS2_IPIER_OFFSET 0x00000038 /* Interrupt Enable register */ /* Reset Register Bit Definitions */ #define XPS2_SRST_RESET 0x0000000A /* Software Reset */ /* Status Register Bit Positions */ #define XPS2_STATUS_RX_FULL 0x00000001 /* Receive Full */ #define XPS2_STATUS_TX_FULL 0x00000002 /* Transmit Full */ /* * Bit definitions for ISR/IER registers. Both the registers have the same bit * definitions and are only defined once. */ #define XPS2_IPIXR_WDT_TOUT 0x00000001 /* Watchdog Timeout Interrupt */ #define XPS2_IPIXR_TX_NOACK 0x00000002 /* Transmit No ACK Interrupt */ #define XPS2_IPIXR_TX_ACK 0x00000004 /* Transmit ACK (Data) Interrupt */ #define XPS2_IPIXR_RX_OVF 0x00000008 /* Receive Overflow Interrupt */ #define XPS2_IPIXR_RX_ERR 0x00000010 /* Receive Error Interrupt */ #define XPS2_IPIXR_RX_FULL 0x00000020 /* Receive Data Interrupt */ /* Mask for all the Transmit Interrupts */ #define XPS2_IPIXR_TX_ALL (XPS2_IPIXR_TX_NOACK | XPS2_IPIXR_TX_ACK) /* Mask for all the Receive Interrupts */ #define XPS2_IPIXR_RX_ALL (XPS2_IPIXR_RX_OVF | XPS2_IPIXR_RX_ERR | \ XPS2_IPIXR_RX_FULL) /* Mask for all the Interrupts */ #define XPS2_IPIXR_ALL (XPS2_IPIXR_TX_ALL | XPS2_IPIXR_RX_ALL | \ XPS2_IPIXR_WDT_TOUT) /* Global Interrupt Enable mask */ #define XPS2_GIER_GIE_MASK 0x80000000 struct xps2data { int irq; spinlock_t lock; void __iomem *base_address; /* virt. address of control registers */ unsigned int flags; struct serio *serio; /* serio */ struct device *dev; }; /************************************/ /* XPS PS/2 data transmission calls */ /************************************/ /** * xps2_recv() - attempts to receive a byte from the PS/2 port. * @drvdata: pointer to ps2 device private data structure * @byte: address where the read data will be copied * * If there is any data available in the PS/2 receiver, this functions reads * the data, otherwise it returns error. */ static int xps2_recv(struct xps2data *drvdata, u8 *byte) { u32 sr; int status = -1; /* If there is data available in the PS/2 receiver, read it */ sr = in_be32(drvdata->base_address + XPS2_STATUS_OFFSET); if (sr & XPS2_STATUS_RX_FULL) { *byte = in_be32(drvdata->base_address + XPS2_RX_DATA_OFFSET); status = 0; } return status; } /*********************/ /* Interrupt handler */ /*********************/ static irqreturn_t xps2_interrupt(int irq, void *dev_id) { struct xps2data *drvdata = dev_id; u32 intr_sr; u8 c; int status; /* Get the PS/2 interrupts and clear them */ intr_sr = in_be32(drvdata->base_address + XPS2_IPISR_OFFSET); out_be32(drvdata->base_address + XPS2_IPISR_OFFSET, intr_sr); /* Check which interrupt is active */ if (intr_sr & XPS2_IPIXR_RX_OVF) dev_warn(drvdata->dev, "receive overrun error\n"); if (intr_sr & XPS2_IPIXR_RX_ERR) drvdata->flags |= SERIO_PARITY; if (intr_sr & (XPS2_IPIXR_TX_NOACK | XPS2_IPIXR_WDT_TOUT)) drvdata->flags |= SERIO_TIMEOUT; if (intr_sr & XPS2_IPIXR_RX_FULL) { status = xps2_recv(drvdata, &c); /* Error, if a byte is not received */ if (status) { dev_err(drvdata->dev, "wrong rcvd byte count (%d)\n", status); } else { serio_interrupt(drvdata->serio, c, drvdata->flags); drvdata->flags = 0; } } return IRQ_HANDLED; } /*******************/ /* serio callbacks */ /*******************/ /** * sxps2_write() - sends a byte out through the PS/2 port. * @pserio: pointer to the serio structure of the PS/2 port * @c: data that needs to be written to the PS/2 port * * This function checks if the PS/2 transmitter is empty and sends a byte. * Otherwise it returns error. Transmission fails only when nothing is connected * to the PS/2 port. Thats why, we do not try to resend the data in case of a * failure. */ static int sxps2_write(struct serio *pserio, unsigned char c) { struct xps2data *drvdata = pserio->port_data; unsigned long flags; u32 sr; int status = -1; spin_lock_irqsave(&drvdata->lock, flags); /* If the PS/2 transmitter is empty send a byte of data */ sr = in_be32(drvdata->base_address + XPS2_STATUS_OFFSET); if (!(sr & XPS2_STATUS_TX_FULL)) { out_be32(drvdata->base_address + XPS2_TX_DATA_OFFSET, c); status = 0; } spin_unlock_irqrestore(&drvdata->lock, flags); return status; } /** * sxps2_open() - called when a port is opened by the higher layer. * @pserio: pointer to the serio structure of the PS/2 device * * This function requests irq and enables interrupts for the PS/2 device. */ static int sxps2_open(struct serio *pserio) { struct xps2data *drvdata = pserio->port_data; int error; u8 c; error = request_irq(drvdata->irq, &xps2_interrupt, 0, DRIVER_NAME, drvdata); if (error) { dev_err(drvdata->dev, "Couldn't allocate interrupt %d\n", drvdata->irq); return error; } /* start reception by enabling the interrupts */ out_be32(drvdata->base_address + XPS2_GIER_OFFSET, XPS2_GIER_GIE_MASK); out_be32(drvdata->base_address + XPS2_IPIER_OFFSET, XPS2_IPIXR_RX_ALL); (void)xps2_recv(drvdata, &c); return 0; /* success */ } /** * sxps2_close() - frees the interrupt. * @pserio: pointer to the serio structure of the PS/2 device * * This function frees the irq and disables interrupts for the PS/2 device. */ static void sxps2_close(struct serio *pserio) { struct xps2data *drvdata = pserio->port_data; /* Disable the PS2 interrupts */ out_be32(drvdata->base_address + XPS2_GIER_OFFSET, 0x00); out_be32(drvdata->base_address + XPS2_IPIER_OFFSET, 0x00); free_irq(drvdata->irq, drvdata); } /** * xps2_of_probe - probe method for the PS/2 device. * @of_dev: pointer to OF device structure * @match: pointer to the structure used for matching a device * * This function probes the PS/2 device in the device tree. * It initializes the driver data structure and the hardware. * It returns 0, if the driver is bound to the PS/2 device, or a negative * value if there is an error. */ static int xps2_of_probe(struct platform_device *ofdev) { struct resource r_mem; /* IO mem resources */ struct xps2data *drvdata; struct serio *serio; struct device *dev = &ofdev->dev; resource_size_t remap_size, phys_addr; unsigned int irq; int error; dev_info(dev, "Device Tree Probing \'%pOFn\'\n", dev->of_node); /* Get iospace for the device */ error = of_address_to_resource(dev->of_node, 0, &r_mem); if (error) { dev_err(dev, "invalid address\n"); return error; } /* Get IRQ for the device */ irq = irq_of_parse_and_map(dev->of_node, 0); if (!irq) { dev_err(dev, "no IRQ found\n"); return -ENODEV; } drvdata = kzalloc(sizeof(struct xps2data), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!drvdata || !serio) { error = -ENOMEM; goto failed1; } spin_lock_init(&drvdata->lock); drvdata->irq = irq; drvdata->serio = serio; drvdata->dev = dev; phys_addr = r_mem.start; remap_size = resource_size(&r_mem); if (!request_mem_region(phys_addr, remap_size, DRIVER_NAME)) { dev_err(dev, "Couldn't lock memory region at 0x%08llX\n", (unsigned long long)phys_addr); error = -EBUSY; goto failed1; } /* Fill in configuration data and add them to the list */ drvdata->base_address = ioremap(phys_addr, remap_size); if (drvdata->base_address == NULL) { dev_err(dev, "Couldn't ioremap memory at 0x%08llX\n", (unsigned long long)phys_addr); error = -EFAULT; goto failed2; } /* Disable all the interrupts, just in case */ out_be32(drvdata->base_address + XPS2_IPIER_OFFSET, 0); /* * Reset the PS2 device and abort any current transaction, * to make sure we have the PS2 in a good state. */ out_be32(drvdata->base_address + XPS2_SRST_OFFSET, XPS2_SRST_RESET); dev_info(dev, "Xilinx PS2 at 0x%08llX mapped to 0x%p, irq=%d\n", (unsigned long long)phys_addr, drvdata->base_address, drvdata->irq); serio->id.type = SERIO_8042; serio->write = sxps2_write; serio->open = sxps2_open; serio->close = sxps2_close; serio->port_data = drvdata; serio->dev.parent = dev; snprintf(serio->name, sizeof(serio->name), "Xilinx XPS PS/2 at %08llX", (unsigned long long)phys_addr); snprintf(serio->phys, sizeof(serio->phys), "xilinxps2/serio at %08llX", (unsigned long long)phys_addr); serio_register_port(serio); platform_set_drvdata(ofdev, drvdata); return 0; /* success */ failed2: release_mem_region(phys_addr, remap_size); failed1: kfree(serio); kfree(drvdata); return error; } /** * xps2_of_remove - unbinds the driver from the PS/2 device. * @of_dev: pointer to OF device structure * * This function is called if a device is physically removed from the system or * if the driver module is being unloaded. It frees any resources allocated to * the device. */ static int xps2_of_remove(struct platform_device *of_dev) { struct xps2data *drvdata = platform_get_drvdata(of_dev); struct resource r_mem; /* IO mem resources */ serio_unregister_port(drvdata->serio); iounmap(drvdata->base_address); /* Get iospace of the device */ if (of_address_to_resource(of_dev->dev.of_node, 0, &r_mem)) dev_err(drvdata->dev, "invalid address\n"); else release_mem_region(r_mem.start, resource_size(&r_mem)); kfree(drvdata); return 0; } /* Match table for of_platform binding */ static const struct of_device_id xps2_of_match[] = { { .compatible = "xlnx,xps-ps2-1.00.a", }, { /* end of list */ }, }; MODULE_DEVICE_TABLE(of, xps2_of_match); static struct platform_driver xps2_of_driver = { .driver = { .name = DRIVER_NAME, .of_match_table = xps2_of_match, }, .probe = xps2_of_probe, .remove = xps2_of_remove, }; module_platform_driver(xps2_of_driver); MODULE_AUTHOR("Xilinx, Inc."); MODULE_DESCRIPTION("Xilinx XPS PS/2 driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/xilinx_ps2.c
/* * drivers/input/serio/gscps2.c * * Copyright (c) 2004-2006 Helge Deller <[email protected]> * Copyright (c) 2002 Laurent Canet <[email protected]> * Copyright (c) 2002 Thibaut Varene <[email protected]> * * Pieces of code based on linux-2.4's hp_mouse.c & hp_keyb.c * Copyright (c) 1999 Alex deVries <[email protected]> * Copyright (c) 1999-2000 Philipp Rumpf <[email protected]> * Copyright (c) 2000 Xavier Debacker <[email protected]> * Copyright (c) 2000-2001 Thomas Marteau <[email protected]> * * HP GSC PS/2 port driver, found in PA/RISC Workstations * * 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. * * TODO: * - Dino testing (did HP ever shipped a machine on which this port * was usable/enabled ?) */ #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/serio.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/delay.h> #include <linux/ioport.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/parisc-device.h> MODULE_AUTHOR("Laurent Canet <[email protected]>, Thibaut Varene <[email protected]>, Helge Deller <[email protected]>"); MODULE_DESCRIPTION("HP GSC PS2 port driver"); MODULE_LICENSE("GPL"); #define PFX "gscps2.c: " /* * Driver constants */ /* various constants */ #define ENABLE 1 #define DISABLE 0 #define GSC_DINO_OFFSET 0x0800 /* offset for DINO controller versus LASI one */ /* PS/2 IO port offsets */ #define GSC_ID 0x00 /* device ID offset (see: GSC_ID_XXX) */ #define GSC_RESET 0x00 /* reset port offset */ #define GSC_RCVDATA 0x04 /* receive port offset */ #define GSC_XMTDATA 0x04 /* transmit port offset */ #define GSC_CONTROL 0x08 /* see: Control register bits */ #define GSC_STATUS 0x0C /* see: Status register bits */ /* Control register bits */ #define GSC_CTRL_ENBL 0x01 /* enable interface */ #define GSC_CTRL_LPBXR 0x02 /* loopback operation */ #define GSC_CTRL_DIAG 0x20 /* directly control clock/data line */ #define GSC_CTRL_DATDIR 0x40 /* data line direct control */ #define GSC_CTRL_CLKDIR 0x80 /* clock line direct control */ /* Status register bits */ #define GSC_STAT_RBNE 0x01 /* Receive Buffer Not Empty */ #define GSC_STAT_TBNE 0x02 /* Transmit Buffer Not Empty */ #define GSC_STAT_TERR 0x04 /* Timeout Error */ #define GSC_STAT_PERR 0x08 /* Parity Error */ #define GSC_STAT_CMPINTR 0x10 /* Composite Interrupt = irq on any port */ #define GSC_STAT_DATSHD 0x40 /* Data Line Shadow */ #define GSC_STAT_CLKSHD 0x80 /* Clock Line Shadow */ /* IDs returned by GSC_ID port register */ #define GSC_ID_KEYBOARD 0 /* device ID values */ #define GSC_ID_MOUSE 1 static irqreturn_t gscps2_interrupt(int irq, void *dev); #define BUFFER_SIZE 0x0f /* GSC PS/2 port device struct */ struct gscps2port { struct list_head node; struct parisc_device *padev; struct serio *port; spinlock_t lock; char __iomem *addr; u8 act, append; /* position in buffer[] */ struct { u8 data; u8 str; } buffer[BUFFER_SIZE+1]; int id; }; /* * Various HW level routines */ #define gscps2_readb_input(x) readb((x)+GSC_RCVDATA) #define gscps2_readb_control(x) readb((x)+GSC_CONTROL) #define gscps2_readb_status(x) readb((x)+GSC_STATUS) #define gscps2_writeb_control(x, y) writeb((x), (y)+GSC_CONTROL) /* * wait_TBE() - wait for Transmit Buffer Empty */ static int wait_TBE(char __iomem *addr) { int timeout = 25000; /* device is expected to react within 250 msec */ while (gscps2_readb_status(addr) & GSC_STAT_TBNE) { if (!--timeout) return 0; /* This should not happen */ udelay(10); } return 1; } /* * gscps2_flush() - flush the receive buffer */ static void gscps2_flush(struct gscps2port *ps2port) { while (gscps2_readb_status(ps2port->addr) & GSC_STAT_RBNE) gscps2_readb_input(ps2port->addr); ps2port->act = ps2port->append = 0; } /* * gscps2_writeb_output() - write a byte to the port * * returns 1 on success, 0 on error */ static inline int gscps2_writeb_output(struct gscps2port *ps2port, u8 data) { unsigned long flags; char __iomem *addr = ps2port->addr; if (!wait_TBE(addr)) { printk(KERN_DEBUG PFX "timeout - could not write byte %#x\n", data); return 0; } while (gscps2_readb_status(addr) & GSC_STAT_RBNE) /* wait */; spin_lock_irqsave(&ps2port->lock, flags); writeb(data, addr+GSC_XMTDATA); spin_unlock_irqrestore(&ps2port->lock, flags); /* this is ugly, but due to timing of the port it seems to be necessary. */ mdelay(6); /* make sure any received data is returned as fast as possible */ /* this is important e.g. when we set the LEDs on the keyboard */ gscps2_interrupt(0, NULL); return 1; } /* * gscps2_enable() - enables or disables the port */ static void gscps2_enable(struct gscps2port *ps2port, int enable) { unsigned long flags; u8 data; /* now enable/disable the port */ spin_lock_irqsave(&ps2port->lock, flags); gscps2_flush(ps2port); data = gscps2_readb_control(ps2port->addr); if (enable) data |= GSC_CTRL_ENBL; else data &= ~GSC_CTRL_ENBL; gscps2_writeb_control(data, ps2port->addr); spin_unlock_irqrestore(&ps2port->lock, flags); wait_TBE(ps2port->addr); gscps2_flush(ps2port); } /* * gscps2_reset() - resets the PS/2 port */ static void gscps2_reset(struct gscps2port *ps2port) { unsigned long flags; /* reset the interface */ spin_lock_irqsave(&ps2port->lock, flags); gscps2_flush(ps2port); writeb(0xff, ps2port->addr + GSC_RESET); gscps2_flush(ps2port); spin_unlock_irqrestore(&ps2port->lock, flags); } static LIST_HEAD(ps2port_list); /** * gscps2_interrupt() - Interruption service routine * * This function reads received PS/2 bytes and processes them on * all interfaces. * The problematic part here is, that the keyboard and mouse PS/2 port * share the same interrupt and it's not possible to send data if any * one of them holds input data. To solve this problem we try to receive * the data as fast as possible and handle the reporting to the upper layer * later. */ static irqreturn_t gscps2_interrupt(int irq, void *dev) { struct gscps2port *ps2port; list_for_each_entry(ps2port, &ps2port_list, node) { unsigned long flags; spin_lock_irqsave(&ps2port->lock, flags); while ( (ps2port->buffer[ps2port->append].str = gscps2_readb_status(ps2port->addr)) & GSC_STAT_RBNE ) { ps2port->buffer[ps2port->append].data = gscps2_readb_input(ps2port->addr); ps2port->append = ((ps2port->append+1) & BUFFER_SIZE); } spin_unlock_irqrestore(&ps2port->lock, flags); } /* list_for_each_entry */ /* all data was read from the ports - now report the data to upper layer */ list_for_each_entry(ps2port, &ps2port_list, node) { while (ps2port->act != ps2port->append) { unsigned int rxflags; u8 data, status; /* Did new data arrived while we read existing data ? If yes, exit now and let the new irq handler start over again */ if (gscps2_readb_status(ps2port->addr) & GSC_STAT_CMPINTR) return IRQ_HANDLED; status = ps2port->buffer[ps2port->act].str; data = ps2port->buffer[ps2port->act].data; ps2port->act = ((ps2port->act+1) & BUFFER_SIZE); rxflags = ((status & GSC_STAT_TERR) ? SERIO_TIMEOUT : 0 ) | ((status & GSC_STAT_PERR) ? SERIO_PARITY : 0 ); serio_interrupt(ps2port->port, data, rxflags); } /* while() */ } /* list_for_each_entry */ return IRQ_HANDLED; } /* * gscps2_write() - send a byte out through the aux interface. */ static int gscps2_write(struct serio *port, unsigned char data) { struct gscps2port *ps2port = port->port_data; if (!gscps2_writeb_output(ps2port, data)) { printk(KERN_DEBUG PFX "sending byte %#x failed.\n", data); return -1; } return 0; } /* * gscps2_open() is called when a port is opened by the higher layer. * It resets and enables the port. */ static int gscps2_open(struct serio *port) { struct gscps2port *ps2port = port->port_data; gscps2_reset(ps2port); /* enable it */ gscps2_enable(ps2port, ENABLE); gscps2_interrupt(0, NULL); return 0; } /* * gscps2_close() disables the port */ static void gscps2_close(struct serio *port) { struct gscps2port *ps2port = port->port_data; gscps2_enable(ps2port, DISABLE); } /** * gscps2_probe() - Probes PS2 devices * @return: success/error report */ static int __init gscps2_probe(struct parisc_device *dev) { struct gscps2port *ps2port; struct serio *serio; unsigned long hpa = dev->hpa.start; int ret; if (!dev->irq) return -ENODEV; /* Offset for DINO PS/2. Works with LASI even */ if (dev->id.sversion == 0x96) hpa += GSC_DINO_OFFSET; ps2port = kzalloc(sizeof(struct gscps2port), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!ps2port || !serio) { ret = -ENOMEM; goto fail_nomem; } dev_set_drvdata(&dev->dev, ps2port); ps2port->port = serio; ps2port->padev = dev; ps2port->addr = ioremap(hpa, GSC_STATUS + 4); if (!ps2port->addr) { ret = -ENOMEM; goto fail_nomem; } spin_lock_init(&ps2port->lock); gscps2_reset(ps2port); ps2port->id = readb(ps2port->addr + GSC_ID) & 0x0f; snprintf(serio->name, sizeof(serio->name), "gsc-ps2-%s", (ps2port->id == GSC_ID_KEYBOARD) ? "keyboard" : "mouse"); strscpy(serio->phys, dev_name(&dev->dev), sizeof(serio->phys)); serio->id.type = SERIO_8042; serio->write = gscps2_write; serio->open = gscps2_open; serio->close = gscps2_close; serio->port_data = ps2port; serio->dev.parent = &dev->dev; ret = -EBUSY; if (request_irq(dev->irq, gscps2_interrupt, IRQF_SHARED, ps2port->port->name, ps2port)) goto fail_miserably; if (ps2port->id != GSC_ID_KEYBOARD && ps2port->id != GSC_ID_MOUSE) { printk(KERN_WARNING PFX "Unsupported PS/2 port at 0x%08lx (id=%d) ignored\n", hpa, ps2port->id); ret = -ENODEV; goto fail; } #if 0 if (!request_mem_region(hpa, GSC_STATUS + 4, ps2port->port.name)) goto fail; #endif pr_info("serio: %s port at 0x%08lx irq %d @ %s\n", ps2port->port->name, hpa, ps2port->padev->irq, ps2port->port->phys); serio_register_port(ps2port->port); list_add_tail(&ps2port->node, &ps2port_list); return 0; fail: free_irq(dev->irq, ps2port); fail_miserably: iounmap(ps2port->addr); release_mem_region(dev->hpa.start, GSC_STATUS + 4); fail_nomem: kfree(ps2port); kfree(serio); return ret; } /** * gscps2_remove() - Removes PS2 devices * @return: success/error report */ static void __exit gscps2_remove(struct parisc_device *dev) { struct gscps2port *ps2port = dev_get_drvdata(&dev->dev); serio_unregister_port(ps2port->port); free_irq(dev->irq, ps2port); gscps2_flush(ps2port); list_del(&ps2port->node); iounmap(ps2port->addr); #if 0 release_mem_region(dev->hpa, GSC_STATUS + 4); #endif dev_set_drvdata(&dev->dev, NULL); kfree(ps2port); } static const struct parisc_device_id gscps2_device_tbl[] __initconst = { { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00084 }, /* LASI PS/2 */ #ifdef DINO_TESTED { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00096 }, /* DINO PS/2 */ #endif { 0, } /* 0 terminated list */ }; MODULE_DEVICE_TABLE(parisc, gscps2_device_tbl); static struct parisc_driver parisc_ps2_driver __refdata = { .name = "gsc_ps2", .id_table = gscps2_device_tbl, .probe = gscps2_probe, .remove = __exit_p(gscps2_remove), }; static int __init gscps2_init(void) { register_parisc_driver(&parisc_ps2_driver); return 0; } static void __exit gscps2_exit(void) { unregister_parisc_driver(&parisc_ps2_driver); } module_init(gscps2_init); module_exit(gscps2_exit);
linux-master
drivers/input/serio/gscps2.c
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/input/serio/sa1111ps2.c * * Copyright (C) 2002 Russell King */ #include <linux/module.h> #include <linux/init.h> #include <linux/input.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <asm/io.h> #include <asm/hardware/sa1111.h> #define PS2CR 0x0000 #define PS2STAT 0x0004 #define PS2DATA 0x0008 #define PS2CLKDIV 0x000c #define PS2PRECNT 0x0010 #define PS2CR_ENA 0x08 #define PS2CR_FKD 0x02 #define PS2CR_FKC 0x01 #define PS2STAT_STP 0x0100 #define PS2STAT_TXE 0x0080 #define PS2STAT_TXB 0x0040 #define PS2STAT_RXF 0x0020 #define PS2STAT_RXB 0x0010 #define PS2STAT_ENA 0x0008 #define PS2STAT_RXP 0x0004 #define PS2STAT_KBD 0x0002 #define PS2STAT_KBC 0x0001 struct ps2if { struct serio *io; struct sa1111_dev *dev; void __iomem *base; int rx_irq; int tx_irq; unsigned int open; spinlock_t lock; unsigned int head; unsigned int tail; unsigned char buf[4]; }; /* * Read all bytes waiting in the PS2 port. There should be * at the most one, but we loop for safety. If there was a * framing error, we have to manually clear the status. */ static irqreturn_t ps2_rxint(int irq, void *dev_id) { struct ps2if *ps2if = dev_id; unsigned int scancode, flag, status; status = readl_relaxed(ps2if->base + PS2STAT); while (status & PS2STAT_RXF) { if (status & PS2STAT_STP) writel_relaxed(PS2STAT_STP, ps2if->base + PS2STAT); flag = (status & PS2STAT_STP ? SERIO_FRAME : 0) | (status & PS2STAT_RXP ? 0 : SERIO_PARITY); scancode = readl_relaxed(ps2if->base + PS2DATA) & 0xff; if (hweight8(scancode) & 1) flag ^= SERIO_PARITY; serio_interrupt(ps2if->io, scancode, flag); status = readl_relaxed(ps2if->base + PS2STAT); } return IRQ_HANDLED; } /* * Completion of ps2 write */ static irqreturn_t ps2_txint(int irq, void *dev_id) { struct ps2if *ps2if = dev_id; unsigned int status; spin_lock(&ps2if->lock); status = readl_relaxed(ps2if->base + PS2STAT); if (ps2if->head == ps2if->tail) { disable_irq_nosync(irq); /* done */ } else if (status & PS2STAT_TXE) { writel_relaxed(ps2if->buf[ps2if->tail], ps2if->base + PS2DATA); ps2if->tail = (ps2if->tail + 1) & (sizeof(ps2if->buf) - 1); } spin_unlock(&ps2if->lock); return IRQ_HANDLED; } /* * Write a byte to the PS2 port. We have to wait for the * port to indicate that the transmitter is empty. */ static int ps2_write(struct serio *io, unsigned char val) { struct ps2if *ps2if = io->port_data; unsigned long flags; unsigned int head; spin_lock_irqsave(&ps2if->lock, flags); /* * If the TX register is empty, we can go straight out. */ if (readl_relaxed(ps2if->base + PS2STAT) & PS2STAT_TXE) { writel_relaxed(val, ps2if->base + PS2DATA); } else { if (ps2if->head == ps2if->tail) enable_irq(ps2if->tx_irq); head = (ps2if->head + 1) & (sizeof(ps2if->buf) - 1); if (head != ps2if->tail) { ps2if->buf[ps2if->head] = val; ps2if->head = head; } } spin_unlock_irqrestore(&ps2if->lock, flags); return 0; } static int ps2_open(struct serio *io) { struct ps2if *ps2if = io->port_data; int ret; ret = sa1111_enable_device(ps2if->dev); if (ret) return ret; ret = request_irq(ps2if->rx_irq, ps2_rxint, 0, SA1111_DRIVER_NAME(ps2if->dev), ps2if); if (ret) { printk(KERN_ERR "sa1111ps2: could not allocate IRQ%d: %d\n", ps2if->rx_irq, ret); sa1111_disable_device(ps2if->dev); return ret; } ret = request_irq(ps2if->tx_irq, ps2_txint, 0, SA1111_DRIVER_NAME(ps2if->dev), ps2if); if (ret) { printk(KERN_ERR "sa1111ps2: could not allocate IRQ%d: %d\n", ps2if->tx_irq, ret); free_irq(ps2if->rx_irq, ps2if); sa1111_disable_device(ps2if->dev); return ret; } ps2if->open = 1; enable_irq_wake(ps2if->rx_irq); writel_relaxed(PS2CR_ENA, ps2if->base + PS2CR); return 0; } static void ps2_close(struct serio *io) { struct ps2if *ps2if = io->port_data; writel_relaxed(0, ps2if->base + PS2CR); disable_irq_wake(ps2if->rx_irq); ps2if->open = 0; free_irq(ps2if->tx_irq, ps2if); free_irq(ps2if->rx_irq, ps2if); sa1111_disable_device(ps2if->dev); } /* * Clear the input buffer. */ static void ps2_clear_input(struct ps2if *ps2if) { int maxread = 100; while (maxread--) { if ((readl_relaxed(ps2if->base + PS2DATA) & 0xff) == 0xff) break; } } static unsigned int ps2_test_one(struct ps2if *ps2if, unsigned int mask) { unsigned int val; writel_relaxed(PS2CR_ENA | mask, ps2if->base + PS2CR); udelay(10); val = readl_relaxed(ps2if->base + PS2STAT); return val & (PS2STAT_KBC | PS2STAT_KBD); } /* * Test the keyboard interface. We basically check to make sure that * we can drive each line to the keyboard independently of each other. */ static int ps2_test(struct ps2if *ps2if) { unsigned int stat; int ret = 0; stat = ps2_test_one(ps2if, PS2CR_FKC); if (stat != PS2STAT_KBD) { printk("PS/2 interface test failed[1]: %02x\n", stat); ret = -ENODEV; } stat = ps2_test_one(ps2if, 0); if (stat != (PS2STAT_KBC | PS2STAT_KBD)) { printk("PS/2 interface test failed[2]: %02x\n", stat); ret = -ENODEV; } stat = ps2_test_one(ps2if, PS2CR_FKD); if (stat != PS2STAT_KBC) { printk("PS/2 interface test failed[3]: %02x\n", stat); ret = -ENODEV; } writel_relaxed(0, ps2if->base + PS2CR); return ret; } /* * Add one device to this driver. */ static int ps2_probe(struct sa1111_dev *dev) { struct ps2if *ps2if; struct serio *serio; int ret; ps2if = kzalloc(sizeof(struct ps2if), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!ps2if || !serio) { ret = -ENOMEM; goto free; } serio->id.type = SERIO_8042; serio->write = ps2_write; serio->open = ps2_open; serio->close = ps2_close; strscpy(serio->name, dev_name(&dev->dev), sizeof(serio->name)); strscpy(serio->phys, dev_name(&dev->dev), sizeof(serio->phys)); serio->port_data = ps2if; serio->dev.parent = &dev->dev; ps2if->io = serio; ps2if->dev = dev; sa1111_set_drvdata(dev, ps2if); spin_lock_init(&ps2if->lock); ps2if->rx_irq = sa1111_get_irq(dev, 0); if (ps2if->rx_irq <= 0) { ret = ps2if->rx_irq ? : -ENXIO; goto free; } ps2if->tx_irq = sa1111_get_irq(dev, 1); if (ps2if->tx_irq <= 0) { ret = ps2if->tx_irq ? : -ENXIO; goto free; } /* * Request the physical region for this PS2 port. */ if (!request_mem_region(dev->res.start, dev->res.end - dev->res.start + 1, SA1111_DRIVER_NAME(dev))) { ret = -EBUSY; goto free; } /* * Our parent device has already mapped the region. */ ps2if->base = dev->mapbase; sa1111_enable_device(ps2if->dev); /* Incoming clock is 8MHz */ writel_relaxed(0, ps2if->base + PS2CLKDIV); writel_relaxed(127, ps2if->base + PS2PRECNT); /* * Flush any pending input. */ ps2_clear_input(ps2if); /* * Test the keyboard interface. */ ret = ps2_test(ps2if); if (ret) goto out; /* * Flush any pending input. */ ps2_clear_input(ps2if); sa1111_disable_device(ps2if->dev); serio_register_port(ps2if->io); return 0; out: sa1111_disable_device(ps2if->dev); release_mem_region(dev->res.start, resource_size(&dev->res)); free: sa1111_set_drvdata(dev, NULL); kfree(ps2if); kfree(serio); return ret; } /* * Remove one device from this driver. */ static void ps2_remove(struct sa1111_dev *dev) { struct ps2if *ps2if = sa1111_get_drvdata(dev); serio_unregister_port(ps2if->io); release_mem_region(dev->res.start, resource_size(&dev->res)); sa1111_set_drvdata(dev, NULL); kfree(ps2if); } /* * Our device driver structure */ static struct sa1111_driver ps2_driver = { .drv = { .name = "sa1111-ps2", .owner = THIS_MODULE, }, .devid = SA1111_DEVID_PS2, .probe = ps2_probe, .remove = ps2_remove, }; static int __init ps2_init(void) { return sa1111_driver_register(&ps2_driver); } static void __exit ps2_exit(void) { sa1111_driver_unregister(&ps2_driver); } module_init(ps2_init); module_exit(ps2_exit); MODULE_AUTHOR("Russell King <[email protected]>"); MODULE_DESCRIPTION("SA1111 PS2 controller driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/sa1111ps2.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * The Serio abstraction module * * Copyright (c) 1999-2004 Vojtech Pavlik * Copyright (c) 2004 Dmitry Torokhov * Copyright (c) 2003 Daniele Bellucci */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/stddef.h> #include <linux/module.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/mutex.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Serio abstraction core"); MODULE_LICENSE("GPL"); /* * serio_mutex protects entire serio subsystem and is taken every time * serio port or driver registered or unregistered. */ static DEFINE_MUTEX(serio_mutex); static LIST_HEAD(serio_list); static void serio_add_port(struct serio *serio); static int serio_reconnect_port(struct serio *serio); static void serio_disconnect_port(struct serio *serio); static void serio_reconnect_subtree(struct serio *serio); static void serio_attach_driver(struct serio_driver *drv); static int serio_connect_driver(struct serio *serio, struct serio_driver *drv) { int retval; mutex_lock(&serio->drv_mutex); retval = drv->connect(serio, drv); mutex_unlock(&serio->drv_mutex); return retval; } static int serio_reconnect_driver(struct serio *serio) { int retval = -1; mutex_lock(&serio->drv_mutex); if (serio->drv && serio->drv->reconnect) retval = serio->drv->reconnect(serio); mutex_unlock(&serio->drv_mutex); return retval; } static void serio_disconnect_driver(struct serio *serio) { mutex_lock(&serio->drv_mutex); if (serio->drv) serio->drv->disconnect(serio); mutex_unlock(&serio->drv_mutex); } static int serio_match_port(const struct serio_device_id *ids, struct serio *serio) { while (ids->type || ids->proto) { if ((ids->type == SERIO_ANY || ids->type == serio->id.type) && (ids->proto == SERIO_ANY || ids->proto == serio->id.proto) && (ids->extra == SERIO_ANY || ids->extra == serio->id.extra) && (ids->id == SERIO_ANY || ids->id == serio->id.id)) return 1; ids++; } return 0; } /* * Basic serio -> driver core mappings */ static int serio_bind_driver(struct serio *serio, struct serio_driver *drv) { int error; if (serio_match_port(drv->id_table, serio)) { serio->dev.driver = &drv->driver; if (serio_connect_driver(serio, drv)) { serio->dev.driver = NULL; return -ENODEV; } error = device_bind_driver(&serio->dev); if (error) { dev_warn(&serio->dev, "device_bind_driver() failed for %s (%s) and %s, error: %d\n", serio->phys, serio->name, drv->description, error); serio_disconnect_driver(serio); serio->dev.driver = NULL; return error; } } return 0; } static void serio_find_driver(struct serio *serio) { int error; error = device_attach(&serio->dev); if (error < 0 && error != -EPROBE_DEFER) dev_warn(&serio->dev, "device_attach() failed for %s (%s), error: %d\n", serio->phys, serio->name, error); } /* * Serio event processing. */ enum serio_event_type { SERIO_RESCAN_PORT, SERIO_RECONNECT_PORT, SERIO_RECONNECT_SUBTREE, SERIO_REGISTER_PORT, SERIO_ATTACH_DRIVER, }; struct serio_event { enum serio_event_type type; void *object; struct module *owner; struct list_head node; }; static DEFINE_SPINLOCK(serio_event_lock); /* protects serio_event_list */ static LIST_HEAD(serio_event_list); static struct serio_event *serio_get_event(void) { struct serio_event *event = NULL; unsigned long flags; spin_lock_irqsave(&serio_event_lock, flags); if (!list_empty(&serio_event_list)) { event = list_first_entry(&serio_event_list, struct serio_event, node); list_del_init(&event->node); } spin_unlock_irqrestore(&serio_event_lock, flags); return event; } static void serio_free_event(struct serio_event *event) { module_put(event->owner); kfree(event); } static void serio_remove_duplicate_events(void *object, enum serio_event_type type) { struct serio_event *e, *next; unsigned long flags; spin_lock_irqsave(&serio_event_lock, flags); list_for_each_entry_safe(e, next, &serio_event_list, node) { if (object == e->object) { /* * If this event is of different type we should not * look further - we only suppress duplicate events * that were sent back-to-back. */ if (type != e->type) break; list_del_init(&e->node); serio_free_event(e); } } spin_unlock_irqrestore(&serio_event_lock, flags); } static void serio_handle_event(struct work_struct *work) { struct serio_event *event; mutex_lock(&serio_mutex); while ((event = serio_get_event())) { switch (event->type) { case SERIO_REGISTER_PORT: serio_add_port(event->object); break; case SERIO_RECONNECT_PORT: serio_reconnect_port(event->object); break; case SERIO_RESCAN_PORT: serio_disconnect_port(event->object); serio_find_driver(event->object); break; case SERIO_RECONNECT_SUBTREE: serio_reconnect_subtree(event->object); break; case SERIO_ATTACH_DRIVER: serio_attach_driver(event->object); break; } serio_remove_duplicate_events(event->object, event->type); serio_free_event(event); } mutex_unlock(&serio_mutex); } static DECLARE_WORK(serio_event_work, serio_handle_event); static int serio_queue_event(void *object, struct module *owner, enum serio_event_type event_type) { unsigned long flags; struct serio_event *event; int retval = 0; spin_lock_irqsave(&serio_event_lock, flags); /* * Scan event list for the other events for the same serio port, * starting with the most recent one. If event is the same we * do not need add new one. If event is of different type we * need to add this event and should not look further because * we need to preseve sequence of distinct events. */ list_for_each_entry_reverse(event, &serio_event_list, node) { if (event->object == object) { if (event->type == event_type) goto out; break; } } event = kmalloc(sizeof(struct serio_event), GFP_ATOMIC); if (!event) { pr_err("Not enough memory to queue event %d\n", event_type); retval = -ENOMEM; goto out; } if (!try_module_get(owner)) { pr_warn("Can't get module reference, dropping event %d\n", event_type); kfree(event); retval = -EINVAL; goto out; } event->type = event_type; event->object = object; event->owner = owner; list_add_tail(&event->node, &serio_event_list); queue_work(system_long_wq, &serio_event_work); out: spin_unlock_irqrestore(&serio_event_lock, flags); return retval; } /* * Remove all events that have been submitted for a given * object, be it serio port or driver. */ static void serio_remove_pending_events(void *object) { struct serio_event *event, *next; unsigned long flags; spin_lock_irqsave(&serio_event_lock, flags); list_for_each_entry_safe(event, next, &serio_event_list, node) { if (event->object == object) { list_del_init(&event->node); serio_free_event(event); } } spin_unlock_irqrestore(&serio_event_lock, flags); } /* * Locate child serio port (if any) that has not been fully registered yet. * * Children are registered by driver's connect() handler so there can't be a * grandchild pending registration together with a child. */ static struct serio *serio_get_pending_child(struct serio *parent) { struct serio_event *event; struct serio *serio, *child = NULL; unsigned long flags; spin_lock_irqsave(&serio_event_lock, flags); list_for_each_entry(event, &serio_event_list, node) { if (event->type == SERIO_REGISTER_PORT) { serio = event->object; if (serio->parent == parent) { child = serio; break; } } } spin_unlock_irqrestore(&serio_event_lock, flags); return child; } /* * Serio port operations */ static ssize_t serio_show_description(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%s\n", serio->name); } static ssize_t modalias_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "serio:ty%02Xpr%02Xid%02Xex%02X\n", serio->id.type, serio->id.proto, serio->id.id, serio->id.extra); } static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%02x\n", serio->id.type); } static ssize_t proto_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%02x\n", serio->id.proto); } static ssize_t id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%02x\n", serio->id.id); } static ssize_t extra_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%02x\n", serio->id.extra); } static ssize_t drvctl_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct serio *serio = to_serio_port(dev); struct device_driver *drv; int error; error = mutex_lock_interruptible(&serio_mutex); if (error) return error; if (!strncmp(buf, "none", count)) { serio_disconnect_port(serio); } else if (!strncmp(buf, "reconnect", count)) { serio_reconnect_subtree(serio); } else if (!strncmp(buf, "rescan", count)) { serio_disconnect_port(serio); serio_find_driver(serio); serio_remove_duplicate_events(serio, SERIO_RESCAN_PORT); } else if ((drv = driver_find(buf, &serio_bus)) != NULL) { serio_disconnect_port(serio); error = serio_bind_driver(serio, to_serio_driver(drv)); serio_remove_duplicate_events(serio, SERIO_RESCAN_PORT); } else { error = -EINVAL; } mutex_unlock(&serio_mutex); return error ? error : count; } static ssize_t serio_show_bind_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%s\n", serio->manual_bind ? "manual" : "auto"); } static ssize_t serio_set_bind_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct serio *serio = to_serio_port(dev); int retval; retval = count; if (!strncmp(buf, "manual", count)) { serio->manual_bind = true; } else if (!strncmp(buf, "auto", count)) { serio->manual_bind = false; } else { retval = -EINVAL; } return retval; } static ssize_t firmware_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct serio *serio = to_serio_port(dev); return sprintf(buf, "%s\n", serio->firmware_id); } static DEVICE_ATTR_RO(type); static DEVICE_ATTR_RO(proto); static DEVICE_ATTR_RO(id); static DEVICE_ATTR_RO(extra); static struct attribute *serio_device_id_attrs[] = { &dev_attr_type.attr, &dev_attr_proto.attr, &dev_attr_id.attr, &dev_attr_extra.attr, NULL }; static const struct attribute_group serio_id_attr_group = { .name = "id", .attrs = serio_device_id_attrs, }; static DEVICE_ATTR_RO(modalias); static DEVICE_ATTR_WO(drvctl); static DEVICE_ATTR(description, S_IRUGO, serio_show_description, NULL); static DEVICE_ATTR(bind_mode, S_IWUSR | S_IRUGO, serio_show_bind_mode, serio_set_bind_mode); static DEVICE_ATTR_RO(firmware_id); static struct attribute *serio_device_attrs[] = { &dev_attr_modalias.attr, &dev_attr_description.attr, &dev_attr_drvctl.attr, &dev_attr_bind_mode.attr, &dev_attr_firmware_id.attr, NULL }; static const struct attribute_group serio_device_attr_group = { .attrs = serio_device_attrs, }; static const struct attribute_group *serio_device_attr_groups[] = { &serio_id_attr_group, &serio_device_attr_group, NULL }; static void serio_release_port(struct device *dev) { struct serio *serio = to_serio_port(dev); kfree(serio); module_put(THIS_MODULE); } /* * Prepare serio port for registration. */ static void serio_init_port(struct serio *serio) { static atomic_t serio_no = ATOMIC_INIT(-1); __module_get(THIS_MODULE); INIT_LIST_HEAD(&serio->node); INIT_LIST_HEAD(&serio->child_node); INIT_LIST_HEAD(&serio->children); spin_lock_init(&serio->lock); mutex_init(&serio->drv_mutex); device_initialize(&serio->dev); dev_set_name(&serio->dev, "serio%lu", (unsigned long)atomic_inc_return(&serio_no)); serio->dev.bus = &serio_bus; serio->dev.release = serio_release_port; serio->dev.groups = serio_device_attr_groups; if (serio->parent) { serio->dev.parent = &serio->parent->dev; serio->depth = serio->parent->depth + 1; } else serio->depth = 0; lockdep_set_subclass(&serio->lock, serio->depth); } /* * Complete serio port registration. * Driver core will attempt to find appropriate driver for the port. */ static void serio_add_port(struct serio *serio) { struct serio *parent = serio->parent; int error; if (parent) { serio_pause_rx(parent); list_add_tail(&serio->child_node, &parent->children); serio_continue_rx(parent); } list_add_tail(&serio->node, &serio_list); if (serio->start) serio->start(serio); error = device_add(&serio->dev); if (error) dev_err(&serio->dev, "device_add() failed for %s (%s), error: %d\n", serio->phys, serio->name, error); } /* * serio_destroy_port() completes unregistration process and removes * port from the system */ static void serio_destroy_port(struct serio *serio) { struct serio *child; while ((child = serio_get_pending_child(serio)) != NULL) { serio_remove_pending_events(child); put_device(&child->dev); } if (serio->stop) serio->stop(serio); if (serio->parent) { serio_pause_rx(serio->parent); list_del_init(&serio->child_node); serio_continue_rx(serio->parent); serio->parent = NULL; } if (device_is_registered(&serio->dev)) device_del(&serio->dev); list_del_init(&serio->node); serio_remove_pending_events(serio); put_device(&serio->dev); } /* * Reconnect serio port (re-initialize attached device). * If reconnect fails (old device is no longer attached or * there was no device to begin with) we do full rescan in * hope of finding a driver for the port. */ static int serio_reconnect_port(struct serio *serio) { int error = serio_reconnect_driver(serio); if (error) { serio_disconnect_port(serio); serio_find_driver(serio); } return error; } /* * Reconnect serio port and all its children (re-initialize attached * devices). */ static void serio_reconnect_subtree(struct serio *root) { struct serio *s = root; int error; do { error = serio_reconnect_port(s); if (!error) { /* * Reconnect was successful, move on to do the * first child. */ if (!list_empty(&s->children)) { s = list_first_entry(&s->children, struct serio, child_node); continue; } } /* * Either it was a leaf node or reconnect failed and it * became a leaf node. Continue reconnecting starting with * the next sibling of the parent node. */ while (s != root) { struct serio *parent = s->parent; if (!list_is_last(&s->child_node, &parent->children)) { s = list_entry(s->child_node.next, struct serio, child_node); break; } s = parent; } } while (s != root); } /* * serio_disconnect_port() unbinds a port from its driver. As a side effect * all children ports are unbound and destroyed. */ static void serio_disconnect_port(struct serio *serio) { struct serio *s = serio; /* * Children ports should be disconnected and destroyed * first; we travel the tree in depth-first order. */ while (!list_empty(&serio->children)) { /* Locate a leaf */ while (!list_empty(&s->children)) s = list_first_entry(&s->children, struct serio, child_node); /* * Prune this leaf node unless it is the one we * started with. */ if (s != serio) { struct serio *parent = s->parent; device_release_driver(&s->dev); serio_destroy_port(s); s = parent; } } /* * OK, no children left, now disconnect this port. */ device_release_driver(&serio->dev); } void serio_rescan(struct serio *serio) { serio_queue_event(serio, NULL, SERIO_RESCAN_PORT); } EXPORT_SYMBOL(serio_rescan); void serio_reconnect(struct serio *serio) { serio_queue_event(serio, NULL, SERIO_RECONNECT_SUBTREE); } EXPORT_SYMBOL(serio_reconnect); /* * Submits register request to kseriod for subsequent execution. * Note that port registration is always asynchronous. */ void __serio_register_port(struct serio *serio, struct module *owner) { serio_init_port(serio); serio_queue_event(serio, owner, SERIO_REGISTER_PORT); } EXPORT_SYMBOL(__serio_register_port); /* * Synchronously unregisters serio port. */ void serio_unregister_port(struct serio *serio) { mutex_lock(&serio_mutex); serio_disconnect_port(serio); serio_destroy_port(serio); mutex_unlock(&serio_mutex); } EXPORT_SYMBOL(serio_unregister_port); /* * Safely unregisters children ports if they are present. */ void serio_unregister_child_port(struct serio *serio) { struct serio *s, *next; mutex_lock(&serio_mutex); list_for_each_entry_safe(s, next, &serio->children, child_node) { serio_disconnect_port(s); serio_destroy_port(s); } mutex_unlock(&serio_mutex); } EXPORT_SYMBOL(serio_unregister_child_port); /* * Serio driver operations */ static ssize_t description_show(struct device_driver *drv, char *buf) { struct serio_driver *driver = to_serio_driver(drv); return sprintf(buf, "%s\n", driver->description ? driver->description : "(none)"); } static DRIVER_ATTR_RO(description); static ssize_t bind_mode_show(struct device_driver *drv, char *buf) { struct serio_driver *serio_drv = to_serio_driver(drv); return sprintf(buf, "%s\n", serio_drv->manual_bind ? "manual" : "auto"); } static ssize_t bind_mode_store(struct device_driver *drv, const char *buf, size_t count) { struct serio_driver *serio_drv = to_serio_driver(drv); int retval; retval = count; if (!strncmp(buf, "manual", count)) { serio_drv->manual_bind = true; } else if (!strncmp(buf, "auto", count)) { serio_drv->manual_bind = false; } else { retval = -EINVAL; } return retval; } static DRIVER_ATTR_RW(bind_mode); static struct attribute *serio_driver_attrs[] = { &driver_attr_description.attr, &driver_attr_bind_mode.attr, NULL, }; ATTRIBUTE_GROUPS(serio_driver); static int serio_driver_probe(struct device *dev) { struct serio *serio = to_serio_port(dev); struct serio_driver *drv = to_serio_driver(dev->driver); return serio_connect_driver(serio, drv); } static void serio_driver_remove(struct device *dev) { struct serio *serio = to_serio_port(dev); serio_disconnect_driver(serio); } static void serio_cleanup(struct serio *serio) { mutex_lock(&serio->drv_mutex); if (serio->drv && serio->drv->cleanup) serio->drv->cleanup(serio); mutex_unlock(&serio->drv_mutex); } static void serio_shutdown(struct device *dev) { struct serio *serio = to_serio_port(dev); serio_cleanup(serio); } static void serio_attach_driver(struct serio_driver *drv) { int error; error = driver_attach(&drv->driver); if (error) pr_warn("driver_attach() failed for %s with error %d\n", drv->driver.name, error); } int __serio_register_driver(struct serio_driver *drv, struct module *owner, const char *mod_name) { bool manual_bind = drv->manual_bind; int error; drv->driver.bus = &serio_bus; drv->driver.owner = owner; drv->driver.mod_name = mod_name; /* * Temporarily disable automatic binding because probing * takes long time and we are better off doing it in kseriod */ drv->manual_bind = true; error = driver_register(&drv->driver); if (error) { pr_err("driver_register() failed for %s, error: %d\n", drv->driver.name, error); return error; } /* * Restore original bind mode and let kseriod bind the * driver to free ports */ if (!manual_bind) { drv->manual_bind = false; error = serio_queue_event(drv, NULL, SERIO_ATTACH_DRIVER); if (error) { driver_unregister(&drv->driver); return error; } } return 0; } EXPORT_SYMBOL(__serio_register_driver); void serio_unregister_driver(struct serio_driver *drv) { struct serio *serio; mutex_lock(&serio_mutex); drv->manual_bind = true; /* so serio_find_driver ignores it */ serio_remove_pending_events(drv); start_over: list_for_each_entry(serio, &serio_list, node) { if (serio->drv == drv) { serio_disconnect_port(serio); serio_find_driver(serio); /* we could've deleted some ports, restart */ goto start_over; } } driver_unregister(&drv->driver); mutex_unlock(&serio_mutex); } EXPORT_SYMBOL(serio_unregister_driver); static void serio_set_drv(struct serio *serio, struct serio_driver *drv) { serio_pause_rx(serio); serio->drv = drv; serio_continue_rx(serio); } static int serio_bus_match(struct device *dev, struct device_driver *drv) { struct serio *serio = to_serio_port(dev); struct serio_driver *serio_drv = to_serio_driver(drv); if (serio->manual_bind || serio_drv->manual_bind) return 0; return serio_match_port(serio_drv->id_table, serio); } #define SERIO_ADD_UEVENT_VAR(fmt, val...) \ do { \ int err = add_uevent_var(env, fmt, val); \ if (err) \ return err; \ } while (0) static int serio_uevent(const struct device *dev, struct kobj_uevent_env *env) { const struct serio *serio; if (!dev) return -ENODEV; serio = to_serio_port(dev); SERIO_ADD_UEVENT_VAR("SERIO_TYPE=%02x", serio->id.type); SERIO_ADD_UEVENT_VAR("SERIO_PROTO=%02x", serio->id.proto); SERIO_ADD_UEVENT_VAR("SERIO_ID=%02x", serio->id.id); SERIO_ADD_UEVENT_VAR("SERIO_EXTRA=%02x", serio->id.extra); SERIO_ADD_UEVENT_VAR("MODALIAS=serio:ty%02Xpr%02Xid%02Xex%02X", serio->id.type, serio->id.proto, serio->id.id, serio->id.extra); if (serio->firmware_id[0]) SERIO_ADD_UEVENT_VAR("SERIO_FIRMWARE_ID=%s", serio->firmware_id); return 0; } #undef SERIO_ADD_UEVENT_VAR #ifdef CONFIG_PM static int serio_suspend(struct device *dev) { struct serio *serio = to_serio_port(dev); serio_cleanup(serio); return 0; } static int serio_resume(struct device *dev) { struct serio *serio = to_serio_port(dev); int error = -ENOENT; mutex_lock(&serio->drv_mutex); if (serio->drv && serio->drv->fast_reconnect) { error = serio->drv->fast_reconnect(serio); if (error && error != -ENOENT) dev_warn(dev, "fast reconnect failed with error %d\n", error); } mutex_unlock(&serio->drv_mutex); if (error) { /* * Driver reconnect can take a while, so better let * kseriod deal with it. */ serio_queue_event(serio, NULL, SERIO_RECONNECT_PORT); } return 0; } static const struct dev_pm_ops serio_pm_ops = { .suspend = serio_suspend, .resume = serio_resume, .poweroff = serio_suspend, .restore = serio_resume, }; #endif /* CONFIG_PM */ /* called from serio_driver->connect/disconnect methods under serio_mutex */ int serio_open(struct serio *serio, struct serio_driver *drv) { serio_set_drv(serio, drv); if (serio->open && serio->open(serio)) { serio_set_drv(serio, NULL); return -1; } return 0; } EXPORT_SYMBOL(serio_open); /* called from serio_driver->connect/disconnect methods under serio_mutex */ void serio_close(struct serio *serio) { if (serio->close) serio->close(serio); serio_set_drv(serio, NULL); } EXPORT_SYMBOL(serio_close); irqreturn_t serio_interrupt(struct serio *serio, unsigned char data, unsigned int dfl) { unsigned long flags; irqreturn_t ret = IRQ_NONE; spin_lock_irqsave(&serio->lock, flags); if (likely(serio->drv)) { ret = serio->drv->interrupt(serio, data, dfl); } else if (!dfl && device_is_registered(&serio->dev)) { serio_rescan(serio); ret = IRQ_HANDLED; } spin_unlock_irqrestore(&serio->lock, flags); return ret; } EXPORT_SYMBOL(serio_interrupt); struct bus_type serio_bus = { .name = "serio", .drv_groups = serio_driver_groups, .match = serio_bus_match, .uevent = serio_uevent, .probe = serio_driver_probe, .remove = serio_driver_remove, .shutdown = serio_shutdown, #ifdef CONFIG_PM .pm = &serio_pm_ops, #endif }; EXPORT_SYMBOL(serio_bus); static int __init serio_init(void) { int error; error = bus_register(&serio_bus); if (error) { pr_err("Failed to register serio bus, error: %d\n", error); return error; } return 0; } static void __exit serio_exit(void) { bus_unregister(&serio_bus); /* * There should not be any outstanding events but work may * still be scheduled so simply cancel it. */ cancel_work_sync(&serio_event_work); } subsys_initcall(serio_init); module_exit(serio_exit);
linux-master
drivers/input/serio/serio.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * linux/drivers/input/serio/ambakmi.c * * Copyright (C) 2000-2003 Deep Blue Solutions Ltd. * Copyright (C) 2002 Russell King. */ #include <linux/module.h> #include <linux/serio.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/amba/bus.h> #include <linux/amba/kmi.h> #include <linux/clk.h> #include <asm/io.h> #include <asm/irq.h> #define KMI_BASE (kmi->base) struct amba_kmi_port { struct serio *io; struct clk *clk; void __iomem *base; unsigned int irq; unsigned int divisor; unsigned int open; }; static irqreturn_t amba_kmi_int(int irq, void *dev_id) { struct amba_kmi_port *kmi = dev_id; unsigned int status = readb(KMIIR); int handled = IRQ_NONE; while (status & KMIIR_RXINTR) { serio_interrupt(kmi->io, readb(KMIDATA), 0); status = readb(KMIIR); handled = IRQ_HANDLED; } return handled; } static int amba_kmi_write(struct serio *io, unsigned char val) { struct amba_kmi_port *kmi = io->port_data; unsigned int timeleft = 10000; /* timeout in 100ms */ while ((readb(KMISTAT) & KMISTAT_TXEMPTY) == 0 && --timeleft) udelay(10); if (timeleft) writeb(val, KMIDATA); return timeleft ? 0 : SERIO_TIMEOUT; } static int amba_kmi_open(struct serio *io) { struct amba_kmi_port *kmi = io->port_data; unsigned int divisor; int ret; ret = clk_prepare_enable(kmi->clk); if (ret) goto out; divisor = clk_get_rate(kmi->clk) / 8000000 - 1; writeb(divisor, KMICLKDIV); writeb(KMICR_EN, KMICR); ret = request_irq(kmi->irq, amba_kmi_int, IRQF_SHARED, "kmi-pl050", kmi); if (ret) { printk(KERN_ERR "kmi: failed to claim IRQ%d\n", kmi->irq); writeb(0, KMICR); goto clk_disable; } writeb(KMICR_EN | KMICR_RXINTREN, KMICR); return 0; clk_disable: clk_disable_unprepare(kmi->clk); out: return ret; } static void amba_kmi_close(struct serio *io) { struct amba_kmi_port *kmi = io->port_data; writeb(0, KMICR); free_irq(kmi->irq, kmi); clk_disable_unprepare(kmi->clk); } static int amba_kmi_probe(struct amba_device *dev, const struct amba_id *id) { struct amba_kmi_port *kmi; struct serio *io; int ret; ret = amba_request_regions(dev, NULL); if (ret) return ret; kmi = kzalloc(sizeof(struct amba_kmi_port), GFP_KERNEL); io = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!kmi || !io) { ret = -ENOMEM; goto out; } io->id.type = SERIO_8042; io->write = amba_kmi_write; io->open = amba_kmi_open; io->close = amba_kmi_close; strscpy(io->name, dev_name(&dev->dev), sizeof(io->name)); strscpy(io->phys, dev_name(&dev->dev), sizeof(io->phys)); io->port_data = kmi; io->dev.parent = &dev->dev; kmi->io = io; kmi->base = ioremap(dev->res.start, resource_size(&dev->res)); if (!kmi->base) { ret = -ENOMEM; goto out; } kmi->clk = clk_get(&dev->dev, "KMIREFCLK"); if (IS_ERR(kmi->clk)) { ret = PTR_ERR(kmi->clk); goto unmap; } kmi->irq = dev->irq[0]; amba_set_drvdata(dev, kmi); serio_register_port(kmi->io); return 0; unmap: iounmap(kmi->base); out: kfree(kmi); kfree(io); amba_release_regions(dev); return ret; } static void amba_kmi_remove(struct amba_device *dev) { struct amba_kmi_port *kmi = amba_get_drvdata(dev); serio_unregister_port(kmi->io); clk_put(kmi->clk); iounmap(kmi->base); kfree(kmi); amba_release_regions(dev); } static int amba_kmi_resume(struct device *dev) { struct amba_kmi_port *kmi = dev_get_drvdata(dev); /* kick the serio layer to rescan this port */ serio_reconnect(kmi->io); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(amba_kmi_dev_pm_ops, NULL, amba_kmi_resume); static const struct amba_id amba_kmi_idtable[] = { { .id = 0x00041050, .mask = 0x000fffff, }, { 0, 0 } }; MODULE_DEVICE_TABLE(amba, amba_kmi_idtable); static struct amba_driver ambakmi_driver = { .drv = { .name = "kmi-pl050", .owner = THIS_MODULE, .pm = pm_sleep_ptr(&amba_kmi_dev_pm_ops), }, .id_table = amba_kmi_idtable, .probe = amba_kmi_probe, .remove = amba_kmi_remove, }; module_amba_driver(ambakmi_driver); MODULE_AUTHOR("Russell King <[email protected]>"); MODULE_DESCRIPTION("AMBA KMI controller driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/serio/ambakmi.c
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/input/serio/pcips2.c * * Copyright (C) 2003 Russell King, All Rights Reserved. * * I'm not sure if this is a generic PS/2 PCI interface or specific to * the Mobility Electronics docking station. */ #include <linux/module.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/input.h> #include <linux/pci.h> #include <linux/slab.h> #include <linux/serio.h> #include <linux/delay.h> #include <asm/io.h> #define PS2_CTRL (0) #define PS2_STATUS (1) #define PS2_DATA (2) #define PS2_CTRL_CLK (1<<0) #define PS2_CTRL_DAT (1<<1) #define PS2_CTRL_TXIRQ (1<<2) #define PS2_CTRL_ENABLE (1<<3) #define PS2_CTRL_RXIRQ (1<<4) #define PS2_STAT_CLK (1<<0) #define PS2_STAT_DAT (1<<1) #define PS2_STAT_PARITY (1<<2) #define PS2_STAT_RXFULL (1<<5) #define PS2_STAT_TXBUSY (1<<6) #define PS2_STAT_TXEMPTY (1<<7) struct pcips2_data { struct serio *io; unsigned int base; struct pci_dev *dev; }; static int pcips2_write(struct serio *io, unsigned char val) { struct pcips2_data *ps2if = io->port_data; unsigned int stat; do { stat = inb(ps2if->base + PS2_STATUS); cpu_relax(); } while (!(stat & PS2_STAT_TXEMPTY)); outb(val, ps2if->base + PS2_DATA); return 0; } static irqreturn_t pcips2_interrupt(int irq, void *devid) { struct pcips2_data *ps2if = devid; unsigned char status, scancode; int handled = 0; do { unsigned int flag; status = inb(ps2if->base + PS2_STATUS); if (!(status & PS2_STAT_RXFULL)) break; handled = 1; scancode = inb(ps2if->base + PS2_DATA); if (status == 0xff && scancode == 0xff) break; flag = (status & PS2_STAT_PARITY) ? 0 : SERIO_PARITY; if (hweight8(scancode) & 1) flag ^= SERIO_PARITY; serio_interrupt(ps2if->io, scancode, flag); } while (1); return IRQ_RETVAL(handled); } static void pcips2_flush_input(struct pcips2_data *ps2if) { unsigned char status, scancode; do { status = inb(ps2if->base + PS2_STATUS); if (!(status & PS2_STAT_RXFULL)) break; scancode = inb(ps2if->base + PS2_DATA); if (status == 0xff && scancode == 0xff) break; } while (1); } static int pcips2_open(struct serio *io) { struct pcips2_data *ps2if = io->port_data; int ret, val = 0; outb(PS2_CTRL_ENABLE, ps2if->base); pcips2_flush_input(ps2if); ret = request_irq(ps2if->dev->irq, pcips2_interrupt, IRQF_SHARED, "pcips2", ps2if); if (ret == 0) val = PS2_CTRL_ENABLE | PS2_CTRL_RXIRQ; outb(val, ps2if->base); return ret; } static void pcips2_close(struct serio *io) { struct pcips2_data *ps2if = io->port_data; outb(0, ps2if->base); free_irq(ps2if->dev->irq, ps2if); } static int pcips2_probe(struct pci_dev *dev, const struct pci_device_id *id) { struct pcips2_data *ps2if; struct serio *serio; int ret; ret = pci_enable_device(dev); if (ret) goto out; ret = pci_request_regions(dev, "pcips2"); if (ret) goto disable; ps2if = kzalloc(sizeof(struct pcips2_data), GFP_KERNEL); serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!ps2if || !serio) { ret = -ENOMEM; goto release; } serio->id.type = SERIO_8042; serio->write = pcips2_write; serio->open = pcips2_open; serio->close = pcips2_close; strscpy(serio->name, pci_name(dev), sizeof(serio->name)); strscpy(serio->phys, dev_name(&dev->dev), sizeof(serio->phys)); serio->port_data = ps2if; serio->dev.parent = &dev->dev; ps2if->io = serio; ps2if->dev = dev; ps2if->base = pci_resource_start(dev, 0); pci_set_drvdata(dev, ps2if); serio_register_port(ps2if->io); return 0; release: kfree(ps2if); kfree(serio); pci_release_regions(dev); disable: pci_disable_device(dev); out: return ret; } static void pcips2_remove(struct pci_dev *dev) { struct pcips2_data *ps2if = pci_get_drvdata(dev); serio_unregister_port(ps2if->io); kfree(ps2if); pci_release_regions(dev); pci_disable_device(dev); } static const struct pci_device_id pcips2_ids[] = { { .vendor = 0x14f2, /* MOBILITY */ .device = 0x0123, /* Keyboard */ .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, .class = PCI_CLASS_INPUT_KEYBOARD << 8, .class_mask = 0xffff00, }, { .vendor = 0x14f2, /* MOBILITY */ .device = 0x0124, /* Mouse */ .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, .class = PCI_CLASS_INPUT_MOUSE << 8, .class_mask = 0xffff00, }, { 0, } }; MODULE_DEVICE_TABLE(pci, pcips2_ids); static struct pci_driver pcips2_driver = { .name = "pcips2", .id_table = pcips2_ids, .probe = pcips2_probe, .remove = pcips2_remove, }; module_pci_driver(pcips2_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Russell King <[email protected]>"); MODULE_DESCRIPTION("PCI PS/2 keyboard/mouse driver");
linux-master
drivers/input/serio/pcips2.c
/* * HIL MLC state machine and serio interface driver * * Copyright (c) 2001 Brian S. Julin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL"). * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * References: * HP-HIL Technical Reference Manual. Hewlett Packard Product No. 45918A * * * Driver theory of operation: * * Some access methods and an ISR is defined by the sub-driver * (e.g. hp_sdc_mlc.c). These methods are expected to provide a * few bits of logic in addition to raw access to the HIL MLC, * specifically, the ISR, which is entirely registered by the * sub-driver and invoked directly, must check for record * termination or packet match, at which point a semaphore must * be cleared and then the hil_mlcs_tasklet must be scheduled. * * The hil_mlcs_tasklet processes the state machine for all MLCs * each time it runs, checking each MLC's progress at the current * node in the state machine, and moving the MLC to subsequent nodes * in the state machine when appropriate. It will reschedule * itself if output is pending. (This rescheduling should be replaced * at some point with a sub-driver-specific mechanism.) * * A timer task prods the tasklet once per second to prevent * hangups when attached devices do not return expected data * and to initiate probes of the loop for new devices. */ #include <linux/hil_mlc.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/timer.h> #include <linux/list.h> MODULE_AUTHOR("Brian S. Julin <[email protected]>"); MODULE_DESCRIPTION("HIL MLC serio"); MODULE_LICENSE("Dual BSD/GPL"); EXPORT_SYMBOL(hil_mlc_register); EXPORT_SYMBOL(hil_mlc_unregister); #define PREFIX "HIL MLC: " static LIST_HEAD(hil_mlcs); static DEFINE_RWLOCK(hil_mlcs_lock); static struct timer_list hil_mlcs_kicker; static int hil_mlcs_probe, hil_mlc_stop; static void hil_mlcs_process(unsigned long unused); static DECLARE_TASKLET_DISABLED_OLD(hil_mlcs_tasklet, hil_mlcs_process); /* #define HIL_MLC_DEBUG */ /********************** Device info/instance management **********************/ static void hil_mlc_clear_di_map(hil_mlc *mlc, int val) { int j; for (j = val; j < 7 ; j++) mlc->di_map[j] = -1; } static void hil_mlc_clear_di_scratch(hil_mlc *mlc) { memset(&mlc->di_scratch, 0, sizeof(mlc->di_scratch)); } static void hil_mlc_copy_di_scratch(hil_mlc *mlc, int idx) { memcpy(&mlc->di[idx], &mlc->di_scratch, sizeof(mlc->di_scratch)); } static int hil_mlc_match_di_scratch(hil_mlc *mlc) { int idx; for (idx = 0; idx < HIL_MLC_DEVMEM; idx++) { int j, found = 0; /* In-use slots are not eligible. */ for (j = 0; j < 7 ; j++) if (mlc->di_map[j] == idx) found++; if (found) continue; if (!memcmp(mlc->di + idx, &mlc->di_scratch, sizeof(mlc->di_scratch))) break; } return idx >= HIL_MLC_DEVMEM ? -1 : idx; } static int hil_mlc_find_free_di(hil_mlc *mlc) { int idx; /* TODO: Pick all-zero slots first, failing that, * randomize the slot picked among those eligible. */ for (idx = 0; idx < HIL_MLC_DEVMEM; idx++) { int j, found = 0; for (j = 0; j < 7 ; j++) if (mlc->di_map[j] == idx) found++; if (!found) break; } return idx; /* Note: It is guaranteed at least one above will match */ } static inline void hil_mlc_clean_serio_map(hil_mlc *mlc) { int idx; for (idx = 0; idx < HIL_MLC_DEVMEM; idx++) { int j, found = 0; for (j = 0; j < 7 ; j++) if (mlc->di_map[j] == idx) found++; if (!found) mlc->serio_map[idx].di_revmap = -1; } } static void hil_mlc_send_polls(hil_mlc *mlc) { int did, i, cnt; struct serio *serio; struct serio_driver *drv; i = cnt = 0; did = (mlc->ipacket[0] & HIL_PKT_ADDR_MASK) >> 8; serio = did ? mlc->serio[mlc->di_map[did - 1]] : NULL; drv = (serio != NULL) ? serio->drv : NULL; while (mlc->icount < 15 - i) { hil_packet p; p = mlc->ipacket[i]; if (did != (p & HIL_PKT_ADDR_MASK) >> 8) { if (drv && drv->interrupt) { drv->interrupt(serio, 0, 0); drv->interrupt(serio, HIL_ERR_INT >> 16, 0); drv->interrupt(serio, HIL_PKT_CMD >> 8, 0); drv->interrupt(serio, HIL_CMD_POL + cnt, 0); } did = (p & HIL_PKT_ADDR_MASK) >> 8; serio = did ? mlc->serio[mlc->di_map[did-1]] : NULL; drv = (serio != NULL) ? serio->drv : NULL; cnt = 0; } cnt++; i++; if (drv && drv->interrupt) { drv->interrupt(serio, (p >> 24), 0); drv->interrupt(serio, (p >> 16) & 0xff, 0); drv->interrupt(serio, (p >> 8) & ~HIL_PKT_ADDR_MASK, 0); drv->interrupt(serio, p & 0xff, 0); } } } /*************************** State engine *********************************/ #define HILSEN_SCHED 0x000100 /* Schedule the tasklet */ #define HILSEN_BREAK 0x000200 /* Wait until next pass */ #define HILSEN_UP 0x000400 /* relative node#, decrement */ #define HILSEN_DOWN 0x000800 /* relative node#, increment */ #define HILSEN_FOLLOW 0x001000 /* use retval as next node# */ #define HILSEN_MASK 0x0000ff #define HILSEN_START 0 #define HILSEN_RESTART 1 #define HILSEN_DHR 9 #define HILSEN_DHR2 10 #define HILSEN_IFC 14 #define HILSEN_HEAL0 16 #define HILSEN_HEAL 18 #define HILSEN_ACF 21 #define HILSEN_ACF2 22 #define HILSEN_DISC0 25 #define HILSEN_DISC 27 #define HILSEN_MATCH 40 #define HILSEN_OPERATE 41 #define HILSEN_PROBE 44 #define HILSEN_DSR 52 #define HILSEN_REPOLL 55 #define HILSEN_IFCACF 58 #define HILSEN_END 60 #define HILSEN_NEXT (HILSEN_DOWN | 1) #define HILSEN_SAME (HILSEN_DOWN | 0) #define HILSEN_LAST (HILSEN_UP | 1) #define HILSEN_DOZE (HILSEN_SAME | HILSEN_SCHED | HILSEN_BREAK) #define HILSEN_SLEEP (HILSEN_SAME | HILSEN_BREAK) static int hilse_match(hil_mlc *mlc, int unused) { int rc; rc = hil_mlc_match_di_scratch(mlc); if (rc == -1) { rc = hil_mlc_find_free_di(mlc); if (rc == -1) goto err; #ifdef HIL_MLC_DEBUG printk(KERN_DEBUG PREFIX "new in slot %i\n", rc); #endif hil_mlc_copy_di_scratch(mlc, rc); mlc->di_map[mlc->ddi] = rc; mlc->serio_map[rc].di_revmap = mlc->ddi; hil_mlc_clean_serio_map(mlc); serio_rescan(mlc->serio[rc]); return -1; } mlc->di_map[mlc->ddi] = rc; #ifdef HIL_MLC_DEBUG printk(KERN_DEBUG PREFIX "same in slot %i\n", rc); #endif mlc->serio_map[rc].di_revmap = mlc->ddi; hil_mlc_clean_serio_map(mlc); return 0; err: printk(KERN_ERR PREFIX "Residual device slots exhausted, close some serios!\n"); return 1; } /* An LCV used to prevent runaway loops, forces 5 second sleep when reset. */ static int hilse_init_lcv(hil_mlc *mlc, int unused) { time64_t now = ktime_get_seconds(); if (mlc->lcv && (now - mlc->lcv_time) < 5) return -1; mlc->lcv_time = now; mlc->lcv = 0; return 0; } static int hilse_inc_lcv(hil_mlc *mlc, int lim) { return mlc->lcv++ >= lim ? -1 : 0; } #if 0 static int hilse_set_lcv(hil_mlc *mlc, int val) { mlc->lcv = val; return 0; } #endif /* Management of the discovered device index (zero based, -1 means no devs) */ static int hilse_set_ddi(hil_mlc *mlc, int val) { mlc->ddi = val; hil_mlc_clear_di_map(mlc, val + 1); return 0; } static int hilse_dec_ddi(hil_mlc *mlc, int unused) { mlc->ddi--; if (mlc->ddi <= -1) { mlc->ddi = -1; hil_mlc_clear_di_map(mlc, 0); return -1; } hil_mlc_clear_di_map(mlc, mlc->ddi + 1); return 0; } static int hilse_inc_ddi(hil_mlc *mlc, int unused) { BUG_ON(mlc->ddi >= 6); mlc->ddi++; return 0; } static int hilse_take_idd(hil_mlc *mlc, int unused) { int i; /* Help the state engine: * Is this a real IDD response or just an echo? * * Real IDD response does not start with a command. */ if (mlc->ipacket[0] & HIL_PKT_CMD) goto bail; /* Should have the command echoed further down. */ for (i = 1; i < 16; i++) { if (((mlc->ipacket[i] & HIL_PKT_ADDR_MASK) == (mlc->ipacket[0] & HIL_PKT_ADDR_MASK)) && (mlc->ipacket[i] & HIL_PKT_CMD) && ((mlc->ipacket[i] & HIL_PKT_DATA_MASK) == HIL_CMD_IDD)) break; } if (i > 15) goto bail; /* And the rest of the packets should still be clear. */ while (++i < 16) if (mlc->ipacket[i]) break; if (i < 16) goto bail; for (i = 0; i < 16; i++) mlc->di_scratch.idd[i] = mlc->ipacket[i] & HIL_PKT_DATA_MASK; /* Next step is to see if RSC supported */ if (mlc->di_scratch.idd[1] & HIL_IDD_HEADER_RSC) return HILSEN_NEXT; if (mlc->di_scratch.idd[1] & HIL_IDD_HEADER_EXD) return HILSEN_DOWN | 4; return 0; bail: mlc->ddi--; return -1; /* This should send us off to ACF */ } static int hilse_take_rsc(hil_mlc *mlc, int unused) { int i; for (i = 0; i < 16; i++) mlc->di_scratch.rsc[i] = mlc->ipacket[i] & HIL_PKT_DATA_MASK; /* Next step is to see if EXD supported (IDD has already been read) */ if (mlc->di_scratch.idd[1] & HIL_IDD_HEADER_EXD) return HILSEN_NEXT; return 0; } static int hilse_take_exd(hil_mlc *mlc, int unused) { int i; for (i = 0; i < 16; i++) mlc->di_scratch.exd[i] = mlc->ipacket[i] & HIL_PKT_DATA_MASK; /* Next step is to see if RNM supported. */ if (mlc->di_scratch.exd[0] & HIL_EXD_HEADER_RNM) return HILSEN_NEXT; return 0; } static int hilse_take_rnm(hil_mlc *mlc, int unused) { int i; for (i = 0; i < 16; i++) mlc->di_scratch.rnm[i] = mlc->ipacket[i] & HIL_PKT_DATA_MASK; printk(KERN_INFO PREFIX "Device name gotten: %16s\n", mlc->di_scratch.rnm); return 0; } static int hilse_operate(hil_mlc *mlc, int repoll) { if (mlc->opercnt == 0) hil_mlcs_probe = 0; mlc->opercnt = 1; hil_mlc_send_polls(mlc); if (!hil_mlcs_probe) return 0; hil_mlcs_probe = 0; mlc->opercnt = 0; return 1; } #define FUNC(funct, funct_arg, zero_rc, neg_rc, pos_rc) \ { HILSE_FUNC, { .func = funct }, funct_arg, zero_rc, neg_rc, pos_rc }, #define OUT(pack) \ { HILSE_OUT, { .packet = pack }, 0, HILSEN_NEXT, HILSEN_DOZE, 0 }, #define CTS \ { HILSE_CTS, { .packet = 0 }, 0, HILSEN_NEXT | HILSEN_SCHED | HILSEN_BREAK, HILSEN_DOZE, 0 }, #define EXPECT(comp, to, got, got_wrong, timed_out) \ { HILSE_EXPECT, { .packet = comp }, to, got, got_wrong, timed_out }, #define EXPECT_LAST(comp, to, got, got_wrong, timed_out) \ { HILSE_EXPECT_LAST, { .packet = comp }, to, got, got_wrong, timed_out }, #define EXPECT_DISC(comp, to, got, got_wrong, timed_out) \ { HILSE_EXPECT_DISC, { .packet = comp }, to, got, got_wrong, timed_out }, #define IN(to, got, got_error, timed_out) \ { HILSE_IN, { .packet = 0 }, to, got, got_error, timed_out }, #define OUT_DISC(pack) \ { HILSE_OUT_DISC, { .packet = pack }, 0, 0, 0, 0 }, #define OUT_LAST(pack) \ { HILSE_OUT_LAST, { .packet = pack }, 0, 0, 0, 0 }, static const struct hilse_node hil_mlc_se[HILSEN_END] = { /* 0 HILSEN_START */ FUNC(hilse_init_lcv, 0, HILSEN_NEXT, HILSEN_SLEEP, 0) /* 1 HILSEN_RESTART */ FUNC(hilse_inc_lcv, 10, HILSEN_NEXT, HILSEN_START, 0) OUT(HIL_CTRL_ONLY) /* Disable APE */ CTS #define TEST_PACKET(x) \ (HIL_PKT_CMD | (x << HIL_PKT_ADDR_SHIFT) | x << 4 | x) OUT(HIL_DO_ALTER_CTRL | HIL_CTRL_TEST | TEST_PACKET(0x5)) EXPECT(HIL_ERR_INT | TEST_PACKET(0x5), 2000, HILSEN_NEXT, HILSEN_RESTART, HILSEN_RESTART) OUT(HIL_DO_ALTER_CTRL | HIL_CTRL_TEST | TEST_PACKET(0xa)) EXPECT(HIL_ERR_INT | TEST_PACKET(0xa), 2000, HILSEN_NEXT, HILSEN_RESTART, HILSEN_RESTART) OUT(HIL_CTRL_ONLY | 0) /* Disable test mode */ /* 9 HILSEN_DHR */ FUNC(hilse_init_lcv, 0, HILSEN_NEXT, HILSEN_SLEEP, 0) /* 10 HILSEN_DHR2 */ FUNC(hilse_inc_lcv, 10, HILSEN_NEXT, HILSEN_START, 0) FUNC(hilse_set_ddi, -1, HILSEN_NEXT, 0, 0) OUT(HIL_PKT_CMD | HIL_CMD_DHR) IN(300000, HILSEN_DHR2, HILSEN_DHR2, HILSEN_NEXT) /* 14 HILSEN_IFC */ OUT(HIL_PKT_CMD | HIL_CMD_IFC) EXPECT(HIL_PKT_CMD | HIL_CMD_IFC | HIL_ERR_INT, 20000, HILSEN_DISC, HILSEN_DHR2, HILSEN_NEXT ) /* If devices are there, they weren't in PUP or other loopback mode. * We're more concerned at this point with restoring operation * to devices than discovering new ones, so we try to salvage * the loop configuration by closing off the loop. */ /* 16 HILSEN_HEAL0 */ FUNC(hilse_dec_ddi, 0, HILSEN_NEXT, HILSEN_ACF, 0) FUNC(hilse_inc_ddi, 0, HILSEN_NEXT, 0, 0) /* 18 HILSEN_HEAL */ OUT_LAST(HIL_CMD_ELB) EXPECT_LAST(HIL_CMD_ELB | HIL_ERR_INT, 20000, HILSEN_REPOLL, HILSEN_DSR, HILSEN_NEXT) FUNC(hilse_dec_ddi, 0, HILSEN_HEAL, HILSEN_NEXT, 0) /* 21 HILSEN_ACF */ FUNC(hilse_init_lcv, 0, HILSEN_NEXT, HILSEN_DOZE, 0) /* 22 HILSEN_ACF2 */ FUNC(hilse_inc_lcv, 10, HILSEN_NEXT, HILSEN_START, 0) OUT(HIL_PKT_CMD | HIL_CMD_ACF | 1) IN(20000, HILSEN_NEXT, HILSEN_DSR, HILSEN_NEXT) /* 25 HILSEN_DISC0 */ OUT_DISC(HIL_PKT_CMD | HIL_CMD_ELB) EXPECT_DISC(HIL_PKT_CMD | HIL_CMD_ELB | HIL_ERR_INT, 20000, HILSEN_NEXT, HILSEN_DSR, HILSEN_DSR) /* Only enter here if response just received */ /* 27 HILSEN_DISC */ OUT_DISC(HIL_PKT_CMD | HIL_CMD_IDD) EXPECT_DISC(HIL_PKT_CMD | HIL_CMD_IDD | HIL_ERR_INT, 20000, HILSEN_NEXT, HILSEN_DSR, HILSEN_START) FUNC(hilse_inc_ddi, 0, HILSEN_NEXT, HILSEN_START, 0) FUNC(hilse_take_idd, 0, HILSEN_MATCH, HILSEN_IFCACF, HILSEN_FOLLOW) OUT_LAST(HIL_PKT_CMD | HIL_CMD_RSC) EXPECT_LAST(HIL_PKT_CMD | HIL_CMD_RSC | HIL_ERR_INT, 30000, HILSEN_NEXT, HILSEN_DSR, HILSEN_DSR) FUNC(hilse_take_rsc, 0, HILSEN_MATCH, 0, HILSEN_FOLLOW) OUT_LAST(HIL_PKT_CMD | HIL_CMD_EXD) EXPECT_LAST(HIL_PKT_CMD | HIL_CMD_EXD | HIL_ERR_INT, 30000, HILSEN_NEXT, HILSEN_DSR, HILSEN_DSR) FUNC(hilse_take_exd, 0, HILSEN_MATCH, 0, HILSEN_FOLLOW) OUT_LAST(HIL_PKT_CMD | HIL_CMD_RNM) EXPECT_LAST(HIL_PKT_CMD | HIL_CMD_RNM | HIL_ERR_INT, 30000, HILSEN_NEXT, HILSEN_DSR, HILSEN_DSR) FUNC(hilse_take_rnm, 0, HILSEN_MATCH, 0, 0) /* 40 HILSEN_MATCH */ FUNC(hilse_match, 0, HILSEN_NEXT, HILSEN_NEXT, /* TODO */ 0) /* 41 HILSEN_OPERATE */ OUT(HIL_PKT_CMD | HIL_CMD_POL) EXPECT(HIL_PKT_CMD | HIL_CMD_POL | HIL_ERR_INT, 20000, HILSEN_NEXT, HILSEN_DSR, HILSEN_NEXT) FUNC(hilse_operate, 0, HILSEN_OPERATE, HILSEN_IFC, HILSEN_NEXT) /* 44 HILSEN_PROBE */ OUT_LAST(HIL_PKT_CMD | HIL_CMD_EPT) IN(10000, HILSEN_DISC, HILSEN_DSR, HILSEN_NEXT) OUT_DISC(HIL_PKT_CMD | HIL_CMD_ELB) IN(10000, HILSEN_DISC, HILSEN_DSR, HILSEN_NEXT) OUT(HIL_PKT_CMD | HIL_CMD_ACF | 1) IN(10000, HILSEN_DISC0, HILSEN_DSR, HILSEN_NEXT) OUT_LAST(HIL_PKT_CMD | HIL_CMD_ELB) IN(10000, HILSEN_OPERATE, HILSEN_DSR, HILSEN_DSR) /* 52 HILSEN_DSR */ FUNC(hilse_set_ddi, -1, HILSEN_NEXT, 0, 0) OUT(HIL_PKT_CMD | HIL_CMD_DSR) IN(20000, HILSEN_DHR, HILSEN_DHR, HILSEN_IFC) /* 55 HILSEN_REPOLL */ OUT(HIL_PKT_CMD | HIL_CMD_RPL) EXPECT(HIL_PKT_CMD | HIL_CMD_RPL | HIL_ERR_INT, 20000, HILSEN_NEXT, HILSEN_DSR, HILSEN_NEXT) FUNC(hilse_operate, 1, HILSEN_OPERATE, HILSEN_IFC, HILSEN_PROBE) /* 58 HILSEN_IFCACF */ OUT(HIL_PKT_CMD | HIL_CMD_IFC) EXPECT(HIL_PKT_CMD | HIL_CMD_IFC | HIL_ERR_INT, 20000, HILSEN_ACF2, HILSEN_DHR2, HILSEN_HEAL) /* 60 HILSEN_END */ }; static inline void hilse_setup_input(hil_mlc *mlc, const struct hilse_node *node) { switch (node->act) { case HILSE_EXPECT_DISC: mlc->imatch = node->object.packet; mlc->imatch |= ((mlc->ddi + 2) << HIL_PKT_ADDR_SHIFT); break; case HILSE_EXPECT_LAST: mlc->imatch = node->object.packet; mlc->imatch |= ((mlc->ddi + 1) << HIL_PKT_ADDR_SHIFT); break; case HILSE_EXPECT: mlc->imatch = node->object.packet; break; case HILSE_IN: mlc->imatch = 0; break; default: BUG(); } mlc->istarted = 1; mlc->intimeout = usecs_to_jiffies(node->arg); mlc->instart = jiffies; mlc->icount = 15; memset(mlc->ipacket, 0, 16 * sizeof(hil_packet)); BUG_ON(down_trylock(&mlc->isem)); } #ifdef HIL_MLC_DEBUG static int doze; static int seidx; /* For debug */ #endif static int hilse_donode(hil_mlc *mlc) { const struct hilse_node *node; int nextidx = 0; int sched_long = 0; unsigned long flags; #ifdef HIL_MLC_DEBUG if (mlc->seidx && mlc->seidx != seidx && mlc->seidx != 41 && mlc->seidx != 42 && mlc->seidx != 43) { printk(KERN_DEBUG PREFIX "z%i \n {%i}", doze, mlc->seidx); doze = 0; } seidx = mlc->seidx; #endif node = hil_mlc_se + mlc->seidx; switch (node->act) { int rc; hil_packet pack; case HILSE_FUNC: BUG_ON(node->object.func == NULL); rc = node->object.func(mlc, node->arg); nextidx = (rc > 0) ? node->ugly : ((rc < 0) ? node->bad : node->good); if (nextidx == HILSEN_FOLLOW) nextidx = rc; break; case HILSE_EXPECT_LAST: case HILSE_EXPECT_DISC: case HILSE_EXPECT: case HILSE_IN: /* Already set up from previous HILSE_OUT_* */ write_lock_irqsave(&mlc->lock, flags); rc = mlc->in(mlc, node->arg); if (rc == 2) { nextidx = HILSEN_DOZE; sched_long = 1; write_unlock_irqrestore(&mlc->lock, flags); break; } if (rc == 1) nextidx = node->ugly; else if (rc == 0) nextidx = node->good; else nextidx = node->bad; mlc->istarted = 0; write_unlock_irqrestore(&mlc->lock, flags); break; case HILSE_OUT_LAST: write_lock_irqsave(&mlc->lock, flags); pack = node->object.packet; pack |= ((mlc->ddi + 1) << HIL_PKT_ADDR_SHIFT); goto out; case HILSE_OUT_DISC: write_lock_irqsave(&mlc->lock, flags); pack = node->object.packet; pack |= ((mlc->ddi + 2) << HIL_PKT_ADDR_SHIFT); goto out; case HILSE_OUT: write_lock_irqsave(&mlc->lock, flags); pack = node->object.packet; out: if (!mlc->istarted) { /* Prepare to receive input */ if ((node + 1)->act & HILSE_IN) hilse_setup_input(mlc, node + 1); } write_unlock_irqrestore(&mlc->lock, flags); if (down_trylock(&mlc->osem)) { nextidx = HILSEN_DOZE; break; } up(&mlc->osem); write_lock_irqsave(&mlc->lock, flags); if (!mlc->ostarted) { mlc->ostarted = 1; mlc->opacket = pack; rc = mlc->out(mlc); nextidx = HILSEN_DOZE; write_unlock_irqrestore(&mlc->lock, flags); if (rc) { hil_mlc_stop = 1; return 1; } break; } mlc->ostarted = 0; mlc->instart = jiffies; write_unlock_irqrestore(&mlc->lock, flags); nextidx = HILSEN_NEXT; break; case HILSE_CTS: write_lock_irqsave(&mlc->lock, flags); rc = mlc->cts(mlc); nextidx = rc ? node->bad : node->good; write_unlock_irqrestore(&mlc->lock, flags); if (rc) { hil_mlc_stop = 1; return 1; } break; default: BUG(); } #ifdef HIL_MLC_DEBUG if (nextidx == HILSEN_DOZE) doze++; #endif while (nextidx & HILSEN_SCHED) { unsigned long now = jiffies; if (!sched_long) goto sched; if (time_after(now, mlc->instart + mlc->intimeout)) goto sched; mod_timer(&hil_mlcs_kicker, mlc->instart + mlc->intimeout); break; sched: tasklet_schedule(&hil_mlcs_tasklet); break; } if (nextidx & HILSEN_DOWN) mlc->seidx += nextidx & HILSEN_MASK; else if (nextidx & HILSEN_UP) mlc->seidx -= nextidx & HILSEN_MASK; else mlc->seidx = nextidx & HILSEN_MASK; if (nextidx & HILSEN_BREAK) return 1; return 0; } /******************** tasklet context functions **************************/ static void hil_mlcs_process(unsigned long unused) { struct list_head *tmp; read_lock(&hil_mlcs_lock); list_for_each(tmp, &hil_mlcs) { struct hil_mlc *mlc = list_entry(tmp, hil_mlc, list); while (hilse_donode(mlc) == 0) { #ifdef HIL_MLC_DEBUG if (mlc->seidx != 41 && mlc->seidx != 42 && mlc->seidx != 43) printk(KERN_DEBUG PREFIX " + "); #endif } } read_unlock(&hil_mlcs_lock); } /************************* Keepalive timer task *********************/ static void hil_mlcs_timer(struct timer_list *unused) { if (hil_mlc_stop) { /* could not send packet - stop immediately. */ pr_warn(PREFIX "HIL seems stuck - Disabling HIL MLC.\n"); return; } hil_mlcs_probe = 1; tasklet_schedule(&hil_mlcs_tasklet); /* Re-insert the periodic task. */ if (!timer_pending(&hil_mlcs_kicker)) mod_timer(&hil_mlcs_kicker, jiffies + HZ); } /******************** user/kernel context functions **********************/ static int hil_mlc_serio_write(struct serio *serio, unsigned char c) { struct hil_mlc_serio_map *map; struct hil_mlc *mlc; struct serio_driver *drv; uint8_t *idx, *last; map = serio->port_data; BUG_ON(map == NULL); mlc = map->mlc; BUG_ON(mlc == NULL); mlc->serio_opacket[map->didx] |= ((hil_packet)c) << (8 * (3 - mlc->serio_oidx[map->didx])); if (mlc->serio_oidx[map->didx] >= 3) { /* for now only commands */ if (!(mlc->serio_opacket[map->didx] & HIL_PKT_CMD)) return -EIO; switch (mlc->serio_opacket[map->didx] & HIL_PKT_DATA_MASK) { case HIL_CMD_IDD: idx = mlc->di[map->didx].idd; goto emu; case HIL_CMD_RSC: idx = mlc->di[map->didx].rsc; goto emu; case HIL_CMD_EXD: idx = mlc->di[map->didx].exd; goto emu; case HIL_CMD_RNM: idx = mlc->di[map->didx].rnm; goto emu; default: break; } mlc->serio_oidx[map->didx] = 0; mlc->serio_opacket[map->didx] = 0; } mlc->serio_oidx[map->didx]++; return -EIO; emu: drv = serio->drv; BUG_ON(drv == NULL); last = idx + 15; while ((last != idx) && (*last == 0)) last--; while (idx != last) { drv->interrupt(serio, 0, 0); drv->interrupt(serio, HIL_ERR_INT >> 16, 0); drv->interrupt(serio, 0, 0); drv->interrupt(serio, *idx, 0); idx++; } drv->interrupt(serio, 0, 0); drv->interrupt(serio, HIL_ERR_INT >> 16, 0); drv->interrupt(serio, HIL_PKT_CMD >> 8, 0); drv->interrupt(serio, *idx, 0); mlc->serio_oidx[map->didx] = 0; mlc->serio_opacket[map->didx] = 0; return 0; } static int hil_mlc_serio_open(struct serio *serio) { struct hil_mlc_serio_map *map; struct hil_mlc *mlc; if (serio_get_drvdata(serio) != NULL) return -EBUSY; map = serio->port_data; BUG_ON(map == NULL); mlc = map->mlc; BUG_ON(mlc == NULL); return 0; } static void hil_mlc_serio_close(struct serio *serio) { struct hil_mlc_serio_map *map; struct hil_mlc *mlc; map = serio->port_data; BUG_ON(map == NULL); mlc = map->mlc; BUG_ON(mlc == NULL); serio_set_drvdata(serio, NULL); serio->drv = NULL; /* TODO wake up interruptable */ } static const struct serio_device_id hil_mlc_serio_id = { .type = SERIO_HIL_MLC, .proto = SERIO_HIL, .extra = SERIO_ANY, .id = SERIO_ANY, }; int hil_mlc_register(hil_mlc *mlc) { int i; unsigned long flags; BUG_ON(mlc == NULL); mlc->istarted = 0; mlc->ostarted = 0; rwlock_init(&mlc->lock); sema_init(&mlc->osem, 1); sema_init(&mlc->isem, 1); mlc->icount = -1; mlc->imatch = 0; mlc->opercnt = 0; sema_init(&(mlc->csem), 0); hil_mlc_clear_di_scratch(mlc); hil_mlc_clear_di_map(mlc, 0); for (i = 0; i < HIL_MLC_DEVMEM; i++) { struct serio *mlc_serio; hil_mlc_copy_di_scratch(mlc, i); mlc_serio = kzalloc(sizeof(*mlc_serio), GFP_KERNEL); mlc->serio[i] = mlc_serio; if (!mlc->serio[i]) { for (; i >= 0; i--) kfree(mlc->serio[i]); return -ENOMEM; } snprintf(mlc_serio->name, sizeof(mlc_serio->name)-1, "HIL_SERIO%d", i); snprintf(mlc_serio->phys, sizeof(mlc_serio->phys)-1, "HIL%d", i); mlc_serio->id = hil_mlc_serio_id; mlc_serio->id.id = i; /* HIL port no. */ mlc_serio->write = hil_mlc_serio_write; mlc_serio->open = hil_mlc_serio_open; mlc_serio->close = hil_mlc_serio_close; mlc_serio->port_data = &(mlc->serio_map[i]); mlc->serio_map[i].mlc = mlc; mlc->serio_map[i].didx = i; mlc->serio_map[i].di_revmap = -1; mlc->serio_opacket[i] = 0; mlc->serio_oidx[i] = 0; serio_register_port(mlc_serio); } mlc->tasklet = &hil_mlcs_tasklet; write_lock_irqsave(&hil_mlcs_lock, flags); list_add_tail(&mlc->list, &hil_mlcs); mlc->seidx = HILSEN_START; write_unlock_irqrestore(&hil_mlcs_lock, flags); tasklet_schedule(&hil_mlcs_tasklet); return 0; } int hil_mlc_unregister(hil_mlc *mlc) { struct list_head *tmp; unsigned long flags; int i; BUG_ON(mlc == NULL); write_lock_irqsave(&hil_mlcs_lock, flags); list_for_each(tmp, &hil_mlcs) if (list_entry(tmp, hil_mlc, list) == mlc) goto found; /* not found in list */ write_unlock_irqrestore(&hil_mlcs_lock, flags); tasklet_schedule(&hil_mlcs_tasklet); return -ENODEV; found: list_del(tmp); write_unlock_irqrestore(&hil_mlcs_lock, flags); for (i = 0; i < HIL_MLC_DEVMEM; i++) { serio_unregister_port(mlc->serio[i]); mlc->serio[i] = NULL; } tasklet_schedule(&hil_mlcs_tasklet); return 0; } /**************************** Module interface *************************/ static int __init hil_mlc_init(void) { timer_setup(&hil_mlcs_kicker, &hil_mlcs_timer, 0); mod_timer(&hil_mlcs_kicker, jiffies + HZ); tasklet_enable(&hil_mlcs_tasklet); return 0; } static void __exit hil_mlc_exit(void) { del_timer_sync(&hil_mlcs_kicker); tasklet_kill(&hil_mlcs_tasklet); } module_init(hil_mlc_init); module_exit(hil_mlc_exit);
linux-master
drivers/input/serio/hil_mlc.c
// SPDX-License-Identifier: GPL-2.0-only /* * i8042 keyboard and mouse controller driver for Linux * * Copyright (c) 1999-2004 Vojtech Pavlik */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/serio.h> #include <linux/err.h> #include <linux/rcupdate.h> #include <linux/platform_device.h> #include <linux/i8042.h> #include <linux/slab.h> #include <linux/suspend.h> #include <linux/property.h> #include <asm/io.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("i8042 keyboard and mouse controller driver"); MODULE_LICENSE("GPL"); static bool i8042_nokbd; module_param_named(nokbd, i8042_nokbd, bool, 0); MODULE_PARM_DESC(nokbd, "Do not probe or use KBD port."); static bool i8042_noaux; module_param_named(noaux, i8042_noaux, bool, 0); MODULE_PARM_DESC(noaux, "Do not probe or use AUX (mouse) port."); static bool i8042_nomux; module_param_named(nomux, i8042_nomux, bool, 0); MODULE_PARM_DESC(nomux, "Do not check whether an active multiplexing controller is present."); static bool i8042_unlock; module_param_named(unlock, i8042_unlock, bool, 0); MODULE_PARM_DESC(unlock, "Ignore keyboard lock."); static bool i8042_probe_defer; module_param_named(probe_defer, i8042_probe_defer, bool, 0); MODULE_PARM_DESC(probe_defer, "Allow deferred probing."); enum i8042_controller_reset_mode { I8042_RESET_NEVER, I8042_RESET_ALWAYS, I8042_RESET_ON_S2RAM, #define I8042_RESET_DEFAULT I8042_RESET_ON_S2RAM }; static enum i8042_controller_reset_mode i8042_reset = I8042_RESET_DEFAULT; static int i8042_set_reset(const char *val, const struct kernel_param *kp) { enum i8042_controller_reset_mode *arg = kp->arg; int error; bool reset; if (val) { error = kstrtobool(val, &reset); if (error) return error; } else { reset = true; } *arg = reset ? I8042_RESET_ALWAYS : I8042_RESET_NEVER; return 0; } static const struct kernel_param_ops param_ops_reset_param = { .flags = KERNEL_PARAM_OPS_FL_NOARG, .set = i8042_set_reset, }; #define param_check_reset_param(name, p) \ __param_check(name, p, enum i8042_controller_reset_mode) module_param_named(reset, i8042_reset, reset_param, 0); MODULE_PARM_DESC(reset, "Reset controller on resume, cleanup or both"); static bool i8042_direct; module_param_named(direct, i8042_direct, bool, 0); MODULE_PARM_DESC(direct, "Put keyboard port into non-translated mode."); static bool i8042_dumbkbd; module_param_named(dumbkbd, i8042_dumbkbd, bool, 0); MODULE_PARM_DESC(dumbkbd, "Pretend that controller can only read data from keyboard"); static bool i8042_noloop; module_param_named(noloop, i8042_noloop, bool, 0); MODULE_PARM_DESC(noloop, "Disable the AUX Loopback command while probing for the AUX port"); static bool i8042_notimeout; module_param_named(notimeout, i8042_notimeout, bool, 0); MODULE_PARM_DESC(notimeout, "Ignore timeouts signalled by i8042"); static bool i8042_kbdreset; module_param_named(kbdreset, i8042_kbdreset, bool, 0); MODULE_PARM_DESC(kbdreset, "Reset device connected to KBD port"); #ifdef CONFIG_X86 static bool i8042_dritek; module_param_named(dritek, i8042_dritek, bool, 0); MODULE_PARM_DESC(dritek, "Force enable the Dritek keyboard extension"); #endif #ifdef CONFIG_PNP static bool i8042_nopnp; module_param_named(nopnp, i8042_nopnp, bool, 0); MODULE_PARM_DESC(nopnp, "Do not use PNP to detect controller settings"); #endif #define DEBUG #ifdef DEBUG static bool i8042_debug; module_param_named(debug, i8042_debug, bool, 0600); MODULE_PARM_DESC(debug, "Turn i8042 debugging mode on and off"); static bool i8042_unmask_kbd_data; module_param_named(unmask_kbd_data, i8042_unmask_kbd_data, bool, 0600); MODULE_PARM_DESC(unmask_kbd_data, "Unconditional enable (may reveal sensitive data) of normally sanitize-filtered kbd data traffic debug log [pre-condition: i8042.debug=1 enabled]"); #endif static bool i8042_present; static bool i8042_bypass_aux_irq_test; static char i8042_kbd_firmware_id[128]; static char i8042_aux_firmware_id[128]; static struct fwnode_handle *i8042_kbd_fwnode; #include "i8042.h" /* * i8042_lock protects serialization between i8042_command and * the interrupt handler. */ static DEFINE_SPINLOCK(i8042_lock); /* * Writers to AUX and KBD ports as well as users issuing i8042_command * directly should acquire i8042_mutex (by means of calling * i8042_lock_chip() and i8042_unlock_chip() helpers) to ensure that * they do not disturb each other (unfortunately in many i8042 * implementations write to one of the ports will immediately abort * command that is being processed by another port). */ static DEFINE_MUTEX(i8042_mutex); struct i8042_port { struct serio *serio; int irq; bool exists; bool driver_bound; signed char mux; }; #define I8042_KBD_PORT_NO 0 #define I8042_AUX_PORT_NO 1 #define I8042_MUX_PORT_NO 2 #define I8042_NUM_PORTS (I8042_NUM_MUX_PORTS + 2) static struct i8042_port i8042_ports[I8042_NUM_PORTS]; static unsigned char i8042_initial_ctr; static unsigned char i8042_ctr; static bool i8042_mux_present; static bool i8042_kbd_irq_registered; static bool i8042_aux_irq_registered; static unsigned char i8042_suppress_kbd_ack; static struct platform_device *i8042_platform_device; static struct notifier_block i8042_kbd_bind_notifier_block; static irqreturn_t i8042_interrupt(int irq, void *dev_id); static bool (*i8042_platform_filter)(unsigned char data, unsigned char str, struct serio *serio); void i8042_lock_chip(void) { mutex_lock(&i8042_mutex); } EXPORT_SYMBOL(i8042_lock_chip); void i8042_unlock_chip(void) { mutex_unlock(&i8042_mutex); } EXPORT_SYMBOL(i8042_unlock_chip); int i8042_install_filter(bool (*filter)(unsigned char data, unsigned char str, struct serio *serio)) { unsigned long flags; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); if (i8042_platform_filter) { ret = -EBUSY; goto out; } i8042_platform_filter = filter; out: spin_unlock_irqrestore(&i8042_lock, flags); return ret; } EXPORT_SYMBOL(i8042_install_filter); int i8042_remove_filter(bool (*filter)(unsigned char data, unsigned char str, struct serio *port)) { unsigned long flags; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); if (i8042_platform_filter != filter) { ret = -EINVAL; goto out; } i8042_platform_filter = NULL; out: spin_unlock_irqrestore(&i8042_lock, flags); return ret; } EXPORT_SYMBOL(i8042_remove_filter); /* * The i8042_wait_read() and i8042_wait_write functions wait for the i8042 to * be ready for reading values from it / writing values to it. * Called always with i8042_lock held. */ static int i8042_wait_read(void) { int i = 0; while ((~i8042_read_status() & I8042_STR_OBF) && (i < I8042_CTL_TIMEOUT)) { udelay(50); i++; } return -(i == I8042_CTL_TIMEOUT); } static int i8042_wait_write(void) { int i = 0; while ((i8042_read_status() & I8042_STR_IBF) && (i < I8042_CTL_TIMEOUT)) { udelay(50); i++; } return -(i == I8042_CTL_TIMEOUT); } /* * i8042_flush() flushes all data that may be in the keyboard and mouse buffers * of the i8042 down the toilet. */ static int i8042_flush(void) { unsigned long flags; unsigned char data, str; int count = 0; int retval = 0; spin_lock_irqsave(&i8042_lock, flags); while ((str = i8042_read_status()) & I8042_STR_OBF) { if (count++ < I8042_BUFFER_SIZE) { udelay(50); data = i8042_read_data(); dbg("%02x <- i8042 (flush, %s)\n", data, str & I8042_STR_AUXDATA ? "aux" : "kbd"); } else { retval = -EIO; break; } } spin_unlock_irqrestore(&i8042_lock, flags); return retval; } /* * i8042_command() executes a command on the i8042. It also sends the input * parameter(s) of the commands to it, and receives the output value(s). The * parameters are to be stored in the param array, and the output is placed * into the same array. The number of the parameters and output values is * encoded in bits 8-11 of the command number. */ static int __i8042_command(unsigned char *param, int command) { int i, error; if (i8042_noloop && command == I8042_CMD_AUX_LOOP) return -1; error = i8042_wait_write(); if (error) return error; dbg("%02x -> i8042 (command)\n", command & 0xff); i8042_write_command(command & 0xff); for (i = 0; i < ((command >> 12) & 0xf); i++) { error = i8042_wait_write(); if (error) { dbg(" -- i8042 (wait write timeout)\n"); return error; } dbg("%02x -> i8042 (parameter)\n", param[i]); i8042_write_data(param[i]); } for (i = 0; i < ((command >> 8) & 0xf); i++) { error = i8042_wait_read(); if (error) { dbg(" -- i8042 (wait read timeout)\n"); return error; } if (command == I8042_CMD_AUX_LOOP && !(i8042_read_status() & I8042_STR_AUXDATA)) { dbg(" -- i8042 (auxerr)\n"); return -1; } param[i] = i8042_read_data(); dbg("%02x <- i8042 (return)\n", param[i]); } return 0; } int i8042_command(unsigned char *param, int command) { unsigned long flags; int retval; if (!i8042_present) return -1; spin_lock_irqsave(&i8042_lock, flags); retval = __i8042_command(param, command); spin_unlock_irqrestore(&i8042_lock, flags); return retval; } EXPORT_SYMBOL(i8042_command); /* * i8042_kbd_write() sends a byte out through the keyboard interface. */ static int i8042_kbd_write(struct serio *port, unsigned char c) { unsigned long flags; int retval = 0; spin_lock_irqsave(&i8042_lock, flags); if (!(retval = i8042_wait_write())) { dbg("%02x -> i8042 (kbd-data)\n", c); i8042_write_data(c); } spin_unlock_irqrestore(&i8042_lock, flags); return retval; } /* * i8042_aux_write() sends a byte out through the aux interface. */ static int i8042_aux_write(struct serio *serio, unsigned char c) { struct i8042_port *port = serio->port_data; return i8042_command(&c, port->mux == -1 ? I8042_CMD_AUX_SEND : I8042_CMD_MUX_SEND + port->mux); } /* * i8042_port_close attempts to clear AUX or KBD port state by disabling * and then re-enabling it. */ static void i8042_port_close(struct serio *serio) { int irq_bit; int disable_bit; const char *port_name; if (serio == i8042_ports[I8042_AUX_PORT_NO].serio) { irq_bit = I8042_CTR_AUXINT; disable_bit = I8042_CTR_AUXDIS; port_name = "AUX"; } else { irq_bit = I8042_CTR_KBDINT; disable_bit = I8042_CTR_KBDDIS; port_name = "KBD"; } i8042_ctr &= ~irq_bit; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't write CTR while closing %s port\n", port_name); udelay(50); i8042_ctr &= ~disable_bit; i8042_ctr |= irq_bit; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_err("Can't reactivate %s port\n", port_name); /* * See if there is any data appeared while we were messing with * port state. */ i8042_interrupt(0, NULL); } /* * i8042_start() is called by serio core when port is about to finish * registering. It will mark port as existing so i8042_interrupt can * start sending data through it. */ static int i8042_start(struct serio *serio) { struct i8042_port *port = serio->port_data; device_set_wakeup_capable(&serio->dev, true); /* * On platforms using suspend-to-idle, allow the keyboard to * wake up the system from sleep by enabling keyboard wakeups * by default. This is consistent with keyboard wakeup * behavior on many platforms using suspend-to-RAM (ACPI S3) * by default. */ if (pm_suspend_default_s2idle() && serio == i8042_ports[I8042_KBD_PORT_NO].serio) { device_set_wakeup_enable(&serio->dev, true); } spin_lock_irq(&i8042_lock); port->exists = true; spin_unlock_irq(&i8042_lock); return 0; } /* * i8042_stop() marks serio port as non-existing so i8042_interrupt * will not try to send data to the port that is about to go away. * The function is called by serio core as part of unregister procedure. */ static void i8042_stop(struct serio *serio) { struct i8042_port *port = serio->port_data; spin_lock_irq(&i8042_lock); port->exists = false; port->serio = NULL; spin_unlock_irq(&i8042_lock); /* * We need to make sure that interrupt handler finishes using * our serio port before we return from this function. * We synchronize with both AUX and KBD IRQs because there is * a (very unlikely) chance that AUX IRQ is raised for KBD port * and vice versa. */ synchronize_irq(I8042_AUX_IRQ); synchronize_irq(I8042_KBD_IRQ); } /* * i8042_filter() filters out unwanted bytes from the input data stream. * It is called from i8042_interrupt and thus is running with interrupts * off and i8042_lock held. */ static bool i8042_filter(unsigned char data, unsigned char str, struct serio *serio) { if (unlikely(i8042_suppress_kbd_ack)) { if ((~str & I8042_STR_AUXDATA) && (data == 0xfa || data == 0xfe)) { i8042_suppress_kbd_ack--; dbg("Extra keyboard ACK - filtered out\n"); return true; } } if (i8042_platform_filter && i8042_platform_filter(data, str, serio)) { dbg("Filtered out by platform filter\n"); return true; } return false; } /* * i8042_interrupt() is the most important function in this driver - * it handles the interrupts from the i8042, and sends incoming bytes * to the upper layers. */ static irqreturn_t i8042_interrupt(int irq, void *dev_id) { struct i8042_port *port; struct serio *serio; unsigned long flags; unsigned char str, data; unsigned int dfl; unsigned int port_no; bool filtered; int ret = 1; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (unlikely(~str & I8042_STR_OBF)) { spin_unlock_irqrestore(&i8042_lock, flags); if (irq) dbg("Interrupt %d, without any data\n", irq); ret = 0; goto out; } data = i8042_read_data(); if (i8042_mux_present && (str & I8042_STR_AUXDATA)) { static unsigned long last_transmit; static unsigned char last_str; dfl = 0; if (str & I8042_STR_MUXERR) { dbg("MUX error, status is %02x, data is %02x\n", str, data); /* * When MUXERR condition is signalled the data register can only contain * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately * it is not always the case. Some KBCs also report 0xfc when there is * nothing connected to the port while others sometimes get confused which * port the data came from and signal error leaving the data intact. They * _do not_ revert to legacy mode (actually I've never seen KBC reverting * to legacy mode yet, when we see one we'll add proper handling). * Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the * rest assume that the data came from the same serio last byte * was transmitted (if transmission happened not too long ago). */ switch (data) { default: if (time_before(jiffies, last_transmit + HZ/10)) { str = last_str; break; } fallthrough; /* report timeout */ case 0xfc: case 0xfd: case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break; case 0xff: dfl = SERIO_PARITY; data = 0xfe; break; } } port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3); last_str = str; last_transmit = jiffies; } else { dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) | ((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0); port_no = (str & I8042_STR_AUXDATA) ? I8042_AUX_PORT_NO : I8042_KBD_PORT_NO; } port = &i8042_ports[port_no]; serio = port->exists ? port->serio : NULL; filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n", port_no, irq, dfl & SERIO_PARITY ? ", bad parity" : "", dfl & SERIO_TIMEOUT ? ", timeout" : ""); filtered = i8042_filter(data, str, serio); spin_unlock_irqrestore(&i8042_lock, flags); if (likely(serio && !filtered)) serio_interrupt(serio, data, dfl); out: return IRQ_RETVAL(ret); } /* * i8042_enable_kbd_port enables keyboard port on chip */ static int i8042_enable_kbd_port(void) { i8042_ctr &= ~I8042_CTR_KBDDIS; i8042_ctr |= I8042_CTR_KBDINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { i8042_ctr &= ~I8042_CTR_KBDINT; i8042_ctr |= I8042_CTR_KBDDIS; pr_err("Failed to enable KBD port\n"); return -EIO; } return 0; } /* * i8042_enable_aux_port enables AUX (mouse) port on chip */ static int i8042_enable_aux_port(void) { i8042_ctr &= ~I8042_CTR_AUXDIS; i8042_ctr |= I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { i8042_ctr &= ~I8042_CTR_AUXINT; i8042_ctr |= I8042_CTR_AUXDIS; pr_err("Failed to enable AUX port\n"); return -EIO; } return 0; } /* * i8042_enable_mux_ports enables 4 individual AUX ports after * the controller has been switched into Multiplexed mode */ static int i8042_enable_mux_ports(void) { unsigned char param; int i; for (i = 0; i < I8042_NUM_MUX_PORTS; i++) { i8042_command(&param, I8042_CMD_MUX_PFX + i); i8042_command(&param, I8042_CMD_AUX_ENABLE); } return i8042_enable_aux_port(); } /* * i8042_set_mux_mode checks whether the controller has an * active multiplexor and puts the chip into Multiplexed (true) * or Legacy (false) mode. */ static int i8042_set_mux_mode(bool multiplex, unsigned char *mux_version) { unsigned char param, val; /* * Get rid of bytes in the queue. */ i8042_flush(); /* * Internal loopback test - send three bytes, they should come back from the * mouse interface, the last should be version. */ param = val = 0xf0; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != val) return -1; param = val = multiplex ? 0x56 : 0xf6; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != val) return -1; param = val = multiplex ? 0xa4 : 0xa5; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param == val) return -1; /* * Workaround for interference with USB Legacy emulation * that causes a v10.12 MUX to be found. */ if (param == 0xac) return -1; if (mux_version) *mux_version = param; return 0; } /* * i8042_check_mux() checks whether the controller supports the PS/2 Active * Multiplexing specification by Synaptics, Phoenix, Insyde and * LCS/Telegraphics. */ static int i8042_check_mux(void) { unsigned char mux_version; if (i8042_set_mux_mode(true, &mux_version)) return -1; pr_info("Detected active multiplexing controller, rev %d.%d\n", (mux_version >> 4) & 0xf, mux_version & 0xf); /* * Disable all muxed ports by disabling AUX. */ i8042_ctr |= I8042_CTR_AUXDIS; i8042_ctr &= ~I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("Failed to disable AUX port, can't use MUX\n"); return -EIO; } i8042_mux_present = true; return 0; } /* * The following is used to test AUX IRQ delivery. */ static struct completion i8042_aux_irq_delivered; static bool i8042_irq_being_tested; static irqreturn_t i8042_aux_test_irq(int irq, void *dev_id) { unsigned long flags; unsigned char str, data; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (str & I8042_STR_OBF) { data = i8042_read_data(); dbg("%02x <- i8042 (aux_test_irq, %s)\n", data, str & I8042_STR_AUXDATA ? "aux" : "kbd"); if (i8042_irq_being_tested && data == 0xa5 && (str & I8042_STR_AUXDATA)) complete(&i8042_aux_irq_delivered); ret = 1; } spin_unlock_irqrestore(&i8042_lock, flags); return IRQ_RETVAL(ret); } /* * i8042_toggle_aux - enables or disables AUX port on i8042 via command and * verifies success by readinng CTR. Used when testing for presence of AUX * port. */ static int i8042_toggle_aux(bool on) { unsigned char param; int i; if (i8042_command(&param, on ? I8042_CMD_AUX_ENABLE : I8042_CMD_AUX_DISABLE)) return -1; /* some chips need some time to set the I8042_CTR_AUXDIS bit */ for (i = 0; i < 100; i++) { udelay(50); if (i8042_command(&param, I8042_CMD_CTL_RCTR)) return -1; if (!(param & I8042_CTR_AUXDIS) == on) return 0; } return -1; } /* * i8042_check_aux() applies as much paranoia as it can at detecting * the presence of an AUX interface. */ static int i8042_check_aux(void) { int retval = -1; bool irq_registered = false; bool aux_loop_broken = false; unsigned long flags; unsigned char param; /* * Get rid of bytes in the queue. */ i8042_flush(); /* * Internal loopback test - filters out AT-type i8042's. Unfortunately * SiS screwed up and their 5597 doesn't support the LOOP command even * though it has an AUX port. */ param = 0x5a; retval = i8042_command(&param, I8042_CMD_AUX_LOOP); if (retval || param != 0x5a) { /* * External connection test - filters out AT-soldered PS/2 i8042's * 0x00 - no error, 0x01-0x03 - clock/data stuck, 0xff - general error * 0xfa - no error on some notebooks which ignore the spec * Because it's common for chipsets to return error on perfectly functioning * AUX ports, we test for this only when the LOOP command failed. */ if (i8042_command(&param, I8042_CMD_AUX_TEST) || (param && param != 0xfa && param != 0xff)) return -1; /* * If AUX_LOOP completed without error but returned unexpected data * mark it as broken */ if (!retval) aux_loop_broken = true; } /* * Bit assignment test - filters out PS/2 i8042's in AT mode */ if (i8042_toggle_aux(false)) { pr_warn("Failed to disable AUX port, but continuing anyway... Is this a SiS?\n"); pr_warn("If AUX port is really absent please use the 'i8042.noaux' option\n"); } if (i8042_toggle_aux(true)) return -1; /* * Reset keyboard (needed on some laptops to successfully detect * touchpad, e.g., some Gigabyte laptop models with Elantech * touchpads). */ if (i8042_kbdreset) { pr_warn("Attempting to reset device connected to KBD port\n"); i8042_kbd_write(NULL, (unsigned char) 0xff); } /* * Test AUX IRQ delivery to make sure BIOS did not grab the IRQ and * used it for a PCI card or somethig else. */ if (i8042_noloop || i8042_bypass_aux_irq_test || aux_loop_broken) { /* * Without LOOP command we can't test AUX IRQ delivery. Assume the port * is working and hope we are right. */ retval = 0; goto out; } if (request_irq(I8042_AUX_IRQ, i8042_aux_test_irq, IRQF_SHARED, "i8042", i8042_platform_device)) goto out; irq_registered = true; if (i8042_enable_aux_port()) goto out; spin_lock_irqsave(&i8042_lock, flags); init_completion(&i8042_aux_irq_delivered); i8042_irq_being_tested = true; param = 0xa5; retval = __i8042_command(&param, I8042_CMD_AUX_LOOP & 0xf0ff); spin_unlock_irqrestore(&i8042_lock, flags); if (retval) goto out; if (wait_for_completion_timeout(&i8042_aux_irq_delivered, msecs_to_jiffies(250)) == 0) { /* * AUX IRQ was never delivered so we need to flush the controller to * get rid of the byte we put there; otherwise keyboard may not work. */ dbg(" -- i8042 (aux irq test timeout)\n"); i8042_flush(); retval = -1; } out: /* * Disable the interface. */ i8042_ctr |= I8042_CTR_AUXDIS; i8042_ctr &= ~I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) retval = -1; if (irq_registered) free_irq(I8042_AUX_IRQ, i8042_platform_device); return retval; } static int i8042_controller_check(void) { if (i8042_flush()) { pr_info("No controller found\n"); return -ENODEV; } return 0; } static int i8042_controller_selftest(void) { unsigned char param; int i = 0; /* * We try this 5 times; on some really fragile systems this does not * take the first time... */ do { if (i8042_command(&param, I8042_CMD_CTL_TEST)) { pr_err("i8042 controller selftest timeout\n"); return -ENODEV; } if (param == I8042_RET_CTL_TEST) return 0; dbg("i8042 controller selftest: %#x != %#x\n", param, I8042_RET_CTL_TEST); msleep(50); } while (i++ < 5); #ifdef CONFIG_X86 /* * On x86, we don't fail entire i8042 initialization if controller * reset fails in hopes that keyboard port will still be functional * and user will still get a working keyboard. This is especially * important on netbooks. On other arches we trust hardware more. */ pr_info("giving up on controller selftest, continuing anyway...\n"); return 0; #else pr_err("i8042 controller selftest failed\n"); return -EIO; #endif } /* * i8042_controller_init initializes the i8042 controller, and, * most importantly, sets it into non-xlated mode if that's * desired. */ static int i8042_controller_init(void) { unsigned long flags; int n = 0; unsigned char ctr[2]; /* * Save the CTR for restore on unload / reboot. */ do { if (n >= 10) { pr_err("Unable to get stable CTR read\n"); return -EIO; } if (n != 0) udelay(50); if (i8042_command(&ctr[n++ % 2], I8042_CMD_CTL_RCTR)) { pr_err("Can't read CTR while initializing i8042\n"); return i8042_probe_defer ? -EPROBE_DEFER : -EIO; } } while (n < 2 || ctr[0] != ctr[1]); i8042_initial_ctr = i8042_ctr = ctr[0]; /* * Disable the keyboard interface and interrupt. */ i8042_ctr |= I8042_CTR_KBDDIS; i8042_ctr &= ~I8042_CTR_KBDINT; /* * Handle keylock. */ spin_lock_irqsave(&i8042_lock, flags); if (~i8042_read_status() & I8042_STR_KEYLOCK) { if (i8042_unlock) i8042_ctr |= I8042_CTR_IGNKEYLOCK; else pr_warn("Warning: Keylock active\n"); } spin_unlock_irqrestore(&i8042_lock, flags); /* * If the chip is configured into nontranslated mode by the BIOS, don't * bother enabling translating and be happy. */ if (~i8042_ctr & I8042_CTR_XLATE) i8042_direct = true; /* * Set nontranslated mode for the kbd interface if requested by an option. * After this the kbd interface becomes a simple serial in/out, like the aux * interface is. We don't do this by default, since it can confuse notebook * BIOSes. */ if (i8042_direct) i8042_ctr &= ~I8042_CTR_XLATE; /* * Write CTR back. */ if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("Can't write CTR while initializing i8042\n"); return -EIO; } /* * Flush whatever accumulated while we were disabling keyboard port. */ i8042_flush(); return 0; } /* * Reset the controller and reset CRT to the original value set by BIOS. */ static void i8042_controller_reset(bool s2r_wants_reset) { i8042_flush(); /* * Disable both KBD and AUX interfaces so they don't get in the way */ i8042_ctr |= I8042_CTR_KBDDIS | I8042_CTR_AUXDIS; i8042_ctr &= ~(I8042_CTR_KBDINT | I8042_CTR_AUXINT); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't write CTR while resetting\n"); /* * Disable MUX mode if present. */ if (i8042_mux_present) i8042_set_mux_mode(false, NULL); /* * Reset the controller if requested. */ if (i8042_reset == I8042_RESET_ALWAYS || (i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) { i8042_controller_selftest(); } /* * Restore the original control register setting. */ if (i8042_command(&i8042_initial_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't restore CTR\n"); } /* * i8042_panic_blink() will turn the keyboard LEDs on or off and is called * when kernel panics. Flashing LEDs is useful for users running X who may * not see the console and will help distinguishing panics from "real" * lockups. * * Note that DELAY has a limit of 10ms so we will not get stuck here * waiting for KBC to free up even if KBD interrupt is off */ #define DELAY do { mdelay(1); if (++delay > 10) return delay; } while(0) static long i8042_panic_blink(int state) { long delay = 0; char led; led = (state) ? 0x01 | 0x04 : 0; while (i8042_read_status() & I8042_STR_IBF) DELAY; dbg("%02x -> i8042 (panic blink)\n", 0xed); i8042_suppress_kbd_ack = 2; i8042_write_data(0xed); /* set leds */ DELAY; while (i8042_read_status() & I8042_STR_IBF) DELAY; DELAY; dbg("%02x -> i8042 (panic blink)\n", led); i8042_write_data(led); DELAY; return delay; } #undef DELAY #ifdef CONFIG_X86 static void i8042_dritek_enable(void) { unsigned char param = 0x90; int error; error = i8042_command(&param, 0x1059); if (error) pr_warn("Failed to enable DRITEK extension: %d\n", error); } #endif #ifdef CONFIG_PM /* * Here we try to reset everything back to a state we had * before suspending. */ static int i8042_controller_resume(bool s2r_wants_reset) { int error; error = i8042_controller_check(); if (error) return error; if (i8042_reset == I8042_RESET_ALWAYS || (i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) { error = i8042_controller_selftest(); if (error) return error; } /* * Restore original CTR value and disable all ports */ i8042_ctr = i8042_initial_ctr; if (i8042_direct) i8042_ctr &= ~I8042_CTR_XLATE; i8042_ctr |= I8042_CTR_AUXDIS | I8042_CTR_KBDDIS; i8042_ctr &= ~(I8042_CTR_AUXINT | I8042_CTR_KBDINT); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_warn("Can't write CTR to resume, retrying...\n"); msleep(50); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("CTR write retry failed\n"); return -EIO; } } #ifdef CONFIG_X86 if (i8042_dritek) i8042_dritek_enable(); #endif if (i8042_mux_present) { if (i8042_set_mux_mode(true, NULL) || i8042_enable_mux_ports()) pr_warn("failed to resume active multiplexor, mouse won't work\n"); } else if (i8042_ports[I8042_AUX_PORT_NO].serio) i8042_enable_aux_port(); if (i8042_ports[I8042_KBD_PORT_NO].serio) i8042_enable_kbd_port(); i8042_interrupt(0, NULL); return 0; } /* * Here we try to restore the original BIOS settings to avoid * upsetting it. */ static int i8042_pm_suspend(struct device *dev) { int i; if (pm_suspend_via_firmware()) i8042_controller_reset(true); /* Set up serio interrupts for system wakeup. */ for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (serio && device_may_wakeup(&serio->dev)) enable_irq_wake(i8042_ports[i].irq); } return 0; } static int i8042_pm_resume_noirq(struct device *dev) { if (!pm_resume_via_firmware()) i8042_interrupt(0, NULL); return 0; } static int i8042_pm_resume(struct device *dev) { bool want_reset; int i; for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (serio && device_may_wakeup(&serio->dev)) disable_irq_wake(i8042_ports[i].irq); } /* * If platform firmware was not going to be involved in suspend, we did * not restore the controller state to whatever it had been at boot * time, so we do not need to do anything. */ if (!pm_suspend_via_firmware()) return 0; /* * We only need to reset the controller if we are resuming after handing * off control to the platform firmware, otherwise we can simply restore * the mode. */ want_reset = pm_resume_via_firmware(); return i8042_controller_resume(want_reset); } static int i8042_pm_thaw(struct device *dev) { i8042_interrupt(0, NULL); return 0; } static int i8042_pm_reset(struct device *dev) { i8042_controller_reset(false); return 0; } static int i8042_pm_restore(struct device *dev) { return i8042_controller_resume(false); } static const struct dev_pm_ops i8042_pm_ops = { .suspend = i8042_pm_suspend, .resume_noirq = i8042_pm_resume_noirq, .resume = i8042_pm_resume, .thaw = i8042_pm_thaw, .poweroff = i8042_pm_reset, .restore = i8042_pm_restore, }; #endif /* CONFIG_PM */ /* * We need to reset the 8042 back to original mode on system shutdown, * because otherwise BIOSes will be confused. */ static void i8042_shutdown(struct platform_device *dev) { i8042_controller_reset(false); } static int i8042_create_kbd_port(void) { struct serio *serio; struct i8042_port *port = &i8042_ports[I8042_KBD_PORT_NO]; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = i8042_direct ? SERIO_8042 : SERIO_8042_XL; serio->write = i8042_dumbkbd ? NULL : i8042_kbd_write; serio->start = i8042_start; serio->stop = i8042_stop; serio->close = i8042_port_close; serio->ps2_cmd_mutex = &i8042_mutex; serio->port_data = port; serio->dev.parent = &i8042_platform_device->dev; strscpy(serio->name, "i8042 KBD port", sizeof(serio->name)); strscpy(serio->phys, I8042_KBD_PHYS_DESC, sizeof(serio->phys)); strscpy(serio->firmware_id, i8042_kbd_firmware_id, sizeof(serio->firmware_id)); set_primary_fwnode(&serio->dev, i8042_kbd_fwnode); port->serio = serio; port->irq = I8042_KBD_IRQ; return 0; } static int i8042_create_aux_port(int idx) { struct serio *serio; int port_no = idx < 0 ? I8042_AUX_PORT_NO : I8042_MUX_PORT_NO + idx; struct i8042_port *port = &i8042_ports[port_no]; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = SERIO_8042; serio->write = i8042_aux_write; serio->start = i8042_start; serio->stop = i8042_stop; serio->ps2_cmd_mutex = &i8042_mutex; serio->port_data = port; serio->dev.parent = &i8042_platform_device->dev; if (idx < 0) { strscpy(serio->name, "i8042 AUX port", sizeof(serio->name)); strscpy(serio->phys, I8042_AUX_PHYS_DESC, sizeof(serio->phys)); strscpy(serio->firmware_id, i8042_aux_firmware_id, sizeof(serio->firmware_id)); serio->close = i8042_port_close; } else { snprintf(serio->name, sizeof(serio->name), "i8042 AUX%d port", idx); snprintf(serio->phys, sizeof(serio->phys), I8042_MUX_PHYS_DESC, idx + 1); strscpy(serio->firmware_id, i8042_aux_firmware_id, sizeof(serio->firmware_id)); } port->serio = serio; port->mux = idx; port->irq = I8042_AUX_IRQ; return 0; } static void i8042_free_kbd_port(void) { kfree(i8042_ports[I8042_KBD_PORT_NO].serio); i8042_ports[I8042_KBD_PORT_NO].serio = NULL; } static void i8042_free_aux_ports(void) { int i; for (i = I8042_AUX_PORT_NO; i < I8042_NUM_PORTS; i++) { kfree(i8042_ports[i].serio); i8042_ports[i].serio = NULL; } } static void i8042_register_ports(void) { int i; for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (!serio) continue; printk(KERN_INFO "serio: %s at %#lx,%#lx irq %d\n", serio->name, (unsigned long) I8042_DATA_REG, (unsigned long) I8042_COMMAND_REG, i8042_ports[i].irq); serio_register_port(serio); } } static void i8042_unregister_ports(void) { int i; for (i = 0; i < I8042_NUM_PORTS; i++) { if (i8042_ports[i].serio) { serio_unregister_port(i8042_ports[i].serio); i8042_ports[i].serio = NULL; } } } static void i8042_free_irqs(void) { if (i8042_aux_irq_registered) free_irq(I8042_AUX_IRQ, i8042_platform_device); if (i8042_kbd_irq_registered) free_irq(I8042_KBD_IRQ, i8042_platform_device); i8042_aux_irq_registered = i8042_kbd_irq_registered = false; } static int i8042_setup_aux(void) { int (*aux_enable)(void); int error; int i; if (i8042_check_aux()) return -ENODEV; if (i8042_nomux || i8042_check_mux()) { error = i8042_create_aux_port(-1); if (error) goto err_free_ports; aux_enable = i8042_enable_aux_port; } else { for (i = 0; i < I8042_NUM_MUX_PORTS; i++) { error = i8042_create_aux_port(i); if (error) goto err_free_ports; } aux_enable = i8042_enable_mux_ports; } error = request_irq(I8042_AUX_IRQ, i8042_interrupt, IRQF_SHARED, "i8042", i8042_platform_device); if (error) goto err_free_ports; error = aux_enable(); if (error) goto err_free_irq; i8042_aux_irq_registered = true; return 0; err_free_irq: free_irq(I8042_AUX_IRQ, i8042_platform_device); err_free_ports: i8042_free_aux_ports(); return error; } static int i8042_setup_kbd(void) { int error; error = i8042_create_kbd_port(); if (error) return error; error = request_irq(I8042_KBD_IRQ, i8042_interrupt, IRQF_SHARED, "i8042", i8042_platform_device); if (error) goto err_free_port; error = i8042_enable_kbd_port(); if (error) goto err_free_irq; i8042_kbd_irq_registered = true; return 0; err_free_irq: free_irq(I8042_KBD_IRQ, i8042_platform_device); err_free_port: i8042_free_kbd_port(); return error; } static int i8042_kbd_bind_notifier(struct notifier_block *nb, unsigned long action, void *data) { struct device *dev = data; struct serio *serio = to_serio_port(dev); struct i8042_port *port = serio->port_data; if (serio != i8042_ports[I8042_KBD_PORT_NO].serio) return 0; switch (action) { case BUS_NOTIFY_BOUND_DRIVER: port->driver_bound = true; break; case BUS_NOTIFY_UNBIND_DRIVER: port->driver_bound = false; break; } return 0; } static int i8042_probe(struct platform_device *dev) { int error; if (i8042_reset == I8042_RESET_ALWAYS) { error = i8042_controller_selftest(); if (error) return error; } error = i8042_controller_init(); if (error) return error; #ifdef CONFIG_X86 if (i8042_dritek) i8042_dritek_enable(); #endif if (!i8042_noaux) { error = i8042_setup_aux(); if (error && error != -ENODEV && error != -EBUSY) goto out_fail; } if (!i8042_nokbd) { error = i8042_setup_kbd(); if (error) goto out_fail; } /* * Ok, everything is ready, let's register all serio ports */ i8042_register_ports(); return 0; out_fail: i8042_free_aux_ports(); /* in case KBD failed but AUX not */ i8042_free_irqs(); i8042_controller_reset(false); return error; } static int i8042_remove(struct platform_device *dev) { i8042_unregister_ports(); i8042_free_irqs(); i8042_controller_reset(false); return 0; } static struct platform_driver i8042_driver = { .driver = { .name = "i8042", #ifdef CONFIG_PM .pm = &i8042_pm_ops, #endif }, .probe = i8042_probe, .remove = i8042_remove, .shutdown = i8042_shutdown, }; static struct notifier_block i8042_kbd_bind_notifier_block = { .notifier_call = i8042_kbd_bind_notifier, }; static int __init i8042_init(void) { int err; dbg_init(); err = i8042_platform_init(); if (err) return (err == -ENODEV) ? 0 : err; err = i8042_controller_check(); if (err) goto err_platform_exit; /* Set this before creating the dev to allow i8042_command to work right away */ i8042_present = true; err = platform_driver_register(&i8042_driver); if (err) goto err_platform_exit; i8042_platform_device = platform_device_alloc("i8042", -1); if (!i8042_platform_device) { err = -ENOMEM; goto err_unregister_driver; } err = platform_device_add(i8042_platform_device); if (err) goto err_free_device; bus_register_notifier(&serio_bus, &i8042_kbd_bind_notifier_block); panic_blink = i8042_panic_blink; return 0; err_free_device: platform_device_put(i8042_platform_device); err_unregister_driver: platform_driver_unregister(&i8042_driver); err_platform_exit: i8042_platform_exit(); return err; } static void __exit i8042_exit(void) { if (!i8042_present) return; platform_device_unregister(i8042_platform_device); platform_driver_unregister(&i8042_driver); i8042_platform_exit(); bus_unregister_notifier(&serio_bus, &i8042_kbd_bind_notifier_block); panic_blink = NULL; } module_init(i8042_init); module_exit(i8042_exit);
linux-master
drivers/input/serio/i8042.c
// SPDX-License-Identifier: GPL-2.0-only /* * Altera University Program PS2 controller driver * * Copyright (C) 2008 Thomas Chou <[email protected]> * * Based on sa1111ps2.c, which is: * Copyright (C) 2002 Russell King */ #include <linux/module.h> #include <linux/input.h> #include <linux/serio.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/of.h> #define DRV_NAME "altera_ps2" struct ps2if { struct serio *io; void __iomem *base; }; /* * Read all bytes waiting in the PS2 port. There should be * at the most one, but we loop for safety. */ static irqreturn_t altera_ps2_rxint(int irq, void *dev_id) { struct ps2if *ps2if = dev_id; unsigned int status; irqreturn_t handled = IRQ_NONE; while ((status = readl(ps2if->base)) & 0xffff0000) { serio_interrupt(ps2if->io, status & 0xff, 0); handled = IRQ_HANDLED; } return handled; } /* * Write a byte to the PS2 port. */ static int altera_ps2_write(struct serio *io, unsigned char val) { struct ps2if *ps2if = io->port_data; writel(val, ps2if->base); return 0; } static int altera_ps2_open(struct serio *io) { struct ps2if *ps2if = io->port_data; /* clear fifo */ while (readl(ps2if->base) & 0xffff0000) /* empty */; writel(1, ps2if->base + 4); /* enable rx irq */ return 0; } static void altera_ps2_close(struct serio *io) { struct ps2if *ps2if = io->port_data; writel(0, ps2if->base + 4); /* disable rx irq */ } /* * Add one device to this driver. */ static int altera_ps2_probe(struct platform_device *pdev) { struct ps2if *ps2if; struct serio *serio; int error, irq; ps2if = devm_kzalloc(&pdev->dev, sizeof(struct ps2if), GFP_KERNEL); if (!ps2if) return -ENOMEM; ps2if->base = devm_platform_get_and_ioremap_resource(pdev, 0, NULL); if (IS_ERR(ps2if->base)) return PTR_ERR(ps2if->base); irq = platform_get_irq(pdev, 0); if (irq < 0) return -ENXIO; error = devm_request_irq(&pdev->dev, irq, altera_ps2_rxint, 0, pdev->name, ps2if); if (error) { dev_err(&pdev->dev, "could not request IRQ %d\n", irq); return error; } serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = SERIO_8042; serio->write = altera_ps2_write; serio->open = altera_ps2_open; serio->close = altera_ps2_close; strscpy(serio->name, dev_name(&pdev->dev), sizeof(serio->name)); strscpy(serio->phys, dev_name(&pdev->dev), sizeof(serio->phys)); serio->port_data = ps2if; serio->dev.parent = &pdev->dev; ps2if->io = serio; dev_info(&pdev->dev, "base %p, irq %d\n", ps2if->base, irq); serio_register_port(ps2if->io); platform_set_drvdata(pdev, ps2if); return 0; } /* * Remove one device from this driver. */ static int altera_ps2_remove(struct platform_device *pdev) { struct ps2if *ps2if = platform_get_drvdata(pdev); serio_unregister_port(ps2if->io); return 0; } #ifdef CONFIG_OF static const struct of_device_id altera_ps2_match[] = { { .compatible = "ALTR,ps2-1.0", }, { .compatible = "altr,ps2-1.0", }, {}, }; MODULE_DEVICE_TABLE(of, altera_ps2_match); #endif /* CONFIG_OF */ /* * Our device driver structure */ static struct platform_driver altera_ps2_driver = { .probe = altera_ps2_probe, .remove = altera_ps2_remove, .driver = { .name = DRV_NAME, .of_match_table = of_match_ptr(altera_ps2_match), }, }; module_platform_driver(altera_ps2_driver); MODULE_DESCRIPTION("Altera University Program PS2 controller driver"); MODULE_AUTHOR("Thomas Chou <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRV_NAME);
linux-master
drivers/input/serio/altera_ps2.c
// SPDX-License-Identifier: GPL-2.0-only /* * TQC PS/2 Multiplexer driver * * Copyright (C) 2010 Dmitry Eremin-Solenikov */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/serio.h> MODULE_AUTHOR("Dmitry Eremin-Solenikov <[email protected]>"); MODULE_DESCRIPTION("TQC PS/2 Multiplexer driver"); MODULE_LICENSE("GPL"); #define PS2MULT_KB_SELECTOR 0xA0 #define PS2MULT_MS_SELECTOR 0xA1 #define PS2MULT_ESCAPE 0x7D #define PS2MULT_BSYNC 0x7E #define PS2MULT_SESSION_START 0x55 #define PS2MULT_SESSION_END 0x56 struct ps2mult_port { struct serio *serio; unsigned char sel; bool registered; }; #define PS2MULT_NUM_PORTS 2 #define PS2MULT_KBD_PORT 0 #define PS2MULT_MOUSE_PORT 1 struct ps2mult { struct serio *mx_serio; struct ps2mult_port ports[PS2MULT_NUM_PORTS]; spinlock_t lock; struct ps2mult_port *in_port; struct ps2mult_port *out_port; bool escape; }; /* First MUST come PS2MULT_NUM_PORTS selectors */ static const unsigned char ps2mult_controls[] = { PS2MULT_KB_SELECTOR, PS2MULT_MS_SELECTOR, PS2MULT_ESCAPE, PS2MULT_BSYNC, PS2MULT_SESSION_START, PS2MULT_SESSION_END, }; static const struct serio_device_id ps2mult_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_PS2MULT, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, ps2mult_serio_ids); static void ps2mult_select_port(struct ps2mult *psm, struct ps2mult_port *port) { struct serio *mx_serio = psm->mx_serio; serio_write(mx_serio, port->sel); psm->out_port = port; dev_dbg(&mx_serio->dev, "switched to sel %02x\n", port->sel); } static int ps2mult_serio_write(struct serio *serio, unsigned char data) { struct serio *mx_port = serio->parent; struct ps2mult *psm = serio_get_drvdata(mx_port); struct ps2mult_port *port = serio->port_data; bool need_escape; unsigned long flags; spin_lock_irqsave(&psm->lock, flags); if (psm->out_port != port) ps2mult_select_port(psm, port); need_escape = memchr(ps2mult_controls, data, sizeof(ps2mult_controls)); dev_dbg(&serio->dev, "write: %s%02x\n", need_escape ? "ESC " : "", data); if (need_escape) serio_write(mx_port, PS2MULT_ESCAPE); serio_write(mx_port, data); spin_unlock_irqrestore(&psm->lock, flags); return 0; } static int ps2mult_serio_start(struct serio *serio) { struct ps2mult *psm = serio_get_drvdata(serio->parent); struct ps2mult_port *port = serio->port_data; unsigned long flags; spin_lock_irqsave(&psm->lock, flags); port->registered = true; spin_unlock_irqrestore(&psm->lock, flags); return 0; } static void ps2mult_serio_stop(struct serio *serio) { struct ps2mult *psm = serio_get_drvdata(serio->parent); struct ps2mult_port *port = serio->port_data; unsigned long flags; spin_lock_irqsave(&psm->lock, flags); port->registered = false; spin_unlock_irqrestore(&psm->lock, flags); } static int ps2mult_create_port(struct ps2mult *psm, int i) { struct serio *mx_serio = psm->mx_serio; struct serio *serio; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; strscpy(serio->name, "TQC PS/2 Multiplexer", sizeof(serio->name)); snprintf(serio->phys, sizeof(serio->phys), "%s/port%d", mx_serio->phys, i); serio->id.type = SERIO_8042; serio->write = ps2mult_serio_write; serio->start = ps2mult_serio_start; serio->stop = ps2mult_serio_stop; serio->parent = psm->mx_serio; serio->port_data = &psm->ports[i]; psm->ports[i].serio = serio; return 0; } static void ps2mult_reset(struct ps2mult *psm) { unsigned long flags; spin_lock_irqsave(&psm->lock, flags); serio_write(psm->mx_serio, PS2MULT_SESSION_END); serio_write(psm->mx_serio, PS2MULT_SESSION_START); ps2mult_select_port(psm, &psm->ports[PS2MULT_KBD_PORT]); spin_unlock_irqrestore(&psm->lock, flags); } static int ps2mult_connect(struct serio *serio, struct serio_driver *drv) { struct ps2mult *psm; int i; int error; if (!serio->write) return -EINVAL; psm = kzalloc(sizeof(*psm), GFP_KERNEL); if (!psm) return -ENOMEM; spin_lock_init(&psm->lock); psm->mx_serio = serio; for (i = 0; i < PS2MULT_NUM_PORTS; i++) { psm->ports[i].sel = ps2mult_controls[i]; error = ps2mult_create_port(psm, i); if (error) goto err_out; } psm->in_port = psm->out_port = &psm->ports[PS2MULT_KBD_PORT]; serio_set_drvdata(serio, psm); error = serio_open(serio, drv); if (error) goto err_out; ps2mult_reset(psm); for (i = 0; i < PS2MULT_NUM_PORTS; i++) { struct serio *s = psm->ports[i].serio; dev_info(&serio->dev, "%s port at %s\n", s->name, serio->phys); serio_register_port(s); } return 0; err_out: while (--i >= 0) kfree(psm->ports[i].serio); kfree(psm); return error; } static void ps2mult_disconnect(struct serio *serio) { struct ps2mult *psm = serio_get_drvdata(serio); /* Note that serio core already take care of children ports */ serio_write(serio, PS2MULT_SESSION_END); serio_close(serio); kfree(psm); serio_set_drvdata(serio, NULL); } static int ps2mult_reconnect(struct serio *serio) { struct ps2mult *psm = serio_get_drvdata(serio); ps2mult_reset(psm); return 0; } static irqreturn_t ps2mult_interrupt(struct serio *serio, unsigned char data, unsigned int dfl) { struct ps2mult *psm = serio_get_drvdata(serio); struct ps2mult_port *in_port; unsigned long flags; dev_dbg(&serio->dev, "Received %02x flags %02x\n", data, dfl); spin_lock_irqsave(&psm->lock, flags); if (psm->escape) { psm->escape = false; in_port = psm->in_port; if (in_port->registered) serio_interrupt(in_port->serio, data, dfl); goto out; } switch (data) { case PS2MULT_ESCAPE: dev_dbg(&serio->dev, "ESCAPE\n"); psm->escape = true; break; case PS2MULT_BSYNC: dev_dbg(&serio->dev, "BSYNC\n"); psm->in_port = psm->out_port; break; case PS2MULT_SESSION_START: dev_dbg(&serio->dev, "SS\n"); break; case PS2MULT_SESSION_END: dev_dbg(&serio->dev, "SE\n"); break; case PS2MULT_KB_SELECTOR: dev_dbg(&serio->dev, "KB\n"); psm->in_port = &psm->ports[PS2MULT_KBD_PORT]; break; case PS2MULT_MS_SELECTOR: dev_dbg(&serio->dev, "MS\n"); psm->in_port = &psm->ports[PS2MULT_MOUSE_PORT]; break; default: in_port = psm->in_port; if (in_port->registered) serio_interrupt(in_port->serio, data, dfl); break; } out: spin_unlock_irqrestore(&psm->lock, flags); return IRQ_HANDLED; } static struct serio_driver ps2mult_drv = { .driver = { .name = "ps2mult", }, .description = "TQC PS/2 Multiplexer driver", .id_table = ps2mult_serio_ids, .interrupt = ps2mult_interrupt, .connect = ps2mult_connect, .disconnect = ps2mult_disconnect, .reconnect = ps2mult_reconnect, }; module_serio_driver(ps2mult_drv);
linux-master
drivers/input/serio/ps2mult.c
// SPDX-License-Identifier: GPL-2.0-only /* * Parallel port to Keyboard port adapter driver for Linux * * Copyright (c) 1999-2004 Vojtech Pavlik */ /* * To connect an AT or XT keyboard to the parallel port, a fairly simple adapter * can be made: * * Parallel port Keyboard port * * +5V --------------------- +5V (4) * * ______ * +5V -------|______|--. * | * ACK (10) ------------| * |--- KBD CLOCK (5) * STROBE (1) ---|<|----' * * ______ * +5V -------|______|--. * | * BUSY (11) -----------| * |--- KBD DATA (1) * AUTOFD (14) --|<|----' * * GND (18-25) ------------- GND (3) * * The diodes can be fairly any type, and the resistors should be somewhere * around 5 kOhm, but the adapter will likely work without the resistors, * too. * * The +5V source can be taken either from USB, from mouse or keyboard ports, * or from a joystick port. Unfortunately, the parallel port of a PC doesn't * have a +5V pin, and feeding the keyboard from signal pins is out of question * with 300 mA power reqirement of a typical AT keyboard. */ #include <linux/module.h> #include <linux/parport.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/serio.h> MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("Parallel port to Keyboard port adapter driver"); MODULE_LICENSE("GPL"); static unsigned int parkbd_pp_no; module_param_named(port, parkbd_pp_no, int, 0); MODULE_PARM_DESC(port, "Parallel port the adapter is connected to (default is 0)"); static unsigned int parkbd_mode = SERIO_8042; module_param_named(mode, parkbd_mode, uint, 0); MODULE_PARM_DESC(mode, "Mode of operation: XT = 0/AT = 1 (default)"); #define PARKBD_CLOCK 0x01 /* Strobe & Ack */ #define PARKBD_DATA 0x02 /* AutoFd & Busy */ static int parkbd_buffer; static int parkbd_counter; static unsigned long parkbd_last; static int parkbd_writing; static unsigned long parkbd_start; static struct pardevice *parkbd_dev; static struct serio *parkbd_port; static int parkbd_readlines(void) { return (parport_read_status(parkbd_dev->port) >> 6) ^ 2; } static void parkbd_writelines(int data) { parport_write_control(parkbd_dev->port, (~data & 3) | 0x10); } static int parkbd_write(struct serio *port, unsigned char c) { unsigned char p; if (!parkbd_mode) return -1; p = c ^ (c >> 4); p = p ^ (p >> 2); p = p ^ (p >> 1); parkbd_counter = 0; parkbd_writing = 1; parkbd_buffer = c | (((int) (~p & 1)) << 8) | 0x600; parkbd_writelines(2); return 0; } static void parkbd_interrupt(void *dev_id) { if (parkbd_writing) { if (parkbd_counter && ((parkbd_counter == 11) || time_after(jiffies, parkbd_last + HZ/100))) { parkbd_counter = 0; parkbd_buffer = 0; parkbd_writing = 0; parkbd_writelines(3); return; } parkbd_writelines(((parkbd_buffer >> parkbd_counter++) & 1) | 2); if (parkbd_counter == 11) { parkbd_counter = 0; parkbd_buffer = 0; parkbd_writing = 0; parkbd_writelines(3); } } else { if ((parkbd_counter == parkbd_mode + 10) || time_after(jiffies, parkbd_last + HZ/100)) { parkbd_counter = 0; parkbd_buffer = 0; } parkbd_buffer |= (parkbd_readlines() >> 1) << parkbd_counter++; if (parkbd_counter == parkbd_mode + 10) serio_interrupt(parkbd_port, (parkbd_buffer >> (2 - parkbd_mode)) & 0xff, 0); } parkbd_last = jiffies; } static int parkbd_getport(struct parport *pp) { struct pardev_cb parkbd_parport_cb; memset(&parkbd_parport_cb, 0, sizeof(parkbd_parport_cb)); parkbd_parport_cb.irq_func = parkbd_interrupt; parkbd_parport_cb.flags = PARPORT_FLAG_EXCL; parkbd_dev = parport_register_dev_model(pp, "parkbd", &parkbd_parport_cb, 0); if (!parkbd_dev) return -ENODEV; if (parport_claim(parkbd_dev)) { parport_unregister_device(parkbd_dev); return -EBUSY; } parkbd_start = jiffies; return 0; } static struct serio *parkbd_allocate_serio(void) { struct serio *serio; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (serio) { serio->id.type = parkbd_mode; serio->write = parkbd_write; strscpy(serio->name, "PARKBD AT/XT keyboard adapter", sizeof(serio->name)); snprintf(serio->phys, sizeof(serio->phys), "%s/serio0", parkbd_dev->port->name); } return serio; } static void parkbd_attach(struct parport *pp) { if (pp->number != parkbd_pp_no) { pr_debug("Not using parport%d.\n", pp->number); return; } if (parkbd_getport(pp)) return; parkbd_port = parkbd_allocate_serio(); if (!parkbd_port) { parport_release(parkbd_dev); parport_unregister_device(parkbd_dev); return; } parkbd_writelines(3); serio_register_port(parkbd_port); printk(KERN_INFO "serio: PARKBD %s adapter on %s\n", parkbd_mode ? "AT" : "XT", parkbd_dev->port->name); return; } static void parkbd_detach(struct parport *port) { if (!parkbd_port || port->number != parkbd_pp_no) return; parport_release(parkbd_dev); serio_unregister_port(parkbd_port); parport_unregister_device(parkbd_dev); parkbd_port = NULL; } static struct parport_driver parkbd_parport_driver = { .name = "parkbd", .match_port = parkbd_attach, .detach = parkbd_detach, .devmodel = true, }; module_parport_driver(parkbd_parport_driver);
linux-master
drivers/input/serio/parkbd.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> #include <asm/unaligned.h> /* * Pressure-threshold modules param code from Alex Perry <[email protected]> */ MODULE_AUTHOR("Josh Myer <[email protected]>"); MODULE_DESCRIPTION("USB KB Gear JamStudio Tablet driver"); MODULE_LICENSE("GPL"); #define USB_VENDOR_ID_KBGEAR 0x084e static int kb_pressure_click = 0x10; module_param(kb_pressure_click, int, 0); MODULE_PARM_DESC(kb_pressure_click, "pressure threshold for clicks"); struct kbtab { unsigned char *data; dma_addr_t data_dma; struct input_dev *dev; struct usb_interface *intf; struct urb *irq; char phys[32]; }; static void kbtab_irq(struct urb *urb) { struct kbtab *kbtab = urb->context; unsigned char *data = kbtab->data; struct input_dev *dev = kbtab->dev; int pressure; int retval; switch (urb->status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&kbtab->intf->dev, "%s - urb shutting down with status: %d\n", __func__, urb->status); return; default: dev_dbg(&kbtab->intf->dev, "%s - nonzero urb status received: %d\n", __func__, urb->status); goto exit; } input_report_key(dev, BTN_TOOL_PEN, 1); input_report_abs(dev, ABS_X, get_unaligned_le16(&data[1])); input_report_abs(dev, ABS_Y, get_unaligned_le16(&data[3])); /*input_report_key(dev, BTN_TOUCH , data[0] & 0x01);*/ input_report_key(dev, BTN_RIGHT, data[0] & 0x02); pressure = data[5]; if (kb_pressure_click == -1) input_report_abs(dev, ABS_PRESSURE, pressure); else input_report_key(dev, BTN_LEFT, pressure > kb_pressure_click ? 1 : 0); input_sync(dev); exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&kbtab->intf->dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static const struct usb_device_id kbtab_ids[] = { { USB_DEVICE(USB_VENDOR_ID_KBGEAR, 0x1001), .driver_info = 0 }, { } }; MODULE_DEVICE_TABLE(usb, kbtab_ids); static int kbtab_open(struct input_dev *dev) { struct kbtab *kbtab = input_get_drvdata(dev); struct usb_device *udev = interface_to_usbdev(kbtab->intf); kbtab->irq->dev = udev; if (usb_submit_urb(kbtab->irq, GFP_KERNEL)) return -EIO; return 0; } static void kbtab_close(struct input_dev *dev) { struct kbtab *kbtab = input_get_drvdata(dev); usb_kill_urb(kbtab->irq); } static int kbtab_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct kbtab *kbtab; struct input_dev *input_dev; int error = -ENOMEM; if (intf->cur_altsetting->desc.bNumEndpoints < 1) return -ENODEV; endpoint = &intf->cur_altsetting->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -ENODEV; kbtab = kzalloc(sizeof(struct kbtab), GFP_KERNEL); input_dev = input_allocate_device(); if (!kbtab || !input_dev) goto fail1; kbtab->data = usb_alloc_coherent(dev, 8, GFP_KERNEL, &kbtab->data_dma); if (!kbtab->data) goto fail1; kbtab->irq = usb_alloc_urb(0, GFP_KERNEL); if (!kbtab->irq) goto fail2; kbtab->intf = intf; kbtab->dev = input_dev; usb_make_path(dev, kbtab->phys, sizeof(kbtab->phys)); strlcat(kbtab->phys, "/input0", sizeof(kbtab->phys)); input_dev->name = "KB Gear Tablet"; input_dev->phys = kbtab->phys; usb_to_input_id(dev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, kbtab); input_dev->open = kbtab_open; input_dev->close = kbtab_close; input_dev->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_LEFT)] |= BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT); input_dev->keybit[BIT_WORD(BTN_DIGI)] |= BIT_MASK(BTN_TOOL_PEN) | BIT_MASK(BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, 0x2000, 4, 0); input_set_abs_params(input_dev, ABS_Y, 0, 0x1750, 4, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 0xff, 0, 0); usb_fill_int_urb(kbtab->irq, dev, usb_rcvintpipe(dev, endpoint->bEndpointAddress), kbtab->data, 8, kbtab_irq, kbtab, endpoint->bInterval); kbtab->irq->transfer_dma = kbtab->data_dma; kbtab->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; error = input_register_device(kbtab->dev); if (error) goto fail3; usb_set_intfdata(intf, kbtab); return 0; fail3: usb_free_urb(kbtab->irq); fail2: usb_free_coherent(dev, 8, kbtab->data, kbtab->data_dma); fail1: input_free_device(input_dev); kfree(kbtab); return error; } static void kbtab_disconnect(struct usb_interface *intf) { struct kbtab *kbtab = usb_get_intfdata(intf); struct usb_device *udev = interface_to_usbdev(intf); usb_set_intfdata(intf, NULL); input_unregister_device(kbtab->dev); usb_free_urb(kbtab->irq); usb_free_coherent(udev, 8, kbtab->data, kbtab->data_dma); kfree(kbtab); } static struct usb_driver kbtab_driver = { .name = "kbtab", .probe = kbtab_probe, .disconnect = kbtab_disconnect, .id_table = kbtab_ids, }; module_usb_driver(kbtab_driver);
linux-master
drivers/input/tablet/kbtab.c
// SPDX-License-Identifier: GPL-2.0-only /* * Pegasus Mobile Notetaker Pen input tablet driver * * Copyright (c) 2016 Martin Kepplinger <[email protected]> */ /* * request packet (control endpoint): * |-------------------------------------| * | Report ID | Nr of bytes | command | * | (1 byte) | (1 byte) | (n bytes) | * |-------------------------------------| * | 0x02 | n | | * |-------------------------------------| * * data packet after set xy mode command, 0x80 0xb5 0x02 0x01 * and pen is in range: * * byte byte name value (bits) * -------------------------------------------- * 0 status 0 1 0 0 0 0 X X * 1 color 0 0 0 0 H 0 S T * 2 X low * 3 X high * 4 Y low * 5 Y high * * X X battery state: * no state reported 0x00 * battery low 0x01 * battery good 0x02 * * H Hovering * S Switch 1 (pen button) * T Tip */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/usb/input.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/mutex.h> /* USB HID defines */ #define USB_REQ_GET_REPORT 0x01 #define USB_REQ_SET_REPORT 0x09 #define USB_VENDOR_ID_PEGASUSTECH 0x0e20 #define USB_DEVICE_ID_PEGASUS_NOTETAKER_EN100 0x0101 /* device specific defines */ #define NOTETAKER_REPORT_ID 0x02 #define NOTETAKER_SET_CMD 0x80 #define NOTETAKER_SET_MODE 0xb5 #define NOTETAKER_LED_MOUSE 0x02 #define PEN_MODE_XY 0x01 #define SPECIAL_COMMAND 0x80 #define BUTTON_PRESSED 0xb5 #define COMMAND_VERSION 0xa9 /* in xy data packet */ #define BATTERY_NO_REPORT 0x40 #define BATTERY_LOW 0x41 #define BATTERY_GOOD 0x42 #define PEN_BUTTON_PRESSED BIT(1) #define PEN_TIP BIT(0) struct pegasus { unsigned char *data; u8 data_len; dma_addr_t data_dma; struct input_dev *dev; struct usb_device *usbdev; struct usb_interface *intf; struct urb *irq; /* serialize access to open/suspend */ struct mutex pm_mutex; bool is_open; char name[128]; char phys[64]; struct work_struct init; }; static int pegasus_control_msg(struct pegasus *pegasus, u8 *data, int len) { const int sizeof_buf = len + 2; int result; int error; u8 *cmd_buf; cmd_buf = kmalloc(sizeof_buf, GFP_KERNEL); if (!cmd_buf) return -ENOMEM; cmd_buf[0] = NOTETAKER_REPORT_ID; cmd_buf[1] = len; memcpy(cmd_buf + 2, data, len); result = usb_control_msg(pegasus->usbdev, usb_sndctrlpipe(pegasus->usbdev, 0), USB_REQ_SET_REPORT, USB_TYPE_VENDOR | USB_DIR_OUT, 0, 0, cmd_buf, sizeof_buf, USB_CTRL_SET_TIMEOUT); kfree(cmd_buf); if (unlikely(result != sizeof_buf)) { error = result < 0 ? result : -EIO; dev_err(&pegasus->usbdev->dev, "control msg error: %d\n", error); return error; } return 0; } static int pegasus_set_mode(struct pegasus *pegasus, u8 mode, u8 led) { u8 cmd[] = { NOTETAKER_SET_CMD, NOTETAKER_SET_MODE, led, mode }; return pegasus_control_msg(pegasus, cmd, sizeof(cmd)); } static void pegasus_parse_packet(struct pegasus *pegasus) { unsigned char *data = pegasus->data; struct input_dev *dev = pegasus->dev; u16 x, y; switch (data[0]) { case SPECIAL_COMMAND: /* device button pressed */ if (data[1] == BUTTON_PRESSED) schedule_work(&pegasus->init); break; /* xy data */ case BATTERY_LOW: dev_warn_once(&dev->dev, "Pen battery low\n"); fallthrough; case BATTERY_NO_REPORT: case BATTERY_GOOD: x = le16_to_cpup((__le16 *)&data[2]); y = le16_to_cpup((__le16 *)&data[4]); /* pen-up event */ if (x == 0 && y == 0) break; input_report_key(dev, BTN_TOUCH, data[1] & PEN_TIP); input_report_key(dev, BTN_RIGHT, data[1] & PEN_BUTTON_PRESSED); input_report_key(dev, BTN_TOOL_PEN, 1); input_report_abs(dev, ABS_X, (s16)x); input_report_abs(dev, ABS_Y, y); input_sync(dev); break; default: dev_warn_once(&pegasus->usbdev->dev, "unknown answer from device\n"); } } static void pegasus_irq(struct urb *urb) { struct pegasus *pegasus = urb->context; struct usb_device *dev = pegasus->usbdev; int retval; switch (urb->status) { case 0: pegasus_parse_packet(pegasus); usb_mark_last_busy(pegasus->usbdev); break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: dev_err(&dev->dev, "%s - urb shutting down with status: %d", __func__, urb->status); return; default: dev_err(&dev->dev, "%s - nonzero urb status received: %d", __func__, urb->status); break; } retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&dev->dev, "%s - usb_submit_urb failed with result %d", __func__, retval); } static void pegasus_init(struct work_struct *work) { struct pegasus *pegasus = container_of(work, struct pegasus, init); int error; error = pegasus_set_mode(pegasus, PEN_MODE_XY, NOTETAKER_LED_MOUSE); if (error) dev_err(&pegasus->usbdev->dev, "pegasus_set_mode error: %d\n", error); } static int pegasus_open(struct input_dev *dev) { struct pegasus *pegasus = input_get_drvdata(dev); int error; error = usb_autopm_get_interface(pegasus->intf); if (error) return error; mutex_lock(&pegasus->pm_mutex); pegasus->irq->dev = pegasus->usbdev; if (usb_submit_urb(pegasus->irq, GFP_KERNEL)) { error = -EIO; goto err_autopm_put; } error = pegasus_set_mode(pegasus, PEN_MODE_XY, NOTETAKER_LED_MOUSE); if (error) goto err_kill_urb; pegasus->is_open = true; mutex_unlock(&pegasus->pm_mutex); return 0; err_kill_urb: usb_kill_urb(pegasus->irq); cancel_work_sync(&pegasus->init); err_autopm_put: mutex_unlock(&pegasus->pm_mutex); usb_autopm_put_interface(pegasus->intf); return error; } static void pegasus_close(struct input_dev *dev) { struct pegasus *pegasus = input_get_drvdata(dev); mutex_lock(&pegasus->pm_mutex); usb_kill_urb(pegasus->irq); cancel_work_sync(&pegasus->init); pegasus->is_open = false; mutex_unlock(&pegasus->pm_mutex); usb_autopm_put_interface(pegasus->intf); } static int pegasus_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct pegasus *pegasus; struct input_dev *input_dev; int error; int pipe; /* We control interface 0 */ if (intf->cur_altsetting->desc.bInterfaceNumber >= 1) return -ENODEV; /* Sanity check that the device has an endpoint */ if (intf->cur_altsetting->desc.bNumEndpoints < 1) { dev_err(&intf->dev, "Invalid number of endpoints\n"); return -EINVAL; } endpoint = &intf->cur_altsetting->endpoint[0].desc; pegasus = kzalloc(sizeof(*pegasus), GFP_KERNEL); input_dev = input_allocate_device(); if (!pegasus || !input_dev) { error = -ENOMEM; goto err_free_mem; } mutex_init(&pegasus->pm_mutex); pegasus->usbdev = dev; pegasus->dev = input_dev; pegasus->intf = intf; pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress); /* Sanity check that pipe's type matches endpoint's type */ if (usb_pipe_type_check(dev, pipe)) { error = -EINVAL; goto err_free_mem; } pegasus->data_len = usb_maxpacket(dev, pipe); pegasus->data = usb_alloc_coherent(dev, pegasus->data_len, GFP_KERNEL, &pegasus->data_dma); if (!pegasus->data) { error = -ENOMEM; goto err_free_mem; } pegasus->irq = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->irq) { error = -ENOMEM; goto err_free_dma; } usb_fill_int_urb(pegasus->irq, dev, pipe, pegasus->data, pegasus->data_len, pegasus_irq, pegasus, endpoint->bInterval); pegasus->irq->transfer_dma = pegasus->data_dma; pegasus->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (dev->manufacturer) strscpy(pegasus->name, dev->manufacturer, sizeof(pegasus->name)); if (dev->product) { if (dev->manufacturer) strlcat(pegasus->name, " ", sizeof(pegasus->name)); strlcat(pegasus->name, dev->product, sizeof(pegasus->name)); } if (!strlen(pegasus->name)) snprintf(pegasus->name, sizeof(pegasus->name), "USB Pegasus Device %04x:%04x", le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); usb_make_path(dev, pegasus->phys, sizeof(pegasus->phys)); strlcat(pegasus->phys, "/input0", sizeof(pegasus->phys)); INIT_WORK(&pegasus->init, pegasus_init); usb_set_intfdata(intf, pegasus); input_dev->name = pegasus->name; input_dev->phys = pegasus->phys; usb_to_input_id(dev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, pegasus); input_dev->open = pegasus_open; input_dev->close = pegasus_close; __set_bit(EV_ABS, input_dev->evbit); __set_bit(EV_KEY, input_dev->evbit); __set_bit(ABS_X, input_dev->absbit); __set_bit(ABS_Y, input_dev->absbit); __set_bit(BTN_TOUCH, input_dev->keybit); __set_bit(BTN_RIGHT, input_dev->keybit); __set_bit(BTN_TOOL_PEN, input_dev->keybit); __set_bit(INPUT_PROP_DIRECT, input_dev->propbit); __set_bit(INPUT_PROP_POINTER, input_dev->propbit); input_set_abs_params(input_dev, ABS_X, -1500, 1500, 8, 0); input_set_abs_params(input_dev, ABS_Y, 1600, 3000, 8, 0); error = input_register_device(pegasus->dev); if (error) goto err_free_urb; return 0; err_free_urb: usb_free_urb(pegasus->irq); err_free_dma: usb_free_coherent(dev, pegasus->data_len, pegasus->data, pegasus->data_dma); err_free_mem: input_free_device(input_dev); kfree(pegasus); usb_set_intfdata(intf, NULL); return error; } static void pegasus_disconnect(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); input_unregister_device(pegasus->dev); usb_free_urb(pegasus->irq); usb_free_coherent(interface_to_usbdev(intf), pegasus->data_len, pegasus->data, pegasus->data_dma); kfree(pegasus); usb_set_intfdata(intf, NULL); } static int pegasus_suspend(struct usb_interface *intf, pm_message_t message) { struct pegasus *pegasus = usb_get_intfdata(intf); mutex_lock(&pegasus->pm_mutex); usb_kill_urb(pegasus->irq); cancel_work_sync(&pegasus->init); mutex_unlock(&pegasus->pm_mutex); return 0; } static int pegasus_resume(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); int retval = 0; mutex_lock(&pegasus->pm_mutex); if (pegasus->is_open && usb_submit_urb(pegasus->irq, GFP_NOIO) < 0) retval = -EIO; mutex_unlock(&pegasus->pm_mutex); return retval; } static int pegasus_reset_resume(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); int retval = 0; mutex_lock(&pegasus->pm_mutex); if (pegasus->is_open) { retval = pegasus_set_mode(pegasus, PEN_MODE_XY, NOTETAKER_LED_MOUSE); if (!retval && usb_submit_urb(pegasus->irq, GFP_NOIO) < 0) retval = -EIO; } mutex_unlock(&pegasus->pm_mutex); return retval; } static const struct usb_device_id pegasus_ids[] = { { USB_DEVICE(USB_VENDOR_ID_PEGASUSTECH, USB_DEVICE_ID_PEGASUS_NOTETAKER_EN100) }, { } }; MODULE_DEVICE_TABLE(usb, pegasus_ids); static struct usb_driver pegasus_driver = { .name = "pegasus_notetaker", .probe = pegasus_probe, .disconnect = pegasus_disconnect, .suspend = pegasus_suspend, .resume = pegasus_resume, .reset_resume = pegasus_reset_resume, .id_table = pegasus_ids, .supports_autosuspend = 1, }; module_usb_driver(pegasus_driver); MODULE_AUTHOR("Martin Kepplinger <[email protected]>"); MODULE_DESCRIPTION("Pegasus Mobile Notetaker Pen tablet driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/tablet/pegasus_notetaker.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Wacom protocol 4 serial tablet driver * * Copyright 2014 Hans de Goede <[email protected]> * Copyright 2011-2012 Julian Squires <[email protected]> * * Many thanks to Bill Seremetis, without whom PenPartner support * would not have been possible. Thanks to Patrick Mahoney. * * This driver was developed with reference to much code written by others, * particularly: * - elo, gunze drivers by Vojtech Pavlik <[email protected]>; * - wacom_w8001 driver by Jaya Kumar <[email protected]>; * - the USB wacom input driver, credited to many people * (see drivers/input/tablet/wacom.h); * - new and old versions of linuxwacom / xf86-input-wacom credited to * Frederic Lepied, France. <[email protected]> and * Ping Cheng, Wacom. <[email protected]>; * - and xf86wacom.c (a presumably ancient version of the linuxwacom code), * by Frederic Lepied and Raph Levien <[email protected]>. * * To do: * - support pad buttons; (requires access to a model with pad buttons) * - support (protocol 4-style) tilt (requires access to a > 1.4 rom model) */ /* * Wacom serial protocol 4 documentation taken from linuxwacom-0.9.9 code, * protocol 4 uses 7 or 9 byte of data in the following format: * * Byte 1 * bit 7 Sync bit always 1 * bit 6 Pointing device detected * bit 5 Cursor = 0 / Stylus = 1 * bit 4 Reserved * bit 3 1 if a button on the pointing device has been pressed * bit 2 P0 (optional) * bit 1 X15 * bit 0 X14 * * Byte 2 * bit 7 Always 0 * bits 6-0 = X13 - X7 * * Byte 3 * bit 7 Always 0 * bits 6-0 = X6 - X0 * * Byte 4 * bit 7 Always 0 * bit 6 B3 * bit 5 B2 * bit 4 B1 * bit 3 B0 * bit 2 P1 (optional) * bit 1 Y15 * bit 0 Y14 * * Byte 5 * bit 7 Always 0 * bits 6-0 = Y13 - Y7 * * Byte 6 * bit 7 Always 0 * bits 6-0 = Y6 - Y0 * * Byte 7 * bit 7 Always 0 * bit 6 Sign of pressure data; or wheel-rel for cursor tool * bit 5 P7; or REL1 for cursor tool * bit 4 P6; or REL0 for cursor tool * bit 3 P5 * bit 2 P4 * bit 1 P3 * bit 0 P2 * * byte 8 and 9 are optional and present only * in tilt mode. * * Byte 8 * bit 7 Always 0 * bit 6 Sign of tilt X * bit 5 Xt6 * bit 4 Xt5 * bit 3 Xt4 * bit 2 Xt3 * bit 1 Xt2 * bit 0 Xt1 * * Byte 9 * bit 7 Always 0 * bit 6 Sign of tilt Y * bit 5 Yt6 * bit 4 Yt5 * bit 3 Yt4 * bit 2 Yt3 * bit 1 Yt2 * bit 0 Yt1 */ #include <linux/completion.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/serio.h> #include <linux/slab.h> #include <linux/string.h> MODULE_AUTHOR("Julian Squires <[email protected]>, Hans de Goede <[email protected]>"); MODULE_DESCRIPTION("Wacom protocol 4 serial tablet driver"); MODULE_LICENSE("GPL"); #define REQUEST_MODEL_AND_ROM_VERSION "~#" #define REQUEST_MAX_COORDINATES "~C\r" #define REQUEST_CONFIGURATION_STRING "~R\r" #define REQUEST_RESET_TO_PROTOCOL_IV "\r#" /* * Note: sending "\r$\r" causes at least the Digitizer II to send * packets in ASCII instead of binary. "\r#" seems to undo that. */ #define COMMAND_START_SENDING_PACKETS "ST\r" #define COMMAND_STOP_SENDING_PACKETS "SP\r" #define COMMAND_MULTI_MODE_INPUT "MU1\r" #define COMMAND_ORIGIN_IN_UPPER_LEFT "OC1\r" #define COMMAND_ENABLE_ALL_MACRO_BUTTONS "~M0\r" #define COMMAND_DISABLE_GROUP_1_MACRO_BUTTONS "~M1\r" #define COMMAND_TRANSMIT_AT_MAX_RATE "IT0\r" #define COMMAND_DISABLE_INCREMENTAL_MODE "IN0\r" #define COMMAND_ENABLE_CONTINUOUS_MODE "SR\r" #define COMMAND_ENABLE_PRESSURE_MODE "PH1\r" #define COMMAND_Z_FILTER "ZF1\r" /* Note that this is a protocol 4 packet without tilt information. */ #define PACKET_LENGTH 7 #define DATA_SIZE 32 /* flags */ #define F_COVERS_SCREEN 0x01 #define F_HAS_STYLUS2 0x02 #define F_HAS_SCROLLWHEEL 0x04 /* device IDs */ #define STYLUS_DEVICE_ID 0x02 #define CURSOR_DEVICE_ID 0x06 #define ERASER_DEVICE_ID 0x0A enum { STYLUS = 1, ERASER, CURSOR }; static const struct { int device_id; int input_id; } tools[] = { { 0, 0 }, { STYLUS_DEVICE_ID, BTN_TOOL_PEN }, { ERASER_DEVICE_ID, BTN_TOOL_RUBBER }, { CURSOR_DEVICE_ID, BTN_TOOL_MOUSE }, }; struct wacom { struct input_dev *dev; struct completion cmd_done; int result; u8 expect; u8 eraser_mask; unsigned int extra_z_bits; unsigned int flags; unsigned int res_x, res_y; unsigned int max_x, max_y; unsigned int tool; unsigned int idx; u8 data[DATA_SIZE]; char phys[32]; }; enum { MODEL_CINTIQ = 0x504C, /* PL */ MODEL_CINTIQ2 = 0x4454, /* DT */ MODEL_DIGITIZER_II = 0x5544, /* UD */ MODEL_GRAPHIRE = 0x4554, /* ET */ MODEL_PENPARTNER = 0x4354, /* CT */ MODEL_ARTPAD_II = 0x4B54, /* KT */ }; static void wacom_handle_model_response(struct wacom *wacom) { int major_v, minor_v, r = 0; char *p; p = strrchr(wacom->data, 'V'); if (p) r = sscanf(p + 1, "%u.%u", &major_v, &minor_v); if (r != 2) major_v = minor_v = 0; switch (wacom->data[2] << 8 | wacom->data[3]) { case MODEL_CINTIQ: /* UNTESTED */ case MODEL_CINTIQ2: if ((wacom->data[2] << 8 | wacom->data[3]) == MODEL_CINTIQ) { wacom->dev->name = "Wacom Cintiq"; wacom->dev->id.version = MODEL_CINTIQ; } else { wacom->dev->name = "Wacom Cintiq II"; wacom->dev->id.version = MODEL_CINTIQ2; } wacom->res_x = 508; wacom->res_y = 508; switch (wacom->data[5] << 8 | wacom->data[6]) { case 0x3731: /* PL-710 */ wacom->res_x = 2540; wacom->res_y = 2540; fallthrough; case 0x3535: /* PL-550 */ case 0x3830: /* PL-800 */ wacom->extra_z_bits = 2; } wacom->flags = F_COVERS_SCREEN; break; case MODEL_PENPARTNER: wacom->dev->name = "Wacom Penpartner"; wacom->dev->id.version = MODEL_PENPARTNER; wacom->res_x = 1000; wacom->res_y = 1000; break; case MODEL_GRAPHIRE: wacom->dev->name = "Wacom Graphire"; wacom->dev->id.version = MODEL_GRAPHIRE; wacom->res_x = 1016; wacom->res_y = 1016; wacom->max_x = 5103; wacom->max_y = 3711; wacom->extra_z_bits = 2; wacom->eraser_mask = 0x08; wacom->flags = F_HAS_STYLUS2 | F_HAS_SCROLLWHEEL; break; case MODEL_ARTPAD_II: case MODEL_DIGITIZER_II: wacom->dev->name = "Wacom Digitizer II"; wacom->dev->id.version = MODEL_DIGITIZER_II; if (major_v == 1 && minor_v <= 2) wacom->extra_z_bits = 0; /* UNTESTED */ break; default: dev_err(&wacom->dev->dev, "Unsupported Wacom model %s\n", wacom->data); wacom->result = -ENODEV; return; } dev_info(&wacom->dev->dev, "%s tablet, version %u.%u\n", wacom->dev->name, major_v, minor_v); } static void wacom_handle_configuration_response(struct wacom *wacom) { int r, skip; dev_dbg(&wacom->dev->dev, "Configuration string: %s\n", wacom->data); r = sscanf(wacom->data, "~R%x,%u,%u,%u,%u", &skip, &skip, &skip, &wacom->res_x, &wacom->res_y); if (r != 5) dev_warn(&wacom->dev->dev, "could not get resolution\n"); } static void wacom_handle_coordinates_response(struct wacom *wacom) { int r; dev_dbg(&wacom->dev->dev, "Coordinates string: %s\n", wacom->data); r = sscanf(wacom->data, "~C%u,%u", &wacom->max_x, &wacom->max_y); if (r != 2) dev_warn(&wacom->dev->dev, "could not get max coordinates\n"); } static void wacom_handle_response(struct wacom *wacom) { if (wacom->data[0] != '~' || wacom->data[1] != wacom->expect) { dev_err(&wacom->dev->dev, "Wacom got an unexpected response: %s\n", wacom->data); wacom->result = -EIO; } else { wacom->result = 0; switch (wacom->data[1]) { case '#': wacom_handle_model_response(wacom); break; case 'R': wacom_handle_configuration_response(wacom); break; case 'C': wacom_handle_coordinates_response(wacom); break; } } complete(&wacom->cmd_done); } static void wacom_handle_packet(struct wacom *wacom) { u8 in_proximity_p, stylus_p, button; unsigned int tool; int x, y, z; in_proximity_p = wacom->data[0] & 0x40; stylus_p = wacom->data[0] & 0x20; button = (wacom->data[3] & 0x78) >> 3; x = (wacom->data[0] & 3) << 14 | wacom->data[1]<<7 | wacom->data[2]; y = (wacom->data[3] & 3) << 14 | wacom->data[4]<<7 | wacom->data[5]; if (in_proximity_p && stylus_p) { z = wacom->data[6] & 0x7f; if (wacom->extra_z_bits >= 1) z = z << 1 | (wacom->data[3] & 0x4) >> 2; if (wacom->extra_z_bits > 1) z = z << 1 | (wacom->data[0] & 0x4) >> 2; z = z ^ (0x40 << wacom->extra_z_bits); } else { z = -1; } if (stylus_p) tool = (button & wacom->eraser_mask) ? ERASER : STYLUS; else tool = CURSOR; if (tool != wacom->tool && wacom->tool != 0) { input_report_key(wacom->dev, tools[wacom->tool].input_id, 0); input_sync(wacom->dev); } wacom->tool = tool; input_report_key(wacom->dev, tools[tool].input_id, in_proximity_p); input_report_abs(wacom->dev, ABS_MISC, in_proximity_p ? tools[tool].device_id : 0); input_report_abs(wacom->dev, ABS_X, x); input_report_abs(wacom->dev, ABS_Y, y); input_report_abs(wacom->dev, ABS_PRESSURE, z); if (stylus_p) { input_report_key(wacom->dev, BTN_TOUCH, button & 1); input_report_key(wacom->dev, BTN_STYLUS, button & 2); input_report_key(wacom->dev, BTN_STYLUS2, button & 4); } else { input_report_key(wacom->dev, BTN_LEFT, button & 1); input_report_key(wacom->dev, BTN_RIGHT, button & 2); input_report_key(wacom->dev, BTN_MIDDLE, button & 4); /* handle relative wheel for non-stylus device */ z = (wacom->data[6] & 0x30) >> 4; if (wacom->data[6] & 0x40) z = -z; input_report_rel(wacom->dev, REL_WHEEL, z); } input_sync(wacom->dev); } static void wacom_clear_data_buf(struct wacom *wacom) { memset(wacom->data, 0, DATA_SIZE); wacom->idx = 0; } static irqreturn_t wacom_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct wacom *wacom = serio_get_drvdata(serio); if (data & 0x80) wacom->idx = 0; /* * We're either expecting a carriage return-terminated ASCII * response string, or a seven-byte packet with the MSB set on * the first byte. * * Note however that some tablets (the PenPartner, for * example) don't send a carriage return at the end of a * command. We handle these by waiting for timeout. */ if (data == '\r' && !(wacom->data[0] & 0x80)) { wacom_handle_response(wacom); wacom_clear_data_buf(wacom); return IRQ_HANDLED; } /* Leave place for 0 termination */ if (wacom->idx > (DATA_SIZE - 2)) { dev_dbg(&wacom->dev->dev, "throwing away %d bytes of garbage\n", wacom->idx); wacom_clear_data_buf(wacom); } wacom->data[wacom->idx++] = data; if (wacom->idx == PACKET_LENGTH && (wacom->data[0] & 0x80)) { wacom_handle_packet(wacom); wacom_clear_data_buf(wacom); } return IRQ_HANDLED; } static void wacom_disconnect(struct serio *serio) { struct wacom *wacom = serio_get_drvdata(serio); serio_close(serio); serio_set_drvdata(serio, NULL); input_unregister_device(wacom->dev); kfree(wacom); } static int wacom_send(struct serio *serio, const u8 *command) { int err = 0; for (; !err && *command; command++) err = serio_write(serio, *command); return err; } static int wacom_send_setup_string(struct wacom *wacom, struct serio *serio) { const u8 *cmd; switch (wacom->dev->id.version) { case MODEL_CINTIQ: /* UNTESTED */ cmd = COMMAND_ORIGIN_IN_UPPER_LEFT COMMAND_TRANSMIT_AT_MAX_RATE COMMAND_ENABLE_CONTINUOUS_MODE COMMAND_START_SENDING_PACKETS; break; case MODEL_PENPARTNER: cmd = COMMAND_ENABLE_PRESSURE_MODE COMMAND_START_SENDING_PACKETS; break; default: cmd = COMMAND_MULTI_MODE_INPUT COMMAND_ORIGIN_IN_UPPER_LEFT COMMAND_ENABLE_ALL_MACRO_BUTTONS COMMAND_DISABLE_GROUP_1_MACRO_BUTTONS COMMAND_TRANSMIT_AT_MAX_RATE COMMAND_DISABLE_INCREMENTAL_MODE COMMAND_ENABLE_CONTINUOUS_MODE COMMAND_Z_FILTER COMMAND_START_SENDING_PACKETS; break; } return wacom_send(serio, cmd); } static int wacom_send_and_wait(struct wacom *wacom, struct serio *serio, const u8 *cmd, const char *desc) { int err; unsigned long u; wacom->expect = cmd[1]; init_completion(&wacom->cmd_done); err = wacom_send(serio, cmd); if (err) return err; u = wait_for_completion_timeout(&wacom->cmd_done, HZ); if (u == 0) { /* Timeout, process what we've received. */ wacom_handle_response(wacom); } wacom->expect = 0; return wacom->result; } static int wacom_setup(struct wacom *wacom, struct serio *serio) { int err; /* Note that setting the link speed is the job of inputattach. * We assume that reset negotiation has already happened, * here. */ err = wacom_send_and_wait(wacom, serio, REQUEST_MODEL_AND_ROM_VERSION, "model and version"); if (err) return err; if (!(wacom->res_x && wacom->res_y)) { err = wacom_send_and_wait(wacom, serio, REQUEST_CONFIGURATION_STRING, "configuration string"); if (err) return err; } if (!(wacom->max_x && wacom->max_y)) { err = wacom_send_and_wait(wacom, serio, REQUEST_MAX_COORDINATES, "coordinates string"); if (err) return err; } return wacom_send_setup_string(wacom, serio); } static int wacom_connect(struct serio *serio, struct serio_driver *drv) { struct wacom *wacom; struct input_dev *input_dev; int err = -ENOMEM; wacom = kzalloc(sizeof(struct wacom), GFP_KERNEL); input_dev = input_allocate_device(); if (!wacom || !input_dev) goto free_device; wacom->dev = input_dev; wacom->extra_z_bits = 1; wacom->eraser_mask = 0x04; wacom->tool = wacom->idx = 0; snprintf(wacom->phys, sizeof(wacom->phys), "%s/input0", serio->phys); input_dev->phys = wacom->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_WACOM_IV; input_dev->id.product = serio->id.extra; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) | BIT_MASK(EV_REL); set_bit(ABS_MISC, input_dev->absbit); set_bit(BTN_TOOL_PEN, input_dev->keybit); set_bit(BTN_TOOL_RUBBER, input_dev->keybit); set_bit(BTN_TOOL_MOUSE, input_dev->keybit); set_bit(BTN_TOUCH, input_dev->keybit); set_bit(BTN_STYLUS, input_dev->keybit); set_bit(BTN_LEFT, input_dev->keybit); set_bit(BTN_RIGHT, input_dev->keybit); set_bit(BTN_MIDDLE, input_dev->keybit); serio_set_drvdata(serio, wacom); err = serio_open(serio, drv); if (err) goto free_device; err = wacom_setup(wacom, serio); if (err) goto close_serio; set_bit(INPUT_PROP_DIRECT, input_dev->propbit); if (!(wacom->flags & F_COVERS_SCREEN)) __set_bit(INPUT_PROP_POINTER, input_dev->propbit); if (wacom->flags & F_HAS_STYLUS2) __set_bit(BTN_STYLUS2, input_dev->keybit); if (wacom->flags & F_HAS_SCROLLWHEEL) __set_bit(REL_WHEEL, input_dev->relbit); input_abs_set_res(wacom->dev, ABS_X, wacom->res_x); input_abs_set_res(wacom->dev, ABS_Y, wacom->res_y); input_set_abs_params(wacom->dev, ABS_X, 0, wacom->max_x, 0, 0); input_set_abs_params(wacom->dev, ABS_Y, 0, wacom->max_y, 0, 0); input_set_abs_params(wacom->dev, ABS_PRESSURE, -1, (1 << (7 + wacom->extra_z_bits)) - 1, 0, 0); err = input_register_device(wacom->dev); if (err) goto close_serio; return 0; close_serio: serio_close(serio); free_device: serio_set_drvdata(serio, NULL); input_free_device(input_dev); kfree(wacom); return err; } static const struct serio_device_id wacom_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_WACOM_IV, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, wacom_serio_ids); static struct serio_driver wacom_drv = { .driver = { .name = "wacom_serial4", }, .description = "Wacom protocol 4 serial tablet driver", .id_table = wacom_serio_ids, .interrupt = wacom_interrupt, .connect = wacom_connect, .disconnect = wacom_disconnect, }; module_serio_driver(wacom_drv);
linux-master
drivers/input/tablet/wacom_serial4.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Native support for the Aiptek HyperPen USB Tablets * (4000U/5000U/6000U/8000U/12000U) * * Copyright (c) 2001 Chris Atenasio <[email protected]> * Copyright (c) 2002-2004 Bryan W. Headley <[email protected]> * * based on wacom.c by * Vojtech Pavlik <[email protected]> * Andreas Bach Aaen <[email protected]> * Clifford Wolf <[email protected]> * Sam Mosel <[email protected]> * James E. Blair <[email protected]> * Daniel Egger <[email protected]> * * Many thanks to Oliver Kuechemann for his support. * * ChangeLog: * v0.1 - Initial release * v0.2 - Hack to get around fake event 28's. (Bryan W. Headley) * v0.3 - Make URB dynamic (Bryan W. Headley, Jun-8-2002) * Released to Linux 2.4.19 and 2.5.x * v0.4 - Rewrote substantial portions of the code to deal with * corrected control sequences, timing, dynamic configuration, * support of 6000U - 12000U, procfs, and macro key support * (Jan-1-2003 - Feb-5-2003, Bryan W. Headley) * v1.0 - Added support for diagnostic messages, count of messages * received from URB - Mar-8-2003, Bryan W. Headley * v1.1 - added support for tablet resolution, changed DV and proximity * some corrections - Jun-22-2003, martin schneebacher * - Added support for the sysfs interface, deprecating the * procfs interface for 2.5.x kernel. Also added support for * Wheel command. Bryan W. Headley July-15-2003. * v1.2 - Reworked jitter timer as a kernel thread. * Bryan W. Headley November-28-2003/Jan-10-2004. * v1.3 - Repaired issue of kernel thread going nuts on single-processor * machines, introduced programmableDelay as a command line * parameter. Feb 7 2004, Bryan W. Headley. * v1.4 - Re-wire jitter so it does not require a thread. Courtesy of * Rene van Paassen. Added reporting of physical pointer device * (e.g., stylus, mouse in reports 2, 3, 4, 5. We don't know * for reports 1, 6.) * what physical device reports for reports 1, 6.) Also enabled * MOUSE and LENS tool button modes. Renamed "rubber" to "eraser". * Feb 20, 2004, Bryan W. Headley. * v1.5 - Added previousJitterable, so we don't do jitter delay when the * user is holding a button down for periods of time. * * NOTE: * This kernel driver is augmented by the "Aiptek" XFree86 input * driver for your X server, as well as the Gaiptek GUI Front-end * "Tablet Manager". * These three products are highly interactive with one another, * so therefore it's easier to document them all as one subsystem. * Please visit the project's "home page", located at, * http://aiptektablet.sourceforge.net. */ #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> #include <linux/uaccess.h> #include <asm/unaligned.h> /* * Aiptek status packet: * * (returned as Report 1 - relative coordinates from mouse and stylus) * * bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 * byte0 0 0 0 0 0 0 0 1 * byte1 0 0 0 0 0 BS2 BS Tip * byte2 X7 X6 X5 X4 X3 X2 X1 X0 * byte3 Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * * (returned as Report 2 - absolute coordinates from the stylus) * * bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 * byte0 0 0 0 0 0 0 1 0 * byte1 X7 X6 X5 X4 X3 X2 X1 X0 * byte2 X15 X14 X13 X12 X11 X10 X9 X8 * byte3 Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * byte4 Y15 Y14 Y13 Y12 Y11 Y10 Y9 Y8 * byte5 * * * BS2 BS1 Tip IR DV * byte6 P7 P6 P5 P4 P3 P2 P1 P0 * byte7 P15 P14 P13 P12 P11 P10 P9 P8 * * (returned as Report 3 - absolute coordinates from the mouse) * * bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 * byte0 0 0 0 0 0 0 1 1 * byte1 X7 X6 X5 X4 X3 X2 X1 X0 * byte2 X15 X14 X13 X12 X11 X10 X9 X8 * byte3 Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * byte4 Y15 Y14 Y13 Y12 Y11 Y10 Y9 Y8 * byte5 * * * BS2 BS1 Tip IR DV * byte6 P7 P6 P5 P4 P3 P2 P1 P0 * byte7 P15 P14 P13 P12 P11 P10 P9 P8 * * (returned as Report 4 - macrokeys from the stylus) * * bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 * byte0 0 0 0 0 0 1 0 0 * byte1 0 0 0 BS2 BS Tip IR DV * byte2 0 0 0 0 0 0 1 0 * byte3 0 0 0 K4 K3 K2 K1 K0 * byte4 P7 P6 P5 P4 P3 P2 P1 P0 * byte5 P15 P14 P13 P12 P11 P10 P9 P8 * * (returned as Report 5 - macrokeys from the mouse) * * bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 * byte0 0 0 0 0 0 1 0 1 * byte1 0 0 0 BS2 BS Tip IR DV * byte2 0 0 0 0 0 0 1 0 * byte3 0 0 0 K4 K3 K2 K1 K0 * byte4 P7 P6 P5 P4 P3 P2 P1 P0 * byte5 P15 P14 P13 P12 P11 P10 P9 P8 * * IR: In Range = Proximity on * DV = Data Valid * BS = Barrel Switch (as in, macro keys) * BS2 also referred to as Tablet Pick * * Command Summary: * * Use report_type CONTROL (3) * Use report_id 2 * * Command/Data Description Return Bytes Return Value * 0x10/0x00 SwitchToMouse 0 * 0x10/0x01 SwitchToTablet 0 * 0x18/0x04 SetResolution 0 * 0x12/0xFF AutoGainOn 0 * 0x17/0x00 FilterOn 0 * 0x01/0x00 GetXExtension 2 MaxX * 0x01/0x01 GetYExtension 2 MaxY * 0x02/0x00 GetModelCode 2 ModelCode = LOBYTE * 0x03/0x00 GetODMCode 2 ODMCode * 0x08/0x00 GetPressureLevels 2 =512 * 0x04/0x00 GetFirmwareVersion 2 Firmware Version * 0x11/0x02 EnableMacroKeys 0 * * To initialize the tablet: * * (1) Send Resolution500LPI (Command) * (2) Query for Model code (Option Report) * (3) Query for ODM code (Option Report) * (4) Query for firmware (Option Report) * (5) Query for GetXExtension (Option Report) * (6) Query for GetYExtension (Option Report) * (7) Query for GetPressureLevels (Option Report) * (8) SwitchToTablet for Absolute coordinates, or * SwitchToMouse for Relative coordinates (Command) * (9) EnableMacroKeys (Command) * (10) FilterOn (Command) * (11) AutoGainOn (Command) * * (Step 9 can be omitted, but you'll then have no function keys.) */ #define USB_VENDOR_ID_AIPTEK 0x08ca #define USB_VENDOR_ID_KYE 0x0458 #define USB_REQ_GET_REPORT 0x01 #define USB_REQ_SET_REPORT 0x09 /* PointerMode codes */ #define AIPTEK_POINTER_ONLY_MOUSE_MODE 0 #define AIPTEK_POINTER_ONLY_STYLUS_MODE 1 #define AIPTEK_POINTER_EITHER_MODE 2 #define AIPTEK_POINTER_ALLOW_MOUSE_MODE(a) \ (a == AIPTEK_POINTER_ONLY_MOUSE_MODE || \ a == AIPTEK_POINTER_EITHER_MODE) #define AIPTEK_POINTER_ALLOW_STYLUS_MODE(a) \ (a == AIPTEK_POINTER_ONLY_STYLUS_MODE || \ a == AIPTEK_POINTER_EITHER_MODE) /* CoordinateMode code */ #define AIPTEK_COORDINATE_RELATIVE_MODE 0 #define AIPTEK_COORDINATE_ABSOLUTE_MODE 1 /* XTilt and YTilt values */ #define AIPTEK_TILT_MIN (-128) #define AIPTEK_TILT_MAX 127 #define AIPTEK_TILT_DISABLE (-10101) /* Wheel values */ #define AIPTEK_WHEEL_MIN 0 #define AIPTEK_WHEEL_MAX 1024 #define AIPTEK_WHEEL_DISABLE (-10101) /* ToolCode values, which BTW are 0x140 .. 0x14f * We have things set up such that if the tool button has changed, * the tools get reset. */ /* toolMode codes */ #define AIPTEK_TOOL_BUTTON_PEN_MODE BTN_TOOL_PEN #define AIPTEK_TOOL_BUTTON_PENCIL_MODE BTN_TOOL_PENCIL #define AIPTEK_TOOL_BUTTON_BRUSH_MODE BTN_TOOL_BRUSH #define AIPTEK_TOOL_BUTTON_AIRBRUSH_MODE BTN_TOOL_AIRBRUSH #define AIPTEK_TOOL_BUTTON_ERASER_MODE BTN_TOOL_RUBBER #define AIPTEK_TOOL_BUTTON_MOUSE_MODE BTN_TOOL_MOUSE #define AIPTEK_TOOL_BUTTON_LENS_MODE BTN_TOOL_LENS /* Diagnostic message codes */ #define AIPTEK_DIAGNOSTIC_NA 0 #define AIPTEK_DIAGNOSTIC_SENDING_RELATIVE_IN_ABSOLUTE 1 #define AIPTEK_DIAGNOSTIC_SENDING_ABSOLUTE_IN_RELATIVE 2 #define AIPTEK_DIAGNOSTIC_TOOL_DISALLOWED 3 /* Time to wait (in ms) to help mask hand jittering * when pressing the stylus buttons. */ #define AIPTEK_JITTER_DELAY_DEFAULT 50 /* Time to wait (in ms) in-between sending the tablet * a command and beginning the process of reading the return * sequence from the tablet. */ #define AIPTEK_PROGRAMMABLE_DELAY_25 25 #define AIPTEK_PROGRAMMABLE_DELAY_50 50 #define AIPTEK_PROGRAMMABLE_DELAY_100 100 #define AIPTEK_PROGRAMMABLE_DELAY_200 200 #define AIPTEK_PROGRAMMABLE_DELAY_300 300 #define AIPTEK_PROGRAMMABLE_DELAY_400 400 #define AIPTEK_PROGRAMMABLE_DELAY_DEFAULT AIPTEK_PROGRAMMABLE_DELAY_400 /* Mouse button programming */ #define AIPTEK_MOUSE_LEFT_BUTTON 0x04 #define AIPTEK_MOUSE_RIGHT_BUTTON 0x08 #define AIPTEK_MOUSE_MIDDLE_BUTTON 0x10 /* Stylus button programming */ #define AIPTEK_STYLUS_LOWER_BUTTON 0x08 #define AIPTEK_STYLUS_UPPER_BUTTON 0x10 /* Length of incoming packet from the tablet */ #define AIPTEK_PACKET_LENGTH 8 /* We report in EV_MISC both the proximity and * whether the report came from the stylus, tablet mouse * or "unknown" -- Unknown when the tablet is in relative * mode, because we only get report 1's. */ #define AIPTEK_REPORT_TOOL_UNKNOWN 0x10 #define AIPTEK_REPORT_TOOL_STYLUS 0x20 #define AIPTEK_REPORT_TOOL_MOUSE 0x40 static int programmableDelay = AIPTEK_PROGRAMMABLE_DELAY_DEFAULT; static int jitterDelay = AIPTEK_JITTER_DELAY_DEFAULT; struct aiptek_features { int odmCode; /* Tablet manufacturer code */ int modelCode; /* Tablet model code (not unique) */ int firmwareCode; /* prom/eeprom version */ char usbPath[64 + 1]; /* device's physical usb path */ }; struct aiptek_settings { int pointerMode; /* stylus-, mouse-only or either */ int coordinateMode; /* absolute/relative coords */ int toolMode; /* pen, pencil, brush, etc. tool */ int xTilt; /* synthetic xTilt amount */ int yTilt; /* synthetic yTilt amount */ int wheel; /* synthetic wheel amount */ int stylusButtonUpper; /* stylus upper btn delivers... */ int stylusButtonLower; /* stylus lower btn delivers... */ int mouseButtonLeft; /* mouse left btn delivers... */ int mouseButtonMiddle; /* mouse middle btn delivers... */ int mouseButtonRight; /* mouse right btn delivers... */ int programmableDelay; /* delay for tablet programming */ int jitterDelay; /* delay for hand jittering */ }; struct aiptek { struct input_dev *inputdev; /* input device struct */ struct usb_interface *intf; /* usb interface struct */ struct urb *urb; /* urb for incoming reports */ dma_addr_t data_dma; /* our dma stuffage */ struct aiptek_features features; /* tablet's array of features */ struct aiptek_settings curSetting; /* tablet's current programmable */ struct aiptek_settings newSetting; /* ... and new param settings */ unsigned int ifnum; /* interface number for IO */ int diagnostic; /* tablet diagnostic codes */ unsigned long eventCount; /* event count */ int inDelay; /* jitter: in jitter delay? */ unsigned long endDelay; /* jitter: time when delay ends */ int previousJitterable; /* jitterable prev value */ int lastMacro; /* macro key to reset */ int previousToolMode; /* pen, pencil, brush, etc. tool */ unsigned char *data; /* incoming packet data */ }; static const int eventTypes[] = { EV_KEY, EV_ABS, EV_REL, EV_MSC, }; static const int absEvents[] = { ABS_X, ABS_Y, ABS_PRESSURE, ABS_TILT_X, ABS_TILT_Y, ABS_WHEEL, ABS_MISC, }; static const int relEvents[] = { REL_X, REL_Y, REL_WHEEL, }; static const int buttonEvents[] = { BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_TOOL_PEN, BTN_TOOL_RUBBER, BTN_TOOL_PENCIL, BTN_TOOL_AIRBRUSH, BTN_TOOL_BRUSH, BTN_TOOL_MOUSE, BTN_TOOL_LENS, BTN_TOUCH, BTN_STYLUS, BTN_STYLUS2, }; /* * Permit easy lookup of keyboard events to send, versus * the bitmap which comes from the tablet. This hides the * issue that the F_keys are not sequentially numbered. */ static const int macroKeyEvents[] = { KEY_ESC, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_F13, KEY_F14, KEY_F15, KEY_F16, KEY_F17, KEY_F18, KEY_F19, KEY_F20, KEY_F21, KEY_F22, KEY_F23, KEY_F24, KEY_STOP, KEY_AGAIN, KEY_PROPS, KEY_UNDO, KEY_FRONT, KEY_COPY, KEY_OPEN, KEY_PASTE, 0 }; /*********************************************************************** * Map values to strings and back. Every map should have the following * as its last element: { NULL, AIPTEK_INVALID_VALUE }. */ #define AIPTEK_INVALID_VALUE -1 struct aiptek_map { const char *string; int value; }; static int map_str_to_val(const struct aiptek_map *map, const char *str, size_t count) { const struct aiptek_map *p; if (str[count - 1] == '\n') count--; for (p = map; p->string; p++) if (!strncmp(str, p->string, count)) return p->value; return AIPTEK_INVALID_VALUE; } static const char *map_val_to_str(const struct aiptek_map *map, int val) { const struct aiptek_map *p; for (p = map; p->value != AIPTEK_INVALID_VALUE; p++) if (val == p->value) return p->string; return "unknown"; } /*********************************************************************** * aiptek_irq can receive one of six potential reports. * The documentation for each is in the body of the function. * * The tablet reports on several attributes per invocation of * aiptek_irq. Because the Linux Input Event system allows the * transmission of ONE attribute per input_report_xxx() call, * collation has to be done on the other end to reconstitute * a complete tablet report. Further, the number of Input Event reports * submitted varies, depending on what USB report type, and circumstance. * To deal with this, EV_MSC is used to indicate an 'end-of-report' * message. This has been an undocumented convention understood by the kernel * tablet driver and clients such as gpm and XFree86's tablet drivers. * * Of the information received from the tablet, the one piece I * cannot transmit is the proximity bit (without resorting to an EV_MSC * convention above.) I therefore have taken over REL_MISC and ABS_MISC * (for relative and absolute reports, respectively) for communicating * Proximity. Why two events? I thought it interesting to know if the * Proximity event occurred while the tablet was in absolute or relative * mode. * Update: REL_MISC proved not to be such a good idea. With REL_MISC you * get an event transmitted each time. ABS_MISC works better, since it * can be set and re-set. Thus, only using ABS_MISC from now on. * * Other tablets use the notion of a certain minimum stylus pressure * to infer proximity. While that could have been done, that is yet * another 'by convention' behavior, the documentation for which * would be spread between two (or more) pieces of software. * * EV_MSC usage was terminated for this purpose in Linux 2.5.x, and * replaced with the input_sync() method (which emits EV_SYN.) */ static void aiptek_irq(struct urb *urb) { struct aiptek *aiptek = urb->context; unsigned char *data = aiptek->data; struct input_dev *inputdev = aiptek->inputdev; struct usb_interface *intf = aiptek->intf; int jitterable = 0; int retval, macro, x, y, z, left, right, middle, p, dv, tip, bs, pck; switch (urb->status) { case 0: /* Success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* This urb is terminated, clean up */ dev_dbg(&intf->dev, "%s - urb shutting down with status: %d\n", __func__, urb->status); return; default: dev_dbg(&intf->dev, "%s - nonzero urb status received: %d\n", __func__, urb->status); goto exit; } /* See if we are in a delay loop -- throw out report if true. */ if (aiptek->inDelay == 1 && time_after(aiptek->endDelay, jiffies)) { goto exit; } aiptek->inDelay = 0; aiptek->eventCount++; /* Report 1 delivers relative coordinates with either a stylus * or the mouse. You do not know, however, which input * tool generated the event. */ if (data[0] == 1) { if (aiptek->curSetting.coordinateMode == AIPTEK_COORDINATE_ABSOLUTE_MODE) { aiptek->diagnostic = AIPTEK_DIAGNOSTIC_SENDING_RELATIVE_IN_ABSOLUTE; } else { x = (signed char) data[2]; y = (signed char) data[3]; /* jitterable keeps track of whether any button has been pressed. * We're also using it to remap the physical mouse button mask * to pseudo-settings. (We don't specifically care about it's * value after moving/transposing mouse button bitmasks, except * that a non-zero value indicates that one or more * mouse button was pressed.) */ jitterable = data[1] & 0x07; left = (data[1] & aiptek->curSetting.mouseButtonLeft >> 2) != 0 ? 1 : 0; right = (data[1] & aiptek->curSetting.mouseButtonRight >> 2) != 0 ? 1 : 0; middle = (data[1] & aiptek->curSetting.mouseButtonMiddle >> 2) != 0 ? 1 : 0; input_report_key(inputdev, BTN_LEFT, left); input_report_key(inputdev, BTN_MIDDLE, middle); input_report_key(inputdev, BTN_RIGHT, right); input_report_abs(inputdev, ABS_MISC, 1 | AIPTEK_REPORT_TOOL_UNKNOWN); input_report_rel(inputdev, REL_X, x); input_report_rel(inputdev, REL_Y, y); /* Wheel support is in the form of a single-event * firing. */ if (aiptek->curSetting.wheel != AIPTEK_WHEEL_DISABLE) { input_report_rel(inputdev, REL_WHEEL, aiptek->curSetting.wheel); aiptek->curSetting.wheel = AIPTEK_WHEEL_DISABLE; } if (aiptek->lastMacro != -1) { input_report_key(inputdev, macroKeyEvents[aiptek->lastMacro], 0); aiptek->lastMacro = -1; } input_sync(inputdev); } } /* Report 2 is delivered only by the stylus, and delivers * absolute coordinates. */ else if (data[0] == 2) { if (aiptek->curSetting.coordinateMode == AIPTEK_COORDINATE_RELATIVE_MODE) { aiptek->diagnostic = AIPTEK_DIAGNOSTIC_SENDING_ABSOLUTE_IN_RELATIVE; } else if (!AIPTEK_POINTER_ALLOW_STYLUS_MODE (aiptek->curSetting.pointerMode)) { aiptek->diagnostic = AIPTEK_DIAGNOSTIC_TOOL_DISALLOWED; } else { x = get_unaligned_le16(data + 1); y = get_unaligned_le16(data + 3); z = get_unaligned_le16(data + 6); dv = (data[5] & 0x01) != 0 ? 1 : 0; p = (data[5] & 0x02) != 0 ? 1 : 0; tip = (data[5] & 0x04) != 0 ? 1 : 0; /* Use jitterable to re-arrange button masks */ jitterable = data[5] & 0x18; bs = (data[5] & aiptek->curSetting.stylusButtonLower) != 0 ? 1 : 0; pck = (data[5] & aiptek->curSetting.stylusButtonUpper) != 0 ? 1 : 0; /* dv indicates 'data valid' (e.g., the tablet is in sync * and has delivered a "correct" report) We will ignore * all 'bad' reports... */ if (dv != 0) { /* If the selected tool changed, reset the old * tool key, and set the new one. */ if (aiptek->previousToolMode != aiptek->curSetting.toolMode) { input_report_key(inputdev, aiptek->previousToolMode, 0); input_report_key(inputdev, aiptek->curSetting.toolMode, 1); aiptek->previousToolMode = aiptek->curSetting.toolMode; } if (p != 0) { input_report_abs(inputdev, ABS_X, x); input_report_abs(inputdev, ABS_Y, y); input_report_abs(inputdev, ABS_PRESSURE, z); input_report_key(inputdev, BTN_TOUCH, tip); input_report_key(inputdev, BTN_STYLUS, bs); input_report_key(inputdev, BTN_STYLUS2, pck); if (aiptek->curSetting.xTilt != AIPTEK_TILT_DISABLE) { input_report_abs(inputdev, ABS_TILT_X, aiptek->curSetting.xTilt); } if (aiptek->curSetting.yTilt != AIPTEK_TILT_DISABLE) { input_report_abs(inputdev, ABS_TILT_Y, aiptek->curSetting.yTilt); } /* Wheel support is in the form of a single-event * firing. */ if (aiptek->curSetting.wheel != AIPTEK_WHEEL_DISABLE) { input_report_abs(inputdev, ABS_WHEEL, aiptek->curSetting.wheel); aiptek->curSetting.wheel = AIPTEK_WHEEL_DISABLE; } } input_report_abs(inputdev, ABS_MISC, p | AIPTEK_REPORT_TOOL_STYLUS); if (aiptek->lastMacro != -1) { input_report_key(inputdev, macroKeyEvents[aiptek->lastMacro], 0); aiptek->lastMacro = -1; } input_sync(inputdev); } } } /* Report 3's come from the mouse in absolute mode. */ else if (data[0] == 3) { if (aiptek->curSetting.coordinateMode == AIPTEK_COORDINATE_RELATIVE_MODE) { aiptek->diagnostic = AIPTEK_DIAGNOSTIC_SENDING_ABSOLUTE_IN_RELATIVE; } else if (!AIPTEK_POINTER_ALLOW_MOUSE_MODE (aiptek->curSetting.pointerMode)) { aiptek->diagnostic = AIPTEK_DIAGNOSTIC_TOOL_DISALLOWED; } else { x = get_unaligned_le16(data + 1); y = get_unaligned_le16(data + 3); jitterable = data[5] & 0x1c; dv = (data[5] & 0x01) != 0 ? 1 : 0; p = (data[5] & 0x02) != 0 ? 1 : 0; left = (data[5] & aiptek->curSetting.mouseButtonLeft) != 0 ? 1 : 0; right = (data[5] & aiptek->curSetting.mouseButtonRight) != 0 ? 1 : 0; middle = (data[5] & aiptek->curSetting.mouseButtonMiddle) != 0 ? 1 : 0; if (dv != 0) { /* If the selected tool changed, reset the old * tool key, and set the new one. */ if (aiptek->previousToolMode != aiptek->curSetting.toolMode) { input_report_key(inputdev, aiptek->previousToolMode, 0); input_report_key(inputdev, aiptek->curSetting.toolMode, 1); aiptek->previousToolMode = aiptek->curSetting.toolMode; } if (p != 0) { input_report_abs(inputdev, ABS_X, x); input_report_abs(inputdev, ABS_Y, y); input_report_key(inputdev, BTN_LEFT, left); input_report_key(inputdev, BTN_MIDDLE, middle); input_report_key(inputdev, BTN_RIGHT, right); /* Wheel support is in the form of a single-event * firing. */ if (aiptek->curSetting.wheel != AIPTEK_WHEEL_DISABLE) { input_report_abs(inputdev, ABS_WHEEL, aiptek->curSetting.wheel); aiptek->curSetting.wheel = AIPTEK_WHEEL_DISABLE; } } input_report_abs(inputdev, ABS_MISC, p | AIPTEK_REPORT_TOOL_MOUSE); if (aiptek->lastMacro != -1) { input_report_key(inputdev, macroKeyEvents[aiptek->lastMacro], 0); aiptek->lastMacro = -1; } input_sync(inputdev); } } } /* Report 4s come from the macro keys when pressed by stylus */ else if (data[0] == 4) { jitterable = data[1] & 0x18; dv = (data[1] & 0x01) != 0 ? 1 : 0; p = (data[1] & 0x02) != 0 ? 1 : 0; tip = (data[1] & 0x04) != 0 ? 1 : 0; bs = (data[1] & aiptek->curSetting.stylusButtonLower) != 0 ? 1 : 0; pck = (data[1] & aiptek->curSetting.stylusButtonUpper) != 0 ? 1 : 0; macro = dv && p && tip && !(data[3] & 1) ? (data[3] >> 1) : -1; z = get_unaligned_le16(data + 4); if (dv) { /* If the selected tool changed, reset the old * tool key, and set the new one. */ if (aiptek->previousToolMode != aiptek->curSetting.toolMode) { input_report_key(inputdev, aiptek->previousToolMode, 0); input_report_key(inputdev, aiptek->curSetting.toolMode, 1); aiptek->previousToolMode = aiptek->curSetting.toolMode; } } if (aiptek->lastMacro != -1 && aiptek->lastMacro != macro) { input_report_key(inputdev, macroKeyEvents[aiptek->lastMacro], 0); aiptek->lastMacro = -1; } if (macro != -1 && macro != aiptek->lastMacro) { input_report_key(inputdev, macroKeyEvents[macro], 1); aiptek->lastMacro = macro; } input_report_abs(inputdev, ABS_MISC, p | AIPTEK_REPORT_TOOL_STYLUS); input_sync(inputdev); } /* Report 5s come from the macro keys when pressed by mouse */ else if (data[0] == 5) { jitterable = data[1] & 0x1c; dv = (data[1] & 0x01) != 0 ? 1 : 0; p = (data[1] & 0x02) != 0 ? 1 : 0; left = (data[1]& aiptek->curSetting.mouseButtonLeft) != 0 ? 1 : 0; right = (data[1] & aiptek->curSetting.mouseButtonRight) != 0 ? 1 : 0; middle = (data[1] & aiptek->curSetting.mouseButtonMiddle) != 0 ? 1 : 0; macro = dv && p && left && !(data[3] & 1) ? (data[3] >> 1) : 0; if (dv) { /* If the selected tool changed, reset the old * tool key, and set the new one. */ if (aiptek->previousToolMode != aiptek->curSetting.toolMode) { input_report_key(inputdev, aiptek->previousToolMode, 0); input_report_key(inputdev, aiptek->curSetting.toolMode, 1); aiptek->previousToolMode = aiptek->curSetting.toolMode; } } if (aiptek->lastMacro != -1 && aiptek->lastMacro != macro) { input_report_key(inputdev, macroKeyEvents[aiptek->lastMacro], 0); aiptek->lastMacro = -1; } if (macro != -1 && macro != aiptek->lastMacro) { input_report_key(inputdev, macroKeyEvents[macro], 1); aiptek->lastMacro = macro; } input_report_abs(inputdev, ABS_MISC, p | AIPTEK_REPORT_TOOL_MOUSE); input_sync(inputdev); } /* We have no idea which tool can generate a report 6. Theoretically, * neither need to, having been given reports 4 & 5 for such use. * However, report 6 is the 'official-looking' report for macroKeys; * reports 4 & 5 supposively are used to support unnamed, unknown * hat switches (which just so happen to be the macroKeys.) */ else if (data[0] == 6) { macro = get_unaligned_le16(data + 1); if (macro > 0) { input_report_key(inputdev, macroKeyEvents[macro - 1], 0); } if (macro < 25) { input_report_key(inputdev, macroKeyEvents[macro + 1], 0); } /* If the selected tool changed, reset the old tool key, and set the new one. */ if (aiptek->previousToolMode != aiptek->curSetting.toolMode) { input_report_key(inputdev, aiptek->previousToolMode, 0); input_report_key(inputdev, aiptek->curSetting.toolMode, 1); aiptek->previousToolMode = aiptek->curSetting.toolMode; } input_report_key(inputdev, macroKeyEvents[macro], 1); input_report_abs(inputdev, ABS_MISC, 1 | AIPTEK_REPORT_TOOL_UNKNOWN); input_sync(inputdev); } else { dev_dbg(&intf->dev, "Unknown report %d\n", data[0]); } /* Jitter may occur when the user presses a button on the stlyus * or the mouse. What we do to prevent that is wait 'x' milliseconds * following a 'jitterable' event, which should give the hand some time * stabilize itself. * * We just introduced aiptek->previousJitterable to carry forth the * notion that jitter occurs when the button state changes from on to off: * a person drawing, holding a button down is not subject to jittering. * With that in mind, changing from upper button depressed to lower button * WILL transition through a jitter delay. */ if (aiptek->previousJitterable != jitterable && aiptek->curSetting.jitterDelay != 0 && aiptek->inDelay != 1) { aiptek->endDelay = jiffies + ((aiptek->curSetting.jitterDelay * HZ) / 1000); aiptek->inDelay = 1; } aiptek->previousJitterable = jitterable; exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval != 0) { dev_err(&intf->dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } } /*********************************************************************** * These are the USB id's known so far. We do not identify them to * specific Aiptek model numbers, because there has been overlaps, * use, and reuse of id's in existing models. Certain models have * been known to use more than one ID, indicative perhaps of * manufacturing revisions. In any event, we consider these * IDs to not be model-specific nor unique. */ static const struct usb_device_id aiptek_ids[] = { {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x01)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x10)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x20)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x21)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x22)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x23)}, {USB_DEVICE(USB_VENDOR_ID_AIPTEK, 0x24)}, {USB_DEVICE(USB_VENDOR_ID_KYE, 0x5003)}, {} }; MODULE_DEVICE_TABLE(usb, aiptek_ids); /*********************************************************************** * Open an instance of the tablet driver. */ static int aiptek_open(struct input_dev *inputdev) { struct aiptek *aiptek = input_get_drvdata(inputdev); aiptek->urb->dev = interface_to_usbdev(aiptek->intf); if (usb_submit_urb(aiptek->urb, GFP_KERNEL) != 0) return -EIO; return 0; } /*********************************************************************** * Close an instance of the tablet driver. */ static void aiptek_close(struct input_dev *inputdev) { struct aiptek *aiptek = input_get_drvdata(inputdev); usb_kill_urb(aiptek->urb); } /*********************************************************************** * aiptek_set_report and aiptek_get_report() are borrowed from Linux 2.4.x, * where they were known as usb_set_report and usb_get_report. */ static int aiptek_set_report(struct aiptek *aiptek, unsigned char report_type, unsigned char report_id, void *buffer, int size) { struct usb_device *udev = interface_to_usbdev(aiptek->intf); return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT, (report_type << 8) + report_id, aiptek->ifnum, buffer, size, 5000); } static int aiptek_get_report(struct aiptek *aiptek, unsigned char report_type, unsigned char report_id, void *buffer, int size) { struct usb_device *udev = interface_to_usbdev(aiptek->intf); return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), USB_REQ_GET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN, (report_type << 8) + report_id, aiptek->ifnum, buffer, size, 5000); } /*********************************************************************** * Send a command to the tablet. */ static int aiptek_command(struct aiptek *aiptek, unsigned char command, unsigned char data) { const int sizeof_buf = 3 * sizeof(u8); int ret; u8 *buf; buf = kmalloc(sizeof_buf, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = 2; buf[1] = command; buf[2] = data; if ((ret = aiptek_set_report(aiptek, 3, 2, buf, sizeof_buf)) != sizeof_buf) { dev_dbg(&aiptek->intf->dev, "aiptek_program: failed, tried to send: 0x%02x 0x%02x\n", command, data); } kfree(buf); return ret < 0 ? ret : 0; } /*********************************************************************** * Retrieve information from the tablet. Querying info is defined as first * sending the {command,data} sequence as a command, followed by a wait * (aka, "programmaticDelay") and then a "read" request. */ static int aiptek_query(struct aiptek *aiptek, unsigned char command, unsigned char data) { const int sizeof_buf = 3 * sizeof(u8); int ret; u8 *buf; buf = kmalloc(sizeof_buf, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = 2; buf[1] = command; buf[2] = data; if (aiptek_command(aiptek, command, data) != 0) { kfree(buf); return -EIO; } msleep(aiptek->curSetting.programmableDelay); if (aiptek_get_report(aiptek, 3, 2, buf, sizeof_buf) != sizeof_buf) { dev_dbg(&aiptek->intf->dev, "aiptek_query failed: returned 0x%02x 0x%02x 0x%02x\n", buf[0], buf[1], buf[2]); ret = -EIO; } else { ret = get_unaligned_le16(buf + 1); } kfree(buf); return ret; } /*********************************************************************** * Program the tablet into either absolute or relative mode. * We also get information about the tablet's size. */ static int aiptek_program_tablet(struct aiptek *aiptek) { int ret; /* Execute Resolution500LPI */ if ((ret = aiptek_command(aiptek, 0x18, 0x04)) < 0) return ret; /* Query getModelCode */ if ((ret = aiptek_query(aiptek, 0x02, 0x00)) < 0) return ret; aiptek->features.modelCode = ret & 0xff; /* Query getODMCode */ if ((ret = aiptek_query(aiptek, 0x03, 0x00)) < 0) return ret; aiptek->features.odmCode = ret; /* Query getFirmwareCode */ if ((ret = aiptek_query(aiptek, 0x04, 0x00)) < 0) return ret; aiptek->features.firmwareCode = ret; /* Query getXextension */ if ((ret = aiptek_query(aiptek, 0x01, 0x00)) < 0) return ret; input_set_abs_params(aiptek->inputdev, ABS_X, 0, ret - 1, 0, 0); /* Query getYextension */ if ((ret = aiptek_query(aiptek, 0x01, 0x01)) < 0) return ret; input_set_abs_params(aiptek->inputdev, ABS_Y, 0, ret - 1, 0, 0); /* Query getPressureLevels */ if ((ret = aiptek_query(aiptek, 0x08, 0x00)) < 0) return ret; input_set_abs_params(aiptek->inputdev, ABS_PRESSURE, 0, ret - 1, 0, 0); /* Depending on whether we are in absolute or relative mode, we will * do a switchToTablet(absolute) or switchToMouse(relative) command. */ if (aiptek->curSetting.coordinateMode == AIPTEK_COORDINATE_ABSOLUTE_MODE) { /* Execute switchToTablet */ if ((ret = aiptek_command(aiptek, 0x10, 0x01)) < 0) { return ret; } } else { /* Execute switchToMouse */ if ((ret = aiptek_command(aiptek, 0x10, 0x00)) < 0) { return ret; } } /* Enable the macro keys */ if ((ret = aiptek_command(aiptek, 0x11, 0x02)) < 0) return ret; #if 0 /* Execute FilterOn */ if ((ret = aiptek_command(aiptek, 0x17, 0x00)) < 0) return ret; #endif /* Execute AutoGainOn */ if ((ret = aiptek_command(aiptek, 0x12, 0xff)) < 0) return ret; /* Reset the eventCount, so we track events from last (re)programming */ aiptek->diagnostic = AIPTEK_DIAGNOSTIC_NA; aiptek->eventCount = 0; return 0; } /*********************************************************************** * Sysfs functions. Sysfs prefers that individually-tunable parameters * exist in their separate pseudo-files. Summary data that is immutable * may exist in a singular file so long as you don't define a writeable * interface. */ /*********************************************************************** * support the 'size' file -- display support */ static ssize_t show_tabletSize(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%dx%d\n", input_abs_get_max(aiptek->inputdev, ABS_X) + 1, input_abs_get_max(aiptek->inputdev, ABS_Y) + 1); } /* These structs define the sysfs files, param #1 is the name of the * file, param 2 is the file permissions, param 3 & 4 are to the * output generator and input parser routines. Absence of a routine is * permitted -- it only means can't either 'cat' the file, or send data * to it. */ static DEVICE_ATTR(size, S_IRUGO, show_tabletSize, NULL); /*********************************************************************** * support routines for the 'pointer_mode' file. Note that this file * both displays current setting and allows reprogramming. */ static struct aiptek_map pointer_mode_map[] = { { "stylus", AIPTEK_POINTER_ONLY_STYLUS_MODE }, { "mouse", AIPTEK_POINTER_ONLY_MOUSE_MODE }, { "either", AIPTEK_POINTER_EITHER_MODE }, { NULL, AIPTEK_INVALID_VALUE } }; static ssize_t show_tabletPointerMode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(pointer_mode_map, aiptek->curSetting.pointerMode)); } static ssize_t store_tabletPointerMode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_mode = map_str_to_val(pointer_mode_map, buf, count); if (new_mode == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.pointerMode = new_mode; return count; } static DEVICE_ATTR(pointer_mode, S_IRUGO | S_IWUSR, show_tabletPointerMode, store_tabletPointerMode); /*********************************************************************** * support routines for the 'coordinate_mode' file. Note that this file * both displays current setting and allows reprogramming. */ static struct aiptek_map coordinate_mode_map[] = { { "absolute", AIPTEK_COORDINATE_ABSOLUTE_MODE }, { "relative", AIPTEK_COORDINATE_RELATIVE_MODE }, { NULL, AIPTEK_INVALID_VALUE } }; static ssize_t show_tabletCoordinateMode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(coordinate_mode_map, aiptek->curSetting.coordinateMode)); } static ssize_t store_tabletCoordinateMode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_mode = map_str_to_val(coordinate_mode_map, buf, count); if (new_mode == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.coordinateMode = new_mode; return count; } static DEVICE_ATTR(coordinate_mode, S_IRUGO | S_IWUSR, show_tabletCoordinateMode, store_tabletCoordinateMode); /*********************************************************************** * support routines for the 'tool_mode' file. Note that this file * both displays current setting and allows reprogramming. */ static struct aiptek_map tool_mode_map[] = { { "mouse", AIPTEK_TOOL_BUTTON_MOUSE_MODE }, { "eraser", AIPTEK_TOOL_BUTTON_ERASER_MODE }, { "pencil", AIPTEK_TOOL_BUTTON_PENCIL_MODE }, { "pen", AIPTEK_TOOL_BUTTON_PEN_MODE }, { "brush", AIPTEK_TOOL_BUTTON_BRUSH_MODE }, { "airbrush", AIPTEK_TOOL_BUTTON_AIRBRUSH_MODE }, { "lens", AIPTEK_TOOL_BUTTON_LENS_MODE }, { NULL, AIPTEK_INVALID_VALUE } }; static ssize_t show_tabletToolMode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(tool_mode_map, aiptek->curSetting.toolMode)); } static ssize_t store_tabletToolMode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_mode = map_str_to_val(tool_mode_map, buf, count); if (new_mode == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.toolMode = new_mode; return count; } static DEVICE_ATTR(tool_mode, S_IRUGO | S_IWUSR, show_tabletToolMode, store_tabletToolMode); /*********************************************************************** * support routines for the 'xtilt' file. Note that this file * both displays current setting and allows reprogramming. */ static ssize_t show_tabletXtilt(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); if (aiptek->curSetting.xTilt == AIPTEK_TILT_DISABLE) { return sysfs_emit(buf, "disable\n"); } else { return sysfs_emit(buf, "%d\n", aiptek->curSetting.xTilt); } } static ssize_t store_tabletXtilt(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int x; if (kstrtoint(buf, 10, &x)) { size_t len = buf[count - 1] == '\n' ? count - 1 : count; if (strncmp(buf, "disable", len)) return -EINVAL; aiptek->newSetting.xTilt = AIPTEK_TILT_DISABLE; } else { if (x < AIPTEK_TILT_MIN || x > AIPTEK_TILT_MAX) return -EINVAL; aiptek->newSetting.xTilt = x; } return count; } static DEVICE_ATTR(xtilt, S_IRUGO | S_IWUSR, show_tabletXtilt, store_tabletXtilt); /*********************************************************************** * support routines for the 'ytilt' file. Note that this file * both displays current setting and allows reprogramming. */ static ssize_t show_tabletYtilt(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); if (aiptek->curSetting.yTilt == AIPTEK_TILT_DISABLE) { return sysfs_emit(buf, "disable\n"); } else { return sysfs_emit(buf, "%d\n", aiptek->curSetting.yTilt); } } static ssize_t store_tabletYtilt(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int y; if (kstrtoint(buf, 10, &y)) { size_t len = buf[count - 1] == '\n' ? count - 1 : count; if (strncmp(buf, "disable", len)) return -EINVAL; aiptek->newSetting.yTilt = AIPTEK_TILT_DISABLE; } else { if (y < AIPTEK_TILT_MIN || y > AIPTEK_TILT_MAX) return -EINVAL; aiptek->newSetting.yTilt = y; } return count; } static DEVICE_ATTR(ytilt, S_IRUGO | S_IWUSR, show_tabletYtilt, store_tabletYtilt); /*********************************************************************** * support routines for the 'jitter' file. Note that this file * both displays current setting and allows reprogramming. */ static ssize_t show_tabletJitterDelay(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%d\n", aiptek->curSetting.jitterDelay); } static ssize_t store_tabletJitterDelay(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int err, j; err = kstrtoint(buf, 10, &j); if (err) return err; aiptek->newSetting.jitterDelay = j; return count; } static DEVICE_ATTR(jitter, S_IRUGO | S_IWUSR, show_tabletJitterDelay, store_tabletJitterDelay); /*********************************************************************** * support routines for the 'delay' file. Note that this file * both displays current setting and allows reprogramming. */ static ssize_t show_tabletProgrammableDelay(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%d\n", aiptek->curSetting.programmableDelay); } static ssize_t store_tabletProgrammableDelay(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int err, d; err = kstrtoint(buf, 10, &d); if (err) return err; aiptek->newSetting.programmableDelay = d; return count; } static DEVICE_ATTR(delay, S_IRUGO | S_IWUSR, show_tabletProgrammableDelay, store_tabletProgrammableDelay); /*********************************************************************** * support routines for the 'event_count' file. Note that this file * only displays current setting. */ static ssize_t show_tabletEventsReceived(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%ld\n", aiptek->eventCount); } static DEVICE_ATTR(event_count, S_IRUGO, show_tabletEventsReceived, NULL); /*********************************************************************** * support routines for the 'diagnostic' file. Note that this file * only displays current setting. */ static ssize_t show_tabletDiagnosticMessage(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); char *retMsg; switch (aiptek->diagnostic) { case AIPTEK_DIAGNOSTIC_NA: retMsg = "no errors\n"; break; case AIPTEK_DIAGNOSTIC_SENDING_RELATIVE_IN_ABSOLUTE: retMsg = "Error: receiving relative reports\n"; break; case AIPTEK_DIAGNOSTIC_SENDING_ABSOLUTE_IN_RELATIVE: retMsg = "Error: receiving absolute reports\n"; break; case AIPTEK_DIAGNOSTIC_TOOL_DISALLOWED: if (aiptek->curSetting.pointerMode == AIPTEK_POINTER_ONLY_MOUSE_MODE) { retMsg = "Error: receiving stylus reports\n"; } else { retMsg = "Error: receiving mouse reports\n"; } break; default: return 0; } return sysfs_emit(buf, retMsg); } static DEVICE_ATTR(diagnostic, S_IRUGO, show_tabletDiagnosticMessage, NULL); /*********************************************************************** * support routines for the 'stylus_upper' file. Note that this file * both displays current setting and allows for setting changing. */ static struct aiptek_map stylus_button_map[] = { { "upper", AIPTEK_STYLUS_UPPER_BUTTON }, { "lower", AIPTEK_STYLUS_LOWER_BUTTON }, { NULL, AIPTEK_INVALID_VALUE } }; static ssize_t show_tabletStylusUpper(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(stylus_button_map, aiptek->curSetting.stylusButtonUpper)); } static ssize_t store_tabletStylusUpper(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_button = map_str_to_val(stylus_button_map, buf, count); if (new_button == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.stylusButtonUpper = new_button; return count; } static DEVICE_ATTR(stylus_upper, S_IRUGO | S_IWUSR, show_tabletStylusUpper, store_tabletStylusUpper); /*********************************************************************** * support routines for the 'stylus_lower' file. Note that this file * both displays current setting and allows for setting changing. */ static ssize_t show_tabletStylusLower(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(stylus_button_map, aiptek->curSetting.stylusButtonLower)); } static ssize_t store_tabletStylusLower(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_button = map_str_to_val(stylus_button_map, buf, count); if (new_button == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.stylusButtonLower = new_button; return count; } static DEVICE_ATTR(stylus_lower, S_IRUGO | S_IWUSR, show_tabletStylusLower, store_tabletStylusLower); /*********************************************************************** * support routines for the 'mouse_left' file. Note that this file * both displays current setting and allows for setting changing. */ static struct aiptek_map mouse_button_map[] = { { "left", AIPTEK_MOUSE_LEFT_BUTTON }, { "middle", AIPTEK_MOUSE_MIDDLE_BUTTON }, { "right", AIPTEK_MOUSE_RIGHT_BUTTON }, { NULL, AIPTEK_INVALID_VALUE } }; static ssize_t show_tabletMouseLeft(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(mouse_button_map, aiptek->curSetting.mouseButtonLeft)); } static ssize_t store_tabletMouseLeft(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_button = map_str_to_val(mouse_button_map, buf, count); if (new_button == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.mouseButtonLeft = new_button; return count; } static DEVICE_ATTR(mouse_left, S_IRUGO | S_IWUSR, show_tabletMouseLeft, store_tabletMouseLeft); /*********************************************************************** * support routines for the 'mouse_middle' file. Note that this file * both displays current setting and allows for setting changing. */ static ssize_t show_tabletMouseMiddle(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(mouse_button_map, aiptek->curSetting.mouseButtonMiddle)); } static ssize_t store_tabletMouseMiddle(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_button = map_str_to_val(mouse_button_map, buf, count); if (new_button == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.mouseButtonMiddle = new_button; return count; } static DEVICE_ATTR(mouse_middle, S_IRUGO | S_IWUSR, show_tabletMouseMiddle, store_tabletMouseMiddle); /*********************************************************************** * support routines for the 'mouse_right' file. Note that this file * both displays current setting and allows for setting changing. */ static ssize_t show_tabletMouseRight(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%s\n", map_val_to_str(mouse_button_map, aiptek->curSetting.mouseButtonRight)); } static ssize_t store_tabletMouseRight(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int new_button = map_str_to_val(mouse_button_map, buf, count); if (new_button == AIPTEK_INVALID_VALUE) return -EINVAL; aiptek->newSetting.mouseButtonRight = new_button; return count; } static DEVICE_ATTR(mouse_right, S_IRUGO | S_IWUSR, show_tabletMouseRight, store_tabletMouseRight); /*********************************************************************** * support routines for the 'wheel' file. Note that this file * both displays current setting and allows for setting changing. */ static ssize_t show_tabletWheel(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); if (aiptek->curSetting.wheel == AIPTEK_WHEEL_DISABLE) { return sysfs_emit(buf, "disable\n"); } else { return sysfs_emit(buf, "%d\n", aiptek->curSetting.wheel); } } static ssize_t store_tabletWheel(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); int err, w; err = kstrtoint(buf, 10, &w); if (err) return err; aiptek->newSetting.wheel = w; return count; } static DEVICE_ATTR(wheel, S_IRUGO | S_IWUSR, show_tabletWheel, store_tabletWheel); /*********************************************************************** * support routines for the 'execute' file. Note that this file * both displays current setting and allows for setting changing. */ static ssize_t show_tabletExecute(struct device *dev, struct device_attribute *attr, char *buf) { /* There is nothing useful to display, so a one-line manual * is in order... */ return sysfs_emit(buf, "Write anything to this file to program your tablet.\n"); } static ssize_t store_tabletExecute(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct aiptek *aiptek = dev_get_drvdata(dev); /* We do not care what you write to this file. Merely the action * of writing to this file triggers a tablet reprogramming. */ memcpy(&aiptek->curSetting, &aiptek->newSetting, sizeof(struct aiptek_settings)); if (aiptek_program_tablet(aiptek) < 0) return -EIO; return count; } static DEVICE_ATTR(execute, S_IRUGO | S_IWUSR, show_tabletExecute, store_tabletExecute); /*********************************************************************** * support routines for the 'odm_code' file. Note that this file * only displays current setting. */ static ssize_t show_tabletODMCode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "0x%04x\n", aiptek->features.odmCode); } static DEVICE_ATTR(odm_code, S_IRUGO, show_tabletODMCode, NULL); /*********************************************************************** * support routines for the 'model_code' file. Note that this file * only displays current setting. */ static ssize_t show_tabletModelCode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "0x%04x\n", aiptek->features.modelCode); } static DEVICE_ATTR(model_code, S_IRUGO, show_tabletModelCode, NULL); /*********************************************************************** * support routines for the 'firmware_code' file. Note that this file * only displays current setting. */ static ssize_t show_firmwareCode(struct device *dev, struct device_attribute *attr, char *buf) { struct aiptek *aiptek = dev_get_drvdata(dev); return sysfs_emit(buf, "%04x\n", aiptek->features.firmwareCode); } static DEVICE_ATTR(firmware_code, S_IRUGO, show_firmwareCode, NULL); static struct attribute *aiptek_dev_attrs[] = { &dev_attr_size.attr, &dev_attr_pointer_mode.attr, &dev_attr_coordinate_mode.attr, &dev_attr_tool_mode.attr, &dev_attr_xtilt.attr, &dev_attr_ytilt.attr, &dev_attr_jitter.attr, &dev_attr_delay.attr, &dev_attr_event_count.attr, &dev_attr_diagnostic.attr, &dev_attr_odm_code.attr, &dev_attr_model_code.attr, &dev_attr_firmware_code.attr, &dev_attr_stylus_lower.attr, &dev_attr_stylus_upper.attr, &dev_attr_mouse_left.attr, &dev_attr_mouse_middle.attr, &dev_attr_mouse_right.attr, &dev_attr_wheel.attr, &dev_attr_execute.attr, NULL }; ATTRIBUTE_GROUPS(aiptek_dev); /*********************************************************************** * This routine is called when a tablet has been identified. It basically * sets up the tablet and the driver's internal structures. */ static int aiptek_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usbdev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct aiptek *aiptek; struct input_dev *inputdev; int i; int speeds[] = { 0, AIPTEK_PROGRAMMABLE_DELAY_50, AIPTEK_PROGRAMMABLE_DELAY_400, AIPTEK_PROGRAMMABLE_DELAY_25, AIPTEK_PROGRAMMABLE_DELAY_100, AIPTEK_PROGRAMMABLE_DELAY_200, AIPTEK_PROGRAMMABLE_DELAY_300 }; int err = -ENOMEM; /* programmableDelay is where the command-line specified * delay is kept. We make it the first element of speeds[], * so therefore, your override speed is tried first, then the * remainder. Note that the default value of 400ms will be tried * if you do not specify any command line parameter. */ speeds[0] = programmableDelay; aiptek = kzalloc(sizeof(struct aiptek), GFP_KERNEL); inputdev = input_allocate_device(); if (!aiptek || !inputdev) { dev_warn(&intf->dev, "cannot allocate memory or input device\n"); goto fail1; } aiptek->data = usb_alloc_coherent(usbdev, AIPTEK_PACKET_LENGTH, GFP_KERNEL, &aiptek->data_dma); if (!aiptek->data) { dev_warn(&intf->dev, "cannot allocate usb buffer\n"); goto fail1; } aiptek->urb = usb_alloc_urb(0, GFP_KERNEL); if (!aiptek->urb) { dev_warn(&intf->dev, "cannot allocate urb\n"); goto fail2; } aiptek->inputdev = inputdev; aiptek->intf = intf; aiptek->ifnum = intf->cur_altsetting->desc.bInterfaceNumber; aiptek->inDelay = 0; aiptek->endDelay = 0; aiptek->previousJitterable = 0; aiptek->lastMacro = -1; /* Set up the curSettings struct. Said struct contains the current * programmable parameters. The newSetting struct contains changes * the user makes to the settings via the sysfs interface. Those * changes are not "committed" to curSettings until the user * writes to the sysfs/.../execute file. */ aiptek->curSetting.pointerMode = AIPTEK_POINTER_EITHER_MODE; aiptek->curSetting.coordinateMode = AIPTEK_COORDINATE_ABSOLUTE_MODE; aiptek->curSetting.toolMode = AIPTEK_TOOL_BUTTON_PEN_MODE; aiptek->curSetting.xTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.yTilt = AIPTEK_TILT_DISABLE; aiptek->curSetting.mouseButtonLeft = AIPTEK_MOUSE_LEFT_BUTTON; aiptek->curSetting.mouseButtonMiddle = AIPTEK_MOUSE_MIDDLE_BUTTON; aiptek->curSetting.mouseButtonRight = AIPTEK_MOUSE_RIGHT_BUTTON; aiptek->curSetting.stylusButtonUpper = AIPTEK_STYLUS_UPPER_BUTTON; aiptek->curSetting.stylusButtonLower = AIPTEK_STYLUS_LOWER_BUTTON; aiptek->curSetting.jitterDelay = jitterDelay; aiptek->curSetting.programmableDelay = programmableDelay; /* Both structs should have equivalent settings */ aiptek->newSetting = aiptek->curSetting; /* Determine the usb devices' physical path. * Asketh not why we always pretend we're using "../input0", * but I suspect this will have to be refactored one * day if a single USB device can be a keyboard & a mouse * & a tablet, and the inputX number actually will tell * us something... */ usb_make_path(usbdev, aiptek->features.usbPath, sizeof(aiptek->features.usbPath)); strlcat(aiptek->features.usbPath, "/input0", sizeof(aiptek->features.usbPath)); /* Set up client data, pointers to open and close routines * for the input device. */ inputdev->name = "Aiptek"; inputdev->phys = aiptek->features.usbPath; usb_to_input_id(usbdev, &inputdev->id); inputdev->dev.parent = &intf->dev; input_set_drvdata(inputdev, aiptek); inputdev->open = aiptek_open; inputdev->close = aiptek_close; /* Now program the capacities of the tablet, in terms of being * an input device. */ for (i = 0; i < ARRAY_SIZE(eventTypes); ++i) __set_bit(eventTypes[i], inputdev->evbit); for (i = 0; i < ARRAY_SIZE(absEvents); ++i) __set_bit(absEvents[i], inputdev->absbit); for (i = 0; i < ARRAY_SIZE(relEvents); ++i) __set_bit(relEvents[i], inputdev->relbit); __set_bit(MSC_SERIAL, inputdev->mscbit); /* Set up key and button codes */ for (i = 0; i < ARRAY_SIZE(buttonEvents); ++i) __set_bit(buttonEvents[i], inputdev->keybit); for (i = 0; i < ARRAY_SIZE(macroKeyEvents); ++i) __set_bit(macroKeyEvents[i], inputdev->keybit); /* * Program the input device coordinate capacities. We do not yet * know what maximum X, Y, and Z values are, so we're putting fake * values in. Later, we'll ask the tablet to put in the correct * values. */ input_set_abs_params(inputdev, ABS_X, 0, 2999, 0, 0); input_set_abs_params(inputdev, ABS_Y, 0, 2249, 0, 0); input_set_abs_params(inputdev, ABS_PRESSURE, 0, 511, 0, 0); input_set_abs_params(inputdev, ABS_TILT_X, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_TILT_Y, AIPTEK_TILT_MIN, AIPTEK_TILT_MAX, 0, 0); input_set_abs_params(inputdev, ABS_WHEEL, AIPTEK_WHEEL_MIN, AIPTEK_WHEEL_MAX - 1, 0, 0); err = usb_find_common_endpoints(intf->cur_altsetting, NULL, NULL, &endpoint, NULL); if (err) { dev_err(&intf->dev, "interface has no int in endpoints, but must have minimum 1\n"); goto fail3; } /* Go set up our URB, which is called when the tablet receives * input. */ usb_fill_int_urb(aiptek->urb, usbdev, usb_rcvintpipe(usbdev, endpoint->bEndpointAddress), aiptek->data, 8, aiptek_irq, aiptek, endpoint->bInterval); aiptek->urb->transfer_dma = aiptek->data_dma; aiptek->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* Program the tablet. This sets the tablet up in the mode * specified in newSetting, and also queries the tablet's * physical capacities. * * Sanity check: if a tablet doesn't like the slow programmatic * delay, we often get sizes of 0x0. Let's use that as an indicator * to try faster delays, up to 25 ms. If that logic fails, well, you'll * have to explain to us how your tablet thinks it's 0x0, and yet that's * not an error :-) */ for (i = 0; i < ARRAY_SIZE(speeds); ++i) { aiptek->curSetting.programmableDelay = speeds[i]; (void)aiptek_program_tablet(aiptek); if (input_abs_get_max(aiptek->inputdev, ABS_X) > 0) { dev_info(&intf->dev, "Aiptek using %d ms programming speed\n", aiptek->curSetting.programmableDelay); break; } } /* Murphy says that some day someone will have a tablet that fails the above test. That's you, Frederic Rodrigo */ if (i == ARRAY_SIZE(speeds)) { dev_info(&intf->dev, "Aiptek tried all speeds, no sane response\n"); err = -EINVAL; goto fail3; } /* Associate this driver's struct with the usb interface. */ usb_set_intfdata(intf, aiptek); /* Register the tablet as an Input Device */ err = input_register_device(aiptek->inputdev); if (err) { dev_warn(&intf->dev, "input_register_device returned err: %d\n", err); goto fail3; } return 0; fail3: usb_free_urb(aiptek->urb); fail2: usb_free_coherent(usbdev, AIPTEK_PACKET_LENGTH, aiptek->data, aiptek->data_dma); fail1: usb_set_intfdata(intf, NULL); input_free_device(inputdev); kfree(aiptek); return err; } /*********************************************************************** * Deal with tablet disconnecting from the system. */ static void aiptek_disconnect(struct usb_interface *intf) { struct aiptek *aiptek = usb_get_intfdata(intf); /* Disassociate driver's struct with usb interface */ usb_set_intfdata(intf, NULL); if (aiptek != NULL) { /* Free & unhook everything from the system. */ usb_kill_urb(aiptek->urb); input_unregister_device(aiptek->inputdev); usb_free_urb(aiptek->urb); usb_free_coherent(interface_to_usbdev(intf), AIPTEK_PACKET_LENGTH, aiptek->data, aiptek->data_dma); kfree(aiptek); } } static struct usb_driver aiptek_driver = { .name = "aiptek", .probe = aiptek_probe, .disconnect = aiptek_disconnect, .id_table = aiptek_ids, .dev_groups = aiptek_dev_groups, }; module_usb_driver(aiptek_driver); MODULE_AUTHOR("Bryan W. Headley/Chris Atenasio/Cedric Brun/Rene van Paassen"); MODULE_DESCRIPTION("Aiptek HyperPen USB Tablet Driver"); MODULE_LICENSE("GPL"); module_param(programmableDelay, int, 0); MODULE_PARM_DESC(programmableDelay, "delay used during tablet programming"); module_param(jitterDelay, int, 0); MODULE_PARM_DESC(jitterDelay, "stylus/mouse settlement delay");
linux-master
drivers/input/tablet/aiptek.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2001-2005 Edouard TISSERANT <[email protected]> * Copyright (c) 2004-2005 Stephane VOLTZ <[email protected]> * * USB Acecad "Acecad Flair" tablet support * * Changelog: * v3.2 - Added sysfs support */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> MODULE_AUTHOR("Edouard TISSERANT <[email protected]>"); MODULE_DESCRIPTION("USB Acecad Flair tablet driver"); MODULE_LICENSE("GPL"); #define USB_VENDOR_ID_ACECAD 0x0460 #define USB_DEVICE_ID_FLAIR 0x0004 #define USB_DEVICE_ID_302 0x0008 struct usb_acecad { char name[128]; char phys[64]; struct usb_interface *intf; struct input_dev *input; struct urb *irq; unsigned char *data; dma_addr_t data_dma; }; static void usb_acecad_irq(struct urb *urb) { struct usb_acecad *acecad = urb->context; unsigned char *data = acecad->data; struct input_dev *dev = acecad->input; struct usb_interface *intf = acecad->intf; struct usb_device *udev = interface_to_usbdev(intf); int prox, status; switch (urb->status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&intf->dev, "%s - urb shutting down with status: %d\n", __func__, urb->status); return; default: dev_dbg(&intf->dev, "%s - nonzero urb status received: %d\n", __func__, urb->status); goto resubmit; } prox = (data[0] & 0x04) >> 2; input_report_key(dev, BTN_TOOL_PEN, prox); if (prox) { int x = data[1] | (data[2] << 8); int y = data[3] | (data[4] << 8); /* Pressure should compute the same way for flair and 302 */ int pressure = data[5] | (data[6] << 8); int touch = data[0] & 0x01; int stylus = (data[0] & 0x10) >> 4; int stylus2 = (data[0] & 0x20) >> 5; input_report_abs(dev, ABS_X, x); input_report_abs(dev, ABS_Y, y); input_report_abs(dev, ABS_PRESSURE, pressure); input_report_key(dev, BTN_TOUCH, touch); input_report_key(dev, BTN_STYLUS, stylus); input_report_key(dev, BTN_STYLUS2, stylus2); } /* event termination */ input_sync(dev); resubmit: status = usb_submit_urb(urb, GFP_ATOMIC); if (status) dev_err(&intf->dev, "can't resubmit intr, %s-%s/input0, status %d\n", udev->bus->bus_name, udev->devpath, status); } static int usb_acecad_open(struct input_dev *dev) { struct usb_acecad *acecad = input_get_drvdata(dev); acecad->irq->dev = interface_to_usbdev(acecad->intf); if (usb_submit_urb(acecad->irq, GFP_KERNEL)) return -EIO; return 0; } static void usb_acecad_close(struct input_dev *dev) { struct usb_acecad *acecad = input_get_drvdata(dev); usb_kill_urb(acecad->irq); } static int usb_acecad_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct usb_host_interface *interface = intf->cur_altsetting; struct usb_endpoint_descriptor *endpoint; struct usb_acecad *acecad; struct input_dev *input_dev; int pipe, maxp; int err; if (interface->desc.bNumEndpoints != 1) return -ENODEV; endpoint = &interface->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -ENODEV; pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress); maxp = usb_maxpacket(dev, pipe); acecad = kzalloc(sizeof(struct usb_acecad), GFP_KERNEL); input_dev = input_allocate_device(); if (!acecad || !input_dev) { err = -ENOMEM; goto fail1; } acecad->data = usb_alloc_coherent(dev, 8, GFP_KERNEL, &acecad->data_dma); if (!acecad->data) { err= -ENOMEM; goto fail1; } acecad->irq = usb_alloc_urb(0, GFP_KERNEL); if (!acecad->irq) { err = -ENOMEM; goto fail2; } acecad->intf = intf; acecad->input = input_dev; if (dev->manufacturer) strscpy(acecad->name, dev->manufacturer, sizeof(acecad->name)); if (dev->product) { if (dev->manufacturer) strlcat(acecad->name, " ", sizeof(acecad->name)); strlcat(acecad->name, dev->product, sizeof(acecad->name)); } usb_make_path(dev, acecad->phys, sizeof(acecad->phys)); strlcat(acecad->phys, "/input0", sizeof(acecad->phys)); input_dev->name = acecad->name; input_dev->phys = acecad->phys; usb_to_input_id(dev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, acecad); input_dev->open = usb_acecad_open; input_dev->close = usb_acecad_close; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); input_dev->keybit[BIT_WORD(BTN_DIGI)] = BIT_MASK(BTN_TOOL_PEN) | BIT_MASK(BTN_TOUCH) | BIT_MASK(BTN_STYLUS) | BIT_MASK(BTN_STYLUS2); switch (id->driver_info) { case 0: input_set_abs_params(input_dev, ABS_X, 0, 5000, 4, 0); input_set_abs_params(input_dev, ABS_Y, 0, 3750, 4, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 512, 0, 0); if (!strlen(acecad->name)) snprintf(acecad->name, sizeof(acecad->name), "USB Acecad Flair Tablet %04x:%04x", le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); break; case 1: input_set_abs_params(input_dev, ABS_X, 0, 53000, 4, 0); input_set_abs_params(input_dev, ABS_Y, 0, 2250, 4, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, 1024, 0, 0); if (!strlen(acecad->name)) snprintf(acecad->name, sizeof(acecad->name), "USB Acecad 302 Tablet %04x:%04x", le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); break; } usb_fill_int_urb(acecad->irq, dev, pipe, acecad->data, maxp > 8 ? 8 : maxp, usb_acecad_irq, acecad, endpoint->bInterval); acecad->irq->transfer_dma = acecad->data_dma; acecad->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; err = input_register_device(acecad->input); if (err) goto fail3; usb_set_intfdata(intf, acecad); return 0; fail3: usb_free_urb(acecad->irq); fail2: usb_free_coherent(dev, 8, acecad->data, acecad->data_dma); fail1: input_free_device(input_dev); kfree(acecad); return err; } static void usb_acecad_disconnect(struct usb_interface *intf) { struct usb_acecad *acecad = usb_get_intfdata(intf); struct usb_device *udev = interface_to_usbdev(intf); usb_set_intfdata(intf, NULL); input_unregister_device(acecad->input); usb_free_urb(acecad->irq); usb_free_coherent(udev, 8, acecad->data, acecad->data_dma); kfree(acecad); } static const struct usb_device_id usb_acecad_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_FLAIR), .driver_info = 0 }, { USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_302), .driver_info = 1 }, { } }; MODULE_DEVICE_TABLE(usb, usb_acecad_id_table); static struct usb_driver usb_acecad_driver = { .name = "usb_acecad", .probe = usb_acecad_probe, .disconnect = usb_acecad_disconnect, .id_table = usb_acecad_id_table, }; module_usb_driver(usb_acecad_driver);
linux-master
drivers/input/tablet/acecad.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * USB Hanwang tablet support * * Copyright (c) 2010 Xing Wei <[email protected]> */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb/input.h> MODULE_AUTHOR("Xing Wei <[email protected]>"); MODULE_DESCRIPTION("USB Hanwang tablet driver"); MODULE_LICENSE("GPL"); #define USB_VENDOR_ID_HANWANG 0x0b57 #define HANWANG_TABLET_INT_CLASS 0x0003 #define HANWANG_TABLET_INT_SUB_CLASS 0x0001 #define HANWANG_TABLET_INT_PROTOCOL 0x0002 #define ART_MASTER_PKGLEN_MAX 10 /* device IDs */ #define STYLUS_DEVICE_ID 0x02 #define TOUCH_DEVICE_ID 0x03 #define CURSOR_DEVICE_ID 0x06 #define ERASER_DEVICE_ID 0x0A #define PAD_DEVICE_ID 0x0F /* match vendor and interface info */ #define HANWANG_TABLET_DEVICE(vend, cl, sc, pr) \ .match_flags = USB_DEVICE_ID_MATCH_VENDOR \ | USB_DEVICE_ID_MATCH_INT_INFO, \ .idVendor = (vend), \ .bInterfaceClass = (cl), \ .bInterfaceSubClass = (sc), \ .bInterfaceProtocol = (pr) enum hanwang_tablet_type { HANWANG_ART_MASTER_III, HANWANG_ART_MASTER_HD, HANWANG_ART_MASTER_II, }; struct hanwang { unsigned char *data; dma_addr_t data_dma; struct input_dev *dev; struct usb_device *usbdev; struct urb *irq; const struct hanwang_features *features; unsigned int current_tool; unsigned int current_id; char name[64]; char phys[32]; }; struct hanwang_features { unsigned short pid; char *name; enum hanwang_tablet_type type; int pkg_len; int max_x; int max_y; int max_tilt_x; int max_tilt_y; int max_pressure; }; static const struct hanwang_features features_array[] = { { 0x8528, "Hanwang Art Master III 0906", HANWANG_ART_MASTER_III, ART_MASTER_PKGLEN_MAX, 0x5757, 0x3692, 0x3f, 0x7f, 2048 }, { 0x8529, "Hanwang Art Master III 0604", HANWANG_ART_MASTER_III, ART_MASTER_PKGLEN_MAX, 0x3d84, 0x2672, 0x3f, 0x7f, 2048 }, { 0x852a, "Hanwang Art Master III 1308", HANWANG_ART_MASTER_III, ART_MASTER_PKGLEN_MAX, 0x7f00, 0x4f60, 0x3f, 0x7f, 2048 }, { 0x8401, "Hanwang Art Master HD 5012", HANWANG_ART_MASTER_HD, ART_MASTER_PKGLEN_MAX, 0x678e, 0x4150, 0x3f, 0x7f, 1024 }, { 0x8503, "Hanwang Art Master II", HANWANG_ART_MASTER_II, ART_MASTER_PKGLEN_MAX, 0x27de, 0x1cfe, 0x3f, 0x7f, 1024 }, }; static const int hw_eventtypes[] = { EV_KEY, EV_ABS, EV_MSC, }; static const int hw_absevents[] = { ABS_X, ABS_Y, ABS_TILT_X, ABS_TILT_Y, ABS_WHEEL, ABS_RX, ABS_RY, ABS_PRESSURE, ABS_MISC, }; static const int hw_btnevents[] = { BTN_STYLUS, BTN_STYLUS2, BTN_TOOL_PEN, BTN_TOOL_RUBBER, BTN_TOOL_MOUSE, BTN_TOOL_FINGER, BTN_0, BTN_1, BTN_2, BTN_3, BTN_4, BTN_5, BTN_6, BTN_7, BTN_8, }; static const int hw_mscevents[] = { MSC_SERIAL, }; static void hanwang_parse_packet(struct hanwang *hanwang) { unsigned char *data = hanwang->data; struct input_dev *input_dev = hanwang->dev; struct usb_device *dev = hanwang->usbdev; enum hanwang_tablet_type type = hanwang->features->type; int i; u16 p; if (type == HANWANG_ART_MASTER_II) { hanwang->current_tool = BTN_TOOL_PEN; hanwang->current_id = STYLUS_DEVICE_ID; } switch (data[0]) { case 0x02: /* data packet */ switch (data[1]) { case 0x80: /* tool prox out */ if (type != HANWANG_ART_MASTER_II) { hanwang->current_id = 0; input_report_key(input_dev, hanwang->current_tool, 0); } break; case 0x00: /* artmaster ii pen leave */ if (type == HANWANG_ART_MASTER_II) { hanwang->current_id = 0; input_report_key(input_dev, hanwang->current_tool, 0); } break; case 0xc2: /* first time tool prox in */ switch (data[3] & 0xf0) { case 0x20: /* art_master III */ case 0x30: /* art_master_HD */ hanwang->current_id = STYLUS_DEVICE_ID; hanwang->current_tool = BTN_TOOL_PEN; input_report_key(input_dev, BTN_TOOL_PEN, 1); break; case 0xa0: /* art_master III */ case 0xb0: /* art_master_HD */ hanwang->current_id = ERASER_DEVICE_ID; hanwang->current_tool = BTN_TOOL_RUBBER; input_report_key(input_dev, BTN_TOOL_RUBBER, 1); break; default: hanwang->current_id = 0; dev_dbg(&dev->dev, "unknown tablet tool %02x\n", data[0]); break; } break; default: /* tool data packet */ switch (type) { case HANWANG_ART_MASTER_III: p = (data[6] << 3) | ((data[7] & 0xc0) >> 5) | (data[1] & 0x01); break; case HANWANG_ART_MASTER_HD: case HANWANG_ART_MASTER_II: p = (data[7] >> 6) | (data[6] << 2); break; default: p = 0; break; } input_report_abs(input_dev, ABS_X, be16_to_cpup((__be16 *)&data[2])); input_report_abs(input_dev, ABS_Y, be16_to_cpup((__be16 *)&data[4])); input_report_abs(input_dev, ABS_PRESSURE, p); input_report_abs(input_dev, ABS_TILT_X, data[7] & 0x3f); input_report_abs(input_dev, ABS_TILT_Y, data[8] & 0x7f); input_report_key(input_dev, BTN_STYLUS, data[1] & 0x02); if (type != HANWANG_ART_MASTER_II) input_report_key(input_dev, BTN_STYLUS2, data[1] & 0x04); else input_report_key(input_dev, BTN_TOOL_PEN, 1); break; } input_report_abs(input_dev, ABS_MISC, hanwang->current_id); input_event(input_dev, EV_MSC, MSC_SERIAL, hanwang->features->pid); break; case 0x0c: /* roll wheel */ hanwang->current_id = PAD_DEVICE_ID; switch (type) { case HANWANG_ART_MASTER_III: input_report_key(input_dev, BTN_TOOL_FINGER, data[1] || data[2] || data[3]); input_report_abs(input_dev, ABS_WHEEL, data[1]); input_report_key(input_dev, BTN_0, data[2]); for (i = 0; i < 8; i++) input_report_key(input_dev, BTN_1 + i, data[3] & (1 << i)); break; case HANWANG_ART_MASTER_HD: input_report_key(input_dev, BTN_TOOL_FINGER, data[1] || data[2] || data[3] || data[4] || data[5] || data[6]); input_report_abs(input_dev, ABS_RX, ((data[1] & 0x1f) << 8) | data[2]); input_report_abs(input_dev, ABS_RY, ((data[3] & 0x1f) << 8) | data[4]); input_report_key(input_dev, BTN_0, data[5] & 0x01); for (i = 0; i < 4; i++) { input_report_key(input_dev, BTN_1 + i, data[5] & (1 << i)); input_report_key(input_dev, BTN_5 + i, data[6] & (1 << i)); } break; case HANWANG_ART_MASTER_II: dev_dbg(&dev->dev, "error packet %02x\n", data[0]); return; } input_report_abs(input_dev, ABS_MISC, hanwang->current_id); input_event(input_dev, EV_MSC, MSC_SERIAL, 0xffffffff); break; default: dev_dbg(&dev->dev, "error packet %02x\n", data[0]); break; } input_sync(input_dev); } static void hanwang_irq(struct urb *urb) { struct hanwang *hanwang = urb->context; struct usb_device *dev = hanwang->usbdev; int retval; switch (urb->status) { case 0: /* success */; hanwang_parse_packet(hanwang); break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_err(&dev->dev, "%s - urb shutting down with status: %d", __func__, urb->status); return; default: dev_err(&dev->dev, "%s - nonzero urb status received: %d", __func__, urb->status); break; } retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&dev->dev, "%s - usb_submit_urb failed with result %d", __func__, retval); } static int hanwang_open(struct input_dev *dev) { struct hanwang *hanwang = input_get_drvdata(dev); hanwang->irq->dev = hanwang->usbdev; if (usb_submit_urb(hanwang->irq, GFP_KERNEL)) return -EIO; return 0; } static void hanwang_close(struct input_dev *dev) { struct hanwang *hanwang = input_get_drvdata(dev); usb_kill_urb(hanwang->irq); } static bool get_features(struct usb_device *dev, struct hanwang *hanwang) { int i; for (i = 0; i < ARRAY_SIZE(features_array); i++) { if (le16_to_cpu(dev->descriptor.idProduct) == features_array[i].pid) { hanwang->features = &features_array[i]; return true; } } return false; } static int hanwang_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct usb_endpoint_descriptor *endpoint; struct hanwang *hanwang; struct input_dev *input_dev; int error; int i; if (intf->cur_altsetting->desc.bNumEndpoints < 1) return -ENODEV; hanwang = kzalloc(sizeof(struct hanwang), GFP_KERNEL); input_dev = input_allocate_device(); if (!hanwang || !input_dev) { error = -ENOMEM; goto fail1; } if (!get_features(dev, hanwang)) { error = -ENXIO; goto fail1; } hanwang->data = usb_alloc_coherent(dev, hanwang->features->pkg_len, GFP_KERNEL, &hanwang->data_dma); if (!hanwang->data) { error = -ENOMEM; goto fail1; } hanwang->irq = usb_alloc_urb(0, GFP_KERNEL); if (!hanwang->irq) { error = -ENOMEM; goto fail2; } hanwang->usbdev = dev; hanwang->dev = input_dev; usb_make_path(dev, hanwang->phys, sizeof(hanwang->phys)); strlcat(hanwang->phys, "/input0", sizeof(hanwang->phys)); strscpy(hanwang->name, hanwang->features->name, sizeof(hanwang->name)); input_dev->name = hanwang->name; input_dev->phys = hanwang->phys; usb_to_input_id(dev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, hanwang); input_dev->open = hanwang_open; input_dev->close = hanwang_close; for (i = 0; i < ARRAY_SIZE(hw_eventtypes); ++i) __set_bit(hw_eventtypes[i], input_dev->evbit); for (i = 0; i < ARRAY_SIZE(hw_absevents); ++i) __set_bit(hw_absevents[i], input_dev->absbit); for (i = 0; i < ARRAY_SIZE(hw_btnevents); ++i) __set_bit(hw_btnevents[i], input_dev->keybit); for (i = 0; i < ARRAY_SIZE(hw_mscevents); ++i) __set_bit(hw_mscevents[i], input_dev->mscbit); input_set_abs_params(input_dev, ABS_X, 0, hanwang->features->max_x, 4, 0); input_set_abs_params(input_dev, ABS_Y, 0, hanwang->features->max_y, 4, 0); input_set_abs_params(input_dev, ABS_TILT_X, 0, hanwang->features->max_tilt_x, 0, 0); input_set_abs_params(input_dev, ABS_TILT_Y, 0, hanwang->features->max_tilt_y, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, hanwang->features->max_pressure, 0, 0); endpoint = &intf->cur_altsetting->endpoint[0].desc; usb_fill_int_urb(hanwang->irq, dev, usb_rcvintpipe(dev, endpoint->bEndpointAddress), hanwang->data, hanwang->features->pkg_len, hanwang_irq, hanwang, endpoint->bInterval); hanwang->irq->transfer_dma = hanwang->data_dma; hanwang->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; error = input_register_device(hanwang->dev); if (error) goto fail3; usb_set_intfdata(intf, hanwang); return 0; fail3: usb_free_urb(hanwang->irq); fail2: usb_free_coherent(dev, hanwang->features->pkg_len, hanwang->data, hanwang->data_dma); fail1: input_free_device(input_dev); kfree(hanwang); return error; } static void hanwang_disconnect(struct usb_interface *intf) { struct hanwang *hanwang = usb_get_intfdata(intf); input_unregister_device(hanwang->dev); usb_free_urb(hanwang->irq); usb_free_coherent(interface_to_usbdev(intf), hanwang->features->pkg_len, hanwang->data, hanwang->data_dma); kfree(hanwang); usb_set_intfdata(intf, NULL); } static const struct usb_device_id hanwang_ids[] = { { HANWANG_TABLET_DEVICE(USB_VENDOR_ID_HANWANG, HANWANG_TABLET_INT_CLASS, HANWANG_TABLET_INT_SUB_CLASS, HANWANG_TABLET_INT_PROTOCOL) }, {} }; MODULE_DEVICE_TABLE(usb, hanwang_ids); static struct usb_driver hanwang_driver = { .name = "hanwang", .probe = hanwang_probe, .disconnect = hanwang_disconnect, .id_table = hanwang_ids, }; module_usb_driver(hanwang_driver);
linux-master
drivers/input/tablet/hanwang.c
// SPDX-License-Identifier: GPL-2.0-only /* * MicroTouch (3M) serial touchscreen driver * * Copyright (c) 2004 Vojtech Pavlik */ /* * 2005/02/19 Dan Streetman <[email protected]> * Copied elo.c and edited for MicroTouch 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 "MicroTouch serial touchscreen driver" MODULE_AUTHOR("Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define MTOUCH_FORMAT_TABLET_STATUS_BIT 0x80 #define MTOUCH_FORMAT_TABLET_TOUCH_BIT 0x40 #define MTOUCH_FORMAT_TABLET_LENGTH 5 #define MTOUCH_RESPONSE_BEGIN_BYTE 0x01 #define MTOUCH_RESPONSE_END_BYTE 0x0d /* todo: check specs for max length of all responses */ #define MTOUCH_MAX_LENGTH 16 #define MTOUCH_MIN_XC 0 #define MTOUCH_MAX_XC 0x3fff #define MTOUCH_MIN_YC 0 #define MTOUCH_MAX_YC 0x3fff #define MTOUCH_GET_XC(data) (((data[2])<<7) | data[1]) #define MTOUCH_GET_YC(data) (((data[4])<<7) | data[3]) #define MTOUCH_GET_TOUCHED(data) (MTOUCH_FORMAT_TABLET_TOUCH_BIT & data[0]) /* * Per-touchscreen data. */ struct mtouch { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[MTOUCH_MAX_LENGTH]; char phys[32]; }; static void mtouch_process_format_tablet(struct mtouch *mtouch) { struct input_dev *dev = mtouch->dev; if (MTOUCH_FORMAT_TABLET_LENGTH == ++mtouch->idx) { input_report_abs(dev, ABS_X, MTOUCH_GET_XC(mtouch->data)); input_report_abs(dev, ABS_Y, MTOUCH_MAX_YC - MTOUCH_GET_YC(mtouch->data)); input_report_key(dev, BTN_TOUCH, MTOUCH_GET_TOUCHED(mtouch->data)); input_sync(dev); mtouch->idx = 0; } } static void mtouch_process_response(struct mtouch *mtouch) { if (MTOUCH_RESPONSE_END_BYTE == mtouch->data[mtouch->idx++]) { /* FIXME - process response */ mtouch->idx = 0; } else if (MTOUCH_MAX_LENGTH == mtouch->idx) { printk(KERN_ERR "mtouch.c: too many response bytes\n"); mtouch->idx = 0; } } static irqreturn_t mtouch_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct mtouch *mtouch = serio_get_drvdata(serio); mtouch->data[mtouch->idx] = data; if (MTOUCH_FORMAT_TABLET_STATUS_BIT & mtouch->data[0]) mtouch_process_format_tablet(mtouch); else if (MTOUCH_RESPONSE_BEGIN_BYTE == mtouch->data[0]) mtouch_process_response(mtouch); else printk(KERN_DEBUG "mtouch.c: unknown/unsynchronized data from device, byte %x\n",mtouch->data[0]); return IRQ_HANDLED; } /* * mtouch_disconnect() is the opposite of mtouch_connect() */ static void mtouch_disconnect(struct serio *serio) { struct mtouch *mtouch = serio_get_drvdata(serio); input_get_device(mtouch->dev); input_unregister_device(mtouch->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(mtouch->dev); kfree(mtouch); } /* * mtouch_connect() is the routine that is called when someone adds a * new serio device that supports MicroTouch (Format Tablet) protocol and registers it as * an input device. */ static int mtouch_connect(struct serio *serio, struct serio_driver *drv) { struct mtouch *mtouch; struct input_dev *input_dev; int err; mtouch = kzalloc(sizeof(struct mtouch), GFP_KERNEL); input_dev = input_allocate_device(); if (!mtouch || !input_dev) { err = -ENOMEM; goto fail1; } mtouch->serio = serio; mtouch->dev = input_dev; snprintf(mtouch->phys, sizeof(mtouch->phys), "%s/input0", serio->phys); input_dev->name = "MicroTouch Serial TouchScreen"; input_dev->phys = mtouch->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_MICROTOUCH; 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(mtouch->dev, ABS_X, MTOUCH_MIN_XC, MTOUCH_MAX_XC, 0, 0); input_set_abs_params(mtouch->dev, ABS_Y, MTOUCH_MIN_YC, MTOUCH_MAX_YC, 0, 0); serio_set_drvdata(serio, mtouch); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(mtouch->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(mtouch); return err; } /* * The serio driver structure. */ static const struct serio_device_id mtouch_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_MICROTOUCH, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, mtouch_serio_ids); static struct serio_driver mtouch_drv = { .driver = { .name = "mtouch", }, .description = DRIVER_DESC, .id_table = mtouch_serio_ids, .interrupt = mtouch_interrupt, .connect = mtouch_connect, .disconnect = mtouch_disconnect, }; module_serio_driver(mtouch_drv);
linux-master
drivers/input/touchscreen/mtouch.c
// SPDX-License-Identifier: GPL-2.0-only /* * EETI Egalax serial touchscreen driver * * Copyright (c) 2015 Zoltán Böszörményi <[email protected]> * * based on the * * Hampshire serial touchscreen driver (Copyright (c) 2010 Adam Bennett) */ #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 "EETI Egalax serial touchscreen driver" /* * Definitions & global arrays. */ #define EGALAX_FORMAT_MAX_LENGTH 6 #define EGALAX_FORMAT_START_BIT BIT(7) #define EGALAX_FORMAT_PRESSURE_BIT BIT(6) #define EGALAX_FORMAT_TOUCH_BIT BIT(0) #define EGALAX_FORMAT_RESOLUTION_MASK 0x06 #define EGALAX_MIN_XC 0 #define EGALAX_MAX_XC 0x4000 #define EGALAX_MIN_YC 0 #define EGALAX_MAX_YC 0x4000 /* * Per-touchscreen data. */ struct egalax { struct input_dev *input; struct serio *serio; int idx; u8 data[EGALAX_FORMAT_MAX_LENGTH]; char phys[32]; }; static void egalax_process_data(struct egalax *egalax) { struct input_dev *dev = egalax->input; u8 *data = egalax->data; u16 x, y; u8 shift; u8 mask; shift = 3 - ((data[0] & EGALAX_FORMAT_RESOLUTION_MASK) >> 1); mask = 0xff >> (shift + 1); x = (((u16)(data[1] & mask) << 7) | (data[2] & 0x7f)) << shift; y = (((u16)(data[3] & mask) << 7) | (data[4] & 0x7f)) << shift; input_report_key(dev, BTN_TOUCH, data[0] & EGALAX_FORMAT_TOUCH_BIT); input_report_abs(dev, ABS_X, x); input_report_abs(dev, ABS_Y, y); input_sync(dev); } static irqreturn_t egalax_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct egalax *egalax = serio_get_drvdata(serio); int pkt_len; egalax->data[egalax->idx++] = data; if (likely(egalax->data[0] & EGALAX_FORMAT_START_BIT)) { pkt_len = egalax->data[0] & EGALAX_FORMAT_PRESSURE_BIT ? 6 : 5; if (pkt_len == egalax->idx) { egalax_process_data(egalax); egalax->idx = 0; } } else { dev_dbg(&serio->dev, "unknown/unsynchronized data: %x\n", egalax->data[0]); egalax->idx = 0; } return IRQ_HANDLED; } /* * egalax_connect() is the routine that is called when someone adds a * new serio device that supports egalax protocol and registers it as * an input device. This is usually accomplished using inputattach. */ static int egalax_connect(struct serio *serio, struct serio_driver *drv) { struct egalax *egalax; struct input_dev *input_dev; int error; egalax = kzalloc(sizeof(struct egalax), GFP_KERNEL); input_dev = input_allocate_device(); if (!egalax || !input_dev) { error = -ENOMEM; goto err_free_mem; } egalax->serio = serio; egalax->input = input_dev; snprintf(egalax->phys, sizeof(egalax->phys), "%s/input0", serio->phys); input_dev->name = "EETI eGalaxTouch Serial TouchScreen"; input_dev->phys = egalax->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_EGALAX; input_dev->id.product = 0; input_dev->id.version = 0x0001; input_dev->dev.parent = &serio->dev; input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, EGALAX_MIN_XC, EGALAX_MAX_XC, 0, 0); input_set_abs_params(input_dev, ABS_Y, EGALAX_MIN_YC, EGALAX_MAX_YC, 0, 0); serio_set_drvdata(serio, egalax); error = serio_open(serio, drv); if (error) goto err_reset_drvdata; error = input_register_device(input_dev); if (error) goto err_close_serio; return 0; err_close_serio: serio_close(serio); err_reset_drvdata: serio_set_drvdata(serio, NULL); err_free_mem: input_free_device(input_dev); kfree(egalax); return error; } static void egalax_disconnect(struct serio *serio) { struct egalax *egalax = serio_get_drvdata(serio); serio_close(serio); serio_set_drvdata(serio, NULL); input_unregister_device(egalax->input); kfree(egalax); } /* * The serio driver structure. */ static const struct serio_device_id egalax_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_EGALAX, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, egalax_serio_ids); static struct serio_driver egalax_drv = { .driver = { .name = "egalax", }, .description = DRIVER_DESC, .id_table = egalax_serio_ids, .interrupt = egalax_interrupt, .connect = egalax_connect, .disconnect = egalax_disconnect, }; module_serio_driver(egalax_drv); MODULE_AUTHOR("Zoltán Böszörményi <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/egalax_ts_serial.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Toradex Colibri VF50 Touchscreen driver * * Copyright 2015 Toradex AG * * Originally authored by Stefan Agner for 3.0 kernel */ #include <linux/delay.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/iio/consumer.h> #include <linux/iio/types.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/types.h> #define DRIVER_NAME "colibri-vf50-ts" #define VF_ADC_MAX ((1 << 12) - 1) #define COLI_TOUCH_MIN_DELAY_US 1000 #define COLI_TOUCH_MAX_DELAY_US 2000 #define COLI_PULLUP_MIN_DELAY_US 10000 #define COLI_PULLUP_MAX_DELAY_US 11000 #define COLI_TOUCH_NO_OF_AVGS 5 #define COLI_TOUCH_REQ_ADC_CHAN 4 struct vf50_touch_device { struct platform_device *pdev; struct input_dev *ts_input; struct iio_channel *channels; struct gpio_desc *gpio_xp; struct gpio_desc *gpio_xm; struct gpio_desc *gpio_yp; struct gpio_desc *gpio_ym; int pen_irq; int min_pressure; bool stop_touchscreen; }; /* * Enables given plates and measures touch parameters using ADC */ static int adc_ts_measure(struct iio_channel *channel, struct gpio_desc *plate_p, struct gpio_desc *plate_m) { int i, value = 0, val = 0; int error; gpiod_set_value(plate_p, 1); gpiod_set_value(plate_m, 1); usleep_range(COLI_TOUCH_MIN_DELAY_US, COLI_TOUCH_MAX_DELAY_US); for (i = 0; i < COLI_TOUCH_NO_OF_AVGS; i++) { error = iio_read_channel_raw(channel, &val); if (error < 0) { value = error; goto error_iio_read; } value += val; } value /= COLI_TOUCH_NO_OF_AVGS; error_iio_read: gpiod_set_value(plate_p, 0); gpiod_set_value(plate_m, 0); return value; } /* * Enable touch detection using falling edge detection on XM */ static void vf50_ts_enable_touch_detection(struct vf50_touch_device *vf50_ts) { /* Enable plate YM (needs to be strong GND, high active) */ gpiod_set_value(vf50_ts->gpio_ym, 1); /* * Let the platform mux to idle state in order to enable * Pull-Up on GPIO */ pinctrl_pm_select_idle_state(&vf50_ts->pdev->dev); /* Wait for the pull-up to be stable on high */ usleep_range(COLI_PULLUP_MIN_DELAY_US, COLI_PULLUP_MAX_DELAY_US); } /* * ADC touch screen sampling bottom half irq handler */ static irqreturn_t vf50_ts_irq_bh(int irq, void *private) { struct vf50_touch_device *vf50_ts = private; struct device *dev = &vf50_ts->pdev->dev; int val_x, val_y, val_z1, val_z2, val_p = 0; bool discard_val_on_start = true; /* Disable the touch detection plates */ gpiod_set_value(vf50_ts->gpio_ym, 0); /* Let the platform mux to default state in order to mux as ADC */ pinctrl_pm_select_default_state(dev); while (!vf50_ts->stop_touchscreen) { /* X-Direction */ val_x = adc_ts_measure(&vf50_ts->channels[0], vf50_ts->gpio_xp, vf50_ts->gpio_xm); if (val_x < 0) break; /* Y-Direction */ val_y = adc_ts_measure(&vf50_ts->channels[1], vf50_ts->gpio_yp, vf50_ts->gpio_ym); if (val_y < 0) break; /* * Touch pressure * Measure on XP/YM */ val_z1 = adc_ts_measure(&vf50_ts->channels[2], vf50_ts->gpio_yp, vf50_ts->gpio_xm); if (val_z1 < 0) break; val_z2 = adc_ts_measure(&vf50_ts->channels[3], vf50_ts->gpio_yp, vf50_ts->gpio_xm); if (val_z2 < 0) break; /* Validate signal (avoid calculation using noise) */ if (val_z1 > 64 && val_x > 64) { /* * Calculate resistance between the plates * lower resistance means higher pressure */ int r_x = (1000 * val_x) / VF_ADC_MAX; val_p = (r_x * val_z2) / val_z1 - r_x; } else { val_p = 2000; } val_p = 2000 - val_p; dev_dbg(dev, "Measured values: x: %d, y: %d, z1: %d, z2: %d, p: %d\n", val_x, val_y, val_z1, val_z2, val_p); /* * If touch pressure is too low, stop measuring and reenable * touch detection */ if (val_p < vf50_ts->min_pressure || val_p > 2000) break; /* * The pressure may not be enough for the first x and the * second y measurement, but, the pressure is ok when the * driver is doing the third and fourth measurement. To * take care of this, we drop the first measurement always. */ if (discard_val_on_start) { discard_val_on_start = false; } else { /* * Report touch position and sleep for * the next measurement. */ input_report_abs(vf50_ts->ts_input, ABS_X, VF_ADC_MAX - val_x); input_report_abs(vf50_ts->ts_input, ABS_Y, VF_ADC_MAX - val_y); input_report_abs(vf50_ts->ts_input, ABS_PRESSURE, val_p); input_report_key(vf50_ts->ts_input, BTN_TOUCH, 1); input_sync(vf50_ts->ts_input); } usleep_range(COLI_PULLUP_MIN_DELAY_US, COLI_PULLUP_MAX_DELAY_US); } /* Report no more touch, re-enable touch detection */ input_report_abs(vf50_ts->ts_input, ABS_PRESSURE, 0); input_report_key(vf50_ts->ts_input, BTN_TOUCH, 0); input_sync(vf50_ts->ts_input); vf50_ts_enable_touch_detection(vf50_ts); return IRQ_HANDLED; } static int vf50_ts_open(struct input_dev *dev_input) { struct vf50_touch_device *touchdev = input_get_drvdata(dev_input); struct device *dev = &touchdev->pdev->dev; dev_dbg(dev, "Input device %s opened, starting touch detection\n", dev_input->name); touchdev->stop_touchscreen = false; /* Mux detection before request IRQ, wait for pull-up to settle */ vf50_ts_enable_touch_detection(touchdev); return 0; } static void vf50_ts_close(struct input_dev *dev_input) { struct vf50_touch_device *touchdev = input_get_drvdata(dev_input); struct device *dev = &touchdev->pdev->dev; touchdev->stop_touchscreen = true; /* Make sure IRQ is not running past close */ mb(); synchronize_irq(touchdev->pen_irq); gpiod_set_value(touchdev->gpio_ym, 0); pinctrl_pm_select_default_state(dev); dev_dbg(dev, "Input device %s closed, disable touch detection\n", dev_input->name); } static int vf50_ts_get_gpiod(struct device *dev, struct gpio_desc **gpio_d, const char *con_id, enum gpiod_flags flags) { int error; *gpio_d = devm_gpiod_get(dev, con_id, flags); if (IS_ERR(*gpio_d)) { error = PTR_ERR(*gpio_d); dev_err(dev, "Could not get gpio_%s %d\n", con_id, error); return error; } return 0; } static void vf50_ts_channel_release(void *data) { struct iio_channel *channels = data; iio_channel_release_all(channels); } static int vf50_ts_probe(struct platform_device *pdev) { struct input_dev *input; struct iio_channel *channels; struct device *dev = &pdev->dev; struct vf50_touch_device *touchdev; int num_adc_channels; int error; channels = iio_channel_get_all(dev); if (IS_ERR(channels)) return PTR_ERR(channels); error = devm_add_action(dev, vf50_ts_channel_release, channels); if (error) { iio_channel_release_all(channels); dev_err(dev, "Failed to register iio channel release action"); return error; } num_adc_channels = 0; while (channels[num_adc_channels].indio_dev) num_adc_channels++; if (num_adc_channels != COLI_TOUCH_REQ_ADC_CHAN) { dev_err(dev, "Inadequate ADC channels specified\n"); return -EINVAL; } touchdev = devm_kzalloc(dev, sizeof(*touchdev), GFP_KERNEL); if (!touchdev) return -ENOMEM; touchdev->pdev = pdev; touchdev->channels = channels; error = of_property_read_u32(dev->of_node, "vf50-ts-min-pressure", &touchdev->min_pressure); if (error) return error; input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "Failed to allocate TS input device\n"); return -ENOMEM; } input->name = DRIVER_NAME; input->id.bustype = BUS_HOST; input->dev.parent = dev; input->open = vf50_ts_open; input->close = vf50_ts_close; input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, 0, VF_ADC_MAX, 0, 0); input_set_abs_params(input, ABS_Y, 0, VF_ADC_MAX, 0, 0); input_set_abs_params(input, ABS_PRESSURE, 0, VF_ADC_MAX, 0, 0); touchdev->ts_input = input; input_set_drvdata(input, touchdev); error = input_register_device(input); if (error) { dev_err(dev, "Failed to register input device\n"); return error; } error = vf50_ts_get_gpiod(dev, &touchdev->gpio_xp, "xp", GPIOD_OUT_LOW); if (error) return error; error = vf50_ts_get_gpiod(dev, &touchdev->gpio_xm, "xm", GPIOD_OUT_LOW); if (error) return error; error = vf50_ts_get_gpiod(dev, &touchdev->gpio_yp, "yp", GPIOD_OUT_LOW); if (error) return error; error = vf50_ts_get_gpiod(dev, &touchdev->gpio_ym, "ym", GPIOD_OUT_LOW); if (error) return error; touchdev->pen_irq = platform_get_irq(pdev, 0); if (touchdev->pen_irq < 0) return touchdev->pen_irq; error = devm_request_threaded_irq(dev, touchdev->pen_irq, NULL, vf50_ts_irq_bh, IRQF_ONESHOT, "vf50 touch", touchdev); if (error) { dev_err(dev, "Failed to request IRQ %d: %d\n", touchdev->pen_irq, error); return error; } return 0; } static const struct of_device_id vf50_touch_of_match[] = { { .compatible = "toradex,vf50-touchscreen", }, { } }; MODULE_DEVICE_TABLE(of, vf50_touch_of_match); static struct platform_driver vf50_touch_driver = { .driver = { .name = "toradex,vf50_touchctrl", .of_match_table = vf50_touch_of_match, }, .probe = vf50_ts_probe, }; module_platform_driver(vf50_touch_driver); MODULE_AUTHOR("Sanchayan Maity"); MODULE_DESCRIPTION("Colibri VF50 Touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/colibri-vf50-ts.c
// SPDX-License-Identifier: GPL-2.0 /* * Raspberry Pi firmware based touchscreen driver * * Copyright (C) 2015, 2017 Raspberry Pi * Copyright (C) 2018 Nicolas Saenz Julienne <[email protected]> */ #include <linux/io.h> #include <linux/of.h> #include <linux/slab.h> #include <linux/device.h> #include <linux/module.h> #include <linux/bitops.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <soc/bcm2835/raspberrypi-firmware.h> #define RPI_TS_DEFAULT_WIDTH 800 #define RPI_TS_DEFAULT_HEIGHT 480 #define RPI_TS_MAX_SUPPORTED_POINTS 10 #define RPI_TS_FTS_TOUCH_DOWN 0 #define RPI_TS_FTS_TOUCH_CONTACT 2 #define RPI_TS_POLL_INTERVAL 17 /* 60fps */ #define RPI_TS_NPOINTS_REG_INVALIDATE 99 struct rpi_ts { struct platform_device *pdev; struct input_dev *input; struct touchscreen_properties prop; void __iomem *fw_regs_va; dma_addr_t fw_regs_phys; int known_ids; }; struct rpi_ts_regs { u8 device_mode; u8 gesture_id; u8 num_points; struct rpi_ts_touch { u8 xh; u8 xl; u8 yh; u8 yl; u8 pressure; /* Not supported */ u8 area; /* Not supported */ } point[RPI_TS_MAX_SUPPORTED_POINTS]; }; static void rpi_ts_poll(struct input_dev *input) { struct rpi_ts *ts = input_get_drvdata(input); struct rpi_ts_regs regs; int modified_ids = 0; long released_ids; int event_type; int touchid; int x, y; int i; memcpy_fromio(&regs, ts->fw_regs_va, sizeof(regs)); /* * We poll the memory based register copy of the touchscreen chip using * the number of points register to know whether the copy has been * updated (we write 99 to the memory copy, the GPU will write between * 0 - 10 points) */ iowrite8(RPI_TS_NPOINTS_REG_INVALIDATE, ts->fw_regs_va + offsetof(struct rpi_ts_regs, num_points)); if (regs.num_points == RPI_TS_NPOINTS_REG_INVALIDATE || (regs.num_points == 0 && ts->known_ids == 0)) return; for (i = 0; i < regs.num_points; i++) { x = (((int)regs.point[i].xh & 0xf) << 8) + regs.point[i].xl; y = (((int)regs.point[i].yh & 0xf) << 8) + regs.point[i].yl; touchid = (regs.point[i].yh >> 4) & 0xf; event_type = (regs.point[i].xh >> 6) & 0x03; modified_ids |= BIT(touchid); if (event_type == RPI_TS_FTS_TOUCH_DOWN || event_type == RPI_TS_FTS_TOUCH_CONTACT) { input_mt_slot(input, touchid); input_mt_report_slot_state(input, MT_TOOL_FINGER, 1); touchscreen_report_pos(input, &ts->prop, x, y, true); } } released_ids = ts->known_ids & ~modified_ids; for_each_set_bit(i, &released_ids, RPI_TS_MAX_SUPPORTED_POINTS) { input_mt_slot(input, i); input_mt_report_slot_inactive(input); modified_ids &= ~(BIT(i)); } ts->known_ids = modified_ids; input_mt_sync_frame(input); input_sync(input); } static void rpi_ts_dma_cleanup(void *data) { struct rpi_ts *ts = data; struct device *dev = &ts->pdev->dev; dma_free_coherent(dev, PAGE_SIZE, ts->fw_regs_va, ts->fw_regs_phys); } static int rpi_ts_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct input_dev *input; struct device_node *fw_node; struct rpi_firmware *fw; struct rpi_ts *ts; u32 touchbuf; int error; fw_node = of_get_parent(np); if (!fw_node) { dev_err(dev, "Missing firmware node\n"); return -ENOENT; } fw = devm_rpi_firmware_get(&pdev->dev, fw_node); of_node_put(fw_node); if (!fw) return -EPROBE_DEFER; ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->pdev = pdev; ts->fw_regs_va = dma_alloc_coherent(dev, PAGE_SIZE, &ts->fw_regs_phys, GFP_KERNEL); if (!ts->fw_regs_va) { dev_err(dev, "failed to dma_alloc_coherent\n"); return -ENOMEM; } error = devm_add_action_or_reset(dev, rpi_ts_dma_cleanup, ts); if (error) { dev_err(dev, "failed to devm_add_action_or_reset, %d\n", error); return error; } touchbuf = (u32)ts->fw_regs_phys; error = rpi_firmware_property(fw, RPI_FIRMWARE_FRAMEBUFFER_SET_TOUCHBUF, &touchbuf, sizeof(touchbuf)); if (error || touchbuf != 0) { dev_warn(dev, "Failed to set touchbuf, %d\n", error); return error; } input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } ts->input = input; input_set_drvdata(input, ts); input->name = "raspberrypi-ts"; input->id.bustype = BUS_HOST; input_set_abs_params(input, ABS_MT_POSITION_X, 0, RPI_TS_DEFAULT_WIDTH, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, RPI_TS_DEFAULT_HEIGHT, 0, 0); touchscreen_parse_properties(input, true, &ts->prop); error = input_mt_init_slots(input, RPI_TS_MAX_SUPPORTED_POINTS, INPUT_MT_DIRECT); if (error) { dev_err(dev, "could not init mt slots, %d\n", error); return error; } error = input_setup_polling(input, rpi_ts_poll); if (error) { dev_err(dev, "could not set up polling mode, %d\n", error); return error; } input_set_poll_interval(input, RPI_TS_POLL_INTERVAL); error = input_register_device(input); if (error) { dev_err(dev, "could not register input device, %d\n", error); return error; } return 0; } static const struct of_device_id rpi_ts_match[] = { { .compatible = "raspberrypi,firmware-ts", }, {}, }; MODULE_DEVICE_TABLE(of, rpi_ts_match); static struct platform_driver rpi_ts_driver = { .driver = { .name = "raspberrypi-ts", .of_match_table = rpi_ts_match, }, .probe = rpi_ts_probe, }; module_platform_driver(rpi_ts_driver); MODULE_AUTHOR("Gordon Hollingworth"); MODULE_AUTHOR("Nicolas Saenz Julienne <[email protected]>"); MODULE_DESCRIPTION("Raspberry Pi firmware based touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/raspberrypi-ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * wm9712.c -- Codec driver for Wolfson WM9712 AC97 Codecs. * * Copyright 2003, 2004, 2005, 2006, 2007 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 WM9712_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 = 3; 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 WM9712 */ static void wm9712_phy_init(struct wm97xx *wm) { u16 dig1 = 0; u16 dig2 = WM97XX_RPR | WM9712_RPU(1); /* WM9712 rpu */ if (rpu) { dig2 &= 0xffc0; dig2 |= WM9712_RPU(rpu); dev_dbg(wm->dev, "setting pen detect pull-up to %d Ohms\n", 64000 / rpu); } /* WM9712 five wire */ if (five_wire) { dig2 |= WM9712_45W; dev_dbg(wm->dev, "setting 5-wire touchscreen mode.\n"); if (pil) { dev_warn(wm->dev, "pressure measurement is not " "supported in 5-wire mode\n"); pil = 0; } } /* touchpanel pressure current*/ if (pil == 2) { dig2 |= WM9712_PIL; dev_dbg(wm->dev, "setting pressure measurement current to 400uA.\n"); } else if (pil) dev_dbg(wm->dev, "setting pressure measurement current to 200uA.\n"); if (!pil) pressure = 0; /* polling mode sample settling delay */ if (delay < 0 || delay > 15) { dev_dbg(wm->dev, "supplied delay out of range.\n"); delay = 4; } dig1 &= 0xff0f; dig1 |= WM97XX_DELAY(delay); dev_dbg(wm->dev, "setting adc sample delay to %d u Secs.\n", delay_table[delay]); /* mask */ dig2 |= ((mask & 0x3) << 6); if (mask) { u16 reg; /* Set GPIO4 as Mask Pin*/ reg = wm97xx_reg_read(wm, AC97_MISC_AFE); wm97xx_reg_write(wm, AC97_MISC_AFE, reg | WM97XX_GPIO_4); reg = wm97xx_reg_read(wm, AC97_GPIO_CFG); wm97xx_reg_write(wm, AC97_GPIO_CFG, reg | WM97XX_GPIO_4); } /* wait - coord mode */ if (coord) dig2 |= WM9712_WAIT; wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, dig1); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2); } static void wm9712_dig_enable(struct wm97xx *wm, int enable) { u16 dig2 = wm->dig[2]; if (enable) { wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2 | WM97XX_PRP_DET_DIG); wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); /* dummy read */ } else wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2 & ~WM97XX_PRP_DET_DIG); } static void wm9712_aux_prepare(struct wm97xx *wm) { memcpy(wm->dig_save, wm->dig, sizeof(wm->dig)); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, 0); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, WM97XX_PRP_DET_DIG); } static void wm9712_dig_restore(struct wm97xx *wm) { wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, wm->dig_save[1]); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, wm->dig_save[2]); } static inline int is_pden(struct wm97xx *wm) { return wm->dig[2] & WM9712_PDEN; } /* * Read a sample from the WM9712 adc in polling mode. */ static int wm9712_poll_sample(struct wm97xx *wm, int adcsel, int *sample) { 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 */ if (wm->mach_ops && wm->mach_ops->pre_sample) wm->mach_ops->pre_sample(adcsel); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, (adcsel & WM97XX_ADCSEL_MASK) | WM97XX_POLL | WM97XX_DELAY(delay)); /* wait 3 AC97 time slots + delay for conversion */ poll_delay(delay); /* wait for POLL to go low */ while ((wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER1) & WM97XX_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\n"); 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\n", adcsel & WM97XX_ADCSEL_MASK, *sample & WM97XX_ADCSEL_MASK); return RC_AGAIN; } if (wants_pen && !(*sample & WM97XX_PEN_DOWN)) { /* Sometimes it reads a wrong value the first time. */ *sample = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (!(*sample & WM97XX_PEN_DOWN)) { wm->pen_probably_down = 0; return RC_PENUP; } } return RC_VALID; } /* * Read a coord from the WM9712 adc in polling mode. */ static int wm9712_poll_coord(struct wm97xx *wm, struct wm97xx_data *data) { int timeout = 5 * delay; if (!wm->pen_probably_down) { u16 data_rd = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); if (!(data_rd & WM97XX_PEN_DOWN)) return RC_PENUP; wm->pen_probably_down = 1; } /* set up digitiser */ 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_WM97XX_DIGITISER1, WM97XX_COO | WM97XX_POLL | WM97XX_DELAY(delay)); /* wait 3 AC97 time slots + delay for conversion and read x */ 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_WM97XX_DIGITISER1) & WM97XX_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\n"); return RC_PENUP; } /* read back y 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 WM9712 touchscreen in polling mode */ static int wm9712_poll_touch(struct wm97xx *wm, struct wm97xx_data *data) { int rc; if (coord) { rc = wm9712_poll_coord(wm, data); if (rc != RC_VALID) return rc; } else { rc = wm9712_poll_sample(wm, WM97XX_ADCSEL_X | WM97XX_PEN_DOWN, &data->x); if (rc != RC_VALID) return rc; rc = wm9712_poll_sample(wm, WM97XX_ADCSEL_Y | WM97XX_PEN_DOWN, &data->y); if (rc != RC_VALID) return rc; if (pil && !five_wire) { rc = wm9712_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 WM9712 continuous mode, i.e. touch data is streamed across * an AC97 slot */ static int wm9712_acc_enable(struct wm97xx *wm, int enable) { u16 dig1, dig2; int ret = 0; dig1 = wm->dig[1]; dig2 = wm->dig[2]; if (enable) { /* continuous mode */ if (wm->mach_ops->acc_startup) { ret = wm->mach_ops->acc_startup(wm); if (ret < 0) return ret; } dig1 &= ~(WM97XX_CM_RATE_MASK | WM97XX_ADCSEL_MASK | WM97XX_DELAY_MASK | WM97XX_SLT_MASK); dig1 |= WM97XX_CTC | WM97XX_COO | WM97XX_SLEN | WM97XX_DELAY(delay) | WM97XX_SLT(wm->acc_slot) | WM97XX_RATE(wm->acc_rate); if (pil) dig1 |= WM97XX_ADCSEL_PRES; dig2 |= WM9712_PDEN; } else { dig1 &= ~(WM97XX_CTC | WM97XX_COO | WM97XX_SLEN); dig2 &= ~WM9712_PDEN; if (wm->mach_ops->acc_shutdown) wm->mach_ops->acc_shutdown(wm); } wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, dig1); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2); return 0; } struct wm97xx_codec_drv wm9712_codec = { .id = WM9712_ID2, .name = "wm9712", .poll_sample = wm9712_poll_sample, .poll_touch = wm9712_poll_touch, .acc_enable = wm9712_acc_enable, .phy_init = wm9712_phy_init, .dig_enable = wm9712_dig_enable, .dig_restore = wm9712_dig_restore, .aux_prepare = wm9712_aux_prepare, }; EXPORT_SYMBOL_GPL(wm9712_codec); /* Module information */ MODULE_AUTHOR("Liam Girdwood <[email protected]>"); MODULE_DESCRIPTION("WM9712 Touch Screen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wm9712.c
// SPDX-License-Identifier: GPL-2.0-only /* * Source for: * Cypress TrueTouch(TM) Standard Product (TTSP) SPI touchscreen driver. * For use with Cypress Txx4xx parts. * Supported parts include: * TMA4XX * TMA1036 * * Copyright (C) 2009, 2010, 2011 Cypress Semiconductor, Inc. * Copyright (C) 2012 Javier Martinez Canillas <[email protected]> * Copyright (C) 2013 Cypress Semiconductor * * Contact Cypress Semiconductor at www.cypress.com <[email protected]> */ #include "cyttsp4_core.h" #include <linux/delay.h> #include <linux/input.h> #include <linux/spi/spi.h> #define CY_SPI_WR_OP 0x00 /* r/~w */ #define CY_SPI_RD_OP 0x01 #define CY_SPI_BITS_PER_WORD 8 #define CY_SPI_A8_BIT 0x02 #define CY_SPI_WR_HEADER_BYTES 2 #define CY_SPI_RD_HEADER_BYTES 1 #define CY_SPI_CMD_BYTES 2 #define CY_SPI_SYNC_BYTE 0 #define CY_SPI_SYNC_ACK 0x62 /* from TRM *A protocol */ #define CY_SPI_DATA_SIZE (2 * 256) #define CY_SPI_DATA_BUF_SIZE (CY_SPI_CMD_BYTES + CY_SPI_DATA_SIZE) static int cyttsp_spi_xfer(struct device *dev, u8 *xfer_buf, u8 op, u16 reg, u8 *buf, int length) { struct spi_device *spi = to_spi_device(dev); struct spi_message msg; struct spi_transfer xfer[2]; u8 *wr_buf = &xfer_buf[0]; u8 rd_buf[CY_SPI_CMD_BYTES]; int retval; int i; if (length > CY_SPI_DATA_SIZE) { dev_err(dev, "%s: length %d is too big.\n", __func__, length); return -EINVAL; } memset(wr_buf, 0, CY_SPI_DATA_BUF_SIZE); memset(rd_buf, 0, CY_SPI_CMD_BYTES); wr_buf[0] = op + (((reg >> 8) & 0x1) ? CY_SPI_A8_BIT : 0); if (op == CY_SPI_WR_OP) { wr_buf[1] = reg & 0xFF; if (length > 0) memcpy(wr_buf + CY_SPI_CMD_BYTES, buf, length); } memset(xfer, 0, sizeof(xfer)); spi_message_init(&msg); /* We set both TX and RX buffers because Cypress TTSP requires full duplex operation. */ xfer[0].tx_buf = wr_buf; xfer[0].rx_buf = rd_buf; switch (op) { case CY_SPI_WR_OP: xfer[0].len = length + CY_SPI_CMD_BYTES; spi_message_add_tail(&xfer[0], &msg); break; case CY_SPI_RD_OP: xfer[0].len = CY_SPI_RD_HEADER_BYTES; spi_message_add_tail(&xfer[0], &msg); xfer[1].rx_buf = buf; xfer[1].len = length; spi_message_add_tail(&xfer[1], &msg); break; default: dev_err(dev, "%s: bad operation code=%d\n", __func__, op); return -EINVAL; } retval = spi_sync(spi, &msg); if (retval < 0) { dev_dbg(dev, "%s: spi_sync() error %d, len=%d, op=%d\n", __func__, retval, xfer[1].len, op); /* * do not return here since was a bad ACK sequence * let the following ACK check handle any errors and * allow silent retries */ } if (rd_buf[CY_SPI_SYNC_BYTE] != CY_SPI_SYNC_ACK) { dev_dbg(dev, "%s: operation %d failed\n", __func__, op); for (i = 0; i < CY_SPI_CMD_BYTES; i++) dev_dbg(dev, "%s: test rd_buf[%d]:0x%02x\n", __func__, i, rd_buf[i]); for (i = 0; i < length; i++) dev_dbg(dev, "%s: test buf[%d]:0x%02x\n", __func__, i, buf[i]); return -EIO; } return 0; } static int cyttsp_spi_read_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, void *data) { int rc; rc = cyttsp_spi_xfer(dev, xfer_buf, CY_SPI_WR_OP, addr, NULL, 0); if (rc) return rc; else return cyttsp_spi_xfer(dev, xfer_buf, CY_SPI_RD_OP, addr, data, length); } static int cyttsp_spi_write_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, const void *data) { return cyttsp_spi_xfer(dev, xfer_buf, CY_SPI_WR_OP, addr, (void *)data, length); } static const struct cyttsp4_bus_ops cyttsp_spi_bus_ops = { .bustype = BUS_SPI, .write = cyttsp_spi_write_block_data, .read = cyttsp_spi_read_block_data, }; static int cyttsp4_spi_probe(struct spi_device *spi) { struct cyttsp4 *ts; int error; /* Set up SPI*/ spi->bits_per_word = CY_SPI_BITS_PER_WORD; spi->mode = SPI_MODE_0; error = spi_setup(spi); if (error < 0) { dev_err(&spi->dev, "%s: SPI setup error %d\n", __func__, error); return error; } ts = cyttsp4_probe(&cyttsp_spi_bus_ops, &spi->dev, spi->irq, CY_SPI_DATA_BUF_SIZE); return PTR_ERR_OR_ZERO(ts); } static void cyttsp4_spi_remove(struct spi_device *spi) { struct cyttsp4 *ts = spi_get_drvdata(spi); cyttsp4_remove(ts); } static struct spi_driver cyttsp4_spi_driver = { .driver = { .name = CYTTSP4_SPI_NAME, .pm = pm_ptr(&cyttsp4_pm_ops), }, .probe = cyttsp4_spi_probe, .remove = cyttsp4_spi_remove, }; module_spi_driver(cyttsp4_spi_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard Product (TTSP) SPI driver"); MODULE_AUTHOR("Cypress"); MODULE_ALIAS("spi:cyttsp4");
linux-master
drivers/input/touchscreen/cyttsp4_spi.c
// SPDX-License-Identifier: GPL-2.0-only /* * Hampshire serial touchscreen driver * * Copyright (c) 2010 Adam Bennett * Based on the dynapro driver (c) Tias Guns */ /* * 2010/04/08 Adam Bennett <[email protected]> * Copied dynapro.c and edited for Hampshire 4-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> #define DRIVER_DESC "Hampshire serial touchscreen driver" MODULE_AUTHOR("Adam Bennett <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define HAMPSHIRE_FORMAT_TOUCH_BIT 0x40 #define HAMPSHIRE_FORMAT_LENGTH 4 #define HAMPSHIRE_RESPONSE_BEGIN_BYTE 0x80 #define HAMPSHIRE_MIN_XC 0 #define HAMPSHIRE_MAX_XC 0x1000 #define HAMPSHIRE_MIN_YC 0 #define HAMPSHIRE_MAX_YC 0x1000 #define HAMPSHIRE_GET_XC(data) (((data[3] & 0x0c) >> 2) | (data[1] << 2) | ((data[0] & 0x38) << 6)) #define HAMPSHIRE_GET_YC(data) ((data[3] & 0x03) | (data[2] << 2) | ((data[0] & 0x07) << 9)) #define HAMPSHIRE_GET_TOUCHED(data) (HAMPSHIRE_FORMAT_TOUCH_BIT & data[0]) /* * Per-touchscreen data. */ struct hampshire { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[HAMPSHIRE_FORMAT_LENGTH]; char phys[32]; }; static void hampshire_process_data(struct hampshire *phampshire) { struct input_dev *dev = phampshire->dev; if (HAMPSHIRE_FORMAT_LENGTH == ++phampshire->idx) { input_report_abs(dev, ABS_X, HAMPSHIRE_GET_XC(phampshire->data)); input_report_abs(dev, ABS_Y, HAMPSHIRE_GET_YC(phampshire->data)); input_report_key(dev, BTN_TOUCH, HAMPSHIRE_GET_TOUCHED(phampshire->data)); input_sync(dev); phampshire->idx = 0; } } static irqreturn_t hampshire_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct hampshire *phampshire = serio_get_drvdata(serio); phampshire->data[phampshire->idx] = data; if (HAMPSHIRE_RESPONSE_BEGIN_BYTE & phampshire->data[0]) hampshire_process_data(phampshire); else dev_dbg(&serio->dev, "unknown/unsynchronized data: %x\n", phampshire->data[0]); return IRQ_HANDLED; } static void hampshire_disconnect(struct serio *serio) { struct hampshire *phampshire = serio_get_drvdata(serio); input_get_device(phampshire->dev); input_unregister_device(phampshire->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(phampshire->dev); kfree(phampshire); } /* * hampshire_connect() is the routine that is called when someone adds a * new serio device that supports hampshire protocol and registers it as * an input device. This is usually accomplished using inputattach. */ static int hampshire_connect(struct serio *serio, struct serio_driver *drv) { struct hampshire *phampshire; struct input_dev *input_dev; int err; phampshire = kzalloc(sizeof(struct hampshire), GFP_KERNEL); input_dev = input_allocate_device(); if (!phampshire || !input_dev) { err = -ENOMEM; goto fail1; } phampshire->serio = serio; phampshire->dev = input_dev; snprintf(phampshire->phys, sizeof(phampshire->phys), "%s/input0", serio->phys); input_dev->name = "Hampshire Serial TouchScreen"; input_dev->phys = phampshire->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_HAMPSHIRE; 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(phampshire->dev, ABS_X, HAMPSHIRE_MIN_XC, HAMPSHIRE_MAX_XC, 0, 0); input_set_abs_params(phampshire->dev, ABS_Y, HAMPSHIRE_MIN_YC, HAMPSHIRE_MAX_YC, 0, 0); serio_set_drvdata(serio, phampshire); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(phampshire->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(phampshire); return err; } /* * The serio driver structure. */ static const struct serio_device_id hampshire_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_HAMPSHIRE, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, hampshire_serio_ids); static struct serio_driver hampshire_drv = { .driver = { .name = "hampshire", }, .description = DRIVER_DESC, .id_table = hampshire_serio_ids, .interrupt = hampshire_interrupt, .connect = hampshire_connect, .disconnect = hampshire_disconnect, }; module_serio_driver(hampshire_drv);
linux-master
drivers/input/touchscreen/hampshire.c
// SPDX-License-Identifier: GPL-2.0 // Melfas MMS114/MMS136/MMS152 touchscreen device driver // // Copyright (c) 2012 Samsung Electronics Co., Ltd. // Author: Joonyoung Shim <[email protected]> #include <linux/module.h> #include <linux/delay.h> #include <linux/of.h> #include <linux/i2c.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> /* Write only registers */ #define MMS114_MODE_CONTROL 0x01 #define MMS114_OPERATION_MODE_MASK 0xE #define MMS114_ACTIVE BIT(1) #define MMS114_XY_RESOLUTION_H 0x02 #define MMS114_X_RESOLUTION 0x03 #define MMS114_Y_RESOLUTION 0x04 #define MMS114_CONTACT_THRESHOLD 0x05 #define MMS114_MOVING_THRESHOLD 0x06 /* Read only registers */ #define MMS114_PACKET_SIZE 0x0F #define MMS114_INFORMATION 0x10 #define MMS114_TSP_REV 0xF0 #define MMS152_FW_REV 0xE1 #define MMS152_COMPAT_GROUP 0xF2 /* Minimum delay time is 50us between stop and start signal of i2c */ #define MMS114_I2C_DELAY 50 /* 200ms needs after power on */ #define MMS114_POWERON_DELAY 200 /* Touchscreen absolute values */ #define MMS114_MAX_AREA 0xff #define MMS114_MAX_TOUCHKEYS 15 #define MMS114_MAX_TOUCH 10 #define MMS114_EVENT_SIZE 8 #define MMS136_EVENT_SIZE 6 /* Touch type */ #define MMS114_TYPE_NONE 0 #define MMS114_TYPE_TOUCHSCREEN 1 #define MMS114_TYPE_TOUCHKEY 2 enum mms_type { TYPE_MMS114 = 114, TYPE_MMS134S = 134, TYPE_MMS136 = 136, TYPE_MMS152 = 152, TYPE_MMS345L = 345, }; struct mms114_data { struct i2c_client *client; struct input_dev *input_dev; struct regulator *core_reg; struct regulator *io_reg; struct touchscreen_properties props; enum mms_type type; unsigned int contact_threshold; unsigned int moving_threshold; u32 keycodes[MMS114_MAX_TOUCHKEYS]; int num_keycodes; /* Use cache data for mode control register(write only) */ u8 cache_mode_control; }; struct mms114_touch { u8 id:4, reserved_bit4:1, type:2, pressed:1; u8 x_hi:4, y_hi:4; u8 x_lo; u8 y_lo; u8 width; u8 strength; u8 reserved[2]; } __packed; static int __mms114_read_reg(struct mms114_data *data, unsigned int reg, unsigned int len, u8 *val) { struct i2c_client *client = data->client; struct i2c_msg xfer[2]; u8 buf = reg & 0xff; int error; if (reg <= MMS114_MODE_CONTROL && reg + len > MMS114_MODE_CONTROL) BUG(); /* Write register */ xfer[0].addr = client->addr; xfer[0].flags = client->flags & I2C_M_TEN; xfer[0].len = 1; xfer[0].buf = &buf; /* Read data */ xfer[1].addr = client->addr; xfer[1].flags = (client->flags & I2C_M_TEN) | I2C_M_RD; xfer[1].len = len; xfer[1].buf = val; error = i2c_transfer(client->adapter, xfer, 2); if (error != 2) { dev_err(&client->dev, "%s: i2c transfer failed (%d)\n", __func__, error); return error < 0 ? error : -EIO; } udelay(MMS114_I2C_DELAY); return 0; } static int mms114_read_reg(struct mms114_data *data, unsigned int reg) { u8 val; int error; if (reg == MMS114_MODE_CONTROL) return data->cache_mode_control; error = __mms114_read_reg(data, reg, 1, &val); return error < 0 ? error : val; } static int mms114_write_reg(struct mms114_data *data, unsigned int reg, unsigned int val) { struct i2c_client *client = data->client; u8 buf[2]; int error; buf[0] = reg & 0xff; buf[1] = val & 0xff; error = i2c_master_send(client, buf, 2); if (error != 2) { dev_err(&client->dev, "%s: i2c send failed (%d)\n", __func__, error); return error < 0 ? error : -EIO; } udelay(MMS114_I2C_DELAY); if (reg == MMS114_MODE_CONTROL) data->cache_mode_control = val; return 0; } static void mms114_process_mt(struct mms114_data *data, struct mms114_touch *touch) { struct i2c_client *client = data->client; struct input_dev *input_dev = data->input_dev; unsigned int id; unsigned int x; unsigned int y; if (touch->id > MMS114_MAX_TOUCH) { dev_err(&client->dev, "Wrong touch id (%d)\n", touch->id); return; } id = touch->id - 1; x = touch->x_lo | touch->x_hi << 8; y = touch->y_lo | touch->y_hi << 8; dev_dbg(&client->dev, "id: %d, type: %d, pressed: %d, x: %d, y: %d, width: %d, strength: %d\n", id, touch->type, touch->pressed, x, y, touch->width, touch->strength); input_mt_slot(input_dev, id); input_mt_report_slot_state(input_dev, MT_TOOL_FINGER, touch->pressed); if (touch->pressed) { touchscreen_report_pos(input_dev, &data->props, x, y, true); input_report_abs(input_dev, ABS_MT_TOUCH_MAJOR, touch->width); input_report_abs(input_dev, ABS_MT_PRESSURE, touch->strength); } } static void mms114_process_touchkey(struct mms114_data *data, struct mms114_touch *touch) { struct i2c_client *client = data->client; struct input_dev *input_dev = data->input_dev; unsigned int keycode_id; if (touch->id == 0) return; if (touch->id > data->num_keycodes) { dev_err(&client->dev, "Wrong touch id for touchkey (%d)\n", touch->id); return; } keycode_id = touch->id - 1; dev_dbg(&client->dev, "keycode id: %d, pressed: %d\n", keycode_id, touch->pressed); input_report_key(input_dev, data->keycodes[keycode_id], touch->pressed); } static irqreturn_t mms114_interrupt(int irq, void *dev_id) { struct mms114_data *data = dev_id; struct i2c_client *client = data->client; struct input_dev *input_dev = data->input_dev; struct mms114_touch touch[MMS114_MAX_TOUCH]; int packet_size; int touch_size; int index; int error; mutex_lock(&input_dev->mutex); if (!input_device_enabled(input_dev)) { mutex_unlock(&input_dev->mutex); goto out; } mutex_unlock(&input_dev->mutex); packet_size = mms114_read_reg(data, MMS114_PACKET_SIZE); if (packet_size <= 0) goto out; /* MMS136 has slightly different event size */ if (data->type == TYPE_MMS134S || data->type == TYPE_MMS136) touch_size = packet_size / MMS136_EVENT_SIZE; else touch_size = packet_size / MMS114_EVENT_SIZE; error = __mms114_read_reg(data, MMS114_INFORMATION, packet_size, (u8 *)touch); if (error < 0) goto out; for (index = 0; index < touch_size; index++) { switch (touch[index].type) { case MMS114_TYPE_TOUCHSCREEN: mms114_process_mt(data, touch + index); break; case MMS114_TYPE_TOUCHKEY: mms114_process_touchkey(data, touch + index); break; default: dev_err(&client->dev, "Wrong touch type (%d)\n", touch[index].type); break; } } input_mt_report_pointer_emulation(data->input_dev, true); input_sync(data->input_dev); out: return IRQ_HANDLED; } static int mms114_set_active(struct mms114_data *data, bool active) { int val; val = mms114_read_reg(data, MMS114_MODE_CONTROL); if (val < 0) return val; val &= ~MMS114_OPERATION_MODE_MASK; /* If active is false, sleep mode */ if (active) val |= MMS114_ACTIVE; return mms114_write_reg(data, MMS114_MODE_CONTROL, val); } static int mms114_get_version(struct mms114_data *data) { struct device *dev = &data->client->dev; u8 buf[6]; int group; int error; switch (data->type) { case TYPE_MMS345L: error = __mms114_read_reg(data, MMS152_FW_REV, 3, buf); if (error) return error; dev_info(dev, "TSP FW Rev: bootloader 0x%x / core 0x%x / config 0x%x\n", buf[0], buf[1], buf[2]); break; case TYPE_MMS152: error = __mms114_read_reg(data, MMS152_FW_REV, 3, buf); if (error) return error; group = i2c_smbus_read_byte_data(data->client, MMS152_COMPAT_GROUP); if (group < 0) return group; dev_info(dev, "TSP FW Rev: bootloader 0x%x / core 0x%x / config 0x%x, Compat group: %c\n", buf[0], buf[1], buf[2], group); break; case TYPE_MMS114: case TYPE_MMS134S: case TYPE_MMS136: error = __mms114_read_reg(data, MMS114_TSP_REV, 6, buf); if (error) return error; dev_info(dev, "TSP Rev: 0x%x, HW Rev: 0x%x, Firmware Ver: 0x%x\n", buf[0], buf[1], buf[3]); break; } return 0; } static int mms114_setup_regs(struct mms114_data *data) { const struct touchscreen_properties *props = &data->props; int val; int error; error = mms114_get_version(data); if (error < 0) return error; /* MMS114, MMS134S and MMS136 have configuration and power on registers */ if (data->type != TYPE_MMS114 && data->type != TYPE_MMS134S && data->type != TYPE_MMS136) return 0; error = mms114_set_active(data, true); if (error < 0) return error; val = (props->max_x >> 8) & 0xf; val |= ((props->max_y >> 8) & 0xf) << 4; error = mms114_write_reg(data, MMS114_XY_RESOLUTION_H, val); if (error < 0) return error; val = props->max_x & 0xff; error = mms114_write_reg(data, MMS114_X_RESOLUTION, val); if (error < 0) return error; val = props->max_x & 0xff; error = mms114_write_reg(data, MMS114_Y_RESOLUTION, val); if (error < 0) return error; if (data->contact_threshold) { error = mms114_write_reg(data, MMS114_CONTACT_THRESHOLD, data->contact_threshold); if (error < 0) return error; } if (data->moving_threshold) { error = mms114_write_reg(data, MMS114_MOVING_THRESHOLD, data->moving_threshold); if (error < 0) return error; } return 0; } static int mms114_start(struct mms114_data *data) { struct i2c_client *client = data->client; int error; error = regulator_enable(data->core_reg); if (error) { dev_err(&client->dev, "Failed to enable avdd: %d\n", error); return error; } error = regulator_enable(data->io_reg); if (error) { dev_err(&client->dev, "Failed to enable vdd: %d\n", error); regulator_disable(data->core_reg); return error; } msleep(MMS114_POWERON_DELAY); error = mms114_setup_regs(data); if (error < 0) { regulator_disable(data->io_reg); regulator_disable(data->core_reg); return error; } enable_irq(client->irq); return 0; } static void mms114_stop(struct mms114_data *data) { struct i2c_client *client = data->client; int error; disable_irq(client->irq); error = regulator_disable(data->io_reg); if (error) dev_warn(&client->dev, "Failed to disable vdd: %d\n", error); error = regulator_disable(data->core_reg); if (error) dev_warn(&client->dev, "Failed to disable avdd: %d\n", error); } static int mms114_input_open(struct input_dev *dev) { struct mms114_data *data = input_get_drvdata(dev); return mms114_start(data); } static void mms114_input_close(struct input_dev *dev) { struct mms114_data *data = input_get_drvdata(dev); mms114_stop(data); } static int mms114_parse_legacy_bindings(struct mms114_data *data) { struct device *dev = &data->client->dev; struct touchscreen_properties *props = &data->props; if (device_property_read_u32(dev, "x-size", &props->max_x)) { dev_dbg(dev, "failed to get legacy x-size property\n"); return -EINVAL; } if (device_property_read_u32(dev, "y-size", &props->max_y)) { dev_dbg(dev, "failed to get legacy y-size property\n"); return -EINVAL; } device_property_read_u32(dev, "contact-threshold", &data->contact_threshold); device_property_read_u32(dev, "moving-threshold", &data->moving_threshold); if (device_property_read_bool(dev, "x-invert")) props->invert_x = true; if (device_property_read_bool(dev, "y-invert")) props->invert_y = true; props->swap_x_y = false; return 0; } static int mms114_probe(struct i2c_client *client) { struct mms114_data *data; struct input_dev *input_dev; const void *match_data; int error; int i; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "Not supported I2C adapter\n"); return -ENODEV; } data = devm_kzalloc(&client->dev, sizeof(struct mms114_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; match_data = device_get_match_data(&client->dev); if (!match_data) return -EINVAL; data->type = (enum mms_type)match_data; data->num_keycodes = device_property_count_u32(&client->dev, "linux,keycodes"); if (data->num_keycodes == -EINVAL) { data->num_keycodes = 0; } else if (data->num_keycodes < 0) { dev_err(&client->dev, "Unable to parse linux,keycodes property: %d\n", data->num_keycodes); return data->num_keycodes; } else if (data->num_keycodes > MMS114_MAX_TOUCHKEYS) { dev_warn(&client->dev, "Found %d linux,keycodes but max is %d, ignoring the rest\n", data->num_keycodes, MMS114_MAX_TOUCHKEYS); data->num_keycodes = MMS114_MAX_TOUCHKEYS; } if (data->num_keycodes > 0) { error = device_property_read_u32_array(&client->dev, "linux,keycodes", data->keycodes, data->num_keycodes); if (error) { dev_err(&client->dev, "Unable to read linux,keycodes values: %d\n", error); return error; } input_dev->keycode = data->keycodes; input_dev->keycodemax = data->num_keycodes; input_dev->keycodesize = sizeof(data->keycodes[0]); for (i = 0; i < data->num_keycodes; i++) input_set_capability(input_dev, EV_KEY, data->keycodes[i]); } 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_PRESSURE, 0, 255, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, MMS114_MAX_AREA, 0, 0); touchscreen_parse_properties(input_dev, true, &data->props); if (!data->props.max_x || !data->props.max_y) { dev_dbg(&client->dev, "missing X/Y size properties, trying legacy bindings\n"); error = mms114_parse_legacy_bindings(data); if (error) return error; input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, data->props.max_x, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, data->props.max_y, 0, 0); } if (data->type == TYPE_MMS114 || data->type == TYPE_MMS134S || data->type == TYPE_MMS136) { /* * The firmware handles movement and pressure fuzz, so * don't duplicate that in software. */ data->moving_threshold = input_abs_get_fuzz(input_dev, ABS_MT_POSITION_X); data->contact_threshold = input_abs_get_fuzz(input_dev, ABS_MT_PRESSURE); input_abs_set_fuzz(input_dev, ABS_MT_POSITION_X, 0); input_abs_set_fuzz(input_dev, ABS_MT_POSITION_Y, 0); input_abs_set_fuzz(input_dev, ABS_MT_PRESSURE, 0); } input_dev->name = devm_kasprintf(&client->dev, GFP_KERNEL, "MELFAS MMS%d Touchscreen", data->type); if (!input_dev->name) return -ENOMEM; input_dev->id.bustype = BUS_I2C; input_dev->dev.parent = &client->dev; input_dev->open = mms114_input_open; input_dev->close = mms114_input_close; error = input_mt_init_slots(input_dev, MMS114_MAX_TOUCH, INPUT_MT_DIRECT); if (error) return error; input_set_drvdata(input_dev, data); i2c_set_clientdata(client, data); data->core_reg = devm_regulator_get(&client->dev, "avdd"); if (IS_ERR(data->core_reg)) { error = PTR_ERR(data->core_reg); dev_err(&client->dev, "Unable to get the Core regulator (%d)\n", error); return error; } data->io_reg = devm_regulator_get(&client->dev, "vdd"); if (IS_ERR(data->io_reg)) { error = PTR_ERR(data->io_reg); dev_err(&client->dev, "Unable to get the IO regulator (%d)\n", error); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, mms114_interrupt, IRQF_ONESHOT | IRQF_NO_AUTOEN, dev_name(&client->dev), 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; } return 0; } static int mms114_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mms114_data *data = i2c_get_clientdata(client); struct input_dev *input_dev = data->input_dev; int id; /* Release all touch */ for (id = 0; id < MMS114_MAX_TOUCH; id++) { input_mt_slot(input_dev, id); input_mt_report_slot_inactive(input_dev); } input_mt_report_pointer_emulation(input_dev, true); input_sync(input_dev); mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) mms114_stop(data); mutex_unlock(&input_dev->mutex); return 0; } static int mms114_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mms114_data *data = i2c_get_clientdata(client); struct input_dev *input_dev = data->input_dev; int error; mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) { error = mms114_start(data); if (error < 0) { mutex_unlock(&input_dev->mutex); return error; } } mutex_unlock(&input_dev->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(mms114_pm_ops, mms114_suspend, mms114_resume); static const struct i2c_device_id mms114_id[] = { { "mms114", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mms114_id); #ifdef CONFIG_OF static const struct of_device_id mms114_dt_match[] = { { .compatible = "melfas,mms114", .data = (void *)TYPE_MMS114, }, { .compatible = "melfas,mms134s", .data = (void *)TYPE_MMS134S, }, { .compatible = "melfas,mms136", .data = (void *)TYPE_MMS136, }, { .compatible = "melfas,mms152", .data = (void *)TYPE_MMS152, }, { .compatible = "melfas,mms345l", .data = (void *)TYPE_MMS345L, }, { } }; MODULE_DEVICE_TABLE(of, mms114_dt_match); #endif static struct i2c_driver mms114_driver = { .driver = { .name = "mms114", .pm = pm_sleep_ptr(&mms114_pm_ops), .of_match_table = of_match_ptr(mms114_dt_match), }, .probe = mms114_probe, .id_table = mms114_id, }; module_i2c_driver(mms114_driver); /* Module information */ MODULE_AUTHOR("Joonyoung Shim <[email protected]>"); MODULE_DESCRIPTION("MELFAS mms114 Touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/mms114.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for MStar msg2638 touchscreens * * Copyright (c) 2021 Vincent Knecht <[email protected]> * * Checksum and IRQ handler based on mstar_drv_common.c and * mstar_drv_mutual_fw_control.c * Copyright (c) 2006-2012 MStar Semiconductor, Inc. * * Driver structure based on zinitix.c by Michael Srba <[email protected]> */ #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/kernel.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/property.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #define MODE_DATA_RAW 0x5A #define MSG2138_MAX_FINGERS 2 #define MSG2638_MAX_FINGERS 5 #define MAX_BUTTONS 4 #define CHIP_ON_DELAY_MS 15 #define FIRMWARE_ON_DELAY_MS 50 #define RESET_DELAY_MIN_US 10000 #define RESET_DELAY_MAX_US 11000 struct msg_chip_data { irq_handler_t irq_handler; unsigned int max_fingers; }; struct msg2138_packet { u8 xy_hi; /* higher bits of x and y coordinates */ u8 x_low; u8 y_low; }; struct msg2138_touch_event { u8 magic; struct msg2138_packet pkt[MSG2138_MAX_FINGERS]; u8 checksum; }; struct msg2638_packet { u8 xy_hi; /* higher bits of x and y coordinates */ u8 x_low; u8 y_low; u8 pressure; }; struct msg2638_touch_event { u8 mode; struct msg2638_packet pkt[MSG2638_MAX_FINGERS]; u8 proximity; u8 checksum; }; struct msg2638_ts_data { struct i2c_client *client; struct input_dev *input_dev; struct touchscreen_properties prop; struct regulator_bulk_data supplies[2]; struct gpio_desc *reset_gpiod; int max_fingers; u32 keycodes[MAX_BUTTONS]; int num_keycodes; }; static u8 msg2638_checksum(u8 *data, u32 length) { s32 sum = 0; u32 i; for (i = 0; i < length; i++) sum += data[i]; return (u8)((-sum) & 0xFF); } static void msg2138_report_keys(struct msg2638_ts_data *msg2638, u8 keys) { int i; /* keys can be 0x00 or 0xff when all keys have been released */ if (keys == 0xff) keys = 0; for (i = 0; i < msg2638->num_keycodes; ++i) input_report_key(msg2638->input_dev, msg2638->keycodes[i], keys & BIT(i)); } static irqreturn_t msg2138_ts_irq_handler(int irq, void *msg2638_handler) { struct msg2638_ts_data *msg2638 = msg2638_handler; struct i2c_client *client = msg2638->client; struct input_dev *input = msg2638->input_dev; struct msg2138_touch_event touch_event; u32 len = sizeof(touch_event); struct i2c_msg msg[] = { { .addr = client->addr, .flags = I2C_M_RD, .len = sizeof(touch_event), .buf = (u8 *)&touch_event, }, }; struct msg2138_packet *p0, *p1; u16 x, y, delta_x, delta_y; int ret; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { dev_err(&client->dev, "Failed I2C transfer in irq handler: %d\n", ret < 0 ? ret : -EIO); goto out; } if (msg2638_checksum((u8 *)&touch_event, len - 1) != touch_event.checksum) { dev_err(&client->dev, "Failed checksum!\n"); goto out; } p0 = &touch_event.pkt[0]; p1 = &touch_event.pkt[1]; /* Ignore non-pressed finger data, but check for key code */ if (p0->xy_hi == 0xFF && p0->x_low == 0xFF && p0->y_low == 0xFF) { if (p1->xy_hi == 0xFF && p1->y_low == 0xFF) msg2138_report_keys(msg2638, p1->x_low); goto report; } x = ((p0->xy_hi & 0xF0) << 4) | p0->x_low; y = ((p0->xy_hi & 0x0F) << 8) | p0->y_low; input_mt_slot(input, 0); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); touchscreen_report_pos(input, &msg2638->prop, x, y, true); /* Ignore non-pressed finger data */ if (p1->xy_hi == 0xFF && p1->x_low == 0xFF && p1->y_low == 0xFF) goto report; /* Second finger is reported as a delta position */ delta_x = ((p1->xy_hi & 0xF0) << 4) | p1->x_low; delta_y = ((p1->xy_hi & 0x0F) << 8) | p1->y_low; /* Ignore second finger if both deltas equal 0 */ if (delta_x == 0 && delta_y == 0) goto report; x += delta_x; y += delta_y; input_mt_slot(input, 1); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); touchscreen_report_pos(input, &msg2638->prop, x, y, true); report: input_mt_sync_frame(msg2638->input_dev); input_sync(msg2638->input_dev); out: return IRQ_HANDLED; } static irqreturn_t msg2638_ts_irq_handler(int irq, void *msg2638_handler) { struct msg2638_ts_data *msg2638 = msg2638_handler; struct i2c_client *client = msg2638->client; struct input_dev *input = msg2638->input_dev; struct msg2638_touch_event touch_event; u32 len = sizeof(touch_event); struct i2c_msg msg[] = { { .addr = client->addr, .flags = I2C_M_RD, .len = sizeof(touch_event), .buf = (u8 *)&touch_event, }, }; struct msg2638_packet *p; u16 x, y; int ret; int i; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { dev_err(&client->dev, "Failed I2C transfer in irq handler: %d\n", ret < 0 ? ret : -EIO); goto out; } if (touch_event.mode != MODE_DATA_RAW) goto out; if (msg2638_checksum((u8 *)&touch_event, len - 1) != touch_event.checksum) { dev_err(&client->dev, "Failed checksum!\n"); goto out; } for (i = 0; i < msg2638->max_fingers; i++) { p = &touch_event.pkt[i]; /* Ignore non-pressed finger data */ if (p->xy_hi == 0xFF && p->x_low == 0xFF && p->y_low == 0xFF) continue; x = (((p->xy_hi & 0xF0) << 4) | p->x_low); y = (((p->xy_hi & 0x0F) << 8) | p->y_low); input_mt_slot(input, i); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); touchscreen_report_pos(input, &msg2638->prop, x, y, true); } input_mt_sync_frame(msg2638->input_dev); input_sync(msg2638->input_dev); out: return IRQ_HANDLED; } static void msg2638_reset(struct msg2638_ts_data *msg2638) { gpiod_set_value_cansleep(msg2638->reset_gpiod, 1); usleep_range(RESET_DELAY_MIN_US, RESET_DELAY_MAX_US); gpiod_set_value_cansleep(msg2638->reset_gpiod, 0); msleep(FIRMWARE_ON_DELAY_MS); } static int msg2638_start(struct msg2638_ts_data *msg2638) { int error; error = regulator_bulk_enable(ARRAY_SIZE(msg2638->supplies), msg2638->supplies); if (error) { dev_err(&msg2638->client->dev, "Failed to enable regulators: %d\n", error); return error; } msleep(CHIP_ON_DELAY_MS); msg2638_reset(msg2638); enable_irq(msg2638->client->irq); return 0; } static int msg2638_stop(struct msg2638_ts_data *msg2638) { int error; disable_irq(msg2638->client->irq); error = regulator_bulk_disable(ARRAY_SIZE(msg2638->supplies), msg2638->supplies); if (error) { dev_err(&msg2638->client->dev, "Failed to disable regulators: %d\n", error); return error; } return 0; } static int msg2638_input_open(struct input_dev *dev) { struct msg2638_ts_data *msg2638 = input_get_drvdata(dev); return msg2638_start(msg2638); } static void msg2638_input_close(struct input_dev *dev) { struct msg2638_ts_data *msg2638 = input_get_drvdata(dev); msg2638_stop(msg2638); } static int msg2638_init_input_dev(struct msg2638_ts_data *msg2638) { struct device *dev = &msg2638->client->dev; struct input_dev *input_dev; int error; int i; input_dev = devm_input_allocate_device(dev); if (!input_dev) { dev_err(dev, "Failed to allocate input device.\n"); return -ENOMEM; } input_set_drvdata(input_dev, msg2638); msg2638->input_dev = input_dev; input_dev->name = "MStar TouchScreen"; input_dev->phys = "input/ts"; input_dev->id.bustype = BUS_I2C; input_dev->open = msg2638_input_open; input_dev->close = msg2638_input_close; if (msg2638->num_keycodes) { input_dev->keycode = msg2638->keycodes; input_dev->keycodemax = msg2638->num_keycodes; input_dev->keycodesize = sizeof(msg2638->keycodes[0]); for (i = 0; i < msg2638->num_keycodes; i++) input_set_capability(input_dev, EV_KEY, msg2638->keycodes[i]); } input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input_dev, EV_ABS, ABS_MT_POSITION_Y); touchscreen_parse_properties(input_dev, true, &msg2638->prop); if (!msg2638->prop.max_x || !msg2638->prop.max_y) { dev_err(dev, "touchscreen-size-x and/or touchscreen-size-y not set in properties\n"); return -EINVAL; } error = input_mt_init_slots(input_dev, msg2638->max_fingers, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) { dev_err(dev, "Failed to initialize MT slots: %d\n", error); return error; } error = input_register_device(input_dev); if (error) { dev_err(dev, "Failed to register input device: %d\n", error); return error; } return 0; } static int msg2638_ts_probe(struct i2c_client *client) { const struct msg_chip_data *chip_data; struct device *dev = &client->dev; struct msg2638_ts_data *msg2638; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(dev, "Failed to assert adapter's support for plain I2C.\n"); return -ENXIO; } msg2638 = devm_kzalloc(dev, sizeof(*msg2638), GFP_KERNEL); if (!msg2638) return -ENOMEM; msg2638->client = client; i2c_set_clientdata(client, msg2638); chip_data = device_get_match_data(&client->dev); if (!chip_data || !chip_data->max_fingers) { dev_err(dev, "Invalid or missing chip data\n"); return -EINVAL; } msg2638->max_fingers = chip_data->max_fingers; msg2638->supplies[0].supply = "vdd"; msg2638->supplies[1].supply = "vddio"; error = devm_regulator_bulk_get(dev, ARRAY_SIZE(msg2638->supplies), msg2638->supplies); if (error) { dev_err(dev, "Failed to get regulators: %d\n", error); return error; } msg2638->reset_gpiod = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(msg2638->reset_gpiod)) { error = PTR_ERR(msg2638->reset_gpiod); dev_err(dev, "Failed to request reset GPIO: %d\n", error); return error; } msg2638->num_keycodes = device_property_count_u32(dev, "linux,keycodes"); if (msg2638->num_keycodes == -EINVAL) { msg2638->num_keycodes = 0; } else if (msg2638->num_keycodes < 0) { dev_err(dev, "Unable to parse linux,keycodes property: %d\n", msg2638->num_keycodes); return msg2638->num_keycodes; } else if (msg2638->num_keycodes > ARRAY_SIZE(msg2638->keycodes)) { dev_warn(dev, "Found %d linux,keycodes but max is %zd, ignoring the rest\n", msg2638->num_keycodes, ARRAY_SIZE(msg2638->keycodes)); msg2638->num_keycodes = ARRAY_SIZE(msg2638->keycodes); } if (msg2638->num_keycodes > 0) { error = device_property_read_u32_array(dev, "linux,keycodes", msg2638->keycodes, msg2638->num_keycodes); if (error) { dev_err(dev, "Unable to read linux,keycodes values: %d\n", error); return error; } } error = devm_request_threaded_irq(dev, client->irq, NULL, chip_data->irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, client->name, msg2638); if (error) { dev_err(dev, "Failed to request IRQ: %d\n", error); return error; } error = msg2638_init_input_dev(msg2638); if (error) { dev_err(dev, "Failed to initialize input device: %d\n", error); return error; } return 0; } static int msg2638_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct msg2638_ts_data *msg2638 = i2c_get_clientdata(client); mutex_lock(&msg2638->input_dev->mutex); if (input_device_enabled(msg2638->input_dev)) msg2638_stop(msg2638); mutex_unlock(&msg2638->input_dev->mutex); return 0; } static int msg2638_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct msg2638_ts_data *msg2638 = i2c_get_clientdata(client); int ret = 0; mutex_lock(&msg2638->input_dev->mutex); if (input_device_enabled(msg2638->input_dev)) ret = msg2638_start(msg2638); mutex_unlock(&msg2638->input_dev->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(msg2638_pm_ops, msg2638_suspend, msg2638_resume); static const struct msg_chip_data msg2138_data = { .irq_handler = msg2138_ts_irq_handler, .max_fingers = MSG2138_MAX_FINGERS, }; static const struct msg_chip_data msg2638_data = { .irq_handler = msg2638_ts_irq_handler, .max_fingers = MSG2638_MAX_FINGERS, }; static const struct of_device_id msg2638_of_match[] = { { .compatible = "mstar,msg2138", .data = &msg2138_data }, { .compatible = "mstar,msg2638", .data = &msg2638_data }, { } }; MODULE_DEVICE_TABLE(of, msg2638_of_match); static struct i2c_driver msg2638_ts_driver = { .probe = msg2638_ts_probe, .driver = { .name = "MStar-TS", .pm = pm_sleep_ptr(&msg2638_pm_ops), .of_match_table = msg2638_of_match, }, }; module_i2c_driver(msg2638_ts_driver); MODULE_AUTHOR("Vincent Knecht <[email protected]>"); MODULE_DESCRIPTION("MStar MSG2638 touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/msg2638.c
// SPDX-License-Identifier: GPL-2.0 /* * ST1232 Touchscreen Controller Driver * * Copyright (C) 2010 Renesas Solutions Corp. * Tony SIM <[email protected]> * * Using code from: * - android.git.kernel.org: projects/kernel/common.git: synaptics_i2c_rmi.c * Copyright (C) 2007 Google, Inc. */ #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/pm_qos.h> #include <linux/slab.h> #include <linux/types.h> #define ST1232_TS_NAME "st1232-ts" #define ST1633_TS_NAME "st1633-ts" #define REG_STATUS 0x01 /* Device Status | Error Code */ #define STATUS_NORMAL 0x00 #define STATUS_INIT 0x01 #define STATUS_ERROR 0x02 #define STATUS_AUTO_TUNING 0x03 #define STATUS_IDLE 0x04 #define STATUS_POWER_DOWN 0x05 #define ERROR_NONE 0x00 #define ERROR_INVALID_ADDRESS 0x10 #define ERROR_INVALID_VALUE 0x20 #define ERROR_INVALID_PLATFORM 0x30 #define REG_XY_RESOLUTION 0x04 #define REG_XY_COORDINATES 0x12 #define ST_TS_MAX_FINGERS 10 struct st_chip_info { bool have_z; u16 max_area; u16 max_fingers; }; struct st1232_ts_data { struct i2c_client *client; struct input_dev *input_dev; struct touchscreen_properties prop; struct dev_pm_qos_request low_latency_req; struct gpio_desc *reset_gpio; const struct st_chip_info *chip_info; int read_buf_len; u8 *read_buf; }; static int st1232_ts_read_data(struct st1232_ts_data *ts, u8 reg, unsigned int n) { struct i2c_client *client = ts->client; struct i2c_msg msg[] = { { .addr = client->addr, .len = sizeof(reg), .buf = &reg, }, { .addr = client->addr, .flags = I2C_M_RD | I2C_M_DMA_SAFE, .len = n, .buf = ts->read_buf, } }; int ret; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) return ret < 0 ? ret : -EIO; return 0; } static int st1232_ts_wait_ready(struct st1232_ts_data *ts) { unsigned int retries; int error; for (retries = 100; retries; retries--) { error = st1232_ts_read_data(ts, REG_STATUS, 1); if (!error) { switch (ts->read_buf[0]) { case STATUS_NORMAL | ERROR_NONE: case STATUS_IDLE | ERROR_NONE: return 0; } } usleep_range(1000, 2000); } return -ENXIO; } static int st1232_ts_read_resolution(struct st1232_ts_data *ts, u16 *max_x, u16 *max_y) { u8 *buf; int error; /* select resolution register */ error = st1232_ts_read_data(ts, REG_XY_RESOLUTION, 3); if (error) return error; buf = ts->read_buf; *max_x = (((buf[0] & 0x0070) << 4) | buf[1]) - 1; *max_y = (((buf[0] & 0x0007) << 8) | buf[2]) - 1; return 0; } static int st1232_ts_parse_and_report(struct st1232_ts_data *ts) { struct input_dev *input = ts->input_dev; struct input_mt_pos pos[ST_TS_MAX_FINGERS]; u8 z[ST_TS_MAX_FINGERS]; int slots[ST_TS_MAX_FINGERS]; int n_contacts = 0; int i; for (i = 0; i < ts->chip_info->max_fingers; i++) { u8 *buf = &ts->read_buf[i * 4]; if (buf[0] & BIT(7)) { unsigned int x = ((buf[0] & 0x70) << 4) | buf[1]; unsigned int y = ((buf[0] & 0x07) << 8) | buf[2]; touchscreen_set_mt_pos(&pos[n_contacts], &ts->prop, x, y); /* st1232 includes a z-axis / touch strength */ if (ts->chip_info->have_z) z[n_contacts] = ts->read_buf[i + 6]; n_contacts++; } } input_mt_assign_slots(input, slots, pos, n_contacts, 0); for (i = 0; i < n_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, pos[i].x); input_report_abs(input, ABS_MT_POSITION_Y, pos[i].y); if (ts->chip_info->have_z) input_report_abs(input, ABS_MT_TOUCH_MAJOR, z[i]); } input_mt_sync_frame(input); input_sync(input); return n_contacts; } static irqreturn_t st1232_ts_irq_handler(int irq, void *dev_id) { struct st1232_ts_data *ts = dev_id; int count; int error; error = st1232_ts_read_data(ts, REG_XY_COORDINATES, ts->read_buf_len); if (error) goto out; count = st1232_ts_parse_and_report(ts); if (!count) { if (ts->low_latency_req.dev) { dev_pm_qos_remove_request(&ts->low_latency_req); ts->low_latency_req.dev = NULL; } } else if (!ts->low_latency_req.dev) { /* First contact, request 100 us latency. */ dev_pm_qos_add_ancestor_request(&ts->client->dev, &ts->low_latency_req, DEV_PM_QOS_RESUME_LATENCY, 100); } out: return IRQ_HANDLED; } static void st1232_ts_power(struct st1232_ts_data *ts, bool poweron) { if (ts->reset_gpio) gpiod_set_value_cansleep(ts->reset_gpio, !poweron); } static void st1232_ts_power_off(void *data) { st1232_ts_power(data, false); } static const struct st_chip_info st1232_chip_info = { .have_z = true, .max_area = 0xff, .max_fingers = 2, }; static const struct st_chip_info st1633_chip_info = { .have_z = false, .max_area = 0x00, .max_fingers = 5, }; static int st1232_ts_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); const struct st_chip_info *match; struct st1232_ts_data *ts; struct input_dev *input_dev; u16 max_x, max_y; int error; match = device_get_match_data(&client->dev); if (!match && id) match = (const void *)id->driver_data; if (!match) { dev_err(&client->dev, "unknown device model\n"); return -ENODEV; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "need I2C_FUNC_I2C\n"); return -EIO; } if (!client->irq) { dev_err(&client->dev, "no IRQ?\n"); return -EINVAL; } ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->chip_info = match; /* allocate a buffer according to the number of registers to read */ ts->read_buf_len = ts->chip_info->max_fingers * 4; ts->read_buf = devm_kzalloc(&client->dev, ts->read_buf_len, GFP_KERNEL); if (!ts->read_buf) return -ENOMEM; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) return -ENOMEM; ts->client = client; ts->input_dev = input_dev; ts->reset_gpio = devm_gpiod_get_optional(&client->dev, NULL, GPIOD_OUT_HIGH); if (IS_ERR(ts->reset_gpio)) { error = PTR_ERR(ts->reset_gpio); dev_err(&client->dev, "Unable to request GPIO pin: %d.\n", error); return error; } st1232_ts_power(ts, true); error = devm_add_action_or_reset(&client->dev, st1232_ts_power_off, ts); if (error) { dev_err(&client->dev, "Failed to install power off action: %d\n", error); return error; } input_dev->name = "st1232-touchscreen"; input_dev->id.bustype = BUS_I2C; /* Wait until device is ready */ error = st1232_ts_wait_ready(ts); if (error) return error; /* Read resolution from the chip */ error = st1232_ts_read_resolution(ts, &max_x, &max_y); if (error) { dev_err(&client->dev, "Failed to read resolution: %d\n", error); return error; } if (ts->chip_info->have_z) input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, ts->chip_info->max_area, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, max_y, 0, 0); touchscreen_parse_properties(input_dev, true, &ts->prop); error = input_mt_init_slots(input_dev, ts->chip_info->max_fingers, INPUT_MT_DIRECT | INPUT_MT_TRACK | INPUT_MT_DROP_UNUSED); if (error) { dev_err(&client->dev, "failed to initialize MT slots\n"); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, st1232_ts_irq_handler, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = input_register_device(ts->input_dev); if (error) { dev_err(&client->dev, "Unable to register %s input device\n", input_dev->name); return error; } i2c_set_clientdata(client, ts); return 0; } static int st1232_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct st1232_ts_data *ts = i2c_get_clientdata(client); disable_irq(client->irq); if (!device_may_wakeup(&client->dev)) st1232_ts_power(ts, false); return 0; } static int st1232_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct st1232_ts_data *ts = i2c_get_clientdata(client); if (!device_may_wakeup(&client->dev)) st1232_ts_power(ts, true); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(st1232_ts_pm_ops, st1232_ts_suspend, st1232_ts_resume); static const struct i2c_device_id st1232_ts_id[] = { { ST1232_TS_NAME, (unsigned long)&st1232_chip_info }, { ST1633_TS_NAME, (unsigned long)&st1633_chip_info }, { } }; MODULE_DEVICE_TABLE(i2c, st1232_ts_id); static const struct of_device_id st1232_ts_dt_ids[] = { { .compatible = "sitronix,st1232", .data = &st1232_chip_info }, { .compatible = "sitronix,st1633", .data = &st1633_chip_info }, { } }; MODULE_DEVICE_TABLE(of, st1232_ts_dt_ids); static struct i2c_driver st1232_ts_driver = { .probe = st1232_ts_probe, .id_table = st1232_ts_id, .driver = { .name = ST1232_TS_NAME, .of_match_table = st1232_ts_dt_ids, .probe_type = PROBE_PREFER_ASYNCHRONOUS, .pm = pm_sleep_ptr(&st1232_ts_pm_ops), }, }; module_i2c_driver(st1232_ts_driver); MODULE_AUTHOR("Tony SIM <[email protected]>"); MODULE_AUTHOR("Martin Kepplinger <[email protected]>"); MODULE_DESCRIPTION("SITRONIX ST1232 Touchscreen Controller Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/st1232.c
// SPDX-License-Identifier: GPL-2.0 // // Freescale i.MX6UL touchscreen controller driver // // Copyright (C) 2015 Freescale Semiconductor, Inc. #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/gpio/consumer.h> #include <linux/input.h> #include <linux/slab.h> #include <linux/completion.h> #include <linux/delay.h> #include <linux/of.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/log2.h> /* ADC configuration registers field define */ #define ADC_AIEN (0x1 << 7) #define ADC_CONV_DISABLE 0x1F #define ADC_AVGE (0x1 << 5) #define ADC_CAL (0x1 << 7) #define ADC_CALF 0x2 #define ADC_12BIT_MODE (0x2 << 2) #define ADC_CONV_MODE_MASK (0x3 << 2) #define ADC_IPG_CLK 0x00 #define ADC_INPUT_CLK_MASK 0x3 #define ADC_CLK_DIV_8 (0x03 << 5) #define ADC_CLK_DIV_MASK (0x3 << 5) #define ADC_SHORT_SAMPLE_MODE (0x0 << 4) #define ADC_SAMPLE_MODE_MASK (0x1 << 4) #define ADC_HARDWARE_TRIGGER (0x1 << 13) #define ADC_AVGS_SHIFT 14 #define ADC_AVGS_MASK (0x3 << 14) #define SELECT_CHANNEL_4 0x04 #define SELECT_CHANNEL_1 0x01 #define DISABLE_CONVERSION_INT (0x0 << 7) /* ADC registers */ #define REG_ADC_HC0 0x00 #define REG_ADC_HC1 0x04 #define REG_ADC_HC2 0x08 #define REG_ADC_HC3 0x0C #define REG_ADC_HC4 0x10 #define REG_ADC_HS 0x14 #define REG_ADC_R0 0x18 #define REG_ADC_CFG 0x2C #define REG_ADC_GC 0x30 #define REG_ADC_GS 0x34 #define ADC_TIMEOUT msecs_to_jiffies(100) /* TSC registers */ #define REG_TSC_BASIC_SETING 0x00 #define REG_TSC_PRE_CHARGE_TIME 0x10 #define REG_TSC_FLOW_CONTROL 0x20 #define REG_TSC_MEASURE_VALUE 0x30 #define REG_TSC_INT_EN 0x40 #define REG_TSC_INT_SIG_EN 0x50 #define REG_TSC_INT_STATUS 0x60 #define REG_TSC_DEBUG_MODE 0x70 #define REG_TSC_DEBUG_MODE2 0x80 /* TSC configuration registers field define */ #define DETECT_4_WIRE_MODE (0x0 << 4) #define AUTO_MEASURE 0x1 #define MEASURE_SIGNAL 0x1 #define DETECT_SIGNAL (0x1 << 4) #define VALID_SIGNAL (0x1 << 8) #define MEASURE_INT_EN 0x1 #define MEASURE_SIG_EN 0x1 #define VALID_SIG_EN (0x1 << 8) #define DE_GLITCH_2 (0x2 << 29) #define START_SENSE (0x1 << 12) #define TSC_DISABLE (0x1 << 16) #define DETECT_MODE 0x2 struct imx6ul_tsc { struct device *dev; struct input_dev *input; void __iomem *tsc_regs; void __iomem *adc_regs; struct clk *tsc_clk; struct clk *adc_clk; struct gpio_desc *xnur_gpio; u32 measure_delay_time; u32 pre_charge_time; bool average_enable; u32 average_select; struct completion completion; }; /* * TSC module need ADC to get the measure value. So * before config TSC, we should initialize ADC module. */ static int imx6ul_adc_init(struct imx6ul_tsc *tsc) { u32 adc_hc = 0; u32 adc_gc; u32 adc_gs; u32 adc_cfg; unsigned long timeout; reinit_completion(&tsc->completion); adc_cfg = readl(tsc->adc_regs + REG_ADC_CFG); adc_cfg &= ~(ADC_CONV_MODE_MASK | ADC_INPUT_CLK_MASK); adc_cfg |= ADC_12BIT_MODE | ADC_IPG_CLK; adc_cfg &= ~(ADC_CLK_DIV_MASK | ADC_SAMPLE_MODE_MASK); adc_cfg |= ADC_CLK_DIV_8 | ADC_SHORT_SAMPLE_MODE; if (tsc->average_enable) { adc_cfg &= ~ADC_AVGS_MASK; adc_cfg |= (tsc->average_select) << ADC_AVGS_SHIFT; } adc_cfg &= ~ADC_HARDWARE_TRIGGER; writel(adc_cfg, tsc->adc_regs + REG_ADC_CFG); /* enable calibration interrupt */ adc_hc |= ADC_AIEN; adc_hc |= ADC_CONV_DISABLE; writel(adc_hc, tsc->adc_regs + REG_ADC_HC0); /* start ADC calibration */ adc_gc = readl(tsc->adc_regs + REG_ADC_GC); adc_gc |= ADC_CAL; if (tsc->average_enable) adc_gc |= ADC_AVGE; writel(adc_gc, tsc->adc_regs + REG_ADC_GC); timeout = wait_for_completion_timeout (&tsc->completion, ADC_TIMEOUT); if (timeout == 0) { dev_err(tsc->dev, "Timeout for adc calibration\n"); return -ETIMEDOUT; } adc_gs = readl(tsc->adc_regs + REG_ADC_GS); if (adc_gs & ADC_CALF) { dev_err(tsc->dev, "ADC calibration failed\n"); return -EINVAL; } /* TSC need the ADC work in hardware trigger */ adc_cfg = readl(tsc->adc_regs + REG_ADC_CFG); adc_cfg |= ADC_HARDWARE_TRIGGER; writel(adc_cfg, tsc->adc_regs + REG_ADC_CFG); return 0; } /* * This is a TSC workaround. Currently TSC misconnect two * ADC channels, this function remap channel configure for * hardware trigger. */ static void imx6ul_tsc_channel_config(struct imx6ul_tsc *tsc) { u32 adc_hc0, adc_hc1, adc_hc2, adc_hc3, adc_hc4; adc_hc0 = DISABLE_CONVERSION_INT; writel(adc_hc0, tsc->adc_regs + REG_ADC_HC0); adc_hc1 = DISABLE_CONVERSION_INT | SELECT_CHANNEL_4; writel(adc_hc1, tsc->adc_regs + REG_ADC_HC1); adc_hc2 = DISABLE_CONVERSION_INT; writel(adc_hc2, tsc->adc_regs + REG_ADC_HC2); adc_hc3 = DISABLE_CONVERSION_INT | SELECT_CHANNEL_1; writel(adc_hc3, tsc->adc_regs + REG_ADC_HC3); adc_hc4 = DISABLE_CONVERSION_INT; writel(adc_hc4, tsc->adc_regs + REG_ADC_HC4); } /* * TSC setting, confige the pre-charge time and measure delay time. * different touch screen may need different pre-charge time and * measure delay time. */ static void imx6ul_tsc_set(struct imx6ul_tsc *tsc) { u32 basic_setting = 0; u32 start; basic_setting |= tsc->measure_delay_time << 8; basic_setting |= DETECT_4_WIRE_MODE | AUTO_MEASURE; writel(basic_setting, tsc->tsc_regs + REG_TSC_BASIC_SETING); writel(DE_GLITCH_2, tsc->tsc_regs + REG_TSC_DEBUG_MODE2); writel(tsc->pre_charge_time, tsc->tsc_regs + REG_TSC_PRE_CHARGE_TIME); writel(MEASURE_INT_EN, tsc->tsc_regs + REG_TSC_INT_EN); writel(MEASURE_SIG_EN | VALID_SIG_EN, tsc->tsc_regs + REG_TSC_INT_SIG_EN); /* start sense detection */ start = readl(tsc->tsc_regs + REG_TSC_FLOW_CONTROL); start |= START_SENSE; start &= ~TSC_DISABLE; writel(start, tsc->tsc_regs + REG_TSC_FLOW_CONTROL); } static int imx6ul_tsc_init(struct imx6ul_tsc *tsc) { int err; err = imx6ul_adc_init(tsc); if (err) return err; imx6ul_tsc_channel_config(tsc); imx6ul_tsc_set(tsc); return 0; } static void imx6ul_tsc_disable(struct imx6ul_tsc *tsc) { u32 tsc_flow; u32 adc_cfg; /* TSC controller enters to idle status */ tsc_flow = readl(tsc->tsc_regs + REG_TSC_FLOW_CONTROL); tsc_flow |= TSC_DISABLE; writel(tsc_flow, tsc->tsc_regs + REG_TSC_FLOW_CONTROL); /* ADC controller enters to stop mode */ adc_cfg = readl(tsc->adc_regs + REG_ADC_HC0); adc_cfg |= ADC_CONV_DISABLE; writel(adc_cfg, tsc->adc_regs + REG_ADC_HC0); } /* Delay some time (max 2ms), wait the pre-charge done. */ static bool tsc_wait_detect_mode(struct imx6ul_tsc *tsc) { unsigned long timeout = jiffies + msecs_to_jiffies(2); u32 state_machine; u32 debug_mode2; do { if (time_after(jiffies, timeout)) return false; usleep_range(200, 400); debug_mode2 = readl(tsc->tsc_regs + REG_TSC_DEBUG_MODE2); state_machine = (debug_mode2 >> 20) & 0x7; } while (state_machine != DETECT_MODE); usleep_range(200, 400); return true; } static irqreturn_t tsc_irq_fn(int irq, void *dev_id) { struct imx6ul_tsc *tsc = dev_id; u32 status; u32 value; u32 x, y; u32 start; status = readl(tsc->tsc_regs + REG_TSC_INT_STATUS); /* write 1 to clear the bit measure-signal */ writel(MEASURE_SIGNAL | DETECT_SIGNAL, tsc->tsc_regs + REG_TSC_INT_STATUS); /* It's a HW self-clean bit. Set this bit and start sense detection */ start = readl(tsc->tsc_regs + REG_TSC_FLOW_CONTROL); start |= START_SENSE; writel(start, tsc->tsc_regs + REG_TSC_FLOW_CONTROL); if (status & MEASURE_SIGNAL) { value = readl(tsc->tsc_regs + REG_TSC_MEASURE_VALUE); x = (value >> 16) & 0x0fff; y = value & 0x0fff; /* * In detect mode, we can get the xnur gpio value, * otherwise assume contact is stiull active. */ if (!tsc_wait_detect_mode(tsc) || gpiod_get_value_cansleep(tsc->xnur_gpio)) { input_report_key(tsc->input, BTN_TOUCH, 1); input_report_abs(tsc->input, ABS_X, x); input_report_abs(tsc->input, ABS_Y, y); } else { input_report_key(tsc->input, BTN_TOUCH, 0); } input_sync(tsc->input); } return IRQ_HANDLED; } static irqreturn_t adc_irq_fn(int irq, void *dev_id) { struct imx6ul_tsc *tsc = dev_id; u32 coco; coco = readl(tsc->adc_regs + REG_ADC_HS); if (coco & 0x01) { readl(tsc->adc_regs + REG_ADC_R0); complete(&tsc->completion); } return IRQ_HANDLED; } static int imx6ul_tsc_start(struct imx6ul_tsc *tsc) { int err; err = clk_prepare_enable(tsc->adc_clk); if (err) { dev_err(tsc->dev, "Could not prepare or enable the adc clock: %d\n", err); return err; } err = clk_prepare_enable(tsc->tsc_clk); if (err) { dev_err(tsc->dev, "Could not prepare or enable the tsc clock: %d\n", err); goto disable_adc_clk; } err = imx6ul_tsc_init(tsc); if (err) goto disable_tsc_clk; return 0; disable_tsc_clk: clk_disable_unprepare(tsc->tsc_clk); disable_adc_clk: clk_disable_unprepare(tsc->adc_clk); return err; } static void imx6ul_tsc_stop(struct imx6ul_tsc *tsc) { imx6ul_tsc_disable(tsc); clk_disable_unprepare(tsc->tsc_clk); clk_disable_unprepare(tsc->adc_clk); } static int imx6ul_tsc_open(struct input_dev *input_dev) { struct imx6ul_tsc *tsc = input_get_drvdata(input_dev); return imx6ul_tsc_start(tsc); } static void imx6ul_tsc_close(struct input_dev *input_dev) { struct imx6ul_tsc *tsc = input_get_drvdata(input_dev); imx6ul_tsc_stop(tsc); } static int imx6ul_tsc_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct imx6ul_tsc *tsc; struct input_dev *input_dev; int err; int tsc_irq; int adc_irq; u32 average_samples; tsc = devm_kzalloc(&pdev->dev, sizeof(*tsc), GFP_KERNEL); if (!tsc) return -ENOMEM; input_dev = devm_input_allocate_device(&pdev->dev); if (!input_dev) return -ENOMEM; input_dev->name = "iMX6UL Touchscreen Controller"; input_dev->id.bustype = BUS_HOST; input_dev->open = imx6ul_tsc_open; input_dev->close = imx6ul_tsc_close; input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, 0xFFF, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, 0xFFF, 0, 0); input_set_drvdata(input_dev, tsc); tsc->dev = &pdev->dev; tsc->input = input_dev; init_completion(&tsc->completion); tsc->xnur_gpio = devm_gpiod_get(&pdev->dev, "xnur", GPIOD_IN); if (IS_ERR(tsc->xnur_gpio)) { err = PTR_ERR(tsc->xnur_gpio); dev_err(&pdev->dev, "failed to request GPIO tsc_X- (xnur): %d\n", err); return err; } tsc->tsc_regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(tsc->tsc_regs)) { err = PTR_ERR(tsc->tsc_regs); dev_err(&pdev->dev, "failed to remap tsc memory: %d\n", err); return err; } tsc->adc_regs = devm_platform_ioremap_resource(pdev, 1); if (IS_ERR(tsc->adc_regs)) { err = PTR_ERR(tsc->adc_regs); dev_err(&pdev->dev, "failed to remap adc memory: %d\n", err); return err; } tsc->tsc_clk = devm_clk_get(&pdev->dev, "tsc"); if (IS_ERR(tsc->tsc_clk)) { err = PTR_ERR(tsc->tsc_clk); dev_err(&pdev->dev, "failed getting tsc clock: %d\n", err); return err; } tsc->adc_clk = devm_clk_get(&pdev->dev, "adc"); if (IS_ERR(tsc->adc_clk)) { err = PTR_ERR(tsc->adc_clk); dev_err(&pdev->dev, "failed getting adc clock: %d\n", err); return err; } tsc_irq = platform_get_irq(pdev, 0); if (tsc_irq < 0) return tsc_irq; adc_irq = platform_get_irq(pdev, 1); if (adc_irq < 0) return adc_irq; err = devm_request_threaded_irq(tsc->dev, tsc_irq, NULL, tsc_irq_fn, IRQF_ONESHOT, dev_name(&pdev->dev), tsc); if (err) { dev_err(&pdev->dev, "failed requesting tsc irq %d: %d\n", tsc_irq, err); return err; } err = devm_request_irq(tsc->dev, adc_irq, adc_irq_fn, 0, dev_name(&pdev->dev), tsc); if (err) { dev_err(&pdev->dev, "failed requesting adc irq %d: %d\n", adc_irq, err); return err; } err = of_property_read_u32(np, "measure-delay-time", &tsc->measure_delay_time); if (err) tsc->measure_delay_time = 0xffff; err = of_property_read_u32(np, "pre-charge-time", &tsc->pre_charge_time); if (err) tsc->pre_charge_time = 0xfff; err = of_property_read_u32(np, "touchscreen-average-samples", &average_samples); if (err) average_samples = 1; switch (average_samples) { case 1: tsc->average_enable = false; tsc->average_select = 0; /* value unused; initialize anyway */ break; case 4: case 8: case 16: case 32: tsc->average_enable = true; tsc->average_select = ilog2(average_samples) - 2; break; default: dev_err(&pdev->dev, "touchscreen-average-samples (%u) must be 1, 4, 8, 16 or 32\n", average_samples); return -EINVAL; } err = input_register_device(tsc->input); if (err) { dev_err(&pdev->dev, "failed to register input device: %d\n", err); return err; } platform_set_drvdata(pdev, tsc); return 0; } static int imx6ul_tsc_suspend(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct imx6ul_tsc *tsc = platform_get_drvdata(pdev); struct input_dev *input_dev = tsc->input; mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) imx6ul_tsc_stop(tsc); mutex_unlock(&input_dev->mutex); return 0; } static int imx6ul_tsc_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct imx6ul_tsc *tsc = platform_get_drvdata(pdev); struct input_dev *input_dev = tsc->input; int retval = 0; mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) retval = imx6ul_tsc_start(tsc); mutex_unlock(&input_dev->mutex); return retval; } static DEFINE_SIMPLE_DEV_PM_OPS(imx6ul_tsc_pm_ops, imx6ul_tsc_suspend, imx6ul_tsc_resume); static const struct of_device_id imx6ul_tsc_match[] = { { .compatible = "fsl,imx6ul-tsc", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, imx6ul_tsc_match); static struct platform_driver imx6ul_tsc_driver = { .driver = { .name = "imx6ul-tsc", .of_match_table = imx6ul_tsc_match, .pm = pm_sleep_ptr(&imx6ul_tsc_pm_ops), }, .probe = imx6ul_tsc_probe, }; module_platform_driver(imx6ul_tsc_driver); MODULE_AUTHOR("Haibo Chen <[email protected]>"); MODULE_DESCRIPTION("Freescale i.MX6UL Touchscreen controller driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/imx6ul_tsc.c
// SPDX-License-Identifier: GPL-2.0 /* * ADC generic resistive touchscreen (GRTS) * This is a generic input driver that connects to an ADC * given the channels in device tree, and reports events to the input * subsystem. * * Copyright (C) 2017,2018 Microchip Technology, * Author: Eugen Hristev <[email protected]> * */ #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/iio/consumer.h> #include <linux/iio/iio.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/property.h> #define DRIVER_NAME "resistive-adc-touch" #define GRTS_DEFAULT_PRESSURE_MIN 50000 #define GRTS_DEFAULT_PRESSURE_MAX 65535 #define GRTS_MAX_POS_MASK GENMASK(11, 0) #define GRTS_MAX_CHANNELS 4 enum grts_ch_type { GRTS_CH_X, GRTS_CH_Y, GRTS_CH_PRESSURE, GRTS_CH_Z1, GRTS_CH_Z2, GRTS_CH_MAX = GRTS_CH_Z2 + 1 }; /** * struct grts_state - generic resistive touch screen information struct * @x_plate_ohms: resistance of the X plate * @pressure_min: number representing the minimum for the pressure * @pressure: are we getting pressure info or not * @iio_chans: list of channels acquired * @iio_cb: iio_callback buffer for the data * @input: the input device structure that we register * @prop: touchscreen properties struct * @ch_map: map of channels that are defined for the touchscreen */ struct grts_state { u32 x_plate_ohms; u32 pressure_min; bool pressure; struct iio_channel *iio_chans; struct iio_cb_buffer *iio_cb; struct input_dev *input; struct touchscreen_properties prop; u8 ch_map[GRTS_CH_MAX]; }; static int grts_cb(const void *data, void *private) { const u16 *touch_info = data; struct grts_state *st = private; unsigned int x, y, press = 0; x = touch_info[st->ch_map[GRTS_CH_X]]; y = touch_info[st->ch_map[GRTS_CH_Y]]; if (st->ch_map[GRTS_CH_PRESSURE] < GRTS_MAX_CHANNELS) { press = touch_info[st->ch_map[GRTS_CH_PRESSURE]]; } else if (st->ch_map[GRTS_CH_Z1] < GRTS_MAX_CHANNELS) { unsigned int z1 = touch_info[st->ch_map[GRTS_CH_Z1]]; unsigned int z2 = touch_info[st->ch_map[GRTS_CH_Z2]]; unsigned int Rt; if (likely(x && z1)) { Rt = z2; Rt -= z1; Rt *= st->x_plate_ohms; Rt = DIV_ROUND_CLOSEST(Rt, 16); Rt *= x; Rt /= z1; Rt = DIV_ROUND_CLOSEST(Rt, 256); /* * On increased pressure the resistance (Rt) is * decreasing so, convert values to make it looks as * real pressure. */ if (Rt < GRTS_DEFAULT_PRESSURE_MAX) press = GRTS_DEFAULT_PRESSURE_MAX - Rt; } } if ((!x && !y) || (st->pressure && (press < st->pressure_min))) { /* report end of touch */ input_report_key(st->input, BTN_TOUCH, 0); input_sync(st->input); return 0; } /* report proper touch to subsystem*/ touchscreen_report_pos(st->input, &st->prop, x, y, false); if (st->pressure) input_report_abs(st->input, ABS_PRESSURE, press); input_report_key(st->input, BTN_TOUCH, 1); input_sync(st->input); return 0; } static int grts_open(struct input_dev *dev) { int error; struct grts_state *st = input_get_drvdata(dev); error = iio_channel_start_all_cb(st->iio_cb); if (error) { dev_err(dev->dev.parent, "failed to start callback buffer.\n"); return error; } return 0; } static void grts_close(struct input_dev *dev) { struct grts_state *st = input_get_drvdata(dev); iio_channel_stop_all_cb(st->iio_cb); } static void grts_disable(void *data) { iio_channel_release_all_cb(data); } static int grts_map_channel(struct grts_state *st, struct device *dev, enum grts_ch_type type, const char *name, bool optional) { int idx; idx = device_property_match_string(dev, "io-channel-names", name); if (idx < 0) { if (!optional) return idx; idx = GRTS_MAX_CHANNELS; } else if (idx >= GRTS_MAX_CHANNELS) { return -EOVERFLOW; } st->ch_map[type] = idx; return 0; } static int grts_get_properties(struct grts_state *st, struct device *dev) { int error; error = grts_map_channel(st, dev, GRTS_CH_X, "x", false); if (error) return error; error = grts_map_channel(st, dev, GRTS_CH_Y, "y", false); if (error) return error; /* pressure is optional */ error = grts_map_channel(st, dev, GRTS_CH_PRESSURE, "pressure", true); if (error) return error; if (st->ch_map[GRTS_CH_PRESSURE] < GRTS_MAX_CHANNELS) { st->pressure = true; return 0; } /* if no pressure is defined, try optional z1 + z2 */ error = grts_map_channel(st, dev, GRTS_CH_Z1, "z1", true); if (error) return error; if (st->ch_map[GRTS_CH_Z1] >= GRTS_MAX_CHANNELS) return 0; /* if z1 is provided z2 is not optional */ error = grts_map_channel(st, dev, GRTS_CH_Z2, "z2", true); if (error) return error; error = device_property_read_u32(dev, "touchscreen-x-plate-ohms", &st->x_plate_ohms); if (error) { dev_err(dev, "can't get touchscreen-x-plate-ohms property\n"); return error; } st->pressure = true; return 0; } static int grts_probe(struct platform_device *pdev) { struct grts_state *st; struct input_dev *input; struct device *dev = &pdev->dev; int error; st = devm_kzalloc(dev, sizeof(struct grts_state), GFP_KERNEL); if (!st) return -ENOMEM; /* get the channels from IIO device */ st->iio_chans = devm_iio_channel_get_all(dev); if (IS_ERR(st->iio_chans)) return dev_err_probe(dev, PTR_ERR(st->iio_chans), "can't get iio channels\n"); if (!device_property_present(dev, "io-channel-names")) return -ENODEV; error = grts_get_properties(st, dev); if (error) { dev_err(dev, "Failed to parse properties\n"); return error; } if (st->pressure) { error = device_property_read_u32(dev, "touchscreen-min-pressure", &st->pressure_min); if (error) { dev_dbg(dev, "can't get touchscreen-min-pressure property.\n"); st->pressure_min = GRTS_DEFAULT_PRESSURE_MIN; } } input = devm_input_allocate_device(dev); if (!input) { dev_err(dev, "failed to allocate input device.\n"); return -ENOMEM; } input->name = DRIVER_NAME; input->id.bustype = BUS_HOST; input->open = grts_open; input->close = grts_close; input_set_abs_params(input, ABS_X, 0, GRTS_MAX_POS_MASK - 1, 0, 0); input_set_abs_params(input, ABS_Y, 0, GRTS_MAX_POS_MASK - 1, 0, 0); if (st->pressure) input_set_abs_params(input, ABS_PRESSURE, st->pressure_min, GRTS_DEFAULT_PRESSURE_MAX, 0, 0); input_set_capability(input, EV_KEY, BTN_TOUCH); /* parse optional device tree properties */ touchscreen_parse_properties(input, false, &st->prop); st->input = input; input_set_drvdata(input, st); error = input_register_device(input); if (error) { dev_err(dev, "failed to register input device."); return error; } st->iio_cb = iio_channel_get_all_cb(dev, grts_cb, st); if (IS_ERR(st->iio_cb)) { dev_err(dev, "failed to allocate callback buffer.\n"); return PTR_ERR(st->iio_cb); } error = devm_add_action_or_reset(dev, grts_disable, st->iio_cb); if (error) { dev_err(dev, "failed to add disable action.\n"); return error; } return 0; } static const struct of_device_id grts_of_match[] = { { .compatible = "resistive-adc-touch", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, grts_of_match); static struct platform_driver grts_driver = { .probe = grts_probe, .driver = { .name = DRIVER_NAME, .of_match_table = grts_of_match, }, }; module_platform_driver(grts_driver); MODULE_AUTHOR("Eugen Hristev <[email protected]>"); MODULE_DESCRIPTION("Generic ADC Resistive Touch Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/resistive-adc-touch.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Ntrig/Microsoft Touchscreens over SPI * * Copyright (c) 2016 Red Hat Inc. */ #include <linux/kernel.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/acpi.h> #include <asm/unaligned.h> #define SURFACE3_PACKET_SIZE 264 #define SURFACE3_REPORT_TOUCH 0xd2 #define SURFACE3_REPORT_PEN 0x16 struct surface3_ts_data { struct spi_device *spi; struct gpio_desc *gpiod_rst[2]; struct input_dev *input_dev; struct input_dev *pen_input_dev; int pen_tool; u8 rd_buf[SURFACE3_PACKET_SIZE] ____cacheline_aligned; }; struct surface3_ts_data_finger { u8 status; __le16 tracking_id; __le16 x; __le16 cx; __le16 y; __le16 cy; __le16 width; __le16 height; u32 padding; } __packed; struct surface3_ts_data_pen { u8 status; __le16 x; __le16 y; __le16 pressure; u8 padding; } __packed; static int surface3_spi_read(struct surface3_ts_data *ts_data) { struct spi_device *spi = ts_data->spi; memset(ts_data->rd_buf, 0, sizeof(ts_data->rd_buf)); return spi_read(spi, ts_data->rd_buf, sizeof(ts_data->rd_buf)); } static void surface3_spi_report_touch(struct surface3_ts_data *ts_data, struct surface3_ts_data_finger *finger) { int st = finger->status & 0x01; int slot; slot = input_mt_get_slot_by_key(ts_data->input_dev, get_unaligned_le16(&finger->tracking_id)); if (slot < 0) return; input_mt_slot(ts_data->input_dev, slot); input_mt_report_slot_state(ts_data->input_dev, MT_TOOL_FINGER, st); if (st) { input_report_abs(ts_data->input_dev, ABS_MT_POSITION_X, get_unaligned_le16(&finger->x)); input_report_abs(ts_data->input_dev, ABS_MT_POSITION_Y, get_unaligned_le16(&finger->y)); input_report_abs(ts_data->input_dev, ABS_MT_WIDTH_MAJOR, get_unaligned_le16(&finger->width)); input_report_abs(ts_data->input_dev, ABS_MT_WIDTH_MINOR, get_unaligned_le16(&finger->height)); } } static void surface3_spi_process_touch(struct surface3_ts_data *ts_data, u8 *data) { unsigned int i; for (i = 0; i < 13; i++) { struct surface3_ts_data_finger *finger; finger = (struct surface3_ts_data_finger *)&data[17 + i * sizeof(struct surface3_ts_data_finger)]; /* * When bit 5 of status is 1, it marks the end of the report: * - touch present: 0xe7 * - touch released: 0xe4 * - nothing valuable: 0xff */ if (finger->status & 0x10) break; surface3_spi_report_touch(ts_data, finger); } input_mt_sync_frame(ts_data->input_dev); input_sync(ts_data->input_dev); } static void surface3_spi_report_pen(struct surface3_ts_data *ts_data, struct surface3_ts_data_pen *pen) { struct input_dev *dev = ts_data->pen_input_dev; int st = pen->status; int prox = st & 0x01; int rubber = st & 0x18; int tool = (prox && rubber) ? BTN_TOOL_RUBBER : BTN_TOOL_PEN; /* fake proximity out to switch tools */ if (ts_data->pen_tool != tool) { input_report_key(dev, ts_data->pen_tool, 0); input_sync(dev); ts_data->pen_tool = tool; } input_report_key(dev, BTN_TOUCH, st & 0x12); input_report_key(dev, ts_data->pen_tool, prox); if (st) { input_report_key(dev, BTN_STYLUS, st & 0x04); input_report_abs(dev, ABS_X, get_unaligned_le16(&pen->x)); input_report_abs(dev, ABS_Y, get_unaligned_le16(&pen->y)); input_report_abs(dev, ABS_PRESSURE, get_unaligned_le16(&pen->pressure)); } } static void surface3_spi_process_pen(struct surface3_ts_data *ts_data, u8 *data) { struct surface3_ts_data_pen *pen; pen = (struct surface3_ts_data_pen *)&data[15]; surface3_spi_report_pen(ts_data, pen); input_sync(ts_data->pen_input_dev); } static void surface3_spi_process(struct surface3_ts_data *ts_data) { static const char header[] = { 0xff, 0xff, 0xff, 0xff, 0xa5, 0x5a, 0xe7, 0x7e, 0x01 }; u8 *data = ts_data->rd_buf; if (memcmp(header, data, sizeof(header))) dev_err(&ts_data->spi->dev, "%s header error: %*ph, ignoring...\n", __func__, (int)sizeof(header), data); switch (data[9]) { case SURFACE3_REPORT_TOUCH: surface3_spi_process_touch(ts_data, data); break; case SURFACE3_REPORT_PEN: surface3_spi_process_pen(ts_data, data); break; default: dev_err(&ts_data->spi->dev, "%s unknown packet type: %x, ignoring...\n", __func__, data[9]); break; } } static irqreturn_t surface3_spi_irq_handler(int irq, void *dev_id) { struct surface3_ts_data *data = dev_id; if (surface3_spi_read(data)) return IRQ_HANDLED; dev_dbg(&data->spi->dev, "%s received -> %*ph\n", __func__, SURFACE3_PACKET_SIZE, data->rd_buf); surface3_spi_process(data); return IRQ_HANDLED; } static void surface3_spi_power(struct surface3_ts_data *data, bool on) { gpiod_set_value(data->gpiod_rst[0], on); gpiod_set_value(data->gpiod_rst[1], on); /* let the device settle a little */ msleep(20); } /** * surface3_spi_get_gpio_config - Get GPIO config from ACPI/DT * * @data: surface3_spi_ts_data pointer */ static int surface3_spi_get_gpio_config(struct surface3_ts_data *data) { struct device *dev; struct gpio_desc *gpiod; int i; dev = &data->spi->dev; /* Get the reset lines GPIO pin number */ for (i = 0; i < 2; i++) { gpiod = devm_gpiod_get_index(dev, NULL, i, GPIOD_OUT_LOW); if (IS_ERR(gpiod)) return dev_err_probe(dev, PTR_ERR(gpiod), "Failed to get power GPIO %d\n", i); data->gpiod_rst[i] = gpiod; } return 0; } static int surface3_spi_create_touch_input(struct surface3_ts_data *data) { struct input_dev *input; int error; input = devm_input_allocate_device(&data->spi->dev); if (!input) return -ENOMEM; data->input_dev = input; input_set_abs_params(input, ABS_MT_POSITION_X, 0, 9600, 0, 0); input_abs_set_res(input, ABS_MT_POSITION_X, 40); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, 7200, 0, 0); input_abs_set_res(input, ABS_MT_POSITION_Y, 48); input_set_abs_params(input, ABS_MT_WIDTH_MAJOR, 0, 1024, 0, 0); input_set_abs_params(input, ABS_MT_WIDTH_MINOR, 0, 1024, 0, 0); input_mt_init_slots(input, 10, INPUT_MT_DIRECT); input->name = "Surface3 SPI Capacitive TouchScreen"; input->phys = "input/ts"; input->id.bustype = BUS_SPI; input->id.vendor = 0x045e; /* Microsoft */ input->id.product = 0x0001; input->id.version = 0x0000; error = input_register_device(input); if (error) { dev_err(&data->spi->dev, "Failed to register input device: %d", error); return error; } return 0; } static int surface3_spi_create_pen_input(struct surface3_ts_data *data) { struct input_dev *input; int error; input = devm_input_allocate_device(&data->spi->dev); if (!input) return -ENOMEM; data->pen_input_dev = input; data->pen_tool = BTN_TOOL_PEN; __set_bit(INPUT_PROP_DIRECT, input->propbit); __set_bit(INPUT_PROP_POINTER, input->propbit); input_set_abs_params(input, ABS_X, 0, 9600, 0, 0); input_abs_set_res(input, ABS_X, 40); input_set_abs_params(input, ABS_Y, 0, 7200, 0, 0); input_abs_set_res(input, ABS_Y, 48); input_set_abs_params(input, ABS_PRESSURE, 0, 1024, 0, 0); input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_capability(input, EV_KEY, BTN_STYLUS); input_set_capability(input, EV_KEY, BTN_TOOL_PEN); input_set_capability(input, EV_KEY, BTN_TOOL_RUBBER); input->name = "Surface3 SPI Pen Input"; input->phys = "input/ts"; input->id.bustype = BUS_SPI; input->id.vendor = 0x045e; /* Microsoft */ input->id.product = 0x0002; input->id.version = 0x0000; error = input_register_device(input); if (error) { dev_err(&data->spi->dev, "Failed to register input device: %d", error); return error; } return 0; } static int surface3_spi_probe(struct spi_device *spi) { struct surface3_ts_data *data; int error; /* Set up SPI*/ spi->bits_per_word = 8; spi->mode = SPI_MODE_0; error = spi_setup(spi); if (error) return error; data = devm_kzalloc(&spi->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->spi = spi; spi_set_drvdata(spi, data); error = surface3_spi_get_gpio_config(data); if (error) return error; surface3_spi_power(data, true); surface3_spi_power(data, false); surface3_spi_power(data, true); error = surface3_spi_create_touch_input(data); if (error) return error; error = surface3_spi_create_pen_input(data); if (error) return error; error = devm_request_threaded_irq(&spi->dev, spi->irq, NULL, surface3_spi_irq_handler, IRQF_ONESHOT, "Surface3-irq", data); if (error) return error; return 0; } static int surface3_spi_suspend(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct surface3_ts_data *data = spi_get_drvdata(spi); disable_irq(data->spi->irq); surface3_spi_power(data, false); return 0; } static int surface3_spi_resume(struct device *dev) { struct spi_device *spi = to_spi_device(dev); struct surface3_ts_data *data = spi_get_drvdata(spi); surface3_spi_power(data, true); enable_irq(data->spi->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(surface3_spi_pm_ops, surface3_spi_suspend, surface3_spi_resume); #ifdef CONFIG_ACPI static const struct acpi_device_id surface3_spi_acpi_match[] = { { "MSHW0037", 0 }, { } }; MODULE_DEVICE_TABLE(acpi, surface3_spi_acpi_match); #endif static struct spi_driver surface3_spi_driver = { .driver = { .name = "Surface3-spi", .acpi_match_table = ACPI_PTR(surface3_spi_acpi_match), .pm = pm_sleep_ptr(&surface3_spi_pm_ops), }, .probe = surface3_spi_probe, }; module_spi_driver(surface3_spi_driver); MODULE_AUTHOR("Benjamin Tissoires <[email protected]>"); MODULE_DESCRIPTION("Surface 3 SPI touchscreen driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/surface3_spi.c
/* * Wacom W8001 penabled serial touchscreen driver * * Copyright (c) 2008 Jaya Kumar * Copyright (c) 2010 Red Hat, Inc. * Copyright (c) 2010 - 2011 Ping Cheng, Wacom. <[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. * * Layout based on Elo serial touchscreen driver by Vojtech Pavlik */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input/mt.h> #include <linux/serio.h> #include <linux/ctype.h> #include <linux/delay.h> #define DRIVER_DESC "Wacom W8001 serial touchscreen driver" MODULE_AUTHOR("Jaya Kumar <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); #define W8001_MAX_PHYS 42 #define W8001_MAX_LENGTH 13 #define W8001_LEAD_MASK 0x80 #define W8001_LEAD_BYTE 0x80 #define W8001_TAB_MASK 0x40 #define W8001_TAB_BYTE 0x40 /* set in first byte of touch data packets */ #define W8001_TOUCH_MASK (0x10 | W8001_LEAD_MASK) #define W8001_TOUCH_BYTE (0x10 | W8001_LEAD_BYTE) #define W8001_QUERY_PACKET 0x20 #define W8001_CMD_STOP '0' #define W8001_CMD_START '1' #define W8001_CMD_QUERY '*' #define W8001_CMD_TOUCHQUERY '%' /* length of data packets in bytes, depends on device. */ #define W8001_PKTLEN_TOUCH93 5 #define W8001_PKTLEN_TOUCH9A 7 #define W8001_PKTLEN_TPCPEN 9 #define W8001_PKTLEN_TPCCTL 11 /* control packet */ #define W8001_PKTLEN_TOUCH2FG 13 /* resolution in points/mm */ #define W8001_PEN_RESOLUTION 100 #define W8001_TOUCH_RESOLUTION 10 struct w8001_coord { u8 rdy; u8 tsw; u8 f1; u8 f2; u16 x; u16 y; u16 pen_pressure; u8 tilt_x; u8 tilt_y; }; /* touch query reply packet */ struct w8001_touch_query { u16 x; u16 y; u8 panel_res; u8 capacity_res; u8 sensor_id; }; /* * Per-touchscreen data. */ struct w8001 { struct input_dev *pen_dev; struct input_dev *touch_dev; struct serio *serio; struct completion cmd_done; int id; int idx; unsigned char response_type; unsigned char response[W8001_MAX_LENGTH]; unsigned char data[W8001_MAX_LENGTH]; char phys[W8001_MAX_PHYS]; int type; unsigned int pktlen; u16 max_touch_x; u16 max_touch_y; u16 max_pen_x; u16 max_pen_y; char pen_name[64]; char touch_name[64]; int open_count; struct mutex mutex; }; static void parse_pen_data(u8 *data, struct w8001_coord *coord) { memset(coord, 0, sizeof(*coord)); coord->rdy = data[0] & 0x20; coord->tsw = data[0] & 0x01; coord->f1 = data[0] & 0x02; coord->f2 = data[0] & 0x04; coord->x = (data[1] & 0x7F) << 9; coord->x |= (data[2] & 0x7F) << 2; coord->x |= (data[6] & 0x60) >> 5; coord->y = (data[3] & 0x7F) << 9; coord->y |= (data[4] & 0x7F) << 2; coord->y |= (data[6] & 0x18) >> 3; coord->pen_pressure = data[5] & 0x7F; coord->pen_pressure |= (data[6] & 0x07) << 7 ; coord->tilt_x = data[7] & 0x7F; coord->tilt_y = data[8] & 0x7F; } static void parse_single_touch(u8 *data, struct w8001_coord *coord) { coord->x = (data[1] << 7) | data[2]; coord->y = (data[3] << 7) | data[4]; coord->tsw = data[0] & 0x01; } static void scale_touch_coordinates(struct w8001 *w8001, unsigned int *x, unsigned int *y) { if (w8001->max_pen_x && w8001->max_touch_x) *x = *x * w8001->max_pen_x / w8001->max_touch_x; if (w8001->max_pen_y && w8001->max_touch_y) *y = *y * w8001->max_pen_y / w8001->max_touch_y; } static void parse_multi_touch(struct w8001 *w8001) { struct input_dev *dev = w8001->touch_dev; unsigned char *data = w8001->data; unsigned int x, y; int i; int count = 0; for (i = 0; i < 2; i++) { bool touch = data[0] & (1 << i); input_mt_slot(dev, i); input_mt_report_slot_state(dev, MT_TOOL_FINGER, touch); if (touch) { x = (data[6 * i + 1] << 7) | data[6 * i + 2]; y = (data[6 * i + 3] << 7) | data[6 * i + 4]; /* data[5,6] and [11,12] is finger capacity */ /* scale to pen maximum */ scale_touch_coordinates(w8001, &x, &y); input_report_abs(dev, ABS_MT_POSITION_X, x); input_report_abs(dev, ABS_MT_POSITION_Y, y); count++; } } /* emulate single touch events when stylus is out of proximity. * This is to make single touch backward support consistent * across all Wacom single touch devices. */ if (w8001->type != BTN_TOOL_PEN && w8001->type != BTN_TOOL_RUBBER) { w8001->type = count == 1 ? BTN_TOOL_FINGER : KEY_RESERVED; input_mt_report_pointer_emulation(dev, true); } input_sync(dev); } static void parse_touchquery(u8 *data, struct w8001_touch_query *query) { memset(query, 0, sizeof(*query)); query->panel_res = data[1]; query->sensor_id = data[2] & 0x7; query->capacity_res = data[7]; query->x = data[3] << 9; query->x |= data[4] << 2; query->x |= (data[2] >> 5) & 0x3; query->y = data[5] << 9; query->y |= data[6] << 2; query->y |= (data[2] >> 3) & 0x3; /* Early days' single-finger touch models need the following defaults */ if (!query->x && !query->y) { query->x = 1024; query->y = 1024; if (query->panel_res) query->x = query->y = (1 << query->panel_res); query->panel_res = W8001_TOUCH_RESOLUTION; } } static void report_pen_events(struct w8001 *w8001, struct w8001_coord *coord) { struct input_dev *dev = w8001->pen_dev; /* * We have 1 bit for proximity (rdy) and 3 bits for tip, side, * side2/eraser. If rdy && f2 are set, this can be either pen + side2, * or eraser. Assume: * - if dev is already in proximity and f2 is toggled → pen + side2 * - if dev comes into proximity with f2 set → eraser * If f2 disappears after assuming eraser, fake proximity out for * eraser and in for pen. */ switch (w8001->type) { case BTN_TOOL_RUBBER: if (!coord->f2) { input_report_abs(dev, ABS_PRESSURE, 0); input_report_key(dev, BTN_TOUCH, 0); input_report_key(dev, BTN_STYLUS, 0); input_report_key(dev, BTN_STYLUS2, 0); input_report_key(dev, BTN_TOOL_RUBBER, 0); input_sync(dev); w8001->type = BTN_TOOL_PEN; } break; case BTN_TOOL_FINGER: case KEY_RESERVED: w8001->type = coord->f2 ? BTN_TOOL_RUBBER : BTN_TOOL_PEN; break; default: input_report_key(dev, BTN_STYLUS2, coord->f2); break; } input_report_abs(dev, ABS_X, coord->x); input_report_abs(dev, ABS_Y, coord->y); input_report_abs(dev, ABS_PRESSURE, coord->pen_pressure); input_report_key(dev, BTN_TOUCH, coord->tsw); input_report_key(dev, BTN_STYLUS, coord->f1); input_report_key(dev, w8001->type, coord->rdy); input_sync(dev); if (!coord->rdy) w8001->type = KEY_RESERVED; } static void report_single_touch(struct w8001 *w8001, struct w8001_coord *coord) { struct input_dev *dev = w8001->touch_dev; unsigned int x = coord->x; unsigned int y = coord->y; /* scale to pen maximum */ scale_touch_coordinates(w8001, &x, &y); input_report_abs(dev, ABS_X, x); input_report_abs(dev, ABS_Y, y); input_report_key(dev, BTN_TOUCH, coord->tsw); input_sync(dev); w8001->type = coord->tsw ? BTN_TOOL_FINGER : KEY_RESERVED; } static irqreturn_t w8001_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct w8001 *w8001 = serio_get_drvdata(serio); struct w8001_coord coord; unsigned char tmp; w8001->data[w8001->idx] = data; switch (w8001->idx++) { case 0: if ((data & W8001_LEAD_MASK) != W8001_LEAD_BYTE) { pr_debug("w8001: unsynchronized data: 0x%02x\n", data); w8001->idx = 0; } break; case W8001_PKTLEN_TOUCH93 - 1: case W8001_PKTLEN_TOUCH9A - 1: tmp = w8001->data[0] & W8001_TOUCH_BYTE; if (tmp != W8001_TOUCH_BYTE) break; if (w8001->pktlen == w8001->idx) { w8001->idx = 0; if (w8001->type != BTN_TOOL_PEN && w8001->type != BTN_TOOL_RUBBER) { parse_single_touch(w8001->data, &coord); report_single_touch(w8001, &coord); } } break; /* Pen coordinates packet */ case W8001_PKTLEN_TPCPEN - 1: tmp = w8001->data[0] & W8001_TAB_MASK; if (unlikely(tmp == W8001_TAB_BYTE)) break; tmp = w8001->data[0] & W8001_TOUCH_BYTE; if (tmp == W8001_TOUCH_BYTE) break; w8001->idx = 0; parse_pen_data(w8001->data, &coord); report_pen_events(w8001, &coord); break; /* control packet */ case W8001_PKTLEN_TPCCTL - 1: tmp = w8001->data[0] & W8001_TOUCH_MASK; if (tmp == W8001_TOUCH_BYTE) break; w8001->idx = 0; memcpy(w8001->response, w8001->data, W8001_MAX_LENGTH); w8001->response_type = W8001_QUERY_PACKET; complete(&w8001->cmd_done); break; /* 2 finger touch packet */ case W8001_PKTLEN_TOUCH2FG - 1: w8001->idx = 0; parse_multi_touch(w8001); break; default: /* * ThinkPad X60 Tablet PC (pen only device) sometimes * sends invalid data packets that are larger than * W8001_PKTLEN_TPCPEN. Let's start over again. */ if (!w8001->touch_dev && w8001->idx > W8001_PKTLEN_TPCPEN - 1) w8001->idx = 0; } return IRQ_HANDLED; } static int w8001_command(struct w8001 *w8001, unsigned char command, bool wait_response) { int rc; w8001->response_type = 0; init_completion(&w8001->cmd_done); rc = serio_write(w8001->serio, command); if (rc == 0 && wait_response) { wait_for_completion_timeout(&w8001->cmd_done, HZ); if (w8001->response_type != W8001_QUERY_PACKET) rc = -EIO; } return rc; } static int w8001_open(struct input_dev *dev) { struct w8001 *w8001 = input_get_drvdata(dev); int err; err = mutex_lock_interruptible(&w8001->mutex); if (err) return err; if (w8001->open_count++ == 0) { err = w8001_command(w8001, W8001_CMD_START, false); if (err) w8001->open_count--; } mutex_unlock(&w8001->mutex); return err; } static void w8001_close(struct input_dev *dev) { struct w8001 *w8001 = input_get_drvdata(dev); mutex_lock(&w8001->mutex); if (--w8001->open_count == 0) w8001_command(w8001, W8001_CMD_STOP, false); mutex_unlock(&w8001->mutex); } static int w8001_detect(struct w8001 *w8001) { int error; error = w8001_command(w8001, W8001_CMD_STOP, false); if (error) return error; msleep(250); /* wait 250ms before querying the device */ return 0; } static int w8001_setup_pen(struct w8001 *w8001, char *basename, size_t basename_sz) { struct input_dev *dev = w8001->pen_dev; struct w8001_coord coord; int error; /* penabled? */ error = w8001_command(w8001, W8001_CMD_QUERY, true); if (error) return error; __set_bit(EV_KEY, dev->evbit); __set_bit(EV_ABS, dev->evbit); __set_bit(BTN_TOUCH, dev->keybit); __set_bit(BTN_TOOL_PEN, dev->keybit); __set_bit(BTN_TOOL_RUBBER, dev->keybit); __set_bit(BTN_STYLUS, dev->keybit); __set_bit(BTN_STYLUS2, dev->keybit); __set_bit(INPUT_PROP_DIRECT, dev->propbit); parse_pen_data(w8001->response, &coord); w8001->max_pen_x = coord.x; w8001->max_pen_y = coord.y; input_set_abs_params(dev, ABS_X, 0, coord.x, 0, 0); input_set_abs_params(dev, ABS_Y, 0, coord.y, 0, 0); input_abs_set_res(dev, ABS_X, W8001_PEN_RESOLUTION); input_abs_set_res(dev, ABS_Y, W8001_PEN_RESOLUTION); input_set_abs_params(dev, ABS_PRESSURE, 0, coord.pen_pressure, 0, 0); if (coord.tilt_x && coord.tilt_y) { input_set_abs_params(dev, ABS_TILT_X, 0, coord.tilt_x, 0, 0); input_set_abs_params(dev, ABS_TILT_Y, 0, coord.tilt_y, 0, 0); } w8001->id = 0x90; strlcat(basename, " Penabled", basename_sz); return 0; } static int w8001_setup_touch(struct w8001 *w8001, char *basename, size_t basename_sz) { struct input_dev *dev = w8001->touch_dev; struct w8001_touch_query touch; int error; /* Touch enabled? */ error = w8001_command(w8001, W8001_CMD_TOUCHQUERY, true); if (error) return error; /* * Some non-touch devices may reply to the touch query. But their * second byte is empty, which indicates touch is not supported. */ if (!w8001->response[1]) return -ENXIO; __set_bit(EV_KEY, dev->evbit); __set_bit(EV_ABS, dev->evbit); __set_bit(BTN_TOUCH, dev->keybit); __set_bit(INPUT_PROP_DIRECT, dev->propbit); parse_touchquery(w8001->response, &touch); w8001->max_touch_x = touch.x; w8001->max_touch_y = touch.y; if (w8001->max_pen_x && w8001->max_pen_y) { /* if pen is supported scale to pen maximum */ touch.x = w8001->max_pen_x; touch.y = w8001->max_pen_y; touch.panel_res = W8001_PEN_RESOLUTION; } input_set_abs_params(dev, ABS_X, 0, touch.x, 0, 0); input_set_abs_params(dev, ABS_Y, 0, touch.y, 0, 0); input_abs_set_res(dev, ABS_X, touch.panel_res); input_abs_set_res(dev, ABS_Y, touch.panel_res); switch (touch.sensor_id) { case 0: case 2: w8001->pktlen = W8001_PKTLEN_TOUCH93; w8001->id = 0x93; strlcat(basename, " 1FG", basename_sz); break; case 1: case 3: case 4: w8001->pktlen = W8001_PKTLEN_TOUCH9A; strlcat(basename, " 1FG", basename_sz); w8001->id = 0x9a; break; case 5: w8001->pktlen = W8001_PKTLEN_TOUCH2FG; __set_bit(BTN_TOOL_DOUBLETAP, dev->keybit); error = input_mt_init_slots(dev, 2, 0); if (error) { dev_err(&w8001->serio->dev, "failed to initialize MT slots: %d\n", error); return error; } input_set_abs_params(dev, ABS_MT_POSITION_X, 0, touch.x, 0, 0); input_set_abs_params(dev, ABS_MT_POSITION_Y, 0, touch.y, 0, 0); input_set_abs_params(dev, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); input_abs_set_res(dev, ABS_MT_POSITION_X, touch.panel_res); input_abs_set_res(dev, ABS_MT_POSITION_Y, touch.panel_res); strlcat(basename, " 2FG", basename_sz); if (w8001->max_pen_x && w8001->max_pen_y) w8001->id = 0xE3; else w8001->id = 0xE2; break; } strlcat(basename, " Touchscreen", basename_sz); return 0; } static void w8001_set_devdata(struct input_dev *dev, struct w8001 *w8001, struct serio *serio) { dev->phys = w8001->phys; dev->id.bustype = BUS_RS232; dev->id.product = w8001->id; dev->id.vendor = 0x056a; dev->id.version = 0x0100; dev->open = w8001_open; dev->close = w8001_close; dev->dev.parent = &serio->dev; input_set_drvdata(dev, w8001); } /* * w8001_disconnect() is the opposite of w8001_connect() */ static void w8001_disconnect(struct serio *serio) { struct w8001 *w8001 = serio_get_drvdata(serio); serio_close(serio); if (w8001->pen_dev) input_unregister_device(w8001->pen_dev); if (w8001->touch_dev) input_unregister_device(w8001->touch_dev); kfree(w8001); serio_set_drvdata(serio, NULL); } /* * w8001_connect() is the routine that is called when someone adds a * new serio device that supports the w8001 protocol and registers it as * an input device. */ static int w8001_connect(struct serio *serio, struct serio_driver *drv) { struct w8001 *w8001; struct input_dev *input_dev_pen; struct input_dev *input_dev_touch; char basename[64]; int err, err_pen, err_touch; w8001 = kzalloc(sizeof(struct w8001), GFP_KERNEL); input_dev_pen = input_allocate_device(); input_dev_touch = input_allocate_device(); if (!w8001 || !input_dev_pen || !input_dev_touch) { err = -ENOMEM; goto fail1; } w8001->serio = serio; w8001->pen_dev = input_dev_pen; w8001->touch_dev = input_dev_touch; mutex_init(&w8001->mutex); init_completion(&w8001->cmd_done); snprintf(w8001->phys, sizeof(w8001->phys), "%s/input0", serio->phys); serio_set_drvdata(serio, w8001); err = serio_open(serio, drv); if (err) goto fail2; err = w8001_detect(w8001); if (err) goto fail3; /* For backwards-compatibility we compose the basename based on * capabilities and then just append the tool type */ strscpy(basename, "Wacom Serial", sizeof(basename)); err_pen = w8001_setup_pen(w8001, basename, sizeof(basename)); err_touch = w8001_setup_touch(w8001, basename, sizeof(basename)); if (err_pen && err_touch) { err = -ENXIO; goto fail3; } if (!err_pen) { strscpy(w8001->pen_name, basename, sizeof(w8001->pen_name)); strlcat(w8001->pen_name, " Pen", sizeof(w8001->pen_name)); input_dev_pen->name = w8001->pen_name; w8001_set_devdata(input_dev_pen, w8001, serio); err = input_register_device(w8001->pen_dev); if (err) goto fail3; } else { input_free_device(input_dev_pen); input_dev_pen = NULL; w8001->pen_dev = NULL; } if (!err_touch) { strscpy(w8001->touch_name, basename, sizeof(w8001->touch_name)); strlcat(w8001->touch_name, " Finger", sizeof(w8001->touch_name)); input_dev_touch->name = w8001->touch_name; w8001_set_devdata(input_dev_touch, w8001, serio); err = input_register_device(w8001->touch_dev); if (err) goto fail4; } else { input_free_device(input_dev_touch); input_dev_touch = NULL; w8001->touch_dev = NULL; } return 0; fail4: if (w8001->pen_dev) input_unregister_device(w8001->pen_dev); fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev_pen); input_free_device(input_dev_touch); kfree(w8001); return err; } static const struct serio_device_id w8001_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_W8001, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, w8001_serio_ids); static struct serio_driver w8001_drv = { .driver = { .name = "w8001", }, .description = DRIVER_DESC, .id_table = w8001_serio_ids, .interrupt = w8001_interrupt, .connect = w8001_connect, .disconnect = w8001_disconnect, }; module_serio_driver(w8001_drv);
linux-master
drivers/input/touchscreen/wacom_w8001.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * TSC2004/TSC2005 touchscreen driver core * * Copyright (C) 2006-2010 Nokia Corporation * Copyright (C) 2015 QWERTY Embedded Design * Copyright (C) 2015 EMAC Inc. * * Author: Lauri Leukkunen <[email protected]> * based on TSC2301 driver by Klaus K. Pedersen <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/of.h> #include <linux/regulator/consumer.h> #include <linux/regmap.h> #include <linux/gpio/consumer.h> #include "tsc200x-core.h" /* * The touchscreen interface operates as follows: * * 1) Pen is pressed against the touchscreen. * 2) TSC200X performs AD conversion. * 3) After the conversion is done TSC200X drives DAV line down. * 4) GPIO IRQ is received and tsc200x_irq_thread() is scheduled. * 5) tsc200x_irq_thread() queues up a transfer to fetch the x, y, z1, z2 * values. * 6) tsc200x_irq_thread() reports coordinates to input layer and sets up * tsc200x_penup_timer() to be called after TSC200X_PENUP_TIME_MS (40ms). * 7) When the penup timer expires, there have not been touch or DAV interrupts * during the last 40ms which means the pen has been lifted. * * ESD recovery via a hardware reset is done if the TSC200X doesn't respond * after a configurable period (in ms) of activity. If esd_timeout is 0, the * watchdog is disabled. */ static const struct regmap_range tsc200x_writable_ranges[] = { regmap_reg_range(TSC200X_REG_AUX_HIGH, TSC200X_REG_CFR2), }; static const struct regmap_access_table tsc200x_writable_table = { .yes_ranges = tsc200x_writable_ranges, .n_yes_ranges = ARRAY_SIZE(tsc200x_writable_ranges), }; const struct regmap_config tsc200x_regmap_config = { .reg_bits = 8, .val_bits = 16, .reg_stride = 0x08, .max_register = 0x78, .read_flag_mask = TSC200X_REG_READ, .write_flag_mask = TSC200X_REG_PND0, .wr_table = &tsc200x_writable_table, .use_single_read = true, .use_single_write = true, }; EXPORT_SYMBOL_GPL(tsc200x_regmap_config); struct tsc200x_data { u16 x; u16 y; u16 z1; u16 z2; } __packed; #define TSC200X_DATA_REGS 4 struct tsc200x { struct device *dev; struct regmap *regmap; __u16 bustype; struct input_dev *idev; char phys[32]; struct mutex mutex; /* raw copy of previous x,y,z */ int in_x; int in_y; int in_z1; int in_z2; struct touchscreen_properties prop; spinlock_t lock; struct timer_list penup_timer; unsigned int esd_timeout; struct delayed_work esd_work; unsigned long last_valid_interrupt; unsigned int x_plate_ohm; bool opened; bool suspended; bool pen_down; struct regulator *vio; struct gpio_desc *reset_gpio; int (*tsc200x_cmd)(struct device *dev, u8 cmd); int irq; }; static void tsc200x_update_pen_state(struct tsc200x *ts, int x, int y, int pressure) { if (pressure) { touchscreen_report_pos(ts->idev, &ts->prop, x, y, false); input_report_abs(ts->idev, ABS_PRESSURE, pressure); if (!ts->pen_down) { input_report_key(ts->idev, BTN_TOUCH, !!pressure); ts->pen_down = true; } } else { input_report_abs(ts->idev, ABS_PRESSURE, 0); if (ts->pen_down) { input_report_key(ts->idev, BTN_TOUCH, 0); ts->pen_down = false; } } input_sync(ts->idev); dev_dbg(ts->dev, "point(%4d,%4d), pressure (%4d)\n", x, y, pressure); } static irqreturn_t tsc200x_irq_thread(int irq, void *_ts) { struct tsc200x *ts = _ts; unsigned long flags; unsigned int pressure; struct tsc200x_data tsdata; int error; /* read the coordinates */ error = regmap_bulk_read(ts->regmap, TSC200X_REG_X, &tsdata, TSC200X_DATA_REGS); if (unlikely(error)) goto out; /* validate position */ if (unlikely(tsdata.x > MAX_12BIT || tsdata.y > MAX_12BIT)) goto out; /* Skip reading if the pressure components are out of range */ if (unlikely(tsdata.z1 == 0 || tsdata.z2 > MAX_12BIT)) goto out; if (unlikely(tsdata.z1 >= tsdata.z2)) goto out; /* * Skip point if this is a pen down with the exact same values as * the value before pen-up - that implies SPI fed us stale data */ if (!ts->pen_down && ts->in_x == tsdata.x && ts->in_y == tsdata.y && ts->in_z1 == tsdata.z1 && ts->in_z2 == tsdata.z2) { goto out; } /* * At this point we are happy we have a valid and useful reading. * Remember it for later comparisons. We may now begin downsampling. */ ts->in_x = tsdata.x; ts->in_y = tsdata.y; ts->in_z1 = tsdata.z1; ts->in_z2 = tsdata.z2; /* Compute touch pressure resistance using equation #1 */ pressure = tsdata.x * (tsdata.z2 - tsdata.z1) / tsdata.z1; pressure = pressure * ts->x_plate_ohm / 4096; if (unlikely(pressure > MAX_12BIT)) goto out; spin_lock_irqsave(&ts->lock, flags); tsc200x_update_pen_state(ts, tsdata.x, tsdata.y, pressure); mod_timer(&ts->penup_timer, jiffies + msecs_to_jiffies(TSC200X_PENUP_TIME_MS)); spin_unlock_irqrestore(&ts->lock, flags); ts->last_valid_interrupt = jiffies; out: return IRQ_HANDLED; } static void tsc200x_penup_timer(struct timer_list *t) { struct tsc200x *ts = from_timer(ts, t, penup_timer); unsigned long flags; spin_lock_irqsave(&ts->lock, flags); tsc200x_update_pen_state(ts, 0, 0, 0); spin_unlock_irqrestore(&ts->lock, flags); } static void tsc200x_start_scan(struct tsc200x *ts) { regmap_write(ts->regmap, TSC200X_REG_CFR0, TSC200X_CFR0_INITVALUE); regmap_write(ts->regmap, TSC200X_REG_CFR1, TSC200X_CFR1_INITVALUE); regmap_write(ts->regmap, TSC200X_REG_CFR2, TSC200X_CFR2_INITVALUE); ts->tsc200x_cmd(ts->dev, TSC200X_CMD_NORMAL); } static void tsc200x_stop_scan(struct tsc200x *ts) { ts->tsc200x_cmd(ts->dev, TSC200X_CMD_STOP); } static void tsc200x_reset(struct tsc200x *ts) { if (ts->reset_gpio) { gpiod_set_value_cansleep(ts->reset_gpio, 1); usleep_range(100, 500); /* only 10us required */ gpiod_set_value_cansleep(ts->reset_gpio, 0); } } /* must be called with ts->mutex held */ static void __tsc200x_disable(struct tsc200x *ts) { tsc200x_stop_scan(ts); disable_irq(ts->irq); del_timer_sync(&ts->penup_timer); cancel_delayed_work_sync(&ts->esd_work); enable_irq(ts->irq); } /* must be called with ts->mutex held */ static void __tsc200x_enable(struct tsc200x *ts) { tsc200x_start_scan(ts); if (ts->esd_timeout && ts->reset_gpio) { ts->last_valid_interrupt = jiffies; schedule_delayed_work(&ts->esd_work, round_jiffies_relative( msecs_to_jiffies(ts->esd_timeout))); } } static ssize_t tsc200x_selftest_show(struct device *dev, struct device_attribute *attr, char *buf) { struct tsc200x *ts = dev_get_drvdata(dev); unsigned int temp_high; unsigned int temp_high_orig; unsigned int temp_high_test; bool success = true; int error; mutex_lock(&ts->mutex); /* * Test TSC200X communications via temp high register. */ __tsc200x_disable(ts); error = regmap_read(ts->regmap, TSC200X_REG_TEMP_HIGH, &temp_high_orig); if (error) { dev_warn(dev, "selftest failed: read error %d\n", error); success = false; goto out; } temp_high_test = (temp_high_orig - 1) & MAX_12BIT; error = regmap_write(ts->regmap, TSC200X_REG_TEMP_HIGH, temp_high_test); if (error) { dev_warn(dev, "selftest failed: write error %d\n", error); success = false; goto out; } error = regmap_read(ts->regmap, TSC200X_REG_TEMP_HIGH, &temp_high); if (error) { dev_warn(dev, "selftest failed: read error %d after write\n", error); success = false; goto out; } if (temp_high != temp_high_test) { dev_warn(dev, "selftest failed: %d != %d\n", temp_high, temp_high_test); success = false; } /* hardware reset */ tsc200x_reset(ts); if (!success) goto out; /* test that the reset really happened */ error = regmap_read(ts->regmap, TSC200X_REG_TEMP_HIGH, &temp_high); if (error) { dev_warn(dev, "selftest failed: read error %d after reset\n", error); success = false; goto out; } if (temp_high != temp_high_orig) { dev_warn(dev, "selftest failed after reset: %d != %d\n", temp_high, temp_high_orig); success = false; } out: __tsc200x_enable(ts); mutex_unlock(&ts->mutex); return sprintf(buf, "%d\n", success); } static DEVICE_ATTR(selftest, S_IRUGO, tsc200x_selftest_show, NULL); static struct attribute *tsc200x_attrs[] = { &dev_attr_selftest.attr, NULL }; static umode_t tsc200x_attr_is_visible(struct kobject *kobj, struct attribute *attr, int n) { struct device *dev = kobj_to_dev(kobj); struct tsc200x *ts = dev_get_drvdata(dev); umode_t mode = attr->mode; if (attr == &dev_attr_selftest.attr) { if (!ts->reset_gpio) mode = 0; } return mode; } static const struct attribute_group tsc200x_attr_group = { .is_visible = tsc200x_attr_is_visible, .attrs = tsc200x_attrs, }; static void tsc200x_esd_work(struct work_struct *work) { struct tsc200x *ts = container_of(work, struct tsc200x, esd_work.work); int error; unsigned int r; if (!mutex_trylock(&ts->mutex)) { /* * If the mutex is taken, it means that disable or enable is in * progress. In that case just reschedule the work. If the work * is not needed, it will be canceled by disable. */ goto reschedule; } if (time_is_after_jiffies(ts->last_valid_interrupt + msecs_to_jiffies(ts->esd_timeout))) goto out; /* We should be able to read register without disabling interrupts. */ error = regmap_read(ts->regmap, TSC200X_REG_CFR0, &r); if (!error && !((r ^ TSC200X_CFR0_INITVALUE) & TSC200X_CFR0_RW_MASK)) { goto out; } /* * If we could not read our known value from configuration register 0 * then we should reset the controller as if from power-up and start * scanning again. */ dev_info(ts->dev, "TSC200X not responding - resetting\n"); disable_irq(ts->irq); del_timer_sync(&ts->penup_timer); tsc200x_update_pen_state(ts, 0, 0, 0); tsc200x_reset(ts); enable_irq(ts->irq); tsc200x_start_scan(ts); out: mutex_unlock(&ts->mutex); reschedule: /* re-arm the watchdog */ schedule_delayed_work(&ts->esd_work, round_jiffies_relative( msecs_to_jiffies(ts->esd_timeout))); } static int tsc200x_open(struct input_dev *input) { struct tsc200x *ts = input_get_drvdata(input); mutex_lock(&ts->mutex); if (!ts->suspended) __tsc200x_enable(ts); ts->opened = true; mutex_unlock(&ts->mutex); return 0; } static void tsc200x_close(struct input_dev *input) { struct tsc200x *ts = input_get_drvdata(input); mutex_lock(&ts->mutex); if (!ts->suspended) __tsc200x_disable(ts); ts->opened = false; mutex_unlock(&ts->mutex); } int tsc200x_probe(struct device *dev, int irq, const struct input_id *tsc_id, struct regmap *regmap, int (*tsc200x_cmd)(struct device *dev, u8 cmd)) { struct tsc200x *ts; struct input_dev *input_dev; u32 x_plate_ohm; u32 esd_timeout; int error; if (irq <= 0) { dev_err(dev, "no irq\n"); return -ENODEV; } if (IS_ERR(regmap)) return PTR_ERR(regmap); if (!tsc200x_cmd) { dev_err(dev, "no cmd function\n"); return -ENODEV; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; input_dev = devm_input_allocate_device(dev); if (!input_dev) return -ENOMEM; ts->irq = irq; ts->dev = dev; ts->idev = input_dev; ts->regmap = regmap; ts->tsc200x_cmd = tsc200x_cmd; error = device_property_read_u32(dev, "ti,x-plate-ohms", &x_plate_ohm); ts->x_plate_ohm = error ? TSC200X_DEF_RESISTOR : x_plate_ohm; error = device_property_read_u32(dev, "ti,esd-recovery-timeout-ms", &esd_timeout); ts->esd_timeout = error ? 0 : esd_timeout; 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, "error acquiring reset gpio: %d\n", error); return error; } ts->vio = devm_regulator_get(dev, "vio"); if (IS_ERR(ts->vio)) { error = PTR_ERR(ts->vio); dev_err(dev, "error acquiring vio regulator: %d", error); return error; } mutex_init(&ts->mutex); spin_lock_init(&ts->lock); timer_setup(&ts->penup_timer, tsc200x_penup_timer, 0); INIT_DELAYED_WORK(&ts->esd_work, tsc200x_esd_work); snprintf(ts->phys, sizeof(ts->phys), "%s/input-ts", dev_name(dev)); if (tsc_id->product == 2004) { input_dev->name = "TSC200X touchscreen"; } else { input_dev->name = devm_kasprintf(dev, GFP_KERNEL, "TSC%04d touchscreen", tsc_id->product); if (!input_dev->name) return -ENOMEM; } input_dev->phys = ts->phys; input_dev->id = *tsc_id; input_dev->open = tsc200x_open; input_dev->close = tsc200x_close; input_set_drvdata(input_dev, ts); __set_bit(INPUT_PROP_DIRECT, input_dev->propbit); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_12BIT, TSC200X_DEF_X_FUZZ, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, TSC200X_DEF_Y_FUZZ, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, MAX_12BIT, TSC200X_DEF_P_FUZZ, 0); touchscreen_parse_properties(input_dev, false, &ts->prop); /* Ensure the touchscreen is off */ tsc200x_stop_scan(ts); error = devm_request_threaded_irq(dev, irq, NULL, tsc200x_irq_thread, IRQF_TRIGGER_RISING | IRQF_ONESHOT, "tsc200x", ts); if (error) { dev_err(dev, "Failed to request irq, err: %d\n", error); return error; } error = regulator_enable(ts->vio); if (error) return error; dev_set_drvdata(dev, ts); error = sysfs_create_group(&dev->kobj, &tsc200x_attr_group); if (error) { dev_err(dev, "Failed to create sysfs attributes, err: %d\n", error); goto disable_regulator; } error = input_register_device(ts->idev); if (error) { dev_err(dev, "Failed to register input device, err: %d\n", error); goto err_remove_sysfs; } irq_set_irq_wake(irq, 1); return 0; err_remove_sysfs: sysfs_remove_group(&dev->kobj, &tsc200x_attr_group); disable_regulator: regulator_disable(ts->vio); return error; } EXPORT_SYMBOL_GPL(tsc200x_probe); void tsc200x_remove(struct device *dev) { struct tsc200x *ts = dev_get_drvdata(dev); sysfs_remove_group(&dev->kobj, &tsc200x_attr_group); regulator_disable(ts->vio); } EXPORT_SYMBOL_GPL(tsc200x_remove); static int tsc200x_suspend(struct device *dev) { struct tsc200x *ts = dev_get_drvdata(dev); mutex_lock(&ts->mutex); if (!ts->suspended && ts->opened) __tsc200x_disable(ts); ts->suspended = true; mutex_unlock(&ts->mutex); return 0; } static int tsc200x_resume(struct device *dev) { struct tsc200x *ts = dev_get_drvdata(dev); mutex_lock(&ts->mutex); if (ts->suspended && ts->opened) __tsc200x_enable(ts); ts->suspended = false; mutex_unlock(&ts->mutex); return 0; } EXPORT_GPL_SIMPLE_DEV_PM_OPS(tsc200x_pm_ops, tsc200x_suspend, tsc200x_resume); MODULE_AUTHOR("Lauri Leukkunen <[email protected]>"); MODULE_DESCRIPTION("TSC200x Touchscreen Driver Core"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/tsc200x-core.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for the Freescale Semiconductor MC13783 touchscreen. * * Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright (C) 2009 Sascha Hauer, Pengutronix * * Initial development of this code was funded by * Phytec Messtechnik GmbH, http://www.phytec.de/ */ #include <linux/platform_device.h> #include <linux/mfd/mc13783.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #define MC13783_TS_NAME "mc13783-ts" #define DEFAULT_SAMPLE_TOLERANCE 300 static unsigned int sample_tolerance = DEFAULT_SAMPLE_TOLERANCE; module_param(sample_tolerance, uint, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(sample_tolerance, "If the minimal and maximal value read out for one axis (out " "of three) differ by this value (default: " __stringify(DEFAULT_SAMPLE_TOLERANCE) ") or more, the reading " "is supposed to be wrong and is discarded. Set to 0 to " "disable this check."); struct mc13783_ts_priv { struct input_dev *idev; struct mc13xxx *mc13xxx; struct delayed_work work; unsigned int sample[4]; struct mc13xxx_ts_platform_data *touch; }; static irqreturn_t mc13783_ts_handler(int irq, void *data) { struct mc13783_ts_priv *priv = data; mc13xxx_irq_ack(priv->mc13xxx, irq); /* * Kick off reading coordinates. Note that if work happens already * be queued for future execution (it rearms itself) it will not * be rescheduled for immediate execution here. However the rearm * delay is HZ / 50 which is acceptable. */ schedule_delayed_work(&priv->work, 0); return IRQ_HANDLED; } #define sort3(a0, a1, a2) ({ \ if (a0 > a1) \ swap(a0, a1); \ if (a1 > a2) \ swap(a1, a2); \ if (a0 > a1) \ swap(a0, a1); \ }) static void mc13783_ts_report_sample(struct mc13783_ts_priv *priv) { struct input_dev *idev = priv->idev; int x0, x1, x2, y0, y1, y2; int cr0, cr1; /* * the values are 10-bit wide only, but the two least significant * bits are for future 12 bit use and reading yields 0 */ x0 = priv->sample[0] & 0xfff; x1 = priv->sample[1] & 0xfff; x2 = priv->sample[2] & 0xfff; y0 = priv->sample[3] & 0xfff; y1 = (priv->sample[0] >> 12) & 0xfff; y2 = (priv->sample[1] >> 12) & 0xfff; cr0 = (priv->sample[2] >> 12) & 0xfff; cr1 = (priv->sample[3] >> 12) & 0xfff; dev_dbg(&idev->dev, "x: (% 4d,% 4d,% 4d) y: (% 4d, % 4d,% 4d) cr: (% 4d, % 4d)\n", x0, x1, x2, y0, y1, y2, cr0, cr1); sort3(x0, x1, x2); sort3(y0, y1, y2); cr0 = (cr0 + cr1) / 2; if (!cr0 || !sample_tolerance || (x2 - x0 < sample_tolerance && y2 - y0 < sample_tolerance)) { /* report the median coordinate and average pressure */ if (cr0) { input_report_abs(idev, ABS_X, x1); input_report_abs(idev, ABS_Y, y1); dev_dbg(&idev->dev, "report (%d, %d, %d)\n", x1, y1, 0x1000 - cr0); schedule_delayed_work(&priv->work, HZ / 50); } else { dev_dbg(&idev->dev, "report release\n"); } input_report_abs(idev, ABS_PRESSURE, cr0 ? 0x1000 - cr0 : cr0); input_report_key(idev, BTN_TOUCH, cr0); input_sync(idev); } else { dev_dbg(&idev->dev, "discard event\n"); } } static void mc13783_ts_work(struct work_struct *work) { struct mc13783_ts_priv *priv = container_of(work, struct mc13783_ts_priv, work.work); unsigned int mode = MC13XXX_ADC_MODE_TS; unsigned int channel = 12; if (mc13xxx_adc_do_conversion(priv->mc13xxx, mode, channel, priv->touch->ato, priv->touch->atox, priv->sample) == 0) mc13783_ts_report_sample(priv); } static int mc13783_ts_open(struct input_dev *dev) { struct mc13783_ts_priv *priv = input_get_drvdata(dev); int ret; mc13xxx_lock(priv->mc13xxx); mc13xxx_irq_ack(priv->mc13xxx, MC13XXX_IRQ_TS); ret = mc13xxx_irq_request(priv->mc13xxx, MC13XXX_IRQ_TS, mc13783_ts_handler, MC13783_TS_NAME, priv); if (ret) goto out; ret = mc13xxx_reg_rmw(priv->mc13xxx, MC13XXX_ADC0, MC13XXX_ADC0_TSMOD_MASK, MC13XXX_ADC0_TSMOD0); if (ret) mc13xxx_irq_free(priv->mc13xxx, MC13XXX_IRQ_TS, priv); out: mc13xxx_unlock(priv->mc13xxx); return ret; } static void mc13783_ts_close(struct input_dev *dev) { struct mc13783_ts_priv *priv = input_get_drvdata(dev); mc13xxx_lock(priv->mc13xxx); mc13xxx_reg_rmw(priv->mc13xxx, MC13XXX_ADC0, MC13XXX_ADC0_TSMOD_MASK, 0); mc13xxx_irq_free(priv->mc13xxx, MC13XXX_IRQ_TS, priv); mc13xxx_unlock(priv->mc13xxx); cancel_delayed_work_sync(&priv->work); } static int __init mc13783_ts_probe(struct platform_device *pdev) { struct mc13783_ts_priv *priv; struct input_dev *idev; int ret = -ENOMEM; priv = kzalloc(sizeof(*priv), GFP_KERNEL); idev = input_allocate_device(); if (!priv || !idev) goto err_free_mem; INIT_DELAYED_WORK(&priv->work, mc13783_ts_work); priv->mc13xxx = dev_get_drvdata(pdev->dev.parent); priv->idev = idev; priv->touch = dev_get_platdata(&pdev->dev); if (!priv->touch) { dev_err(&pdev->dev, "missing platform data\n"); ret = -ENODEV; goto err_free_mem; } idev->name = MC13783_TS_NAME; idev->dev.parent = &pdev->dev; idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); idev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(idev, ABS_X, 0, 0xfff, 0, 0); input_set_abs_params(idev, ABS_Y, 0, 0xfff, 0, 0); input_set_abs_params(idev, ABS_PRESSURE, 0, 0xfff, 0, 0); idev->open = mc13783_ts_open; idev->close = mc13783_ts_close; input_set_drvdata(idev, priv); ret = input_register_device(priv->idev); if (ret) { dev_err(&pdev->dev, "register input device failed with %d\n", ret); goto err_free_mem; } platform_set_drvdata(pdev, priv); return 0; err_free_mem: input_free_device(idev); kfree(priv); return ret; } static int mc13783_ts_remove(struct platform_device *pdev) { struct mc13783_ts_priv *priv = platform_get_drvdata(pdev); input_unregister_device(priv->idev); kfree(priv); return 0; } static struct platform_driver mc13783_ts_driver = { .remove = mc13783_ts_remove, .driver = { .name = MC13783_TS_NAME, }, }; module_platform_driver_probe(mc13783_ts_driver, mc13783_ts_probe); MODULE_DESCRIPTION("MC13783 input touchscreen driver"); MODULE_AUTHOR("Sascha Hauer <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:" MC13783_TS_NAME);
linux-master
drivers/input/touchscreen/mc13783_ts.c
// SPDX-License-Identifier: GPL-2.0 // // Copyright (C) 2014-2015 Pengutronix, Markus Pargmann <[email protected]> // Based on driver from 2011: // Juergen Beisert, Pengutronix <[email protected]> // // This is the driver for the imx25 TCQ (Touchscreen Conversion Queue) // connected to the imx25 ADC. #include <linux/clk.h> #include <linux/device.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/mfd/imx25-tsadc.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/regmap.h> static const char mx25_tcq_name[] = "mx25-tcq"; enum mx25_tcq_mode { MX25_TS_4WIRE, }; struct mx25_tcq_priv { struct regmap *regs; struct regmap *core_regs; struct input_dev *idev; enum mx25_tcq_mode mode; unsigned int pen_threshold; unsigned int sample_count; unsigned int expected_samples; unsigned int pen_debounce; unsigned int settling_time; struct clk *clk; int irq; struct device *dev; }; static struct regmap_config mx25_tcq_regconfig = { .fast_io = true, .max_register = 0x5c, .reg_bits = 32, .val_bits = 32, .reg_stride = 4, }; static const struct of_device_id mx25_tcq_ids[] = { { .compatible = "fsl,imx25-tcq", }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, mx25_tcq_ids); #define TSC_4WIRE_PRE_INDEX 0 #define TSC_4WIRE_X_INDEX 1 #define TSC_4WIRE_Y_INDEX 2 #define TSC_4WIRE_POST_INDEX 3 #define TSC_4WIRE_LEAVE 4 #define MX25_TSC_DEF_THRESHOLD 80 #define TSC_MAX_SAMPLES 16 #define MX25_TSC_REPEAT_WAIT 14 enum mx25_adc_configurations { MX25_CFG_PRECHARGE = 0, MX25_CFG_TOUCH_DETECT, MX25_CFG_X_MEASUREMENT, MX25_CFG_Y_MEASUREMENT, }; #define MX25_PRECHARGE_VALUE (\ MX25_ADCQ_CFG_YPLL_OFF | \ MX25_ADCQ_CFG_XNUR_OFF | \ MX25_ADCQ_CFG_XPUL_HIGH | \ MX25_ADCQ_CFG_REFP_INT | \ MX25_ADCQ_CFG_IN_XP | \ MX25_ADCQ_CFG_REFN_NGND2 | \ MX25_ADCQ_CFG_IGS) #define MX25_TOUCH_DETECT_VALUE (\ MX25_ADCQ_CFG_YNLR | \ MX25_ADCQ_CFG_YPLL_OFF | \ MX25_ADCQ_CFG_XNUR_OFF | \ MX25_ADCQ_CFG_XPUL_OFF | \ MX25_ADCQ_CFG_REFP_INT | \ MX25_ADCQ_CFG_IN_XP | \ MX25_ADCQ_CFG_REFN_NGND2 | \ MX25_ADCQ_CFG_PENIACK) static void imx25_setup_queue_cfgs(struct mx25_tcq_priv *priv, unsigned int settling_cnt) { u32 precharge_cfg = MX25_PRECHARGE_VALUE | MX25_ADCQ_CFG_SETTLING_TIME(settling_cnt); u32 touch_detect_cfg = MX25_TOUCH_DETECT_VALUE | MX25_ADCQ_CFG_NOS(1) | MX25_ADCQ_CFG_SETTLING_TIME(settling_cnt); regmap_write(priv->core_regs, MX25_TSC_TICR, precharge_cfg); /* PRECHARGE */ regmap_write(priv->regs, MX25_ADCQ_CFG(MX25_CFG_PRECHARGE), precharge_cfg); /* TOUCH_DETECT */ regmap_write(priv->regs, MX25_ADCQ_CFG(MX25_CFG_TOUCH_DETECT), touch_detect_cfg); /* X Measurement */ regmap_write(priv->regs, MX25_ADCQ_CFG(MX25_CFG_X_MEASUREMENT), MX25_ADCQ_CFG_YPLL_OFF | MX25_ADCQ_CFG_XNUR_LOW | MX25_ADCQ_CFG_XPUL_HIGH | MX25_ADCQ_CFG_REFP_XP | MX25_ADCQ_CFG_IN_YP | MX25_ADCQ_CFG_REFN_XN | MX25_ADCQ_CFG_NOS(priv->sample_count) | MX25_ADCQ_CFG_SETTLING_TIME(settling_cnt)); /* Y Measurement */ regmap_write(priv->regs, MX25_ADCQ_CFG(MX25_CFG_Y_MEASUREMENT), MX25_ADCQ_CFG_YNLR | MX25_ADCQ_CFG_YPLL_HIGH | MX25_ADCQ_CFG_XNUR_OFF | MX25_ADCQ_CFG_XPUL_OFF | MX25_ADCQ_CFG_REFP_YP | MX25_ADCQ_CFG_IN_XP | MX25_ADCQ_CFG_REFN_YN | MX25_ADCQ_CFG_NOS(priv->sample_count) | MX25_ADCQ_CFG_SETTLING_TIME(settling_cnt)); /* Enable the touch detection right now */ regmap_write(priv->core_regs, MX25_TSC_TICR, touch_detect_cfg | MX25_ADCQ_CFG_IGS); } static int imx25_setup_queue_4wire(struct mx25_tcq_priv *priv, unsigned settling_cnt, int *items) { imx25_setup_queue_cfgs(priv, settling_cnt); /* Setup the conversion queue */ regmap_write(priv->regs, MX25_ADCQ_ITEM_7_0, MX25_ADCQ_ITEM(0, MX25_CFG_PRECHARGE) | MX25_ADCQ_ITEM(1, MX25_CFG_TOUCH_DETECT) | MX25_ADCQ_ITEM(2, MX25_CFG_X_MEASUREMENT) | MX25_ADCQ_ITEM(3, MX25_CFG_Y_MEASUREMENT) | MX25_ADCQ_ITEM(4, MX25_CFG_PRECHARGE) | MX25_ADCQ_ITEM(5, MX25_CFG_TOUCH_DETECT)); /* * We measure X/Y with 'sample_count' number of samples and execute a * touch detection twice, with 1 sample each */ priv->expected_samples = priv->sample_count * 2 + 2; *items = 6; return 0; } static void mx25_tcq_disable_touch_irq(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_PDMSK, MX25_ADCQ_CR_PDMSK); } static void mx25_tcq_enable_touch_irq(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_PDMSK, 0); } static void mx25_tcq_disable_fifo_irq(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_MR, MX25_ADCQ_MR_FDRY_IRQ, MX25_ADCQ_MR_FDRY_IRQ); } static void mx25_tcq_enable_fifo_irq(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_MR, MX25_ADCQ_MR_FDRY_IRQ, 0); } static void mx25_tcq_force_queue_start(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_FQS, MX25_ADCQ_CR_FQS); } static void mx25_tcq_force_queue_stop(struct mx25_tcq_priv *priv) { regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_FQS, 0); } static void mx25_tcq_fifo_reset(struct mx25_tcq_priv *priv) { u32 tcqcr; regmap_read(priv->regs, MX25_ADCQ_CR, &tcqcr); regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_FRST, MX25_ADCQ_CR_FRST); regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_FRST, 0); regmap_write(priv->regs, MX25_ADCQ_CR, tcqcr); } static void mx25_tcq_re_enable_touch_detection(struct mx25_tcq_priv *priv) { /* stop the queue from looping */ mx25_tcq_force_queue_stop(priv); /* for a clean touch detection, preload the X plane */ regmap_write(priv->core_regs, MX25_TSC_TICR, MX25_PRECHARGE_VALUE); /* waste some time now to pre-load the X plate to high voltage */ mx25_tcq_fifo_reset(priv); /* re-enable the detection right now */ regmap_write(priv->core_regs, MX25_TSC_TICR, MX25_TOUCH_DETECT_VALUE | MX25_ADCQ_CFG_IGS); regmap_update_bits(priv->regs, MX25_ADCQ_SR, MX25_ADCQ_SR_PD, MX25_ADCQ_SR_PD); /* enable the pen down event to be a source for the interrupt */ regmap_update_bits(priv->regs, MX25_ADCQ_MR, MX25_ADCQ_MR_PD_IRQ, 0); /* lets fire the next IRQ if someone touches the touchscreen */ mx25_tcq_enable_touch_irq(priv); } static void mx25_tcq_create_event_for_4wire(struct mx25_tcq_priv *priv, u32 *sample_buf, unsigned int samples) { unsigned int x_pos = 0; unsigned int y_pos = 0; unsigned int touch_pre = 0; unsigned int touch_post = 0; unsigned int i; for (i = 0; i < samples; i++) { unsigned int index = MX25_ADCQ_FIFO_ID(sample_buf[i]); unsigned int val = MX25_ADCQ_FIFO_DATA(sample_buf[i]); switch (index) { case 1: touch_pre = val; break; case 2: x_pos = val; break; case 3: y_pos = val; break; case 5: touch_post = val; break; default: dev_dbg(priv->dev, "Dropped samples because of invalid index %d\n", index); return; } } if (samples != 0) { /* * only if both touch measures are below a threshold, * the position is valid */ if (touch_pre < priv->pen_threshold && touch_post < priv->pen_threshold) { /* valid samples, generate a report */ x_pos /= priv->sample_count; y_pos /= priv->sample_count; input_report_abs(priv->idev, ABS_X, x_pos); input_report_abs(priv->idev, ABS_Y, y_pos); input_report_key(priv->idev, BTN_TOUCH, 1); input_sync(priv->idev); /* get next sample */ mx25_tcq_enable_fifo_irq(priv); } else if (touch_pre >= priv->pen_threshold && touch_post >= priv->pen_threshold) { /* * if both samples are invalid, * generate a release report */ input_report_key(priv->idev, BTN_TOUCH, 0); input_sync(priv->idev); mx25_tcq_re_enable_touch_detection(priv); } else { /* * if only one of both touch measurements are * below the threshold, still some bouncing * happens. Take additional samples in this * case to be sure */ mx25_tcq_enable_fifo_irq(priv); } } } static irqreturn_t mx25_tcq_irq_thread(int irq, void *dev_id) { struct mx25_tcq_priv *priv = dev_id; u32 sample_buf[TSC_MAX_SAMPLES]; unsigned int samples; u32 stats; unsigned int i; /* * Check how many samples are available. We always have to read exactly * sample_count samples from the fifo, or a multiple of sample_count. * Otherwise we mixup samples into different touch events. */ regmap_read(priv->regs, MX25_ADCQ_SR, &stats); samples = MX25_ADCQ_SR_FDN(stats); samples -= samples % priv->sample_count; if (!samples) return IRQ_HANDLED; for (i = 0; i != samples; ++i) regmap_read(priv->regs, MX25_ADCQ_FIFO, &sample_buf[i]); mx25_tcq_create_event_for_4wire(priv, sample_buf, samples); return IRQ_HANDLED; } static irqreturn_t mx25_tcq_irq(int irq, void *dev_id) { struct mx25_tcq_priv *priv = dev_id; u32 stat; int ret = IRQ_HANDLED; regmap_read(priv->regs, MX25_ADCQ_SR, &stat); if (stat & (MX25_ADCQ_SR_FRR | MX25_ADCQ_SR_FUR | MX25_ADCQ_SR_FOR)) mx25_tcq_re_enable_touch_detection(priv); if (stat & MX25_ADCQ_SR_PD) { mx25_tcq_disable_touch_irq(priv); mx25_tcq_force_queue_start(priv); mx25_tcq_enable_fifo_irq(priv); } if (stat & MX25_ADCQ_SR_FDRY) { mx25_tcq_disable_fifo_irq(priv); ret = IRQ_WAKE_THREAD; } regmap_update_bits(priv->regs, MX25_ADCQ_SR, MX25_ADCQ_SR_FRR | MX25_ADCQ_SR_FUR | MX25_ADCQ_SR_FOR | MX25_ADCQ_SR_PD, MX25_ADCQ_SR_FRR | MX25_ADCQ_SR_FUR | MX25_ADCQ_SR_FOR | MX25_ADCQ_SR_PD); return ret; } /* configure the state machine for a 4-wire touchscreen */ static int mx25_tcq_init(struct mx25_tcq_priv *priv) { u32 tgcr; unsigned int ipg_div; unsigned int adc_period; unsigned int debounce_cnt; unsigned int settling_cnt; int itemct; int error; regmap_read(priv->core_regs, MX25_TSC_TGCR, &tgcr); ipg_div = max_t(unsigned int, 4, MX25_TGCR_GET_ADCCLK(tgcr)); adc_period = USEC_PER_SEC * ipg_div * 2 + 2; adc_period /= clk_get_rate(priv->clk) / 1000 + 1; debounce_cnt = DIV_ROUND_UP(priv->pen_debounce, adc_period * 8) - 1; settling_cnt = DIV_ROUND_UP(priv->settling_time, adc_period * 8) - 1; /* Reset */ regmap_write(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_QRST | MX25_ADCQ_CR_FRST); regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_QRST | MX25_ADCQ_CR_FRST, 0); /* up to 128 * 8 ADC clocks are possible */ if (debounce_cnt > 127) debounce_cnt = 127; /* up to 255 * 8 ADC clocks are possible */ if (settling_cnt > 255) settling_cnt = 255; error = imx25_setup_queue_4wire(priv, settling_cnt, &itemct); if (error) return error; regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_LITEMID_MASK | MX25_ADCQ_CR_WMRK_MASK, MX25_ADCQ_CR_LITEMID(itemct - 1) | MX25_ADCQ_CR_WMRK(priv->expected_samples - 1)); /* setup debounce count */ regmap_update_bits(priv->core_regs, MX25_TSC_TGCR, MX25_TGCR_PDBTIME_MASK, MX25_TGCR_PDBTIME(debounce_cnt)); /* enable debounce */ regmap_update_bits(priv->core_regs, MX25_TSC_TGCR, MX25_TGCR_PDBEN, MX25_TGCR_PDBEN); regmap_update_bits(priv->core_regs, MX25_TSC_TGCR, MX25_TGCR_PDEN, MX25_TGCR_PDEN); /* enable the engine on demand */ regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_QSM_MASK, MX25_ADCQ_CR_QSM_FQS); /* Enable repeat and repeat wait */ regmap_update_bits(priv->regs, MX25_ADCQ_CR, MX25_ADCQ_CR_RPT | MX25_ADCQ_CR_RWAIT_MASK, MX25_ADCQ_CR_RPT | MX25_ADCQ_CR_RWAIT(MX25_TSC_REPEAT_WAIT)); return 0; } static int mx25_tcq_parse_dt(struct platform_device *pdev, struct mx25_tcq_priv *priv) { struct device_node *np = pdev->dev.of_node; u32 wires; int error; /* Setup defaults */ priv->pen_threshold = 500; priv->sample_count = 3; priv->pen_debounce = 1000000; priv->settling_time = 250000; error = of_property_read_u32(np, "fsl,wires", &wires); if (error) { dev_err(&pdev->dev, "Failed to find fsl,wires properties\n"); return error; } if (wires == 4) { priv->mode = MX25_TS_4WIRE; } else { dev_err(&pdev->dev, "%u-wire mode not supported\n", wires); return -EINVAL; } /* These are optional, we don't care about the return values */ of_property_read_u32(np, "fsl,pen-threshold", &priv->pen_threshold); of_property_read_u32(np, "fsl,settling-time-ns", &priv->settling_time); of_property_read_u32(np, "fsl,pen-debounce-ns", &priv->pen_debounce); return 0; } static int mx25_tcq_open(struct input_dev *idev) { struct device *dev = &idev->dev; struct mx25_tcq_priv *priv = dev_get_drvdata(dev); int error; error = clk_prepare_enable(priv->clk); if (error) { dev_err(dev, "Failed to enable ipg clock\n"); return error; } error = mx25_tcq_init(priv); if (error) { dev_err(dev, "Failed to init tcq\n"); clk_disable_unprepare(priv->clk); return error; } mx25_tcq_re_enable_touch_detection(priv); return 0; } static void mx25_tcq_close(struct input_dev *idev) { struct mx25_tcq_priv *priv = input_get_drvdata(idev); mx25_tcq_force_queue_stop(priv); mx25_tcq_disable_touch_irq(priv); mx25_tcq_disable_fifo_irq(priv); clk_disable_unprepare(priv->clk); } static int mx25_tcq_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct input_dev *idev; struct mx25_tcq_priv *priv; struct mx25_tsadc *tsadc = dev_get_drvdata(dev->parent); void __iomem *mem; int error; priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->dev = dev; mem = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(mem)) return PTR_ERR(mem); error = mx25_tcq_parse_dt(pdev, priv); if (error) return error; priv->regs = devm_regmap_init_mmio(dev, mem, &mx25_tcq_regconfig); if (IS_ERR(priv->regs)) { dev_err(dev, "Failed to initialize regmap\n"); return PTR_ERR(priv->regs); } priv->irq = platform_get_irq(pdev, 0); if (priv->irq <= 0) return priv->irq; idev = devm_input_allocate_device(dev); if (!idev) { dev_err(dev, "Failed to allocate input device\n"); return -ENOMEM; } idev->name = mx25_tcq_name; input_set_capability(idev, EV_KEY, BTN_TOUCH); input_set_abs_params(idev, ABS_X, 0, 0xfff, 0, 0); input_set_abs_params(idev, ABS_Y, 0, 0xfff, 0, 0); idev->id.bustype = BUS_HOST; idev->open = mx25_tcq_open; idev->close = mx25_tcq_close; priv->idev = idev; input_set_drvdata(idev, priv); priv->core_regs = tsadc->regs; if (!priv->core_regs) return -EINVAL; priv->clk = tsadc->clk; if (!priv->clk) return -EINVAL; platform_set_drvdata(pdev, priv); error = devm_request_threaded_irq(dev, priv->irq, mx25_tcq_irq, mx25_tcq_irq_thread, 0, pdev->name, priv); if (error) { dev_err(dev, "Failed requesting IRQ\n"); return error; } error = input_register_device(idev); if (error) { dev_err(dev, "Failed to register input device\n"); return error; } return 0; } static struct platform_driver mx25_tcq_driver = { .driver = { .name = "mx25-tcq", .of_match_table = mx25_tcq_ids, }, .probe = mx25_tcq_probe, }; module_platform_driver(mx25_tcq_driver); MODULE_DESCRIPTION("TS input driver for Freescale mx25"); MODULE_AUTHOR("Markus Pargmann <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/fsl-imx25-tcq.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Motorola PCAP2 touchscreen as found in the EZX phone platform. * * Copyright (C) 2006 Harald Welte <[email protected]> * Copyright (C) 2009 Daniel Ribeiro <[email protected]> */ #include <linux/module.h> #include <linux/fs.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/pm.h> #include <linux/timer.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/mfd/ezx-pcap.h> struct pcap_ts { struct pcap_chip *pcap; struct input_dev *input; struct delayed_work work; u16 x, y; u16 pressure; u8 read_state; }; #define SAMPLE_DELAY 20 /* msecs */ #define X_AXIS_MIN 0 #define X_AXIS_MAX 1023 #define Y_AXIS_MAX X_AXIS_MAX #define Y_AXIS_MIN X_AXIS_MIN #define PRESSURE_MAX X_AXIS_MAX #define PRESSURE_MIN X_AXIS_MIN static void pcap_ts_read_xy(void *data, u16 res[2]) { struct pcap_ts *pcap_ts = data; switch (pcap_ts->read_state) { case PCAP_ADC_TS_M_PRESSURE: /* pressure reading is unreliable */ if (res[0] > PRESSURE_MIN && res[0] < PRESSURE_MAX) pcap_ts->pressure = res[0]; pcap_ts->read_state = PCAP_ADC_TS_M_XY; schedule_delayed_work(&pcap_ts->work, 0); break; case PCAP_ADC_TS_M_XY: pcap_ts->y = res[0]; pcap_ts->x = res[1]; if (pcap_ts->x <= X_AXIS_MIN || pcap_ts->x >= X_AXIS_MAX || pcap_ts->y <= Y_AXIS_MIN || pcap_ts->y >= Y_AXIS_MAX) { /* pen has been released */ input_report_abs(pcap_ts->input, ABS_PRESSURE, 0); input_report_key(pcap_ts->input, BTN_TOUCH, 0); pcap_ts->read_state = PCAP_ADC_TS_M_STANDBY; schedule_delayed_work(&pcap_ts->work, 0); } else { /* pen is touching the screen */ input_report_abs(pcap_ts->input, ABS_X, pcap_ts->x); input_report_abs(pcap_ts->input, ABS_Y, pcap_ts->y); input_report_key(pcap_ts->input, BTN_TOUCH, 1); input_report_abs(pcap_ts->input, ABS_PRESSURE, pcap_ts->pressure); /* switch back to pressure read mode */ pcap_ts->read_state = PCAP_ADC_TS_M_PRESSURE; schedule_delayed_work(&pcap_ts->work, msecs_to_jiffies(SAMPLE_DELAY)); } input_sync(pcap_ts->input); break; default: dev_warn(&pcap_ts->input->dev, "pcap_ts: Warning, unhandled read_state %d\n", pcap_ts->read_state); break; } } static void pcap_ts_work(struct work_struct *work) { struct delayed_work *dw = to_delayed_work(work); struct pcap_ts *pcap_ts = container_of(dw, struct pcap_ts, work); u8 ch[2]; pcap_set_ts_bits(pcap_ts->pcap, pcap_ts->read_state << PCAP_ADC_TS_M_SHIFT); if (pcap_ts->read_state == PCAP_ADC_TS_M_STANDBY) return; /* start adc conversion */ ch[0] = PCAP_ADC_CH_TS_X1; ch[1] = PCAP_ADC_CH_TS_Y1; pcap_adc_async(pcap_ts->pcap, PCAP_ADC_BANK_1, 0, ch, pcap_ts_read_xy, pcap_ts); } static irqreturn_t pcap_ts_event_touch(int pirq, void *data) { struct pcap_ts *pcap_ts = data; if (pcap_ts->read_state == PCAP_ADC_TS_M_STANDBY) { pcap_ts->read_state = PCAP_ADC_TS_M_PRESSURE; schedule_delayed_work(&pcap_ts->work, 0); } return IRQ_HANDLED; } static int pcap_ts_open(struct input_dev *dev) { struct pcap_ts *pcap_ts = input_get_drvdata(dev); pcap_ts->read_state = PCAP_ADC_TS_M_STANDBY; schedule_delayed_work(&pcap_ts->work, 0); return 0; } static void pcap_ts_close(struct input_dev *dev) { struct pcap_ts *pcap_ts = input_get_drvdata(dev); cancel_delayed_work_sync(&pcap_ts->work); pcap_ts->read_state = PCAP_ADC_TS_M_NONTS; pcap_set_ts_bits(pcap_ts->pcap, pcap_ts->read_state << PCAP_ADC_TS_M_SHIFT); } static int pcap_ts_probe(struct platform_device *pdev) { struct input_dev *input_dev; struct pcap_ts *pcap_ts; int err = -ENOMEM; pcap_ts = kzalloc(sizeof(*pcap_ts), GFP_KERNEL); if (!pcap_ts) return err; pcap_ts->pcap = dev_get_drvdata(pdev->dev.parent); platform_set_drvdata(pdev, pcap_ts); input_dev = input_allocate_device(); if (!input_dev) goto fail; INIT_DELAYED_WORK(&pcap_ts->work, pcap_ts_work); pcap_ts->read_state = PCAP_ADC_TS_M_NONTS; pcap_set_ts_bits(pcap_ts->pcap, pcap_ts->read_state << PCAP_ADC_TS_M_SHIFT); pcap_ts->input = input_dev; input_set_drvdata(input_dev, pcap_ts); input_dev->name = "pcap-touchscreen"; input_dev->phys = "pcap_ts/input0"; input_dev->id.bustype = BUS_HOST; input_dev->id.vendor = 0x0001; input_dev->id.product = 0x0002; input_dev->id.version = 0x0100; input_dev->dev.parent = &pdev->dev; input_dev->open = pcap_ts_open; input_dev->close = pcap_ts_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, X_AXIS_MIN, X_AXIS_MAX, 0, 0); input_set_abs_params(input_dev, ABS_Y, Y_AXIS_MIN, Y_AXIS_MAX, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, PRESSURE_MIN, PRESSURE_MAX, 0, 0); err = input_register_device(pcap_ts->input); if (err) goto fail_allocate; err = request_irq(pcap_to_irq(pcap_ts->pcap, PCAP_IRQ_TS), pcap_ts_event_touch, 0, "Touch Screen", pcap_ts); if (err) goto fail_register; return 0; fail_register: input_unregister_device(input_dev); goto fail; fail_allocate: input_free_device(input_dev); fail: kfree(pcap_ts); return err; } static int pcap_ts_remove(struct platform_device *pdev) { struct pcap_ts *pcap_ts = platform_get_drvdata(pdev); free_irq(pcap_to_irq(pcap_ts->pcap, PCAP_IRQ_TS), pcap_ts); cancel_delayed_work_sync(&pcap_ts->work); input_unregister_device(pcap_ts->input); kfree(pcap_ts); return 0; } #ifdef CONFIG_PM static int pcap_ts_suspend(struct device *dev) { struct pcap_ts *pcap_ts = dev_get_drvdata(dev); pcap_set_ts_bits(pcap_ts->pcap, PCAP_ADC_TS_REF_LOWPWR); return 0; } static int pcap_ts_resume(struct device *dev) { struct pcap_ts *pcap_ts = dev_get_drvdata(dev); pcap_set_ts_bits(pcap_ts->pcap, pcap_ts->read_state << PCAP_ADC_TS_M_SHIFT); return 0; } static const struct dev_pm_ops pcap_ts_pm_ops = { .suspend = pcap_ts_suspend, .resume = pcap_ts_resume, }; #define PCAP_TS_PM_OPS (&pcap_ts_pm_ops) #else #define PCAP_TS_PM_OPS NULL #endif static struct platform_driver pcap_ts_driver = { .probe = pcap_ts_probe, .remove = pcap_ts_remove, .driver = { .name = "pcap-ts", .pm = PCAP_TS_PM_OPS, }, }; module_platform_driver(pcap_ts_driver); MODULE_DESCRIPTION("Motorola PCAP2 touchscreen driver"); MODULE_AUTHOR("Daniel Ribeiro / Harald Welte"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pcap_ts");
linux-master
drivers/input/touchscreen/pcap_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Source for: * Cypress TrueTouch(TM) Standard Product (TTSP) SPI 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]> * Copyright (C) 2013 Cypress Semiconductor * * Contact Cypress Semiconductor at www.cypress.com <[email protected]> */ #include "cyttsp_core.h" #include <linux/delay.h> #include <linux/input.h> #include <linux/spi/spi.h> #define CY_SPI_NAME "cyttsp-spi" #define CY_SPI_WR_OP 0x00 /* r/~w */ #define CY_SPI_RD_OP 0x01 #define CY_SPI_CMD_BYTES 4 #define CY_SPI_SYNC_BYTE 2 #define CY_SPI_SYNC_ACK1 0x62 /* from protocol v.2 */ #define CY_SPI_SYNC_ACK2 0x9D /* from protocol v.2 */ #define CY_SPI_DATA_SIZE 128 #define CY_SPI_DATA_BUF_SIZE (CY_SPI_CMD_BYTES + CY_SPI_DATA_SIZE) #define CY_SPI_BITS_PER_WORD 8 static int cyttsp_spi_xfer(struct device *dev, u8 *xfer_buf, u8 op, u16 reg, u8 *buf, int length) { struct spi_device *spi = to_spi_device(dev); struct spi_message msg; struct spi_transfer xfer[2]; u8 *wr_buf = &xfer_buf[0]; u8 *rd_buf = &xfer_buf[CY_SPI_DATA_BUF_SIZE]; int retval; int i; if (length > CY_SPI_DATA_SIZE) { dev_err(dev, "%s: length %d is too big.\n", __func__, length); return -EINVAL; } memset(wr_buf, 0, CY_SPI_DATA_BUF_SIZE); memset(rd_buf, 0, CY_SPI_DATA_BUF_SIZE); wr_buf[0] = 0x00; /* header byte 0 */ wr_buf[1] = 0xFF; /* header byte 1 */ wr_buf[2] = reg; /* reg index */ wr_buf[3] = op; /* r/~w */ if (op == CY_SPI_WR_OP) memcpy(wr_buf + CY_SPI_CMD_BYTES, buf, length); memset(xfer, 0, sizeof(xfer)); spi_message_init(&msg); /* We set both TX and RX buffers because Cypress TTSP requires full duplex operation. */ xfer[0].tx_buf = wr_buf; xfer[0].rx_buf = rd_buf; switch (op) { case CY_SPI_WR_OP: xfer[0].len = length + CY_SPI_CMD_BYTES; spi_message_add_tail(&xfer[0], &msg); break; case CY_SPI_RD_OP: xfer[0].len = CY_SPI_CMD_BYTES; spi_message_add_tail(&xfer[0], &msg); xfer[1].rx_buf = buf; xfer[1].len = length; spi_message_add_tail(&xfer[1], &msg); break; default: dev_err(dev, "%s: bad operation code=%d\n", __func__, op); return -EINVAL; } retval = spi_sync(spi, &msg); if (retval < 0) { dev_dbg(dev, "%s: spi_sync() error %d, len=%d, op=%d\n", __func__, retval, xfer[1].len, op); /* * do not return here since was a bad ACK sequence * let the following ACK check handle any errors and * allow silent retries */ } if (rd_buf[CY_SPI_SYNC_BYTE] != CY_SPI_SYNC_ACK1 || rd_buf[CY_SPI_SYNC_BYTE + 1] != CY_SPI_SYNC_ACK2) { dev_dbg(dev, "%s: operation %d failed\n", __func__, op); for (i = 0; i < CY_SPI_CMD_BYTES; i++) dev_dbg(dev, "%s: test rd_buf[%d]:0x%02x\n", __func__, i, rd_buf[i]); for (i = 0; i < length; i++) dev_dbg(dev, "%s: test buf[%d]:0x%02x\n", __func__, i, buf[i]); return -EIO; } return 0; } static int cyttsp_spi_read_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, void *data) { return cyttsp_spi_xfer(dev, xfer_buf, CY_SPI_RD_OP, addr, data, length); } static int cyttsp_spi_write_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, const void *data) { return cyttsp_spi_xfer(dev, xfer_buf, CY_SPI_WR_OP, addr, (void *)data, length); } static const struct cyttsp_bus_ops cyttsp_spi_bus_ops = { .bustype = BUS_SPI, .write = cyttsp_spi_write_block_data, .read = cyttsp_spi_read_block_data, }; static int cyttsp_spi_probe(struct spi_device *spi) { struct cyttsp *ts; int error; /* Set up SPI*/ spi->bits_per_word = CY_SPI_BITS_PER_WORD; spi->mode = SPI_MODE_0; error = spi_setup(spi); if (error < 0) { dev_err(&spi->dev, "%s: SPI setup error %d\n", __func__, error); return error; } ts = cyttsp_probe(&cyttsp_spi_bus_ops, &spi->dev, spi->irq, CY_SPI_DATA_BUF_SIZE * 2); if (IS_ERR(ts)) return PTR_ERR(ts); spi_set_drvdata(spi, ts); return 0; } static const struct of_device_id cyttsp_of_spi_match[] = { { .compatible = "cypress,cy8ctma340", }, { .compatible = "cypress,cy8ctst341", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, cyttsp_of_spi_match); static struct spi_driver cyttsp_spi_driver = { .driver = { .name = CY_SPI_NAME, .pm = pm_sleep_ptr(&cyttsp_pm_ops), .of_match_table = cyttsp_of_spi_match, }, .probe = cyttsp_spi_probe, }; module_spi_driver(cyttsp_spi_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard Product (TTSP) SPI driver"); MODULE_AUTHOR("Cypress"); MODULE_ALIAS("spi:cyttsp");
linux-master
drivers/input/touchscreen/cyttsp_spi.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Allwinner sunxi resistive touchscreen controller driver * * Copyright (C) 2013 - 2014 Hans de Goede <[email protected]> * * The hwmon parts are based on work by Corentin LABBE which is: * Copyright (C) 2013 Corentin LABBE <[email protected]> */ /* * The sun4i-ts controller is capable of detecting a second touch, but when a * second touch is present then the accuracy becomes so bad the reported touch * location is not useable. * * The original android driver contains some complicated heuristics using the * aprox. distance between the 2 touches to see if the user is making a pinch * open / close movement, and then reports emulated multi-touch events around * the last touch coordinate (as the dual-touch coordinates are worthless). * * These kinds of heuristics are just asking for trouble (and don't belong * in the kernel). So this driver offers straight forward, reliable single * touch functionality only. * * s.a. A20 User Manual "1.15 TP" (Documentation/arch/arm/sunxi.rst) * (looks like the description in the A20 User Manual v1.3 is better * than the one in the A10 User Manual v.1.5) */ #include <linux/err.h> #include <linux/hwmon.h> #include <linux/thermal.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/slab.h> #define TP_CTRL0 0x00 #define TP_CTRL1 0x04 #define TP_CTRL2 0x08 #define TP_CTRL3 0x0c #define TP_INT_FIFOC 0x10 #define TP_INT_FIFOS 0x14 #define TP_TPR 0x18 #define TP_CDAT 0x1c #define TEMP_DATA 0x20 #define TP_DATA 0x24 /* TP_CTRL0 bits */ #define ADC_FIRST_DLY(x) ((x) << 24) /* 8 bits */ #define ADC_FIRST_DLY_MODE(x) ((x) << 23) #define ADC_CLK_SEL(x) ((x) << 22) #define ADC_CLK_DIV(x) ((x) << 20) /* 3 bits */ #define FS_DIV(x) ((x) << 16) /* 4 bits */ #define T_ACQ(x) ((x) << 0) /* 16 bits */ /* TP_CTRL1 bits */ #define STYLUS_UP_DEBOUN(x) ((x) << 12) /* 8 bits */ #define STYLUS_UP_DEBOUN_EN(x) ((x) << 9) #define TOUCH_PAN_CALI_EN(x) ((x) << 6) #define TP_DUAL_EN(x) ((x) << 5) #define TP_MODE_EN(x) ((x) << 4) #define TP_ADC_SELECT(x) ((x) << 3) #define ADC_CHAN_SELECT(x) ((x) << 0) /* 3 bits */ /* on sun6i, bits 3~6 are left shifted by 1 to 4~7 */ #define SUN6I_TP_MODE_EN(x) ((x) << 5) /* TP_CTRL2 bits */ #define TP_SENSITIVE_ADJUST(x) ((x) << 28) /* 4 bits */ #define TP_MODE_SELECT(x) ((x) << 26) /* 2 bits */ #define PRE_MEA_EN(x) ((x) << 24) #define PRE_MEA_THRE_CNT(x) ((x) << 0) /* 24 bits */ /* TP_CTRL3 bits */ #define FILTER_EN(x) ((x) << 2) #define FILTER_TYPE(x) ((x) << 0) /* 2 bits */ /* TP_INT_FIFOC irq and fifo mask / control bits */ #define TEMP_IRQ_EN(x) ((x) << 18) #define OVERRUN_IRQ_EN(x) ((x) << 17) #define DATA_IRQ_EN(x) ((x) << 16) #define TP_DATA_XY_CHANGE(x) ((x) << 13) #define FIFO_TRIG(x) ((x) << 8) /* 5 bits */ #define DATA_DRQ_EN(x) ((x) << 7) #define FIFO_FLUSH(x) ((x) << 4) #define TP_UP_IRQ_EN(x) ((x) << 1) #define TP_DOWN_IRQ_EN(x) ((x) << 0) /* TP_INT_FIFOS irq and fifo status bits */ #define TEMP_DATA_PENDING BIT(18) #define FIFO_OVERRUN_PENDING BIT(17) #define FIFO_DATA_PENDING BIT(16) #define TP_IDLE_FLG BIT(2) #define TP_UP_PENDING BIT(1) #define TP_DOWN_PENDING BIT(0) /* TP_TPR bits */ #define TEMP_ENABLE(x) ((x) << 16) #define TEMP_PERIOD(x) ((x) << 0) /* t = x * 256 * 16 / clkin */ struct sun4i_ts_data { struct device *dev; struct input_dev *input; void __iomem *base; unsigned int irq; bool ignore_fifo_data; int temp_data; int temp_offset; int temp_step; }; static void sun4i_ts_irq_handle_input(struct sun4i_ts_data *ts, u32 reg_val) { u32 x, y; if (reg_val & FIFO_DATA_PENDING) { x = readl(ts->base + TP_DATA); y = readl(ts->base + TP_DATA); /* The 1st location reported after an up event is unreliable */ if (!ts->ignore_fifo_data) { input_report_abs(ts->input, ABS_X, x); input_report_abs(ts->input, ABS_Y, y); /* * The hardware has a separate down status bit, but * that gets set before we get the first location, * resulting in reporting a click on the old location. */ input_report_key(ts->input, BTN_TOUCH, 1); input_sync(ts->input); } else { ts->ignore_fifo_data = false; } } if (reg_val & TP_UP_PENDING) { ts->ignore_fifo_data = true; input_report_key(ts->input, BTN_TOUCH, 0); input_sync(ts->input); } } static irqreturn_t sun4i_ts_irq(int irq, void *dev_id) { struct sun4i_ts_data *ts = dev_id; u32 reg_val; reg_val = readl(ts->base + TP_INT_FIFOS); if (reg_val & TEMP_DATA_PENDING) ts->temp_data = readl(ts->base + TEMP_DATA); if (ts->input) sun4i_ts_irq_handle_input(ts, reg_val); writel(reg_val, ts->base + TP_INT_FIFOS); return IRQ_HANDLED; } static int sun4i_ts_open(struct input_dev *dev) { struct sun4i_ts_data *ts = input_get_drvdata(dev); /* Flush, set trig level to 1, enable temp, data and up irqs */ writel(TEMP_IRQ_EN(1) | DATA_IRQ_EN(1) | FIFO_TRIG(1) | FIFO_FLUSH(1) | TP_UP_IRQ_EN(1), ts->base + TP_INT_FIFOC); return 0; } static void sun4i_ts_close(struct input_dev *dev) { struct sun4i_ts_data *ts = input_get_drvdata(dev); /* Deactivate all input IRQs */ writel(TEMP_IRQ_EN(1), ts->base + TP_INT_FIFOC); } static int sun4i_get_temp(const struct sun4i_ts_data *ts, int *temp) { /* No temp_data until the first irq */ if (ts->temp_data == -1) return -EAGAIN; *temp = ts->temp_data * ts->temp_step - ts->temp_offset; return 0; } static int sun4i_get_tz_temp(struct thermal_zone_device *tz, int *temp) { return sun4i_get_temp(thermal_zone_device_priv(tz), temp); } static const struct thermal_zone_device_ops sun4i_ts_tz_ops = { .get_temp = sun4i_get_tz_temp, }; static ssize_t show_temp(struct device *dev, struct device_attribute *devattr, char *buf) { struct sun4i_ts_data *ts = dev_get_drvdata(dev); int temp; int error; error = sun4i_get_temp(ts, &temp); if (error) return error; return sprintf(buf, "%d\n", temp); } static ssize_t show_temp_label(struct device *dev, struct device_attribute *devattr, char *buf) { return sprintf(buf, "SoC temperature\n"); } static DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL); static DEVICE_ATTR(temp1_label, S_IRUGO, show_temp_label, NULL); static struct attribute *sun4i_ts_attrs[] = { &dev_attr_temp1_input.attr, &dev_attr_temp1_label.attr, NULL }; ATTRIBUTE_GROUPS(sun4i_ts); static int sun4i_ts_probe(struct platform_device *pdev) { struct sun4i_ts_data *ts; struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct device *hwmon; struct thermal_zone_device *thermal; int error; u32 reg; bool ts_attached; u32 tp_sensitive_adjust = 15; u32 filter_type = 1; ts = devm_kzalloc(dev, sizeof(struct sun4i_ts_data), GFP_KERNEL); if (!ts) return -ENOMEM; ts->dev = dev; ts->ignore_fifo_data = true; ts->temp_data = -1; if (of_device_is_compatible(np, "allwinner,sun6i-a31-ts")) { /* Allwinner SDK has temperature (C) = (value / 6) - 271 */ ts->temp_offset = 271000; ts->temp_step = 167; } else if (of_device_is_compatible(np, "allwinner,sun4i-a10-ts")) { /* * The A10 temperature sensor has quite a wide spread, these * parameters are based on the averaging of the calibration * results of 4 completely different boards, with a spread of * temp_step from 0.096 - 0.170 and temp_offset from 176 - 331. */ ts->temp_offset = 257000; ts->temp_step = 133; } else { /* * The user manuals do not contain the formula for calculating * the temperature. The formula used here is from the AXP209, * which is designed by X-Powers, an affiliate of Allwinner: * * temperature (C) = (value * 0.1) - 144.7 * * Allwinner does not have any documentation whatsoever for * this hardware. Moreover, it is claimed that the sensor * is inaccurate and cannot work properly. */ ts->temp_offset = 144700; ts->temp_step = 100; } ts_attached = of_property_read_bool(np, "allwinner,ts-attached"); if (ts_attached) { ts->input = devm_input_allocate_device(dev); if (!ts->input) return -ENOMEM; ts->input->name = pdev->name; ts->input->phys = "sun4i_ts/input0"; ts->input->open = sun4i_ts_open; ts->input->close = sun4i_ts_close; ts->input->id.bustype = BUS_HOST; ts->input->id.vendor = 0x0001; ts->input->id.product = 0x0001; ts->input->id.version = 0x0100; ts->input->evbit[0] = BIT(EV_SYN) | BIT(EV_KEY) | BIT(EV_ABS); __set_bit(BTN_TOUCH, ts->input->keybit); input_set_abs_params(ts->input, ABS_X, 0, 4095, 0, 0); input_set_abs_params(ts->input, ABS_Y, 0, 4095, 0, 0); input_set_drvdata(ts->input, ts); } ts->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(ts->base)) return PTR_ERR(ts->base); ts->irq = platform_get_irq(pdev, 0); error = devm_request_irq(dev, ts->irq, sun4i_ts_irq, 0, "sun4i-ts", ts); if (error) return error; /* * Select HOSC clk, clkin = clk / 6, adc samplefreq = clkin / 8192, * t_acq = clkin / (16 * 64) */ writel(ADC_CLK_SEL(0) | ADC_CLK_DIV(2) | FS_DIV(7) | T_ACQ(63), ts->base + TP_CTRL0); /* * tp_sensitive_adjust is an optional property * tp_mode = 0 : only x and y coordinates, as we don't use dual touch */ of_property_read_u32(np, "allwinner,tp-sensitive-adjust", &tp_sensitive_adjust); writel(TP_SENSITIVE_ADJUST(tp_sensitive_adjust) | TP_MODE_SELECT(0), ts->base + TP_CTRL2); /* * Enable median and averaging filter, optional property for * filter type. */ of_property_read_u32(np, "allwinner,filter-type", &filter_type); writel(FILTER_EN(1) | FILTER_TYPE(filter_type), ts->base + TP_CTRL3); /* Enable temperature measurement, period 1953 (2 seconds) */ writel(TEMP_ENABLE(1) | TEMP_PERIOD(1953), ts->base + TP_TPR); /* * Set stylus up debounce to aprox 10 ms, enable debounce, and * finally enable tp mode. */ reg = STYLUS_UP_DEBOUN(5) | STYLUS_UP_DEBOUN_EN(1); if (of_device_is_compatible(np, "allwinner,sun6i-a31-ts")) reg |= SUN6I_TP_MODE_EN(1); else reg |= TP_MODE_EN(1); writel(reg, ts->base + TP_CTRL1); /* * The thermal core does not register hwmon devices for DT-based * thermal zone sensors, such as this one. */ hwmon = devm_hwmon_device_register_with_groups(ts->dev, "sun4i_ts", ts, sun4i_ts_groups); if (IS_ERR(hwmon)) return PTR_ERR(hwmon); thermal = devm_thermal_of_zone_register(ts->dev, 0, ts, &sun4i_ts_tz_ops); if (IS_ERR(thermal)) return PTR_ERR(thermal); writel(TEMP_IRQ_EN(1), ts->base + TP_INT_FIFOC); if (ts_attached) { error = input_register_device(ts->input); if (error) { writel(0, ts->base + TP_INT_FIFOC); return error; } } platform_set_drvdata(pdev, ts); return 0; } static int sun4i_ts_remove(struct platform_device *pdev) { struct sun4i_ts_data *ts = platform_get_drvdata(pdev); /* Explicit unregister to avoid open/close changing the imask later */ if (ts->input) input_unregister_device(ts->input); /* Deactivate all IRQs */ writel(0, ts->base + TP_INT_FIFOC); return 0; } static const struct of_device_id sun4i_ts_of_match[] = { { .compatible = "allwinner,sun4i-a10-ts", }, { .compatible = "allwinner,sun5i-a13-ts", }, { .compatible = "allwinner,sun6i-a31-ts", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, sun4i_ts_of_match); static struct platform_driver sun4i_ts_driver = { .driver = { .name = "sun4i-ts", .of_match_table = sun4i_ts_of_match, }, .probe = sun4i_ts_probe, .remove = sun4i_ts_remove, }; module_platform_driver(sun4i_ts_driver); MODULE_DESCRIPTION("Allwinner sun4i resistive touchscreen controller driver"); MODULE_AUTHOR("Hans de Goede <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/sun4i-ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Semtech SX8654 I2C touchscreen controller. * * Copyright (c) 2015 Armadeus Systems * Sébastien Szymanski <[email protected]> * * Using code from: * - sx865x.c * Copyright (c) 2013 U-MoBo Srl * Pierluigi Passaro <[email protected]> * - sx8650.c * Copyright (c) 2009 Wayne Roberts * - tsc2007.c * Copyright (c) 2008 Kwangwoo Lee * - 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/bitops.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/module.h> #include <linux/of.h> /* register addresses */ #define I2C_REG_TOUCH0 0x00 #define I2C_REG_TOUCH1 0x01 #define I2C_REG_CHANMASK 0x04 #define I2C_REG_IRQMASK 0x22 #define I2C_REG_IRQSRC 0x23 #define I2C_REG_SOFTRESET 0x3f #define I2C_REG_SX8650_STAT 0x05 #define SX8650_STAT_CONVIRQ BIT(7) /* commands */ #define CMD_READ_REGISTER 0x40 #define CMD_PENTRG 0xe0 /* value for I2C_REG_SOFTRESET */ #define SOFTRESET_VALUE 0xde /* bits for I2C_REG_IRQSRC */ #define IRQ_PENTOUCH_TOUCHCONVDONE BIT(3) #define IRQ_PENRELEASE BIT(2) /* bits for RegTouch1 */ #define CONDIRQ 0x20 #define RPDNT_100K 0x00 #define FILT_7SA 0x03 /* bits for I2C_REG_CHANMASK */ #define CONV_X BIT(7) #define CONV_Y BIT(6) /* coordinates rate: higher nibble of CTRL0 register */ #define RATE_MANUAL 0x00 #define RATE_5000CPS 0xf0 /* power delay: lower nibble of CTRL0 register */ #define POWDLY_1_1MS 0x0b /* for sx8650, as we have no pen release IRQ there: timeout in ns following the * last PENIRQ after which we assume the pen is lifted. */ #define SX8650_PENIRQ_TIMEOUT msecs_to_jiffies(10) #define MAX_12BIT ((1 << 12) - 1) #define MAX_I2C_READ_LEN 10 /* see datasheet section 5.1.5 */ /* channel definition */ #define CH_X 0x00 #define CH_Y 0x01 struct sx865x_data { u8 cmd_manual; u8 chan_mask; bool has_irq_penrelease; bool has_reg_irqmask; irq_handler_t irqh; }; struct sx8654 { struct input_dev *input; struct i2c_client *client; struct gpio_desc *gpio_reset; spinlock_t lock; /* for input reporting from irq/timer */ struct timer_list timer; struct touchscreen_properties props; const struct sx865x_data *data; }; static inline void sx865x_penrelease(struct sx8654 *ts) { struct input_dev *input_dev = ts->input; input_report_key(input_dev, BTN_TOUCH, 0); input_sync(input_dev); } static void sx865x_penrelease_timer_handler(struct timer_list *t) { struct sx8654 *ts = from_timer(ts, t, timer); unsigned long flags; spin_lock_irqsave(&ts->lock, flags); sx865x_penrelease(ts); spin_unlock_irqrestore(&ts->lock, flags); dev_dbg(&ts->client->dev, "penrelease by timer\n"); } static irqreturn_t sx8650_irq(int irq, void *handle) { struct sx8654 *ts = handle; struct device *dev = &ts->client->dev; int len, i; unsigned long flags; u8 stat; u16 x, y; u16 ch; u16 chdata; __be16 data[MAX_I2C_READ_LEN / sizeof(__be16)]; u8 nchan = hweight32(ts->data->chan_mask); u8 readlen = nchan * sizeof(*data); stat = i2c_smbus_read_byte_data(ts->client, CMD_READ_REGISTER | I2C_REG_SX8650_STAT); if (!(stat & SX8650_STAT_CONVIRQ)) { dev_dbg(dev, "%s ignore stat [0x%02x]", __func__, stat); return IRQ_HANDLED; } len = i2c_master_recv(ts->client, (u8 *)data, readlen); if (len != readlen) { dev_dbg(dev, "ignore short recv (%d)\n", len); return IRQ_HANDLED; } spin_lock_irqsave(&ts->lock, flags); x = 0; y = 0; for (i = 0; i < nchan; i++) { chdata = be16_to_cpu(data[i]); if (unlikely(chdata == 0xFFFF)) { dev_dbg(dev, "invalid qualified data @ %d\n", i); continue; } else if (unlikely(chdata & 0x8000)) { dev_warn(dev, "hibit @ %d [0x%04x]\n", i, chdata); continue; } ch = chdata >> 12; if (ch == CH_X) x = chdata & MAX_12BIT; else if (ch == CH_Y) y = chdata & MAX_12BIT; else dev_warn(dev, "unknown channel %d [0x%04x]\n", ch, chdata); } touchscreen_report_pos(ts->input, &ts->props, x, y, false); input_report_key(ts->input, BTN_TOUCH, 1); input_sync(ts->input); dev_dbg(dev, "point(%4d,%4d)\n", x, y); mod_timer(&ts->timer, jiffies + SX8650_PENIRQ_TIMEOUT); spin_unlock_irqrestore(&ts->lock, flags); return IRQ_HANDLED; } static irqreturn_t sx8654_irq(int irq, void *handle) { struct sx8654 *sx8654 = handle; int irqsrc; u8 data[4]; unsigned int x, y; int retval; irqsrc = i2c_smbus_read_byte_data(sx8654->client, CMD_READ_REGISTER | I2C_REG_IRQSRC); dev_dbg(&sx8654->client->dev, "irqsrc = 0x%x", irqsrc); if (irqsrc < 0) goto out; if (irqsrc & IRQ_PENRELEASE) { dev_dbg(&sx8654->client->dev, "pen release interrupt"); input_report_key(sx8654->input, BTN_TOUCH, 0); input_sync(sx8654->input); } if (irqsrc & IRQ_PENTOUCH_TOUCHCONVDONE) { dev_dbg(&sx8654->client->dev, "pen touch interrupt"); retval = i2c_master_recv(sx8654->client, data, sizeof(data)); if (retval != sizeof(data)) goto out; /* invalid data */ if (unlikely(data[0] & 0x80 || data[2] & 0x80)) goto out; x = ((data[0] & 0xf) << 8) | (data[1]); y = ((data[2] & 0xf) << 8) | (data[3]); touchscreen_report_pos(sx8654->input, &sx8654->props, x, y, false); input_report_key(sx8654->input, BTN_TOUCH, 1); input_sync(sx8654->input); dev_dbg(&sx8654->client->dev, "point(%4d,%4d)\n", x, y); } out: return IRQ_HANDLED; } static int sx8654_reset(struct sx8654 *ts) { int err; if (ts->gpio_reset) { gpiod_set_value_cansleep(ts->gpio_reset, 1); udelay(2); /* Tpulse > 1µs */ gpiod_set_value_cansleep(ts->gpio_reset, 0); } else { dev_dbg(&ts->client->dev, "NRST unavailable, try softreset\n"); err = i2c_smbus_write_byte_data(ts->client, I2C_REG_SOFTRESET, SOFTRESET_VALUE); if (err) return err; } return 0; } static int sx8654_open(struct input_dev *dev) { struct sx8654 *sx8654 = input_get_drvdata(dev); struct i2c_client *client = sx8654->client; int error; /* enable pen trigger mode */ error = i2c_smbus_write_byte_data(client, I2C_REG_TOUCH0, RATE_5000CPS | POWDLY_1_1MS); if (error) { dev_err(&client->dev, "writing to I2C_REG_TOUCH0 failed"); return error; } error = i2c_smbus_write_byte(client, CMD_PENTRG); if (error) { dev_err(&client->dev, "writing command CMD_PENTRG failed"); return error; } enable_irq(client->irq); return 0; } static void sx8654_close(struct input_dev *dev) { struct sx8654 *sx8654 = input_get_drvdata(dev); struct i2c_client *client = sx8654->client; int error; disable_irq(client->irq); if (!sx8654->data->has_irq_penrelease) del_timer_sync(&sx8654->timer); /* enable manual mode mode */ error = i2c_smbus_write_byte(client, sx8654->data->cmd_manual); if (error) { dev_err(&client->dev, "writing command CMD_MANUAL failed"); return; } error = i2c_smbus_write_byte_data(client, I2C_REG_TOUCH0, RATE_MANUAL); if (error) { dev_err(&client->dev, "writing to I2C_REG_TOUCH0 failed"); return; } } static int sx8654_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct sx8654 *sx8654; struct input_dev *input; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) return -ENXIO; sx8654 = devm_kzalloc(&client->dev, sizeof(*sx8654), GFP_KERNEL); if (!sx8654) return -ENOMEM; sx8654->gpio_reset = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(sx8654->gpio_reset)) return dev_err_probe(&client->dev, PTR_ERR(sx8654->gpio_reset), "unable to get reset-gpio\n"); dev_dbg(&client->dev, "got GPIO reset pin\n"); sx8654->data = device_get_match_data(&client->dev); if (!sx8654->data) sx8654->data = (const struct sx865x_data *)id->driver_data; if (!sx8654->data) { dev_err(&client->dev, "invalid or missing device data\n"); return -EINVAL; } if (!sx8654->data->has_irq_penrelease) { dev_dbg(&client->dev, "use timer for penrelease\n"); timer_setup(&sx8654->timer, sx865x_penrelease_timer_handler, 0); spin_lock_init(&sx8654->lock); } input = devm_input_allocate_device(&client->dev); if (!input) return -ENOMEM; input->name = "SX8654 I2C Touchscreen"; input->id.bustype = BUS_I2C; input->dev.parent = &client->dev; input->open = sx8654_open; input->close = sx8654_close; __set_bit(INPUT_PROP_DIRECT, input->propbit); input_set_capability(input, EV_KEY, BTN_TOUCH); input_set_abs_params(input, ABS_X, 0, MAX_12BIT, 0, 0); input_set_abs_params(input, ABS_Y, 0, MAX_12BIT, 0, 0); touchscreen_parse_properties(input, false, &sx8654->props); sx8654->client = client; sx8654->input = input; input_set_drvdata(sx8654->input, sx8654); error = sx8654_reset(sx8654); if (error) { dev_err(&client->dev, "reset failed"); return error; } error = i2c_smbus_write_byte_data(client, I2C_REG_CHANMASK, sx8654->data->chan_mask); if (error) { dev_err(&client->dev, "writing to I2C_REG_CHANMASK failed"); return error; } if (sx8654->data->has_reg_irqmask) { error = i2c_smbus_write_byte_data(client, I2C_REG_IRQMASK, IRQ_PENTOUCH_TOUCHCONVDONE | IRQ_PENRELEASE); if (error) { dev_err(&client->dev, "writing I2C_REG_IRQMASK failed"); return error; } } error = i2c_smbus_write_byte_data(client, I2C_REG_TOUCH1, CONDIRQ | RPDNT_100K | FILT_7SA); if (error) { dev_err(&client->dev, "writing to I2C_REG_TOUCH1 failed"); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, sx8654->data->irqh, IRQF_ONESHOT, client->name, sx8654); if (error) { dev_err(&client->dev, "Failed to enable IRQ %d, error: %d\n", client->irq, error); return error; } /* Disable the IRQ, we'll enable it in sx8654_open() */ disable_irq(client->irq); error = input_register_device(sx8654->input); if (error) return error; return 0; } static const struct sx865x_data sx8650_data = { .cmd_manual = 0xb0, .has_irq_penrelease = false, .has_reg_irqmask = false, .chan_mask = (CONV_X | CONV_Y), .irqh = sx8650_irq, }; static const struct sx865x_data sx8654_data = { .cmd_manual = 0xc0, .has_irq_penrelease = true, .has_reg_irqmask = true, .chan_mask = (CONV_X | CONV_Y), .irqh = sx8654_irq, }; #ifdef CONFIG_OF static const struct of_device_id sx8654_of_match[] = { { .compatible = "semtech,sx8650", .data = &sx8650_data, }, { .compatible = "semtech,sx8654", .data = &sx8654_data, }, { .compatible = "semtech,sx8655", .data = &sx8654_data, }, { .compatible = "semtech,sx8656", .data = &sx8654_data, }, { } }; MODULE_DEVICE_TABLE(of, sx8654_of_match); #endif static const struct i2c_device_id sx8654_id_table[] = { { .name = "semtech_sx8650", .driver_data = (long)&sx8650_data }, { .name = "semtech_sx8654", .driver_data = (long)&sx8654_data }, { .name = "semtech_sx8655", .driver_data = (long)&sx8654_data }, { .name = "semtech_sx8656", .driver_data = (long)&sx8654_data }, { } }; MODULE_DEVICE_TABLE(i2c, sx8654_id_table); static struct i2c_driver sx8654_driver = { .driver = { .name = "sx8654", .of_match_table = of_match_ptr(sx8654_of_match), }, .id_table = sx8654_id_table, .probe = sx8654_probe, }; module_i2c_driver(sx8654_driver); MODULE_AUTHOR("Sébastien Szymanski <[email protected]>"); MODULE_DESCRIPTION("Semtech SX8654 I2C Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/sx8654.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) ST-Ericsson SA 2010 * Author: Naveen Kumar G <[email protected]> for ST-Ericsson */ #include <linux/bitops.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/kernel.h> #include <linux/module.h> #include <linux/property.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/types.h> #define MAX_FINGERS 2 #define RESET_DELAY 30 #define PENUP_TIMEOUT (10) #define DELTA_MIN 16 #define MASK_BITS 0x03 #define SHIFT_8 8 #define SHIFT_2 2 #define LENGTH_OF_BUFFER 11 #define I2C_RETRY_COUNT 5 #define BU21013_SENSORS_BTN_0_7_REG 0x70 #define BU21013_SENSORS_BTN_8_15_REG 0x71 #define BU21013_SENSORS_BTN_16_23_REG 0x72 #define BU21013_X1_POS_MSB_REG 0x73 #define BU21013_X1_POS_LSB_REG 0x74 #define BU21013_Y1_POS_MSB_REG 0x75 #define BU21013_Y1_POS_LSB_REG 0x76 #define BU21013_X2_POS_MSB_REG 0x77 #define BU21013_X2_POS_LSB_REG 0x78 #define BU21013_Y2_POS_MSB_REG 0x79 #define BU21013_Y2_POS_LSB_REG 0x7A #define BU21013_INT_CLR_REG 0xE8 #define BU21013_INT_MODE_REG 0xE9 #define BU21013_GAIN_REG 0xEA #define BU21013_OFFSET_MODE_REG 0xEB #define BU21013_XY_EDGE_REG 0xEC #define BU21013_RESET_REG 0xED #define BU21013_CALIB_REG 0xEE #define BU21013_DONE_REG 0xEF #define BU21013_SENSOR_0_7_REG 0xF0 #define BU21013_SENSOR_8_15_REG 0xF1 #define BU21013_SENSOR_16_23_REG 0xF2 #define BU21013_POS_MODE1_REG 0xF3 #define BU21013_POS_MODE2_REG 0xF4 #define BU21013_CLK_MODE_REG 0xF5 #define BU21013_IDLE_REG 0xFA #define BU21013_FILTER_REG 0xFB #define BU21013_TH_ON_REG 0xFC #define BU21013_TH_OFF_REG 0xFD #define BU21013_RESET_ENABLE 0x01 #define BU21013_SENSORS_EN_0_7 0x3F #define BU21013_SENSORS_EN_8_15 0xFC #define BU21013_SENSORS_EN_16_23 0x1F #define BU21013_POS_MODE1_0 0x02 #define BU21013_POS_MODE1_1 0x04 #define BU21013_POS_MODE1_2 0x08 #define BU21013_POS_MODE2_ZERO 0x01 #define BU21013_POS_MODE2_AVG1 0x02 #define BU21013_POS_MODE2_AVG2 0x04 #define BU21013_POS_MODE2_EN_XY 0x08 #define BU21013_POS_MODE2_EN_RAW 0x10 #define BU21013_POS_MODE2_MULTI 0x80 #define BU21013_CLK_MODE_DIV 0x01 #define BU21013_CLK_MODE_EXT 0x02 #define BU21013_CLK_MODE_CALIB 0x80 #define BU21013_IDLET_0 0x01 #define BU21013_IDLET_1 0x02 #define BU21013_IDLET_2 0x04 #define BU21013_IDLET_3 0x08 #define BU21013_IDLE_INTERMIT_EN 0x10 #define BU21013_DELTA_0_6 0x7F #define BU21013_FILTER_EN 0x80 #define BU21013_INT_MODE_LEVEL 0x00 #define BU21013_INT_MODE_EDGE 0x01 #define BU21013_GAIN_0 0x01 #define BU21013_GAIN_1 0x02 #define BU21013_GAIN_2 0x04 #define BU21013_OFFSET_MODE_DEFAULT 0x00 #define BU21013_OFFSET_MODE_MOVE 0x01 #define BU21013_OFFSET_MODE_DISABLE 0x02 #define BU21013_TH_ON_0 0x01 #define BU21013_TH_ON_1 0x02 #define BU21013_TH_ON_2 0x04 #define BU21013_TH_ON_3 0x08 #define BU21013_TH_ON_4 0x10 #define BU21013_TH_ON_5 0x20 #define BU21013_TH_ON_6 0x40 #define BU21013_TH_ON_7 0x80 #define BU21013_TH_ON_MAX 0xFF #define BU21013_TH_OFF_0 0x01 #define BU21013_TH_OFF_1 0x02 #define BU21013_TH_OFF_2 0x04 #define BU21013_TH_OFF_3 0x08 #define BU21013_TH_OFF_4 0x10 #define BU21013_TH_OFF_5 0x20 #define BU21013_TH_OFF_6 0x40 #define BU21013_TH_OFF_7 0x80 #define BU21013_TH_OFF_MAX 0xFF #define BU21013_X_EDGE_0 0x01 #define BU21013_X_EDGE_1 0x02 #define BU21013_X_EDGE_2 0x04 #define BU21013_X_EDGE_3 0x08 #define BU21013_Y_EDGE_0 0x10 #define BU21013_Y_EDGE_1 0x20 #define BU21013_Y_EDGE_2 0x40 #define BU21013_Y_EDGE_3 0x80 #define BU21013_DONE 0x01 #define BU21013_NUMBER_OF_X_SENSORS (6) #define BU21013_NUMBER_OF_Y_SENSORS (11) #define DRIVER_TP "bu21013_tp" /** * struct bu21013_ts - touch panel data structure * @client: pointer to the i2c client * @in_dev: pointer to the input device structure * @props: the device coordinate transformation properties * @regulator: pointer to the Regulator used for touch screen * @cs_gpiod: chip select GPIO line * @int_gpiod: touch interrupt GPIO line * @touch_x_max: maximum X coordinate reported by the device * @touch_y_max: maximum Y coordinate reported by the device * @x_flip: indicates that the driver should invert X coordinate before * reporting * @y_flip: indicates that the driver should invert Y coordinate before * reporting * @touch_stopped: touch stop flag * * Touch panel device data structure */ struct bu21013_ts { struct i2c_client *client; struct input_dev *in_dev; struct touchscreen_properties props; struct regulator *regulator; struct gpio_desc *cs_gpiod; struct gpio_desc *int_gpiod; u32 touch_x_max; u32 touch_y_max; bool x_flip; bool y_flip; bool touch_stopped; }; static int bu21013_read_block_data(struct bu21013_ts *ts, u8 *buf) { int ret, i; for (i = 0; i < I2C_RETRY_COUNT; i++) { ret = i2c_smbus_read_i2c_block_data(ts->client, BU21013_SENSORS_BTN_0_7_REG, LENGTH_OF_BUFFER, buf); if (ret == LENGTH_OF_BUFFER) return 0; } return -EINVAL; } static int bu21013_do_touch_report(struct bu21013_ts *ts) { struct input_dev *input = ts->in_dev; struct input_mt_pos pos[MAX_FINGERS]; int slots[MAX_FINGERS]; u8 buf[LENGTH_OF_BUFFER]; bool has_x_sensors, has_y_sensors; int finger_down_count = 0; int i; if (bu21013_read_block_data(ts, buf) < 0) return -EINVAL; has_x_sensors = hweight32(buf[0] & BU21013_SENSORS_EN_0_7); has_y_sensors = hweight32(((buf[1] & BU21013_SENSORS_EN_8_15) | ((buf[2] & BU21013_SENSORS_EN_16_23) << SHIFT_8)) >> SHIFT_2); if (!has_x_sensors || !has_y_sensors) return 0; for (i = 0; i < MAX_FINGERS; i++) { const u8 *data = &buf[4 * i + 3]; unsigned int x, y; x = data[0] << SHIFT_2 | (data[1] & MASK_BITS); y = data[2] << SHIFT_2 | (data[3] & MASK_BITS); if (x != 0 && y != 0) touchscreen_set_mt_pos(&pos[finger_down_count++], &ts->props, x, y); } if (finger_down_count == 2 && (abs(pos[0].x - pos[1].x) < DELTA_MIN || abs(pos[0].y - pos[1].y) < DELTA_MIN)) { return 0; } input_mt_assign_slots(input, slots, pos, finger_down_count, DELTA_MIN); for (i = 0; i < finger_down_count; 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, pos[i].x); input_report_abs(input, ABS_MT_POSITION_Y, pos[i].y); } input_mt_sync_frame(input); input_sync(input); return 0; } static irqreturn_t bu21013_gpio_irq(int irq, void *device_data) { struct bu21013_ts *ts = device_data; int keep_polling; int error; do { error = bu21013_do_touch_report(ts); if (error) { dev_err(&ts->client->dev, "%s failed\n", __func__); break; } if (unlikely(ts->touch_stopped)) break; keep_polling = ts->int_gpiod ? gpiod_get_value(ts->int_gpiod) : false; if (keep_polling) usleep_range(2000, 2500); } while (keep_polling); return IRQ_HANDLED; } static int bu21013_init_chip(struct bu21013_ts *ts) { struct i2c_client *client = ts->client; int error; error = i2c_smbus_write_byte_data(client, BU21013_RESET_REG, BU21013_RESET_ENABLE); if (error) { dev_err(&client->dev, "BU21013_RESET reg write failed\n"); return error; } msleep(RESET_DELAY); error = i2c_smbus_write_byte_data(client, BU21013_SENSOR_0_7_REG, BU21013_SENSORS_EN_0_7); if (error) { dev_err(&client->dev, "BU21013_SENSOR_0_7 reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_SENSOR_8_15_REG, BU21013_SENSORS_EN_8_15); if (error) { dev_err(&client->dev, "BU21013_SENSOR_8_15 reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_SENSOR_16_23_REG, BU21013_SENSORS_EN_16_23); if (error) { dev_err(&client->dev, "BU21013_SENSOR_16_23 reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_POS_MODE1_REG, BU21013_POS_MODE1_0 | BU21013_POS_MODE1_1); if (error) { dev_err(&client->dev, "BU21013_POS_MODE1 reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_POS_MODE2_REG, BU21013_POS_MODE2_ZERO | BU21013_POS_MODE2_AVG1 | BU21013_POS_MODE2_AVG2 | BU21013_POS_MODE2_EN_RAW | BU21013_POS_MODE2_MULTI); if (error) { dev_err(&client->dev, "BU21013_POS_MODE2 reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_CLK_MODE_REG, BU21013_CLK_MODE_DIV | BU21013_CLK_MODE_CALIB); if (error) { dev_err(&client->dev, "BU21013_CLK_MODE reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_IDLE_REG, BU21013_IDLET_0 | BU21013_IDLE_INTERMIT_EN); if (error) { dev_err(&client->dev, "BU21013_IDLE reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_INT_MODE_REG, BU21013_INT_MODE_LEVEL); if (error) { dev_err(&client->dev, "BU21013_INT_MODE reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_FILTER_REG, BU21013_DELTA_0_6 | BU21013_FILTER_EN); if (error) { dev_err(&client->dev, "BU21013_FILTER reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_TH_ON_REG, BU21013_TH_ON_5); if (error) { dev_err(&client->dev, "BU21013_TH_ON reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_TH_OFF_REG, BU21013_TH_OFF_4 | BU21013_TH_OFF_3); if (error) { dev_err(&client->dev, "BU21013_TH_OFF reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_GAIN_REG, BU21013_GAIN_0 | BU21013_GAIN_1); if (error) { dev_err(&client->dev, "BU21013_GAIN reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_OFFSET_MODE_REG, BU21013_OFFSET_MODE_DEFAULT); if (error) { dev_err(&client->dev, "BU21013_OFFSET_MODE reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_XY_EDGE_REG, BU21013_X_EDGE_0 | BU21013_X_EDGE_2 | BU21013_Y_EDGE_1 | BU21013_Y_EDGE_3); if (error) { dev_err(&client->dev, "BU21013_XY_EDGE reg write failed\n"); return error; } error = i2c_smbus_write_byte_data(client, BU21013_DONE_REG, BU21013_DONE); if (error) { dev_err(&client->dev, "BU21013_REG_DONE reg write failed\n"); return error; } return 0; } static void bu21013_power_off(void *_ts) { struct bu21013_ts *ts = _ts; regulator_disable(ts->regulator); } static void bu21013_disable_chip(void *_ts) { struct bu21013_ts *ts = _ts; gpiod_set_value(ts->cs_gpiod, 0); } static int bu21013_probe(struct i2c_client *client) { struct bu21013_ts *ts; struct input_dev *in_dev; struct input_absinfo *info; u32 max_x = 0, max_y = 0; struct device *dev = &client->dev; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(dev, "i2c smbus byte data not supported\n"); return -EIO; } if (!client->irq) { dev_err(dev, "No IRQ set up\n"); return -EINVAL; } ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; ts->x_flip = device_property_read_bool(dev, "rohm,flip-x"); ts->y_flip = device_property_read_bool(dev, "rohm,flip-y"); in_dev = devm_input_allocate_device(dev); if (!in_dev) { dev_err(dev, "device memory alloc failed\n"); return -ENOMEM; } ts->in_dev = in_dev; input_set_drvdata(in_dev, ts); /* register the device to input subsystem */ in_dev->name = DRIVER_TP; in_dev->id.bustype = BUS_I2C; device_property_read_u32(dev, "rohm,touch-max-x", &max_x); device_property_read_u32(dev, "rohm,touch-max-y", &max_y); input_set_abs_params(in_dev, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(in_dev, ABS_MT_POSITION_Y, 0, max_y, 0, 0); touchscreen_parse_properties(in_dev, true, &ts->props); /* Adjust for the legacy "flip" properties, if present */ if (!ts->props.invert_x && device_property_read_bool(dev, "rohm,flip-x")) { info = &in_dev->absinfo[ABS_MT_POSITION_X]; info->maximum -= info->minimum; info->minimum = 0; } if (!ts->props.invert_y && device_property_read_bool(dev, "rohm,flip-y")) { info = &in_dev->absinfo[ABS_MT_POSITION_Y]; info->maximum -= info->minimum; info->minimum = 0; } error = input_mt_init_slots(in_dev, MAX_FINGERS, INPUT_MT_DIRECT | INPUT_MT_TRACK | INPUT_MT_DROP_UNUSED); if (error) { dev_err(dev, "failed to initialize MT slots"); return error; } ts->regulator = devm_regulator_get(dev, "avdd"); if (IS_ERR(ts->regulator)) { dev_err(dev, "regulator_get failed\n"); return PTR_ERR(ts->regulator); } error = regulator_enable(ts->regulator); if (error) { dev_err(dev, "regulator enable failed\n"); return error; } error = devm_add_action_or_reset(dev, bu21013_power_off, ts); if (error) { dev_err(dev, "failed to install power off handler\n"); return error; } /* Named "CS" on the chip, DT binding is "reset" */ ts->cs_gpiod = devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ts->cs_gpiod)) return dev_err_probe(dev, PTR_ERR(ts->cs_gpiod), "failed to get CS GPIO\n"); gpiod_set_consumer_name(ts->cs_gpiod, "BU21013 CS"); error = devm_add_action_or_reset(dev, bu21013_disable_chip, ts); if (error) { dev_err(dev, "failed to install chip disable handler\n"); return error; } /* Named "INT" on the chip, DT binding is "touch" */ ts->int_gpiod = devm_gpiod_get_optional(dev, "touch", GPIOD_IN); error = PTR_ERR_OR_ZERO(ts->int_gpiod); if (error) return dev_err_probe(dev, error, "failed to get INT GPIO\n"); if (ts->int_gpiod) gpiod_set_consumer_name(ts->int_gpiod, "BU21013 INT"); /* configure the touch panel controller */ error = bu21013_init_chip(ts); if (error) { dev_err(dev, "error in bu21013 config\n"); return error; } error = devm_request_threaded_irq(dev, client->irq, NULL, bu21013_gpio_irq, IRQF_ONESHOT, DRIVER_TP, ts); if (error) { dev_err(dev, "request irq %d failed\n", client->irq); return error; } error = input_register_device(in_dev); if (error) { dev_err(dev, "failed to register input device\n"); return error; } i2c_set_clientdata(client, ts); return 0; } static void bu21013_remove(struct i2c_client *client) { struct bu21013_ts *ts = i2c_get_clientdata(client); /* Make sure IRQ will exit quickly even if there is contact */ ts->touch_stopped = true; /* The resources will be freed by devm */ } static int bu21013_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct bu21013_ts *ts = i2c_get_clientdata(client); ts->touch_stopped = true; mb(); disable_irq(client->irq); if (!device_may_wakeup(&client->dev)) regulator_disable(ts->regulator); return 0; } static int bu21013_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct bu21013_ts *ts = i2c_get_clientdata(client); int error; if (!device_may_wakeup(&client->dev)) { error = regulator_enable(ts->regulator); if (error) { dev_err(&client->dev, "failed to re-enable regulator when resuming\n"); return error; } error = bu21013_init_chip(ts); if (error) { dev_err(&client->dev, "failed to reinitialize chip when resuming\n"); return error; } } ts->touch_stopped = false; mb(); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(bu21013_dev_pm_ops, bu21013_suspend, bu21013_resume); static const struct i2c_device_id bu21013_id[] = { { DRIVER_TP, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, bu21013_id); static struct i2c_driver bu21013_driver = { .driver = { .name = DRIVER_TP, .pm = pm_sleep_ptr(&bu21013_dev_pm_ops), }, .probe = bu21013_probe, .remove = bu21013_remove, .id_table = bu21013_id, }; module_i2c_driver(bu21013_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Naveen Kumar G <[email protected]>"); MODULE_DESCRIPTION("bu21013 touch screen controller driver");
linux-master
drivers/input/touchscreen/bu21013_ts.c
// SPDX-License-Identifier: GPL-2.0 /* * Rohm BU21029 touchscreen controller driver * * Copyright (C) 2015-2018 Bosch Sicherheitssysteme GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/module.h> #include <linux/regulator/consumer.h> #include <linux/timer.h> /* * HW_ID1 Register (PAGE=0, ADDR=0x0E, Reset value=0x02, Read only) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | HW_IDH | * +--------+--------+--------+--------+--------+--------+--------+--------+ * HW_ID2 Register (PAGE=0, ADDR=0x0F, Reset value=0x29, Read only) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | HW_IDL | * +--------+--------+--------+--------+--------+--------+--------+--------+ * HW_IDH: high 8bits of IC's ID * HW_IDL: low 8bits of IC's ID */ #define BU21029_HWID_REG (0x0E << 3) #define SUPPORTED_HWID 0x0229 /* * CFR0 Register (PAGE=0, ADDR=0x00, Reset value=0x20) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | 0 | 0 | CALIB | INTRM | 0 | 0 | 0 | 0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * CALIB: 0 = not to use calibration result (*) * 1 = use calibration result * INTRM: 0 = INT output depend on "pen down" (*) * 1 = INT output always "0" */ #define BU21029_CFR0_REG (0x00 << 3) #define CFR0_VALUE 0x00 /* * CFR1 Register (PAGE=0, ADDR=0x01, Reset value=0xA6) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | MAV | AVE[2:0] | 0 | SMPL[2:0] | * +--------+--------+--------+--------+--------+--------+--------+--------+ * MAV: 0 = median average filter off * 1 = median average filter on (*) * AVE: AVE+1 = number of average samples for MAV, * if AVE>SMPL, then AVE=SMPL (=3) * SMPL: SMPL+1 = number of conversion samples for MAV (=7) */ #define BU21029_CFR1_REG (0x01 << 3) #define CFR1_VALUE 0xA6 /* * CFR2 Register (PAGE=0, ADDR=0x02, Reset value=0x04) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | INTVL_TIME[3:0] | TIME_ST_ADC[3:0] | * +--------+--------+--------+--------+--------+--------+--------+--------+ * INTVL_TIME: waiting time between completion of conversion * and start of next conversion, only usable in * autoscan mode (=20.480ms) * TIME_ST_ADC: waiting time between application of voltage * to panel and start of A/D conversion (=100us) */ #define BU21029_CFR2_REG (0x02 << 3) #define CFR2_VALUE 0xC9 /* * CFR3 Register (PAGE=0, ADDR=0x0B, Reset value=0x72) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | RM8 | STRETCH| PU90K | DUAL | PIDAC_OFS[3:0] | * +--------+--------+--------+--------+--------+--------+--------+--------+ * RM8: 0 = coordinate resolution is 12bit (*) * 1 = coordinate resolution is 8bit * STRETCH: 0 = SCL_STRETCH function off * 1 = SCL_STRETCH function on (*) * PU90K: 0 = internal pull-up resistance for touch detection is ~50kohms (*) * 1 = internal pull-up resistance for touch detection is ~90kohms * DUAL: 0 = dual touch detection off (*) * 1 = dual touch detection on * PIDAC_OFS: dual touch detection circuit adjustment, it is not necessary * to change this from initial value */ #define BU21029_CFR3_REG (0x0B << 3) #define CFR3_VALUE 0x42 /* * LDO Register (PAGE=0, ADDR=0x0C, Reset value=0x00) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | 0 | PVDD[2:0] | 0 | AVDD[2:0] | * +--------+--------+--------+--------+--------+--------+--------+--------+ * PVDD: output voltage of panel output regulator (=2.000V) * AVDD: output voltage of analog circuit regulator (=2.000V) */ #define BU21029_LDO_REG (0x0C << 3) #define LDO_VALUE 0x77 /* * Serial Interface Command Byte 1 (CID=1) * +--------+--------+--------+--------+--------+--------+--------+--------+ * | D7 | D6 | D5 | D4 | D3 | D2 | D1 | D0 | * +--------+--------+--------+--------+--------+--------+--------+--------+ * | 1 | CF | CMSK | PDM | STP | * +--------+--------+--------+--------+--------+--------+--------+--------+ * CF: conversion function, see table 3 in datasheet p6 (=0000, automatic scan) * CMSK: 0 = executes convert function (*) * 1 = reads the convert result * PDM: 0 = power down after convert function stops (*) * 1 = keep power on after convert function stops * STP: 1 = abort current conversion and power down, set to "0" automatically */ #define BU21029_AUTOSCAN 0x80 /* * The timeout value needs to be larger than INTVL_TIME + tConv4 (sample and * conversion time), where tConv4 is calculated by formula: * tPON + tDLY1 + (tTIME_ST_ADC + (tADC * tSMPL) * 2 + tDLY2) * 3 * see figure 8 in datasheet p15 for details of each field. */ #define PEN_UP_TIMEOUT_MS 50 #define STOP_DELAY_MIN_US 50 #define STOP_DELAY_MAX_US 1000 #define START_DELAY_MS 2 #define BUF_LEN 8 #define SCALE_12BIT (1 << 12) #define MAX_12BIT ((1 << 12) - 1) #define DRIVER_NAME "bu21029" struct bu21029_ts_data { struct i2c_client *client; struct input_dev *in_dev; struct timer_list timer; struct regulator *vdd; struct gpio_desc *reset_gpios; u32 x_plate_ohms; struct touchscreen_properties prop; }; static void bu21029_touch_report(struct bu21029_ts_data *bu21029, const u8 *buf) { u16 x, y, z1, z2; u32 rz; s32 max_pressure = input_abs_get_max(bu21029->in_dev, ABS_PRESSURE); /* * compose upper 8 and lower 4 bits into a 12bit value: * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * | ByteH | ByteL | * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * |b07|b06|b05|b04|b03|b02|b01|b00|b07|b06|b05|b04|b03|b02|b01|b00| * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * |v11|v10|v09|v08|v07|v06|v05|v04|v03|v02|v01|v00| 0 | 0 | 0 | 0 | * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ */ x = (buf[0] << 4) | (buf[1] >> 4); y = (buf[2] << 4) | (buf[3] >> 4); z1 = (buf[4] << 4) | (buf[5] >> 4); z2 = (buf[6] << 4) | (buf[7] >> 4); if (z1 && z2) { /* * calculate Rz (pressure resistance value) by equation: * Rz = Rx * (x/Q) * ((z2/z1) - 1), where * Rx is x-plate resistance, * Q is the touch screen resolution (8bit = 256, 12bit = 4096) * x, z1, z2 are the measured positions. */ rz = z2 - z1; rz *= x; rz *= bu21029->x_plate_ohms; rz /= z1; rz = DIV_ROUND_CLOSEST(rz, SCALE_12BIT); if (rz <= max_pressure) { touchscreen_report_pos(bu21029->in_dev, &bu21029->prop, x, y, false); input_report_abs(bu21029->in_dev, ABS_PRESSURE, max_pressure - rz); input_report_key(bu21029->in_dev, BTN_TOUCH, 1); input_sync(bu21029->in_dev); } } } static void bu21029_touch_release(struct timer_list *t) { struct bu21029_ts_data *bu21029 = from_timer(bu21029, t, timer); input_report_abs(bu21029->in_dev, ABS_PRESSURE, 0); input_report_key(bu21029->in_dev, BTN_TOUCH, 0); input_sync(bu21029->in_dev); } static irqreturn_t bu21029_touch_soft_irq(int irq, void *data) { struct bu21029_ts_data *bu21029 = data; u8 buf[BUF_LEN]; int error; /* * Read touch data and deassert interrupt (will assert again after * INTVL_TIME + tConv4 for continuous touch) */ error = i2c_smbus_read_i2c_block_data(bu21029->client, BU21029_AUTOSCAN, sizeof(buf), buf); if (error < 0) goto out; bu21029_touch_report(bu21029, buf); /* reset timer for pen up detection */ mod_timer(&bu21029->timer, jiffies + msecs_to_jiffies(PEN_UP_TIMEOUT_MS)); out: return IRQ_HANDLED; } static void bu21029_put_chip_in_reset(struct bu21029_ts_data *bu21029) { if (bu21029->reset_gpios) { gpiod_set_value_cansleep(bu21029->reset_gpios, 1); usleep_range(STOP_DELAY_MIN_US, STOP_DELAY_MAX_US); } } static int bu21029_start_chip(struct input_dev *dev) { struct bu21029_ts_data *bu21029 = input_get_drvdata(dev); struct i2c_client *i2c = bu21029->client; struct { u8 reg; u8 value; } init_table[] = { {BU21029_CFR0_REG, CFR0_VALUE}, {BU21029_CFR1_REG, CFR1_VALUE}, {BU21029_CFR2_REG, CFR2_VALUE}, {BU21029_CFR3_REG, CFR3_VALUE}, {BU21029_LDO_REG, LDO_VALUE} }; int error, i; __be16 hwid; error = regulator_enable(bu21029->vdd); if (error) { dev_err(&i2c->dev, "failed to power up chip: %d", error); return error; } /* take chip out of reset */ if (bu21029->reset_gpios) { gpiod_set_value_cansleep(bu21029->reset_gpios, 0); msleep(START_DELAY_MS); } error = i2c_smbus_read_i2c_block_data(i2c, BU21029_HWID_REG, sizeof(hwid), (u8 *)&hwid); if (error < 0) { dev_err(&i2c->dev, "failed to read HW ID\n"); goto err_out; } if (be16_to_cpu(hwid) != SUPPORTED_HWID) { dev_err(&i2c->dev, "unsupported HW ID 0x%x\n", be16_to_cpu(hwid)); error = -ENODEV; goto err_out; } for (i = 0; i < ARRAY_SIZE(init_table); ++i) { error = i2c_smbus_write_byte_data(i2c, init_table[i].reg, init_table[i].value); if (error < 0) { dev_err(&i2c->dev, "failed to write %#02x to register %#02x: %d\n", init_table[i].value, init_table[i].reg, error); goto err_out; } } error = i2c_smbus_write_byte(i2c, BU21029_AUTOSCAN); if (error < 0) { dev_err(&i2c->dev, "failed to start autoscan\n"); goto err_out; } enable_irq(bu21029->client->irq); return 0; err_out: bu21029_put_chip_in_reset(bu21029); regulator_disable(bu21029->vdd); return error; } static void bu21029_stop_chip(struct input_dev *dev) { struct bu21029_ts_data *bu21029 = input_get_drvdata(dev); disable_irq(bu21029->client->irq); del_timer_sync(&bu21029->timer); bu21029_put_chip_in_reset(bu21029); regulator_disable(bu21029->vdd); } static int bu21029_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct bu21029_ts_data *bu21029; struct input_dev *in_dev; int error; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WRITE_BYTE | I2C_FUNC_SMBUS_WRITE_BYTE_DATA | I2C_FUNC_SMBUS_READ_I2C_BLOCK)) { dev_err(dev, "i2c functionality support is not sufficient\n"); return -EIO; } bu21029 = devm_kzalloc(dev, sizeof(*bu21029), GFP_KERNEL); if (!bu21029) return -ENOMEM; error = device_property_read_u32(dev, "rohm,x-plate-ohms", &bu21029->x_plate_ohms); if (error) { dev_err(dev, "invalid 'x-plate-ohms' supplied: %d\n", error); return error; } bu21029->vdd = devm_regulator_get(dev, "vdd"); if (IS_ERR(bu21029->vdd)) return dev_err_probe(dev, PTR_ERR(bu21029->vdd), "failed to acquire 'vdd' supply\n"); bu21029->reset_gpios = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(bu21029->reset_gpios)) return dev_err_probe(dev, PTR_ERR(bu21029->reset_gpios), "failed to acquire 'reset' gpio\n"); in_dev = devm_input_allocate_device(dev); if (!in_dev) { dev_err(dev, "unable to allocate input device\n"); return -ENOMEM; } bu21029->client = client; bu21029->in_dev = in_dev; timer_setup(&bu21029->timer, bu21029_touch_release, 0); in_dev->name = DRIVER_NAME; in_dev->id.bustype = BUS_I2C; in_dev->open = bu21029_start_chip; in_dev->close = bu21029_stop_chip; input_set_capability(in_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(in_dev, ABS_X, 0, MAX_12BIT, 0, 0); input_set_abs_params(in_dev, ABS_Y, 0, MAX_12BIT, 0, 0); input_set_abs_params(in_dev, ABS_PRESSURE, 0, MAX_12BIT, 0, 0); touchscreen_parse_properties(in_dev, false, &bu21029->prop); input_set_drvdata(in_dev, bu21029); error = devm_request_threaded_irq(dev, client->irq, NULL, bu21029_touch_soft_irq, IRQF_ONESHOT | IRQF_NO_AUTOEN, DRIVER_NAME, bu21029); if (error) { dev_err(dev, "unable to request touch irq: %d\n", error); return error; } error = input_register_device(in_dev); if (error) { dev_err(dev, "unable to register input device: %d\n", error); return error; } i2c_set_clientdata(client, bu21029); return 0; } static int bu21029_suspend(struct device *dev) { struct i2c_client *i2c = to_i2c_client(dev); struct bu21029_ts_data *bu21029 = i2c_get_clientdata(i2c); if (!device_may_wakeup(dev)) { mutex_lock(&bu21029->in_dev->mutex); if (input_device_enabled(bu21029->in_dev)) bu21029_stop_chip(bu21029->in_dev); mutex_unlock(&bu21029->in_dev->mutex); } return 0; } static int bu21029_resume(struct device *dev) { struct i2c_client *i2c = to_i2c_client(dev); struct bu21029_ts_data *bu21029 = i2c_get_clientdata(i2c); if (!device_may_wakeup(dev)) { mutex_lock(&bu21029->in_dev->mutex); if (input_device_enabled(bu21029->in_dev)) bu21029_start_chip(bu21029->in_dev); mutex_unlock(&bu21029->in_dev->mutex); } return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(bu21029_pm_ops, bu21029_suspend, bu21029_resume); static const struct i2c_device_id bu21029_ids[] = { { DRIVER_NAME, 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, bu21029_ids); #ifdef CONFIG_OF static const struct of_device_id bu21029_of_ids[] = { { .compatible = "rohm,bu21029" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, bu21029_of_ids); #endif static struct i2c_driver bu21029_driver = { .driver = { .name = DRIVER_NAME, .of_match_table = of_match_ptr(bu21029_of_ids), .pm = pm_sleep_ptr(&bu21029_pm_ops), }, .id_table = bu21029_ids, .probe = bu21029_probe, }; module_i2c_driver(bu21029_driver); MODULE_AUTHOR("Zhu Yi <[email protected]>"); MODULE_DESCRIPTION("Rohm BU21029 touchscreen controller driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/bu21029_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Touchscreen driver for Dialog Semiconductor DA9034 * * Copyright (C) 2006-2008 Marvell International Ltd. * Fengwei Yin <[email protected]> * Bin Yang <[email protected]> * Eric Miao <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/workqueue.h> #include <linux/mfd/da903x.h> #include <linux/slab.h> #define DA9034_MANUAL_CTRL 0x50 #define DA9034_LDO_ADC_EN (1 << 4) #define DA9034_AUTO_CTRL1 0x51 #define DA9034_AUTO_CTRL2 0x52 #define DA9034_AUTO_TSI_EN (1 << 3) #define DA9034_PEN_DETECT (1 << 4) #define DA9034_TSI_CTRL1 0x53 #define DA9034_TSI_CTRL2 0x54 #define DA9034_TSI_X_MSB 0x6c #define DA9034_TSI_Y_MSB 0x6d #define DA9034_TSI_XY_LSB 0x6e enum { STATE_IDLE, /* wait for pendown */ STATE_BUSY, /* TSI busy sampling */ STATE_STOP, /* sample available */ STATE_WAIT, /* Wait to start next sample */ }; enum { EVENT_PEN_DOWN, EVENT_PEN_UP, EVENT_TSI_READY, EVENT_TIMEDOUT, }; struct da9034_touch { struct device *da9034_dev; struct input_dev *input_dev; struct delayed_work tsi_work; struct notifier_block notifier; int state; int interval_ms; int x_inverted; int y_inverted; int last_x; int last_y; }; static inline int is_pen_down(struct da9034_touch *touch) { return da903x_query_status(touch->da9034_dev, DA9034_STATUS_PEN_DOWN); } static inline int detect_pen_down(struct da9034_touch *touch, int on) { if (on) return da903x_set_bits(touch->da9034_dev, DA9034_AUTO_CTRL2, DA9034_PEN_DETECT); else return da903x_clr_bits(touch->da9034_dev, DA9034_AUTO_CTRL2, DA9034_PEN_DETECT); } static int read_tsi(struct da9034_touch *touch) { uint8_t _x, _y, _v; int ret; ret = da903x_read(touch->da9034_dev, DA9034_TSI_X_MSB, &_x); if (ret) return ret; ret = da903x_read(touch->da9034_dev, DA9034_TSI_Y_MSB, &_y); if (ret) return ret; ret = da903x_read(touch->da9034_dev, DA9034_TSI_XY_LSB, &_v); if (ret) return ret; touch->last_x = ((_x << 2) & 0x3fc) | (_v & 0x3); touch->last_y = ((_y << 2) & 0x3fc) | ((_v & 0xc) >> 2); return 0; } static inline int start_tsi(struct da9034_touch *touch) { return da903x_set_bits(touch->da9034_dev, DA9034_AUTO_CTRL2, DA9034_AUTO_TSI_EN); } static inline int stop_tsi(struct da9034_touch *touch) { return da903x_clr_bits(touch->da9034_dev, DA9034_AUTO_CTRL2, DA9034_AUTO_TSI_EN); } static inline void report_pen_down(struct da9034_touch *touch) { int x = touch->last_x; int y = touch->last_y; x &= 0xfff; if (touch->x_inverted) x = 1024 - x; y &= 0xfff; if (touch->y_inverted) y = 1024 - y; input_report_abs(touch->input_dev, ABS_X, x); input_report_abs(touch->input_dev, ABS_Y, y); input_report_key(touch->input_dev, BTN_TOUCH, 1); input_sync(touch->input_dev); } static inline void report_pen_up(struct da9034_touch *touch) { input_report_key(touch->input_dev, BTN_TOUCH, 0); input_sync(touch->input_dev); } static void da9034_event_handler(struct da9034_touch *touch, int event) { int err; switch (touch->state) { case STATE_IDLE: if (event != EVENT_PEN_DOWN) break; /* Enable auto measurement of the TSI, this will * automatically disable pen down detection */ err = start_tsi(touch); if (err) goto err_reset; touch->state = STATE_BUSY; break; case STATE_BUSY: if (event != EVENT_TSI_READY) break; err = read_tsi(touch); if (err) goto err_reset; /* Disable auto measurement of the TSI, so that * pen down status will be available */ err = stop_tsi(touch); if (err) goto err_reset; touch->state = STATE_STOP; /* FIXME: PEN_{UP/DOWN} events are expected to be * available by stopping TSI, but this is found not * always true, delay and simulate such an event * here is more reliable */ mdelay(1); da9034_event_handler(touch, is_pen_down(touch) ? EVENT_PEN_DOWN : EVENT_PEN_UP); break; case STATE_STOP: if (event == EVENT_PEN_DOWN) { report_pen_down(touch); schedule_delayed_work(&touch->tsi_work, msecs_to_jiffies(touch->interval_ms)); touch->state = STATE_WAIT; } if (event == EVENT_PEN_UP) { report_pen_up(touch); touch->state = STATE_IDLE; } break; case STATE_WAIT: if (event != EVENT_TIMEDOUT) break; if (is_pen_down(touch)) { start_tsi(touch); touch->state = STATE_BUSY; } else { report_pen_up(touch); touch->state = STATE_IDLE; } break; } return; err_reset: touch->state = STATE_IDLE; stop_tsi(touch); detect_pen_down(touch, 1); } static void da9034_tsi_work(struct work_struct *work) { struct da9034_touch *touch = container_of(work, struct da9034_touch, tsi_work.work); da9034_event_handler(touch, EVENT_TIMEDOUT); } static int da9034_touch_notifier(struct notifier_block *nb, unsigned long event, void *data) { struct da9034_touch *touch = container_of(nb, struct da9034_touch, notifier); if (event & DA9034_EVENT_TSI_READY) da9034_event_handler(touch, EVENT_TSI_READY); if ((event & DA9034_EVENT_PEN_DOWN) && touch->state == STATE_IDLE) da9034_event_handler(touch, EVENT_PEN_DOWN); return 0; } static int da9034_touch_open(struct input_dev *dev) { struct da9034_touch *touch = input_get_drvdata(dev); int ret; ret = da903x_register_notifier(touch->da9034_dev, &touch->notifier, DA9034_EVENT_PEN_DOWN | DA9034_EVENT_TSI_READY); if (ret) return -EBUSY; /* Enable ADC LDO */ ret = da903x_set_bits(touch->da9034_dev, DA9034_MANUAL_CTRL, DA9034_LDO_ADC_EN); if (ret) return ret; /* TSI_DELAY: 3 slots, TSI_SKIP: 3 slots */ ret = da903x_write(touch->da9034_dev, DA9034_TSI_CTRL1, 0x1b); if (ret) return ret; ret = da903x_write(touch->da9034_dev, DA9034_TSI_CTRL2, 0x00); if (ret) return ret; touch->state = STATE_IDLE; detect_pen_down(touch, 1); return 0; } static void da9034_touch_close(struct input_dev *dev) { struct da9034_touch *touch = input_get_drvdata(dev); da903x_unregister_notifier(touch->da9034_dev, &touch->notifier, DA9034_EVENT_PEN_DOWN | DA9034_EVENT_TSI_READY); cancel_delayed_work_sync(&touch->tsi_work); touch->state = STATE_IDLE; stop_tsi(touch); detect_pen_down(touch, 0); /* Disable ADC LDO */ da903x_clr_bits(touch->da9034_dev, DA9034_MANUAL_CTRL, DA9034_LDO_ADC_EN); } static int da9034_touch_probe(struct platform_device *pdev) { struct da9034_touch_pdata *pdata = dev_get_platdata(&pdev->dev); struct da9034_touch *touch; struct input_dev *input_dev; int error; touch = devm_kzalloc(&pdev->dev, sizeof(struct da9034_touch), GFP_KERNEL); if (!touch) { dev_err(&pdev->dev, "failed to allocate driver data\n"); return -ENOMEM; } touch->da9034_dev = pdev->dev.parent; if (pdata) { touch->interval_ms = pdata->interval_ms; touch->x_inverted = pdata->x_inverted; touch->y_inverted = pdata->y_inverted; } else { /* fallback into default */ touch->interval_ms = 10; } INIT_DELAYED_WORK(&touch->tsi_work, da9034_tsi_work); touch->notifier.notifier_call = da9034_touch_notifier; input_dev = devm_input_allocate_device(&pdev->dev); if (!input_dev) { dev_err(&pdev->dev, "failed to allocate input device\n"); return -ENOMEM; } input_dev->name = pdev->name; input_dev->open = da9034_touch_open; input_dev->close = da9034_touch_close; input_dev->dev.parent = &pdev->dev; __set_bit(EV_ABS, input_dev->evbit); __set_bit(ABS_X, input_dev->absbit); __set_bit(ABS_Y, input_dev->absbit); input_set_abs_params(input_dev, ABS_X, 0, 1023, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, 1023, 0, 0); __set_bit(EV_KEY, input_dev->evbit); __set_bit(BTN_TOUCH, input_dev->keybit); touch->input_dev = input_dev; input_set_drvdata(input_dev, touch); error = input_register_device(input_dev); if (error) return error; return 0; } static struct platform_driver da9034_touch_driver = { .driver = { .name = "da9034-touch", }, .probe = da9034_touch_probe, }; module_platform_driver(da9034_touch_driver); MODULE_DESCRIPTION("Touchscreen driver for Dialog Semiconductor DA9034"); MODULE_AUTHOR("Eric Miao <[email protected]>, Bin Yang <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:da9034-touch");
linux-master
drivers/input/touchscreen/da9034-ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * cyttsp_i2c.c * Cypress TrueTouch(TM) Standard Product (TTSP) I2C touchscreen driver. * For use with Cypress Txx4xx parts. * Supported parts include: * TMA4XX * TMA1036 * * Copyright (C) 2009, 2010, 2011 Cypress Semiconductor, Inc. * Copyright (C) 2012 Javier Martinez Canillas <[email protected]> * Copyright (C) 2013 Cypress Semiconductor * * Contact Cypress Semiconductor at www.cypress.com <[email protected]> */ #include "cyttsp4_core.h" #include <linux/i2c.h> #include <linux/input.h> #define CYTTSP4_I2C_DATA_SIZE (3 * 256) static const struct cyttsp4_bus_ops cyttsp4_i2c_bus_ops = { .bustype = BUS_I2C, .write = cyttsp_i2c_write_block_data, .read = cyttsp_i2c_read_block_data, }; static int cyttsp4_i2c_probe(struct i2c_client *client) { struct cyttsp4 *ts; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C functionality not Supported\n"); return -EIO; } ts = cyttsp4_probe(&cyttsp4_i2c_bus_ops, &client->dev, client->irq, CYTTSP4_I2C_DATA_SIZE); return PTR_ERR_OR_ZERO(ts); } static void cyttsp4_i2c_remove(struct i2c_client *client) { struct cyttsp4 *ts = i2c_get_clientdata(client); cyttsp4_remove(ts); } static const struct i2c_device_id cyttsp4_i2c_id[] = { { CYTTSP4_I2C_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, cyttsp4_i2c_id); static struct i2c_driver cyttsp4_i2c_driver = { .driver = { .name = CYTTSP4_I2C_NAME, .pm = pm_ptr(&cyttsp4_pm_ops), }, .probe = cyttsp4_i2c_probe, .remove = cyttsp4_i2c_remove, .id_table = cyttsp4_i2c_id, }; module_i2c_driver(cyttsp4_i2c_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard Product (TTSP) I2C driver"); MODULE_AUTHOR("Cypress");
linux-master
drivers/input/touchscreen/cyttsp4_i2c.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2021 * Author(s): Giulio Benetti <[email protected]> */ #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/regulator/consumer.h> #include <linux/regmap.h> #include <asm/unaligned.h> #define HY46XX_CHKSUM_CODE 0x1 #define HY46XX_FINGER_NUM 0x2 #define HY46XX_CHKSUM_LEN 0x7 #define HY46XX_THRESHOLD 0x80 #define HY46XX_GLOVE_EN 0x84 #define HY46XX_REPORT_SPEED 0x88 #define HY46XX_PWR_NOISE_EN 0x89 #define HY46XX_FILTER_DATA 0x8A #define HY46XX_GAIN 0x92 #define HY46XX_EDGE_OFFSET 0x93 #define HY46XX_RX_NR_USED 0x94 #define HY46XX_TX_NR_USED 0x95 #define HY46XX_PWR_MODE 0xA5 #define HY46XX_FW_VERSION 0xA6 #define HY46XX_LIB_VERSION 0xA7 #define HY46XX_TP_INFO 0xA8 #define HY46XX_TP_CHIP_ID 0xA9 #define HY46XX_BOOT_VER 0xB0 #define HY46XX_TPLEN 0x6 #define HY46XX_REPORT_PKT_LEN 0x44 #define HY46XX_MAX_SUPPORTED_POINTS 11 #define TOUCH_EVENT_DOWN 0x00 #define TOUCH_EVENT_UP 0x01 #define TOUCH_EVENT_CONTACT 0x02 #define TOUCH_EVENT_RESERVED 0x03 struct hycon_hy46xx_data { struct i2c_client *client; struct input_dev *input; struct touchscreen_properties prop; struct regulator *vcc; struct gpio_desc *reset_gpio; struct mutex mutex; struct regmap *regmap; int threshold; bool glove_enable; int report_speed; bool noise_filter_enable; int filter_data; int gain; int edge_offset; int rx_number_used; int tx_number_used; int power_mode; int fw_version; int lib_version; int tp_information; int tp_chip_id; int bootloader_version; }; static const struct regmap_config hycon_hy46xx_i2c_regmap_config = { .reg_bits = 8, .val_bits = 8, }; static bool hycon_hy46xx_check_checksum(struct hycon_hy46xx_data *tsdata, u8 *buf) { u8 chksum = 0; int i; for (i = 2; i < buf[HY46XX_CHKSUM_LEN]; i++) chksum += buf[i]; if (chksum == buf[HY46XX_CHKSUM_CODE]) return true; dev_err_ratelimited(&tsdata->client->dev, "checksum error: 0x%02x expected, got 0x%02x\n", chksum, buf[HY46XX_CHKSUM_CODE]); return false; } static irqreturn_t hycon_hy46xx_isr(int irq, void *dev_id) { struct hycon_hy46xx_data *tsdata = dev_id; struct device *dev = &tsdata->client->dev; u8 rdbuf[HY46XX_REPORT_PKT_LEN]; int i, x, y, id; int error; memset(rdbuf, 0, sizeof(rdbuf)); error = regmap_bulk_read(tsdata->regmap, 0, rdbuf, sizeof(rdbuf)); if (error) { dev_err_ratelimited(dev, "Unable to fetch data, error: %d\n", error); goto out; } if (!hycon_hy46xx_check_checksum(tsdata, rdbuf)) goto out; for (i = 0; i < HY46XX_MAX_SUPPORTED_POINTS; i++) { u8 *buf = &rdbuf[3 + (HY46XX_TPLEN * i)]; int type = buf[0] >> 6; if (type == TOUCH_EVENT_RESERVED) continue; x = get_unaligned_be16(buf) & 0x0fff; y = get_unaligned_be16(buf + 2) & 0x0fff; id = buf[2] >> 4; 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, false); input_sync(tsdata->input); out: return IRQ_HANDLED; } struct hycon_hy46xx_attribute { struct device_attribute dattr; size_t field_offset; u8 address; u8 limit_low; u8 limit_high; }; #define HYCON_ATTR_U8(_field, _mode, _address, _limit_low, _limit_high) \ struct hycon_hy46xx_attribute hycon_hy46xx_attr_##_field = { \ .dattr = __ATTR(_field, _mode, \ hycon_hy46xx_setting_show, \ hycon_hy46xx_setting_store), \ .field_offset = offsetof(struct hycon_hy46xx_data, _field), \ .address = _address, \ .limit_low = _limit_low, \ .limit_high = _limit_high, \ } #define HYCON_ATTR_BOOL(_field, _mode, _address) \ struct hycon_hy46xx_attribute hycon_hy46xx_attr_##_field = { \ .dattr = __ATTR(_field, _mode, \ hycon_hy46xx_setting_show, \ hycon_hy46xx_setting_store), \ .field_offset = offsetof(struct hycon_hy46xx_data, _field), \ .address = _address, \ .limit_low = false, \ .limit_high = true, \ } static ssize_t hycon_hy46xx_setting_show(struct device *dev, struct device_attribute *dattr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct hycon_hy46xx_data *tsdata = i2c_get_clientdata(client); struct hycon_hy46xx_attribute *attr = container_of(dattr, struct hycon_hy46xx_attribute, dattr); u8 *field = (u8 *)tsdata + attr->field_offset; size_t count = 0; int error = 0; int val; mutex_lock(&tsdata->mutex); error = regmap_read(tsdata->regmap, attr->address, &val); if (error < 0) { dev_err(&tsdata->client->dev, "Failed to fetch attribute %s, error %d\n", dattr->attr.name, error); goto out; } 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 hycon_hy46xx_setting_store(struct device *dev, struct device_attribute *dattr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct hycon_hy46xx_data *tsdata = i2c_get_clientdata(client); struct hycon_hy46xx_attribute *attr = container_of(dattr, struct hycon_hy46xx_attribute, dattr); u8 *field = (u8 *)tsdata + attr->field_offset; unsigned int val; int error; mutex_lock(&tsdata->mutex); error = kstrtouint(buf, 0, &val); if (error) goto out; if (val < attr->limit_low || val > attr->limit_high) { error = -ERANGE; goto out; } error = regmap_write(tsdata->regmap, attr->address, val); if (error < 0) { 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; } static HYCON_ATTR_U8(threshold, 0644, HY46XX_THRESHOLD, 0, 255); static HYCON_ATTR_BOOL(glove_enable, 0644, HY46XX_GLOVE_EN); static HYCON_ATTR_U8(report_speed, 0644, HY46XX_REPORT_SPEED, 0, 255); static HYCON_ATTR_BOOL(noise_filter_enable, 0644, HY46XX_PWR_NOISE_EN); static HYCON_ATTR_U8(filter_data, 0644, HY46XX_FILTER_DATA, 0, 5); static HYCON_ATTR_U8(gain, 0644, HY46XX_GAIN, 0, 5); static HYCON_ATTR_U8(edge_offset, 0644, HY46XX_EDGE_OFFSET, 0, 5); static HYCON_ATTR_U8(fw_version, 0444, HY46XX_FW_VERSION, 0, 255); static HYCON_ATTR_U8(lib_version, 0444, HY46XX_LIB_VERSION, 0, 255); static HYCON_ATTR_U8(tp_information, 0444, HY46XX_TP_INFO, 0, 255); static HYCON_ATTR_U8(tp_chip_id, 0444, HY46XX_TP_CHIP_ID, 0, 255); static HYCON_ATTR_U8(bootloader_version, 0444, HY46XX_BOOT_VER, 0, 255); static struct attribute *hycon_hy46xx_attrs[] = { &hycon_hy46xx_attr_threshold.dattr.attr, &hycon_hy46xx_attr_glove_enable.dattr.attr, &hycon_hy46xx_attr_report_speed.dattr.attr, &hycon_hy46xx_attr_noise_filter_enable.dattr.attr, &hycon_hy46xx_attr_filter_data.dattr.attr, &hycon_hy46xx_attr_gain.dattr.attr, &hycon_hy46xx_attr_edge_offset.dattr.attr, &hycon_hy46xx_attr_fw_version.dattr.attr, &hycon_hy46xx_attr_lib_version.dattr.attr, &hycon_hy46xx_attr_tp_information.dattr.attr, &hycon_hy46xx_attr_tp_chip_id.dattr.attr, &hycon_hy46xx_attr_bootloader_version.dattr.attr, NULL }; static const struct attribute_group hycon_hy46xx_attr_group = { .attrs = hycon_hy46xx_attrs, }; static void hycon_hy46xx_get_defaults(struct device *dev, struct hycon_hy46xx_data *tsdata) { bool val_bool; int error; u32 val; error = device_property_read_u32(dev, "hycon,threshold", &val); if (!error) { error = regmap_write(tsdata->regmap, HY46XX_THRESHOLD, val); if (error < 0) goto out; tsdata->threshold = val; } val_bool = device_property_read_bool(dev, "hycon,glove-enable"); error = regmap_write(tsdata->regmap, HY46XX_GLOVE_EN, val_bool); if (error < 0) goto out; tsdata->glove_enable = val_bool; error = device_property_read_u32(dev, "hycon,report-speed-hz", &val); if (!error) { error = regmap_write(tsdata->regmap, HY46XX_REPORT_SPEED, val); if (error < 0) goto out; tsdata->report_speed = val; } val_bool = device_property_read_bool(dev, "hycon,noise-filter-enable"); error = regmap_write(tsdata->regmap, HY46XX_PWR_NOISE_EN, val_bool); if (error < 0) goto out; tsdata->noise_filter_enable = val_bool; error = device_property_read_u32(dev, "hycon,filter-data", &val); if (!error) { error = regmap_write(tsdata->regmap, HY46XX_FILTER_DATA, val); if (error < 0) goto out; tsdata->filter_data = val; } error = device_property_read_u32(dev, "hycon,gain", &val); if (!error) { error = regmap_write(tsdata->regmap, HY46XX_GAIN, val); if (error < 0) goto out; tsdata->gain = val; } error = device_property_read_u32(dev, "hycon,edge-offset", &val); if (!error) { error = regmap_write(tsdata->regmap, HY46XX_EDGE_OFFSET, val); if (error < 0) goto out; tsdata->edge_offset = val; } return; out: dev_err(&tsdata->client->dev, "Failed to set default settings"); } static void hycon_hy46xx_get_parameters(struct hycon_hy46xx_data *tsdata) { int error; u32 val; error = regmap_read(tsdata->regmap, HY46XX_THRESHOLD, &val); if (error < 0) goto out; tsdata->threshold = val; error = regmap_read(tsdata->regmap, HY46XX_GLOVE_EN, &val); if (error < 0) goto out; tsdata->glove_enable = val; error = regmap_read(tsdata->regmap, HY46XX_REPORT_SPEED, &val); if (error < 0) goto out; tsdata->report_speed = val; error = regmap_read(tsdata->regmap, HY46XX_PWR_NOISE_EN, &val); if (error < 0) goto out; tsdata->noise_filter_enable = val; error = regmap_read(tsdata->regmap, HY46XX_FILTER_DATA, &val); if (error < 0) goto out; tsdata->filter_data = val; error = regmap_read(tsdata->regmap, HY46XX_GAIN, &val); if (error < 0) goto out; tsdata->gain = val; error = regmap_read(tsdata->regmap, HY46XX_EDGE_OFFSET, &val); if (error < 0) goto out; tsdata->edge_offset = val; error = regmap_read(tsdata->regmap, HY46XX_RX_NR_USED, &val); if (error < 0) goto out; tsdata->rx_number_used = val; error = regmap_read(tsdata->regmap, HY46XX_TX_NR_USED, &val); if (error < 0) goto out; tsdata->tx_number_used = val; error = regmap_read(tsdata->regmap, HY46XX_PWR_MODE, &val); if (error < 0) goto out; tsdata->power_mode = val; error = regmap_read(tsdata->regmap, HY46XX_FW_VERSION, &val); if (error < 0) goto out; tsdata->fw_version = val; error = regmap_read(tsdata->regmap, HY46XX_LIB_VERSION, &val); if (error < 0) goto out; tsdata->lib_version = val; error = regmap_read(tsdata->regmap, HY46XX_TP_INFO, &val); if (error < 0) goto out; tsdata->tp_information = val; error = regmap_read(tsdata->regmap, HY46XX_TP_CHIP_ID, &val); if (error < 0) goto out; tsdata->tp_chip_id = val; error = regmap_read(tsdata->regmap, HY46XX_BOOT_VER, &val); if (error < 0) goto out; tsdata->bootloader_version = val; return; out: dev_err(&tsdata->client->dev, "Failed to read default settings"); } static void hycon_hy46xx_disable_regulator(void *arg) { struct hycon_hy46xx_data *data = arg; regulator_disable(data->vcc); } static int hycon_hy46xx_probe(struct i2c_client *client) { struct hycon_hy46xx_data *tsdata; struct input_dev *input; int error; dev_dbg(&client->dev, "probing for HYCON HY46XX I2C\n"); tsdata = devm_kzalloc(&client->dev, sizeof(*tsdata), GFP_KERNEL); if (!tsdata) return -ENOMEM; tsdata->vcc = devm_regulator_get(&client->dev, "vcc"); if (IS_ERR(tsdata->vcc)) { error = PTR_ERR(tsdata->vcc); if (error != -EPROBE_DEFER) dev_err(&client->dev, "failed to request regulator: %d\n", error); return error; } error = regulator_enable(tsdata->vcc); if (error < 0) { dev_err(&client->dev, "failed to enable vcc: %d\n", error); return error; } error = devm_add_action_or_reset(&client->dev, hycon_hy46xx_disable_regulator, tsdata); if (error) return error; tsdata->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_LOW); 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; } if (tsdata->reset_gpio) { usleep_range(5000, 6000); gpiod_set_value_cansleep(tsdata->reset_gpio, 1); usleep_range(5000, 6000); gpiod_set_value_cansleep(tsdata->reset_gpio, 0); msleep(1000); } 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->regmap = devm_regmap_init_i2c(client, &hycon_hy46xx_i2c_regmap_config); if (IS_ERR(tsdata->regmap)) { dev_err(&client->dev, "regmap allocation failed\n"); return PTR_ERR(tsdata->regmap); } hycon_hy46xx_get_defaults(&client->dev, tsdata); hycon_hy46xx_get_parameters(tsdata); input->name = "Hycon Capacitive Touch"; input->id.bustype = BUS_I2C; input->dev.parent = &client->dev; input_set_abs_params(input, ABS_MT_POSITION_X, 0, -1, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, -1, 0, 0); touchscreen_parse_properties(input, true, &tsdata->prop); error = input_mt_init_slots(input, HY46XX_MAX_SUPPORTED_POINTS, INPUT_MT_DIRECT); if (error) { dev_err(&client->dev, "Unable to init MT slots.\n"); return error; } i2c_set_clientdata(client, tsdata); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, hycon_hy46xx_isr, IRQF_ONESHOT, client->name, tsdata); if (error) { dev_err(&client->dev, "Unable to request touchscreen IRQ.\n"); return error; } error = devm_device_add_group(&client->dev, &hycon_hy46xx_attr_group); if (error) return error; error = input_register_device(input); if (error) return error; dev_dbg(&client->dev, "HYCON HY46XX initialized: IRQ %d, Reset pin %d.\n", client->irq, tsdata->reset_gpio ? desc_to_gpio(tsdata->reset_gpio) : -1); return 0; } static const struct i2c_device_id hycon_hy46xx_id[] = { { .name = "hy4613" }, { .name = "hy4614" }, { .name = "hy4621" }, { .name = "hy4623" }, { .name = "hy4633" }, { .name = "hy4635" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, hycon_hy46xx_id); static const struct of_device_id hycon_hy46xx_of_match[] = { { .compatible = "hycon,hy4613" }, { .compatible = "hycon,hy4614" }, { .compatible = "hycon,hy4621" }, { .compatible = "hycon,hy4623" }, { .compatible = "hycon,hy4633" }, { .compatible = "hycon,hy4635" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, hycon_hy46xx_of_match); static struct i2c_driver hycon_hy46xx_driver = { .driver = { .name = "hycon_hy46xx", .of_match_table = hycon_hy46xx_of_match, .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, .id_table = hycon_hy46xx_id, .probe = hycon_hy46xx_probe, }; module_i2c_driver(hycon_hy46xx_driver); MODULE_AUTHOR("Giulio Benetti <[email protected]>"); MODULE_DESCRIPTION("HYCON HY46XX I2C Touchscreen Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/hycon-hy46xx.c
// SPDX-License-Identifier: GPL-2.0-only /* * ICS MK712 touchscreen controller driver * * Copyright (c) 1999-2002 Transmeta Corporation * Copyright (c) 2005 Rick Koch <[email protected]> * Copyright (c) 2005 Vojtech Pavlik <[email protected]> */ /* * This driver supports the ICS MicroClock MK712 TouchScreen controller, * found in Gateway AOL Connected Touchpad computers. * * Documentation for ICS MK712 can be found at: * https://www.idt.com/general-parts/mk712-touch-screen-controller */ /* * 1999-12-18: original version, Daniel Quinlan * 1999-12-19: added anti-jitter code, report pen-up events, fixed mk712_poll * to use queue_empty, Nathan Laredo * 1999-12-20: improved random point rejection, Nathan Laredo * 2000-01-05: checked in new anti-jitter code, changed mouse protocol, fixed * queue code, added module options, other fixes, Daniel Quinlan * 2002-03-15: Clean up for kernel merge <[email protected]> * Fixed multi open race, fixed memory checks, fixed resource * allocation, fixed close/powerdown bug, switched to new init * 2005-01-18: Ported to 2.6 from 2.4.28, Rick Koch * 2005-02-05: Rewritten for the input layer, Vojtech Pavlik * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/input.h> #include <asm/io.h> MODULE_AUTHOR("Daniel Quinlan <[email protected]>, Vojtech Pavlik <[email protected]>"); MODULE_DESCRIPTION("ICS MicroClock MK712 TouchScreen driver"); MODULE_LICENSE("GPL"); static unsigned int mk712_io = 0x260; /* Also 0x200, 0x208, 0x300 */ module_param_hw_named(io, mk712_io, uint, ioport, 0); MODULE_PARM_DESC(io, "I/O base address of MK712 touchscreen controller"); static unsigned int mk712_irq = 10; /* Also 12, 14, 15 */ module_param_hw_named(irq, mk712_irq, uint, irq, 0); MODULE_PARM_DESC(irq, "IRQ of MK712 touchscreen controller"); /* eight 8-bit registers */ #define MK712_STATUS 0 #define MK712_X 2 #define MK712_Y 4 #define MK712_CONTROL 6 #define MK712_RATE 7 /* status */ #define MK712_STATUS_TOUCH 0x10 #define MK712_CONVERSION_COMPLETE 0x80 /* control */ #define MK712_ENABLE_INT 0x01 #define MK712_INT_ON_CONVERSION_COMPLETE 0x02 #define MK712_INT_ON_CHANGE_IN_TOUCH_STATUS 0x04 #define MK712_ENABLE_PERIODIC_CONVERSIONS 0x10 #define MK712_READ_ONE_POINT 0x20 #define MK712_POWERUP 0x40 static struct input_dev *mk712_dev; static DEFINE_SPINLOCK(mk712_lock); static irqreturn_t mk712_interrupt(int irq, void *dev_id) { unsigned char status; static int debounce = 1; static unsigned short last_x; static unsigned short last_y; spin_lock(&mk712_lock); status = inb(mk712_io + MK712_STATUS); if (~status & MK712_CONVERSION_COMPLETE) { debounce = 1; goto end; } if (~status & MK712_STATUS_TOUCH) { debounce = 1; input_report_key(mk712_dev, BTN_TOUCH, 0); goto end; } if (debounce) { debounce = 0; goto end; } input_report_key(mk712_dev, BTN_TOUCH, 1); input_report_abs(mk712_dev, ABS_X, last_x); input_report_abs(mk712_dev, ABS_Y, last_y); end: last_x = inw(mk712_io + MK712_X) & 0x0fff; last_y = inw(mk712_io + MK712_Y) & 0x0fff; input_sync(mk712_dev); spin_unlock(&mk712_lock); return IRQ_HANDLED; } static int mk712_open(struct input_dev *dev) { unsigned long flags; spin_lock_irqsave(&mk712_lock, flags); outb(0, mk712_io + MK712_CONTROL); /* Reset */ outb(MK712_ENABLE_INT | MK712_INT_ON_CONVERSION_COMPLETE | MK712_INT_ON_CHANGE_IN_TOUCH_STATUS | MK712_ENABLE_PERIODIC_CONVERSIONS | MK712_POWERUP, mk712_io + MK712_CONTROL); outb(10, mk712_io + MK712_RATE); /* 187 points per second */ spin_unlock_irqrestore(&mk712_lock, flags); return 0; } static void mk712_close(struct input_dev *dev) { unsigned long flags; spin_lock_irqsave(&mk712_lock, flags); outb(0, mk712_io + MK712_CONTROL); spin_unlock_irqrestore(&mk712_lock, flags); } static int __init mk712_init(void) { int err; if (!request_region(mk712_io, 8, "mk712")) { printk(KERN_WARNING "mk712: unable to get IO region\n"); return -ENODEV; } outb(0, mk712_io + MK712_CONTROL); if ((inw(mk712_io + MK712_X) & 0xf000) || /* Sanity check */ (inw(mk712_io + MK712_Y) & 0xf000) || (inw(mk712_io + MK712_STATUS) & 0xf333)) { printk(KERN_WARNING "mk712: device not present\n"); err = -ENODEV; goto fail1; } mk712_dev = input_allocate_device(); if (!mk712_dev) { printk(KERN_ERR "mk712: not enough memory\n"); err = -ENOMEM; goto fail1; } mk712_dev->name = "ICS MicroClock MK712 TouchScreen"; mk712_dev->phys = "isa0260/input0"; mk712_dev->id.bustype = BUS_ISA; mk712_dev->id.vendor = 0x0005; mk712_dev->id.product = 0x0001; mk712_dev->id.version = 0x0100; mk712_dev->open = mk712_open; mk712_dev->close = mk712_close; mk712_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); mk712_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); input_set_abs_params(mk712_dev, ABS_X, 0, 0xfff, 88, 0); input_set_abs_params(mk712_dev, ABS_Y, 0, 0xfff, 88, 0); if (request_irq(mk712_irq, mk712_interrupt, 0, "mk712", mk712_dev)) { printk(KERN_WARNING "mk712: unable to get IRQ\n"); err = -EBUSY; goto fail1; } err = input_register_device(mk712_dev); if (err) goto fail2; return 0; fail2: free_irq(mk712_irq, mk712_dev); fail1: input_free_device(mk712_dev); release_region(mk712_io, 8); return err; } static void __exit mk712_exit(void) { input_unregister_device(mk712_dev); free_irq(mk712_irq, mk712_dev); release_region(mk712_io, 8); } module_init(mk712_init); module_exit(mk712_exit);
linux-master
drivers/input/touchscreen/mk712.c
// SPDX-License-Identifier: GPL-2.0-only /* * ADS7846 based touchscreen and sensor driver * * 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/types.h> #include <linux/hwmon.h> #include <linux/err.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/pm.h> #include <linux/property.h> #include <linux/gpio/consumer.h> #include <linux/spi/spi.h> #include <linux/spi/ads7846.h> #include <linux/regulator/consumer.h> #include <linux/module.h> #include <asm/unaligned.h> /* * This code has been heavily tested on a Nokia 770, and lightly * tested on other ads7846 devices (OSK/Mistral, Lubbock, Spitz). * TSC2046 is just newer ads7846 silicon. * Support for ads7843 tested on Atmel at91sam926x-EK. * Support for ads7845 has only been stubbed in. * Support for Analog Devices AD7873 and AD7843 tested. * * IRQ handling needs a workaround because of a shortcoming in handling * edge triggered IRQs on some platforms like the OMAP1/2. These * platforms don't handle the ARM lazy IRQ disabling properly, thus we * have to maintain our own SW IRQ disabled status. This should be * removed as soon as the affected platform's IRQ handling is fixed. * * App note sbaa036 talks in more detail about accurate sampling... * that ought to help in situations like LCDs inducing noise (which * can also be helped by using synch signals) and more generally. * This driver tries to utilize the measures described in the app * note. The strength of filtering can be set in the board-* specific * files. */ #define TS_POLL_DELAY 1 /* ms delay before the first sample */ #define TS_POLL_PERIOD 5 /* ms delay between samples */ /* this driver doesn't aim at the peak continuous sample rate */ #define SAMPLE_BITS (8 /*cmd*/ + 16 /*sample*/ + 2 /* before, after */) struct ads7846_buf { u8 cmd; __be16 data; } __packed; struct ads7846_buf_layout { unsigned int offset; unsigned int count; unsigned int skip; }; /* * We allocate this separately to avoid cache line sharing issues when * driver is used with DMA-based SPI controllers (like atmel_spi) on * systems where main memory is not DMA-coherent (most non-x86 boards). */ struct ads7846_packet { unsigned int count; unsigned int count_skip; unsigned int cmds; unsigned int last_cmd_idx; struct ads7846_buf_layout l[5]; struct ads7846_buf *rx; struct ads7846_buf *tx; struct ads7846_buf pwrdown_cmd; bool ignore; u16 x, y, z1, z2; }; struct ads7846 { struct input_dev *input; char phys[32]; char name[32]; struct spi_device *spi; struct regulator *reg; u16 model; u16 vref_mv; u16 vref_delay_usecs; u16 x_plate_ohms; u16 pressure_max; bool swap_xy; bool use_internal; struct ads7846_packet *packet; struct spi_transfer xfer[18]; struct spi_message msg[5]; int msg_count; wait_queue_head_t wait; bool pendown; int read_cnt; int read_rep; int last_read; u16 debounce_max; u16 debounce_tol; u16 debounce_rep; u16 penirq_recheck_delay_usecs; struct touchscreen_properties core_prop; struct mutex lock; bool stopped; /* P: lock */ bool disabled; /* P: lock */ bool suspended; /* P: lock */ int (*filter)(void *data, int data_idx, int *val); void *filter_data; int (*get_pendown_state)(void); struct gpio_desc *gpio_pendown; void (*wait_for_sync)(void); }; enum ads7846_filter { ADS7846_FILTER_OK, ADS7846_FILTER_REPEAT, ADS7846_FILTER_IGNORE, }; /* leave chip selected when we're done, for quicker re-select? */ #if 0 #define CS_CHANGE(xfer) ((xfer).cs_change = 1) #else #define CS_CHANGE(xfer) ((xfer).cs_change = 0) #endif /*--------------------------------------------------------------------------*/ /* The ADS7846 has touchscreen and other sensors. * Earlier ads784x chips are somewhat compatible. */ #define ADS_START (1 << 7) #define ADS_A2A1A0_d_y (1 << 4) /* differential */ #define ADS_A2A1A0_d_z1 (3 << 4) /* differential */ #define ADS_A2A1A0_d_z2 (4 << 4) /* differential */ #define ADS_A2A1A0_d_x (5 << 4) /* differential */ #define ADS_A2A1A0_temp0 (0 << 4) /* non-differential */ #define ADS_A2A1A0_vbatt (2 << 4) /* non-differential */ #define ADS_A2A1A0_vaux (6 << 4) /* non-differential */ #define ADS_A2A1A0_temp1 (7 << 4) /* non-differential */ #define ADS_8_BIT (1 << 3) #define ADS_12_BIT (0 << 3) #define ADS_SER (1 << 2) /* non-differential */ #define ADS_DFR (0 << 2) /* differential */ #define ADS_PD10_PDOWN (0 << 0) /* low power mode + penirq */ #define ADS_PD10_ADC_ON (1 << 0) /* ADC on */ #define ADS_PD10_REF_ON (2 << 0) /* vREF on + penirq */ #define ADS_PD10_ALL_ON (3 << 0) /* ADC + vREF on */ #define MAX_12BIT ((1<<12)-1) /* leave ADC powered up (disables penirq) between differential samples */ #define READ_12BIT_DFR(x, adc, vref) (ADS_START | ADS_A2A1A0_d_ ## x \ | ADS_12_BIT | ADS_DFR | \ (adc ? ADS_PD10_ADC_ON : 0) | (vref ? ADS_PD10_REF_ON : 0)) #define READ_Y(vref) (READ_12BIT_DFR(y, 1, vref)) #define READ_Z1(vref) (READ_12BIT_DFR(z1, 1, vref)) #define READ_Z2(vref) (READ_12BIT_DFR(z2, 1, vref)) #define READ_X(vref) (READ_12BIT_DFR(x, 1, vref)) #define PWRDOWN (READ_12BIT_DFR(y, 0, 0)) /* LAST */ /* single-ended samples need to first power up reference voltage; * we leave both ADC and VREF powered */ #define READ_12BIT_SER(x) (ADS_START | ADS_A2A1A0_ ## x \ | ADS_12_BIT | ADS_SER) #define REF_ON (READ_12BIT_DFR(x, 1, 1)) #define REF_OFF (READ_12BIT_DFR(y, 0, 0)) /* Order commands in the most optimal way to reduce Vref switching and * settling time: * Measure: X; Vref: X+, X-; IN: Y+ * Measure: Y; Vref: Y+, Y-; IN: X+ * Measure: Z1; Vref: Y+, X-; IN: X+ * Measure: Z2; Vref: Y+, X-; IN: Y- */ enum ads7846_cmds { ADS7846_X, ADS7846_Y, ADS7846_Z1, ADS7846_Z2, ADS7846_PWDOWN, }; static int get_pendown_state(struct ads7846 *ts) { if (ts->get_pendown_state) return ts->get_pendown_state(); return gpiod_get_value(ts->gpio_pendown); } static void ads7846_report_pen_up(struct ads7846 *ts) { struct input_dev *input = ts->input; input_report_key(input, BTN_TOUCH, 0); input_report_abs(input, ABS_PRESSURE, 0); input_sync(input); ts->pendown = false; dev_vdbg(&ts->spi->dev, "UP\n"); } /* Must be called with ts->lock held */ static void ads7846_stop(struct ads7846 *ts) { if (!ts->disabled && !ts->suspended) { /* Signal IRQ thread to stop polling and disable the handler. */ ts->stopped = true; mb(); wake_up(&ts->wait); disable_irq(ts->spi->irq); } } /* Must be called with ts->lock held */ static void ads7846_restart(struct ads7846 *ts) { if (!ts->disabled && !ts->suspended) { /* Check if pen was released since last stop */ if (ts->pendown && !get_pendown_state(ts)) ads7846_report_pen_up(ts); /* Tell IRQ thread that it may poll the device. */ ts->stopped = false; mb(); enable_irq(ts->spi->irq); } } /* Must be called with ts->lock held */ static void __ads7846_disable(struct ads7846 *ts) { ads7846_stop(ts); regulator_disable(ts->reg); /* * We know the chip's in low power mode since we always * leave it that way after every request */ } /* Must be called with ts->lock held */ static void __ads7846_enable(struct ads7846 *ts) { int error; error = regulator_enable(ts->reg); if (error != 0) dev_err(&ts->spi->dev, "Failed to enable supply: %d\n", error); ads7846_restart(ts); } static void ads7846_disable(struct ads7846 *ts) { mutex_lock(&ts->lock); if (!ts->disabled) { if (!ts->suspended) __ads7846_disable(ts); ts->disabled = true; } mutex_unlock(&ts->lock); } static void ads7846_enable(struct ads7846 *ts) { mutex_lock(&ts->lock); if (ts->disabled) { ts->disabled = false; if (!ts->suspended) __ads7846_enable(ts); } mutex_unlock(&ts->lock); } /*--------------------------------------------------------------------------*/ /* * Non-touchscreen sensors only use single-ended conversions. * The range is GND..vREF. The ads7843 and ads7835 must use external vREF; * ads7846 lets that pin be unconnected, to use internal vREF. */ struct ser_req { u8 ref_on; u8 command; u8 ref_off; u16 scratch; 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. */ __be16 sample ____cacheline_aligned; }; struct ads7845_ser_req { u8 command[3]; struct spi_message msg; struct spi_transfer xfer[2]; /* * DMA (thus cache coherency maintenance) requires the * transfer buffers to live in their own cache lines. */ u8 sample[3] ____cacheline_aligned; }; static int ads7846_read12_ser(struct device *dev, unsigned command) { struct spi_device *spi = to_spi_device(dev); struct ads7846 *ts = dev_get_drvdata(dev); struct ser_req *req; int status; req = kzalloc(sizeof *req, GFP_KERNEL); if (!req) return -ENOMEM; spi_message_init(&req->msg); /* maybe turn on internal vREF, and let it settle */ if (ts->use_internal) { req->ref_on = REF_ON; req->xfer[0].tx_buf = &req->ref_on; req->xfer[0].len = 1; spi_message_add_tail(&req->xfer[0], &req->msg); req->xfer[1].rx_buf = &req->scratch; req->xfer[1].len = 2; /* for 1uF, settle for 800 usec; no cap, 100 usec. */ req->xfer[1].delay.value = ts->vref_delay_usecs; req->xfer[1].delay.unit = SPI_DELAY_UNIT_USECS; spi_message_add_tail(&req->xfer[1], &req->msg); /* Enable reference voltage */ command |= ADS_PD10_REF_ON; } /* Enable ADC in every case */ command |= ADS_PD10_ADC_ON; /* take sample */ req->command = (u8) command; req->xfer[2].tx_buf = &req->command; req->xfer[2].len = 1; spi_message_add_tail(&req->xfer[2], &req->msg); req->xfer[3].rx_buf = &req->sample; req->xfer[3].len = 2; spi_message_add_tail(&req->xfer[3], &req->msg); /* REVISIT: take a few more samples, and compare ... */ /* converter in low power mode & enable PENIRQ */ req->ref_off = PWRDOWN; req->xfer[4].tx_buf = &req->ref_off; req->xfer[4].len = 1; spi_message_add_tail(&req->xfer[4], &req->msg); req->xfer[5].rx_buf = &req->scratch; req->xfer[5].len = 2; CS_CHANGE(req->xfer[5]); spi_message_add_tail(&req->xfer[5], &req->msg); mutex_lock(&ts->lock); ads7846_stop(ts); status = spi_sync(spi, &req->msg); ads7846_restart(ts); mutex_unlock(&ts->lock); if (status == 0) { /* on-wire is a must-ignore bit, a BE12 value, then padding */ status = be16_to_cpu(req->sample); status = status >> 3; status &= 0x0fff; } kfree(req); return status; } static int ads7845_read12_ser(struct device *dev, unsigned command) { struct spi_device *spi = to_spi_device(dev); struct ads7846 *ts = dev_get_drvdata(dev); struct ads7845_ser_req *req; int status; req = kzalloc(sizeof *req, GFP_KERNEL); if (!req) return -ENOMEM; spi_message_init(&req->msg); req->command[0] = (u8) command; req->xfer[0].tx_buf = req->command; req->xfer[0].rx_buf = req->sample; req->xfer[0].len = 3; spi_message_add_tail(&req->xfer[0], &req->msg); mutex_lock(&ts->lock); ads7846_stop(ts); status = spi_sync(spi, &req->msg); ads7846_restart(ts); mutex_unlock(&ts->lock); if (status == 0) { /* BE12 value, then padding */ status = get_unaligned_be16(&req->sample[1]); status = status >> 3; status &= 0x0fff; } kfree(req); return status; } #if IS_ENABLED(CONFIG_HWMON) #define SHOW(name, var, adjust) static ssize_t \ name ## _show(struct device *dev, struct device_attribute *attr, char *buf) \ { \ struct ads7846 *ts = dev_get_drvdata(dev); \ ssize_t v = ads7846_read12_ser(&ts->spi->dev, \ READ_12BIT_SER(var)); \ if (v < 0) \ return v; \ return sprintf(buf, "%u\n", adjust(ts, v)); \ } \ static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL); /* Sysfs conventions report temperatures in millidegrees Celsius. * ADS7846 could use the low-accuracy two-sample scheme, but can't do the high * accuracy scheme without calibration data. For now we won't try either; * userspace sees raw sensor values, and must scale/calibrate appropriately. */ static inline unsigned null_adjust(struct ads7846 *ts, ssize_t v) { return v; } SHOW(temp0, temp0, null_adjust) /* temp1_input */ SHOW(temp1, temp1, null_adjust) /* temp2_input */ /* sysfs conventions report voltages in millivolts. We can convert voltages * if we know vREF. userspace may need to scale vAUX to match the board's * external resistors; we assume that vBATT only uses the internal ones. */ static inline unsigned vaux_adjust(struct ads7846 *ts, ssize_t v) { unsigned retval = v; /* external resistors may scale vAUX into 0..vREF */ retval *= ts->vref_mv; retval = retval >> 12; return retval; } static inline unsigned vbatt_adjust(struct ads7846 *ts, ssize_t v) { unsigned retval = vaux_adjust(ts, v); /* ads7846 has a resistor ladder to scale this signal down */ if (ts->model == 7846) retval *= 4; return retval; } SHOW(in0_input, vaux, vaux_adjust) SHOW(in1_input, vbatt, vbatt_adjust) static umode_t ads7846_is_visible(struct kobject *kobj, struct attribute *attr, int index) { struct device *dev = kobj_to_dev(kobj); struct ads7846 *ts = dev_get_drvdata(dev); if (ts->model == 7843 && index < 2) /* in0, in1 */ return 0; if (ts->model == 7845 && index != 2) /* in0 */ return 0; return attr->mode; } static struct attribute *ads7846_attributes[] = { &dev_attr_temp0.attr, /* 0 */ &dev_attr_temp1.attr, /* 1 */ &dev_attr_in0_input.attr, /* 2 */ &dev_attr_in1_input.attr, /* 3 */ NULL, }; static const struct attribute_group ads7846_attr_group = { .attrs = ads7846_attributes, .is_visible = ads7846_is_visible, }; __ATTRIBUTE_GROUPS(ads7846_attr); static int ads784x_hwmon_register(struct spi_device *spi, struct ads7846 *ts) { struct device *hwmon; /* hwmon sensors need a reference voltage */ switch (ts->model) { case 7846: if (!ts->vref_mv) { dev_dbg(&spi->dev, "assuming 2.5V internal vREF\n"); ts->vref_mv = 2500; ts->use_internal = true; } break; case 7845: case 7843: if (!ts->vref_mv) { dev_warn(&spi->dev, "external vREF for ADS%d not specified\n", ts->model); return 0; } break; } hwmon = devm_hwmon_device_register_with_groups(&spi->dev, spi->modalias, ts, ads7846_attr_groups); return PTR_ERR_OR_ZERO(hwmon); } #else static inline int ads784x_hwmon_register(struct spi_device *spi, struct ads7846 *ts) { return 0; } #endif static ssize_t ads7846_pen_down_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ads7846 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->pendown); } static DEVICE_ATTR(pen_down, S_IRUGO, ads7846_pen_down_show, NULL); static ssize_t ads7846_disable_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ads7846 *ts = dev_get_drvdata(dev); return sprintf(buf, "%u\n", ts->disabled); } static ssize_t ads7846_disable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ads7846 *ts = dev_get_drvdata(dev); unsigned int i; int err; err = kstrtouint(buf, 10, &i); if (err) return err; if (i) ads7846_disable(ts); else ads7846_enable(ts); return count; } static DEVICE_ATTR(disable, 0664, ads7846_disable_show, ads7846_disable_store); static struct attribute *ads784x_attributes[] = { &dev_attr_pen_down.attr, &dev_attr_disable.attr, NULL, }; static const struct attribute_group ads784x_attr_group = { .attrs = ads784x_attributes, }; /*--------------------------------------------------------------------------*/ static void null_wait_for_sync(void) { } static int ads7846_debounce_filter(void *ads, int data_idx, int *val) { struct ads7846 *ts = ads; if (!ts->read_cnt || (abs(ts->last_read - *val) > ts->debounce_tol)) { /* Start over collecting consistent readings. */ ts->read_rep = 0; /* * Repeat it, if this was the first read or the read * wasn't consistent enough. */ if (ts->read_cnt < ts->debounce_max) { ts->last_read = *val; ts->read_cnt++; return ADS7846_FILTER_REPEAT; } else { /* * Maximum number of debouncing reached and still * not enough number of consistent readings. Abort * the whole sample, repeat it in the next sampling * period. */ ts->read_cnt = 0; return ADS7846_FILTER_IGNORE; } } else { if (++ts->read_rep > ts->debounce_rep) { /* * Got a good reading for this coordinate, * go for the next one. */ ts->read_cnt = 0; ts->read_rep = 0; return ADS7846_FILTER_OK; } else { /* Read more values that are consistent. */ ts->read_cnt++; return ADS7846_FILTER_REPEAT; } } } static int ads7846_no_filter(void *ads, int data_idx, int *val) { return ADS7846_FILTER_OK; } static int ads7846_get_value(struct ads7846_buf *buf) { int value; value = be16_to_cpup(&buf->data); /* enforce ADC output is 12 bits width */ return (value >> 3) & 0xfff; } static void ads7846_set_cmd_val(struct ads7846 *ts, enum ads7846_cmds cmd_idx, u16 val) { struct ads7846_packet *packet = ts->packet; switch (cmd_idx) { case ADS7846_Y: packet->y = val; break; case ADS7846_X: packet->x = val; break; case ADS7846_Z1: packet->z1 = val; break; case ADS7846_Z2: packet->z2 = val; break; default: WARN_ON_ONCE(1); } } static u8 ads7846_get_cmd(enum ads7846_cmds cmd_idx, int vref) { switch (cmd_idx) { case ADS7846_Y: return READ_Y(vref); case ADS7846_X: return READ_X(vref); /* 7846 specific commands */ case ADS7846_Z1: return READ_Z1(vref); case ADS7846_Z2: return READ_Z2(vref); case ADS7846_PWDOWN: return PWRDOWN; default: WARN_ON_ONCE(1); } return 0; } static bool ads7846_cmd_need_settle(enum ads7846_cmds cmd_idx) { switch (cmd_idx) { case ADS7846_X: case ADS7846_Y: case ADS7846_Z1: case ADS7846_Z2: return true; case ADS7846_PWDOWN: return false; default: WARN_ON_ONCE(1); } return false; } static int ads7846_filter(struct ads7846 *ts) { struct ads7846_packet *packet = ts->packet; int action; int val; unsigned int cmd_idx, b; packet->ignore = false; for (cmd_idx = packet->last_cmd_idx; cmd_idx < packet->cmds - 1; cmd_idx++) { struct ads7846_buf_layout *l = &packet->l[cmd_idx]; packet->last_cmd_idx = cmd_idx; for (b = l->skip; b < l->count; b++) { val = ads7846_get_value(&packet->rx[l->offset + b]); action = ts->filter(ts->filter_data, cmd_idx, &val); if (action == ADS7846_FILTER_REPEAT) { if (b == l->count - 1) return -EAGAIN; } else if (action == ADS7846_FILTER_OK) { ads7846_set_cmd_val(ts, cmd_idx, val); break; } else { packet->ignore = true; return 0; } } } return 0; } static void ads7846_read_state(struct ads7846 *ts) { struct ads7846_packet *packet = ts->packet; struct spi_message *m; int msg_idx = 0; int error; packet->last_cmd_idx = 0; while (true) { ts->wait_for_sync(); m = &ts->msg[msg_idx]; error = spi_sync(ts->spi, m); if (error) { dev_err(&ts->spi->dev, "spi_sync --> %d\n", error); packet->ignore = true; return; } error = ads7846_filter(ts); if (error) continue; return; } } static void ads7846_report_state(struct ads7846 *ts) { struct ads7846_packet *packet = ts->packet; unsigned int Rt; u16 x, y, z1, z2; x = packet->x; y = packet->y; if (ts->model == 7845) { z1 = 0; z2 = 0; } else { z1 = packet->z1; z2 = packet->z2; } /* range filtering */ if (x == MAX_12BIT) x = 0; if (ts->model == 7843 || ts->model == 7845) { Rt = ts->pressure_max / 2; } else if (likely(x && z1)) { /* compute touch pressure resistance using equation #2 */ Rt = z2; Rt -= z1; Rt *= ts->x_plate_ohms; Rt = DIV_ROUND_CLOSEST(Rt, 16); Rt *= x; Rt /= z1; Rt = DIV_ROUND_CLOSEST(Rt, 256); } else { Rt = 0; } /* * 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 */ if (packet->ignore || Rt > ts->pressure_max) { dev_vdbg(&ts->spi->dev, "ignored %d pressure %d\n", packet->ignore, Rt); return; } /* * Maybe check the pendown state before reporting. This discards * false readings when the pen is lifted. */ if (ts->penirq_recheck_delay_usecs) { udelay(ts->penirq_recheck_delay_usecs); if (!get_pendown_state(ts)) Rt = 0; } /* * NOTE: We can't rely on the pressure to determine the pen down * state, even 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 * timer by reading the pen signal state (it's a GPIO _and_ IRQ). */ if (Rt) { struct input_dev *input = ts->input; if (!ts->pendown) { input_report_key(input, BTN_TOUCH, 1); ts->pendown = true; dev_vdbg(&ts->spi->dev, "DOWN\n"); } touchscreen_report_pos(input, &ts->core_prop, x, y, false); input_report_abs(input, ABS_PRESSURE, ts->pressure_max - Rt); input_sync(input); dev_vdbg(&ts->spi->dev, "%4d/%4d/%4d\n", x, y, Rt); } } static irqreturn_t ads7846_hard_irq(int irq, void *handle) { struct ads7846 *ts = handle; return get_pendown_state(ts) ? IRQ_WAKE_THREAD : IRQ_HANDLED; } static irqreturn_t ads7846_irq(int irq, void *handle) { struct ads7846 *ts = handle; /* Start with a small delay before checking pendown state */ msleep(TS_POLL_DELAY); while (!ts->stopped && get_pendown_state(ts)) { /* pen is down, continue with the measurement */ ads7846_read_state(ts); if (!ts->stopped) ads7846_report_state(ts); wait_event_timeout(ts->wait, ts->stopped, msecs_to_jiffies(TS_POLL_PERIOD)); } if (ts->pendown && !ts->stopped) ads7846_report_pen_up(ts); return IRQ_HANDLED; } static int ads7846_suspend(struct device *dev) { struct ads7846 *ts = dev_get_drvdata(dev); mutex_lock(&ts->lock); if (!ts->suspended) { if (!ts->disabled) __ads7846_disable(ts); if (device_may_wakeup(&ts->spi->dev)) enable_irq_wake(ts->spi->irq); ts->suspended = true; } mutex_unlock(&ts->lock); return 0; } static int ads7846_resume(struct device *dev) { struct ads7846 *ts = dev_get_drvdata(dev); mutex_lock(&ts->lock); if (ts->suspended) { ts->suspended = false; if (device_may_wakeup(&ts->spi->dev)) disable_irq_wake(ts->spi->irq); if (!ts->disabled) __ads7846_enable(ts); } mutex_unlock(&ts->lock); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(ads7846_pm, ads7846_suspend, ads7846_resume); static int ads7846_setup_pendown(struct spi_device *spi, struct ads7846 *ts, const struct ads7846_platform_data *pdata) { /* * REVISIT when the irq can be triggered active-low, or if for some * reason the touchscreen isn't hooked up, we don't need to access * the pendown state. */ if (pdata->get_pendown_state) { ts->get_pendown_state = pdata->get_pendown_state; } else { ts->gpio_pendown = gpiod_get(&spi->dev, "pendown", GPIOD_IN); if (IS_ERR(ts->gpio_pendown)) { dev_err(&spi->dev, "failed to request pendown GPIO\n"); return PTR_ERR(ts->gpio_pendown); } if (pdata->gpio_pendown_debounce) gpiod_set_debounce(ts->gpio_pendown, pdata->gpio_pendown_debounce); } return 0; } /* * Set up the transfers to read touchscreen state; this assumes we * use formula #2 for pressure, not #3. */ static int ads7846_setup_spi_msg(struct ads7846 *ts, const struct ads7846_platform_data *pdata) { struct spi_message *m = &ts->msg[0]; struct spi_transfer *x = ts->xfer; struct ads7846_packet *packet = ts->packet; int vref = pdata->keep_vref_on; unsigned int count, offset = 0; unsigned int cmd_idx, b; unsigned long time; size_t size = 0; /* time per bit */ time = NSEC_PER_SEC / ts->spi->max_speed_hz; count = pdata->settle_delay_usecs * NSEC_PER_USEC / time; packet->count_skip = DIV_ROUND_UP(count, 24); if (ts->debounce_max && ts->debounce_rep) /* ads7846_debounce_filter() is making ts->debounce_rep + 2 * reads. So we need to get all samples for normal case. */ packet->count = ts->debounce_rep + 2; else packet->count = 1; if (ts->model == 7846) packet->cmds = 5; /* x, y, z1, z2, pwdown */ else packet->cmds = 3; /* x, y, pwdown */ for (cmd_idx = 0; cmd_idx < packet->cmds; cmd_idx++) { struct ads7846_buf_layout *l = &packet->l[cmd_idx]; unsigned int max_count; if (cmd_idx == packet->cmds - 1) cmd_idx = ADS7846_PWDOWN; if (ads7846_cmd_need_settle(cmd_idx)) max_count = packet->count + packet->count_skip; else max_count = packet->count; l->offset = offset; offset += max_count; l->count = max_count; l->skip = packet->count_skip; size += sizeof(*packet->tx) * max_count; } packet->tx = devm_kzalloc(&ts->spi->dev, size, GFP_KERNEL); if (!packet->tx) return -ENOMEM; packet->rx = devm_kzalloc(&ts->spi->dev, size, GFP_KERNEL); if (!packet->rx) return -ENOMEM; if (ts->model == 7873) { /* * The AD7873 is almost identical to the ADS7846 * keep VREF off during differential/ratiometric * conversion modes. */ ts->model = 7846; vref = 0; } ts->msg_count = 1; spi_message_init(m); m->context = ts; for (cmd_idx = 0; cmd_idx < packet->cmds; cmd_idx++) { struct ads7846_buf_layout *l = &packet->l[cmd_idx]; u8 cmd; if (cmd_idx == packet->cmds - 1) cmd_idx = ADS7846_PWDOWN; cmd = ads7846_get_cmd(cmd_idx, vref); for (b = 0; b < l->count; b++) packet->tx[l->offset + b].cmd = cmd; } x->tx_buf = packet->tx; x->rx_buf = packet->rx; x->len = size; spi_message_add_tail(x, m); return 0; } static const struct of_device_id ads7846_dt_ids[] = { { .compatible = "ti,tsc2046", .data = (void *) 7846 }, { .compatible = "ti,ads7843", .data = (void *) 7843 }, { .compatible = "ti,ads7845", .data = (void *) 7845 }, { .compatible = "ti,ads7846", .data = (void *) 7846 }, { .compatible = "ti,ads7873", .data = (void *) 7873 }, { } }; MODULE_DEVICE_TABLE(of, ads7846_dt_ids); static const struct ads7846_platform_data *ads7846_get_props(struct device *dev) { struct ads7846_platform_data *pdata; u32 value; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return ERR_PTR(-ENOMEM); pdata->model = (uintptr_t)device_get_match_data(dev); device_property_read_u16(dev, "ti,vref-delay-usecs", &pdata->vref_delay_usecs); device_property_read_u16(dev, "ti,vref-mv", &pdata->vref_mv); pdata->keep_vref_on = device_property_read_bool(dev, "ti,keep-vref-on"); pdata->swap_xy = device_property_read_bool(dev, "ti,swap-xy"); device_property_read_u16(dev, "ti,settle-delay-usec", &pdata->settle_delay_usecs); device_property_read_u16(dev, "ti,penirq-recheck-delay-usecs", &pdata->penirq_recheck_delay_usecs); device_property_read_u16(dev, "ti,x-plate-ohms", &pdata->x_plate_ohms); device_property_read_u16(dev, "ti,y-plate-ohms", &pdata->y_plate_ohms); device_property_read_u16(dev, "ti,x-min", &pdata->x_min); device_property_read_u16(dev, "ti,y-min", &pdata->y_min); device_property_read_u16(dev, "ti,x-max", &pdata->x_max); device_property_read_u16(dev, "ti,y-max", &pdata->y_max); /* * touchscreen-max-pressure gets parsed during * touchscreen_parse_properties() */ device_property_read_u16(dev, "ti,pressure-min", &pdata->pressure_min); if (!device_property_read_u32(dev, "touchscreen-min-pressure", &value)) pdata->pressure_min = (u16) value; device_property_read_u16(dev, "ti,pressure-max", &pdata->pressure_max); device_property_read_u16(dev, "ti,debounce-max", &pdata->debounce_max); if (!device_property_read_u32(dev, "touchscreen-average-samples", &value)) pdata->debounce_max = (u16) value; device_property_read_u16(dev, "ti,debounce-tol", &pdata->debounce_tol); device_property_read_u16(dev, "ti,debounce-rep", &pdata->debounce_rep); device_property_read_u32(dev, "ti,pendown-gpio-debounce", &pdata->gpio_pendown_debounce); pdata->wakeup = device_property_read_bool(dev, "wakeup-source") || device_property_read_bool(dev, "linux,wakeup"); return pdata; } static void ads7846_regulator_disable(void *regulator) { regulator_disable(regulator); } static int ads7846_probe(struct spi_device *spi) { const struct ads7846_platform_data *pdata; struct ads7846 *ts; struct device *dev = &spi->dev; struct ads7846_packet *packet; struct input_dev *input_dev; unsigned long irq_flags; int err; if (!spi->irq) { dev_dbg(dev, "no IRQ?\n"); return -EINVAL; } /* don't exceed max specified sample rate */ if (spi->max_speed_hz > (125000 * SAMPLE_BITS)) { dev_err(dev, "f(sample) %d KHz?\n", (spi->max_speed_hz/SAMPLE_BITS)/1000); return -EINVAL; } /* * We'd set TX word size 8 bits and RX word size to 13 bits ... except * that even if the hardware can do that, the SPI controller driver * may not. So we stick to very-portable 8 bit words, both RX and TX. */ spi->bits_per_word = 8; spi->mode &= ~SPI_MODE_X_MASK; spi->mode |= SPI_MODE_0; err = spi_setup(spi); if (err < 0) return err; ts = devm_kzalloc(dev, sizeof(struct ads7846), GFP_KERNEL); if (!ts) return -ENOMEM; packet = devm_kzalloc(dev, sizeof(struct ads7846_packet), GFP_KERNEL); if (!packet) return -ENOMEM; input_dev = devm_input_allocate_device(dev); if (!input_dev) return -ENOMEM; spi_set_drvdata(spi, ts); ts->packet = packet; ts->spi = spi; ts->input = input_dev; mutex_init(&ts->lock); init_waitqueue_head(&ts->wait); pdata = dev_get_platdata(dev); if (!pdata) { pdata = ads7846_get_props(dev); if (IS_ERR(pdata)) return PTR_ERR(pdata); } ts->model = pdata->model ? : 7846; ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100; ts->x_plate_ohms = pdata->x_plate_ohms ? : 400; ts->vref_mv = pdata->vref_mv; if (pdata->debounce_max) { ts->debounce_max = pdata->debounce_max; if (ts->debounce_max < 2) ts->debounce_max = 2; ts->debounce_tol = pdata->debounce_tol; ts->debounce_rep = pdata->debounce_rep; ts->filter = ads7846_debounce_filter; ts->filter_data = ts; } else { ts->filter = ads7846_no_filter; } err = ads7846_setup_pendown(spi, ts, pdata); if (err) return err; if (pdata->penirq_recheck_delay_usecs) ts->penirq_recheck_delay_usecs = pdata->penirq_recheck_delay_usecs; ts->wait_for_sync = pdata->wait_for_sync ? : null_wait_for_sync; snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(dev)); snprintf(ts->name, sizeof(ts->name), "ADS%d Touchscreen", ts->model); input_dev->name = ts->name; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_SPI; input_dev->id.product = pdata->model; input_set_capability(input_dev, EV_KEY, BTN_TOUCH); 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); if (ts->model != 7845) input_set_abs_params(input_dev, ABS_PRESSURE, pdata->pressure_min, pdata->pressure_max, 0, 0); /* * Parse common framework properties. Must be done here to ensure the * correct behaviour in case of using the legacy vendor bindings. The * general binding value overrides the vendor specific one. */ touchscreen_parse_properties(ts->input, false, &ts->core_prop); ts->pressure_max = input_abs_get_max(input_dev, ABS_PRESSURE) ? : ~0; /* * Check if legacy ti,swap-xy binding is used instead of * touchscreen-swapped-x-y */ if (!ts->core_prop.swap_x_y && pdata->swap_xy) { swap(input_dev->absinfo[ABS_X], input_dev->absinfo[ABS_Y]); ts->core_prop.swap_x_y = true; } ads7846_setup_spi_msg(ts, pdata); ts->reg = devm_regulator_get(dev, "vcc"); if (IS_ERR(ts->reg)) { err = PTR_ERR(ts->reg); dev_err(dev, "unable to get regulator: %d\n", err); return err; } err = regulator_enable(ts->reg); if (err) { dev_err(dev, "unable to enable regulator: %d\n", err); return err; } err = devm_add_action_or_reset(dev, ads7846_regulator_disable, ts->reg); if (err) return err; irq_flags = pdata->irq_flags ? : IRQF_TRIGGER_FALLING; irq_flags |= IRQF_ONESHOT; err = devm_request_threaded_irq(dev, spi->irq, ads7846_hard_irq, ads7846_irq, irq_flags, dev->driver->name, ts); if (err && err != -EPROBE_DEFER && !pdata->irq_flags) { dev_info(dev, "trying pin change workaround on irq %d\n", spi->irq); irq_flags |= IRQF_TRIGGER_RISING; err = devm_request_threaded_irq(dev, spi->irq, ads7846_hard_irq, ads7846_irq, irq_flags, dev->driver->name, ts); } if (err) { dev_dbg(dev, "irq %d busy?\n", spi->irq); return err; } err = ads784x_hwmon_register(spi, ts); if (err) return err; dev_info(dev, "touchscreen, irq %d\n", spi->irq); /* * Take a first sample, leaving nPENIRQ active and vREF off; avoid * the touchscreen, in case it's not connected. */ if (ts->model == 7845) ads7845_read12_ser(dev, PWRDOWN); else (void) ads7846_read12_ser(dev, READ_12BIT_SER(vaux)); err = devm_device_add_group(dev, &ads784x_attr_group); if (err) return err; err = input_register_device(input_dev); if (err) return err; device_init_wakeup(dev, pdata->wakeup); /* * If device does not carry platform data we must have allocated it * when parsing DT data. */ if (!dev_get_platdata(dev)) devm_kfree(dev, (void *)pdata); return 0; } static void ads7846_remove(struct spi_device *spi) { struct ads7846 *ts = spi_get_drvdata(spi); ads7846_stop(ts); } static struct spi_driver ads7846_driver = { .driver = { .name = "ads7846", .pm = pm_sleep_ptr(&ads7846_pm), .of_match_table = ads7846_dt_ids, }, .probe = ads7846_probe, .remove = ads7846_remove, }; module_spi_driver(ads7846_driver); MODULE_DESCRIPTION("ADS7846 TouchScreen Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:ads7846");
linux-master
drivers/input/touchscreen/ads7846.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for Novatek NT11205 i2c touchscreen controller as found * on the Acer Iconia One 7 B1-750 tablet. * * Copyright (c) 2023 Hans de Goede <[email protected]> */ #include <linux/delay.h> #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 <asm/unaligned.h> #define NVT_TS_TOUCH_START 0x00 #define NVT_TS_TOUCH_SIZE 6 #define NVT_TS_PARAMETERS_START 0x78 /* These are offsets from NVT_TS_PARAMETERS_START */ #define NVT_TS_PARAMS_WIDTH 0x04 #define NVT_TS_PARAMS_HEIGHT 0x06 #define NVT_TS_PARAMS_MAX_TOUCH 0x09 #define NVT_TS_PARAMS_MAX_BUTTONS 0x0a #define NVT_TS_PARAMS_IRQ_TYPE 0x0b #define NVT_TS_PARAMS_WAKE_TYPE 0x0c #define NVT_TS_PARAMS_CHIP_ID 0x0e #define NVT_TS_PARAMS_SIZE 0x0f #define NVT_TS_SUPPORTED_WAKE_TYPE 0x05 #define NVT_TS_SUPPORTED_CHIP_ID 0x05 #define NVT_TS_MAX_TOUCHES 10 #define NVT_TS_MAX_SIZE 4096 #define NVT_TS_TOUCH_INVALID 0xff #define NVT_TS_TOUCH_SLOT_SHIFT 3 #define NVT_TS_TOUCH_TYPE_MASK GENMASK(2, 0) #define NVT_TS_TOUCH_NEW 1 #define NVT_TS_TOUCH_UPDATE 2 #define NVT_TS_TOUCH_RELEASE 3 static const int nvt_ts_irq_type[4] = { IRQF_TRIGGER_RISING, IRQF_TRIGGER_FALLING, IRQF_TRIGGER_LOW, IRQF_TRIGGER_HIGH }; struct nvt_ts_data { struct i2c_client *client; struct input_dev *input; struct gpio_desc *reset_gpio; struct touchscreen_properties prop; int max_touches; u8 buf[NVT_TS_TOUCH_SIZE * NVT_TS_MAX_TOUCHES]; }; static int nvt_ts_read_data(struct i2c_client *client, u8 reg, u8 *data, int count) { struct i2c_msg msg[2] = { { .addr = client->addr, .len = 1, .buf = &reg, }, { .addr = client->addr, .flags = I2C_M_RD, .len = count, .buf = data, } }; int ret; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { dev_err(&client->dev, "Error reading from 0x%02x: %d\n", reg, ret); return (ret < 0) ? ret : -EIO; } return 0; } static irqreturn_t nvt_ts_irq(int irq, void *dev_id) { struct nvt_ts_data *data = dev_id; struct device *dev = &data->client->dev; int i, error, slot, x, y; bool active; u8 *touch; error = nvt_ts_read_data(data->client, NVT_TS_TOUCH_START, data->buf, data->max_touches * NVT_TS_TOUCH_SIZE); if (error) return IRQ_HANDLED; for (i = 0; i < data->max_touches; i++) { touch = &data->buf[i * NVT_TS_TOUCH_SIZE]; if (touch[0] == NVT_TS_TOUCH_INVALID) continue; slot = touch[0] >> NVT_TS_TOUCH_SLOT_SHIFT; if (slot < 1 || slot > data->max_touches) { dev_warn(dev, "slot %d out of range, ignoring\n", slot); continue; } switch (touch[0] & NVT_TS_TOUCH_TYPE_MASK) { case NVT_TS_TOUCH_NEW: case NVT_TS_TOUCH_UPDATE: active = true; break; case NVT_TS_TOUCH_RELEASE: active = false; break; default: dev_warn(dev, "slot %d unknown state %d\n", slot, touch[0] & 7); continue; } slot--; x = (touch[1] << 4) | (touch[3] >> 4); y = (touch[2] << 4) | (touch[3] & 0x0f); input_mt_slot(data->input, slot); input_mt_report_slot_state(data->input, MT_TOOL_FINGER, active); touchscreen_report_pos(data->input, &data->prop, x, y, true); } input_mt_sync_frame(data->input); input_sync(data->input); return IRQ_HANDLED; } static int nvt_ts_start(struct input_dev *dev) { struct nvt_ts_data *data = input_get_drvdata(dev); enable_irq(data->client->irq); gpiod_set_value_cansleep(data->reset_gpio, 0); return 0; } static void nvt_ts_stop(struct input_dev *dev) { struct nvt_ts_data *data = input_get_drvdata(dev); disable_irq(data->client->irq); gpiod_set_value_cansleep(data->reset_gpio, 1); } static int nvt_ts_suspend(struct device *dev) { struct nvt_ts_data *data = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&data->input->mutex); if (input_device_enabled(data->input)) nvt_ts_stop(data->input); mutex_unlock(&data->input->mutex); return 0; } static int nvt_ts_resume(struct device *dev) { struct nvt_ts_data *data = i2c_get_clientdata(to_i2c_client(dev)); mutex_lock(&data->input->mutex); if (input_device_enabled(data->input)) nvt_ts_start(data->input); mutex_unlock(&data->input->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(nvt_ts_pm_ops, nvt_ts_suspend, nvt_ts_resume); static int nvt_ts_probe(struct i2c_client *client) { struct device *dev = &client->dev; int error, width, height, irq_type; struct nvt_ts_data *data; struct input_dev *input; 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->client = client; i2c_set_clientdata(client, data); data->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW); error = PTR_ERR_OR_ZERO(data->reset_gpio); if (error) { dev_err(dev, "failed to request reset GPIO: %d\n", error); return error; } /* Wait for controller to come out of reset before params read */ msleep(100); error = nvt_ts_read_data(data->client, NVT_TS_PARAMETERS_START, data->buf, NVT_TS_PARAMS_SIZE); gpiod_set_value_cansleep(data->reset_gpio, 1); /* Put back in reset */ if (error) return error; width = get_unaligned_be16(&data->buf[NVT_TS_PARAMS_WIDTH]); height = get_unaligned_be16(&data->buf[NVT_TS_PARAMS_HEIGHT]); data->max_touches = data->buf[NVT_TS_PARAMS_MAX_TOUCH]; irq_type = data->buf[NVT_TS_PARAMS_IRQ_TYPE]; if (width > NVT_TS_MAX_SIZE || height >= NVT_TS_MAX_SIZE || data->max_touches > NVT_TS_MAX_TOUCHES || irq_type >= ARRAY_SIZE(nvt_ts_irq_type) || data->buf[NVT_TS_PARAMS_WAKE_TYPE] != NVT_TS_SUPPORTED_WAKE_TYPE || data->buf[NVT_TS_PARAMS_CHIP_ID] != NVT_TS_SUPPORTED_CHIP_ID) { dev_err(dev, "Unsupported touchscreen parameters: %*ph\n", NVT_TS_PARAMS_SIZE, data->buf); return -EIO; } dev_dbg(dev, "Detected %dx%d touchscreen with %d max touches\n", width, height, data->max_touches); if (data->buf[NVT_TS_PARAMS_MAX_BUTTONS]) dev_warn(dev, "Touchscreen buttons are not supported\n"); input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; input->name = client->name; input->id.bustype = BUS_I2C; input->open = nvt_ts_start; input->close = nvt_ts_stop; input_set_abs_params(input, ABS_MT_POSITION_X, 0, width - 1, 0, 0); input_set_abs_params(input, ABS_MT_POSITION_Y, 0, height - 1, 0, 0); touchscreen_parse_properties(input, true, &data->prop); error = input_mt_init_slots(input, data->max_touches, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; data->input = input; input_set_drvdata(input, data); error = devm_request_threaded_irq(dev, client->irq, NULL, nvt_ts_irq, IRQF_ONESHOT | IRQF_NO_AUTOEN | nvt_ts_irq_type[irq_type], client->name, data); 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; } return 0; } static const struct i2c_device_id nvt_ts_i2c_id[] = { { "NVT-ts" }, { } }; MODULE_DEVICE_TABLE(i2c, nvt_ts_i2c_id); static struct i2c_driver nvt_ts_driver = { .driver = { .name = "novatek-nvt-ts", .pm = pm_sleep_ptr(&nvt_ts_pm_ops), }, .probe = nvt_ts_probe, .id_table = nvt_ts_i2c_id, }; module_i2c_driver(nvt_ts_driver); MODULE_DESCRIPTION("Novatek NT11205 touchscreen driver"); MODULE_AUTHOR("Hans de Goede <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/novatek-nvt-ts.c
/* * TI Touch Screen driver * * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation version 2. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/err.h> #include <linux/module.h> #include <linux/input.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/clk.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/of.h> #include <linux/sort.h> #include <linux/pm_wakeirq.h> #include <linux/mfd/ti_am335x_tscadc.h> #define ADCFSM_STEPID 0x10 #define SEQ_SETTLE 275 #define MAX_12BIT ((1 << 12) - 1) #define TSC_IRQENB_MASK (IRQENB_FIFO0THRES | IRQENB_EOS | IRQENB_HW_PEN) static const int config_pins[] = { STEPCONFIG_XPP, STEPCONFIG_XNN, STEPCONFIG_YPP, STEPCONFIG_YNN, }; struct titsc { struct input_dev *input; struct ti_tscadc_dev *mfd_tscadc; struct device *dev; unsigned int irq; unsigned int wires; unsigned int x_plate_resistance; bool pen_down; int coordinate_readouts; u32 config_inp[4]; u32 bit_xp, bit_xn, bit_yp, bit_yn; u32 inp_xp, inp_xn, inp_yp, inp_yn; u32 step_mask; u32 charge_delay; }; static unsigned int titsc_readl(struct titsc *ts, unsigned int reg) { return readl(ts->mfd_tscadc->tscadc_base + reg); } static void titsc_writel(struct titsc *tsc, unsigned int reg, unsigned int val) { writel(val, tsc->mfd_tscadc->tscadc_base + reg); } static int titsc_config_wires(struct titsc *ts_dev) { u32 analog_line[4]; u32 wire_order[4]; int i, bit_cfg; for (i = 0; i < 4; i++) { /* * Get the order in which TSC wires are attached * w.r.t. each of the analog input lines on the EVM. */ analog_line[i] = (ts_dev->config_inp[i] & 0xF0) >> 4; wire_order[i] = ts_dev->config_inp[i] & 0x0F; if (WARN_ON(analog_line[i] > 7)) return -EINVAL; if (WARN_ON(wire_order[i] > ARRAY_SIZE(config_pins))) return -EINVAL; } for (i = 0; i < 4; i++) { int an_line; int wi_order; an_line = analog_line[i]; wi_order = wire_order[i]; bit_cfg = config_pins[wi_order]; if (bit_cfg == 0) return -EINVAL; switch (wi_order) { case 0: ts_dev->bit_xp = bit_cfg; ts_dev->inp_xp = an_line; break; case 1: ts_dev->bit_xn = bit_cfg; ts_dev->inp_xn = an_line; break; case 2: ts_dev->bit_yp = bit_cfg; ts_dev->inp_yp = an_line; break; case 3: ts_dev->bit_yn = bit_cfg; ts_dev->inp_yn = an_line; break; } } return 0; } static void titsc_step_config(struct titsc *ts_dev) { unsigned int config; int i, n; int end_step, first_step, tsc_steps; u32 stepenable; config = STEPCONFIG_MODE_HWSYNC | STEPCONFIG_AVG_16 | ts_dev->bit_xp | STEPCONFIG_INM_ADCREFM; switch (ts_dev->wires) { case 4: config |= STEPCONFIG_INP(ts_dev->inp_yp) | ts_dev->bit_xn; break; case 5: config |= ts_dev->bit_yn | STEPCONFIG_INP_AN4 | ts_dev->bit_xn | ts_dev->bit_yp; break; case 8: config |= STEPCONFIG_INP(ts_dev->inp_yp) | ts_dev->bit_xn; break; } tsc_steps = ts_dev->coordinate_readouts * 2 + 2; first_step = TOTAL_STEPS - tsc_steps; /* Steps 16 to 16-coordinate_readouts is for X */ end_step = first_step + tsc_steps; n = 0; for (i = end_step - ts_dev->coordinate_readouts; i < end_step; i++) { titsc_writel(ts_dev, REG_STEPCONFIG(i), config); titsc_writel(ts_dev, REG_STEPDELAY(i), n++ == 0 ? STEPCONFIG_OPENDLY : 0); } config = 0; config = STEPCONFIG_MODE_HWSYNC | STEPCONFIG_AVG_16 | ts_dev->bit_yn | STEPCONFIG_INM_ADCREFM; switch (ts_dev->wires) { case 4: config |= ts_dev->bit_yp | STEPCONFIG_INP(ts_dev->inp_xp); break; case 5: config |= ts_dev->bit_xp | STEPCONFIG_INP_AN4 | STEPCONFIG_XNP | STEPCONFIG_YPN; break; case 8: config |= ts_dev->bit_yp | STEPCONFIG_INP(ts_dev->inp_xp); break; } /* 1 ... coordinate_readouts is for Y */ end_step = first_step + ts_dev->coordinate_readouts; n = 0; for (i = first_step; i < end_step; i++) { titsc_writel(ts_dev, REG_STEPCONFIG(i), config); titsc_writel(ts_dev, REG_STEPDELAY(i), n++ == 0 ? STEPCONFIG_OPENDLY : 0); } /* Make CHARGECONFIG same as IDLECONFIG */ config = titsc_readl(ts_dev, REG_IDLECONFIG); titsc_writel(ts_dev, REG_CHARGECONFIG, config); titsc_writel(ts_dev, REG_CHARGEDELAY, ts_dev->charge_delay); /* coordinate_readouts + 1 ... coordinate_readouts + 2 is for Z */ config = STEPCONFIG_MODE_HWSYNC | STEPCONFIG_AVG_16 | ts_dev->bit_yp | ts_dev->bit_xn | STEPCONFIG_INM_ADCREFM | STEPCONFIG_INP(ts_dev->inp_xp); titsc_writel(ts_dev, REG_STEPCONFIG(end_step), config); titsc_writel(ts_dev, REG_STEPDELAY(end_step), STEPCONFIG_OPENDLY); end_step++; config = STEPCONFIG_MODE_HWSYNC | STEPCONFIG_AVG_16 | ts_dev->bit_yp | ts_dev->bit_xn | STEPCONFIG_INM_ADCREFM | STEPCONFIG_INP(ts_dev->inp_yn); titsc_writel(ts_dev, REG_STEPCONFIG(end_step), config); titsc_writel(ts_dev, REG_STEPDELAY(end_step), STEPCONFIG_OPENDLY); /* The steps end ... end - readouts * 2 + 2 and bit 0 for TS_Charge */ stepenable = 1; for (i = 0; i < tsc_steps; i++) stepenable |= 1 << (first_step + i + 1); ts_dev->step_mask = stepenable; am335x_tsc_se_set_cache(ts_dev->mfd_tscadc, ts_dev->step_mask); } static int titsc_cmp_coord(const void *a, const void *b) { return *(int *)a - *(int *)b; } static void titsc_read_coordinates(struct titsc *ts_dev, u32 *x, u32 *y, u32 *z1, u32 *z2) { unsigned int yvals[7], xvals[7]; unsigned int i, xsum = 0, ysum = 0; unsigned int creads = ts_dev->coordinate_readouts; for (i = 0; i < creads; i++) { yvals[i] = titsc_readl(ts_dev, REG_FIFO0); yvals[i] &= 0xfff; } *z1 = titsc_readl(ts_dev, REG_FIFO0); *z1 &= 0xfff; *z2 = titsc_readl(ts_dev, REG_FIFO0); *z2 &= 0xfff; for (i = 0; i < creads; i++) { xvals[i] = titsc_readl(ts_dev, REG_FIFO0); xvals[i] &= 0xfff; } /* * If co-ordinates readouts is less than 4 then * report the average. In case of 4 or more * readouts, sort the co-ordinate samples, drop * min and max values and report the average of * remaining values. */ if (creads <= 3) { for (i = 0; i < creads; i++) { ysum += yvals[i]; xsum += xvals[i]; } ysum /= creads; xsum /= creads; } else { sort(yvals, creads, sizeof(unsigned int), titsc_cmp_coord, NULL); sort(xvals, creads, sizeof(unsigned int), titsc_cmp_coord, NULL); for (i = 1; i < creads - 1; i++) { ysum += yvals[i]; xsum += xvals[i]; } ysum /= creads - 2; xsum /= creads - 2; } *y = ysum; *x = xsum; } static irqreturn_t titsc_irq(int irq, void *dev) { struct titsc *ts_dev = dev; struct input_dev *input_dev = ts_dev->input; unsigned int fsm, status, irqclr = 0; unsigned int x = 0, y = 0; unsigned int z1, z2, z; status = titsc_readl(ts_dev, REG_RAWIRQSTATUS); if (status & IRQENB_HW_PEN) { ts_dev->pen_down = true; irqclr |= IRQENB_HW_PEN; pm_stay_awake(ts_dev->dev); } if (status & IRQENB_PENUP) { fsm = titsc_readl(ts_dev, REG_ADCFSM); if (fsm == ADCFSM_STEPID) { ts_dev->pen_down = false; input_report_key(input_dev, BTN_TOUCH, 0); input_report_abs(input_dev, ABS_PRESSURE, 0); input_sync(input_dev); pm_relax(ts_dev->dev); } else { ts_dev->pen_down = true; } irqclr |= IRQENB_PENUP; } if (status & IRQENB_EOS) irqclr |= IRQENB_EOS; /* * ADC and touchscreen share the IRQ line. * FIFO1 interrupts are used by ADC. Handle FIFO0 IRQs here only */ if (status & IRQENB_FIFO0THRES) { titsc_read_coordinates(ts_dev, &x, &y, &z1, &z2); if (ts_dev->pen_down && z1 != 0 && z2 != 0) { /* * Calculate pressure using formula * Resistance(touch) = x plate resistance * * x position/4096 * ((z2 / z1) - 1) */ z = z1 - z2; z *= x; z *= ts_dev->x_plate_resistance; z /= z2; z = (z + 2047) >> 12; if (z <= MAX_12BIT) { input_report_abs(input_dev, ABS_X, x); input_report_abs(input_dev, ABS_Y, y); input_report_abs(input_dev, ABS_PRESSURE, z); input_report_key(input_dev, BTN_TOUCH, 1); input_sync(input_dev); } } irqclr |= IRQENB_FIFO0THRES; } if (irqclr) { titsc_writel(ts_dev, REG_IRQSTATUS, irqclr); if (status & IRQENB_EOS) am335x_tsc_se_set_cache(ts_dev->mfd_tscadc, ts_dev->step_mask); return IRQ_HANDLED; } return IRQ_NONE; } static int titsc_parse_dt(struct platform_device *pdev, struct titsc *ts_dev) { struct device_node *node = pdev->dev.of_node; int err; if (!node) return -EINVAL; err = of_property_read_u32(node, "ti,wires", &ts_dev->wires); if (err < 0) return err; switch (ts_dev->wires) { case 4: case 5: case 8: break; default: return -EINVAL; } err = of_property_read_u32(node, "ti,x-plate-resistance", &ts_dev->x_plate_resistance); if (err < 0) return err; /* * Try with the new binding first. If it fails, try again with * bogus, miss-spelled version. */ err = of_property_read_u32(node, "ti,coordinate-readouts", &ts_dev->coordinate_readouts); if (err < 0) { dev_warn(&pdev->dev, "please use 'ti,coordinate-readouts' instead\n"); err = of_property_read_u32(node, "ti,coordiante-readouts", &ts_dev->coordinate_readouts); } if (err < 0) return err; if (ts_dev->coordinate_readouts <= 0) { dev_warn(&pdev->dev, "invalid co-ordinate readouts, resetting it to 5\n"); ts_dev->coordinate_readouts = 5; } err = of_property_read_u32(node, "ti,charge-delay", &ts_dev->charge_delay); /* * If ti,charge-delay value is not specified, then use * CHARGEDLY_OPENDLY as the default value. */ if (err < 0) { ts_dev->charge_delay = CHARGEDLY_OPENDLY; dev_warn(&pdev->dev, "ti,charge-delay not specified\n"); } return of_property_read_u32_array(node, "ti,wire-config", ts_dev->config_inp, ARRAY_SIZE(ts_dev->config_inp)); } /* * The functions for inserting/removing driver as a module. */ static int titsc_probe(struct platform_device *pdev) { struct titsc *ts_dev; struct input_dev *input_dev; struct ti_tscadc_dev *tscadc_dev = ti_tscadc_dev_get(pdev); int err; /* Allocate memory for device */ ts_dev = kzalloc(sizeof(*ts_dev), GFP_KERNEL); input_dev = input_allocate_device(); if (!ts_dev || !input_dev) { dev_err(&pdev->dev, "failed to allocate memory.\n"); err = -ENOMEM; goto err_free_mem; } tscadc_dev->tsc = ts_dev; ts_dev->mfd_tscadc = tscadc_dev; ts_dev->input = input_dev; ts_dev->irq = tscadc_dev->irq; ts_dev->dev = &pdev->dev; err = titsc_parse_dt(pdev, ts_dev); if (err) { dev_err(&pdev->dev, "Could not find valid DT data.\n"); goto err_free_mem; } err = request_irq(ts_dev->irq, titsc_irq, IRQF_SHARED, pdev->dev.driver->name, ts_dev); if (err) { dev_err(&pdev->dev, "failed to allocate irq.\n"); goto err_free_mem; } device_init_wakeup(&pdev->dev, true); err = dev_pm_set_wake_irq(&pdev->dev, ts_dev->irq); if (err) dev_err(&pdev->dev, "irq wake enable failed.\n"); titsc_writel(ts_dev, REG_IRQSTATUS, TSC_IRQENB_MASK); titsc_writel(ts_dev, REG_IRQENABLE, IRQENB_FIFO0THRES); titsc_writel(ts_dev, REG_IRQENABLE, IRQENB_EOS); err = titsc_config_wires(ts_dev); if (err) { dev_err(&pdev->dev, "wrong i/p wire configuration\n"); goto err_free_irq; } titsc_step_config(ts_dev); titsc_writel(ts_dev, REG_FIFO0THR, ts_dev->coordinate_readouts * 2 + 2 - 1); input_dev->name = "ti-tsc"; 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, 0, MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, 0, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, MAX_12BIT, 0, 0); /* register to the input system */ err = input_register_device(input_dev); if (err) goto err_free_irq; platform_set_drvdata(pdev, ts_dev); return 0; err_free_irq: dev_pm_clear_wake_irq(&pdev->dev); device_init_wakeup(&pdev->dev, false); free_irq(ts_dev->irq, ts_dev); err_free_mem: input_free_device(input_dev); kfree(ts_dev); return err; } static int titsc_remove(struct platform_device *pdev) { struct titsc *ts_dev = platform_get_drvdata(pdev); u32 steps; dev_pm_clear_wake_irq(&pdev->dev); device_init_wakeup(&pdev->dev, false); free_irq(ts_dev->irq, ts_dev); /* total steps followed by the enable mask */ steps = 2 * ts_dev->coordinate_readouts + 2; steps = (1 << steps) - 1; am335x_tsc_se_clr(ts_dev->mfd_tscadc, steps); input_unregister_device(ts_dev->input); kfree(ts_dev); return 0; } static int titsc_suspend(struct device *dev) { struct titsc *ts_dev = dev_get_drvdata(dev); unsigned int idle; if (device_may_wakeup(dev)) { titsc_writel(ts_dev, REG_IRQSTATUS, TSC_IRQENB_MASK); idle = titsc_readl(ts_dev, REG_IRQENABLE); titsc_writel(ts_dev, REG_IRQENABLE, (idle | IRQENB_HW_PEN)); titsc_writel(ts_dev, REG_IRQWAKEUP, IRQWKUP_ENB); } return 0; } static int titsc_resume(struct device *dev) { struct titsc *ts_dev = dev_get_drvdata(dev); if (device_may_wakeup(dev)) { titsc_writel(ts_dev, REG_IRQWAKEUP, 0x00); titsc_writel(ts_dev, REG_IRQCLR, IRQENB_HW_PEN); pm_relax(dev); } titsc_step_config(ts_dev); titsc_writel(ts_dev, REG_FIFO0THR, ts_dev->coordinate_readouts * 2 + 2 - 1); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(titsc_pm_ops, titsc_suspend, titsc_resume); static const struct of_device_id ti_tsc_dt_ids[] = { { .compatible = "ti,am3359-tsc", }, { } }; MODULE_DEVICE_TABLE(of, ti_tsc_dt_ids); static struct platform_driver ti_tsc_driver = { .probe = titsc_probe, .remove = titsc_remove, .driver = { .name = "TI-am335x-tsc", .pm = pm_sleep_ptr(&titsc_pm_ops), .of_match_table = ti_tsc_dt_ids, }, }; module_platform_driver(ti_tsc_driver); MODULE_DESCRIPTION("TI touchscreen controller driver"); MODULE_AUTHOR("Rachna Patil <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/ti_am335x_tsc.c
// SPDX-License-Identifier: GPL-2.0-only /* * cyttsp4_core.c * Cypress TrueTouch(TM) Standard Product V4 Core driver module. * For use with Cypress Txx4xx parts. * Supported parts include: * TMA4XX * TMA1036 * * Copyright (C) 2012 Cypress Semiconductor * * Contact Cypress Semiconductor at www.cypress.com <[email protected]> */ #include "cyttsp4_core.h" #include <linux/delay.h> #include <linux/gpio.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/pm_runtime.h> #include <linux/sched.h> #include <linux/slab.h> /* Timeout in ms. */ #define CY_CORE_REQUEST_EXCLUSIVE_TIMEOUT 500 #define CY_CORE_SLEEP_REQUEST_EXCLUSIVE_TIMEOUT 5000 #define CY_CORE_MODE_CHANGE_TIMEOUT 1000 #define CY_CORE_RESET_AND_WAIT_TIMEOUT 500 #define CY_CORE_WAKEUP_TIMEOUT 500 #define CY_CORE_STARTUP_RETRY_COUNT 3 static const char * const cyttsp4_tch_abs_string[] = { [CY_TCH_X] = "X", [CY_TCH_Y] = "Y", [CY_TCH_P] = "P", [CY_TCH_T] = "T", [CY_TCH_E] = "E", [CY_TCH_O] = "O", [CY_TCH_W] = "W", [CY_TCH_MAJ] = "MAJ", [CY_TCH_MIN] = "MIN", [CY_TCH_OR] = "OR", [CY_TCH_NUM_ABS] = "INVALID" }; static const u8 ldr_exit[] = { 0xFF, 0x01, 0x3B, 0x00, 0x00, 0x4F, 0x6D, 0x17 }; static const u8 ldr_err_app[] = { 0x01, 0x02, 0x00, 0x00, 0x55, 0xDD, 0x17 }; static inline size_t merge_bytes(u8 high, u8 low) { return (high << 8) + low; } #ifdef VERBOSE_DEBUG static void cyttsp4_pr_buf(struct device *dev, u8 *pr_buf, u8 *dptr, int size, const char *data_name) { int i, k; const char fmt[] = "%02X "; int max; if (!size) return; max = (CY_MAX_PRBUF_SIZE - 1) - sizeof(CY_PR_TRUNCATED); pr_buf[0] = 0; for (i = k = 0; i < size && k < max; i++, k += 3) scnprintf(pr_buf + k, CY_MAX_PRBUF_SIZE, fmt, dptr[i]); dev_vdbg(dev, "%s: %s[0..%d]=%s%s\n", __func__, data_name, size - 1, pr_buf, size <= max ? "" : CY_PR_TRUNCATED); } #else #define cyttsp4_pr_buf(dev, pr_buf, dptr, size, data_name) do { } while (0) #endif static int cyttsp4_load_status_regs(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; struct device *dev = cd->dev; int rc; rc = cyttsp4_adap_read(cd, CY_REG_BASE, si->si_ofs.mode_size, si->xy_mode); if (rc < 0) dev_err(dev, "%s: fail read mode regs r=%d\n", __func__, rc); else cyttsp4_pr_buf(dev, cd->pr_buf, si->xy_mode, si->si_ofs.mode_size, "xy_mode"); return rc; } static int cyttsp4_handshake(struct cyttsp4 *cd, u8 mode) { u8 cmd = mode ^ CY_HST_TOGGLE; int rc; /* * Mode change issued, handshaking now will cause endless mode change * requests, for sync mode modechange will do same with handshake * */ if (mode & CY_HST_MODE_CHANGE) return 0; rc = cyttsp4_adap_write(cd, CY_REG_BASE, sizeof(cmd), &cmd); if (rc < 0) dev_err(cd->dev, "%s: bus write fail on handshake (ret=%d)\n", __func__, rc); return rc; } static int cyttsp4_hw_soft_reset(struct cyttsp4 *cd) { u8 cmd = CY_HST_RESET; int rc = cyttsp4_adap_write(cd, CY_REG_BASE, sizeof(cmd), &cmd); if (rc < 0) { dev_err(cd->dev, "%s: FAILED to execute SOFT reset\n", __func__); return rc; } return 0; } static int cyttsp4_hw_hard_reset(struct cyttsp4 *cd) { if (cd->cpdata->xres) { cd->cpdata->xres(cd->cpdata, cd->dev); dev_dbg(cd->dev, "%s: execute HARD reset\n", __func__); return 0; } dev_err(cd->dev, "%s: FAILED to execute HARD reset\n", __func__); return -ENOSYS; } static int cyttsp4_hw_reset(struct cyttsp4 *cd) { int rc = cyttsp4_hw_hard_reset(cd); if (rc == -ENOSYS) rc = cyttsp4_hw_soft_reset(cd); return rc; } /* * Gets number of bits for a touch filed as parameter, * sets maximum value for field which is used as bit mask * and returns number of bytes required for that field */ static int cyttsp4_bits_2_bytes(unsigned int nbits, size_t *max) { *max = 1UL << nbits; return (nbits + 7) / 8; } static int cyttsp4_si_data_offsets(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; int rc = cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(si->si_data), &si->si_data); if (rc < 0) { dev_err(cd->dev, "%s: fail read sysinfo data offsets r=%d\n", __func__, rc); return rc; } /* Print sysinfo data offsets */ cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)&si->si_data, sizeof(si->si_data), "sysinfo_data_offsets"); /* convert sysinfo data offset bytes into integers */ si->si_ofs.map_sz = merge_bytes(si->si_data.map_szh, si->si_data.map_szl); si->si_ofs.map_sz = merge_bytes(si->si_data.map_szh, si->si_data.map_szl); si->si_ofs.cydata_ofs = merge_bytes(si->si_data.cydata_ofsh, si->si_data.cydata_ofsl); si->si_ofs.test_ofs = merge_bytes(si->si_data.test_ofsh, si->si_data.test_ofsl); si->si_ofs.pcfg_ofs = merge_bytes(si->si_data.pcfg_ofsh, si->si_data.pcfg_ofsl); si->si_ofs.opcfg_ofs = merge_bytes(si->si_data.opcfg_ofsh, si->si_data.opcfg_ofsl); si->si_ofs.ddata_ofs = merge_bytes(si->si_data.ddata_ofsh, si->si_data.ddata_ofsl); si->si_ofs.mdata_ofs = merge_bytes(si->si_data.mdata_ofsh, si->si_data.mdata_ofsl); return rc; } static int cyttsp4_si_get_cydata(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; int read_offset; int mfgid_sz, calc_mfgid_sz; void *p; int rc; if (si->si_ofs.test_ofs <= si->si_ofs.cydata_ofs) { dev_err(cd->dev, "%s: invalid offset test_ofs: %zu, cydata_ofs: %zu\n", __func__, si->si_ofs.test_ofs, si->si_ofs.cydata_ofs); return -EINVAL; } si->si_ofs.cydata_size = si->si_ofs.test_ofs - si->si_ofs.cydata_ofs; dev_dbg(cd->dev, "%s: cydata size: %zd\n", __func__, si->si_ofs.cydata_size); p = krealloc(si->si_ptrs.cydata, si->si_ofs.cydata_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: failed to allocate cydata memory\n", __func__); return -ENOMEM; } si->si_ptrs.cydata = p; read_offset = si->si_ofs.cydata_ofs; /* Read the CYDA registers up to MFGID field */ rc = cyttsp4_adap_read(cd, read_offset, offsetof(struct cyttsp4_cydata, mfgid_sz) + sizeof(si->si_ptrs.cydata->mfgid_sz), si->si_ptrs.cydata); if (rc < 0) { dev_err(cd->dev, "%s: fail read cydata r=%d\n", __func__, rc); return rc; } /* Check MFGID size */ mfgid_sz = si->si_ptrs.cydata->mfgid_sz; calc_mfgid_sz = si->si_ofs.cydata_size - sizeof(struct cyttsp4_cydata); if (mfgid_sz != calc_mfgid_sz) { dev_err(cd->dev, "%s: mismatch in MFGID size, reported:%d calculated:%d\n", __func__, mfgid_sz, calc_mfgid_sz); return -EINVAL; } read_offset += offsetof(struct cyttsp4_cydata, mfgid_sz) + sizeof(si->si_ptrs.cydata->mfgid_sz); /* Read the CYDA registers for MFGID field */ rc = cyttsp4_adap_read(cd, read_offset, si->si_ptrs.cydata->mfgid_sz, si->si_ptrs.cydata->mfg_id); if (rc < 0) { dev_err(cd->dev, "%s: fail read cydata r=%d\n", __func__, rc); return rc; } read_offset += si->si_ptrs.cydata->mfgid_sz; /* Read the rest of the CYDA registers */ rc = cyttsp4_adap_read(cd, read_offset, sizeof(struct cyttsp4_cydata) - offsetof(struct cyttsp4_cydata, cyito_idh), &si->si_ptrs.cydata->cyito_idh); if (rc < 0) { dev_err(cd->dev, "%s: fail read cydata r=%d\n", __func__, rc); return rc; } cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.cydata, si->si_ofs.cydata_size, "sysinfo_cydata"); return rc; } static int cyttsp4_si_get_test_data(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; void *p; int rc; if (si->si_ofs.pcfg_ofs <= si->si_ofs.test_ofs) { dev_err(cd->dev, "%s: invalid offset pcfg_ofs: %zu, test_ofs: %zu\n", __func__, si->si_ofs.pcfg_ofs, si->si_ofs.test_ofs); return -EINVAL; } si->si_ofs.test_size = si->si_ofs.pcfg_ofs - si->si_ofs.test_ofs; p = krealloc(si->si_ptrs.test, si->si_ofs.test_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: failed to allocate test memory\n", __func__); return -ENOMEM; } si->si_ptrs.test = p; rc = cyttsp4_adap_read(cd, si->si_ofs.test_ofs, si->si_ofs.test_size, si->si_ptrs.test); if (rc < 0) { dev_err(cd->dev, "%s: fail read test data r=%d\n", __func__, rc); return rc; } cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.test, si->si_ofs.test_size, "sysinfo_test_data"); if (si->si_ptrs.test->post_codel & CY_POST_CODEL_WDG_RST) dev_info(cd->dev, "%s: %s codel=%02X\n", __func__, "Reset was a WATCHDOG RESET", si->si_ptrs.test->post_codel); if (!(si->si_ptrs.test->post_codel & CY_POST_CODEL_CFG_DATA_CRC_FAIL)) dev_info(cd->dev, "%s: %s codel=%02X\n", __func__, "Config Data CRC FAIL", si->si_ptrs.test->post_codel); if (!(si->si_ptrs.test->post_codel & CY_POST_CODEL_PANEL_TEST_FAIL)) dev_info(cd->dev, "%s: %s codel=%02X\n", __func__, "PANEL TEST FAIL", si->si_ptrs.test->post_codel); dev_info(cd->dev, "%s: SCANNING is %s codel=%02X\n", __func__, si->si_ptrs.test->post_codel & 0x08 ? "ENABLED" : "DISABLED", si->si_ptrs.test->post_codel); return rc; } static int cyttsp4_si_get_pcfg_data(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; void *p; int rc; if (si->si_ofs.opcfg_ofs <= si->si_ofs.pcfg_ofs) { dev_err(cd->dev, "%s: invalid offset opcfg_ofs: %zu, pcfg_ofs: %zu\n", __func__, si->si_ofs.opcfg_ofs, si->si_ofs.pcfg_ofs); return -EINVAL; } si->si_ofs.pcfg_size = si->si_ofs.opcfg_ofs - si->si_ofs.pcfg_ofs; p = krealloc(si->si_ptrs.pcfg, si->si_ofs.pcfg_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: failed to allocate pcfg memory\n", __func__); return -ENOMEM; } si->si_ptrs.pcfg = p; rc = cyttsp4_adap_read(cd, si->si_ofs.pcfg_ofs, si->si_ofs.pcfg_size, si->si_ptrs.pcfg); if (rc < 0) { dev_err(cd->dev, "%s: fail read pcfg data r=%d\n", __func__, rc); return rc; } si->si_ofs.max_x = merge_bytes((si->si_ptrs.pcfg->res_xh & CY_PCFG_RESOLUTION_X_MASK), si->si_ptrs.pcfg->res_xl); si->si_ofs.x_origin = !!(si->si_ptrs.pcfg->res_xh & CY_PCFG_ORIGIN_X_MASK); si->si_ofs.max_y = merge_bytes((si->si_ptrs.pcfg->res_yh & CY_PCFG_RESOLUTION_Y_MASK), si->si_ptrs.pcfg->res_yl); si->si_ofs.y_origin = !!(si->si_ptrs.pcfg->res_yh & CY_PCFG_ORIGIN_Y_MASK); si->si_ofs.max_p = merge_bytes(si->si_ptrs.pcfg->max_zh, si->si_ptrs.pcfg->max_zl); cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.pcfg, si->si_ofs.pcfg_size, "sysinfo_pcfg_data"); return rc; } static int cyttsp4_si_get_opcfg_data(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; struct cyttsp4_tch_abs_params *tch; struct cyttsp4_tch_rec_params *tch_old, *tch_new; enum cyttsp4_tch_abs abs; int i; void *p; int rc; if (si->si_ofs.ddata_ofs <= si->si_ofs.opcfg_ofs) { dev_err(cd->dev, "%s: invalid offset ddata_ofs: %zu, opcfg_ofs: %zu\n", __func__, si->si_ofs.ddata_ofs, si->si_ofs.opcfg_ofs); return -EINVAL; } si->si_ofs.opcfg_size = si->si_ofs.ddata_ofs - si->si_ofs.opcfg_ofs; p = krealloc(si->si_ptrs.opcfg, si->si_ofs.opcfg_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: failed to allocate opcfg memory\n", __func__); return -ENOMEM; } si->si_ptrs.opcfg = p; rc = cyttsp4_adap_read(cd, si->si_ofs.opcfg_ofs, si->si_ofs.opcfg_size, si->si_ptrs.opcfg); if (rc < 0) { dev_err(cd->dev, "%s: fail read opcfg data r=%d\n", __func__, rc); return rc; } si->si_ofs.cmd_ofs = si->si_ptrs.opcfg->cmd_ofs; si->si_ofs.rep_ofs = si->si_ptrs.opcfg->rep_ofs; si->si_ofs.rep_sz = (si->si_ptrs.opcfg->rep_szh * 256) + si->si_ptrs.opcfg->rep_szl; si->si_ofs.num_btns = si->si_ptrs.opcfg->num_btns; si->si_ofs.num_btn_regs = (si->si_ofs.num_btns + CY_NUM_BTN_PER_REG - 1) / CY_NUM_BTN_PER_REG; si->si_ofs.tt_stat_ofs = si->si_ptrs.opcfg->tt_stat_ofs; si->si_ofs.obj_cfg0 = si->si_ptrs.opcfg->obj_cfg0; si->si_ofs.max_tchs = si->si_ptrs.opcfg->max_tchs & CY_BYTE_OFS_MASK; si->si_ofs.tch_rec_size = si->si_ptrs.opcfg->tch_rec_size & CY_BYTE_OFS_MASK; /* Get the old touch fields */ for (abs = CY_TCH_X; abs < CY_NUM_TCH_FIELDS; abs++) { tch = &si->si_ofs.tch_abs[abs]; tch_old = &si->si_ptrs.opcfg->tch_rec_old[abs]; tch->ofs = tch_old->loc & CY_BYTE_OFS_MASK; tch->size = cyttsp4_bits_2_bytes(tch_old->size, &tch->max); tch->bofs = (tch_old->loc & CY_BOFS_MASK) >> CY_BOFS_SHIFT; } /* button fields */ si->si_ofs.btn_rec_size = si->si_ptrs.opcfg->btn_rec_size; si->si_ofs.btn_diff_ofs = si->si_ptrs.opcfg->btn_diff_ofs; si->si_ofs.btn_diff_size = si->si_ptrs.opcfg->btn_diff_size; if (si->si_ofs.tch_rec_size > CY_TMA1036_TCH_REC_SIZE) { /* Get the extended touch fields */ for (i = 0; i < CY_NUM_EXT_TCH_FIELDS; abs++, i++) { tch = &si->si_ofs.tch_abs[abs]; tch_new = &si->si_ptrs.opcfg->tch_rec_new[i]; tch->ofs = tch_new->loc & CY_BYTE_OFS_MASK; tch->size = cyttsp4_bits_2_bytes(tch_new->size, &tch->max); tch->bofs = (tch_new->loc & CY_BOFS_MASK) >> CY_BOFS_SHIFT; } } for (abs = 0; abs < CY_TCH_NUM_ABS; abs++) { dev_dbg(cd->dev, "%s: tch_rec_%s\n", __func__, cyttsp4_tch_abs_string[abs]); dev_dbg(cd->dev, "%s: ofs =%2zd\n", __func__, si->si_ofs.tch_abs[abs].ofs); dev_dbg(cd->dev, "%s: siz =%2zd\n", __func__, si->si_ofs.tch_abs[abs].size); dev_dbg(cd->dev, "%s: max =%2zd\n", __func__, si->si_ofs.tch_abs[abs].max); dev_dbg(cd->dev, "%s: bofs=%2zd\n", __func__, si->si_ofs.tch_abs[abs].bofs); } si->si_ofs.mode_size = si->si_ofs.tt_stat_ofs + 1; si->si_ofs.data_size = si->si_ofs.max_tchs * si->si_ptrs.opcfg->tch_rec_size; cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.opcfg, si->si_ofs.opcfg_size, "sysinfo_opcfg_data"); return 0; } static int cyttsp4_si_get_ddata(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; void *p; int rc; si->si_ofs.ddata_size = si->si_ofs.mdata_ofs - si->si_ofs.ddata_ofs; p = krealloc(si->si_ptrs.ddata, si->si_ofs.ddata_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: fail alloc ddata memory\n", __func__); return -ENOMEM; } si->si_ptrs.ddata = p; rc = cyttsp4_adap_read(cd, si->si_ofs.ddata_ofs, si->si_ofs.ddata_size, si->si_ptrs.ddata); if (rc < 0) dev_err(cd->dev, "%s: fail read ddata data r=%d\n", __func__, rc); else cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.ddata, si->si_ofs.ddata_size, "sysinfo_ddata"); return rc; } static int cyttsp4_si_get_mdata(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; void *p; int rc; si->si_ofs.mdata_size = si->si_ofs.map_sz - si->si_ofs.mdata_ofs; p = krealloc(si->si_ptrs.mdata, si->si_ofs.mdata_size, GFP_KERNEL); if (p == NULL) { dev_err(cd->dev, "%s: fail alloc mdata memory\n", __func__); return -ENOMEM; } si->si_ptrs.mdata = p; rc = cyttsp4_adap_read(cd, si->si_ofs.mdata_ofs, si->si_ofs.mdata_size, si->si_ptrs.mdata); if (rc < 0) dev_err(cd->dev, "%s: fail read mdata data r=%d\n", __func__, rc); else cyttsp4_pr_buf(cd->dev, cd->pr_buf, (u8 *)si->si_ptrs.mdata, si->si_ofs.mdata_size, "sysinfo_mdata"); return rc; } static int cyttsp4_si_get_btn_data(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; int btn; int num_defined_keys; u16 *key_table; void *p; int rc = 0; if (si->si_ofs.num_btns) { si->si_ofs.btn_keys_size = si->si_ofs.num_btns * sizeof(struct cyttsp4_btn); p = krealloc(si->btn, si->si_ofs.btn_keys_size, GFP_KERNEL|__GFP_ZERO); if (p == NULL) { dev_err(cd->dev, "%s: %s\n", __func__, "fail alloc btn_keys memory"); return -ENOMEM; } si->btn = p; if (cd->cpdata->sett[CY_IC_GRPNUM_BTN_KEYS] == NULL) num_defined_keys = 0; else if (cd->cpdata->sett[CY_IC_GRPNUM_BTN_KEYS]->data == NULL) num_defined_keys = 0; else num_defined_keys = cd->cpdata->sett [CY_IC_GRPNUM_BTN_KEYS]->size; for (btn = 0; btn < si->si_ofs.num_btns && btn < num_defined_keys; btn++) { key_table = (u16 *)cd->cpdata->sett [CY_IC_GRPNUM_BTN_KEYS]->data; si->btn[btn].key_code = key_table[btn]; si->btn[btn].state = CY_BTN_RELEASED; si->btn[btn].enabled = true; } for (; btn < si->si_ofs.num_btns; btn++) { si->btn[btn].key_code = KEY_RESERVED; si->btn[btn].state = CY_BTN_RELEASED; si->btn[btn].enabled = true; } return rc; } si->si_ofs.btn_keys_size = 0; kfree(si->btn); si->btn = NULL; return rc; } static int cyttsp4_si_get_op_data_ptrs(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; void *p; p = krealloc(si->xy_mode, si->si_ofs.mode_size, GFP_KERNEL|__GFP_ZERO); if (p == NULL) return -ENOMEM; si->xy_mode = p; p = krealloc(si->xy_data, si->si_ofs.data_size, GFP_KERNEL|__GFP_ZERO); if (p == NULL) return -ENOMEM; si->xy_data = p; p = krealloc(si->btn_rec_data, si->si_ofs.btn_rec_size * si->si_ofs.num_btns, GFP_KERNEL|__GFP_ZERO); if (p == NULL) return -ENOMEM; si->btn_rec_data = p; return 0; } static void cyttsp4_si_put_log_data(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; dev_dbg(cd->dev, "%s: cydata_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.cydata_ofs, si->si_ofs.cydata_size); dev_dbg(cd->dev, "%s: test_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.test_ofs, si->si_ofs.test_size); dev_dbg(cd->dev, "%s: pcfg_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.pcfg_ofs, si->si_ofs.pcfg_size); dev_dbg(cd->dev, "%s: opcfg_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.opcfg_ofs, si->si_ofs.opcfg_size); dev_dbg(cd->dev, "%s: ddata_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.ddata_ofs, si->si_ofs.ddata_size); dev_dbg(cd->dev, "%s: mdata_ofs =%4zd siz=%4zd\n", __func__, si->si_ofs.mdata_ofs, si->si_ofs.mdata_size); dev_dbg(cd->dev, "%s: cmd_ofs =%4zd\n", __func__, si->si_ofs.cmd_ofs); dev_dbg(cd->dev, "%s: rep_ofs =%4zd\n", __func__, si->si_ofs.rep_ofs); dev_dbg(cd->dev, "%s: rep_sz =%4zd\n", __func__, si->si_ofs.rep_sz); dev_dbg(cd->dev, "%s: num_btns =%4zd\n", __func__, si->si_ofs.num_btns); dev_dbg(cd->dev, "%s: num_btn_regs =%4zd\n", __func__, si->si_ofs.num_btn_regs); dev_dbg(cd->dev, "%s: tt_stat_ofs =%4zd\n", __func__, si->si_ofs.tt_stat_ofs); dev_dbg(cd->dev, "%s: tch_rec_size =%4zd\n", __func__, si->si_ofs.tch_rec_size); dev_dbg(cd->dev, "%s: max_tchs =%4zd\n", __func__, si->si_ofs.max_tchs); dev_dbg(cd->dev, "%s: mode_size =%4zd\n", __func__, si->si_ofs.mode_size); dev_dbg(cd->dev, "%s: data_size =%4zd\n", __func__, si->si_ofs.data_size); dev_dbg(cd->dev, "%s: map_sz =%4zd\n", __func__, si->si_ofs.map_sz); dev_dbg(cd->dev, "%s: btn_rec_size =%2zd\n", __func__, si->si_ofs.btn_rec_size); dev_dbg(cd->dev, "%s: btn_diff_ofs =%2zd\n", __func__, si->si_ofs.btn_diff_ofs); dev_dbg(cd->dev, "%s: btn_diff_size =%2zd\n", __func__, si->si_ofs.btn_diff_size); dev_dbg(cd->dev, "%s: max_x = 0x%04zX (%zd)\n", __func__, si->si_ofs.max_x, si->si_ofs.max_x); dev_dbg(cd->dev, "%s: x_origin = %zd (%s)\n", __func__, si->si_ofs.x_origin, si->si_ofs.x_origin == CY_NORMAL_ORIGIN ? "left corner" : "right corner"); dev_dbg(cd->dev, "%s: max_y = 0x%04zX (%zd)\n", __func__, si->si_ofs.max_y, si->si_ofs.max_y); dev_dbg(cd->dev, "%s: y_origin = %zd (%s)\n", __func__, si->si_ofs.y_origin, si->si_ofs.y_origin == CY_NORMAL_ORIGIN ? "upper corner" : "lower corner"); dev_dbg(cd->dev, "%s: max_p = 0x%04zX (%zd)\n", __func__, si->si_ofs.max_p, si->si_ofs.max_p); dev_dbg(cd->dev, "%s: xy_mode=%p xy_data=%p\n", __func__, si->xy_mode, si->xy_data); } static int cyttsp4_get_sysinfo_regs(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; int rc; rc = cyttsp4_si_data_offsets(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_cydata(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_test_data(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_pcfg_data(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_opcfg_data(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_ddata(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_mdata(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_btn_data(cd); if (rc < 0) return rc; rc = cyttsp4_si_get_op_data_ptrs(cd); if (rc < 0) { dev_err(cd->dev, "%s: failed to get_op_data\n", __func__); return rc; } cyttsp4_si_put_log_data(cd); /* provide flow control handshake */ rc = cyttsp4_handshake(cd, si->si_data.hst_mode); if (rc < 0) dev_err(cd->dev, "%s: handshake fail on sysinfo reg\n", __func__); si->ready = true; return rc; } static void cyttsp4_queue_startup_(struct cyttsp4 *cd) { if (cd->startup_state == STARTUP_NONE) { cd->startup_state = STARTUP_QUEUED; schedule_work(&cd->startup_work); dev_dbg(cd->dev, "%s: cyttsp4_startup queued\n", __func__); } else { dev_dbg(cd->dev, "%s: startup_state = %d\n", __func__, cd->startup_state); } } static void cyttsp4_report_slot_liftoff(struct cyttsp4_mt_data *md, int max_slots) { int t; if (md->num_prv_tch == 0) return; for (t = 0; t < max_slots; t++) { input_mt_slot(md->input, t); input_mt_report_slot_inactive(md->input); } } static void cyttsp4_lift_all(struct cyttsp4_mt_data *md) { if (!md->si) return; if (md->num_prv_tch != 0) { cyttsp4_report_slot_liftoff(md, md->si->si_ofs.tch_abs[CY_TCH_T].max); input_sync(md->input); md->num_prv_tch = 0; } } static void cyttsp4_get_touch_axis(struct cyttsp4_mt_data *md, int *axis, int size, int max, u8 *xy_data, int bofs) { int nbyte; int next; for (nbyte = 0, *axis = 0, next = 0; nbyte < size; nbyte++) { dev_vdbg(&md->input->dev, "%s: *axis=%02X(%d) size=%d max=%08X xy_data=%p" " xy_data[%d]=%02X(%d) bofs=%d\n", __func__, *axis, *axis, size, max, xy_data, next, xy_data[next], xy_data[next], bofs); *axis = (*axis * 256) + (xy_data[next] >> bofs); next++; } *axis &= max - 1; dev_vdbg(&md->input->dev, "%s: *axis=%02X(%d) size=%d max=%08X xy_data=%p" " xy_data[%d]=%02X(%d)\n", __func__, *axis, *axis, size, max, xy_data, next, xy_data[next], xy_data[next]); } static void cyttsp4_get_touch(struct cyttsp4_mt_data *md, struct cyttsp4_touch *touch, u8 *xy_data) { struct device *dev = &md->input->dev; struct cyttsp4_sysinfo *si = md->si; enum cyttsp4_tch_abs abs; bool flipped; for (abs = CY_TCH_X; abs < CY_TCH_NUM_ABS; abs++) { cyttsp4_get_touch_axis(md, &touch->abs[abs], si->si_ofs.tch_abs[abs].size, si->si_ofs.tch_abs[abs].max, xy_data + si->si_ofs.tch_abs[abs].ofs, si->si_ofs.tch_abs[abs].bofs); dev_vdbg(dev, "%s: get %s=%04X(%d)\n", __func__, cyttsp4_tch_abs_string[abs], touch->abs[abs], touch->abs[abs]); } if (md->pdata->flags & CY_FLAG_FLIP) { swap(touch->abs[CY_TCH_X], touch->abs[CY_TCH_Y]); flipped = true; } else flipped = false; if (md->pdata->flags & CY_FLAG_INV_X) { if (flipped) touch->abs[CY_TCH_X] = md->si->si_ofs.max_y - touch->abs[CY_TCH_X]; else touch->abs[CY_TCH_X] = md->si->si_ofs.max_x - touch->abs[CY_TCH_X]; } if (md->pdata->flags & CY_FLAG_INV_Y) { if (flipped) touch->abs[CY_TCH_Y] = md->si->si_ofs.max_x - touch->abs[CY_TCH_Y]; else touch->abs[CY_TCH_Y] = md->si->si_ofs.max_y - touch->abs[CY_TCH_Y]; } dev_vdbg(dev, "%s: flip=%s inv-x=%s inv-y=%s x=%04X(%d) y=%04X(%d)\n", __func__, flipped ? "true" : "false", md->pdata->flags & CY_FLAG_INV_X ? "true" : "false", md->pdata->flags & CY_FLAG_INV_Y ? "true" : "false", touch->abs[CY_TCH_X], touch->abs[CY_TCH_X], touch->abs[CY_TCH_Y], touch->abs[CY_TCH_Y]); } static void cyttsp4_final_sync(struct input_dev *input, int max_slots, int *ids) { int t; for (t = 0; t < max_slots; t++) { if (ids[t]) continue; input_mt_slot(input, t); input_mt_report_slot_inactive(input); } input_sync(input); } static void cyttsp4_get_mt_touches(struct cyttsp4_mt_data *md, int num_cur_tch) { struct device *dev = &md->input->dev; struct cyttsp4_sysinfo *si = md->si; struct cyttsp4_touch tch; int sig; int i, j, t = 0; int ids[max(CY_TMA1036_MAX_TCH, CY_TMA4XX_MAX_TCH)]; memset(ids, 0, si->si_ofs.tch_abs[CY_TCH_T].max * sizeof(int)); for (i = 0; i < num_cur_tch; i++) { cyttsp4_get_touch(md, &tch, si->xy_data + (i * si->si_ofs.tch_rec_size)); if ((tch.abs[CY_TCH_T] < md->pdata->frmwrk->abs [(CY_ABS_ID_OST * CY_NUM_ABS_SET) + CY_MIN_OST]) || (tch.abs[CY_TCH_T] > md->pdata->frmwrk->abs [(CY_ABS_ID_OST * CY_NUM_ABS_SET) + CY_MAX_OST])) { dev_err(dev, "%s: tch=%d -> bad trk_id=%d max_id=%d\n", __func__, i, tch.abs[CY_TCH_T], md->pdata->frmwrk->abs[(CY_ABS_ID_OST * CY_NUM_ABS_SET) + CY_MAX_OST]); continue; } /* use 0 based track id's */ sig = md->pdata->frmwrk->abs [(CY_ABS_ID_OST * CY_NUM_ABS_SET) + 0]; if (sig != CY_IGNORE_VALUE) { t = tch.abs[CY_TCH_T] - md->pdata->frmwrk->abs [(CY_ABS_ID_OST * CY_NUM_ABS_SET) + CY_MIN_OST]; if (tch.abs[CY_TCH_E] == CY_EV_LIFTOFF) { dev_dbg(dev, "%s: t=%d e=%d lift-off\n", __func__, t, tch.abs[CY_TCH_E]); goto cyttsp4_get_mt_touches_pr_tch; } input_mt_slot(md->input, t); input_mt_report_slot_state(md->input, MT_TOOL_FINGER, true); ids[t] = true; } /* all devices: position and pressure fields */ for (j = 0; j <= CY_ABS_W_OST; j++) { sig = md->pdata->frmwrk->abs[((CY_ABS_X_OST + j) * CY_NUM_ABS_SET) + 0]; if (sig != CY_IGNORE_VALUE) input_report_abs(md->input, sig, tch.abs[CY_TCH_X + j]); } if (si->si_ofs.tch_rec_size > CY_TMA1036_TCH_REC_SIZE) { /* * TMA400 size and orientation fields: * if pressure is non-zero and major touch * signal is zero, then set major and minor touch * signals to minimum non-zero value */ if (tch.abs[CY_TCH_P] > 0 && tch.abs[CY_TCH_MAJ] == 0) tch.abs[CY_TCH_MAJ] = tch.abs[CY_TCH_MIN] = 1; /* Get the extended touch fields */ for (j = 0; j < CY_NUM_EXT_TCH_FIELDS; j++) { sig = md->pdata->frmwrk->abs [((CY_ABS_MAJ_OST + j) * CY_NUM_ABS_SET) + 0]; if (sig != CY_IGNORE_VALUE) input_report_abs(md->input, sig, tch.abs[CY_TCH_MAJ + j]); } } cyttsp4_get_mt_touches_pr_tch: if (si->si_ofs.tch_rec_size > CY_TMA1036_TCH_REC_SIZE) dev_dbg(dev, "%s: t=%d x=%d y=%d z=%d M=%d m=%d o=%d e=%d\n", __func__, t, tch.abs[CY_TCH_X], tch.abs[CY_TCH_Y], tch.abs[CY_TCH_P], tch.abs[CY_TCH_MAJ], tch.abs[CY_TCH_MIN], tch.abs[CY_TCH_OR], tch.abs[CY_TCH_E]); else dev_dbg(dev, "%s: t=%d x=%d y=%d z=%d e=%d\n", __func__, t, tch.abs[CY_TCH_X], tch.abs[CY_TCH_Y], tch.abs[CY_TCH_P], tch.abs[CY_TCH_E]); } cyttsp4_final_sync(md->input, si->si_ofs.tch_abs[CY_TCH_T].max, ids); md->num_prv_tch = num_cur_tch; return; } /* read xy_data for all current touches */ static int cyttsp4_xy_worker(struct cyttsp4 *cd) { struct cyttsp4_mt_data *md = &cd->md; struct device *dev = &md->input->dev; struct cyttsp4_sysinfo *si = md->si; u8 num_cur_tch; u8 hst_mode; u8 rep_len; u8 rep_stat; u8 tt_stat; int rc = 0; /* * Get event data from cyttsp4 device. * The event data includes all data * for all active touches. * Event data also includes button data */ /* * Use 2 reads: * 1st read to get mode + button bytes + touch count (core) * 2nd read (optional) to get touch 1 - touch n data */ hst_mode = si->xy_mode[CY_REG_BASE]; rep_len = si->xy_mode[si->si_ofs.rep_ofs]; rep_stat = si->xy_mode[si->si_ofs.rep_ofs + 1]; tt_stat = si->xy_mode[si->si_ofs.tt_stat_ofs]; dev_vdbg(dev, "%s: %s%02X %s%d %s%02X %s%02X\n", __func__, "hst_mode=", hst_mode, "rep_len=", rep_len, "rep_stat=", rep_stat, "tt_stat=", tt_stat); num_cur_tch = GET_NUM_TOUCHES(tt_stat); dev_vdbg(dev, "%s: num_cur_tch=%d\n", __func__, num_cur_tch); if (rep_len == 0 && num_cur_tch > 0) { dev_err(dev, "%s: report length error rep_len=%d num_tch=%d\n", __func__, rep_len, num_cur_tch); goto cyttsp4_xy_worker_exit; } /* read touches */ if (num_cur_tch > 0) { rc = cyttsp4_adap_read(cd, si->si_ofs.tt_stat_ofs + 1, num_cur_tch * si->si_ofs.tch_rec_size, si->xy_data); if (rc < 0) { dev_err(dev, "%s: read fail on touch regs r=%d\n", __func__, rc); goto cyttsp4_xy_worker_exit; } } /* print xy data */ cyttsp4_pr_buf(dev, cd->pr_buf, si->xy_data, num_cur_tch * si->si_ofs.tch_rec_size, "xy_data"); /* check any error conditions */ if (IS_BAD_PKT(rep_stat)) { dev_dbg(dev, "%s: Invalid buffer detected\n", __func__); rc = 0; goto cyttsp4_xy_worker_exit; } if (IS_LARGE_AREA(tt_stat)) dev_dbg(dev, "%s: Large area detected\n", __func__); if (num_cur_tch > si->si_ofs.max_tchs) { dev_err(dev, "%s: too many tch; set to max tch (n=%d c=%zd)\n", __func__, num_cur_tch, si->si_ofs.max_tchs); num_cur_tch = si->si_ofs.max_tchs; } /* extract xy_data for all currently reported touches */ dev_vdbg(dev, "%s: extract data num_cur_tch=%d\n", __func__, num_cur_tch); if (num_cur_tch) cyttsp4_get_mt_touches(md, num_cur_tch); else cyttsp4_lift_all(md); rc = 0; cyttsp4_xy_worker_exit: return rc; } static int cyttsp4_mt_attention(struct cyttsp4 *cd) { struct device *dev = cd->dev; struct cyttsp4_mt_data *md = &cd->md; int rc = 0; if (!md->si) return 0; mutex_lock(&md->report_lock); if (!md->is_suspended) { /* core handles handshake */ rc = cyttsp4_xy_worker(cd); } else { dev_vdbg(dev, "%s: Ignoring report while suspended\n", __func__); } mutex_unlock(&md->report_lock); if (rc < 0) dev_err(dev, "%s: xy_worker error r=%d\n", __func__, rc); return rc; } static irqreturn_t cyttsp4_irq(int irq, void *handle) { struct cyttsp4 *cd = handle; struct device *dev = cd->dev; enum cyttsp4_mode cur_mode; u8 cmd_ofs = cd->sysinfo.si_ofs.cmd_ofs; u8 mode[3]; int rc; /* * Check whether this IRQ should be ignored (external) * This should be the very first thing to check since * ignore_irq may be set for a very short period of time */ if (atomic_read(&cd->ignore_irq)) { dev_vdbg(dev, "%s: Ignoring IRQ\n", __func__); return IRQ_HANDLED; } dev_dbg(dev, "%s int:0x%x\n", __func__, cd->int_status); mutex_lock(&cd->system_lock); /* Just to debug */ if (cd->sleep_state == SS_SLEEP_ON || cd->sleep_state == SS_SLEEPING) dev_vdbg(dev, "%s: Received IRQ while in sleep\n", __func__); rc = cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(mode), mode); if (rc) { dev_err(cd->dev, "%s: Fail read adapter r=%d\n", __func__, rc); goto cyttsp4_irq_exit; } dev_vdbg(dev, "%s mode[0-2]:0x%X 0x%X 0x%X\n", __func__, mode[0], mode[1], mode[2]); if (IS_BOOTLOADER(mode[0], mode[1])) { cur_mode = CY_MODE_BOOTLOADER; dev_vdbg(dev, "%s: bl running\n", __func__); if (cd->mode == CY_MODE_BOOTLOADER) { /* Signal bootloader heartbeat heard */ wake_up(&cd->wait_q); goto cyttsp4_irq_exit; } /* switch to bootloader */ dev_dbg(dev, "%s: restart switch to bl m=%d -> m=%d\n", __func__, cd->mode, cur_mode); /* catch operation->bl glitch */ if (cd->mode != CY_MODE_UNKNOWN) { /* Incase startup_state do not let startup_() */ cd->mode = CY_MODE_UNKNOWN; cyttsp4_queue_startup_(cd); goto cyttsp4_irq_exit; } /* * do not wake thread on this switch since * it is possible to get an early heartbeat * prior to performing the reset */ cd->mode = cur_mode; goto cyttsp4_irq_exit; } switch (mode[0] & CY_HST_MODE) { case CY_HST_OPERATE: cur_mode = CY_MODE_OPERATIONAL; dev_vdbg(dev, "%s: operational\n", __func__); break; case CY_HST_CAT: cur_mode = CY_MODE_CAT; dev_vdbg(dev, "%s: CaT\n", __func__); break; case CY_HST_SYSINFO: cur_mode = CY_MODE_SYSINFO; dev_vdbg(dev, "%s: sysinfo\n", __func__); break; default: cur_mode = CY_MODE_UNKNOWN; dev_err(dev, "%s: unknown HST mode 0x%02X\n", __func__, mode[0]); break; } /* Check whether this IRQ should be ignored (internal) */ if (cd->int_status & CY_INT_IGNORE) { dev_vdbg(dev, "%s: Ignoring IRQ\n", __func__); goto cyttsp4_irq_exit; } /* Check for wake up interrupt */ if (cd->int_status & CY_INT_AWAKE) { cd->int_status &= ~CY_INT_AWAKE; wake_up(&cd->wait_q); dev_vdbg(dev, "%s: Received wake up interrupt\n", __func__); goto cyttsp4_irq_handshake; } /* Expecting mode change interrupt */ if ((cd->int_status & CY_INT_MODE_CHANGE) && (mode[0] & CY_HST_MODE_CHANGE) == 0) { cd->int_status &= ~CY_INT_MODE_CHANGE; dev_dbg(dev, "%s: finish mode switch m=%d -> m=%d\n", __func__, cd->mode, cur_mode); cd->mode = cur_mode; wake_up(&cd->wait_q); goto cyttsp4_irq_handshake; } /* compare current core mode to current device mode */ dev_vdbg(dev, "%s: cd->mode=%d cur_mode=%d\n", __func__, cd->mode, cur_mode); if ((mode[0] & CY_HST_MODE_CHANGE) == 0 && cd->mode != cur_mode) { /* Unexpected mode change occurred */ dev_err(dev, "%s %d->%d 0x%x\n", __func__, cd->mode, cur_mode, cd->int_status); dev_dbg(dev, "%s: Unexpected mode change, startup\n", __func__); cyttsp4_queue_startup_(cd); goto cyttsp4_irq_exit; } /* Expecting command complete interrupt */ dev_vdbg(dev, "%s: command byte:0x%x\n", __func__, mode[cmd_ofs]); if ((cd->int_status & CY_INT_EXEC_CMD) && mode[cmd_ofs] & CY_CMD_COMPLETE) { cd->int_status &= ~CY_INT_EXEC_CMD; dev_vdbg(dev, "%s: Received command complete interrupt\n", __func__); wake_up(&cd->wait_q); /* * It is possible to receive a single interrupt for * command complete and touch/button status report. * Continue processing for a possible status report. */ } /* This should be status report, read status regs */ if (cd->mode == CY_MODE_OPERATIONAL) { dev_vdbg(dev, "%s: Read status registers\n", __func__); rc = cyttsp4_load_status_regs(cd); if (rc < 0) dev_err(dev, "%s: fail read mode regs r=%d\n", __func__, rc); } cyttsp4_mt_attention(cd); cyttsp4_irq_handshake: /* handshake the event */ dev_vdbg(dev, "%s: Handshake mode=0x%02X r=%d\n", __func__, mode[0], rc); rc = cyttsp4_handshake(cd, mode[0]); if (rc < 0) dev_err(dev, "%s: Fail handshake mode=0x%02X r=%d\n", __func__, mode[0], rc); /* * a non-zero udelay period is required for using * IRQF_TRIGGER_LOW in order to delay until the * device completes isr deassert */ udelay(cd->cpdata->level_irq_udelay); cyttsp4_irq_exit: mutex_unlock(&cd->system_lock); return IRQ_HANDLED; } static void cyttsp4_start_wd_timer(struct cyttsp4 *cd) { if (!CY_WATCHDOG_TIMEOUT) return; mod_timer(&cd->watchdog_timer, jiffies + msecs_to_jiffies(CY_WATCHDOG_TIMEOUT)); } static void cyttsp4_stop_wd_timer(struct cyttsp4 *cd) { if (!CY_WATCHDOG_TIMEOUT) return; /* * Ensure we wait until the watchdog timer * running on a different CPU finishes */ timer_shutdown_sync(&cd->watchdog_timer); cancel_work_sync(&cd->watchdog_work); } static void cyttsp4_watchdog_timer(struct timer_list *t) { struct cyttsp4 *cd = from_timer(cd, t, watchdog_timer); dev_vdbg(cd->dev, "%s: Watchdog timer triggered\n", __func__); schedule_work(&cd->watchdog_work); return; } static int cyttsp4_request_exclusive(struct cyttsp4 *cd, void *ownptr, int timeout_ms) { int t = msecs_to_jiffies(timeout_ms); bool with_timeout = (timeout_ms != 0); mutex_lock(&cd->system_lock); if (!cd->exclusive_dev && cd->exclusive_waits == 0) { cd->exclusive_dev = ownptr; goto exit; } cd->exclusive_waits++; wait: mutex_unlock(&cd->system_lock); if (with_timeout) { t = wait_event_timeout(cd->wait_q, !cd->exclusive_dev, t); if (IS_TMO(t)) { dev_err(cd->dev, "%s: tmo waiting exclusive access\n", __func__); mutex_lock(&cd->system_lock); cd->exclusive_waits--; mutex_unlock(&cd->system_lock); return -ETIME; } } else { wait_event(cd->wait_q, !cd->exclusive_dev); } mutex_lock(&cd->system_lock); if (cd->exclusive_dev) goto wait; cd->exclusive_dev = ownptr; cd->exclusive_waits--; exit: mutex_unlock(&cd->system_lock); return 0; } /* * returns error if was not owned */ static int cyttsp4_release_exclusive(struct cyttsp4 *cd, void *ownptr) { mutex_lock(&cd->system_lock); if (cd->exclusive_dev != ownptr) { mutex_unlock(&cd->system_lock); return -EINVAL; } dev_vdbg(cd->dev, "%s: exclusive_dev %p freed\n", __func__, cd->exclusive_dev); cd->exclusive_dev = NULL; wake_up(&cd->wait_q); mutex_unlock(&cd->system_lock); return 0; } static int cyttsp4_wait_bl_heartbeat(struct cyttsp4 *cd) { long t; int rc = 0; /* wait heartbeat */ dev_vdbg(cd->dev, "%s: wait heartbeat...\n", __func__); t = wait_event_timeout(cd->wait_q, cd->mode == CY_MODE_BOOTLOADER, msecs_to_jiffies(CY_CORE_RESET_AND_WAIT_TIMEOUT)); if (IS_TMO(t)) { dev_err(cd->dev, "%s: tmo waiting bl heartbeat cd->mode=%d\n", __func__, cd->mode); rc = -ETIME; } return rc; } static int cyttsp4_wait_sysinfo_mode(struct cyttsp4 *cd) { long t; dev_vdbg(cd->dev, "%s: wait sysinfo...\n", __func__); t = wait_event_timeout(cd->wait_q, cd->mode == CY_MODE_SYSINFO, msecs_to_jiffies(CY_CORE_MODE_CHANGE_TIMEOUT)); if (IS_TMO(t)) { dev_err(cd->dev, "%s: tmo waiting exit bl cd->mode=%d\n", __func__, cd->mode); mutex_lock(&cd->system_lock); cd->int_status &= ~CY_INT_MODE_CHANGE; mutex_unlock(&cd->system_lock); return -ETIME; } return 0; } static int cyttsp4_reset_and_wait(struct cyttsp4 *cd) { int rc; /* reset hardware */ mutex_lock(&cd->system_lock); dev_dbg(cd->dev, "%s: reset hw...\n", __func__); rc = cyttsp4_hw_reset(cd); cd->mode = CY_MODE_UNKNOWN; mutex_unlock(&cd->system_lock); if (rc < 0) { dev_err(cd->dev, "%s:Fail hw reset r=%d\n", __func__, rc); return rc; } return cyttsp4_wait_bl_heartbeat(cd); } /* * returns err if refused or timeout; block until mode change complete * bit is set (mode change interrupt) */ static int cyttsp4_set_mode(struct cyttsp4 *cd, int new_mode) { u8 new_dev_mode; u8 mode; long t; int rc; switch (new_mode) { case CY_MODE_OPERATIONAL: new_dev_mode = CY_HST_OPERATE; break; case CY_MODE_SYSINFO: new_dev_mode = CY_HST_SYSINFO; break; case CY_MODE_CAT: new_dev_mode = CY_HST_CAT; break; default: dev_err(cd->dev, "%s: invalid mode: %02X(%d)\n", __func__, new_mode, new_mode); return -EINVAL; } /* change mode */ dev_dbg(cd->dev, "%s: %s=%p new_dev_mode=%02X new_mode=%d\n", __func__, "have exclusive", cd->exclusive_dev, new_dev_mode, new_mode); mutex_lock(&cd->system_lock); rc = cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(mode), &mode); if (rc < 0) { mutex_unlock(&cd->system_lock); dev_err(cd->dev, "%s: Fail read mode r=%d\n", __func__, rc); goto exit; } /* Clear device mode bits and set to new mode */ mode &= ~CY_HST_MODE; mode |= new_dev_mode | CY_HST_MODE_CHANGE; cd->int_status |= CY_INT_MODE_CHANGE; rc = cyttsp4_adap_write(cd, CY_REG_BASE, sizeof(mode), &mode); mutex_unlock(&cd->system_lock); if (rc < 0) { dev_err(cd->dev, "%s: Fail write mode change r=%d\n", __func__, rc); goto exit; } /* wait for mode change done interrupt */ t = wait_event_timeout(cd->wait_q, (cd->int_status & CY_INT_MODE_CHANGE) == 0, msecs_to_jiffies(CY_CORE_MODE_CHANGE_TIMEOUT)); dev_dbg(cd->dev, "%s: back from wait t=%ld cd->mode=%d\n", __func__, t, cd->mode); if (IS_TMO(t)) { dev_err(cd->dev, "%s: %s\n", __func__, "tmo waiting mode change"); mutex_lock(&cd->system_lock); cd->int_status &= ~CY_INT_MODE_CHANGE; mutex_unlock(&cd->system_lock); rc = -EINVAL; } exit: return rc; } static void cyttsp4_watchdog_work(struct work_struct *work) { struct cyttsp4 *cd = container_of(work, struct cyttsp4, watchdog_work); u8 *mode; int retval; mutex_lock(&cd->system_lock); retval = cyttsp4_load_status_regs(cd); if (retval < 0) { dev_err(cd->dev, "%s: failed to access device in watchdog timer r=%d\n", __func__, retval); cyttsp4_queue_startup_(cd); goto cyttsp4_timer_watchdog_exit_error; } mode = &cd->sysinfo.xy_mode[CY_REG_BASE]; if (IS_BOOTLOADER(mode[0], mode[1])) { dev_err(cd->dev, "%s: device found in bootloader mode when operational mode\n", __func__); cyttsp4_queue_startup_(cd); goto cyttsp4_timer_watchdog_exit_error; } cyttsp4_start_wd_timer(cd); cyttsp4_timer_watchdog_exit_error: mutex_unlock(&cd->system_lock); return; } static int cyttsp4_core_sleep_(struct cyttsp4 *cd) { enum cyttsp4_sleep_state ss = SS_SLEEP_ON; enum cyttsp4_int_state int_status = CY_INT_IGNORE; int rc = 0; u8 mode[2]; /* Already in sleep mode? */ mutex_lock(&cd->system_lock); if (cd->sleep_state == SS_SLEEP_ON) { mutex_unlock(&cd->system_lock); return 0; } cd->sleep_state = SS_SLEEPING; mutex_unlock(&cd->system_lock); cyttsp4_stop_wd_timer(cd); /* Wait until currently running IRQ handler exits and disable IRQ */ disable_irq(cd->irq); dev_vdbg(cd->dev, "%s: write DEEP SLEEP...\n", __func__); mutex_lock(&cd->system_lock); rc = cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(mode), &mode); if (rc) { mutex_unlock(&cd->system_lock); dev_err(cd->dev, "%s: Fail read adapter r=%d\n", __func__, rc); goto error; } if (IS_BOOTLOADER(mode[0], mode[1])) { mutex_unlock(&cd->system_lock); dev_err(cd->dev, "%s: Device in BOOTLOADER mode.\n", __func__); rc = -EINVAL; goto error; } mode[0] |= CY_HST_SLEEP; rc = cyttsp4_adap_write(cd, CY_REG_BASE, sizeof(mode[0]), &mode[0]); mutex_unlock(&cd->system_lock); if (rc) { dev_err(cd->dev, "%s: Fail write adapter r=%d\n", __func__, rc); goto error; } dev_vdbg(cd->dev, "%s: write DEEP SLEEP succeeded\n", __func__); if (cd->cpdata->power) { dev_dbg(cd->dev, "%s: Power down HW\n", __func__); rc = cd->cpdata->power(cd->cpdata, 0, cd->dev, &cd->ignore_irq); } else { dev_dbg(cd->dev, "%s: No power function\n", __func__); rc = 0; } if (rc < 0) { dev_err(cd->dev, "%s: HW Power down fails r=%d\n", __func__, rc); goto error; } /* Give time to FW to sleep */ msleep(50); goto exit; error: ss = SS_SLEEP_OFF; int_status = CY_INT_NONE; cyttsp4_start_wd_timer(cd); exit: mutex_lock(&cd->system_lock); cd->sleep_state = ss; cd->int_status |= int_status; mutex_unlock(&cd->system_lock); enable_irq(cd->irq); return rc; } static int cyttsp4_startup_(struct cyttsp4 *cd) { int retry = CY_CORE_STARTUP_RETRY_COUNT; int rc; cyttsp4_stop_wd_timer(cd); reset: if (retry != CY_CORE_STARTUP_RETRY_COUNT) dev_dbg(cd->dev, "%s: Retry %d\n", __func__, CY_CORE_STARTUP_RETRY_COUNT - retry); /* reset hardware and wait for heartbeat */ rc = cyttsp4_reset_and_wait(cd); if (rc < 0) { dev_err(cd->dev, "%s: Error on h/w reset r=%d\n", __func__, rc); if (retry--) goto reset; goto exit; } /* exit bl into sysinfo mode */ dev_vdbg(cd->dev, "%s: write exit ldr...\n", __func__); mutex_lock(&cd->system_lock); cd->int_status &= ~CY_INT_IGNORE; cd->int_status |= CY_INT_MODE_CHANGE; rc = cyttsp4_adap_write(cd, CY_REG_BASE, sizeof(ldr_exit), (u8 *)ldr_exit); mutex_unlock(&cd->system_lock); if (rc < 0) { dev_err(cd->dev, "%s: Fail write r=%d\n", __func__, rc); if (retry--) goto reset; goto exit; } rc = cyttsp4_wait_sysinfo_mode(cd); if (rc < 0) { u8 buf[sizeof(ldr_err_app)]; int rc1; /* Check for invalid/corrupted touch application */ rc1 = cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(ldr_err_app), buf); if (rc1) { dev_err(cd->dev, "%s: Fail read r=%d\n", __func__, rc1); } else if (!memcmp(buf, ldr_err_app, sizeof(ldr_err_app))) { dev_err(cd->dev, "%s: Error launching touch application\n", __func__); mutex_lock(&cd->system_lock); cd->invalid_touch_app = true; mutex_unlock(&cd->system_lock); goto exit_no_wd; } if (retry--) goto reset; goto exit; } mutex_lock(&cd->system_lock); cd->invalid_touch_app = false; mutex_unlock(&cd->system_lock); /* read sysinfo data */ dev_vdbg(cd->dev, "%s: get sysinfo regs..\n", __func__); rc = cyttsp4_get_sysinfo_regs(cd); if (rc < 0) { dev_err(cd->dev, "%s: failed to get sysinfo regs rc=%d\n", __func__, rc); if (retry--) goto reset; goto exit; } rc = cyttsp4_set_mode(cd, CY_MODE_OPERATIONAL); if (rc < 0) { dev_err(cd->dev, "%s: failed to set mode to operational rc=%d\n", __func__, rc); if (retry--) goto reset; goto exit; } cyttsp4_lift_all(&cd->md); /* restore to sleep if was suspended */ mutex_lock(&cd->system_lock); if (cd->sleep_state == SS_SLEEP_ON) { cd->sleep_state = SS_SLEEP_OFF; mutex_unlock(&cd->system_lock); cyttsp4_core_sleep_(cd); goto exit_no_wd; } mutex_unlock(&cd->system_lock); exit: cyttsp4_start_wd_timer(cd); exit_no_wd: return rc; } static int cyttsp4_startup(struct cyttsp4 *cd) { int rc; mutex_lock(&cd->system_lock); cd->startup_state = STARTUP_RUNNING; mutex_unlock(&cd->system_lock); rc = cyttsp4_request_exclusive(cd, cd->dev, CY_CORE_REQUEST_EXCLUSIVE_TIMEOUT); if (rc < 0) { dev_err(cd->dev, "%s: fail get exclusive ex=%p own=%p\n", __func__, cd->exclusive_dev, cd->dev); goto exit; } rc = cyttsp4_startup_(cd); if (cyttsp4_release_exclusive(cd, cd->dev) < 0) /* Don't return fail code, mode is already changed. */ dev_err(cd->dev, "%s: fail to release exclusive\n", __func__); else dev_vdbg(cd->dev, "%s: pass release exclusive\n", __func__); exit: mutex_lock(&cd->system_lock); cd->startup_state = STARTUP_NONE; mutex_unlock(&cd->system_lock); /* Wake the waiters for end of startup */ wake_up(&cd->wait_q); return rc; } static void cyttsp4_startup_work_function(struct work_struct *work) { struct cyttsp4 *cd = container_of(work, struct cyttsp4, startup_work); int rc; rc = cyttsp4_startup(cd); if (rc < 0) dev_err(cd->dev, "%s: Fail queued startup r=%d\n", __func__, rc); } static void cyttsp4_free_si_ptrs(struct cyttsp4 *cd) { struct cyttsp4_sysinfo *si = &cd->sysinfo; if (!si) return; kfree(si->si_ptrs.cydata); kfree(si->si_ptrs.test); kfree(si->si_ptrs.pcfg); kfree(si->si_ptrs.opcfg); kfree(si->si_ptrs.ddata); kfree(si->si_ptrs.mdata); kfree(si->btn); kfree(si->xy_mode); kfree(si->xy_data); kfree(si->btn_rec_data); } static int cyttsp4_core_sleep(struct cyttsp4 *cd) { int rc; rc = cyttsp4_request_exclusive(cd, cd->dev, CY_CORE_SLEEP_REQUEST_EXCLUSIVE_TIMEOUT); if (rc < 0) { dev_err(cd->dev, "%s: fail get exclusive ex=%p own=%p\n", __func__, cd->exclusive_dev, cd->dev); return 0; } rc = cyttsp4_core_sleep_(cd); if (cyttsp4_release_exclusive(cd, cd->dev) < 0) dev_err(cd->dev, "%s: fail to release exclusive\n", __func__); else dev_vdbg(cd->dev, "%s: pass release exclusive\n", __func__); return rc; } static int cyttsp4_core_wake_(struct cyttsp4 *cd) { struct device *dev = cd->dev; int rc; u8 mode; int t; /* Already woken? */ mutex_lock(&cd->system_lock); if (cd->sleep_state == SS_SLEEP_OFF) { mutex_unlock(&cd->system_lock); return 0; } cd->int_status &= ~CY_INT_IGNORE; cd->int_status |= CY_INT_AWAKE; cd->sleep_state = SS_WAKING; if (cd->cpdata->power) { dev_dbg(dev, "%s: Power up HW\n", __func__); rc = cd->cpdata->power(cd->cpdata, 1, dev, &cd->ignore_irq); } else { dev_dbg(dev, "%s: No power function\n", __func__); rc = -ENOSYS; } if (rc < 0) { dev_err(dev, "%s: HW Power up fails r=%d\n", __func__, rc); /* Initiate a read transaction to wake up */ cyttsp4_adap_read(cd, CY_REG_BASE, sizeof(mode), &mode); } else dev_vdbg(cd->dev, "%s: HW power up succeeds\n", __func__); mutex_unlock(&cd->system_lock); t = wait_event_timeout(cd->wait_q, (cd->int_status & CY_INT_AWAKE) == 0, msecs_to_jiffies(CY_CORE_WAKEUP_TIMEOUT)); if (IS_TMO(t)) { dev_err(dev, "%s: TMO waiting for wakeup\n", __func__); mutex_lock(&cd->system_lock); cd->int_status &= ~CY_INT_AWAKE; /* Try starting up */ cyttsp4_queue_startup_(cd); mutex_unlock(&cd->system_lock); } mutex_lock(&cd->system_lock); cd->sleep_state = SS_SLEEP_OFF; mutex_unlock(&cd->system_lock); cyttsp4_start_wd_timer(cd); return 0; } static int cyttsp4_core_wake(struct cyttsp4 *cd) { int rc; rc = cyttsp4_request_exclusive(cd, cd->dev, CY_CORE_REQUEST_EXCLUSIVE_TIMEOUT); if (rc < 0) { dev_err(cd->dev, "%s: fail get exclusive ex=%p own=%p\n", __func__, cd->exclusive_dev, cd->dev); return 0; } rc = cyttsp4_core_wake_(cd); if (cyttsp4_release_exclusive(cd, cd->dev) < 0) dev_err(cd->dev, "%s: fail to release exclusive\n", __func__); else dev_vdbg(cd->dev, "%s: pass release exclusive\n", __func__); return rc; } static int cyttsp4_core_suspend(struct device *dev) { struct cyttsp4 *cd = dev_get_drvdata(dev); struct cyttsp4_mt_data *md = &cd->md; int rc; md->is_suspended = true; rc = cyttsp4_core_sleep(cd); if (rc < 0) { dev_err(dev, "%s: Error on sleep\n", __func__); return -EAGAIN; } return 0; } static int cyttsp4_core_resume(struct device *dev) { struct cyttsp4 *cd = dev_get_drvdata(dev); struct cyttsp4_mt_data *md = &cd->md; int rc; md->is_suspended = false; rc = cyttsp4_core_wake(cd); if (rc < 0) { dev_err(dev, "%s: Error on wake\n", __func__); return -EAGAIN; } return 0; } EXPORT_GPL_RUNTIME_DEV_PM_OPS(cyttsp4_pm_ops, cyttsp4_core_suspend, cyttsp4_core_resume, NULL); static int cyttsp4_mt_open(struct input_dev *input) { pm_runtime_get(input->dev.parent); return 0; } static void cyttsp4_mt_close(struct input_dev *input) { struct cyttsp4_mt_data *md = input_get_drvdata(input); mutex_lock(&md->report_lock); if (!md->is_suspended) pm_runtime_put(input->dev.parent); mutex_unlock(&md->report_lock); } static int cyttsp4_setup_input_device(struct cyttsp4 *cd) { struct device *dev = cd->dev; struct cyttsp4_mt_data *md = &cd->md; int signal = CY_IGNORE_VALUE; int max_x, max_y, max_p, min, max; int max_x_tmp, max_y_tmp; int i; int rc; dev_vdbg(dev, "%s: Initialize event signals\n", __func__); __set_bit(EV_ABS, md->input->evbit); __set_bit(EV_REL, md->input->evbit); __set_bit(EV_KEY, md->input->evbit); max_x_tmp = md->si->si_ofs.max_x; max_y_tmp = md->si->si_ofs.max_y; /* get maximum values from the sysinfo data */ if (md->pdata->flags & CY_FLAG_FLIP) { max_x = max_y_tmp - 1; max_y = max_x_tmp - 1; } else { max_x = max_x_tmp - 1; max_y = max_y_tmp - 1; } max_p = md->si->si_ofs.max_p; /* set event signal capabilities */ for (i = 0; i < (md->pdata->frmwrk->size / CY_NUM_ABS_SET); i++) { signal = md->pdata->frmwrk->abs [(i * CY_NUM_ABS_SET) + CY_SIGNAL_OST]; if (signal != CY_IGNORE_VALUE) { __set_bit(signal, md->input->absbit); min = md->pdata->frmwrk->abs [(i * CY_NUM_ABS_SET) + CY_MIN_OST]; max = md->pdata->frmwrk->abs [(i * CY_NUM_ABS_SET) + CY_MAX_OST]; if (i == CY_ABS_ID_OST) { /* shift track ids down to start at 0 */ max = max - min; min = min - min; } else if (i == CY_ABS_X_OST) max = max_x; else if (i == CY_ABS_Y_OST) max = max_y; else if (i == CY_ABS_P_OST) max = max_p; input_set_abs_params(md->input, signal, min, max, md->pdata->frmwrk->abs [(i * CY_NUM_ABS_SET) + CY_FUZZ_OST], md->pdata->frmwrk->abs [(i * CY_NUM_ABS_SET) + CY_FLAT_OST]); dev_dbg(dev, "%s: register signal=%02X min=%d max=%d\n", __func__, signal, min, max); if ((i == CY_ABS_ID_OST) && (md->si->si_ofs.tch_rec_size < CY_TMA4XX_TCH_REC_SIZE)) break; } } input_mt_init_slots(md->input, md->si->si_ofs.tch_abs[CY_TCH_T].max, INPUT_MT_DIRECT); rc = input_register_device(md->input); if (rc < 0) dev_err(dev, "%s: Error, failed register input device r=%d\n", __func__, rc); return rc; } static int cyttsp4_mt_probe(struct cyttsp4 *cd) { struct device *dev = cd->dev; struct cyttsp4_mt_data *md = &cd->md; struct cyttsp4_mt_platform_data *pdata = cd->pdata->mt_pdata; int rc = 0; mutex_init(&md->report_lock); md->pdata = pdata; /* Create the input device and register it. */ dev_vdbg(dev, "%s: Create the input device and register it\n", __func__); md->input = input_allocate_device(); if (md->input == NULL) { dev_err(dev, "%s: Error, failed to allocate input device\n", __func__); rc = -ENOSYS; goto error_alloc_failed; } md->input->name = pdata->inp_dev_name; scnprintf(md->phys, sizeof(md->phys)-1, "%s", dev_name(dev)); md->input->phys = md->phys; md->input->id.bustype = cd->bus_ops->bustype; md->input->dev.parent = dev; md->input->open = cyttsp4_mt_open; md->input->close = cyttsp4_mt_close; input_set_drvdata(md->input, md); /* get sysinfo */ md->si = &cd->sysinfo; rc = cyttsp4_setup_input_device(cd); if (rc) goto error_init_input; return 0; error_init_input: input_free_device(md->input); error_alloc_failed: dev_err(dev, "%s failed.\n", __func__); return rc; } struct cyttsp4 *cyttsp4_probe(const struct cyttsp4_bus_ops *ops, struct device *dev, u16 irq, size_t xfer_buf_size) { struct cyttsp4 *cd; struct cyttsp4_platform_data *pdata = dev_get_platdata(dev); unsigned long irq_flags; int rc = 0; if (!pdata || !pdata->core_pdata || !pdata->mt_pdata) { dev_err(dev, "%s: Missing platform data\n", __func__); rc = -ENODEV; goto error_no_pdata; } cd = kzalloc(sizeof(*cd), GFP_KERNEL); if (!cd) { dev_err(dev, "%s: Error, kzalloc\n", __func__); rc = -ENOMEM; goto error_alloc_data; } cd->xfer_buf = kzalloc(xfer_buf_size, GFP_KERNEL); if (!cd->xfer_buf) { dev_err(dev, "%s: Error, kzalloc\n", __func__); rc = -ENOMEM; goto error_free_cd; } /* Initialize device info */ cd->dev = dev; cd->pdata = pdata; cd->cpdata = pdata->core_pdata; cd->bus_ops = ops; /* Initialize mutexes and spinlocks */ mutex_init(&cd->system_lock); mutex_init(&cd->adap_lock); /* Initialize wait queue */ init_waitqueue_head(&cd->wait_q); /* Initialize works */ INIT_WORK(&cd->startup_work, cyttsp4_startup_work_function); INIT_WORK(&cd->watchdog_work, cyttsp4_watchdog_work); /* Initialize IRQ */ cd->irq = gpio_to_irq(cd->cpdata->irq_gpio); if (cd->irq < 0) { rc = -EINVAL; goto error_free_xfer; } dev_set_drvdata(dev, cd); /* Call platform init function */ if (cd->cpdata->init) { dev_dbg(cd->dev, "%s: Init HW\n", __func__); rc = cd->cpdata->init(cd->cpdata, 1, cd->dev); } else { dev_dbg(cd->dev, "%s: No HW INIT function\n", __func__); rc = 0; } if (rc < 0) dev_err(cd->dev, "%s: HW Init fail r=%d\n", __func__, rc); dev_dbg(dev, "%s: initialize threaded irq=%d\n", __func__, cd->irq); if (cd->cpdata->level_irq_udelay > 0) /* use level triggered interrupts */ irq_flags = IRQF_TRIGGER_LOW | IRQF_ONESHOT; else /* use edge triggered interrupts */ irq_flags = IRQF_TRIGGER_FALLING | IRQF_ONESHOT; rc = request_threaded_irq(cd->irq, NULL, cyttsp4_irq, irq_flags, dev_name(dev), cd); if (rc < 0) { dev_err(dev, "%s: Error, could not request irq\n", __func__); goto error_request_irq; } /* Setup watchdog timer */ timer_setup(&cd->watchdog_timer, cyttsp4_watchdog_timer, 0); /* * call startup directly to ensure that the device * is tested before leaving the probe */ rc = cyttsp4_startup(cd); /* Do not fail probe if startup fails but the device is detected */ if (rc < 0 && cd->mode == CY_MODE_UNKNOWN) { dev_err(cd->dev, "%s: Fail initial startup r=%d\n", __func__, rc); goto error_startup; } rc = cyttsp4_mt_probe(cd); if (rc < 0) { dev_err(dev, "%s: Error, fail mt probe\n", __func__); goto error_startup; } pm_runtime_enable(dev); return cd; error_startup: cancel_work_sync(&cd->startup_work); cyttsp4_stop_wd_timer(cd); pm_runtime_disable(dev); cyttsp4_free_si_ptrs(cd); free_irq(cd->irq, cd); error_request_irq: if (cd->cpdata->init) cd->cpdata->init(cd->cpdata, 0, dev); error_free_xfer: kfree(cd->xfer_buf); error_free_cd: kfree(cd); error_alloc_data: error_no_pdata: dev_err(dev, "%s failed.\n", __func__); return ERR_PTR(rc); } EXPORT_SYMBOL_GPL(cyttsp4_probe); static void cyttsp4_mt_release(struct cyttsp4_mt_data *md) { input_unregister_device(md->input); input_set_drvdata(md->input, NULL); } int cyttsp4_remove(struct cyttsp4 *cd) { struct device *dev = cd->dev; cyttsp4_mt_release(&cd->md); /* * Suspend the device before freeing the startup_work and stopping * the watchdog since sleep function restarts watchdog on failure */ pm_runtime_suspend(dev); pm_runtime_disable(dev); cancel_work_sync(&cd->startup_work); cyttsp4_stop_wd_timer(cd); free_irq(cd->irq, cd); if (cd->cpdata->init) cd->cpdata->init(cd->cpdata, 0, dev); cyttsp4_free_si_ptrs(cd); kfree(cd); return 0; } EXPORT_SYMBOL_GPL(cyttsp4_remove); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen core driver"); MODULE_AUTHOR("Cypress");
linux-master
drivers/input/touchscreen/cyttsp4_core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * wm97xx-core.c -- Touch screen driver core for Wolfson WM9705, WM9712 * and WM9713 AC97 Codecs. * * 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]> * * Notes: * * Features: * - supports WM9705, WM9712, WM9713 * - polling mode * - continuous mode (arch-dependent) * - adjustable rpu/dpp settings * - adjustable pressure current * - adjustable sample settle delay * - 4 and 5 wire touchscreens (5 wire is WM9712 only) * - pen down detection * - battery monitor * - sample AUX adcs * - power management * - codec GPIO * - codec event notification * Todo * - Support for async sampling control for noisy LCDs. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/proc_fs.h> #include <linux/pm.h> #include <linux/interrupt.h> #include <linux/bitops.h> #include <linux/mfd/wm97xx.h> #include <linux/workqueue.h> #include <linux/wm97xx.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/slab.h> #define TS_NAME "wm97xx" #define WM_CORE_VERSION "1.00" #define DEFAULT_PRESSURE 0xb0c0 /* * Touchscreen absolute values * * These parameters are used to help the input layer discard out of * range readings and reduce jitter etc. * * o min, max:- indicate the min and max values your touch screen returns * o fuzz:- use a higher number to reduce jitter * * The default values correspond to Mainstone II in QVGA mode * * Please read * Documentation/input/input-programming.rst for more details. */ static int abs_x[3] = {150, 4000, 5}; module_param_array(abs_x, int, NULL, 0); MODULE_PARM_DESC(abs_x, "Touchscreen absolute X min, max, fuzz"); static int abs_y[3] = {200, 4000, 40}; module_param_array(abs_y, int, NULL, 0); MODULE_PARM_DESC(abs_y, "Touchscreen absolute Y min, max, fuzz"); static int abs_p[3] = {0, 150, 4}; module_param_array(abs_p, int, NULL, 0); MODULE_PARM_DESC(abs_p, "Touchscreen absolute Pressure min, max, fuzz"); /* * wm97xx IO access, all IO locking done by AC97 layer */ int wm97xx_reg_read(struct wm97xx *wm, u16 reg) { if (wm->ac97) return wm->ac97->bus->ops->read(wm->ac97, reg); else return -1; } EXPORT_SYMBOL_GPL(wm97xx_reg_read); void wm97xx_reg_write(struct wm97xx *wm, u16 reg, u16 val) { /* cache digitiser registers */ if (reg >= AC97_WM9713_DIG1 && reg <= AC97_WM9713_DIG3) wm->dig[(reg - AC97_WM9713_DIG1) >> 1] = val; /* cache gpio regs */ if (reg >= AC97_GPIO_CFG && reg <= AC97_MISC_AFE) wm->gpio[(reg - AC97_GPIO_CFG) >> 1] = val; /* wm9713 irq reg */ if (reg == 0x5a) wm->misc = val; if (wm->ac97) wm->ac97->bus->ops->write(wm->ac97, reg, val); } EXPORT_SYMBOL_GPL(wm97xx_reg_write); /** * wm97xx_read_aux_adc - Read the aux adc. * @wm: wm97xx device. * @adcsel: codec ADC to be read * * Reads the selected AUX ADC. */ int wm97xx_read_aux_adc(struct wm97xx *wm, u16 adcsel) { int power_adc = 0, auxval; u16 power = 0; int rc = 0; int timeout = 0; /* get codec */ mutex_lock(&wm->codec_mutex); /* When the touchscreen is not in use, we may have to power up * the AUX ADC before we can use sample the AUX inputs-> */ if (wm->id == WM9713_ID2 && (power = wm97xx_reg_read(wm, AC97_EXTENDED_MID)) & 0x8000) { power_adc = 1; wm97xx_reg_write(wm, AC97_EXTENDED_MID, power & 0x7fff); } /* Prepare the codec for AUX reading */ wm->codec->aux_prepare(wm); /* Turn polling mode on to read AUX ADC */ wm->pen_probably_down = 1; while (rc != RC_VALID && timeout++ < 5) rc = wm->codec->poll_sample(wm, adcsel, &auxval); if (power_adc) wm97xx_reg_write(wm, AC97_EXTENDED_MID, power | 0x8000); wm->codec->dig_restore(wm); wm->pen_probably_down = 0; if (timeout >= 5) { dev_err(wm->dev, "timeout reading auxadc %d, disabling digitiser\n", adcsel); wm->codec->dig_enable(wm, false); } mutex_unlock(&wm->codec_mutex); return (rc == RC_VALID ? auxval & 0xfff : -EBUSY); } EXPORT_SYMBOL_GPL(wm97xx_read_aux_adc); /** * wm97xx_get_gpio - Get the status of a codec GPIO. * @wm: wm97xx device. * @gpio: gpio * * Get the status of a codec GPIO pin */ enum wm97xx_gpio_status wm97xx_get_gpio(struct wm97xx *wm, u32 gpio) { u16 status; enum wm97xx_gpio_status ret; mutex_lock(&wm->codec_mutex); status = wm97xx_reg_read(wm, AC97_GPIO_STATUS); if (status & gpio) ret = WM97XX_GPIO_HIGH; else ret = WM97XX_GPIO_LOW; mutex_unlock(&wm->codec_mutex); return ret; } EXPORT_SYMBOL_GPL(wm97xx_get_gpio); /** * wm97xx_set_gpio - Set the status of a codec GPIO. * @wm: wm97xx device. * @gpio: gpio * @status: status * * Set the status of a codec GPIO pin */ void wm97xx_set_gpio(struct wm97xx *wm, u32 gpio, enum wm97xx_gpio_status status) { u16 reg; mutex_lock(&wm->codec_mutex); reg = wm97xx_reg_read(wm, AC97_GPIO_STATUS); if (status == WM97XX_GPIO_HIGH) reg |= gpio; else reg &= ~gpio; if (wm->id == WM9712_ID2 && wm->variant != WM97xx_WM1613) wm97xx_reg_write(wm, AC97_GPIO_STATUS, reg << 1); else wm97xx_reg_write(wm, AC97_GPIO_STATUS, reg); mutex_unlock(&wm->codec_mutex); } EXPORT_SYMBOL_GPL(wm97xx_set_gpio); /* * Codec GPIO pin configuration, this sets pin direction, polarity, * stickyness and wake up. */ void wm97xx_config_gpio(struct wm97xx *wm, u32 gpio, enum wm97xx_gpio_dir dir, enum wm97xx_gpio_pol pol, enum wm97xx_gpio_sticky sticky, enum wm97xx_gpio_wake wake) { u16 reg; mutex_lock(&wm->codec_mutex); reg = wm97xx_reg_read(wm, AC97_GPIO_POLARITY); if (pol == WM97XX_GPIO_POL_HIGH) reg |= gpio; else reg &= ~gpio; wm97xx_reg_write(wm, AC97_GPIO_POLARITY, reg); reg = wm97xx_reg_read(wm, AC97_GPIO_STICKY); if (sticky == WM97XX_GPIO_STICKY) reg |= gpio; else reg &= ~gpio; wm97xx_reg_write(wm, AC97_GPIO_STICKY, reg); reg = wm97xx_reg_read(wm, AC97_GPIO_WAKEUP); if (wake == WM97XX_GPIO_WAKE) reg |= gpio; else reg &= ~gpio; wm97xx_reg_write(wm, AC97_GPIO_WAKEUP, reg); reg = wm97xx_reg_read(wm, AC97_GPIO_CFG); if (dir == WM97XX_GPIO_IN) reg |= gpio; else reg &= ~gpio; wm97xx_reg_write(wm, AC97_GPIO_CFG, reg); mutex_unlock(&wm->codec_mutex); } EXPORT_SYMBOL_GPL(wm97xx_config_gpio); /* * Configure the WM97XX_PRP value to use while system is suspended. * If a value other than 0 is set then WM97xx pen detection will be * left enabled in the configured mode while the system is in suspend, * the device has users and suspend has not been disabled via the * wakeup sysfs entries. * * @wm: WM97xx device to configure * @mode: WM97XX_PRP value to configure while suspended */ void wm97xx_set_suspend_mode(struct wm97xx *wm, u16 mode) { wm->suspend_mode = mode; device_init_wakeup(&wm->input_dev->dev, mode != 0); } EXPORT_SYMBOL_GPL(wm97xx_set_suspend_mode); /* * Codec PENDOWN irq handler * */ static irqreturn_t wm97xx_pen_interrupt(int irq, void *dev_id) { struct wm97xx *wm = dev_id; int pen_was_down = wm->pen_is_down; /* do we need to enable the touch panel reader */ if (wm->id == WM9705_ID2) { if (wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD) & WM97XX_PEN_DOWN) wm->pen_is_down = 1; else wm->pen_is_down = 0; } else { u16 status, pol; mutex_lock(&wm->codec_mutex); status = wm97xx_reg_read(wm, AC97_GPIO_STATUS); pol = wm97xx_reg_read(wm, AC97_GPIO_POLARITY); if (WM97XX_GPIO_13 & pol & status) { wm->pen_is_down = 1; wm97xx_reg_write(wm, AC97_GPIO_POLARITY, pol & ~WM97XX_GPIO_13); } else { wm->pen_is_down = 0; wm97xx_reg_write(wm, AC97_GPIO_POLARITY, pol | WM97XX_GPIO_13); } if (wm->id == WM9712_ID2 && wm->variant != WM97xx_WM1613) wm97xx_reg_write(wm, AC97_GPIO_STATUS, (status & ~WM97XX_GPIO_13) << 1); else wm97xx_reg_write(wm, AC97_GPIO_STATUS, status & ~WM97XX_GPIO_13); mutex_unlock(&wm->codec_mutex); } /* If the system is not using continuous mode or it provides a * pen down operation then we need to schedule polls while the * pen is down. Otherwise the machine driver is responsible * for scheduling reads. */ if (!wm->mach_ops->acc_enabled || wm->mach_ops->acc_pen_down) { if (wm->pen_is_down && !pen_was_down) { /* Data is not available immediately on pen down */ queue_delayed_work(wm->ts_workq, &wm->ts_reader, 1); } /* Let ts_reader report the pen up for debounce. */ if (!wm->pen_is_down && pen_was_down) wm->pen_is_down = 1; } if (!wm->pen_is_down && wm->mach_ops->acc_enabled) wm->mach_ops->acc_pen_up(wm); return IRQ_HANDLED; } /* * initialise pen IRQ handler and workqueue */ static int wm97xx_init_pen_irq(struct wm97xx *wm) { u16 reg; if (request_threaded_irq(wm->pen_irq, NULL, wm97xx_pen_interrupt, IRQF_SHARED | IRQF_ONESHOT, "wm97xx-pen", wm)) { dev_err(wm->dev, "Failed to register pen down interrupt, polling"); wm->pen_irq = 0; return -EINVAL; } /* Configure GPIO as interrupt source on WM971x */ if (wm->id != WM9705_ID2) { BUG_ON(!wm->mach_ops->irq_gpio); reg = wm97xx_reg_read(wm, AC97_MISC_AFE); wm97xx_reg_write(wm, AC97_MISC_AFE, reg & ~(wm->mach_ops->irq_gpio)); reg = wm97xx_reg_read(wm, 0x5a); wm97xx_reg_write(wm, 0x5a, reg & ~0x0001); } return 0; } static int wm97xx_read_samples(struct wm97xx *wm) { struct wm97xx_data data; int rc; mutex_lock(&wm->codec_mutex); if (wm->mach_ops && wm->mach_ops->acc_enabled) rc = wm->mach_ops->acc_pen_down(wm); else rc = wm->codec->poll_touch(wm, &data); if (rc & RC_PENUP) { if (wm->pen_is_down) { wm->pen_is_down = 0; dev_dbg(wm->dev, "pen up\n"); input_report_abs(wm->input_dev, ABS_PRESSURE, 0); input_report_key(wm->input_dev, BTN_TOUCH, 0); input_sync(wm->input_dev); } else if (!(rc & RC_AGAIN)) { /* We need high frequency updates only while * pen is down, the user never will be able to * touch screen faster than a few times per * second... On the other hand, when the user * is actively working with the touchscreen we * don't want to lose the quick response. So we * will slowly increase sleep time after the * pen is up and quicky restore it to ~one task * switch when pen is down again. */ if (wm->ts_reader_interval < HZ / 10) wm->ts_reader_interval++; } } else if (rc & RC_VALID) { dev_dbg(wm->dev, "pen down: x=%x:%d, y=%x:%d, pressure=%x:%d\n", data.x >> 12, data.x & 0xfff, data.y >> 12, data.y & 0xfff, data.p >> 12, data.p & 0xfff); if (abs_x[0] > (data.x & 0xfff) || abs_x[1] < (data.x & 0xfff) || abs_y[0] > (data.y & 0xfff) || abs_y[1] < (data.y & 0xfff)) { dev_dbg(wm->dev, "Measurement out of range, dropping it\n"); rc = RC_AGAIN; goto out; } input_report_abs(wm->input_dev, ABS_X, data.x & 0xfff); input_report_abs(wm->input_dev, ABS_Y, data.y & 0xfff); input_report_abs(wm->input_dev, ABS_PRESSURE, data.p & 0xfff); input_report_key(wm->input_dev, BTN_TOUCH, 1); input_sync(wm->input_dev); wm->pen_is_down = 1; wm->ts_reader_interval = wm->ts_reader_min_interval; } else if (rc & RC_PENDOWN) { dev_dbg(wm->dev, "pen down\n"); wm->pen_is_down = 1; wm->ts_reader_interval = wm->ts_reader_min_interval; } out: mutex_unlock(&wm->codec_mutex); return rc; } /* * The touchscreen sample reader. */ static void wm97xx_ts_reader(struct work_struct *work) { int rc; struct wm97xx *wm = container_of(work, struct wm97xx, ts_reader.work); BUG_ON(!wm->codec); do { rc = wm97xx_read_samples(wm); } while (rc & RC_AGAIN); if (wm->pen_is_down || !wm->pen_irq) queue_delayed_work(wm->ts_workq, &wm->ts_reader, wm->ts_reader_interval); } /** * wm97xx_ts_input_open - Open the touch screen input device. * @idev: Input device to be opened. * * Called by the input sub system to open a wm97xx touchscreen device. * Starts the touchscreen thread and touch digitiser. */ static int wm97xx_ts_input_open(struct input_dev *idev) { struct wm97xx *wm = input_get_drvdata(idev); wm->ts_workq = alloc_ordered_workqueue("kwm97xx", 0); if (wm->ts_workq == NULL) { dev_err(wm->dev, "Failed to create workqueue\n"); return -EINVAL; } /* start digitiser */ if (wm->mach_ops && wm->mach_ops->acc_enabled) wm->codec->acc_enable(wm, 1); wm->codec->dig_enable(wm, 1); INIT_DELAYED_WORK(&wm->ts_reader, wm97xx_ts_reader); wm->ts_reader_min_interval = HZ >= 100 ? HZ / 100 : 1; if (wm->ts_reader_min_interval < 1) wm->ts_reader_min_interval = 1; wm->ts_reader_interval = wm->ts_reader_min_interval; wm->pen_is_down = 0; if (wm->pen_irq) wm97xx_init_pen_irq(wm); else dev_err(wm->dev, "No IRQ specified\n"); /* If we either don't have an interrupt for pen down events or * failed to acquire it then we need to poll. */ if (wm->pen_irq == 0) queue_delayed_work(wm->ts_workq, &wm->ts_reader, wm->ts_reader_interval); return 0; } /** * wm97xx_ts_input_close - Close the touch screen input device. * @idev: Input device to be closed. * * Called by the input sub system to close a wm97xx touchscreen * device. Kills the touchscreen thread and stops the touch * digitiser. */ static void wm97xx_ts_input_close(struct input_dev *idev) { struct wm97xx *wm = input_get_drvdata(idev); u16 reg; if (wm->pen_irq) { /* Return the interrupt to GPIO usage (disabling it) */ if (wm->id != WM9705_ID2) { BUG_ON(!wm->mach_ops->irq_gpio); reg = wm97xx_reg_read(wm, AC97_MISC_AFE); wm97xx_reg_write(wm, AC97_MISC_AFE, reg | wm->mach_ops->irq_gpio); } free_irq(wm->pen_irq, wm); } wm->pen_is_down = 0; /* ts_reader rearms itself so we need to explicitly stop it * before we destroy the workqueue. */ cancel_delayed_work_sync(&wm->ts_reader); destroy_workqueue(wm->ts_workq); /* stop digitiser */ wm->codec->dig_enable(wm, 0); if (wm->mach_ops && wm->mach_ops->acc_enabled) wm->codec->acc_enable(wm, 0); } static int wm97xx_register_touch(struct wm97xx *wm) { struct wm97xx_pdata *pdata = dev_get_platdata(wm->dev); int ret; wm->input_dev = devm_input_allocate_device(wm->dev); if (wm->input_dev == NULL) return -ENOMEM; /* set up touch configuration */ wm->input_dev->name = "wm97xx touchscreen"; wm->input_dev->phys = "wm97xx"; wm->input_dev->open = wm97xx_ts_input_open; wm->input_dev->close = wm97xx_ts_input_close; __set_bit(EV_ABS, wm->input_dev->evbit); __set_bit(EV_KEY, wm->input_dev->evbit); __set_bit(BTN_TOUCH, wm->input_dev->keybit); input_set_abs_params(wm->input_dev, ABS_X, abs_x[0], abs_x[1], abs_x[2], 0); input_set_abs_params(wm->input_dev, ABS_Y, abs_y[0], abs_y[1], abs_y[2], 0); input_set_abs_params(wm->input_dev, ABS_PRESSURE, abs_p[0], abs_p[1], abs_p[2], 0); input_set_drvdata(wm->input_dev, wm); wm->input_dev->dev.parent = wm->dev; ret = input_register_device(wm->input_dev); if (ret) return ret; /* * register our extended touch device (for machine specific * extensions) */ wm->touch_dev = platform_device_alloc("wm97xx-touch", -1); if (!wm->touch_dev) return -ENOMEM; platform_set_drvdata(wm->touch_dev, wm); wm->touch_dev->dev.parent = wm->dev; wm->touch_dev->dev.platform_data = pdata; ret = platform_device_add(wm->touch_dev); if (ret < 0) goto touch_reg_err; return 0; touch_reg_err: platform_device_put(wm->touch_dev); return ret; } static void wm97xx_unregister_touch(struct wm97xx *wm) { platform_device_unregister(wm->touch_dev); } static int _wm97xx_probe(struct wm97xx *wm) { int id = 0; mutex_init(&wm->codec_mutex); dev_set_drvdata(wm->dev, wm); /* check that we have a supported codec */ id = wm97xx_reg_read(wm, AC97_VENDOR_ID1); if (id != WM97XX_ID1) { dev_err(wm->dev, "Device with vendor %04x is not a wm97xx\n", id); return -ENODEV; } wm->id = wm97xx_reg_read(wm, AC97_VENDOR_ID2); wm->variant = WM97xx_GENERIC; dev_info(wm->dev, "detected a wm97%02x codec\n", wm->id & 0xff); switch (wm->id & 0xff) { #ifdef CONFIG_TOUCHSCREEN_WM9705 case 0x05: wm->codec = &wm9705_codec; break; #endif #ifdef CONFIG_TOUCHSCREEN_WM9712 case 0x12: wm->codec = &wm9712_codec; break; #endif #ifdef CONFIG_TOUCHSCREEN_WM9713 case 0x13: wm->codec = &wm9713_codec; break; #endif default: dev_err(wm->dev, "Support for wm97%02x not compiled in.\n", wm->id & 0xff); return -ENODEV; } /* set up physical characteristics */ wm->codec->phy_init(wm); /* load gpio cache */ wm->gpio[0] = wm97xx_reg_read(wm, AC97_GPIO_CFG); wm->gpio[1] = wm97xx_reg_read(wm, AC97_GPIO_POLARITY); wm->gpio[2] = wm97xx_reg_read(wm, AC97_GPIO_STICKY); wm->gpio[3] = wm97xx_reg_read(wm, AC97_GPIO_WAKEUP); wm->gpio[4] = wm97xx_reg_read(wm, AC97_GPIO_STATUS); wm->gpio[5] = wm97xx_reg_read(wm, AC97_MISC_AFE); return wm97xx_register_touch(wm); } static void wm97xx_remove_battery(struct wm97xx *wm) { platform_device_unregister(wm->battery_dev); } static int wm97xx_add_battery(struct wm97xx *wm, struct wm97xx_batt_pdata *pdata) { int ret; wm->battery_dev = platform_device_alloc("wm97xx-battery", -1); if (!wm->battery_dev) return -ENOMEM; platform_set_drvdata(wm->battery_dev, wm); wm->battery_dev->dev.parent = wm->dev; wm->battery_dev->dev.platform_data = pdata; ret = platform_device_add(wm->battery_dev); if (ret) platform_device_put(wm->battery_dev); return ret; } static int wm97xx_probe(struct device *dev) { struct wm97xx *wm; int ret; struct wm97xx_pdata *pdata = dev_get_platdata(dev); wm = devm_kzalloc(dev, sizeof(struct wm97xx), GFP_KERNEL); if (!wm) return -ENOMEM; wm->dev = dev; wm->ac97 = to_ac97_t(dev); ret = _wm97xx_probe(wm); if (ret) return ret; ret = wm97xx_add_battery(wm, pdata ? pdata->batt_pdata : NULL); if (ret < 0) goto batt_err; return ret; batt_err: wm97xx_unregister_touch(wm); return ret; } static int wm97xx_remove(struct device *dev) { struct wm97xx *wm = dev_get_drvdata(dev); wm97xx_remove_battery(wm); wm97xx_unregister_touch(wm); return 0; } static int wm97xx_mfd_probe(struct platform_device *pdev) { struct wm97xx *wm; struct wm97xx_platform_data *mfd_pdata = dev_get_platdata(&pdev->dev); int ret; wm = devm_kzalloc(&pdev->dev, sizeof(struct wm97xx), GFP_KERNEL); if (!wm) return -ENOMEM; wm->dev = &pdev->dev; wm->ac97 = mfd_pdata->ac97; ret = _wm97xx_probe(wm); if (ret) return ret; ret = wm97xx_add_battery(wm, mfd_pdata->batt_pdata); if (ret < 0) goto batt_err; return ret; batt_err: wm97xx_unregister_touch(wm); return ret; } static int wm97xx_mfd_remove(struct platform_device *pdev) { wm97xx_remove(&pdev->dev); return 0; } static int wm97xx_suspend(struct device *dev) { struct wm97xx *wm = dev_get_drvdata(dev); u16 reg; int suspend_mode; if (device_may_wakeup(&wm->input_dev->dev)) suspend_mode = wm->suspend_mode; else suspend_mode = 0; mutex_lock(&wm->input_dev->mutex); if (input_device_enabled(wm->input_dev)) cancel_delayed_work_sync(&wm->ts_reader); /* Power down the digitiser (bypassing the cache for resume) */ reg = wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER2); reg &= ~WM97XX_PRP_DET_DIG; if (input_device_enabled(wm->input_dev)) reg |= suspend_mode; wm->ac97->bus->ops->write(wm->ac97, AC97_WM97XX_DIGITISER2, reg); /* WM9713 has an additional power bit - turn it off if there * are no users or if suspend mode is zero. */ if (wm->id == WM9713_ID2 && (!input_device_enabled(wm->input_dev) || !suspend_mode)) { reg = wm97xx_reg_read(wm, AC97_EXTENDED_MID) | 0x8000; wm97xx_reg_write(wm, AC97_EXTENDED_MID, reg); } mutex_unlock(&wm->input_dev->mutex); return 0; } static int wm97xx_resume(struct device *dev) { struct wm97xx *wm = dev_get_drvdata(dev); mutex_lock(&wm->input_dev->mutex); /* restore digitiser and gpios */ if (wm->id == WM9713_ID2) { wm97xx_reg_write(wm, AC97_WM9713_DIG1, wm->dig[0]); wm97xx_reg_write(wm, 0x5a, wm->misc); if (input_device_enabled(wm->input_dev)) { u16 reg; reg = wm97xx_reg_read(wm, AC97_EXTENDED_MID) & 0x7fff; wm97xx_reg_write(wm, AC97_EXTENDED_MID, reg); } } wm97xx_reg_write(wm, AC97_WM9713_DIG2, wm->dig[1]); wm97xx_reg_write(wm, AC97_WM9713_DIG3, wm->dig[2]); wm97xx_reg_write(wm, AC97_GPIO_CFG, wm->gpio[0]); wm97xx_reg_write(wm, AC97_GPIO_POLARITY, wm->gpio[1]); wm97xx_reg_write(wm, AC97_GPIO_STICKY, wm->gpio[2]); wm97xx_reg_write(wm, AC97_GPIO_WAKEUP, wm->gpio[3]); wm97xx_reg_write(wm, AC97_GPIO_STATUS, wm->gpio[4]); wm97xx_reg_write(wm, AC97_MISC_AFE, wm->gpio[5]); if (input_device_enabled(wm->input_dev) && !wm->pen_irq) { wm->ts_reader_interval = wm->ts_reader_min_interval; queue_delayed_work(wm->ts_workq, &wm->ts_reader, wm->ts_reader_interval); } mutex_unlock(&wm->input_dev->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(wm97xx_pm_ops, wm97xx_suspend, wm97xx_resume); /* * Machine specific operations */ int wm97xx_register_mach_ops(struct wm97xx *wm, struct wm97xx_mach_ops *mach_ops) { mutex_lock(&wm->codec_mutex); if (wm->mach_ops) { mutex_unlock(&wm->codec_mutex); return -EINVAL; } wm->mach_ops = mach_ops; mutex_unlock(&wm->codec_mutex); return 0; } EXPORT_SYMBOL_GPL(wm97xx_register_mach_ops); void wm97xx_unregister_mach_ops(struct wm97xx *wm) { mutex_lock(&wm->codec_mutex); wm->mach_ops = NULL; mutex_unlock(&wm->codec_mutex); } EXPORT_SYMBOL_GPL(wm97xx_unregister_mach_ops); static struct device_driver wm97xx_driver = { .name = "wm97xx-ts", #ifdef CONFIG_AC97_BUS .bus = &ac97_bus_type, #endif .owner = THIS_MODULE, .probe = wm97xx_probe, .remove = wm97xx_remove, .pm = pm_sleep_ptr(&wm97xx_pm_ops), }; static struct platform_driver wm97xx_mfd_driver = { .driver = { .name = "wm97xx-ts", .pm = pm_sleep_ptr(&wm97xx_pm_ops), }, .probe = wm97xx_mfd_probe, .remove = wm97xx_mfd_remove, }; static int __init wm97xx_init(void) { int ret; ret = platform_driver_register(&wm97xx_mfd_driver); if (ret) return ret; if (IS_BUILTIN(CONFIG_AC97_BUS)) ret = driver_register(&wm97xx_driver); return ret; } static void __exit wm97xx_exit(void) { if (IS_BUILTIN(CONFIG_AC97_BUS)) driver_unregister(&wm97xx_driver); platform_driver_unregister(&wm97xx_mfd_driver); } module_init(wm97xx_init); module_exit(wm97xx_exit); /* Module information */ MODULE_AUTHOR("Liam Girdwood <[email protected]>"); MODULE_DESCRIPTION("WM97xx Core - Touch Screen / AUX ADC / GPIO Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wm97xx-core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * TSC2005 touchscreen driver * * Copyright (C) 2006-2010 Nokia Corporation * Copyright (C) 2015 QWERTY Embedded Design * Copyright (C) 2015 EMAC Inc. * * Based on original tsc2005.c by Lauri Leukkunen <[email protected]> */ #include <linux/input.h> #include <linux/module.h> #include <linux/of.h> #include <linux/spi/spi.h> #include <linux/regmap.h> #include "tsc200x-core.h" static const struct input_id tsc2005_input_id = { .bustype = BUS_SPI, .product = 2005, }; static int tsc2005_cmd(struct device *dev, u8 cmd) { u8 tx = TSC200X_CMD | TSC200X_CMD_12BIT | cmd; struct spi_transfer xfer = { .tx_buf = &tx, .len = 1, .bits_per_word = 8, }; struct spi_message msg; struct spi_device *spi = to_spi_device(dev); int error; spi_message_init(&msg); spi_message_add_tail(&xfer, &msg); error = spi_sync(spi, &msg); if (error) { dev_err(dev, "%s: failed, command: %x, spi error: %d\n", __func__, cmd, error); return error; } return 0; } static int tsc2005_probe(struct spi_device *spi) { int error; spi->mode = SPI_MODE_0; spi->bits_per_word = 8; if (!spi->max_speed_hz) spi->max_speed_hz = TSC2005_SPI_MAX_SPEED_HZ; error = spi_setup(spi); if (error) return error; return tsc200x_probe(&spi->dev, spi->irq, &tsc2005_input_id, devm_regmap_init_spi(spi, &tsc200x_regmap_config), tsc2005_cmd); } static void tsc2005_remove(struct spi_device *spi) { tsc200x_remove(&spi->dev); } #ifdef CONFIG_OF static const struct of_device_id tsc2005_of_match[] = { { .compatible = "ti,tsc2005" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, tsc2005_of_match); #endif static struct spi_driver tsc2005_driver = { .driver = { .name = "tsc2005", .of_match_table = of_match_ptr(tsc2005_of_match), .pm = pm_sleep_ptr(&tsc200x_pm_ops), }, .probe = tsc2005_probe, .remove = tsc2005_remove, }; module_spi_driver(tsc2005_driver); MODULE_AUTHOR("Michael Welling <[email protected]>"); MODULE_DESCRIPTION("TSC2005 Touchscreen Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:tsc2005");
linux-master
drivers/input/touchscreen/tsc2005.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Touchscreen driver for WM831x PMICs * * Copyright 2011 Wolfson Microelectronics plc. * Author: Mark Brown <[email protected]> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/pm.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/irq.h> #include <linux/mfd/wm831x/pdata.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/types.h> /* * R16424 (0x4028) - Touch Control 1 */ #define WM831X_TCH_ENA 0x8000 /* TCH_ENA */ #define WM831X_TCH_CVT_ENA 0x4000 /* TCH_CVT_ENA */ #define WM831X_TCH_SLPENA 0x1000 /* TCH_SLPENA */ #define WM831X_TCH_Z_ENA 0x0400 /* TCH_Z_ENA */ #define WM831X_TCH_Y_ENA 0x0200 /* TCH_Y_ENA */ #define WM831X_TCH_X_ENA 0x0100 /* TCH_X_ENA */ #define WM831X_TCH_DELAY_MASK 0x00E0 /* TCH_DELAY - [7:5] */ #define WM831X_TCH_DELAY_SHIFT 5 /* TCH_DELAY - [7:5] */ #define WM831X_TCH_DELAY_WIDTH 3 /* TCH_DELAY - [7:5] */ #define WM831X_TCH_RATE_MASK 0x001F /* TCH_RATE - [4:0] */ #define WM831X_TCH_RATE_SHIFT 0 /* TCH_RATE - [4:0] */ #define WM831X_TCH_RATE_WIDTH 5 /* TCH_RATE - [4:0] */ /* * R16425 (0x4029) - Touch Control 2 */ #define WM831X_TCH_PD_WK 0x2000 /* TCH_PD_WK */ #define WM831X_TCH_5WIRE 0x1000 /* TCH_5WIRE */ #define WM831X_TCH_PDONLY 0x0800 /* TCH_PDONLY */ #define WM831X_TCH_ISEL 0x0100 /* TCH_ISEL */ #define WM831X_TCH_RPU_MASK 0x000F /* TCH_RPU - [3:0] */ #define WM831X_TCH_RPU_SHIFT 0 /* TCH_RPU - [3:0] */ #define WM831X_TCH_RPU_WIDTH 4 /* TCH_RPU - [3:0] */ /* * R16426-8 (0x402A-C) - Touch Data X/Y/X */ #define WM831X_TCH_PD 0x8000 /* TCH_PD1 */ #define WM831X_TCH_DATA_MASK 0x0FFF /* TCH_DATA - [11:0] */ #define WM831X_TCH_DATA_SHIFT 0 /* TCH_DATA - [11:0] */ #define WM831X_TCH_DATA_WIDTH 12 /* TCH_DATA - [11:0] */ struct wm831x_ts { struct input_dev *input_dev; struct wm831x *wm831x; unsigned int data_irq; unsigned int pd_irq; bool pressure; bool pen_down; struct work_struct pd_data_work; }; static void wm831x_pd_data_work(struct work_struct *work) { struct wm831x_ts *wm831x_ts = container_of(work, struct wm831x_ts, pd_data_work); if (wm831x_ts->pen_down) { enable_irq(wm831x_ts->data_irq); dev_dbg(wm831x_ts->wm831x->dev, "IRQ PD->DATA done\n"); } else { enable_irq(wm831x_ts->pd_irq); dev_dbg(wm831x_ts->wm831x->dev, "IRQ DATA->PD done\n"); } } static irqreturn_t wm831x_ts_data_irq(int irq, void *irq_data) { struct wm831x_ts *wm831x_ts = irq_data; struct wm831x *wm831x = wm831x_ts->wm831x; static int data_types[] = { ABS_X, ABS_Y, ABS_PRESSURE }; u16 data[3]; int count; int i, ret; if (wm831x_ts->pressure) count = 3; else count = 2; wm831x_set_bits(wm831x, WM831X_INTERRUPT_STATUS_1, WM831X_TCHDATA_EINT, WM831X_TCHDATA_EINT); ret = wm831x_bulk_read(wm831x, WM831X_TOUCH_DATA_X, count, data); if (ret != 0) { dev_err(wm831x->dev, "Failed to read touch data: %d\n", ret); return IRQ_NONE; } /* * We get a pen down reading on every reading, report pen up if any * individual reading does so. */ wm831x_ts->pen_down = true; for (i = 0; i < count; i++) { if (!(data[i] & WM831X_TCH_PD)) { wm831x_ts->pen_down = false; continue; } input_report_abs(wm831x_ts->input_dev, data_types[i], data[i] & WM831X_TCH_DATA_MASK); } if (!wm831x_ts->pen_down) { /* Switch from data to pen down */ dev_dbg(wm831x->dev, "IRQ DATA->PD\n"); disable_irq_nosync(wm831x_ts->data_irq); /* Don't need data any more */ wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_X_ENA | WM831X_TCH_Y_ENA | WM831X_TCH_Z_ENA, 0); /* Flush any final samples that arrived while reading */ wm831x_set_bits(wm831x, WM831X_INTERRUPT_STATUS_1, WM831X_TCHDATA_EINT, WM831X_TCHDATA_EINT); wm831x_bulk_read(wm831x, WM831X_TOUCH_DATA_X, count, data); if (wm831x_ts->pressure) input_report_abs(wm831x_ts->input_dev, ABS_PRESSURE, 0); input_report_key(wm831x_ts->input_dev, BTN_TOUCH, 0); schedule_work(&wm831x_ts->pd_data_work); } else { input_report_key(wm831x_ts->input_dev, BTN_TOUCH, 1); } input_sync(wm831x_ts->input_dev); return IRQ_HANDLED; } static irqreturn_t wm831x_ts_pen_down_irq(int irq, void *irq_data) { struct wm831x_ts *wm831x_ts = irq_data; struct wm831x *wm831x = wm831x_ts->wm831x; int ena = 0; if (wm831x_ts->pen_down) return IRQ_HANDLED; disable_irq_nosync(wm831x_ts->pd_irq); /* Start collecting data */ if (wm831x_ts->pressure) ena |= WM831X_TCH_Z_ENA; wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_X_ENA | WM831X_TCH_Y_ENA | WM831X_TCH_Z_ENA, WM831X_TCH_X_ENA | WM831X_TCH_Y_ENA | ena); wm831x_set_bits(wm831x, WM831X_INTERRUPT_STATUS_1, WM831X_TCHPD_EINT, WM831X_TCHPD_EINT); wm831x_ts->pen_down = true; /* Switch from pen down to data */ dev_dbg(wm831x->dev, "IRQ PD->DATA\n"); schedule_work(&wm831x_ts->pd_data_work); return IRQ_HANDLED; } static int wm831x_ts_input_open(struct input_dev *idev) { struct wm831x_ts *wm831x_ts = input_get_drvdata(idev); struct wm831x *wm831x = wm831x_ts->wm831x; wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_ENA | WM831X_TCH_CVT_ENA | WM831X_TCH_X_ENA | WM831X_TCH_Y_ENA | WM831X_TCH_Z_ENA, WM831X_TCH_ENA); wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_CVT_ENA, WM831X_TCH_CVT_ENA); return 0; } static void wm831x_ts_input_close(struct input_dev *idev) { struct wm831x_ts *wm831x_ts = input_get_drvdata(idev); struct wm831x *wm831x = wm831x_ts->wm831x; /* Shut the controller down, disabling all other functionality too */ wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_ENA | WM831X_TCH_X_ENA | WM831X_TCH_Y_ENA | WM831X_TCH_Z_ENA, 0); /* Make sure any pending IRQs are done, the above will prevent * new ones firing. */ synchronize_irq(wm831x_ts->data_irq); synchronize_irq(wm831x_ts->pd_irq); /* Make sure the IRQ completion work is quiesced */ flush_work(&wm831x_ts->pd_data_work); /* If we ended up with the pen down then make sure we revert back * to pen detection state for the next time we start up. */ if (wm831x_ts->pen_down) { disable_irq(wm831x_ts->data_irq); enable_irq(wm831x_ts->pd_irq); wm831x_ts->pen_down = false; } } static int wm831x_ts_probe(struct platform_device *pdev) { struct wm831x_ts *wm831x_ts; struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent); struct wm831x_pdata *core_pdata = dev_get_platdata(pdev->dev.parent); struct wm831x_touch_pdata *pdata = NULL; struct input_dev *input_dev; int error, irqf; if (core_pdata) pdata = core_pdata->touch; wm831x_ts = devm_kzalloc(&pdev->dev, sizeof(struct wm831x_ts), GFP_KERNEL); input_dev = devm_input_allocate_device(&pdev->dev); if (!wm831x_ts || !input_dev) { error = -ENOMEM; goto err_alloc; } wm831x_ts->wm831x = wm831x; wm831x_ts->input_dev = input_dev; INIT_WORK(&wm831x_ts->pd_data_work, wm831x_pd_data_work); /* * If we have a direct IRQ use it, otherwise use the interrupt * from the WM831x IRQ controller. */ wm831x_ts->data_irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "TCHDATA")); if (pdata && pdata->data_irq) wm831x_ts->data_irq = pdata->data_irq; wm831x_ts->pd_irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "TCHPD")); if (pdata && pdata->pd_irq) wm831x_ts->pd_irq = pdata->pd_irq; if (pdata) wm831x_ts->pressure = pdata->pressure; else wm831x_ts->pressure = true; /* Five wire touchscreens can't report pressure */ if (pdata && pdata->fivewire) { wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_2, WM831X_TCH_5WIRE, WM831X_TCH_5WIRE); /* Pressure measurements are not possible for five wire mode */ WARN_ON(pdata->pressure && pdata->fivewire); wm831x_ts->pressure = false; } else { wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_2, WM831X_TCH_5WIRE, 0); } if (pdata) { switch (pdata->isel) { default: dev_err(&pdev->dev, "Unsupported ISEL setting: %d\n", pdata->isel); fallthrough; case 200: case 0: wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_2, WM831X_TCH_ISEL, 0); break; case 400: wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_2, WM831X_TCH_ISEL, WM831X_TCH_ISEL); break; } } wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_2, WM831X_TCH_PDONLY, 0); /* Default to 96 samples/sec */ wm831x_set_bits(wm831x, WM831X_TOUCH_CONTROL_1, WM831X_TCH_RATE_MASK, 6); if (pdata && pdata->data_irqf) irqf = pdata->data_irqf; else irqf = IRQF_TRIGGER_HIGH; error = request_threaded_irq(wm831x_ts->data_irq, NULL, wm831x_ts_data_irq, irqf | IRQF_ONESHOT | IRQF_NO_AUTOEN, "Touchscreen data", wm831x_ts); if (error) { dev_err(&pdev->dev, "Failed to request data IRQ %d: %d\n", wm831x_ts->data_irq, error); goto err_alloc; } if (pdata && pdata->pd_irqf) irqf = pdata->pd_irqf; else irqf = IRQF_TRIGGER_HIGH; error = request_threaded_irq(wm831x_ts->pd_irq, NULL, wm831x_ts_pen_down_irq, irqf | IRQF_ONESHOT, "Touchscreen pen down", wm831x_ts); if (error) { dev_err(&pdev->dev, "Failed to request pen down IRQ %d: %d\n", wm831x_ts->pd_irq, error); goto err_data_irq; } /* set up touch configuration */ input_dev->name = "WM831x touchscreen"; input_dev->phys = "wm831x"; input_dev->open = wm831x_ts_input_open; input_dev->close = wm831x_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, 4095, 5, 0); input_set_abs_params(input_dev, ABS_Y, 0, 4095, 5, 0); if (wm831x_ts->pressure) input_set_abs_params(input_dev, ABS_PRESSURE, 0, 4095, 5, 0); input_set_drvdata(input_dev, wm831x_ts); input_dev->dev.parent = &pdev->dev; error = input_register_device(input_dev); if (error) goto err_pd_irq; platform_set_drvdata(pdev, wm831x_ts); return 0; err_pd_irq: free_irq(wm831x_ts->pd_irq, wm831x_ts); err_data_irq: free_irq(wm831x_ts->data_irq, wm831x_ts); err_alloc: return error; } static int wm831x_ts_remove(struct platform_device *pdev) { struct wm831x_ts *wm831x_ts = platform_get_drvdata(pdev); free_irq(wm831x_ts->pd_irq, wm831x_ts); free_irq(wm831x_ts->data_irq, wm831x_ts); return 0; } static struct platform_driver wm831x_ts_driver = { .driver = { .name = "wm831x-touch", }, .probe = wm831x_ts_probe, .remove = wm831x_ts_remove, }; module_platform_driver(wm831x_ts_driver); /* Module information */ MODULE_AUTHOR("Mark Brown <[email protected]>"); MODULE_DESCRIPTION("WM831x PMIC touchscreen driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:wm831x-touch");
linux-master
drivers/input/touchscreen/wm831x-ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Dynapro serial touchscreen driver * * Copyright (c) 2009 Tias Guns * Based on the inexio driver (c) Vojtech Pavlik and Dan Streetman and * Richard Lemon */ /* * 2009/09/19 Tias Guns <[email protected]> * Copied inexio.c and edited for Dynapro protocol (from retired Xorg module) */ #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 "Dynapro serial touchscreen driver" MODULE_AUTHOR("Tias Guns <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define DYNAPRO_FORMAT_TOUCH_BIT 0x40 #define DYNAPRO_FORMAT_LENGTH 3 #define DYNAPRO_RESPONSE_BEGIN_BYTE 0x80 #define DYNAPRO_MIN_XC 0 #define DYNAPRO_MAX_XC 0x3ff #define DYNAPRO_MIN_YC 0 #define DYNAPRO_MAX_YC 0x3ff #define DYNAPRO_GET_XC(data) (data[1] | ((data[0] & 0x38) << 4)) #define DYNAPRO_GET_YC(data) (data[2] | ((data[0] & 0x07) << 7)) #define DYNAPRO_GET_TOUCHED(data) (DYNAPRO_FORMAT_TOUCH_BIT & data[0]) /* * Per-touchscreen data. */ struct dynapro { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[DYNAPRO_FORMAT_LENGTH]; char phys[32]; }; static void dynapro_process_data(struct dynapro *pdynapro) { struct input_dev *dev = pdynapro->dev; if (DYNAPRO_FORMAT_LENGTH == ++pdynapro->idx) { input_report_abs(dev, ABS_X, DYNAPRO_GET_XC(pdynapro->data)); input_report_abs(dev, ABS_Y, DYNAPRO_GET_YC(pdynapro->data)); input_report_key(dev, BTN_TOUCH, DYNAPRO_GET_TOUCHED(pdynapro->data)); input_sync(dev); pdynapro->idx = 0; } } static irqreturn_t dynapro_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct dynapro *pdynapro = serio_get_drvdata(serio); pdynapro->data[pdynapro->idx] = data; if (DYNAPRO_RESPONSE_BEGIN_BYTE & pdynapro->data[0]) dynapro_process_data(pdynapro); else dev_dbg(&serio->dev, "unknown/unsynchronized data: %x\n", pdynapro->data[0]); return IRQ_HANDLED; } static void dynapro_disconnect(struct serio *serio) { struct dynapro *pdynapro = serio_get_drvdata(serio); input_get_device(pdynapro->dev); input_unregister_device(pdynapro->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(pdynapro->dev); kfree(pdynapro); } /* * dynapro_connect() is the routine that is called when someone adds a * new serio device that supports dynapro protocol and registers it as * an input device. This is usually accomplished using inputattach. */ static int dynapro_connect(struct serio *serio, struct serio_driver *drv) { struct dynapro *pdynapro; struct input_dev *input_dev; int err; pdynapro = kzalloc(sizeof(struct dynapro), GFP_KERNEL); input_dev = input_allocate_device(); if (!pdynapro || !input_dev) { err = -ENOMEM; goto fail1; } pdynapro->serio = serio; pdynapro->dev = input_dev; snprintf(pdynapro->phys, sizeof(pdynapro->phys), "%s/input0", serio->phys); input_dev->name = "Dynapro Serial TouchScreen"; input_dev->phys = pdynapro->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_DYNAPRO; 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(pdynapro->dev, ABS_X, DYNAPRO_MIN_XC, DYNAPRO_MAX_XC, 0, 0); input_set_abs_params(pdynapro->dev, ABS_Y, DYNAPRO_MIN_YC, DYNAPRO_MAX_YC, 0, 0); serio_set_drvdata(serio, pdynapro); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(pdynapro->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(pdynapro); return err; } /* * The serio driver structure. */ static const struct serio_device_id dynapro_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_DYNAPRO, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, dynapro_serio_ids); static struct serio_driver dynapro_drv = { .driver = { .name = "dynapro", }, .description = DRIVER_DESC, .id_table = dynapro_serio_ids, .interrupt = dynapro_interrupt, .connect = dynapro_connect, .disconnect = dynapro_disconnect, }; module_serio_driver(dynapro_drv);
linux-master
drivers/input/touchscreen/dynapro.c
// SPDX-License-Identifier: GPL-2.0-only /* * Sahara TouchIT-213 serial touchscreen driver * * Copyright (c) 2007-2008 Claudio Nieder <[email protected]> * * Based on Touchright driver (drivers/input/touchscreen/touchright.c) * Copyright (c) 2006 Rick Koch <[email protected]> * Copyright (c) 2004 Vojtech Pavlik * and Dan Streetman <[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 "Sahara TouchIT-213 serial touchscreen driver" MODULE_AUTHOR("Claudio Nieder <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ /* * Data is received through COM1 at 9600bit/s,8bit,no parity in packets * of 5 byte each. * * +--------+ +--------+ +--------+ +--------+ +--------+ * |1000000p| |0xxxxxxx| |0xxxxxxx| |0yyyyyyy| |0yyyyyyy| * +--------+ +--------+ +--------+ +--------+ +--------+ * MSB LSB MSB LSB * * The value of p is 1 as long as the screen is touched and 0 when * reporting the location where touching stopped, e.g. where the pen was * lifted from the screen. * * When holding the screen in landscape mode as the BIOS text output is * presented, x is the horizontal axis with values growing from left to * right and y is the vertical axis with values growing from top to * bottom. * * When holding the screen in portrait mode with the Sahara logo in its * correct position, x ist the vertical axis with values growing from * top to bottom and y is the horizontal axis with values growing from * right to left. */ #define T213_FORMAT_TOUCH_BIT 0x01 #define T213_FORMAT_STATUS_BYTE 0x80 #define T213_FORMAT_STATUS_MASK ~T213_FORMAT_TOUCH_BIT /* * On my Sahara Touch-IT 213 I have observed x values from 0 to 0x7f0 * and y values from 0x1d to 0x7e9, so the actual measurement is * probably done with an 11 bit precision. */ #define T213_MIN_XC 0 #define T213_MAX_XC 0x07ff #define T213_MIN_YC 0 #define T213_MAX_YC 0x07ff /* * Per-touchscreen data. */ struct touchit213 { struct input_dev *dev; struct serio *serio; int idx; unsigned char csum; unsigned char data[5]; char phys[32]; }; static irqreturn_t touchit213_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct touchit213 *touchit213 = serio_get_drvdata(serio); struct input_dev *dev = touchit213->dev; touchit213->data[touchit213->idx] = data; switch (touchit213->idx++) { case 0: if ((touchit213->data[0] & T213_FORMAT_STATUS_MASK) != T213_FORMAT_STATUS_BYTE) { pr_debug("unsynchronized data: 0x%02x\n", data); touchit213->idx = 0; } break; case 4: touchit213->idx = 0; input_report_abs(dev, ABS_X, (touchit213->data[1] << 7) | touchit213->data[2]); input_report_abs(dev, ABS_Y, (touchit213->data[3] << 7) | touchit213->data[4]); input_report_key(dev, BTN_TOUCH, touchit213->data[0] & T213_FORMAT_TOUCH_BIT); input_sync(dev); break; } return IRQ_HANDLED; } /* * touchit213_disconnect() is the opposite of touchit213_connect() */ static void touchit213_disconnect(struct serio *serio) { struct touchit213 *touchit213 = serio_get_drvdata(serio); input_get_device(touchit213->dev); input_unregister_device(touchit213->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(touchit213->dev); kfree(touchit213); } /* * touchit213_connect() is the routine that is called when someone adds a * new serio device that supports the Touchright protocol and registers it as * an input device. */ static int touchit213_connect(struct serio *serio, struct serio_driver *drv) { struct touchit213 *touchit213; struct input_dev *input_dev; int err; touchit213 = kzalloc(sizeof(struct touchit213), GFP_KERNEL); input_dev = input_allocate_device(); if (!touchit213 || !input_dev) { err = -ENOMEM; goto fail1; } touchit213->serio = serio; touchit213->dev = input_dev; snprintf(touchit213->phys, sizeof(touchit213->phys), "%s/input0", serio->phys); input_dev->name = "Sahara Touch-iT213 Serial TouchScreen"; input_dev->phys = touchit213->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_TOUCHIT213; 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(touchit213->dev, ABS_X, T213_MIN_XC, T213_MAX_XC, 0, 0); input_set_abs_params(touchit213->dev, ABS_Y, T213_MIN_YC, T213_MAX_YC, 0, 0); serio_set_drvdata(serio, touchit213); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(touchit213->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(touchit213); return err; } /* * The serio driver structure. */ static const struct serio_device_id touchit213_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_TOUCHIT213, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, touchit213_serio_ids); static struct serio_driver touchit213_drv = { .driver = { .name = "touchit213", }, .description = DRIVER_DESC, .id_table = touchit213_serio_ids, .interrupt = touchit213_interrupt, .connect = touchit213_connect, .disconnect = touchit213_disconnect, }; module_serio_driver(touchit213_drv);
linux-master
drivers/input/touchscreen/touchit213.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Azoteq IQS7210A/7211A/E Trackpad/Touchscreen Controller * * Copyright (C) 2023 Jeff LaBundy <[email protected]> */ #include <linux/bits.h> #include <linux/delay.h> #include <linux/device.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/iopoll.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/property.h> #include <linux/slab.h> #include <asm/unaligned.h> #define IQS7211_PROD_NUM 0x00 #define IQS7211_EVENT_MASK_ALL GENMASK(14, 8) #define IQS7211_EVENT_MASK_ALP BIT(13) #define IQS7211_EVENT_MASK_BTN BIT(12) #define IQS7211_EVENT_MASK_ATI BIT(11) #define IQS7211_EVENT_MASK_MOVE BIT(10) #define IQS7211_EVENT_MASK_GSTR BIT(9) #define IQS7211_EVENT_MODE BIT(8) #define IQS7211_COMMS_ERROR 0xEEEE #define IQS7211_COMMS_RETRY_MS 50 #define IQS7211_COMMS_SLEEP_US 100 #define IQS7211_COMMS_TIMEOUT_US (100 * USEC_PER_MSEC) #define IQS7211_RESET_TIMEOUT_MS 150 #define IQS7211_START_TIMEOUT_US (1 * USEC_PER_SEC) #define IQS7211_NUM_RETRIES 5 #define IQS7211_NUM_CRX 8 #define IQS7211_MAX_CTX 13 #define IQS7211_MAX_CONTACTS 2 #define IQS7211_MAX_CYCLES 21 /* * The following delay is used during instances that must wait for the open- * drain RDY pin to settle. Its value is calculated as 5*R*C, where R and C * represent typical datasheet values of 4.7k and 100 nF, respectively. */ #define iqs7211_irq_wait() usleep_range(2500, 2600) enum iqs7211_dev_id { IQS7210A, IQS7211A, IQS7211E, }; enum iqs7211_comms_mode { IQS7211_COMMS_MODE_WAIT, IQS7211_COMMS_MODE_FREE, IQS7211_COMMS_MODE_FORCE, }; struct iqs7211_reg_field_desc { struct list_head list; u8 addr; u16 mask; u16 val; }; enum iqs7211_reg_key_id { IQS7211_REG_KEY_NONE, IQS7211_REG_KEY_PROX, IQS7211_REG_KEY_TOUCH, IQS7211_REG_KEY_TAP, IQS7211_REG_KEY_HOLD, IQS7211_REG_KEY_PALM, IQS7211_REG_KEY_AXIAL_X, IQS7211_REG_KEY_AXIAL_Y, IQS7211_REG_KEY_RESERVED }; enum iqs7211_reg_grp_id { IQS7211_REG_GRP_TP, IQS7211_REG_GRP_BTN, IQS7211_REG_GRP_ALP, IQS7211_REG_GRP_SYS, IQS7211_NUM_REG_GRPS }; static const char * const iqs7211_reg_grp_names[IQS7211_NUM_REG_GRPS] = { [IQS7211_REG_GRP_TP] = "trackpad", [IQS7211_REG_GRP_BTN] = "button", [IQS7211_REG_GRP_ALP] = "alp", }; static const u16 iqs7211_reg_grp_masks[IQS7211_NUM_REG_GRPS] = { [IQS7211_REG_GRP_TP] = IQS7211_EVENT_MASK_GSTR, [IQS7211_REG_GRP_BTN] = IQS7211_EVENT_MASK_BTN, [IQS7211_REG_GRP_ALP] = IQS7211_EVENT_MASK_ALP, }; struct iqs7211_event_desc { const char *name; u16 mask; u16 enable; enum iqs7211_reg_grp_id reg_grp; enum iqs7211_reg_key_id reg_key; }; static const struct iqs7211_event_desc iqs7210a_kp_events[] = { { .mask = BIT(10), .enable = BIT(13) | BIT(12), .reg_grp = IQS7211_REG_GRP_ALP, }, { .name = "event-prox", .mask = BIT(2), .enable = BIT(5) | BIT(4), .reg_grp = IQS7211_REG_GRP_BTN, .reg_key = IQS7211_REG_KEY_PROX, }, { .name = "event-touch", .mask = BIT(3), .enable = BIT(5) | BIT(4), .reg_grp = IQS7211_REG_GRP_BTN, .reg_key = IQS7211_REG_KEY_TOUCH, }, { .name = "event-tap", .mask = BIT(0), .enable = BIT(0), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_TAP, }, { .name = "event-hold", .mask = BIT(1), .enable = BIT(1), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-swipe-x-neg", .mask = BIT(2), .enable = BIT(2), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-x-pos", .mask = BIT(3), .enable = BIT(3), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-y-pos", .mask = BIT(4), .enable = BIT(4), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, { .name = "event-swipe-y-neg", .mask = BIT(5), .enable = BIT(5), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, }; static const struct iqs7211_event_desc iqs7211a_kp_events[] = { { .mask = BIT(14), .reg_grp = IQS7211_REG_GRP_ALP, }, { .name = "event-tap", .mask = BIT(0), .enable = BIT(0), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_TAP, }, { .name = "event-hold", .mask = BIT(1), .enable = BIT(1), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-swipe-x-neg", .mask = BIT(2), .enable = BIT(2), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-x-pos", .mask = BIT(3), .enable = BIT(3), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-y-pos", .mask = BIT(4), .enable = BIT(4), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, { .name = "event-swipe-y-neg", .mask = BIT(5), .enable = BIT(5), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, }; static const struct iqs7211_event_desc iqs7211e_kp_events[] = { { .mask = BIT(14), .reg_grp = IQS7211_REG_GRP_ALP, }, { .name = "event-tap", .mask = BIT(0), .enable = BIT(0), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_TAP, }, { .name = "event-tap-double", .mask = BIT(1), .enable = BIT(1), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_TAP, }, { .name = "event-tap-triple", .mask = BIT(2), .enable = BIT(2), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_TAP, }, { .name = "event-hold", .mask = BIT(3), .enable = BIT(3), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-palm", .mask = BIT(4), .enable = BIT(4), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_PALM, }, { .name = "event-swipe-x-pos", .mask = BIT(8), .enable = BIT(8), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-x-neg", .mask = BIT(9), .enable = BIT(9), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_X, }, { .name = "event-swipe-y-pos", .mask = BIT(10), .enable = BIT(10), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, { .name = "event-swipe-y-neg", .mask = BIT(11), .enable = BIT(11), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_AXIAL_Y, }, { .name = "event-swipe-x-pos-hold", .mask = BIT(12), .enable = BIT(12), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-swipe-x-neg-hold", .mask = BIT(13), .enable = BIT(13), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-swipe-y-pos-hold", .mask = BIT(14), .enable = BIT(14), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, { .name = "event-swipe-y-neg-hold", .mask = BIT(15), .enable = BIT(15), .reg_grp = IQS7211_REG_GRP_TP, .reg_key = IQS7211_REG_KEY_HOLD, }, }; struct iqs7211_dev_desc { const char *tp_name; const char *kp_name; u16 prod_num; u16 show_reset; u16 ati_error[IQS7211_NUM_REG_GRPS]; u16 ati_start[IQS7211_NUM_REG_GRPS]; u16 suspend; u16 ack_reset; u16 comms_end; u16 comms_req; int charge_shift; int info_offs; int gesture_offs; int contact_offs; u8 sys_stat; u8 sys_ctrl; u8 alp_config; u8 tp_config; u8 exp_file; u8 kp_enable[IQS7211_NUM_REG_GRPS]; u8 gesture_angle; u8 rx_tx_map; u8 cycle_alloc[2]; u8 cycle_limit[2]; const struct iqs7211_event_desc *kp_events; int num_kp_events; int min_crx_alp; int num_ctx; }; static const struct iqs7211_dev_desc iqs7211_devs[] = { [IQS7210A] = { .tp_name = "iqs7210a_trackpad", .kp_name = "iqs7210a_keys", .prod_num = 944, .show_reset = BIT(15), .ati_error = { [IQS7211_REG_GRP_TP] = BIT(12), [IQS7211_REG_GRP_BTN] = BIT(0), [IQS7211_REG_GRP_ALP] = BIT(8), }, .ati_start = { [IQS7211_REG_GRP_TP] = BIT(13), [IQS7211_REG_GRP_BTN] = BIT(1), [IQS7211_REG_GRP_ALP] = BIT(9), }, .suspend = BIT(11), .ack_reset = BIT(7), .comms_end = BIT(2), .comms_req = BIT(1), .charge_shift = 4, .info_offs = 0, .gesture_offs = 1, .contact_offs = 4, .sys_stat = 0x0A, .sys_ctrl = 0x35, .alp_config = 0x39, .tp_config = 0x4E, .exp_file = 0x57, .kp_enable = { [IQS7211_REG_GRP_TP] = 0x58, [IQS7211_REG_GRP_BTN] = 0x37, [IQS7211_REG_GRP_ALP] = 0x37, }, .gesture_angle = 0x5F, .rx_tx_map = 0x60, .cycle_alloc = { 0x66, 0x75, }, .cycle_limit = { 10, 6, }, .kp_events = iqs7210a_kp_events, .num_kp_events = ARRAY_SIZE(iqs7210a_kp_events), .min_crx_alp = 4, .num_ctx = IQS7211_MAX_CTX - 1, }, [IQS7211A] = { .tp_name = "iqs7211a_trackpad", .kp_name = "iqs7211a_keys", .prod_num = 763, .show_reset = BIT(7), .ati_error = { [IQS7211_REG_GRP_TP] = BIT(3), [IQS7211_REG_GRP_ALP] = BIT(5), }, .ati_start = { [IQS7211_REG_GRP_TP] = BIT(5), [IQS7211_REG_GRP_ALP] = BIT(6), }, .ack_reset = BIT(7), .comms_req = BIT(4), .charge_shift = 0, .info_offs = 0, .gesture_offs = 1, .contact_offs = 4, .sys_stat = 0x10, .sys_ctrl = 0x50, .tp_config = 0x60, .alp_config = 0x72, .exp_file = 0x74, .kp_enable = { [IQS7211_REG_GRP_TP] = 0x80, }, .gesture_angle = 0x87, .rx_tx_map = 0x90, .cycle_alloc = { 0xA0, 0xB0, }, .cycle_limit = { 10, 8, }, .kp_events = iqs7211a_kp_events, .num_kp_events = ARRAY_SIZE(iqs7211a_kp_events), .num_ctx = IQS7211_MAX_CTX - 1, }, [IQS7211E] = { .tp_name = "iqs7211e_trackpad", .kp_name = "iqs7211e_keys", .prod_num = 1112, .show_reset = BIT(7), .ati_error = { [IQS7211_REG_GRP_TP] = BIT(3), [IQS7211_REG_GRP_ALP] = BIT(5), }, .ati_start = { [IQS7211_REG_GRP_TP] = BIT(5), [IQS7211_REG_GRP_ALP] = BIT(6), }, .suspend = BIT(11), .ack_reset = BIT(7), .comms_end = BIT(6), .comms_req = BIT(4), .charge_shift = 0, .info_offs = 1, .gesture_offs = 0, .contact_offs = 2, .sys_stat = 0x0E, .sys_ctrl = 0x33, .tp_config = 0x41, .alp_config = 0x36, .exp_file = 0x4A, .kp_enable = { [IQS7211_REG_GRP_TP] = 0x4B, }, .gesture_angle = 0x55, .rx_tx_map = 0x56, .cycle_alloc = { 0x5D, 0x6C, }, .cycle_limit = { 10, 11, }, .kp_events = iqs7211e_kp_events, .num_kp_events = ARRAY_SIZE(iqs7211e_kp_events), .num_ctx = IQS7211_MAX_CTX, }, }; struct iqs7211_prop_desc { const char *name; enum iqs7211_reg_key_id reg_key; u8 reg_addr[IQS7211_NUM_REG_GRPS][ARRAY_SIZE(iqs7211_devs)]; int reg_shift; int reg_width; int val_pitch; int val_min; int val_max; const char *label; }; static const struct iqs7211_prop_desc iqs7211_props[] = { { .name = "azoteq,ati-frac-div-fine", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x1E, [IQS7211A] = 0x30, [IQS7211E] = 0x21, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x22, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x23, [IQS7211A] = 0x36, [IQS7211E] = 0x25, }, }, .reg_shift = 9, .reg_width = 5, .label = "ATI fine fractional divider", }, { .name = "azoteq,ati-frac-mult-coarse", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x1E, [IQS7211A] = 0x30, [IQS7211E] = 0x21, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x22, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x23, [IQS7211A] = 0x36, [IQS7211E] = 0x25, }, }, .reg_shift = 5, .reg_width = 4, .label = "ATI coarse fractional multiplier", }, { .name = "azoteq,ati-frac-div-coarse", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x1E, [IQS7211A] = 0x30, [IQS7211E] = 0x21, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x22, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x23, [IQS7211A] = 0x36, [IQS7211E] = 0x25, }, }, .reg_shift = 0, .reg_width = 5, .label = "ATI coarse fractional divider", }, { .name = "azoteq,ati-comp-div", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x1F, [IQS7211E] = 0x22, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x24, }, [IQS7211_REG_GRP_ALP] = { [IQS7211E] = 0x26, }, }, .reg_shift = 0, .reg_width = 8, .val_max = 31, .label = "ATI compensation divider", }, { .name = "azoteq,ati-comp-div", .reg_addr = { [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x24, }, }, .reg_shift = 8, .reg_width = 8, .val_max = 31, .label = "ATI compensation divider", }, { .name = "azoteq,ati-comp-div", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7211A] = 0x31, }, [IQS7211_REG_GRP_ALP] = { [IQS7211A] = 0x37, }, }, .val_max = 31, .label = "ATI compensation divider", }, { .name = "azoteq,ati-target", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x20, [IQS7211A] = 0x32, [IQS7211E] = 0x23, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x27, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x28, [IQS7211A] = 0x38, [IQS7211E] = 0x27, }, }, .label = "ATI target", }, { .name = "azoteq,ati-base", .reg_addr[IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x26, }, .reg_shift = 8, .reg_width = 8, .val_pitch = 8, .label = "ATI base", }, { .name = "azoteq,ati-base", .reg_addr[IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x26, }, .reg_shift = 0, .reg_width = 8, .val_pitch = 8, .label = "ATI base", }, { .name = "azoteq,rate-active-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x29, [IQS7211A] = 0x40, [IQS7211E] = 0x28, }, .label = "active mode report rate", }, { .name = "azoteq,rate-touch-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2A, [IQS7211A] = 0x41, [IQS7211E] = 0x29, }, .label = "idle-touch mode report rate", }, { .name = "azoteq,rate-idle-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2B, [IQS7211A] = 0x42, [IQS7211E] = 0x2A, }, .label = "idle mode report rate", }, { .name = "azoteq,rate-lp1-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2C, [IQS7211A] = 0x43, [IQS7211E] = 0x2B, }, .label = "low-power mode 1 report rate", }, { .name = "azoteq,rate-lp2-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2D, [IQS7211A] = 0x44, [IQS7211E] = 0x2C, }, .label = "low-power mode 2 report rate", }, { .name = "azoteq,timeout-active-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2E, [IQS7211A] = 0x45, [IQS7211E] = 0x2D, }, .val_pitch = 1000, .label = "active mode timeout", }, { .name = "azoteq,timeout-touch-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x2F, [IQS7211A] = 0x46, [IQS7211E] = 0x2E, }, .val_pitch = 1000, .label = "idle-touch mode timeout", }, { .name = "azoteq,timeout-idle-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x30, [IQS7211A] = 0x47, [IQS7211E] = 0x2F, }, .val_pitch = 1000, .label = "idle mode timeout", }, { .name = "azoteq,timeout-lp1-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x31, [IQS7211A] = 0x48, [IQS7211E] = 0x30, }, .val_pitch = 1000, .label = "low-power mode 1 timeout", }, { .name = "azoteq,timeout-lp2-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x32, [IQS7211E] = 0x31, }, .reg_shift = 8, .reg_width = 8, .val_pitch = 1000, .val_max = 60000, .label = "trackpad reference value update rate", }, { .name = "azoteq,timeout-lp2-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7211A] = 0x49, }, .val_pitch = 1000, .val_max = 60000, .label = "trackpad reference value update rate", }, { .name = "azoteq,timeout-ati-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x32, [IQS7211E] = 0x31, }, .reg_width = 8, .val_pitch = 1000, .val_max = 60000, .label = "ATI error timeout", }, { .name = "azoteq,timeout-ati-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7211A] = 0x35, }, .val_pitch = 1000, .val_max = 60000, .label = "ATI error timeout", }, { .name = "azoteq,timeout-comms-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x33, [IQS7211A] = 0x4A, [IQS7211E] = 0x32, }, .label = "communication timeout", }, { .name = "azoteq,timeout-press-ms", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x34, }, .reg_width = 8, .val_pitch = 1000, .val_max = 60000, .label = "press timeout", }, { .name = "azoteq,ati-mode", .reg_addr[IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x37, }, .reg_shift = 15, .reg_width = 1, .label = "ATI mode", }, { .name = "azoteq,ati-mode", .reg_addr[IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x37, }, .reg_shift = 7, .reg_width = 1, .label = "ATI mode", }, { .name = "azoteq,sense-mode", .reg_addr[IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x37, [IQS7211A] = 0x72, [IQS7211E] = 0x36, }, .reg_shift = 8, .reg_width = 1, .label = "sensing mode", }, { .name = "azoteq,sense-mode", .reg_addr[IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x37, }, .reg_shift = 0, .reg_width = 2, .val_max = 2, .label = "sensing mode", }, { .name = "azoteq,fosc-freq", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x38, [IQS7211A] = 0x52, [IQS7211E] = 0x35, }, .reg_shift = 4, .reg_width = 1, .label = "core clock frequency selection", }, { .name = "azoteq,fosc-trim", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x38, [IQS7211A] = 0x52, [IQS7211E] = 0x35, }, .reg_shift = 0, .reg_width = 4, .label = "core clock frequency trim", }, { .name = "azoteq,touch-exit", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x3B, [IQS7211A] = 0x53, [IQS7211E] = 0x38, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x3E, }, }, .reg_shift = 8, .reg_width = 8, .label = "touch exit factor", }, { .name = "azoteq,touch-enter", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x3B, [IQS7211A] = 0x53, [IQS7211E] = 0x38, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x3E, }, }, .reg_shift = 0, .reg_width = 8, .label = "touch entrance factor", }, { .name = "azoteq,thresh", .reg_addr = { [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x3C, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x3D, [IQS7211A] = 0x54, [IQS7211E] = 0x39, }, }, .label = "threshold", }, { .name = "azoteq,debounce-exit", .reg_addr = { [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x3F, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x40, [IQS7211A] = 0x56, [IQS7211E] = 0x3A, }, }, .reg_shift = 8, .reg_width = 8, .label = "debounce exit factor", }, { .name = "azoteq,debounce-enter", .reg_addr = { [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x3F, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x40, [IQS7211A] = 0x56, [IQS7211E] = 0x3A, }, }, .reg_shift = 0, .reg_width = 8, .label = "debounce entrance factor", }, { .name = "azoteq,conv-frac", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x48, [IQS7211A] = 0x58, [IQS7211E] = 0x3D, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x49, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x4A, [IQS7211A] = 0x59, [IQS7211E] = 0x3E, }, }, .reg_shift = 8, .reg_width = 8, .label = "conversion frequency fractional divider", }, { .name = "azoteq,conv-period", .reg_addr = { [IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x48, [IQS7211A] = 0x58, [IQS7211E] = 0x3D, }, [IQS7211_REG_GRP_BTN] = { [IQS7210A] = 0x49, }, [IQS7211_REG_GRP_ALP] = { [IQS7210A] = 0x4A, [IQS7211A] = 0x59, [IQS7211E] = 0x3E, }, }, .reg_shift = 0, .reg_width = 8, .label = "conversion period", }, { .name = "azoteq,thresh", .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x55, [IQS7211A] = 0x67, [IQS7211E] = 0x48, }, .reg_shift = 0, .reg_width = 8, .label = "threshold", }, { .name = "azoteq,contact-split", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x55, [IQS7211A] = 0x67, [IQS7211E] = 0x48, }, .reg_shift = 8, .reg_width = 8, .label = "contact split factor", }, { .name = "azoteq,trim-x", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x56, [IQS7211E] = 0x49, }, .reg_shift = 0, .reg_width = 8, .label = "horizontal trim width", }, { .name = "azoteq,trim-x", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7211A] = 0x68, }, .label = "horizontal trim width", }, { .name = "azoteq,trim-y", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7210A] = 0x56, [IQS7211E] = 0x49, }, .reg_shift = 8, .reg_width = 8, .label = "vertical trim height", }, { .name = "azoteq,trim-y", .reg_addr[IQS7211_REG_GRP_SYS] = { [IQS7211A] = 0x69, }, .label = "vertical trim height", }, { .name = "azoteq,gesture-max-ms", .reg_key = IQS7211_REG_KEY_TAP, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x59, [IQS7211A] = 0x81, [IQS7211E] = 0x4C, }, .label = "maximum gesture time", }, { .name = "azoteq,gesture-mid-ms", .reg_key = IQS7211_REG_KEY_TAP, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7211E] = 0x4D, }, .label = "repeated gesture time", }, { .name = "azoteq,gesture-dist", .reg_key = IQS7211_REG_KEY_TAP, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5A, [IQS7211A] = 0x82, [IQS7211E] = 0x4E, }, .label = "gesture distance", }, { .name = "azoteq,gesture-dist", .reg_key = IQS7211_REG_KEY_HOLD, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5A, [IQS7211A] = 0x82, [IQS7211E] = 0x4E, }, .label = "gesture distance", }, { .name = "azoteq,gesture-min-ms", .reg_key = IQS7211_REG_KEY_HOLD, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5B, [IQS7211A] = 0x83, [IQS7211E] = 0x4F, }, .label = "minimum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_key = IQS7211_REG_KEY_AXIAL_X, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5C, [IQS7211A] = 0x84, [IQS7211E] = 0x50, }, .label = "maximum gesture time", }, { .name = "azoteq,gesture-max-ms", .reg_key = IQS7211_REG_KEY_AXIAL_Y, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5C, [IQS7211A] = 0x84, [IQS7211E] = 0x50, }, .label = "maximum gesture time", }, { .name = "azoteq,gesture-dist", .reg_key = IQS7211_REG_KEY_AXIAL_X, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5D, [IQS7211A] = 0x85, [IQS7211E] = 0x51, }, .label = "gesture distance", }, { .name = "azoteq,gesture-dist", .reg_key = IQS7211_REG_KEY_AXIAL_Y, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7210A] = 0x5E, [IQS7211A] = 0x86, [IQS7211E] = 0x52, }, .label = "gesture distance", }, { .name = "azoteq,gesture-dist-rep", .reg_key = IQS7211_REG_KEY_AXIAL_X, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7211E] = 0x53, }, .label = "repeated gesture distance", }, { .name = "azoteq,gesture-dist-rep", .reg_key = IQS7211_REG_KEY_AXIAL_Y, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7211E] = 0x54, }, .label = "repeated gesture distance", }, { .name = "azoteq,thresh", .reg_key = IQS7211_REG_KEY_PALM, .reg_addr[IQS7211_REG_GRP_TP] = { [IQS7211E] = 0x55, }, .reg_shift = 8, .reg_width = 8, .val_max = 42, .label = "threshold", }, }; static const u8 iqs7211_gesture_angle[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x14, 0x15, 0x16, 0x17, 0x19, 0x1A, 0x1B, 0x1C, 0x1E, 0x1F, 0x21, 0x22, 0x23, 0x25, 0x26, 0x28, 0x2A, 0x2B, 0x2D, 0x2E, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3A, 0x3C, 0x3E, 0x40, 0x42, 0x45, 0x47, 0x4A, 0x4C, 0x4F, 0x52, 0x55, 0x58, 0x5B, 0x5F, 0x63, 0x66, 0x6B, 0x6F, 0x73, 0x78, 0x7E, 0x83, 0x89, 0x90, 0x97, 0x9E, 0xA7, 0xB0, 0xBA, 0xC5, 0xD1, 0xDF, 0xEF, }; struct iqs7211_ver_info { __le16 prod_num; __le16 major; __le16 minor; __le32 patch; } __packed; struct iqs7211_touch_data { __le16 abs_x; __le16 abs_y; __le16 pressure; __le16 area; } __packed; struct iqs7211_tp_config { u8 tp_settings; u8 total_rx; u8 total_tx; u8 num_contacts; __le16 max_x; __le16 max_y; } __packed; struct iqs7211_private { const struct iqs7211_dev_desc *dev_desc; struct gpio_desc *reset_gpio; struct gpio_desc *irq_gpio; struct i2c_client *client; struct input_dev *tp_idev; struct input_dev *kp_idev; struct iqs7211_ver_info ver_info; struct iqs7211_tp_config tp_config; struct touchscreen_properties prop; struct list_head reg_field_head; enum iqs7211_comms_mode comms_init; enum iqs7211_comms_mode comms_mode; unsigned int num_contacts; unsigned int kp_code[ARRAY_SIZE(iqs7211e_kp_events)]; u8 rx_tx_map[IQS7211_MAX_CTX + 1]; u8 cycle_alloc[2][33]; u8 exp_file[2]; u16 event_mask; u16 ati_start; u16 gesture_cache; }; static int iqs7211_irq_poll(struct iqs7211_private *iqs7211, u64 timeout_us) { int error, val; error = readx_poll_timeout(gpiod_get_value_cansleep, iqs7211->irq_gpio, val, val, IQS7211_COMMS_SLEEP_US, timeout_us); return val < 0 ? val : error; } static int iqs7211_hard_reset(struct iqs7211_private *iqs7211) { if (!iqs7211->reset_gpio) return 0; gpiod_set_value_cansleep(iqs7211->reset_gpio, 1); /* * The following delay ensures the shared RDY/MCLR pin is sampled in * between periodic assertions by the device and assumes the default * communication timeout has not been overwritten in OTP memory. */ if (iqs7211->reset_gpio == iqs7211->irq_gpio) msleep(IQS7211_RESET_TIMEOUT_MS); else usleep_range(1000, 1100); gpiod_set_value_cansleep(iqs7211->reset_gpio, 0); if (iqs7211->reset_gpio == iqs7211->irq_gpio) iqs7211_irq_wait(); return iqs7211_irq_poll(iqs7211, IQS7211_START_TIMEOUT_US); } static int iqs7211_force_comms(struct iqs7211_private *iqs7211) { u8 msg_buf[] = { 0xFF, }; int ret; switch (iqs7211->comms_mode) { case IQS7211_COMMS_MODE_WAIT: return iqs7211_irq_poll(iqs7211, IQS7211_START_TIMEOUT_US); case IQS7211_COMMS_MODE_FREE: return 0; case IQS7211_COMMS_MODE_FORCE: break; default: return -EINVAL; } /* * The device cannot communicate until it asserts its interrupt (RDY) * pin. Attempts to do so while RDY is deasserted return an ACK; how- * ever all write data is ignored, and all read data returns 0xEE. * * Unsolicited communication must be preceded by a special force com- * munication command, after which the device eventually asserts its * RDY pin and agrees to communicate. * * Regardless of whether communication is forced or the result of an * interrupt, the device automatically deasserts its RDY pin once it * detects an I2C stop condition, or a timeout expires. */ ret = gpiod_get_value_cansleep(iqs7211->irq_gpio); if (ret < 0) return ret; else if (ret > 0) return 0; ret = i2c_master_send(iqs7211->client, msg_buf, sizeof(msg_buf)); if (ret < (int)sizeof(msg_buf)) { if (ret >= 0) ret = -EIO; msleep(IQS7211_COMMS_RETRY_MS); return ret; } iqs7211_irq_wait(); return iqs7211_irq_poll(iqs7211, IQS7211_COMMS_TIMEOUT_US); } static int iqs7211_read_burst(struct iqs7211_private *iqs7211, u8 reg, void *val, u16 val_len) { int ret, i; struct i2c_client *client = iqs7211->client; struct i2c_msg msg[] = { { .addr = client->addr, .flags = 0, .len = sizeof(reg), .buf = &reg, }, { .addr = client->addr, .flags = I2C_M_RD, .len = val_len, .buf = (u8 *)val, }, }; /* * The following loop protects against an edge case in which the RDY * pin is automatically deasserted just as the read is initiated. In * that case, the read must be retried using forced communication. */ for (i = 0; i < IQS7211_NUM_RETRIES; i++) { ret = iqs7211_force_comms(iqs7211); if (ret < 0) continue; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret < (int)ARRAY_SIZE(msg)) { if (ret >= 0) ret = -EIO; msleep(IQS7211_COMMS_RETRY_MS); continue; } if (get_unaligned_le16(msg[1].buf) == IQS7211_COMMS_ERROR) { ret = -ENODATA; continue; } ret = 0; break; } iqs7211_irq_wait(); if (ret < 0) dev_err(&client->dev, "Failed to read from address 0x%02X: %d\n", reg, ret); return ret; } static int iqs7211_read_word(struct iqs7211_private *iqs7211, u8 reg, u16 *val) { __le16 val_buf; int error; error = iqs7211_read_burst(iqs7211, reg, &val_buf, sizeof(val_buf)); if (error) return error; *val = le16_to_cpu(val_buf); return 0; } static int iqs7211_write_burst(struct iqs7211_private *iqs7211, u8 reg, const void *val, u16 val_len) { int msg_len = sizeof(reg) + val_len; int ret, i; struct i2c_client *client = iqs7211->client; u8 *msg_buf; msg_buf = kzalloc(msg_len, GFP_KERNEL); if (!msg_buf) return -ENOMEM; *msg_buf = reg; memcpy(msg_buf + sizeof(reg), val, val_len); /* * The following loop protects against an edge case in which the RDY * pin is automatically asserted just before the force communication * command is sent. * * In that case, the subsequent I2C stop condition tricks the device * into preemptively deasserting the RDY pin and the command must be * sent again. */ for (i = 0; i < IQS7211_NUM_RETRIES; i++) { ret = iqs7211_force_comms(iqs7211); if (ret < 0) continue; ret = i2c_master_send(client, msg_buf, msg_len); if (ret < msg_len) { if (ret >= 0) ret = -EIO; msleep(IQS7211_COMMS_RETRY_MS); continue; } ret = 0; break; } kfree(msg_buf); iqs7211_irq_wait(); if (ret < 0) dev_err(&client->dev, "Failed to write to address 0x%02X: %d\n", reg, ret); return ret; } static int iqs7211_write_word(struct iqs7211_private *iqs7211, u8 reg, u16 val) { __le16 val_buf = cpu_to_le16(val); return iqs7211_write_burst(iqs7211, reg, &val_buf, sizeof(val_buf)); } static int iqs7211_start_comms(struct iqs7211_private *iqs7211) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; bool forced_comms; unsigned int val; u16 comms_setup; int error; /* * Until forced communication can be enabled, the host must wait for a * communication window each time it intends to elicit a response from * the device. * * Forced communication is not necessary, however, if the host adapter * can support clock stretching. In that case, the device freely clock * stretches until all pending conversions are complete. */ forced_comms = device_property_present(&client->dev, "azoteq,forced-comms"); error = device_property_read_u32(&client->dev, "azoteq,forced-comms-default", &val); if (error == -EINVAL) { iqs7211->comms_init = IQS7211_COMMS_MODE_WAIT; } else if (error) { dev_err(&client->dev, "Failed to read default communication mode: %d\n", error); return error; } else if (val) { iqs7211->comms_init = forced_comms ? IQS7211_COMMS_MODE_FORCE : IQS7211_COMMS_MODE_WAIT; } else { iqs7211->comms_init = forced_comms ? IQS7211_COMMS_MODE_WAIT : IQS7211_COMMS_MODE_FREE; } iqs7211->comms_mode = iqs7211->comms_init; error = iqs7211_hard_reset(iqs7211); if (error) { dev_err(&client->dev, "Failed to reset device: %d\n", error); return error; } error = iqs7211_read_burst(iqs7211, IQS7211_PROD_NUM, &iqs7211->ver_info, sizeof(iqs7211->ver_info)); if (error) return error; if (le16_to_cpu(iqs7211->ver_info.prod_num) != dev_desc->prod_num) { dev_err(&client->dev, "Invalid product number: %u\n", le16_to_cpu(iqs7211->ver_info.prod_num)); return -EINVAL; } error = iqs7211_read_word(iqs7211, dev_desc->sys_ctrl + 1, &comms_setup); if (error) return error; if (forced_comms) comms_setup |= dev_desc->comms_req; else comms_setup &= ~dev_desc->comms_req; error = iqs7211_write_word(iqs7211, dev_desc->sys_ctrl + 1, comms_setup | dev_desc->comms_end); if (error) return error; if (forced_comms) iqs7211->comms_mode = IQS7211_COMMS_MODE_FORCE; else iqs7211->comms_mode = IQS7211_COMMS_MODE_FREE; error = iqs7211_read_burst(iqs7211, dev_desc->exp_file, iqs7211->exp_file, sizeof(iqs7211->exp_file)); if (error) return error; error = iqs7211_read_burst(iqs7211, dev_desc->tp_config, &iqs7211->tp_config, sizeof(iqs7211->tp_config)); if (error) return error; error = iqs7211_write_word(iqs7211, dev_desc->sys_ctrl + 1, comms_setup); if (error) return error; iqs7211->event_mask = comms_setup & ~IQS7211_EVENT_MASK_ALL; iqs7211->event_mask |= (IQS7211_EVENT_MASK_ATI | IQS7211_EVENT_MODE); return 0; } static int iqs7211_init_device(struct iqs7211_private *iqs7211) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct iqs7211_reg_field_desc *reg_field; __le16 sys_ctrl[] = { cpu_to_le16(dev_desc->ack_reset), cpu_to_le16(iqs7211->event_mask), }; int error, i; /* * Acknowledge reset before writing any registers in case the device * suffers a spurious reset during initialization. The communication * mode is configured at this time as well. */ error = iqs7211_write_burst(iqs7211, dev_desc->sys_ctrl, sys_ctrl, sizeof(sys_ctrl)); if (error) return error; if (iqs7211->event_mask & dev_desc->comms_req) iqs7211->comms_mode = IQS7211_COMMS_MODE_FORCE; else iqs7211->comms_mode = IQS7211_COMMS_MODE_FREE; /* * Take advantage of the stop-bit disable function, if available, to * save the trouble of having to reopen a communication window after * each read or write. */ error = iqs7211_write_word(iqs7211, dev_desc->sys_ctrl + 1, iqs7211->event_mask | dev_desc->comms_end); if (error) return error; list_for_each_entry(reg_field, &iqs7211->reg_field_head, list) { u16 new_val = reg_field->val; if (reg_field->mask < U16_MAX) { u16 old_val; error = iqs7211_read_word(iqs7211, reg_field->addr, &old_val); if (error) return error; new_val = old_val & ~reg_field->mask; new_val |= reg_field->val; if (new_val == old_val) continue; } error = iqs7211_write_word(iqs7211, reg_field->addr, new_val); if (error) return error; } error = iqs7211_write_burst(iqs7211, dev_desc->tp_config, &iqs7211->tp_config, sizeof(iqs7211->tp_config)); if (error) return error; if (**iqs7211->cycle_alloc) { error = iqs7211_write_burst(iqs7211, dev_desc->rx_tx_map, &iqs7211->rx_tx_map, dev_desc->num_ctx); if (error) return error; for (i = 0; i < sizeof(dev_desc->cycle_limit); i++) { error = iqs7211_write_burst(iqs7211, dev_desc->cycle_alloc[i], iqs7211->cycle_alloc[i], dev_desc->cycle_limit[i] * 3); if (error) return error; } } *sys_ctrl = cpu_to_le16(iqs7211->ati_start); return iqs7211_write_burst(iqs7211, dev_desc->sys_ctrl, sys_ctrl, sizeof(sys_ctrl)); } static int iqs7211_add_field(struct iqs7211_private *iqs7211, struct iqs7211_reg_field_desc new_field) { struct i2c_client *client = iqs7211->client; struct iqs7211_reg_field_desc *reg_field; if (!new_field.addr) return 0; list_for_each_entry(reg_field, &iqs7211->reg_field_head, list) { if (reg_field->addr != new_field.addr) continue; reg_field->mask |= new_field.mask; reg_field->val |= new_field.val; return 0; } reg_field = devm_kzalloc(&client->dev, sizeof(*reg_field), GFP_KERNEL); if (!reg_field) return -ENOMEM; reg_field->addr = new_field.addr; reg_field->mask = new_field.mask; reg_field->val = new_field.val; list_add(&reg_field->list, &iqs7211->reg_field_head); return 0; } static int iqs7211_parse_props(struct iqs7211_private *iqs7211, struct fwnode_handle *reg_grp_node, enum iqs7211_reg_grp_id reg_grp, enum iqs7211_reg_key_id reg_key) { struct i2c_client *client = iqs7211->client; int i; for (i = 0; i < ARRAY_SIZE(iqs7211_props); i++) { const char *name = iqs7211_props[i].name; u8 reg_addr = iqs7211_props[i].reg_addr[reg_grp] [iqs7211->dev_desc - iqs7211_devs]; int reg_shift = iqs7211_props[i].reg_shift; int reg_width = iqs7211_props[i].reg_width ? : 16; int val_pitch = iqs7211_props[i].val_pitch ? : 1; int val_min = iqs7211_props[i].val_min; int val_max = iqs7211_props[i].val_max; const char *label = iqs7211_props[i].label ? : name; struct iqs7211_reg_field_desc reg_field; unsigned int val; int error; if (iqs7211_props[i].reg_key != reg_key) continue; if (!reg_addr) continue; error = fwnode_property_read_u32(reg_grp_node, name, &val); if (error == -EINVAL) { continue; } else if (error) { dev_err(&client->dev, "Failed to read %s %s: %d\n", fwnode_get_name(reg_grp_node), label, error); return error; } if (!val_max) val_max = GENMASK(reg_width - 1, 0) * val_pitch; if (val < val_min || val > val_max) { dev_err(&client->dev, "Invalid %s: %u\n", label, val); return -EINVAL; } reg_field.addr = reg_addr; reg_field.mask = GENMASK(reg_shift + reg_width - 1, reg_shift); reg_field.val = val / val_pitch << reg_shift; error = iqs7211_add_field(iqs7211, reg_field); if (error) return error; } return 0; } static int iqs7211_parse_event(struct iqs7211_private *iqs7211, struct fwnode_handle *event_node, enum iqs7211_reg_grp_id reg_grp, enum iqs7211_reg_key_id reg_key, unsigned int *event_code) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; struct iqs7211_reg_field_desc reg_field; unsigned int val; int error; error = iqs7211_parse_props(iqs7211, event_node, reg_grp, reg_key); if (error) return error; if (reg_key == IQS7211_REG_KEY_AXIAL_X || reg_key == IQS7211_REG_KEY_AXIAL_Y) { error = fwnode_property_read_u32(event_node, "azoteq,gesture-angle", &val); if (!error) { if (val >= ARRAY_SIZE(iqs7211_gesture_angle)) { dev_err(&client->dev, "Invalid %s gesture angle: %u\n", fwnode_get_name(event_node), val); return -EINVAL; } reg_field.addr = dev_desc->gesture_angle; reg_field.mask = U8_MAX; reg_field.val = iqs7211_gesture_angle[val]; error = iqs7211_add_field(iqs7211, reg_field); if (error) return error; } else if (error != -EINVAL) { dev_err(&client->dev, "Failed to read %s gesture angle: %d\n", fwnode_get_name(event_node), error); return error; } } error = fwnode_property_read_u32(event_node, "linux,code", event_code); if (error == -EINVAL) error = 0; else if (error) dev_err(&client->dev, "Failed to read %s code: %d\n", fwnode_get_name(event_node), error); return error; } static int iqs7211_parse_cycles(struct iqs7211_private *iqs7211, struct fwnode_handle *tp_node) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; int num_cycles = dev_desc->cycle_limit[0] + dev_desc->cycle_limit[1]; int error, count, i, j, k, cycle_start; unsigned int cycle_alloc[IQS7211_MAX_CYCLES][2]; u8 total_rx = iqs7211->tp_config.total_rx; u8 total_tx = iqs7211->tp_config.total_tx; for (i = 0; i < IQS7211_MAX_CYCLES * 2; i++) *(cycle_alloc[0] + i) = U8_MAX; count = fwnode_property_count_u32(tp_node, "azoteq,channel-select"); if (count == -EINVAL) { /* * Assign each sensing cycle's slots (0 and 1) to a channel, * defined as the intersection between two CRx and CTx pins. * A channel assignment of 255 means the slot is unused. */ for (i = 0, cycle_start = 0; i < total_tx; i++) { int cycle_stop = 0; for (j = 0; j < total_rx; j++) { /* * Channels formed by CRx0-3 and CRx4-7 are * bound to slots 0 and 1, respectively. */ int slot = iqs7211->rx_tx_map[j] < 4 ? 0 : 1; int chan = i * total_rx + j; for (k = cycle_start; k < num_cycles; k++) { if (cycle_alloc[k][slot] < U8_MAX) continue; cycle_alloc[k][slot] = chan; break; } if (k < num_cycles) { cycle_stop = max(k, cycle_stop); continue; } dev_err(&client->dev, "Insufficient number of cycles\n"); return -EINVAL; } /* * Sensing cycles cannot straddle more than one CTx * pin. As such, the next row's starting cycle must * be greater than the previous row's highest cycle. */ cycle_start = cycle_stop + 1; } } else if (count < 0) { dev_err(&client->dev, "Failed to count channels: %d\n", count); return count; } else if (count > num_cycles * 2) { dev_err(&client->dev, "Insufficient number of cycles\n"); return -EINVAL; } else if (count > 0) { error = fwnode_property_read_u32_array(tp_node, "azoteq,channel-select", cycle_alloc[0], count); if (error) { dev_err(&client->dev, "Failed to read channels: %d\n", error); return error; } for (i = 0; i < count; i++) { int chan = *(cycle_alloc[0] + i); if (chan == U8_MAX) continue; if (chan >= total_rx * total_tx) { dev_err(&client->dev, "Invalid channel: %d\n", chan); return -EINVAL; } for (j = 0; j < count; j++) { if (j == i || *(cycle_alloc[0] + j) != chan) continue; dev_err(&client->dev, "Duplicate channel: %d\n", chan); return -EINVAL; } } } /* * Once the raw channel assignments have been derived, they must be * packed according to the device's register map. */ for (i = 0, cycle_start = 0; i < sizeof(dev_desc->cycle_limit); i++) { int offs = 0; for (j = cycle_start; j < cycle_start + dev_desc->cycle_limit[i]; j++) { iqs7211->cycle_alloc[i][offs++] = 0x05; iqs7211->cycle_alloc[i][offs++] = cycle_alloc[j][0]; iqs7211->cycle_alloc[i][offs++] = cycle_alloc[j][1]; } cycle_start += dev_desc->cycle_limit[i]; } return 0; } static int iqs7211_parse_tp(struct iqs7211_private *iqs7211, struct fwnode_handle *tp_node) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; unsigned int pins[IQS7211_MAX_CTX]; int error, count, i, j; count = fwnode_property_count_u32(tp_node, "azoteq,rx-enable"); if (count == -EINVAL) { return 0; } else if (count < 0) { dev_err(&client->dev, "Failed to count CRx pins: %d\n", count); return count; } else if (count > IQS7211_NUM_CRX) { dev_err(&client->dev, "Invalid number of CRx pins\n"); return -EINVAL; } error = fwnode_property_read_u32_array(tp_node, "azoteq,rx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read CRx pins: %d\n", error); return error; } for (i = 0; i < count; i++) { if (pins[i] >= IQS7211_NUM_CRX) { dev_err(&client->dev, "Invalid CRx pin: %u\n", pins[i]); return -EINVAL; } iqs7211->rx_tx_map[i] = pins[i]; } iqs7211->tp_config.total_rx = count; count = fwnode_property_count_u32(tp_node, "azoteq,tx-enable"); if (count < 0) { dev_err(&client->dev, "Failed to count CTx pins: %d\n", count); return count; } else if (count > dev_desc->num_ctx) { dev_err(&client->dev, "Invalid number of CTx pins\n"); return -EINVAL; } error = fwnode_property_read_u32_array(tp_node, "azoteq,tx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read CTx pins: %d\n", error); return error; } for (i = 0; i < count; i++) { if (pins[i] >= dev_desc->num_ctx) { dev_err(&client->dev, "Invalid CTx pin: %u\n", pins[i]); return -EINVAL; } for (j = 0; j < iqs7211->tp_config.total_rx; j++) { if (iqs7211->rx_tx_map[j] != pins[i]) continue; dev_err(&client->dev, "Conflicting CTx pin: %u\n", pins[i]); return -EINVAL; } iqs7211->rx_tx_map[iqs7211->tp_config.total_rx + i] = pins[i]; } iqs7211->tp_config.total_tx = count; return iqs7211_parse_cycles(iqs7211, tp_node); } static int iqs7211_parse_alp(struct iqs7211_private *iqs7211, struct fwnode_handle *alp_node) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; struct iqs7211_reg_field_desc reg_field; int error, count, i; count = fwnode_property_count_u32(alp_node, "azoteq,rx-enable"); if (count < 0 && count != -EINVAL) { dev_err(&client->dev, "Failed to count CRx pins: %d\n", count); return count; } else if (count > IQS7211_NUM_CRX) { dev_err(&client->dev, "Invalid number of CRx pins\n"); return -EINVAL; } else if (count >= 0) { unsigned int pins[IQS7211_NUM_CRX]; error = fwnode_property_read_u32_array(alp_node, "azoteq,rx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read CRx pins: %d\n", error); return error; } reg_field.addr = dev_desc->alp_config; reg_field.mask = GENMASK(IQS7211_NUM_CRX - 1, 0); reg_field.val = 0; for (i = 0; i < count; i++) { if (pins[i] < dev_desc->min_crx_alp || pins[i] >= IQS7211_NUM_CRX) { dev_err(&client->dev, "Invalid CRx pin: %u\n", pins[i]); return -EINVAL; } reg_field.val |= BIT(pins[i]); } error = iqs7211_add_field(iqs7211, reg_field); if (error) return error; } count = fwnode_property_count_u32(alp_node, "azoteq,tx-enable"); if (count < 0 && count != -EINVAL) { dev_err(&client->dev, "Failed to count CTx pins: %d\n", count); return count; } else if (count > dev_desc->num_ctx) { dev_err(&client->dev, "Invalid number of CTx pins\n"); return -EINVAL; } else if (count >= 0) { unsigned int pins[IQS7211_MAX_CTX]; error = fwnode_property_read_u32_array(alp_node, "azoteq,tx-enable", pins, count); if (error) { dev_err(&client->dev, "Failed to read CTx pins: %d\n", error); return error; } reg_field.addr = dev_desc->alp_config + 1; reg_field.mask = GENMASK(dev_desc->num_ctx - 1, 0); reg_field.val = 0; for (i = 0; i < count; i++) { if (pins[i] >= dev_desc->num_ctx) { dev_err(&client->dev, "Invalid CTx pin: %u\n", pins[i]); return -EINVAL; } reg_field.val |= BIT(pins[i]); } error = iqs7211_add_field(iqs7211, reg_field); if (error) return error; } return 0; } static int (*iqs7211_parse_extra[IQS7211_NUM_REG_GRPS]) (struct iqs7211_private *iqs7211, struct fwnode_handle *reg_grp_node) = { [IQS7211_REG_GRP_TP] = iqs7211_parse_tp, [IQS7211_REG_GRP_ALP] = iqs7211_parse_alp, }; static int iqs7211_parse_reg_grp(struct iqs7211_private *iqs7211, struct fwnode_handle *reg_grp_node, enum iqs7211_reg_grp_id reg_grp) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct iqs7211_reg_field_desc reg_field; int error, i; error = iqs7211_parse_props(iqs7211, reg_grp_node, reg_grp, IQS7211_REG_KEY_NONE); if (error) return error; if (iqs7211_parse_extra[reg_grp]) { error = iqs7211_parse_extra[reg_grp](iqs7211, reg_grp_node); if (error) return error; } iqs7211->ati_start |= dev_desc->ati_start[reg_grp]; reg_field.addr = dev_desc->kp_enable[reg_grp]; reg_field.mask = 0; reg_field.val = 0; for (i = 0; i < dev_desc->num_kp_events; i++) { const char *event_name = dev_desc->kp_events[i].name; struct fwnode_handle *event_node; if (dev_desc->kp_events[i].reg_grp != reg_grp) continue; reg_field.mask |= dev_desc->kp_events[i].enable; if (event_name) event_node = fwnode_get_named_child_node(reg_grp_node, event_name); else event_node = fwnode_handle_get(reg_grp_node); if (!event_node) continue; error = iqs7211_parse_event(iqs7211, event_node, dev_desc->kp_events[i].reg_grp, dev_desc->kp_events[i].reg_key, &iqs7211->kp_code[i]); fwnode_handle_put(event_node); if (error) return error; reg_field.val |= dev_desc->kp_events[i].enable; iqs7211->event_mask |= iqs7211_reg_grp_masks[reg_grp]; } return iqs7211_add_field(iqs7211, reg_field); } static int iqs7211_register_kp(struct iqs7211_private *iqs7211) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct input_dev *kp_idev = iqs7211->kp_idev; struct i2c_client *client = iqs7211->client; int error, i; for (i = 0; i < dev_desc->num_kp_events; i++) if (iqs7211->kp_code[i]) break; if (i == dev_desc->num_kp_events) return 0; kp_idev = devm_input_allocate_device(&client->dev); if (!kp_idev) return -ENOMEM; iqs7211->kp_idev = kp_idev; kp_idev->name = dev_desc->kp_name; kp_idev->id.bustype = BUS_I2C; for (i = 0; i < dev_desc->num_kp_events; i++) if (iqs7211->kp_code[i]) input_set_capability(iqs7211->kp_idev, EV_KEY, iqs7211->kp_code[i]); error = input_register_device(kp_idev); if (error) dev_err(&client->dev, "Failed to register %s: %d\n", kp_idev->name, error); return error; } static int iqs7211_register_tp(struct iqs7211_private *iqs7211) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct touchscreen_properties *prop = &iqs7211->prop; struct input_dev *tp_idev = iqs7211->tp_idev; struct i2c_client *client = iqs7211->client; int error; error = device_property_read_u32(&client->dev, "azoteq,num-contacts", &iqs7211->num_contacts); if (error == -EINVAL) { return 0; } else if (error) { dev_err(&client->dev, "Failed to read number of contacts: %d\n", error); return error; } else if (iqs7211->num_contacts > IQS7211_MAX_CONTACTS) { dev_err(&client->dev, "Invalid number of contacts: %u\n", iqs7211->num_contacts); return -EINVAL; } iqs7211->tp_config.num_contacts = iqs7211->num_contacts ? : 1; if (!iqs7211->num_contacts) return 0; iqs7211->event_mask |= IQS7211_EVENT_MASK_MOVE; tp_idev = devm_input_allocate_device(&client->dev); if (!tp_idev) return -ENOMEM; iqs7211->tp_idev = tp_idev; tp_idev->name = dev_desc->tp_name; tp_idev->id.bustype = BUS_I2C; input_set_abs_params(tp_idev, ABS_MT_POSITION_X, 0, le16_to_cpu(iqs7211->tp_config.max_x), 0, 0); input_set_abs_params(tp_idev, ABS_MT_POSITION_Y, 0, le16_to_cpu(iqs7211->tp_config.max_y), 0, 0); input_set_abs_params(tp_idev, ABS_MT_PRESSURE, 0, U16_MAX, 0, 0); touchscreen_parse_properties(tp_idev, 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 trackpad size: %u*%u\n", prop->max_x, prop->max_y); return -EINVAL; } iqs7211->tp_config.max_x = cpu_to_le16(prop->max_x); iqs7211->tp_config.max_y = cpu_to_le16(prop->max_y); error = input_mt_init_slots(tp_idev, iqs7211->num_contacts, INPUT_MT_DIRECT); if (error) { dev_err(&client->dev, "Failed to initialize slots: %d\n", error); return error; } error = input_register_device(tp_idev); if (error) dev_err(&client->dev, "Failed to register %s: %d\n", tp_idev->name, error); return error; } static int iqs7211_report(struct iqs7211_private *iqs7211) { const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; struct i2c_client *client = iqs7211->client; struct iqs7211_touch_data *touch_data; u16 info_flags, charge_mode, gesture_flags; __le16 status[12]; int error, i; error = iqs7211_read_burst(iqs7211, dev_desc->sys_stat, status, dev_desc->contact_offs * sizeof(__le16) + iqs7211->num_contacts * sizeof(*touch_data)); if (error) return error; info_flags = le16_to_cpu(status[dev_desc->info_offs]); if (info_flags & dev_desc->show_reset) { dev_err(&client->dev, "Unexpected device reset\n"); /* * The device may or may not expect forced communication after * it exits hardware reset, so the corresponding state machine * must be reset as well. */ iqs7211->comms_mode = iqs7211->comms_init; return iqs7211_init_device(iqs7211); } for (i = 0; i < ARRAY_SIZE(dev_desc->ati_error); i++) { if (!(info_flags & dev_desc->ati_error[i])) continue; dev_err(&client->dev, "Unexpected %s ATI error\n", iqs7211_reg_grp_names[i]); return 0; } for (i = 0; i < iqs7211->num_contacts; i++) { u16 pressure; touch_data = (struct iqs7211_touch_data *) &status[dev_desc->contact_offs] + i; pressure = le16_to_cpu(touch_data->pressure); input_mt_slot(iqs7211->tp_idev, i); if (input_mt_report_slot_state(iqs7211->tp_idev, MT_TOOL_FINGER, pressure != 0)) { touchscreen_report_pos(iqs7211->tp_idev, &iqs7211->prop, le16_to_cpu(touch_data->abs_x), le16_to_cpu(touch_data->abs_y), true); input_report_abs(iqs7211->tp_idev, ABS_MT_PRESSURE, pressure); } } if (iqs7211->num_contacts) { input_mt_sync_frame(iqs7211->tp_idev); input_sync(iqs7211->tp_idev); } if (!iqs7211->kp_idev) return 0; charge_mode = info_flags & GENMASK(dev_desc->charge_shift + 2, dev_desc->charge_shift); charge_mode >>= dev_desc->charge_shift; /* * A charging mode higher than 2 (idle mode) indicates the device last * operated in low-power mode and intends to express an ALP event. */ if (info_flags & dev_desc->kp_events->mask && charge_mode > 2) { input_report_key(iqs7211->kp_idev, *iqs7211->kp_code, 1); input_sync(iqs7211->kp_idev); input_report_key(iqs7211->kp_idev, *iqs7211->kp_code, 0); } for (i = 0; i < dev_desc->num_kp_events; i++) { if (dev_desc->kp_events[i].reg_grp != IQS7211_REG_GRP_BTN) continue; input_report_key(iqs7211->kp_idev, iqs7211->kp_code[i], info_flags & dev_desc->kp_events[i].mask); } gesture_flags = le16_to_cpu(status[dev_desc->gesture_offs]); for (i = 0; i < dev_desc->num_kp_events; i++) { enum iqs7211_reg_key_id reg_key = dev_desc->kp_events[i].reg_key; u16 mask = dev_desc->kp_events[i].mask; if (dev_desc->kp_events[i].reg_grp != IQS7211_REG_GRP_TP) continue; if ((gesture_flags ^ iqs7211->gesture_cache) & mask) input_report_key(iqs7211->kp_idev, iqs7211->kp_code[i], gesture_flags & mask); iqs7211->gesture_cache &= ~mask; /* * Hold and palm gestures persist while the contact remains in * place; all others are momentary and hence are followed by a * complementary release event. */ if (reg_key == IQS7211_REG_KEY_HOLD || reg_key == IQS7211_REG_KEY_PALM) { iqs7211->gesture_cache |= gesture_flags & mask; gesture_flags &= ~mask; } } if (gesture_flags) { input_sync(iqs7211->kp_idev); for (i = 0; i < dev_desc->num_kp_events; i++) if (dev_desc->kp_events[i].reg_grp == IQS7211_REG_GRP_TP && gesture_flags & dev_desc->kp_events[i].mask) input_report_key(iqs7211->kp_idev, iqs7211->kp_code[i], 0); } input_sync(iqs7211->kp_idev); return 0; } static irqreturn_t iqs7211_irq(int irq, void *context) { struct iqs7211_private *iqs7211 = context; return iqs7211_report(iqs7211) ? IRQ_NONE : IRQ_HANDLED; } static int iqs7211_suspend(struct device *dev) { struct iqs7211_private *iqs7211 = dev_get_drvdata(dev); const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; int error; if (!dev_desc->suspend || device_may_wakeup(dev)) return 0; /* * I2C communication prompts the device to assert its RDY pin if it is * not already asserted. As such, the interrupt must be disabled so as * to prevent reentrant interrupts. */ disable_irq(gpiod_to_irq(iqs7211->irq_gpio)); error = iqs7211_write_word(iqs7211, dev_desc->sys_ctrl, dev_desc->suspend); enable_irq(gpiod_to_irq(iqs7211->irq_gpio)); return error; } static int iqs7211_resume(struct device *dev) { struct iqs7211_private *iqs7211 = dev_get_drvdata(dev); const struct iqs7211_dev_desc *dev_desc = iqs7211->dev_desc; __le16 sys_ctrl[] = { 0, cpu_to_le16(iqs7211->event_mask), }; int error; if (!dev_desc->suspend || device_may_wakeup(dev)) return 0; disable_irq(gpiod_to_irq(iqs7211->irq_gpio)); /* * Forced communication, if in use, must be explicitly enabled as part * of the wake-up command. */ error = iqs7211_write_burst(iqs7211, dev_desc->sys_ctrl, sys_ctrl, sizeof(sys_ctrl)); enable_irq(gpiod_to_irq(iqs7211->irq_gpio)); return error; } static DEFINE_SIMPLE_DEV_PM_OPS(iqs7211_pm, iqs7211_suspend, iqs7211_resume); static ssize_t fw_info_show(struct device *dev, struct device_attribute *attr, char *buf) { struct iqs7211_private *iqs7211 = dev_get_drvdata(dev); return scnprintf(buf, PAGE_SIZE, "%u.%u.%u.%u:%u.%u\n", le16_to_cpu(iqs7211->ver_info.prod_num), le32_to_cpu(iqs7211->ver_info.patch), le16_to_cpu(iqs7211->ver_info.major), le16_to_cpu(iqs7211->ver_info.minor), iqs7211->exp_file[1], iqs7211->exp_file[0]); } static DEVICE_ATTR_RO(fw_info); static struct attribute *iqs7211_attrs[] = { &dev_attr_fw_info.attr, NULL }; ATTRIBUTE_GROUPS(iqs7211); static const struct of_device_id iqs7211_of_match[] = { { .compatible = "azoteq,iqs7210a", .data = &iqs7211_devs[IQS7210A], }, { .compatible = "azoteq,iqs7211a", .data = &iqs7211_devs[IQS7211A], }, { .compatible = "azoteq,iqs7211e", .data = &iqs7211_devs[IQS7211E], }, { } }; MODULE_DEVICE_TABLE(of, iqs7211_of_match); static int iqs7211_probe(struct i2c_client *client) { struct iqs7211_private *iqs7211; enum iqs7211_reg_grp_id reg_grp; unsigned long irq_flags; bool shared_irq; int error, irq; iqs7211 = devm_kzalloc(&client->dev, sizeof(*iqs7211), GFP_KERNEL); if (!iqs7211) return -ENOMEM; i2c_set_clientdata(client, iqs7211); iqs7211->client = client; INIT_LIST_HEAD(&iqs7211->reg_field_head); iqs7211->dev_desc = device_get_match_data(&client->dev); if (!iqs7211->dev_desc) return -ENODEV; shared_irq = iqs7211->dev_desc->num_ctx == IQS7211_MAX_CTX; /* * The RDY pin behaves as an interrupt, but must also be polled ahead * of unsolicited I2C communication. As such, it is first opened as a * GPIO and then passed to gpiod_to_irq() to register the interrupt. * * If an extra CTx pin is present, the RDY and MCLR pins are combined * into a single bidirectional pin. In that case, the platform's GPIO * must be configured as an open-drain output. */ iqs7211->irq_gpio = devm_gpiod_get(&client->dev, "irq", shared_irq ? GPIOD_OUT_LOW : GPIOD_IN); if (IS_ERR(iqs7211->irq_gpio)) { error = PTR_ERR(iqs7211->irq_gpio); dev_err(&client->dev, "Failed to request IRQ GPIO: %d\n", error); return error; } if (shared_irq) { iqs7211->reset_gpio = iqs7211->irq_gpio; } else { iqs7211->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(iqs7211->reset_gpio)) { error = PTR_ERR(iqs7211->reset_gpio); dev_err(&client->dev, "Failed to request reset GPIO: %d\n", error); return error; } } error = iqs7211_start_comms(iqs7211); if (error) return error; for (reg_grp = 0; reg_grp < IQS7211_NUM_REG_GRPS; reg_grp++) { const char *reg_grp_name = iqs7211_reg_grp_names[reg_grp]; struct fwnode_handle *reg_grp_node; if (reg_grp_name) reg_grp_node = device_get_named_child_node(&client->dev, reg_grp_name); else reg_grp_node = fwnode_handle_get(dev_fwnode(&client->dev)); if (!reg_grp_node) continue; error = iqs7211_parse_reg_grp(iqs7211, reg_grp_node, reg_grp); fwnode_handle_put(reg_grp_node); if (error) return error; } error = iqs7211_register_kp(iqs7211); if (error) return error; error = iqs7211_register_tp(iqs7211); if (error) return error; error = iqs7211_init_device(iqs7211); if (error) return error; irq = gpiod_to_irq(iqs7211->irq_gpio); if (irq < 0) return irq; irq_flags = gpiod_is_active_low(iqs7211->irq_gpio) ? IRQF_TRIGGER_LOW : IRQF_TRIGGER_HIGH; irq_flags |= IRQF_ONESHOT; error = devm_request_threaded_irq(&client->dev, irq, NULL, iqs7211_irq, irq_flags, client->name, iqs7211); if (error) dev_err(&client->dev, "Failed to request IRQ: %d\n", error); return error; } static struct i2c_driver iqs7211_i2c_driver = { .probe = iqs7211_probe, .driver = { .name = "iqs7211", .of_match_table = iqs7211_of_match, .dev_groups = iqs7211_groups, .pm = pm_sleep_ptr(&iqs7211_pm), }, }; module_i2c_driver(iqs7211_i2c_driver); MODULE_AUTHOR("Jeff LaBundy <[email protected]>"); MODULE_DESCRIPTION("Azoteq IQS7210A/7211A/E Trackpad/Touchscreen Controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/iqs7211.c
// SPDX-License-Identifier: GPL-2.0-only /* * Touchright 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]> */ #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 "Touchright serial touchscreen driver" MODULE_AUTHOR("Rick Koch <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define TR_FORMAT_TOUCH_BIT 0x01 #define TR_FORMAT_STATUS_BYTE 0x40 #define TR_FORMAT_STATUS_MASK ~TR_FORMAT_TOUCH_BIT #define TR_LENGTH 5 #define TR_MIN_XC 0 #define TR_MAX_XC 0x1ff #define TR_MIN_YC 0 #define TR_MAX_YC 0x1ff /* * Per-touchscreen data. */ struct tr { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[TR_LENGTH]; char phys[32]; }; static irqreturn_t tr_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct tr *tr = serio_get_drvdata(serio); struct input_dev *dev = tr->dev; tr->data[tr->idx] = data; if ((tr->data[0] & TR_FORMAT_STATUS_MASK) == TR_FORMAT_STATUS_BYTE) { if (++tr->idx == TR_LENGTH) { input_report_abs(dev, ABS_X, (tr->data[1] << 5) | (tr->data[2] >> 1)); input_report_abs(dev, ABS_Y, (tr->data[3] << 5) | (tr->data[4] >> 1)); input_report_key(dev, BTN_TOUCH, tr->data[0] & TR_FORMAT_TOUCH_BIT); input_sync(dev); tr->idx = 0; } } return IRQ_HANDLED; } /* * tr_disconnect() is the opposite of tr_connect() */ static void tr_disconnect(struct serio *serio) { struct tr *tr = serio_get_drvdata(serio); input_get_device(tr->dev); input_unregister_device(tr->dev); serio_close(serio); serio_set_drvdata(serio, NULL); input_put_device(tr->dev); kfree(tr); } /* * tr_connect() is the routine that is called when someone adds a * new serio device that supports the Touchright protocol and registers it as * an input device. */ static int tr_connect(struct serio *serio, struct serio_driver *drv) { struct tr *tr; struct input_dev *input_dev; int err; tr = kzalloc(sizeof(struct tr), GFP_KERNEL); input_dev = input_allocate_device(); if (!tr || !input_dev) { err = -ENOMEM; goto fail1; } tr->serio = serio; tr->dev = input_dev; snprintf(tr->phys, sizeof(tr->phys), "%s/input0", serio->phys); input_dev->name = "Touchright Serial TouchScreen"; input_dev->phys = tr->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_TOUCHRIGHT; 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(tr->dev, ABS_X, TR_MIN_XC, TR_MAX_XC, 0, 0); input_set_abs_params(tr->dev, ABS_Y, TR_MIN_YC, TR_MAX_YC, 0, 0); serio_set_drvdata(serio, tr); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(tr->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(tr); return err; } /* * The serio driver structure. */ static const struct serio_device_id tr_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_TOUCHRIGHT, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, tr_serio_ids); static struct serio_driver tr_drv = { .driver = { .name = "touchright", }, .description = DRIVER_DESC, .id_table = tr_serio_ids, .interrupt = tr_interrupt, .connect = tr_connect, .disconnect = tr_disconnect, }; module_serio_driver(tr_drv);
linux-master
drivers/input/touchscreen/touchright.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2012-2013 MundoReader S.L. * Author: Heiko Stuebner <[email protected]> * * based in parts on Nook zforce driver * * Copyright (C) 2010 Barnes & Noble, Inc. * Author: Pieter Truter<[email protected]> */ #include <linux/module.h> #include <linux/hrtimer.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/device.h> #include <linux/sysfs.h> #include <linux/input/mt.h> #include <linux/platform_data/zforce_ts.h> #include <linux/regulator/consumer.h> #include <linux/of.h> #define WAIT_TIMEOUT msecs_to_jiffies(1000) #define FRAME_START 0xee #define FRAME_MAXSIZE 257 /* Offsets of the different parts of the payload the controller sends */ #define PAYLOAD_HEADER 0 #define PAYLOAD_LENGTH 1 #define PAYLOAD_BODY 2 /* Response offsets */ #define RESPONSE_ID 0 #define RESPONSE_DATA 1 /* Commands */ #define COMMAND_DEACTIVATE 0x00 #define COMMAND_INITIALIZE 0x01 #define COMMAND_RESOLUTION 0x02 #define COMMAND_SETCONFIG 0x03 #define COMMAND_DATAREQUEST 0x04 #define COMMAND_SCANFREQ 0x08 #define COMMAND_STATUS 0X1e /* * Responses the controller sends as a result of * command requests */ #define RESPONSE_DEACTIVATE 0x00 #define RESPONSE_INITIALIZE 0x01 #define RESPONSE_RESOLUTION 0x02 #define RESPONSE_SETCONFIG 0x03 #define RESPONSE_SCANFREQ 0x08 #define RESPONSE_STATUS 0X1e /* * Notifications are sent by the touch controller without * being requested by the driver and include for example * touch indications */ #define NOTIFICATION_TOUCH 0x04 #define NOTIFICATION_BOOTCOMPLETE 0x07 #define NOTIFICATION_OVERRUN 0x25 #define NOTIFICATION_PROXIMITY 0x26 #define NOTIFICATION_INVALID_COMMAND 0xfe #define ZFORCE_REPORT_POINTS 2 #define ZFORCE_MAX_AREA 0xff #define STATE_DOWN 0 #define STATE_MOVE 1 #define STATE_UP 2 #define SETCONFIG_DUALTOUCH (1 << 0) struct zforce_point { int coord_x; int coord_y; int state; int id; int area_major; int area_minor; int orientation; int pressure; int prblty; }; /* * @client the i2c_client * @input the input device * @suspending in the process of going to suspend (don't emit wakeup * events for commands executed to suspend the device) * @suspended device suspended * @access_mutex serialize i2c-access, to keep multipart reads together * @command_done completion to wait for the command result * @command_mutex serialize commands sent to the ic * @command_waiting the id of the command that is currently waiting * for a result * @command_result returned result of the command */ struct zforce_ts { struct i2c_client *client; struct input_dev *input; const struct zforce_ts_platdata *pdata; char phys[32]; struct regulator *reg_vdd; struct gpio_desc *gpio_int; struct gpio_desc *gpio_rst; bool suspending; bool suspended; bool boot_complete; /* Firmware version information */ u16 version_major; u16 version_minor; u16 version_build; u16 version_rev; struct mutex access_mutex; struct completion command_done; struct mutex command_mutex; int command_waiting; int command_result; }; static int zforce_command(struct zforce_ts *ts, u8 cmd) { struct i2c_client *client = ts->client; char buf[3]; int ret; dev_dbg(&client->dev, "%s: 0x%x\n", __func__, cmd); buf[0] = FRAME_START; buf[1] = 1; /* data size, command only */ buf[2] = cmd; mutex_lock(&ts->access_mutex); ret = i2c_master_send(client, &buf[0], ARRAY_SIZE(buf)); mutex_unlock(&ts->access_mutex); if (ret < 0) { dev_err(&client->dev, "i2c send data request error: %d\n", ret); return ret; } return 0; } static void zforce_reset_assert(struct zforce_ts *ts) { gpiod_set_value_cansleep(ts->gpio_rst, 1); } static void zforce_reset_deassert(struct zforce_ts *ts) { gpiod_set_value_cansleep(ts->gpio_rst, 0); } static int zforce_send_wait(struct zforce_ts *ts, const char *buf, int len) { struct i2c_client *client = ts->client; int ret; ret = mutex_trylock(&ts->command_mutex); if (!ret) { dev_err(&client->dev, "already waiting for a command\n"); return -EBUSY; } dev_dbg(&client->dev, "sending %d bytes for command 0x%x\n", buf[1], buf[2]); ts->command_waiting = buf[2]; mutex_lock(&ts->access_mutex); ret = i2c_master_send(client, buf, len); mutex_unlock(&ts->access_mutex); if (ret < 0) { dev_err(&client->dev, "i2c send data request error: %d\n", ret); goto unlock; } dev_dbg(&client->dev, "waiting for result for command 0x%x\n", buf[2]); if (wait_for_completion_timeout(&ts->command_done, WAIT_TIMEOUT) == 0) { ret = -ETIME; goto unlock; } ret = ts->command_result; unlock: mutex_unlock(&ts->command_mutex); return ret; } static int zforce_command_wait(struct zforce_ts *ts, u8 cmd) { struct i2c_client *client = ts->client; char buf[3]; int ret; dev_dbg(&client->dev, "%s: 0x%x\n", __func__, cmd); buf[0] = FRAME_START; buf[1] = 1; /* data size, command only */ buf[2] = cmd; ret = zforce_send_wait(ts, &buf[0], ARRAY_SIZE(buf)); if (ret < 0) { dev_err(&client->dev, "i2c send data request error: %d\n", ret); return ret; } return 0; } static int zforce_resolution(struct zforce_ts *ts, u16 x, u16 y) { struct i2c_client *client = ts->client; char buf[7] = { FRAME_START, 5, COMMAND_RESOLUTION, (x & 0xff), ((x >> 8) & 0xff), (y & 0xff), ((y >> 8) & 0xff) }; dev_dbg(&client->dev, "set resolution to (%d,%d)\n", x, y); return zforce_send_wait(ts, &buf[0], ARRAY_SIZE(buf)); } static int zforce_scan_frequency(struct zforce_ts *ts, u16 idle, u16 finger, u16 stylus) { struct i2c_client *client = ts->client; char buf[9] = { FRAME_START, 7, COMMAND_SCANFREQ, (idle & 0xff), ((idle >> 8) & 0xff), (finger & 0xff), ((finger >> 8) & 0xff), (stylus & 0xff), ((stylus >> 8) & 0xff) }; dev_dbg(&client->dev, "set scan frequency to (idle: %d, finger: %d, stylus: %d)\n", idle, finger, stylus); return zforce_send_wait(ts, &buf[0], ARRAY_SIZE(buf)); } static int zforce_setconfig(struct zforce_ts *ts, char b1) { struct i2c_client *client = ts->client; char buf[7] = { FRAME_START, 5, COMMAND_SETCONFIG, b1, 0, 0, 0 }; dev_dbg(&client->dev, "set config to (%d)\n", b1); return zforce_send_wait(ts, &buf[0], ARRAY_SIZE(buf)); } static int zforce_start(struct zforce_ts *ts) { struct i2c_client *client = ts->client; const struct zforce_ts_platdata *pdata = ts->pdata; int ret; dev_dbg(&client->dev, "starting device\n"); ret = zforce_command_wait(ts, COMMAND_INITIALIZE); if (ret) { dev_err(&client->dev, "Unable to initialize, %d\n", ret); return ret; } ret = zforce_resolution(ts, pdata->x_max, pdata->y_max); if (ret) { dev_err(&client->dev, "Unable to set resolution, %d\n", ret); goto error; } ret = zforce_scan_frequency(ts, 10, 50, 50); if (ret) { dev_err(&client->dev, "Unable to set scan frequency, %d\n", ret); goto error; } ret = zforce_setconfig(ts, SETCONFIG_DUALTOUCH); if (ret) { dev_err(&client->dev, "Unable to set config\n"); goto error; } /* start sending touch events */ ret = zforce_command(ts, COMMAND_DATAREQUEST); if (ret) { dev_err(&client->dev, "Unable to request data\n"); goto error; } /* * Per NN, initial cal. take max. of 200msec. * Allow time to complete this calibration */ msleep(200); return 0; error: zforce_command_wait(ts, COMMAND_DEACTIVATE); return ret; } static int zforce_stop(struct zforce_ts *ts) { struct i2c_client *client = ts->client; int ret; dev_dbg(&client->dev, "stopping device\n"); /* Deactivates touch sensing and puts the device into sleep. */ ret = zforce_command_wait(ts, COMMAND_DEACTIVATE); if (ret != 0) { dev_err(&client->dev, "could not deactivate device, %d\n", ret); return ret; } return 0; } static int zforce_touch_event(struct zforce_ts *ts, u8 *payload) { struct i2c_client *client = ts->client; const struct zforce_ts_platdata *pdata = ts->pdata; struct zforce_point point; int count, i, num = 0; count = payload[0]; if (count > ZFORCE_REPORT_POINTS) { dev_warn(&client->dev, "too many coordinates %d, expected max %d\n", count, ZFORCE_REPORT_POINTS); count = ZFORCE_REPORT_POINTS; } for (i = 0; i < count; i++) { point.coord_x = payload[9 * i + 2] << 8 | payload[9 * i + 1]; point.coord_y = payload[9 * i + 4] << 8 | payload[9 * i + 3]; if (point.coord_x > pdata->x_max || point.coord_y > pdata->y_max) { dev_warn(&client->dev, "coordinates (%d,%d) invalid\n", point.coord_x, point.coord_y); point.coord_x = point.coord_y = 0; } point.state = payload[9 * i + 5] & 0x0f; point.id = (payload[9 * i + 5] & 0xf0) >> 4; /* determine touch major, minor and orientation */ point.area_major = max(payload[9 * i + 6], payload[9 * i + 7]); point.area_minor = min(payload[9 * i + 6], payload[9 * i + 7]); point.orientation = payload[9 * i + 6] > payload[9 * i + 7]; point.pressure = payload[9 * i + 8]; point.prblty = payload[9 * i + 9]; dev_dbg(&client->dev, "point %d/%d: state %d, id %d, pressure %d, prblty %d, x %d, y %d, amajor %d, aminor %d, ori %d\n", i, count, point.state, point.id, point.pressure, point.prblty, point.coord_x, point.coord_y, point.area_major, point.area_minor, point.orientation); /* the zforce id starts with "1", so needs to be decreased */ input_mt_slot(ts->input, point.id - 1); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, point.state != STATE_UP); if (point.state != STATE_UP) { input_report_abs(ts->input, ABS_MT_POSITION_X, point.coord_x); input_report_abs(ts->input, ABS_MT_POSITION_Y, point.coord_y); input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, point.area_major); input_report_abs(ts->input, ABS_MT_TOUCH_MINOR, point.area_minor); input_report_abs(ts->input, ABS_MT_ORIENTATION, point.orientation); num++; } } input_mt_sync_frame(ts->input); input_mt_report_finger_count(ts->input, num); input_sync(ts->input); return 0; } static int zforce_read_packet(struct zforce_ts *ts, u8 *buf) { struct i2c_client *client = ts->client; int ret; mutex_lock(&ts->access_mutex); /* read 2 byte message header */ ret = i2c_master_recv(client, buf, 2); if (ret < 0) { dev_err(&client->dev, "error reading header: %d\n", ret); goto unlock; } if (buf[PAYLOAD_HEADER] != FRAME_START) { dev_err(&client->dev, "invalid frame start: %d\n", buf[0]); ret = -EIO; goto unlock; } if (buf[PAYLOAD_LENGTH] == 0) { dev_err(&client->dev, "invalid payload length: %d\n", buf[PAYLOAD_LENGTH]); ret = -EIO; goto unlock; } /* read the message */ ret = i2c_master_recv(client, &buf[PAYLOAD_BODY], buf[PAYLOAD_LENGTH]); if (ret < 0) { dev_err(&client->dev, "error reading payload: %d\n", ret); goto unlock; } dev_dbg(&client->dev, "read %d bytes for response command 0x%x\n", buf[PAYLOAD_LENGTH], buf[PAYLOAD_BODY]); unlock: mutex_unlock(&ts->access_mutex); return ret; } static void zforce_complete(struct zforce_ts *ts, int cmd, int result) { struct i2c_client *client = ts->client; if (ts->command_waiting == cmd) { dev_dbg(&client->dev, "completing command 0x%x\n", cmd); ts->command_result = result; complete(&ts->command_done); } else { dev_dbg(&client->dev, "command %d not for us\n", cmd); } } static irqreturn_t zforce_irq(int irq, void *dev_id) { struct zforce_ts *ts = dev_id; struct i2c_client *client = ts->client; if (ts->suspended && device_may_wakeup(&client->dev)) pm_wakeup_event(&client->dev, 500); return IRQ_WAKE_THREAD; } static irqreturn_t zforce_irq_thread(int irq, void *dev_id) { struct zforce_ts *ts = dev_id; struct i2c_client *client = ts->client; int ret; u8 payload_buffer[FRAME_MAXSIZE]; u8 *payload; /* * When still suspended, return. * Due to the level-interrupt we will get re-triggered later. */ if (ts->suspended) { msleep(20); return IRQ_HANDLED; } dev_dbg(&client->dev, "handling interrupt\n"); /* Don't emit wakeup events from commands run by zforce_suspend */ if (!ts->suspending && device_may_wakeup(&client->dev)) pm_stay_awake(&client->dev); /* * Run at least once and exit the loop if * - the optional interrupt GPIO isn't specified * (there is only one packet read per ISR invocation, then) * or * - the GPIO isn't active any more * (packet read until the level GPIO indicates that there is * no IRQ any more) */ do { ret = zforce_read_packet(ts, payload_buffer); if (ret < 0) { dev_err(&client->dev, "could not read packet, ret: %d\n", ret); break; } payload = &payload_buffer[PAYLOAD_BODY]; switch (payload[RESPONSE_ID]) { case NOTIFICATION_TOUCH: /* * Always report touch-events received while * suspending, when being a wakeup source */ if (ts->suspending && device_may_wakeup(&client->dev)) pm_wakeup_event(&client->dev, 500); zforce_touch_event(ts, &payload[RESPONSE_DATA]); break; case NOTIFICATION_BOOTCOMPLETE: ts->boot_complete = payload[RESPONSE_DATA]; zforce_complete(ts, payload[RESPONSE_ID], 0); break; case RESPONSE_INITIALIZE: case RESPONSE_DEACTIVATE: case RESPONSE_SETCONFIG: case RESPONSE_RESOLUTION: case RESPONSE_SCANFREQ: zforce_complete(ts, payload[RESPONSE_ID], payload[RESPONSE_DATA]); break; case RESPONSE_STATUS: /* * Version Payload Results * [2:major] [2:minor] [2:build] [2:rev] */ ts->version_major = (payload[RESPONSE_DATA + 1] << 8) | payload[RESPONSE_DATA]; ts->version_minor = (payload[RESPONSE_DATA + 3] << 8) | payload[RESPONSE_DATA + 2]; ts->version_build = (payload[RESPONSE_DATA + 5] << 8) | payload[RESPONSE_DATA + 4]; ts->version_rev = (payload[RESPONSE_DATA + 7] << 8) | payload[RESPONSE_DATA + 6]; dev_dbg(&ts->client->dev, "Firmware Version %04x:%04x %04x:%04x\n", ts->version_major, ts->version_minor, ts->version_build, ts->version_rev); zforce_complete(ts, payload[RESPONSE_ID], 0); break; case NOTIFICATION_INVALID_COMMAND: dev_err(&ts->client->dev, "invalid command: 0x%x\n", payload[RESPONSE_DATA]); break; default: dev_err(&ts->client->dev, "unrecognized response id: 0x%x\n", payload[RESPONSE_ID]); break; } } while (gpiod_get_value_cansleep(ts->gpio_int)); if (!ts->suspending && device_may_wakeup(&client->dev)) pm_relax(&client->dev); dev_dbg(&client->dev, "finished interrupt\n"); return IRQ_HANDLED; } static int zforce_input_open(struct input_dev *dev) { struct zforce_ts *ts = input_get_drvdata(dev); return zforce_start(ts); } static void zforce_input_close(struct input_dev *dev) { struct zforce_ts *ts = input_get_drvdata(dev); struct i2c_client *client = ts->client; int ret; ret = zforce_stop(ts); if (ret) dev_warn(&client->dev, "stopping zforce failed\n"); return; } static int zforce_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct zforce_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); ts->suspending = true; /* * When configured as a wakeup source device should always wake * the system, therefore start device if necessary. */ if (device_may_wakeup(&client->dev)) { dev_dbg(&client->dev, "suspend while being a wakeup source\n"); /* Need to start device, if not open, to be a wakeup source. */ if (!input_device_enabled(input)) { ret = zforce_start(ts); if (ret) goto unlock; } enable_irq_wake(client->irq); } else if (input_device_enabled(input)) { dev_dbg(&client->dev, "suspend without being a wakeup source\n"); ret = zforce_stop(ts); if (ret) goto unlock; disable_irq(client->irq); } ts->suspended = true; unlock: ts->suspending = false; mutex_unlock(&input->mutex); return ret; } static int zforce_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct zforce_ts *ts = i2c_get_clientdata(client); struct input_dev *input = ts->input; int ret = 0; mutex_lock(&input->mutex); ts->suspended = false; if (device_may_wakeup(&client->dev)) { dev_dbg(&client->dev, "resume from being a wakeup source\n"); disable_irq_wake(client->irq); /* need to stop device if it was not open on suspend */ if (!input_device_enabled(input)) { ret = zforce_stop(ts); if (ret) goto unlock; } } else if (input_device_enabled(input)) { dev_dbg(&client->dev, "resume without being a wakeup source\n"); enable_irq(client->irq); ret = zforce_start(ts); if (ret < 0) goto unlock; } unlock: mutex_unlock(&input->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(zforce_pm_ops, zforce_suspend, zforce_resume); static void zforce_reset(void *data) { struct zforce_ts *ts = data; zforce_reset_assert(ts); udelay(10); if (!IS_ERR(ts->reg_vdd)) regulator_disable(ts->reg_vdd); } static struct zforce_ts_platdata *zforce_parse_dt(struct device *dev) { struct zforce_ts_platdata *pdata; struct device_node *np = dev->of_node; if (!np) return ERR_PTR(-ENOENT); pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { dev_err(dev, "failed to allocate platform data\n"); return ERR_PTR(-ENOMEM); } if (of_property_read_u32(np, "x-size", &pdata->x_max)) { dev_err(dev, "failed to get x-size property\n"); return ERR_PTR(-EINVAL); } if (of_property_read_u32(np, "y-size", &pdata->y_max)) { dev_err(dev, "failed to get y-size property\n"); return ERR_PTR(-EINVAL); } return pdata; } static int zforce_probe(struct i2c_client *client) { const struct zforce_ts_platdata *pdata = dev_get_platdata(&client->dev); struct zforce_ts *ts; struct input_dev *input_dev; int ret; if (!pdata) { pdata = zforce_parse_dt(&client->dev); if (IS_ERR(pdata)) return PTR_ERR(pdata); } ts = devm_kzalloc(&client->dev, sizeof(struct zforce_ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->gpio_rst = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ts->gpio_rst)) { ret = PTR_ERR(ts->gpio_rst); dev_err(&client->dev, "failed to request reset GPIO: %d\n", ret); return ret; } if (ts->gpio_rst) { ts->gpio_int = devm_gpiod_get_optional(&client->dev, "irq", GPIOD_IN); if (IS_ERR(ts->gpio_int)) { ret = PTR_ERR(ts->gpio_int); dev_err(&client->dev, "failed to request interrupt GPIO: %d\n", ret); return ret; } } else { /* * Deprecated GPIO handling for compatibility * with legacy binding. */ /* INT GPIO */ ts->gpio_int = devm_gpiod_get_index(&client->dev, NULL, 0, GPIOD_IN); if (IS_ERR(ts->gpio_int)) { ret = PTR_ERR(ts->gpio_int); dev_err(&client->dev, "failed to request interrupt GPIO: %d\n", ret); return ret; } /* RST GPIO */ ts->gpio_rst = devm_gpiod_get_index(&client->dev, NULL, 1, GPIOD_OUT_HIGH); if (IS_ERR(ts->gpio_rst)) { ret = PTR_ERR(ts->gpio_rst); dev_err(&client->dev, "failed to request reset GPIO: %d\n", ret); return ret; } } ts->reg_vdd = devm_regulator_get_optional(&client->dev, "vdd"); if (IS_ERR(ts->reg_vdd)) { ret = PTR_ERR(ts->reg_vdd); if (ret == -EPROBE_DEFER) return ret; } else { ret = regulator_enable(ts->reg_vdd); if (ret) return ret; /* * according to datasheet add 100us grace time after regular * regulator enable delay. */ udelay(100); } ret = devm_add_action(&client->dev, zforce_reset, ts); if (ret) { dev_err(&client->dev, "failed to register reset action, %d\n", ret); /* hereafter the regulator will be disabled by the action */ if (!IS_ERR(ts->reg_vdd)) regulator_disable(ts->reg_vdd); return ret; } snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) { dev_err(&client->dev, "could not allocate input device\n"); return -ENOMEM; } mutex_init(&ts->access_mutex); mutex_init(&ts->command_mutex); ts->pdata = pdata; ts->client = client; ts->input = input_dev; input_dev->name = "Neonode zForce touchscreen"; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_I2C; input_dev->open = zforce_input_open; input_dev->close = zforce_input_close; __set_bit(EV_KEY, input_dev->evbit); __set_bit(EV_SYN, input_dev->evbit); __set_bit(EV_ABS, input_dev->evbit); /* For multi touch */ input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, pdata->x_max, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, pdata->y_max, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, ZFORCE_MAX_AREA, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR, 0, ZFORCE_MAX_AREA, 0, 0); input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 1, 0, 0); input_mt_init_slots(input_dev, ZFORCE_REPORT_POINTS, INPUT_MT_DIRECT); input_set_drvdata(ts->input, ts); init_completion(&ts->command_done); /* * The zforce pulls the interrupt low when it has data ready. * After it is triggered the isr thread runs until all the available * packets have been read and the interrupt is high again. * Therefore we can trigger the interrupt anytime it is low and do * not need to limit it to the interrupt edge. */ ret = devm_request_threaded_irq(&client->dev, client->irq, zforce_irq, zforce_irq_thread, IRQF_TRIGGER_LOW | IRQF_ONESHOT, input_dev->name, ts); if (ret) { dev_err(&client->dev, "irq %d request failed\n", client->irq); return ret; } i2c_set_clientdata(client, ts); /* let the controller boot */ zforce_reset_deassert(ts); ts->command_waiting = NOTIFICATION_BOOTCOMPLETE; if (wait_for_completion_timeout(&ts->command_done, WAIT_TIMEOUT) == 0) dev_warn(&client->dev, "bootcomplete timed out\n"); /* need to start device to get version information */ ret = zforce_command_wait(ts, COMMAND_INITIALIZE); if (ret) { dev_err(&client->dev, "unable to initialize, %d\n", ret); return ret; } /* this gets the firmware version among other information */ ret = zforce_command_wait(ts, COMMAND_STATUS); if (ret < 0) { dev_err(&client->dev, "couldn't get status, %d\n", ret); zforce_stop(ts); return ret; } /* stop device and put it into sleep until it is opened */ ret = zforce_stop(ts); if (ret < 0) return ret; device_set_wakeup_capable(&client->dev, true); ret = input_register_device(input_dev); if (ret) { dev_err(&client->dev, "could not register input device, %d\n", ret); return ret; } return 0; } static struct i2c_device_id zforce_idtable[] = { { "zforce-ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, zforce_idtable); #ifdef CONFIG_OF static const struct of_device_id zforce_dt_idtable[] = { { .compatible = "neonode,zforce" }, {}, }; MODULE_DEVICE_TABLE(of, zforce_dt_idtable); #endif static struct i2c_driver zforce_driver = { .driver = { .name = "zforce-ts", .pm = pm_sleep_ptr(&zforce_pm_ops), .of_match_table = of_match_ptr(zforce_dt_idtable), }, .probe = zforce_probe, .id_table = zforce_idtable, }; module_i2c_driver(zforce_driver); MODULE_AUTHOR("Heiko Stuebner <[email protected]>"); MODULE_DESCRIPTION("zForce TouchScreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/zforce_ts.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Atmel maXTouch Touchscreen driver * * Copyright (C) 2010 Samsung Electronics Co.Ltd * Copyright (C) 2011-2014 Atmel Corporation * Copyright (C) 2012 Google, Inc. * Copyright (C) 2016 Zodiac Inflight Innovations * * Author: Joonyoung Shim <[email protected]> */ #include <linux/acpi.h> #include <linux/dmi.h> #include <linux/module.h> #include <linux/init.h> #include <linux/completion.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/i2c.h> #include <linux/input/mt.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/of.h> #include <linux/property.h> #include <linux/slab.h> #include <linux/regulator/consumer.h> #include <linux/gpio/consumer.h> #include <asm/unaligned.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/videobuf2-v4l2.h> #include <media/videobuf2-vmalloc.h> #include <dt-bindings/input/atmel-maxtouch.h> /* Firmware files */ #define MXT_FW_NAME "maxtouch.fw" #define MXT_CFG_NAME "maxtouch.cfg" #define MXT_CFG_MAGIC "OBP_RAW V1" /* Registers */ #define MXT_OBJECT_START 0x07 #define MXT_OBJECT_SIZE 6 #define MXT_INFO_CHECKSUM_SIZE 3 #define MXT_MAX_BLOCK_WRITE 256 /* Object types */ #define MXT_DEBUG_DIAGNOSTIC_T37 37 #define MXT_GEN_MESSAGE_T5 5 #define MXT_GEN_COMMAND_T6 6 #define MXT_GEN_POWER_T7 7 #define MXT_GEN_ACQUIRE_T8 8 #define MXT_GEN_DATASOURCE_T53 53 #define MXT_TOUCH_MULTI_T9 9 #define MXT_TOUCH_KEYARRAY_T15 15 #define MXT_TOUCH_PROXIMITY_T23 23 #define MXT_TOUCH_PROXKEY_T52 52 #define MXT_TOUCH_PTC_KEYS_T97 97 #define MXT_PROCI_GRIPFACE_T20 20 #define MXT_PROCG_NOISE_T22 22 #define MXT_PROCI_ONETOUCH_T24 24 #define MXT_PROCI_TWOTOUCH_T27 27 #define MXT_PROCI_GRIP_T40 40 #define MXT_PROCI_PALM_T41 41 #define MXT_PROCI_TOUCHSUPPRESSION_T42 42 #define MXT_PROCI_STYLUS_T47 47 #define MXT_PROCG_NOISESUPPRESSION_T48 48 #define MXT_SPT_COMMSCONFIG_T18 18 #define MXT_SPT_GPIOPWM_T19 19 #define MXT_SPT_SELFTEST_T25 25 #define MXT_SPT_CTECONFIG_T28 28 #define MXT_SPT_USERDATA_T38 38 #define MXT_SPT_DIGITIZER_T43 43 #define MXT_SPT_MESSAGECOUNT_T44 44 #define MXT_SPT_CTECONFIG_T46 46 #define MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71 71 #define MXT_TOUCH_MULTITOUCHSCREEN_T100 100 /* MXT_GEN_MESSAGE_T5 object */ #define MXT_RPTID_NOMSG 0xff /* MXT_GEN_COMMAND_T6 field */ #define MXT_COMMAND_RESET 0 #define MXT_COMMAND_BACKUPNV 1 #define MXT_COMMAND_CALIBRATE 2 #define MXT_COMMAND_REPORTALL 3 #define MXT_COMMAND_DIAGNOSTIC 5 /* Define for T6 status byte */ #define MXT_T6_STATUS_RESET BIT(7) #define MXT_T6_STATUS_OFL BIT(6) #define MXT_T6_STATUS_SIGERR BIT(5) #define MXT_T6_STATUS_CAL BIT(4) #define MXT_T6_STATUS_CFGERR BIT(3) #define MXT_T6_STATUS_COMSERR BIT(2) /* MXT_GEN_POWER_T7 field */ struct t7_config { u8 idle; u8 active; } __packed; #define MXT_POWER_CFG_RUN 0 #define MXT_POWER_CFG_DEEPSLEEP 1 /* MXT_TOUCH_MULTI_T9 field */ #define MXT_T9_CTRL 0 #define MXT_T9_XSIZE 3 #define MXT_T9_YSIZE 4 #define MXT_T9_ORIENT 9 #define MXT_T9_RANGE 18 /* MXT_TOUCH_MULTI_T9 status */ #define MXT_T9_UNGRIP BIT(0) #define MXT_T9_SUPPRESS BIT(1) #define MXT_T9_AMP BIT(2) #define MXT_T9_VECTOR BIT(3) #define MXT_T9_MOVE BIT(4) #define MXT_T9_RELEASE BIT(5) #define MXT_T9_PRESS BIT(6) #define MXT_T9_DETECT BIT(7) struct t9_range { __le16 x; __le16 y; } __packed; /* MXT_TOUCH_MULTI_T9 orient */ #define MXT_T9_ORIENT_SWITCH BIT(0) #define MXT_T9_ORIENT_INVERTX BIT(1) #define MXT_T9_ORIENT_INVERTY BIT(2) /* MXT_SPT_COMMSCONFIG_T18 */ #define MXT_COMMS_CTRL 0 #define MXT_COMMS_CMD 1 #define MXT_COMMS_RETRIGEN BIT(6) /* MXT_DEBUG_DIAGNOSTIC_T37 */ #define MXT_DIAGNOSTIC_PAGEUP 0x01 #define MXT_DIAGNOSTIC_DELTAS 0x10 #define MXT_DIAGNOSTIC_REFS 0x11 #define MXT_DIAGNOSTIC_SIZE 128 #define MXT_FAMILY_1386 160 #define MXT1386_COLUMNS 3 #define MXT1386_PAGES_PER_COLUMN 8 struct t37_debug { #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37 u8 mode; u8 page; u8 data[MXT_DIAGNOSTIC_SIZE]; #endif }; /* Define for MXT_GEN_COMMAND_T6 */ #define MXT_BOOT_VALUE 0xa5 #define MXT_RESET_VALUE 0x01 #define MXT_BACKUP_VALUE 0x55 /* T100 Multiple Touch Touchscreen */ #define MXT_T100_CTRL 0 #define MXT_T100_CFG1 1 #define MXT_T100_TCHAUX 3 #define MXT_T100_XSIZE 9 #define MXT_T100_XRANGE 13 #define MXT_T100_YSIZE 20 #define MXT_T100_YRANGE 24 #define MXT_T100_CFG_SWITCHXY BIT(5) #define MXT_T100_CFG_INVERTY BIT(6) #define MXT_T100_CFG_INVERTX BIT(7) #define MXT_T100_TCHAUX_VECT BIT(0) #define MXT_T100_TCHAUX_AMPL BIT(1) #define MXT_T100_TCHAUX_AREA BIT(2) #define MXT_T100_DETECT BIT(7) #define MXT_T100_TYPE_MASK 0x70 enum t100_type { MXT_T100_TYPE_FINGER = 1, MXT_T100_TYPE_PASSIVE_STYLUS = 2, MXT_T100_TYPE_HOVERING_FINGER = 4, MXT_T100_TYPE_GLOVE = 5, MXT_T100_TYPE_LARGE_TOUCH = 6, }; #define MXT_DISTANCE_ACTIVE_TOUCH 0 #define MXT_DISTANCE_HOVERING 1 #define MXT_TOUCH_MAJOR_DEFAULT 1 #define MXT_PRESSURE_DEFAULT 1 /* Delay times */ #define MXT_BACKUP_TIME 50 /* msec */ #define MXT_RESET_GPIO_TIME 20 /* msec */ #define MXT_RESET_INVALID_CHG 100 /* msec */ #define MXT_RESET_TIME 200 /* msec */ #define MXT_RESET_TIMEOUT 3000 /* msec */ #define MXT_CRC_TIMEOUT 1000 /* msec */ #define MXT_FW_RESET_TIME 3000 /* msec */ #define MXT_FW_CHG_TIMEOUT 300 /* msec */ #define MXT_WAKEUP_TIME 25 /* msec */ /* Command to unlock bootloader */ #define MXT_UNLOCK_CMD_MSB 0xaa #define MXT_UNLOCK_CMD_LSB 0xdc /* Bootloader mode status */ #define MXT_WAITING_BOOTLOAD_CMD 0xc0 /* valid 7 6 bit only */ #define MXT_WAITING_FRAME_DATA 0x80 /* valid 7 6 bit only */ #define MXT_FRAME_CRC_CHECK 0x02 #define MXT_FRAME_CRC_FAIL 0x03 #define MXT_FRAME_CRC_PASS 0x04 #define MXT_APP_CRC_FAIL 0x40 /* valid 7 8 bit only */ #define MXT_BOOT_STATUS_MASK 0x3f #define MXT_BOOT_EXTENDED_ID BIT(5) #define MXT_BOOT_ID_MASK 0x1f /* Touchscreen absolute values */ #define MXT_MAX_AREA 0xff #define MXT_PIXELS_PER_MM 20 struct mxt_info { u8 family_id; u8 variant_id; u8 version; u8 build; u8 matrix_xsize; u8 matrix_ysize; u8 object_num; }; struct mxt_object { u8 type; u16 start_address; u8 size_minus_one; u8 instances_minus_one; u8 num_report_ids; } __packed; struct mxt_dbg { u16 t37_address; u16 diag_cmd_address; struct t37_debug *t37_buf; unsigned int t37_pages; unsigned int t37_nodes; struct v4l2_device v4l2; struct v4l2_pix_format format; struct video_device vdev; struct vb2_queue queue; struct mutex lock; int input; }; enum v4l_dbg_inputs { MXT_V4L_INPUT_DELTAS, MXT_V4L_INPUT_REFS, MXT_V4L_INPUT_MAX, }; enum mxt_suspend_mode { MXT_SUSPEND_DEEP_SLEEP = 0, MXT_SUSPEND_T9_CTRL = 1, }; /* Config update context */ struct mxt_cfg { u8 *raw; size_t raw_size; off_t raw_pos; u8 *mem; size_t mem_size; int start_ofs; struct mxt_info info; }; /* Each client has this additional data */ struct mxt_data { struct i2c_client *client; struct input_dev *input_dev; char phys[64]; /* device physical location */ struct mxt_object *object_table; struct mxt_info *info; void *raw_info_block; unsigned int irq; unsigned int max_x; unsigned int max_y; bool invertx; bool inverty; bool xy_switch; u8 xsize; u8 ysize; bool in_bootloader; u16 mem_size; u8 t100_aux_ampl; u8 t100_aux_area; u8 t100_aux_vect; u8 max_reportid; u32 config_crc; u32 info_crc; u8 bootloader_addr; u8 *msg_buf; u8 t6_status; bool update_input; u8 last_message_count; u8 num_touchids; u8 multitouch; struct t7_config t7_cfg; struct mxt_dbg dbg; struct regulator_bulk_data regulators[2]; struct gpio_desc *reset_gpio; struct gpio_desc *wake_gpio; bool use_retrigen_workaround; /* Cached parameters from object table */ u16 T5_address; u8 T5_msg_size; u8 T6_reportid; u16 T6_address; u16 T7_address; u16 T71_address; u8 T9_reportid_min; u8 T9_reportid_max; u8 T15_reportid_min; u8 T15_reportid_max; u16 T18_address; u8 T19_reportid; u16 T44_address; u8 T97_reportid_min; u8 T97_reportid_max; u8 T100_reportid_min; u8 T100_reportid_max; /* for fw update in bootloader */ struct completion bl_completion; /* for reset handling */ struct completion reset_completion; /* for config update handling */ struct completion crc_completion; u32 *t19_keymap; unsigned int t19_num_keys; u32 *t15_keymap; unsigned int t15_num_keys; enum mxt_suspend_mode suspend_mode; u32 wakeup_method; }; struct mxt_vb2_buffer { struct vb2_buffer vb; struct list_head list; }; static size_t mxt_obj_size(const struct mxt_object *obj) { return obj->size_minus_one + 1; } static size_t mxt_obj_instances(const struct mxt_object *obj) { return obj->instances_minus_one + 1; } static bool mxt_object_readable(unsigned int type) { switch (type) { case MXT_GEN_COMMAND_T6: case MXT_GEN_POWER_T7: case MXT_GEN_ACQUIRE_T8: case MXT_GEN_DATASOURCE_T53: case MXT_TOUCH_MULTI_T9: case MXT_TOUCH_KEYARRAY_T15: case MXT_TOUCH_PROXIMITY_T23: case MXT_TOUCH_PROXKEY_T52: case MXT_TOUCH_PTC_KEYS_T97: case MXT_TOUCH_MULTITOUCHSCREEN_T100: case MXT_PROCI_GRIPFACE_T20: case MXT_PROCG_NOISE_T22: case MXT_PROCI_ONETOUCH_T24: case MXT_PROCI_TWOTOUCH_T27: case MXT_PROCI_GRIP_T40: case MXT_PROCI_PALM_T41: case MXT_PROCI_TOUCHSUPPRESSION_T42: case MXT_PROCI_STYLUS_T47: case MXT_PROCG_NOISESUPPRESSION_T48: case MXT_SPT_COMMSCONFIG_T18: case MXT_SPT_GPIOPWM_T19: case MXT_SPT_SELFTEST_T25: case MXT_SPT_CTECONFIG_T28: case MXT_SPT_USERDATA_T38: case MXT_SPT_DIGITIZER_T43: case MXT_SPT_CTECONFIG_T46: case MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71: return true; default: return false; } } static void mxt_dump_message(struct mxt_data *data, u8 *message) { dev_dbg(&data->client->dev, "message: %*ph\n", data->T5_msg_size, message); } static int mxt_wait_for_completion(struct mxt_data *data, struct completion *comp, unsigned int timeout_ms) { struct device *dev = &data->client->dev; unsigned long timeout = msecs_to_jiffies(timeout_ms); long ret; ret = wait_for_completion_interruptible_timeout(comp, timeout); if (ret < 0) { return ret; } else if (ret == 0) { dev_err(dev, "Wait for completion timed out.\n"); return -ETIMEDOUT; } return 0; } static int mxt_bootloader_read(struct mxt_data *data, u8 *val, unsigned int count) { int ret; struct i2c_msg msg; msg.addr = data->bootloader_addr; msg.flags = data->client->flags & I2C_M_TEN; msg.flags |= I2C_M_RD; msg.len = count; msg.buf = val; ret = i2c_transfer(data->client->adapter, &msg, 1); if (ret == 1) { ret = 0; } else { ret = ret < 0 ? ret : -EIO; dev_err(&data->client->dev, "%s: i2c recv failed (%d)\n", __func__, ret); } return ret; } static int mxt_bootloader_write(struct mxt_data *data, const u8 * const val, unsigned int count) { int ret; struct i2c_msg msg; msg.addr = data->bootloader_addr; msg.flags = data->client->flags & I2C_M_TEN; msg.len = count; msg.buf = (u8 *)val; ret = i2c_transfer(data->client->adapter, &msg, 1); if (ret == 1) { ret = 0; } else { ret = ret < 0 ? ret : -EIO; dev_err(&data->client->dev, "%s: i2c send failed (%d)\n", __func__, ret); } return ret; } static int mxt_lookup_bootloader_address(struct mxt_data *data, bool retry) { u8 appmode = data->client->addr; u8 bootloader; u8 family_id = data->info ? data->info->family_id : 0; switch (appmode) { case 0x4a: case 0x4b: /* Chips after 1664S use different scheme */ if (retry || family_id >= 0xa2) { bootloader = appmode - 0x24; break; } fallthrough; /* for normal case */ case 0x4c: case 0x4d: case 0x5a: case 0x5b: bootloader = appmode - 0x26; break; default: dev_err(&data->client->dev, "Appmode i2c address 0x%02x not found\n", appmode); return -EINVAL; } data->bootloader_addr = bootloader; return 0; } static int mxt_probe_bootloader(struct mxt_data *data, bool alt_address) { struct device *dev = &data->client->dev; int error; u8 val; bool crc_failure; error = mxt_lookup_bootloader_address(data, alt_address); if (error) return error; error = mxt_bootloader_read(data, &val, 1); if (error) return error; /* Check app crc fail mode */ crc_failure = (val & ~MXT_BOOT_STATUS_MASK) == MXT_APP_CRC_FAIL; dev_err(dev, "Detected bootloader, status:%02X%s\n", val, crc_failure ? ", APP_CRC_FAIL" : ""); return 0; } static u8 mxt_get_bootloader_version(struct mxt_data *data, u8 val) { struct device *dev = &data->client->dev; u8 buf[3]; if (val & MXT_BOOT_EXTENDED_ID) { if (mxt_bootloader_read(data, &buf[0], 3) != 0) { dev_err(dev, "%s: i2c failure\n", __func__); return val; } dev_dbg(dev, "Bootloader ID:%d Version:%d\n", buf[1], buf[2]); return buf[0]; } else { dev_dbg(dev, "Bootloader ID:%d\n", val & MXT_BOOT_ID_MASK); return val; } } static int mxt_check_bootloader(struct mxt_data *data, unsigned int state, bool wait) { struct device *dev = &data->client->dev; u8 val; int ret; recheck: if (wait) { /* * In application update mode, the interrupt * line signals state transitions. We must wait for the * CHG assertion before reading the status byte. * Once the status byte has been read, the line is deasserted. */ ret = mxt_wait_for_completion(data, &data->bl_completion, MXT_FW_CHG_TIMEOUT); if (ret) { /* * TODO: handle -ERESTARTSYS better by terminating * fw update process before returning to userspace * by writing length 0x000 to device (iff we are in * WAITING_FRAME_DATA state). */ dev_err(dev, "Update wait error %d\n", ret); return ret; } } ret = mxt_bootloader_read(data, &val, 1); if (ret) return ret; if (state == MXT_WAITING_BOOTLOAD_CMD) val = mxt_get_bootloader_version(data, val); switch (state) { case MXT_WAITING_BOOTLOAD_CMD: case MXT_WAITING_FRAME_DATA: case MXT_APP_CRC_FAIL: val &= ~MXT_BOOT_STATUS_MASK; break; case MXT_FRAME_CRC_PASS: if (val == MXT_FRAME_CRC_CHECK) { goto recheck; } else if (val == MXT_FRAME_CRC_FAIL) { dev_err(dev, "Bootloader CRC fail\n"); return -EINVAL; } break; default: return -EINVAL; } if (val != state) { dev_err(dev, "Invalid bootloader state %02X != %02X\n", val, state); return -EINVAL; } return 0; } static int mxt_send_bootloader_cmd(struct mxt_data *data, bool unlock) { u8 buf[2]; if (unlock) { buf[0] = MXT_UNLOCK_CMD_LSB; buf[1] = MXT_UNLOCK_CMD_MSB; } else { buf[0] = 0x01; buf[1] = 0x01; } return mxt_bootloader_write(data, buf, sizeof(buf)); } static bool mxt_wakeup_toggle(struct i2c_client *client, bool wake_up, bool in_i2c) { struct mxt_data *data = i2c_get_clientdata(client); switch (data->wakeup_method) { case ATMEL_MXT_WAKEUP_I2C_SCL: if (!in_i2c) return false; break; case ATMEL_MXT_WAKEUP_GPIO: if (in_i2c) return false; gpiod_set_value(data->wake_gpio, wake_up); break; default: return false; } if (wake_up) { dev_dbg(&client->dev, "waking up controller\n"); msleep(MXT_WAKEUP_TIME); } return true; } static int __mxt_read_reg(struct i2c_client *client, u16 reg, u16 len, void *val) { struct i2c_msg xfer[2]; bool retried = false; u8 buf[2]; int ret; buf[0] = reg & 0xff; buf[1] = (reg >> 8) & 0xff; /* Write register */ xfer[0].addr = client->addr; xfer[0].flags = 0; xfer[0].len = 2; xfer[0].buf = buf; /* Read data */ xfer[1].addr = client->addr; xfer[1].flags = I2C_M_RD; xfer[1].len = len; xfer[1].buf = val; retry: ret = i2c_transfer(client->adapter, xfer, 2); if (ret == 2) { ret = 0; } else if (!retried && mxt_wakeup_toggle(client, true, true)) { retried = true; goto retry; } else { if (ret >= 0) ret = -EIO; dev_err(&client->dev, "%s: i2c transfer failed (%d)\n", __func__, ret); } return ret; } static int __mxt_write_reg(struct i2c_client *client, u16 reg, u16 len, const void *val) { bool retried = false; u8 *buf; size_t count; int ret; count = len + 2; buf = kmalloc(count, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = reg & 0xff; buf[1] = (reg >> 8) & 0xff; memcpy(&buf[2], val, len); retry: ret = i2c_master_send(client, buf, count); if (ret == count) { ret = 0; } else if (!retried && mxt_wakeup_toggle(client, true, true)) { retried = true; goto retry; } else { if (ret >= 0) ret = -EIO; dev_err(&client->dev, "%s: i2c send failed (%d)\n", __func__, ret); } kfree(buf); return ret; } static int mxt_write_reg(struct i2c_client *client, u16 reg, u8 val) { return __mxt_write_reg(client, reg, 1, &val); } static struct mxt_object * mxt_get_object(struct mxt_data *data, u8 type) { struct mxt_object *object; int i; for (i = 0; i < data->info->object_num; i++) { object = data->object_table + i; if (object->type == type) return object; } dev_warn(&data->client->dev, "Invalid object type T%u\n", type); return NULL; } static void mxt_proc_t6_messages(struct mxt_data *data, u8 *msg) { struct device *dev = &data->client->dev; u8 status = msg[1]; u32 crc = msg[2] | (msg[3] << 8) | (msg[4] << 16); if (crc != data->config_crc) { data->config_crc = crc; dev_dbg(dev, "T6 Config Checksum: 0x%06X\n", crc); } complete(&data->crc_completion); /* Detect reset */ if (status & MXT_T6_STATUS_RESET) complete(&data->reset_completion); /* Output debug if status has changed */ if (status != data->t6_status) dev_dbg(dev, "T6 Status 0x%02X%s%s%s%s%s%s%s\n", status, status == 0 ? " OK" : "", status & MXT_T6_STATUS_RESET ? " RESET" : "", status & MXT_T6_STATUS_OFL ? " OFL" : "", status & MXT_T6_STATUS_SIGERR ? " SIGERR" : "", status & MXT_T6_STATUS_CAL ? " CAL" : "", status & MXT_T6_STATUS_CFGERR ? " CFGERR" : "", status & MXT_T6_STATUS_COMSERR ? " COMSERR" : ""); /* Save current status */ data->t6_status = status; } static int mxt_write_object(struct mxt_data *data, u8 type, u8 offset, u8 val) { struct mxt_object *object; u16 reg; object = mxt_get_object(data, type); if (!object || offset >= mxt_obj_size(object)) return -EINVAL; reg = object->start_address; return mxt_write_reg(data->client, reg + offset, val); } static void mxt_input_button(struct mxt_data *data, u8 *message) { struct input_dev *input = data->input_dev; int i; for (i = 0; i < data->t19_num_keys; i++) { if (data->t19_keymap[i] == KEY_RESERVED) continue; /* Active-low switch */ input_report_key(input, data->t19_keymap[i], !(message[1] & BIT(i))); } } static void mxt_input_sync(struct mxt_data *data) { input_mt_report_pointer_emulation(data->input_dev, data->t19_num_keys); input_sync(data->input_dev); } static void mxt_proc_t9_message(struct mxt_data *data, u8 *message) { struct device *dev = &data->client->dev; struct input_dev *input_dev = data->input_dev; int id; u8 status; int x; int y; int area; int amplitude; id = message[0] - data->T9_reportid_min; status = message[1]; x = (message[2] << 4) | ((message[4] >> 4) & 0xf); y = (message[3] << 4) | ((message[4] & 0xf)); /* Handle 10/12 bit switching */ if (data->max_x < 1024) x >>= 2; if (data->max_y < 1024) y >>= 2; area = message[5]; amplitude = message[6]; dev_dbg(dev, "[%u] %c%c%c%c%c%c%c%c x: %5u y: %5u area: %3u amp: %3u\n", id, (status & MXT_T9_DETECT) ? 'D' : '.', (status & MXT_T9_PRESS) ? 'P' : '.', (status & MXT_T9_RELEASE) ? 'R' : '.', (status & MXT_T9_MOVE) ? 'M' : '.', (status & MXT_T9_VECTOR) ? 'V' : '.', (status & MXT_T9_AMP) ? 'A' : '.', (status & MXT_T9_SUPPRESS) ? 'S' : '.', (status & MXT_T9_UNGRIP) ? 'U' : '.', x, y, area, amplitude); input_mt_slot(input_dev, id); if (status & MXT_T9_DETECT) { /* * Multiple bits may be set if the host is slow to read * the status messages, indicating all the events that * have happened. */ if (status & MXT_T9_RELEASE) { input_mt_report_slot_inactive(input_dev); mxt_input_sync(data); } /* if active, pressure must be non-zero */ if (!amplitude) amplitude = MXT_PRESSURE_DEFAULT; /* Touch active */ input_mt_report_slot_state(input_dev, MT_TOOL_FINGER, 1); input_report_abs(input_dev, ABS_MT_POSITION_X, x); input_report_abs(input_dev, ABS_MT_POSITION_Y, y); input_report_abs(input_dev, ABS_MT_PRESSURE, amplitude); input_report_abs(input_dev, ABS_MT_TOUCH_MAJOR, area); } else { /* Touch no longer active, close out slot */ input_mt_report_slot_inactive(input_dev); } data->update_input = true; } static void mxt_proc_t15_messages(struct mxt_data *data, u8 *message) { struct input_dev *input_dev = data->input_dev; unsigned long keystates = get_unaligned_le32(&message[2]); int key; for (key = 0; key < data->t15_num_keys; key++) input_report_key(input_dev, data->t15_keymap[key], keystates & BIT(key)); data->update_input = true; } static void mxt_proc_t97_messages(struct mxt_data *data, u8 *message) { mxt_proc_t15_messages(data, message); } static void mxt_proc_t100_message(struct mxt_data *data, u8 *message) { struct device *dev = &data->client->dev; struct input_dev *input_dev = data->input_dev; int id; u8 status; u8 type = 0; u16 x; u16 y; int distance = 0; int tool = 0; u8 major = 0; u8 pressure = 0; u8 orientation = 0; id = message[0] - data->T100_reportid_min - 2; /* ignore SCRSTATUS events */ if (id < 0) return; status = message[1]; x = get_unaligned_le16(&message[2]); y = get_unaligned_le16(&message[4]); if (status & MXT_T100_DETECT) { type = (status & MXT_T100_TYPE_MASK) >> 4; switch (type) { case MXT_T100_TYPE_HOVERING_FINGER: tool = MT_TOOL_FINGER; distance = MXT_DISTANCE_HOVERING; if (data->t100_aux_vect) orientation = message[data->t100_aux_vect]; break; case MXT_T100_TYPE_FINGER: case MXT_T100_TYPE_GLOVE: tool = MT_TOOL_FINGER; distance = MXT_DISTANCE_ACTIVE_TOUCH; if (data->t100_aux_area) major = message[data->t100_aux_area]; if (data->t100_aux_ampl) pressure = message[data->t100_aux_ampl]; if (data->t100_aux_vect) orientation = message[data->t100_aux_vect]; break; case MXT_T100_TYPE_PASSIVE_STYLUS: tool = MT_TOOL_PEN; /* * Passive stylus is reported with size zero so * hardcode. */ major = MXT_TOUCH_MAJOR_DEFAULT; if (data->t100_aux_ampl) pressure = message[data->t100_aux_ampl]; break; case MXT_T100_TYPE_LARGE_TOUCH: /* Ignore suppressed touch */ break; default: dev_dbg(dev, "Unexpected T100 type\n"); return; } } /* * Values reported should be non-zero if tool is touching the * device */ if (!pressure && type != MXT_T100_TYPE_HOVERING_FINGER) pressure = MXT_PRESSURE_DEFAULT; input_mt_slot(input_dev, id); if (status & MXT_T100_DETECT) { dev_dbg(dev, "[%u] type:%u x:%u y:%u a:%02X p:%02X v:%02X\n", id, type, x, y, major, pressure, orientation); input_mt_report_slot_state(input_dev, tool, 1); input_report_abs(input_dev, ABS_MT_POSITION_X, x); input_report_abs(input_dev, ABS_MT_POSITION_Y, y); input_report_abs(input_dev, ABS_MT_TOUCH_MAJOR, major); input_report_abs(input_dev, ABS_MT_PRESSURE, pressure); input_report_abs(input_dev, ABS_MT_DISTANCE, distance); input_report_abs(input_dev, ABS_MT_ORIENTATION, orientation); } else { dev_dbg(dev, "[%u] release\n", id); /* close out slot */ input_mt_report_slot_inactive(input_dev); } data->update_input = true; } static int mxt_proc_message(struct mxt_data *data, u8 *message) { u8 report_id = message[0]; if (report_id == MXT_RPTID_NOMSG) return 0; if (report_id == data->T6_reportid) { mxt_proc_t6_messages(data, message); } else if (!data->input_dev) { /* * Do not report events if input device * is not yet registered. */ mxt_dump_message(data, message); } else if (report_id >= data->T9_reportid_min && report_id <= data->T9_reportid_max) { mxt_proc_t9_message(data, message); } else if (report_id >= data->T15_reportid_min && report_id <= data->T15_reportid_max) { mxt_proc_t15_messages(data, message); } else if (report_id >= data->T97_reportid_min && report_id <= data->T97_reportid_max) { mxt_proc_t97_messages(data, message); } else if (report_id >= data->T100_reportid_min && report_id <= data->T100_reportid_max) { mxt_proc_t100_message(data, message); } else if (report_id == data->T19_reportid) { mxt_input_button(data, message); data->update_input = true; } else { mxt_dump_message(data, message); } return 1; } static int mxt_read_and_process_messages(struct mxt_data *data, u8 count) { struct device *dev = &data->client->dev; int ret; int i; u8 num_valid = 0; /* Safety check for msg_buf */ if (count > data->max_reportid) return -EINVAL; /* Process remaining messages if necessary */ ret = __mxt_read_reg(data->client, data->T5_address, data->T5_msg_size * count, data->msg_buf); if (ret) { dev_err(dev, "Failed to read %u messages (%d)\n", count, ret); return ret; } for (i = 0; i < count; i++) { ret = mxt_proc_message(data, data->msg_buf + data->T5_msg_size * i); if (ret == 1) num_valid++; } /* return number of messages read */ return num_valid; } static irqreturn_t mxt_process_messages_t44(struct mxt_data *data) { struct device *dev = &data->client->dev; int ret; u8 count, num_left; /* Read T44 and T5 together */ ret = __mxt_read_reg(data->client, data->T44_address, data->T5_msg_size + 1, data->msg_buf); if (ret) { dev_err(dev, "Failed to read T44 and T5 (%d)\n", ret); return IRQ_NONE; } count = data->msg_buf[0]; /* * This condition may be caused by the CHG line being configured in * Mode 0. It results in unnecessary I2C operations but it is benign. */ if (count == 0) return IRQ_NONE; if (count > data->max_reportid) { dev_warn(dev, "T44 count %d exceeded max report id\n", count); count = data->max_reportid; } /* Process first message */ ret = mxt_proc_message(data, data->msg_buf + 1); if (ret < 0) { dev_warn(dev, "Unexpected invalid message\n"); return IRQ_NONE; } num_left = count - 1; /* Process remaining messages if necessary */ if (num_left) { ret = mxt_read_and_process_messages(data, num_left); if (ret < 0) goto end; else if (ret != num_left) dev_warn(dev, "Unexpected invalid message\n"); } end: if (data->update_input) { mxt_input_sync(data); data->update_input = false; } return IRQ_HANDLED; } static int mxt_process_messages_until_invalid(struct mxt_data *data) { struct device *dev = &data->client->dev; int count, read; u8 tries = 2; count = data->max_reportid; /* Read messages until we force an invalid */ do { read = mxt_read_and_process_messages(data, count); if (read < count) return 0; } while (--tries); if (data->update_input) { mxt_input_sync(data); data->update_input = false; } dev_err(dev, "CHG pin isn't cleared\n"); return -EBUSY; } static irqreturn_t mxt_process_messages(struct mxt_data *data) { int total_handled, num_handled; u8 count = data->last_message_count; if (count < 1 || count > data->max_reportid) count = 1; /* include final invalid message */ total_handled = mxt_read_and_process_messages(data, count + 1); if (total_handled < 0) return IRQ_NONE; /* if there were invalid messages, then we are done */ else if (total_handled <= count) goto update_count; /* keep reading two msgs until one is invalid or reportid limit */ do { num_handled = mxt_read_and_process_messages(data, 2); if (num_handled < 0) return IRQ_NONE; total_handled += num_handled; if (num_handled < 2) break; } while (total_handled < data->num_touchids); update_count: data->last_message_count = total_handled; if (data->update_input) { mxt_input_sync(data); data->update_input = false; } return IRQ_HANDLED; } static irqreturn_t mxt_interrupt(int irq, void *dev_id) { struct mxt_data *data = dev_id; if (data->in_bootloader) { /* bootloader state transition completion */ complete(&data->bl_completion); return IRQ_HANDLED; } if (!data->object_table) return IRQ_HANDLED; if (data->T44_address) { return mxt_process_messages_t44(data); } else { return mxt_process_messages(data); } } static int mxt_t6_command(struct mxt_data *data, u16 cmd_offset, u8 value, bool wait) { u16 reg; u8 command_register; int timeout_counter = 0; int ret; reg = data->T6_address + cmd_offset; ret = mxt_write_reg(data->client, reg, value); if (ret) return ret; if (!wait) return 0; do { msleep(20); ret = __mxt_read_reg(data->client, reg, 1, &command_register); if (ret) return ret; } while (command_register != 0 && timeout_counter++ <= 100); if (timeout_counter > 100) { dev_err(&data->client->dev, "Command failed!\n"); return -EIO; } return 0; } static int mxt_acquire_irq(struct mxt_data *data) { int error; enable_irq(data->irq); if (data->use_retrigen_workaround) { error = mxt_process_messages_until_invalid(data); if (error) return error; } return 0; } static int mxt_soft_reset(struct mxt_data *data) { struct device *dev = &data->client->dev; int ret = 0; dev_info(dev, "Resetting device\n"); disable_irq(data->irq); reinit_completion(&data->reset_completion); ret = mxt_t6_command(data, MXT_COMMAND_RESET, MXT_RESET_VALUE, false); if (ret) return ret; /* Ignore CHG line for 100ms after reset */ msleep(MXT_RESET_INVALID_CHG); mxt_acquire_irq(data); ret = mxt_wait_for_completion(data, &data->reset_completion, MXT_RESET_TIMEOUT); if (ret) return ret; return 0; } static void mxt_update_crc(struct mxt_data *data, u8 cmd, u8 value) { /* * On failure, CRC is set to 0 and config will always be * downloaded. */ data->config_crc = 0; reinit_completion(&data->crc_completion); mxt_t6_command(data, cmd, value, true); /* * Wait for crc message. On failure, CRC is set to 0 and config will * always be downloaded. */ mxt_wait_for_completion(data, &data->crc_completion, MXT_CRC_TIMEOUT); } static void mxt_calc_crc24(u32 *crc, u8 firstbyte, u8 secondbyte) { static const unsigned int crcpoly = 0x80001B; u32 result; u32 data_word; data_word = (secondbyte << 8) | firstbyte; result = ((*crc << 1) ^ data_word); if (result & 0x1000000) result ^= crcpoly; *crc = result; } static u32 mxt_calculate_crc(u8 *base, off_t start_off, off_t end_off) { u32 crc = 0; u8 *ptr = base + start_off; u8 *last_val = base + end_off - 1; if (end_off < start_off) return -EINVAL; while (ptr < last_val) { mxt_calc_crc24(&crc, *ptr, *(ptr + 1)); ptr += 2; } /* if len is odd, fill the last byte with 0 */ if (ptr == last_val) mxt_calc_crc24(&crc, *ptr, 0); /* Mask to 24-bit */ crc &= 0x00FFFFFF; return crc; } static int mxt_check_retrigen(struct mxt_data *data) { struct i2c_client *client = data->client; int error; int val; struct irq_data *irqd; data->use_retrigen_workaround = false; irqd = irq_get_irq_data(data->irq); if (!irqd) return -EINVAL; if (irqd_is_level_type(irqd)) return 0; if (data->T18_address) { error = __mxt_read_reg(client, data->T18_address + MXT_COMMS_CTRL, 1, &val); if (error) return error; if (val & MXT_COMMS_RETRIGEN) return 0; } dev_warn(&client->dev, "Enabling RETRIGEN workaround\n"); data->use_retrigen_workaround = true; return 0; } static int mxt_prepare_cfg_mem(struct mxt_data *data, struct mxt_cfg *cfg) { struct device *dev = &data->client->dev; struct mxt_object *object; unsigned int type, instance, size, byte_offset; int offset; int ret; int i; u16 reg; u8 val; while (cfg->raw_pos < cfg->raw_size) { /* Read type, instance, length */ ret = sscanf(cfg->raw + cfg->raw_pos, "%x %x %x%n", &type, &instance, &size, &offset); if (ret == 0) { /* EOF */ break; } else if (ret != 3) { dev_err(dev, "Bad format: failed to parse object\n"); return -EINVAL; } cfg->raw_pos += offset; object = mxt_get_object(data, type); if (!object) { /* Skip object */ for (i = 0; i < size; i++) { ret = sscanf(cfg->raw + cfg->raw_pos, "%hhx%n", &val, &offset); if (ret != 1) { dev_err(dev, "Bad format in T%d at %d\n", type, i); return -EINVAL; } cfg->raw_pos += offset; } continue; } if (size > mxt_obj_size(object)) { /* * Either we are in fallback mode due to wrong * config or config from a later fw version, * or the file is corrupt or hand-edited. */ dev_warn(dev, "Discarding %zu byte(s) in T%u\n", size - mxt_obj_size(object), type); } else if (mxt_obj_size(object) > size) { /* * If firmware is upgraded, new bytes may be added to * end of objects. It is generally forward compatible * to zero these bytes - previous behaviour will be * retained. However this does invalidate the CRC and * will force fallback mode until the configuration is * updated. We warn here but do nothing else - the * malloc has zeroed the entire configuration. */ dev_warn(dev, "Zeroing %zu byte(s) in T%d\n", mxt_obj_size(object) - size, type); } if (instance >= mxt_obj_instances(object)) { dev_err(dev, "Object instances exceeded!\n"); return -EINVAL; } reg = object->start_address + mxt_obj_size(object) * instance; for (i = 0; i < size; i++) { ret = sscanf(cfg->raw + cfg->raw_pos, "%hhx%n", &val, &offset); if (ret != 1) { dev_err(dev, "Bad format in T%d at %d\n", type, i); return -EINVAL; } cfg->raw_pos += offset; if (i > mxt_obj_size(object)) continue; byte_offset = reg + i - cfg->start_ofs; if (byte_offset >= 0 && byte_offset < cfg->mem_size) { *(cfg->mem + byte_offset) = val; } else { dev_err(dev, "Bad object: reg:%d, T%d, ofs=%d\n", reg, object->type, byte_offset); return -EINVAL; } } } return 0; } static int mxt_upload_cfg_mem(struct mxt_data *data, struct mxt_cfg *cfg) { unsigned int byte_offset = 0; int error; /* Write configuration as blocks */ while (byte_offset < cfg->mem_size) { unsigned int size = cfg->mem_size - byte_offset; if (size > MXT_MAX_BLOCK_WRITE) size = MXT_MAX_BLOCK_WRITE; error = __mxt_write_reg(data->client, cfg->start_ofs + byte_offset, size, cfg->mem + byte_offset); if (error) { dev_err(&data->client->dev, "Config write error, ret=%d\n", error); return error; } byte_offset += size; } return 0; } static int mxt_init_t7_power_cfg(struct mxt_data *data); /* * mxt_update_cfg - download configuration to chip * * Atmel Raw Config File Format * * The first four lines of the raw config file contain: * 1) Version * 2) Chip ID Information (first 7 bytes of device memory) * 3) Chip Information Block 24-bit CRC Checksum * 4) Chip Configuration 24-bit CRC Checksum * * The rest of the file consists of one line per object instance: * <TYPE> <INSTANCE> <SIZE> <CONTENTS> * * <TYPE> - 2-byte object type as hex * <INSTANCE> - 2-byte object instance number as hex * <SIZE> - 2-byte object size as hex * <CONTENTS> - array of <SIZE> 1-byte hex values */ static int mxt_update_cfg(struct mxt_data *data, const struct firmware *fw) { struct device *dev = &data->client->dev; struct mxt_cfg cfg; int ret; int offset; int i; u32 info_crc, config_crc, calculated_crc; u16 crc_start = 0; /* Make zero terminated copy of the OBP_RAW file */ cfg.raw = kmemdup_nul(fw->data, fw->size, GFP_KERNEL); if (!cfg.raw) return -ENOMEM; cfg.raw_size = fw->size; mxt_update_crc(data, MXT_COMMAND_REPORTALL, 1); if (strncmp(cfg.raw, MXT_CFG_MAGIC, strlen(MXT_CFG_MAGIC))) { dev_err(dev, "Unrecognised config file\n"); ret = -EINVAL; goto release_raw; } cfg.raw_pos = strlen(MXT_CFG_MAGIC); /* Load information block and check */ for (i = 0; i < sizeof(struct mxt_info); i++) { ret = sscanf(cfg.raw + cfg.raw_pos, "%hhx%n", (unsigned char *)&cfg.info + i, &offset); if (ret != 1) { dev_err(dev, "Bad format\n"); ret = -EINVAL; goto release_raw; } cfg.raw_pos += offset; } if (cfg.info.family_id != data->info->family_id) { dev_err(dev, "Family ID mismatch!\n"); ret = -EINVAL; goto release_raw; } if (cfg.info.variant_id != data->info->variant_id) { dev_err(dev, "Variant ID mismatch!\n"); ret = -EINVAL; goto release_raw; } /* Read CRCs */ ret = sscanf(cfg.raw + cfg.raw_pos, "%x%n", &info_crc, &offset); if (ret != 1) { dev_err(dev, "Bad format: failed to parse Info CRC\n"); ret = -EINVAL; goto release_raw; } cfg.raw_pos += offset; ret = sscanf(cfg.raw + cfg.raw_pos, "%x%n", &config_crc, &offset); if (ret != 1) { dev_err(dev, "Bad format: failed to parse Config CRC\n"); ret = -EINVAL; goto release_raw; } cfg.raw_pos += offset; /* * The Info Block CRC is calculated over mxt_info and the object * table. If it does not match then we are trying to load the * configuration from a different chip or firmware version, so * the configuration CRC is invalid anyway. */ if (info_crc == data->info_crc) { if (config_crc == 0 || data->config_crc == 0) { dev_info(dev, "CRC zero, attempting to apply config\n"); } else if (config_crc == data->config_crc) { dev_dbg(dev, "Config CRC 0x%06X: OK\n", data->config_crc); ret = 0; goto release_raw; } else { dev_info(dev, "Config CRC 0x%06X: does not match file 0x%06X\n", data->config_crc, config_crc); } } else { dev_warn(dev, "Warning: Info CRC error - device=0x%06X file=0x%06X\n", data->info_crc, info_crc); } /* Malloc memory to store configuration */ cfg.start_ofs = MXT_OBJECT_START + data->info->object_num * sizeof(struct mxt_object) + MXT_INFO_CHECKSUM_SIZE; cfg.mem_size = data->mem_size - cfg.start_ofs; cfg.mem = kzalloc(cfg.mem_size, GFP_KERNEL); if (!cfg.mem) { ret = -ENOMEM; goto release_raw; } ret = mxt_prepare_cfg_mem(data, &cfg); if (ret) goto release_mem; /* Calculate crc of the received configs (not the raw config file) */ if (data->T71_address) crc_start = data->T71_address; else if (data->T7_address) crc_start = data->T7_address; else dev_warn(dev, "Could not find CRC start\n"); if (crc_start > cfg.start_ofs) { calculated_crc = mxt_calculate_crc(cfg.mem, crc_start - cfg.start_ofs, cfg.mem_size); if (config_crc > 0 && config_crc != calculated_crc) dev_warn(dev, "Config CRC in file inconsistent, calculated=%06X, file=%06X\n", calculated_crc, config_crc); } ret = mxt_upload_cfg_mem(data, &cfg); if (ret) goto release_mem; mxt_update_crc(data, MXT_COMMAND_BACKUPNV, MXT_BACKUP_VALUE); ret = mxt_check_retrigen(data); if (ret) goto release_mem; ret = mxt_soft_reset(data); if (ret) goto release_mem; dev_info(dev, "Config successfully updated\n"); /* T7 config may have changed */ mxt_init_t7_power_cfg(data); release_mem: kfree(cfg.mem); release_raw: kfree(cfg.raw); return ret; } static void mxt_free_input_device(struct mxt_data *data) { if (data->input_dev) { input_unregister_device(data->input_dev); data->input_dev = NULL; } } static void mxt_free_object_table(struct mxt_data *data) { #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37 video_unregister_device(&data->dbg.vdev); v4l2_device_unregister(&data->dbg.v4l2); #endif data->object_table = NULL; data->info = NULL; kfree(data->raw_info_block); data->raw_info_block = NULL; kfree(data->msg_buf); data->msg_buf = NULL; data->T5_address = 0; data->T5_msg_size = 0; data->T6_reportid = 0; data->T7_address = 0; data->T71_address = 0; data->T9_reportid_min = 0; data->T9_reportid_max = 0; data->T15_reportid_min = 0; data->T15_reportid_max = 0; data->T18_address = 0; data->T19_reportid = 0; data->T44_address = 0; data->T97_reportid_min = 0; data->T97_reportid_max = 0; data->T100_reportid_min = 0; data->T100_reportid_max = 0; data->max_reportid = 0; } static int mxt_parse_object_table(struct mxt_data *data, struct mxt_object *object_table) { struct i2c_client *client = data->client; int i; u8 reportid; u16 end_address; /* Valid Report IDs start counting from 1 */ reportid = 1; data->mem_size = 0; for (i = 0; i < data->info->object_num; i++) { struct mxt_object *object = object_table + i; u8 min_id, max_id; le16_to_cpus(&object->start_address); if (object->num_report_ids) { min_id = reportid; reportid += object->num_report_ids * mxt_obj_instances(object); max_id = reportid - 1; } else { min_id = 0; max_id = 0; } dev_dbg(&data->client->dev, "T%u Start:%u Size:%zu Instances:%zu Report IDs:%u-%u\n", object->type, object->start_address, mxt_obj_size(object), mxt_obj_instances(object), min_id, max_id); switch (object->type) { case MXT_GEN_MESSAGE_T5: if (data->info->family_id == 0x80 && data->info->version < 0x20) { /* * On mXT224 firmware versions prior to V2.0 * read and discard unused CRC byte otherwise * DMA reads are misaligned. */ data->T5_msg_size = mxt_obj_size(object); } else { /* CRC not enabled, so skip last byte */ data->T5_msg_size = mxt_obj_size(object) - 1; } data->T5_address = object->start_address; break; case MXT_GEN_COMMAND_T6: data->T6_reportid = min_id; data->T6_address = object->start_address; break; case MXT_GEN_POWER_T7: data->T7_address = object->start_address; break; case MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71: data->T71_address = object->start_address; break; case MXT_TOUCH_MULTI_T9: data->multitouch = MXT_TOUCH_MULTI_T9; /* Only handle messages from first T9 instance */ data->T9_reportid_min = min_id; data->T9_reportid_max = min_id + object->num_report_ids - 1; data->num_touchids = object->num_report_ids; break; case MXT_TOUCH_KEYARRAY_T15: data->T15_reportid_min = min_id; data->T15_reportid_max = max_id; break; case MXT_SPT_COMMSCONFIG_T18: data->T18_address = object->start_address; break; case MXT_SPT_MESSAGECOUNT_T44: data->T44_address = object->start_address; break; case MXT_SPT_GPIOPWM_T19: data->T19_reportid = min_id; break; case MXT_TOUCH_PTC_KEYS_T97: data->T97_reportid_min = min_id; data->T97_reportid_max = max_id; break; case MXT_TOUCH_MULTITOUCHSCREEN_T100: data->multitouch = MXT_TOUCH_MULTITOUCHSCREEN_T100; data->T100_reportid_min = min_id; data->T100_reportid_max = max_id; /* first two report IDs reserved */ data->num_touchids = object->num_report_ids - 2; break; } end_address = object->start_address + mxt_obj_size(object) * mxt_obj_instances(object) - 1; if (end_address >= data->mem_size) data->mem_size = end_address + 1; } /* Store maximum reportid */ data->max_reportid = reportid; /* If T44 exists, T5 position has to be directly after */ if (data->T44_address && (data->T5_address != data->T44_address + 1)) { dev_err(&client->dev, "Invalid T44 position\n"); return -EINVAL; } data->msg_buf = kcalloc(data->max_reportid, data->T5_msg_size, GFP_KERNEL); if (!data->msg_buf) return -ENOMEM; return 0; } static int mxt_read_info_block(struct mxt_data *data) { struct i2c_client *client = data->client; int error; size_t size; void *id_buf, *buf; uint8_t num_objects; u32 calculated_crc; u8 *crc_ptr; /* If info block already allocated, free it */ if (data->raw_info_block) mxt_free_object_table(data); /* Read 7-byte ID information block starting at address 0 */ size = sizeof(struct mxt_info); id_buf = kzalloc(size, GFP_KERNEL); if (!id_buf) return -ENOMEM; error = __mxt_read_reg(client, 0, size, id_buf); if (error) goto err_free_mem; /* Resize buffer to give space for rest of info block */ num_objects = ((struct mxt_info *)id_buf)->object_num; size += (num_objects * sizeof(struct mxt_object)) + MXT_INFO_CHECKSUM_SIZE; buf = krealloc(id_buf, size, GFP_KERNEL); if (!buf) { error = -ENOMEM; goto err_free_mem; } id_buf = buf; /* Read rest of info block */ error = __mxt_read_reg(client, MXT_OBJECT_START, size - MXT_OBJECT_START, id_buf + MXT_OBJECT_START); if (error) goto err_free_mem; /* Extract & calculate checksum */ crc_ptr = id_buf + size - MXT_INFO_CHECKSUM_SIZE; data->info_crc = crc_ptr[0] | (crc_ptr[1] << 8) | (crc_ptr[2] << 16); calculated_crc = mxt_calculate_crc(id_buf, 0, size - MXT_INFO_CHECKSUM_SIZE); /* * CRC mismatch can be caused by data corruption due to I2C comms * issue or else device is not using Object Based Protocol (eg i2c-hid) */ if ((data->info_crc == 0) || (data->info_crc != calculated_crc)) { dev_err(&client->dev, "Info Block CRC error calculated=0x%06X read=0x%06X\n", calculated_crc, data->info_crc); error = -EIO; goto err_free_mem; } data->raw_info_block = id_buf; data->info = (struct mxt_info *)id_buf; dev_info(&client->dev, "Family: %u Variant: %u Firmware V%u.%u.%02X Objects: %u\n", data->info->family_id, data->info->variant_id, data->info->version >> 4, data->info->version & 0xf, data->info->build, data->info->object_num); /* Parse object table information */ error = mxt_parse_object_table(data, id_buf + MXT_OBJECT_START); if (error) { dev_err(&client->dev, "Error %d parsing object table\n", error); mxt_free_object_table(data); return error; } data->object_table = (struct mxt_object *)(id_buf + MXT_OBJECT_START); return 0; err_free_mem: kfree(id_buf); return error; } static int mxt_read_t9_resolution(struct mxt_data *data) { struct i2c_client *client = data->client; int error; struct t9_range range; unsigned char orient; struct mxt_object *object; object = mxt_get_object(data, MXT_TOUCH_MULTI_T9); if (!object) return -EINVAL; error = __mxt_read_reg(client, object->start_address + MXT_T9_XSIZE, sizeof(data->xsize), &data->xsize); if (error) return error; error = __mxt_read_reg(client, object->start_address + MXT_T9_YSIZE, sizeof(data->ysize), &data->ysize); if (error) return error; error = __mxt_read_reg(client, object->start_address + MXT_T9_RANGE, sizeof(range), &range); if (error) return error; data->max_x = get_unaligned_le16(&range.x); data->max_y = get_unaligned_le16(&range.y); error = __mxt_read_reg(client, object->start_address + MXT_T9_ORIENT, 1, &orient); if (error) return error; data->xy_switch = orient & MXT_T9_ORIENT_SWITCH; data->invertx = orient & MXT_T9_ORIENT_INVERTX; data->inverty = orient & MXT_T9_ORIENT_INVERTY; return 0; } static int mxt_read_t100_config(struct mxt_data *data) { struct i2c_client *client = data->client; int error; struct mxt_object *object; u16 range_x, range_y; u8 cfg, tchaux; u8 aux; object = mxt_get_object(data, MXT_TOUCH_MULTITOUCHSCREEN_T100); if (!object) return -EINVAL; /* read touchscreen dimensions */ error = __mxt_read_reg(client, object->start_address + MXT_T100_XRANGE, sizeof(range_x), &range_x); if (error) return error; data->max_x = get_unaligned_le16(&range_x); error = __mxt_read_reg(client, object->start_address + MXT_T100_YRANGE, sizeof(range_y), &range_y); if (error) return error; data->max_y = get_unaligned_le16(&range_y); error = __mxt_read_reg(client, object->start_address + MXT_T100_XSIZE, sizeof(data->xsize), &data->xsize); if (error) return error; error = __mxt_read_reg(client, object->start_address + MXT_T100_YSIZE, sizeof(data->ysize), &data->ysize); if (error) return error; /* read orientation config */ error = __mxt_read_reg(client, object->start_address + MXT_T100_CFG1, 1, &cfg); if (error) return error; data->xy_switch = cfg & MXT_T100_CFG_SWITCHXY; data->invertx = cfg & MXT_T100_CFG_INVERTX; data->inverty = cfg & MXT_T100_CFG_INVERTY; /* allocate aux bytes */ error = __mxt_read_reg(client, object->start_address + MXT_T100_TCHAUX, 1, &tchaux); if (error) return error; aux = 6; if (tchaux & MXT_T100_TCHAUX_VECT) data->t100_aux_vect = aux++; if (tchaux & MXT_T100_TCHAUX_AMPL) data->t100_aux_ampl = aux++; if (tchaux & MXT_T100_TCHAUX_AREA) data->t100_aux_area = aux++; dev_dbg(&client->dev, "T100 aux mappings vect:%u ampl:%u area:%u\n", data->t100_aux_vect, data->t100_aux_ampl, data->t100_aux_area); return 0; } static int mxt_input_open(struct input_dev *dev); static void mxt_input_close(struct input_dev *dev); static void mxt_set_up_as_touchpad(struct input_dev *input_dev, struct mxt_data *data) { int i; input_dev->name = "Atmel maXTouch Touchpad"; __set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit); input_abs_set_res(input_dev, ABS_X, MXT_PIXELS_PER_MM); input_abs_set_res(input_dev, ABS_Y, MXT_PIXELS_PER_MM); input_abs_set_res(input_dev, ABS_MT_POSITION_X, MXT_PIXELS_PER_MM); input_abs_set_res(input_dev, ABS_MT_POSITION_Y, MXT_PIXELS_PER_MM); for (i = 0; i < data->t19_num_keys; i++) if (data->t19_keymap[i] != KEY_RESERVED) input_set_capability(input_dev, EV_KEY, data->t19_keymap[i]); } static int mxt_initialize_input_device(struct mxt_data *data) { struct device *dev = &data->client->dev; struct input_dev *input_dev; int error; unsigned int num_mt_slots; unsigned int mt_flags = 0; int i; switch (data->multitouch) { case MXT_TOUCH_MULTI_T9: num_mt_slots = data->T9_reportid_max - data->T9_reportid_min + 1; error = mxt_read_t9_resolution(data); if (error) dev_warn(dev, "Failed to initialize T9 resolution\n"); break; case MXT_TOUCH_MULTITOUCHSCREEN_T100: num_mt_slots = data->num_touchids; error = mxt_read_t100_config(data); if (error) dev_warn(dev, "Failed to read T100 config\n"); break; default: dev_err(dev, "Invalid multitouch object\n"); return -EINVAL; } /* Handle default values and orientation switch */ if (data->max_x == 0) data->max_x = 1023; if (data->max_y == 0) data->max_y = 1023; if (data->xy_switch) swap(data->max_x, data->max_y); dev_info(dev, "Touchscreen size X%uY%u\n", data->max_x, data->max_y); /* Register input device */ input_dev = input_allocate_device(); if (!input_dev) return -ENOMEM; input_dev->name = "Atmel maXTouch Touchscreen"; input_dev->phys = data->phys; input_dev->id.bustype = BUS_I2C; input_dev->dev.parent = dev; input_dev->open = mxt_input_open; input_dev->close = mxt_input_close; input_dev->keycode = data->t15_keymap; input_dev->keycodemax = data->t15_num_keys; input_dev->keycodesize = sizeof(data->t15_keymap[0]); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); /* For single touch */ input_set_abs_params(input_dev, ABS_X, 0, data->max_x, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, data->max_y, 0, 0); if (data->multitouch == MXT_TOUCH_MULTI_T9 || (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 && data->t100_aux_ampl)) { input_set_abs_params(input_dev, ABS_PRESSURE, 0, 255, 0, 0); } /* If device has buttons we assume it is a touchpad */ if (data->t19_num_keys) { mxt_set_up_as_touchpad(input_dev, data); mt_flags |= INPUT_MT_POINTER; } else { mt_flags |= INPUT_MT_DIRECT; } /* For multi touch */ error = input_mt_init_slots(input_dev, num_mt_slots, mt_flags); if (error) { dev_err(dev, "Error %d initialising slots\n", error); goto err_free_mem; } if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100) { input_set_abs_params(input_dev, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); input_set_abs_params(input_dev, ABS_MT_DISTANCE, MXT_DISTANCE_ACTIVE_TOUCH, MXT_DISTANCE_HOVERING, 0, 0); } input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, data->max_x, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, data->max_y, 0, 0); if (data->multitouch == MXT_TOUCH_MULTI_T9 || (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 && data->t100_aux_area)) { input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, MXT_MAX_AREA, 0, 0); } if (data->multitouch == MXT_TOUCH_MULTI_T9 || (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 && data->t100_aux_ampl)) { input_set_abs_params(input_dev, ABS_MT_PRESSURE, 0, 255, 0, 0); } if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 && data->t100_aux_vect) { input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 255, 0, 0); } if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 && data->t100_aux_vect) { input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 255, 0, 0); } /* For T15 and T97 Key Array */ if (data->T15_reportid_min || data->T97_reportid_min) { for (i = 0; i < data->t15_num_keys; i++) input_set_capability(input_dev, EV_KEY, data->t15_keymap[i]); } input_set_drvdata(input_dev, data); error = input_register_device(input_dev); if (error) { dev_err(dev, "Error %d registering input device\n", error); goto err_free_mem; } data->input_dev = input_dev; return 0; err_free_mem: input_free_device(input_dev); return error; } static int mxt_configure_objects(struct mxt_data *data, const struct firmware *cfg); static void mxt_config_cb(const struct firmware *cfg, void *ctx) { mxt_configure_objects(ctx, cfg); release_firmware(cfg); } static int mxt_initialize(struct mxt_data *data) { struct i2c_client *client = data->client; int recovery_attempts = 0; int error; while (1) { error = mxt_read_info_block(data); if (!error) break; /* Check bootloader state */ error = mxt_probe_bootloader(data, false); if (error) { dev_info(&client->dev, "Trying alternate bootloader address\n"); error = mxt_probe_bootloader(data, true); if (error) { /* Chip is not in appmode or bootloader mode */ return error; } } /* OK, we are in bootloader, see if we can recover */ if (++recovery_attempts > 1) { dev_err(&client->dev, "Could not recover from bootloader mode\n"); /* * We can reflash from this state, so do not * abort initialization. */ data->in_bootloader = true; return 0; } /* Attempt to exit bootloader into app mode */ mxt_send_bootloader_cmd(data, false); msleep(MXT_FW_RESET_TIME); } error = mxt_check_retrigen(data); if (error) return error; error = mxt_acquire_irq(data); if (error) return error; error = request_firmware_nowait(THIS_MODULE, true, MXT_CFG_NAME, &client->dev, GFP_KERNEL, data, mxt_config_cb); if (error) { dev_err(&client->dev, "Failed to invoke firmware loader: %d\n", error); return error; } return 0; } static int mxt_set_t7_power_cfg(struct mxt_data *data, u8 sleep) { struct device *dev = &data->client->dev; int error; struct t7_config *new_config; struct t7_config deepsleep = { .active = 0, .idle = 0 }; if (sleep == MXT_POWER_CFG_DEEPSLEEP) new_config = &deepsleep; else new_config = &data->t7_cfg; error = __mxt_write_reg(data->client, data->T7_address, sizeof(data->t7_cfg), new_config); if (error) return error; dev_dbg(dev, "Set T7 ACTV:%d IDLE:%d\n", new_config->active, new_config->idle); return 0; } static int mxt_init_t7_power_cfg(struct mxt_data *data) { struct device *dev = &data->client->dev; int error; bool retry = false; recheck: error = __mxt_read_reg(data->client, data->T7_address, sizeof(data->t7_cfg), &data->t7_cfg); if (error) return error; if (data->t7_cfg.active == 0 || data->t7_cfg.idle == 0) { if (!retry) { dev_dbg(dev, "T7 cfg zero, resetting\n"); mxt_soft_reset(data); retry = true; goto recheck; } else { dev_dbg(dev, "T7 cfg zero after reset, overriding\n"); data->t7_cfg.active = 20; data->t7_cfg.idle = 100; return mxt_set_t7_power_cfg(data, MXT_POWER_CFG_RUN); } } dev_dbg(dev, "Initialized power cfg: ACTV %d, IDLE %d\n", data->t7_cfg.active, data->t7_cfg.idle); return 0; } #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37 static const struct v4l2_file_operations mxt_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 u16 mxt_get_debug_value(struct mxt_data *data, unsigned int x, unsigned int y) { struct mxt_info *info = data->info; struct mxt_dbg *dbg = &data->dbg; unsigned int ofs, page; unsigned int col = 0; unsigned int col_width; if (info->family_id == MXT_FAMILY_1386) { col_width = info->matrix_ysize / MXT1386_COLUMNS; col = y / col_width; y = y % col_width; } else { col_width = info->matrix_ysize; } ofs = (y + (x * col_width)) * sizeof(u16); page = ofs / MXT_DIAGNOSTIC_SIZE; ofs %= MXT_DIAGNOSTIC_SIZE; if (info->family_id == MXT_FAMILY_1386) page += col * MXT1386_PAGES_PER_COLUMN; return get_unaligned_le16(&dbg->t37_buf[page].data[ofs]); } static int mxt_convert_debug_pages(struct mxt_data *data, u16 *outbuf) { struct mxt_dbg *dbg = &data->dbg; unsigned int x = 0; unsigned int y = 0; unsigned int i, rx, ry; for (i = 0; i < dbg->t37_nodes; i++) { /* Handle orientation */ rx = data->xy_switch ? y : x; ry = data->xy_switch ? x : y; rx = data->invertx ? (data->xsize - 1 - rx) : rx; ry = data->inverty ? (data->ysize - 1 - ry) : ry; outbuf[i] = mxt_get_debug_value(data, rx, ry); /* Next value */ if (++x >= (data->xy_switch ? data->ysize : data->xsize)) { x = 0; y++; } } return 0; } static int mxt_read_diagnostic_debug(struct mxt_data *data, u8 mode, u16 *outbuf) { struct mxt_dbg *dbg = &data->dbg; int retries = 0; int page; int ret; u8 cmd = mode; struct t37_debug *p; u8 cmd_poll; for (page = 0; page < dbg->t37_pages; page++) { p = dbg->t37_buf + page; ret = mxt_write_reg(data->client, dbg->diag_cmd_address, cmd); if (ret) return ret; retries = 0; msleep(20); wait_cmd: /* Read back command byte */ ret = __mxt_read_reg(data->client, dbg->diag_cmd_address, sizeof(cmd_poll), &cmd_poll); if (ret) return ret; /* Field is cleared once the command has been processed */ if (cmd_poll) { if (retries++ > 100) return -EINVAL; msleep(20); goto wait_cmd; } /* Read T37 page */ ret = __mxt_read_reg(data->client, dbg->t37_address, sizeof(struct t37_debug), p); if (ret) return ret; if (p->mode != mode || p->page != page) { dev_err(&data->client->dev, "T37 page mismatch\n"); return -EINVAL; } dev_dbg(&data->client->dev, "%s page:%d retries:%d\n", __func__, page, retries); /* For remaining pages, write PAGEUP rather than mode */ cmd = MXT_DIAGNOSTIC_PAGEUP; } return mxt_convert_debug_pages(data, outbuf); } static int mxt_queue_setup(struct vb2_queue *q, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct mxt_data *data = q->drv_priv; size_t size = data->dbg.t37_nodes * sizeof(u16); if (*nplanes) return sizes[0] < size ? -EINVAL : 0; *nplanes = 1; sizes[0] = size; return 0; } static void mxt_buffer_queue(struct vb2_buffer *vb) { struct mxt_data *data = vb2_get_drv_priv(vb->vb2_queue); u16 *ptr; int ret; u8 mode; ptr = vb2_plane_vaddr(vb, 0); if (!ptr) { dev_err(&data->client->dev, "Error acquiring frame ptr\n"); goto fault; } switch (data->dbg.input) { case MXT_V4L_INPUT_DELTAS: default: mode = MXT_DIAGNOSTIC_DELTAS; break; case MXT_V4L_INPUT_REFS: mode = MXT_DIAGNOSTIC_REFS; break; } ret = mxt_read_diagnostic_debug(data, mode, ptr); if (ret) goto fault; vb2_set_plane_payload(vb, 0, data->dbg.t37_nodes * sizeof(u16)); vb2_buffer_done(vb, VB2_BUF_STATE_DONE); return; fault: vb2_buffer_done(vb, VB2_BUF_STATE_ERROR); } /* V4L2 structures */ static const struct vb2_ops mxt_queue_ops = { .queue_setup = mxt_queue_setup, .buf_queue = mxt_buffer_queue, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static const struct vb2_queue mxt_queue = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ, .buf_struct_size = sizeof(struct mxt_vb2_buffer), .ops = &mxt_queue_ops, .mem_ops = &vb2_vmalloc_memops, .timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC, .min_buffers_needed = 1, }; static int mxt_vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct mxt_data *data = video_drvdata(file); strscpy(cap->driver, "atmel_mxt_ts", sizeof(cap->driver)); strscpy(cap->card, "atmel_mxt_ts touch", sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "I2C:%s", dev_name(&data->client->dev)); return 0; } static int mxt_vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *i) { if (i->index >= MXT_V4L_INPUT_MAX) return -EINVAL; i->type = V4L2_INPUT_TYPE_TOUCH; switch (i->index) { case MXT_V4L_INPUT_REFS: strscpy(i->name, "Mutual Capacitance References", sizeof(i->name)); break; case MXT_V4L_INPUT_DELTAS: strscpy(i->name, "Mutual Capacitance Deltas", sizeof(i->name)); break; } return 0; } static int mxt_set_input(struct mxt_data *data, unsigned int i) { struct v4l2_pix_format *f = &data->dbg.format; if (i >= MXT_V4L_INPUT_MAX) return -EINVAL; if (i == MXT_V4L_INPUT_DELTAS) f->pixelformat = V4L2_TCH_FMT_DELTA_TD16; else f->pixelformat = V4L2_TCH_FMT_TU16; f->width = data->xy_switch ? data->ysize : data->xsize; f->height = data->xy_switch ? data->xsize : data->ysize; f->field = V4L2_FIELD_NONE; f->colorspace = V4L2_COLORSPACE_RAW; f->bytesperline = f->width * sizeof(u16); f->sizeimage = f->width * f->height * sizeof(u16); data->dbg.input = i; return 0; } static int mxt_vidioc_s_input(struct file *file, void *priv, unsigned int i) { return mxt_set_input(video_drvdata(file), i); } static int mxt_vidioc_g_input(struct file *file, void *priv, unsigned int *i) { struct mxt_data *data = video_drvdata(file); *i = data->dbg.input; return 0; } static int mxt_vidioc_fmt(struct file *file, void *priv, struct v4l2_format *f) { struct mxt_data *data = video_drvdata(file); f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; f->fmt.pix = data->dbg.format; return 0; } static int mxt_vidioc_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *fmt) { if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; switch (fmt->index) { case 0: fmt->pixelformat = V4L2_TCH_FMT_TU16; break; case 1: fmt->pixelformat = V4L2_TCH_FMT_DELTA_TD16; break; default: return -EINVAL; } return 0; } static int mxt_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 mxt_video_ioctl_ops = { .vidioc_querycap = mxt_vidioc_querycap, .vidioc_enum_fmt_vid_cap = mxt_vidioc_enum_fmt, .vidioc_s_fmt_vid_cap = mxt_vidioc_fmt, .vidioc_g_fmt_vid_cap = mxt_vidioc_fmt, .vidioc_try_fmt_vid_cap = mxt_vidioc_fmt, .vidioc_g_parm = mxt_vidioc_g_parm, .vidioc_enum_input = mxt_vidioc_enum_input, .vidioc_g_input = mxt_vidioc_g_input, .vidioc_s_input = mxt_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 mxt_video_device = { .name = "Atmel maxTouch", .fops = &mxt_video_fops, .ioctl_ops = &mxt_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 mxt_debug_init(struct mxt_data *data) { struct mxt_info *info = data->info; struct mxt_dbg *dbg = &data->dbg; struct mxt_object *object; int error; object = mxt_get_object(data, MXT_GEN_COMMAND_T6); if (!object) goto error; dbg->diag_cmd_address = object->start_address + MXT_COMMAND_DIAGNOSTIC; object = mxt_get_object(data, MXT_DEBUG_DIAGNOSTIC_T37); if (!object) goto error; if (mxt_obj_size(object) != sizeof(struct t37_debug)) { dev_warn(&data->client->dev, "Bad T37 size"); goto error; } dbg->t37_address = object->start_address; /* Calculate size of data and allocate buffer */ dbg->t37_nodes = data->xsize * data->ysize; if (info->family_id == MXT_FAMILY_1386) dbg->t37_pages = MXT1386_COLUMNS * MXT1386_PAGES_PER_COLUMN; else dbg->t37_pages = DIV_ROUND_UP(data->xsize * info->matrix_ysize * sizeof(u16), sizeof(dbg->t37_buf->data)); dbg->t37_buf = devm_kmalloc_array(&data->client->dev, dbg->t37_pages, sizeof(struct t37_debug), GFP_KERNEL); if (!dbg->t37_buf) goto error; /* init channel to zero */ mxt_set_input(data, 0); /* register video device */ snprintf(dbg->v4l2.name, sizeof(dbg->v4l2.name), "%s", "atmel_mxt_ts"); error = v4l2_device_register(&data->client->dev, &dbg->v4l2); if (error) goto error; /* initialize the queue */ mutex_init(&dbg->lock); dbg->queue = mxt_queue; dbg->queue.drv_priv = data; dbg->queue.lock = &dbg->lock; dbg->queue.dev = &data->client->dev; error = vb2_queue_init(&dbg->queue); if (error) goto error_unreg_v4l2; dbg->vdev = mxt_video_device; dbg->vdev.v4l2_dev = &dbg->v4l2; dbg->vdev.lock = &dbg->lock; dbg->vdev.vfl_dir = VFL_DIR_RX; dbg->vdev.queue = &dbg->queue; video_set_drvdata(&dbg->vdev, data); error = video_register_device(&dbg->vdev, VFL_TYPE_TOUCH, -1); if (error) goto error_unreg_v4l2; return; error_unreg_v4l2: v4l2_device_unregister(&dbg->v4l2); error: dev_warn(&data->client->dev, "Error initializing T37\n"); } #else static void mxt_debug_init(struct mxt_data *data) { } #endif static int mxt_configure_objects(struct mxt_data *data, const struct firmware *cfg) { struct device *dev = &data->client->dev; int error; error = mxt_init_t7_power_cfg(data); if (error) { dev_err(dev, "Failed to initialize power cfg\n"); return error; } if (cfg) { error = mxt_update_cfg(data, cfg); if (error) dev_warn(dev, "Error %d updating config\n", error); } if (data->multitouch) { error = mxt_initialize_input_device(data); if (error) return error; } else { dev_warn(dev, "No touch object detected\n"); } mxt_debug_init(data); return 0; } /* Firmware Version is returned as Major.Minor.Build */ static ssize_t mxt_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = dev_get_drvdata(dev); struct mxt_info *info = data->info; return scnprintf(buf, PAGE_SIZE, "%u.%u.%02X\n", info->version >> 4, info->version & 0xf, info->build); } /* Hardware Version is returned as FamilyID.VariantID */ static ssize_t mxt_hw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = dev_get_drvdata(dev); struct mxt_info *info = data->info; return scnprintf(buf, PAGE_SIZE, "%u.%u\n", info->family_id, info->variant_id); } static ssize_t mxt_show_instance(char *buf, int count, struct mxt_object *object, int instance, const u8 *val) { int i; if (mxt_obj_instances(object) > 1) count += scnprintf(buf + count, PAGE_SIZE - count, "Instance %u\n", instance); for (i = 0; i < mxt_obj_size(object); i++) count += scnprintf(buf + count, PAGE_SIZE - count, "\t[%2u]: %02x (%d)\n", i, val[i], val[i]); count += scnprintf(buf + count, PAGE_SIZE - count, "\n"); return count; } static ssize_t mxt_object_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = dev_get_drvdata(dev); struct mxt_object *object; int count = 0; int i, j; int error; u8 *obuf; /* Pre-allocate buffer large enough to hold max sized object. */ obuf = kmalloc(256, GFP_KERNEL); if (!obuf) return -ENOMEM; error = 0; for (i = 0; i < data->info->object_num; i++) { object = data->object_table + i; if (!mxt_object_readable(object->type)) continue; count += scnprintf(buf + count, PAGE_SIZE - count, "T%u:\n", object->type); for (j = 0; j < mxt_obj_instances(object); j++) { u16 size = mxt_obj_size(object); u16 addr = object->start_address + j * size; error = __mxt_read_reg(data->client, addr, size, obuf); if (error) goto done; count = mxt_show_instance(buf, count, object, j, obuf); } } done: kfree(obuf); return error ?: count; } static int mxt_check_firmware_format(struct device *dev, const struct firmware *fw) { unsigned int pos = 0; char c; while (pos < fw->size) { c = *(fw->data + pos); if (c < '0' || (c > '9' && c < 'A') || c > 'F') return 0; pos++; } /* * To convert file try: * xxd -r -p mXTXXX__APP_VX-X-XX.enc > maxtouch.fw */ dev_err(dev, "Aborting: firmware file must be in binary format\n"); return -EINVAL; } static int mxt_load_fw(struct device *dev, const char *fn) { struct mxt_data *data = dev_get_drvdata(dev); const struct firmware *fw = NULL; unsigned int frame_size; unsigned int pos = 0; unsigned int retry = 0; unsigned int frame = 0; int ret; ret = request_firmware(&fw, fn, dev); if (ret) { dev_err(dev, "Unable to open firmware %s\n", fn); return ret; } /* Check for incorrect enc file */ ret = mxt_check_firmware_format(dev, fw); if (ret) goto release_firmware; if (!data->in_bootloader) { /* Change to the bootloader mode */ data->in_bootloader = true; ret = mxt_t6_command(data, MXT_COMMAND_RESET, MXT_BOOT_VALUE, false); if (ret) goto release_firmware; msleep(MXT_RESET_TIME); /* Do not need to scan since we know family ID */ ret = mxt_lookup_bootloader_address(data, 0); if (ret) goto release_firmware; mxt_free_input_device(data); mxt_free_object_table(data); } else { enable_irq(data->irq); } reinit_completion(&data->bl_completion); ret = mxt_check_bootloader(data, MXT_WAITING_BOOTLOAD_CMD, false); if (ret) { /* Bootloader may still be unlocked from previous attempt */ ret = mxt_check_bootloader(data, MXT_WAITING_FRAME_DATA, false); if (ret) goto disable_irq; } else { dev_info(dev, "Unlocking bootloader\n"); /* Unlock bootloader */ ret = mxt_send_bootloader_cmd(data, true); if (ret) goto disable_irq; } while (pos < fw->size) { ret = mxt_check_bootloader(data, MXT_WAITING_FRAME_DATA, true); if (ret) goto disable_irq; frame_size = ((*(fw->data + pos) << 8) | *(fw->data + pos + 1)); /* Take account of CRC bytes */ frame_size += 2; /* Write one frame to device */ ret = mxt_bootloader_write(data, fw->data + pos, frame_size); if (ret) goto disable_irq; ret = mxt_check_bootloader(data, MXT_FRAME_CRC_PASS, true); if (ret) { retry++; /* Back off by 20ms per retry */ msleep(retry * 20); if (retry > 20) { dev_err(dev, "Retry count exceeded\n"); goto disable_irq; } } else { retry = 0; pos += frame_size; frame++; } if (frame % 50 == 0) dev_dbg(dev, "Sent %d frames, %d/%zd bytes\n", frame, pos, fw->size); } /* Wait for flash. */ ret = mxt_wait_for_completion(data, &data->bl_completion, MXT_FW_RESET_TIME); if (ret) goto disable_irq; dev_dbg(dev, "Sent %d frames, %d bytes\n", frame, pos); /* * Wait for device to reset. Some bootloader versions do not assert * the CHG line after bootloading has finished, so ignore potential * errors. */ mxt_wait_for_completion(data, &data->bl_completion, MXT_FW_RESET_TIME); data->in_bootloader = false; disable_irq: disable_irq(data->irq); release_firmware: release_firmware(fw); return ret; } static ssize_t mxt_update_fw_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mxt_data *data = dev_get_drvdata(dev); int error; error = mxt_load_fw(dev, MXT_FW_NAME); if (error) { dev_err(dev, "The firmware update failed(%d)\n", error); count = error; } else { dev_info(dev, "The firmware update succeeded\n"); error = mxt_initialize(data); if (error) return error; } return count; } static DEVICE_ATTR(fw_version, S_IRUGO, mxt_fw_version_show, NULL); static DEVICE_ATTR(hw_version, S_IRUGO, mxt_hw_version_show, NULL); static DEVICE_ATTR(object, S_IRUGO, mxt_object_show, NULL); static DEVICE_ATTR(update_fw, S_IWUSR, NULL, mxt_update_fw_store); static struct attribute *mxt_attrs[] = { &dev_attr_fw_version.attr, &dev_attr_hw_version.attr, &dev_attr_object.attr, &dev_attr_update_fw.attr, NULL }; static const struct attribute_group mxt_attr_group = { .attrs = mxt_attrs, }; static void mxt_start(struct mxt_data *data) { mxt_wakeup_toggle(data->client, true, false); switch (data->suspend_mode) { case MXT_SUSPEND_T9_CTRL: mxt_soft_reset(data); /* Touch enable */ /* 0x83 = SCANEN | RPTEN | ENABLE */ mxt_write_object(data, MXT_TOUCH_MULTI_T9, MXT_T9_CTRL, 0x83); break; case MXT_SUSPEND_DEEP_SLEEP: default: mxt_set_t7_power_cfg(data, MXT_POWER_CFG_RUN); /* Recalibrate since chip has been in deep sleep */ mxt_t6_command(data, MXT_COMMAND_CALIBRATE, 1, false); break; } } static void mxt_stop(struct mxt_data *data) { switch (data->suspend_mode) { case MXT_SUSPEND_T9_CTRL: /* Touch disable */ mxt_write_object(data, MXT_TOUCH_MULTI_T9, MXT_T9_CTRL, 0); break; case MXT_SUSPEND_DEEP_SLEEP: default: mxt_set_t7_power_cfg(data, MXT_POWER_CFG_DEEPSLEEP); break; } mxt_wakeup_toggle(data->client, false, false); } static int mxt_input_open(struct input_dev *dev) { struct mxt_data *data = input_get_drvdata(dev); mxt_start(data); return 0; } static void mxt_input_close(struct input_dev *dev) { struct mxt_data *data = input_get_drvdata(dev); mxt_stop(data); } static int mxt_parse_device_properties(struct mxt_data *data) { static const char keymap_property[] = "linux,gpio-keymap"; static const char buttons_property[] = "linux,keycodes"; struct device *dev = &data->client->dev; u32 *keymap; u32 *buttonmap; int n_keys; int error; if (device_property_present(dev, keymap_property)) { n_keys = device_property_count_u32(dev, keymap_property); if (n_keys <= 0) { error = n_keys < 0 ? n_keys : -EINVAL; dev_err(dev, "invalid/malformed '%s' property: %d\n", keymap_property, error); return error; } keymap = devm_kmalloc_array(dev, n_keys, sizeof(*keymap), GFP_KERNEL); if (!keymap) return -ENOMEM; error = device_property_read_u32_array(dev, keymap_property, keymap, n_keys); if (error) { dev_err(dev, "failed to parse '%s' property: %d\n", keymap_property, error); return error; } data->t19_keymap = keymap; data->t19_num_keys = n_keys; } if (device_property_present(dev, buttons_property)) { n_keys = device_property_count_u32(dev, buttons_property); if (n_keys <= 0) { error = n_keys < 0 ? n_keys : -EINVAL; dev_err(dev, "invalid/malformed '%s' property: %d\n", buttons_property, error); return error; } buttonmap = devm_kmalloc_array(dev, n_keys, sizeof(*buttonmap), GFP_KERNEL); if (!buttonmap) return -ENOMEM; error = device_property_read_u32_array(dev, buttons_property, buttonmap, n_keys); if (error) { dev_err(dev, "failed to parse '%s' property: %d\n", buttons_property, error); return error; } data->t15_keymap = buttonmap; data->t15_num_keys = n_keys; } return 0; } static const struct dmi_system_id chromebook_T9_suspend_dmi[] = { { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "GOOGLE"), DMI_MATCH(DMI_PRODUCT_NAME, "Link"), }, }, { .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "Peppy"), }, }, { } }; static int mxt_probe(struct i2c_client *client) { struct mxt_data *data; int error; /* * Ignore devices that do not have device properties attached to * them, as we need help determining whether we are dealing with * touch screen or touchpad. * * So far on x86 the only users of Atmel touch controllers are * Chromebooks, and chromeos_laptop driver will ensure that * necessary properties are provided (if firmware does not do that). */ if (!device_property_present(&client->dev, "compatible")) return -ENXIO; /* * Ignore ACPI devices representing bootloader mode. * * This is a bit of a hack: Google Chromebook BIOS creates ACPI * devices for both application and bootloader modes, but we are * interested in application mode only (if device is in bootloader * mode we'll end up switching into application anyway). So far * application mode addresses were all above 0x40, so we'll use it * as a threshold. */ if (ACPI_COMPANION(&client->dev) && client->addr < 0x40) return -ENXIO; data = devm_kzalloc(&client->dev, sizeof(struct mxt_data), GFP_KERNEL); if (!data) return -ENOMEM; snprintf(data->phys, sizeof(data->phys), "i2c-%u-%04x/input0", client->adapter->nr, client->addr); data->client = client; data->irq = client->irq; i2c_set_clientdata(client, data); init_completion(&data->bl_completion); init_completion(&data->reset_completion); init_completion(&data->crc_completion); data->suspend_mode = dmi_check_system(chromebook_T9_suspend_dmi) ? MXT_SUSPEND_T9_CTRL : MXT_SUSPEND_DEEP_SLEEP; error = mxt_parse_device_properties(data); if (error) return error; /* * VDDA is the analog voltage supply 2.57..3.47 V * VDD is the digital voltage supply 1.71..3.47 V */ data->regulators[0].supply = "vdda"; data->regulators[1].supply = "vdd"; error = devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(data->regulators), data->regulators); if (error) { if (error != -EPROBE_DEFER) dev_err(&client->dev, "Failed to get regulators %d\n", error); return error; } /* Request the RESET line as asserted so we go into reset */ data->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(data->reset_gpio)) { error = PTR_ERR(data->reset_gpio); dev_err(&client->dev, "Failed to get reset gpio: %d\n", error); return error; } /* Request the WAKE line as asserted so we go out of sleep */ data->wake_gpio = devm_gpiod_get_optional(&client->dev, "wake", GPIOD_OUT_HIGH); if (IS_ERR(data->wake_gpio)) { error = PTR_ERR(data->wake_gpio); dev_err(&client->dev, "Failed to get wake gpio: %d\n", error); return error; } error = devm_request_threaded_irq(&client->dev, client->irq, NULL, mxt_interrupt, IRQF_ONESHOT | IRQF_NO_AUTOEN, client->name, data); if (error) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = regulator_bulk_enable(ARRAY_SIZE(data->regulators), data->regulators); if (error) { dev_err(&client->dev, "failed to enable regulators: %d\n", error); return error; } /* * The device takes 40ms to come up after power-on according * to the mXT224 datasheet, page 13. */ msleep(MXT_BACKUP_TIME); if (data->reset_gpio) { /* Wait a while and then de-assert the RESET GPIO line */ msleep(MXT_RESET_GPIO_TIME); gpiod_set_value(data->reset_gpio, 0); msleep(MXT_RESET_INVALID_CHG); } /* * Controllers like mXT1386 have a dedicated WAKE line that could be * connected to a GPIO or to I2C SCL pin, or permanently asserted low. * * This WAKE line is used for waking controller from a deep-sleep and * it needs to be asserted low for 25 milliseconds before I2C transfers * could be accepted by controller if it was in a deep-sleep mode. * Controller will go into sleep automatically after 2 seconds of * inactivity if WAKE line is deasserted and deep sleep is activated. * * If WAKE line is connected to I2C SCL pin, then the first I2C transfer * will get an instant NAK and transfer needs to be retried after 25ms. * * If WAKE line is connected to a GPIO line, the line must be asserted * 25ms before the host attempts to communicate with the controller. */ device_property_read_u32(&client->dev, "atmel,wakeup-method", &data->wakeup_method); error = mxt_initialize(data); if (error) goto err_disable_regulators; error = sysfs_create_group(&client->dev.kobj, &mxt_attr_group); if (error) { dev_err(&client->dev, "Failure %d creating sysfs group\n", error); goto err_free_object; } return 0; err_free_object: mxt_free_input_device(data); mxt_free_object_table(data); err_disable_regulators: regulator_bulk_disable(ARRAY_SIZE(data->regulators), data->regulators); return error; } static void mxt_remove(struct i2c_client *client) { struct mxt_data *data = i2c_get_clientdata(client); disable_irq(data->irq); sysfs_remove_group(&client->dev.kobj, &mxt_attr_group); mxt_free_input_device(data); mxt_free_object_table(data); regulator_bulk_disable(ARRAY_SIZE(data->regulators), data->regulators); } static int mxt_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mxt_data *data = i2c_get_clientdata(client); struct input_dev *input_dev = data->input_dev; if (!input_dev) return 0; mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) mxt_stop(data); mutex_unlock(&input_dev->mutex); disable_irq(data->irq); return 0; } static int mxt_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mxt_data *data = i2c_get_clientdata(client); struct input_dev *input_dev = data->input_dev; if (!input_dev) return 0; enable_irq(data->irq); mutex_lock(&input_dev->mutex); if (input_device_enabled(input_dev)) mxt_start(data); mutex_unlock(&input_dev->mutex); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(mxt_pm_ops, mxt_suspend, mxt_resume); static const struct of_device_id mxt_of_match[] = { { .compatible = "atmel,maxtouch", }, /* Compatibles listed below are deprecated */ { .compatible = "atmel,qt602240_ts", }, { .compatible = "atmel,atmel_mxt_ts", }, { .compatible = "atmel,atmel_mxt_tp", }, { .compatible = "atmel,mXT224", }, {}, }; MODULE_DEVICE_TABLE(of, mxt_of_match); #ifdef CONFIG_ACPI static const struct acpi_device_id mxt_acpi_id[] = { { "ATML0000", 0 }, /* Touchpad */ { "ATML0001", 0 }, /* Touchscreen */ { } }; MODULE_DEVICE_TABLE(acpi, mxt_acpi_id); #endif static const struct i2c_device_id mxt_id[] = { { "qt602240_ts", 0 }, { "atmel_mxt_ts", 0 }, { "atmel_mxt_tp", 0 }, { "maxtouch", 0 }, { "mXT224", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mxt_id); static struct i2c_driver mxt_driver = { .driver = { .name = "atmel_mxt_ts", .of_match_table = mxt_of_match, .acpi_match_table = ACPI_PTR(mxt_acpi_id), .pm = pm_sleep_ptr(&mxt_pm_ops), }, .probe = mxt_probe, .remove = mxt_remove, .id_table = mxt_id, }; module_i2c_driver(mxt_driver); /* Module information */ MODULE_AUTHOR("Joonyoung Shim <[email protected]>"); MODULE_DESCRIPTION("Atmel maXTouch Touchscreen driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/atmel_mxt_ts.c
// SPDX-License-Identifier: GPL-2.0+ /* * Touch Screen driver for Renesas MIGO-R Platform * * Copyright (c) 2008 Magnus Damm * Copyright (c) 2007 Ujjwal Pande <[email protected]>, * Kenati Technologies Pvt Ltd. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/pm.h> #include <linux/slab.h> #include <asm/io.h> #include <linux/i2c.h> #include <linux/timer.h> #define EVENT_PENDOWN 1 #define EVENT_REPEAT 2 #define EVENT_PENUP 3 struct migor_ts_priv { struct i2c_client *client; struct input_dev *input; int irq; }; static const u_int8_t migor_ts_ena_seq[17] = { 0x33, 0x22, 0x11, 0x01, 0x06, 0x07, }; static const u_int8_t migor_ts_dis_seq[17] = { }; static irqreturn_t migor_ts_isr(int irq, void *dev_id) { struct migor_ts_priv *priv = dev_id; unsigned short xpos, ypos; unsigned char event; u_int8_t buf[16]; /* * The touch screen controller chip is hooked up to the CPU * using I2C and a single interrupt line. The interrupt line * is pulled low whenever someone taps the screen. To deassert * the interrupt line we need to acknowledge the interrupt by * communicating with the controller over the slow i2c bus. * * Since I2C bus controller may sleep we are using threaded * IRQ here. */ memset(buf, 0, sizeof(buf)); /* Set Index 0 */ buf[0] = 0; if (i2c_master_send(priv->client, buf, 1) != 1) { dev_err(&priv->client->dev, "Unable to write i2c index\n"); goto out; } /* Now do Page Read */ if (i2c_master_recv(priv->client, buf, sizeof(buf)) != sizeof(buf)) { dev_err(&priv->client->dev, "Unable to read i2c page\n"); goto out; } ypos = ((buf[9] & 0x03) << 8 | buf[8]); xpos = ((buf[11] & 0x03) << 8 | buf[10]); event = buf[12]; switch (event) { case EVENT_PENDOWN: case EVENT_REPEAT: input_report_key(priv->input, BTN_TOUCH, 1); input_report_abs(priv->input, ABS_X, ypos); /*X-Y swap*/ input_report_abs(priv->input, ABS_Y, xpos); input_sync(priv->input); break; case EVENT_PENUP: input_report_key(priv->input, BTN_TOUCH, 0); input_sync(priv->input); break; } out: return IRQ_HANDLED; } static int migor_ts_open(struct input_dev *dev) { struct migor_ts_priv *priv = input_get_drvdata(dev); struct i2c_client *client = priv->client; int count; /* enable controller */ count = i2c_master_send(client, migor_ts_ena_seq, sizeof(migor_ts_ena_seq)); if (count != sizeof(migor_ts_ena_seq)) { dev_err(&client->dev, "Unable to enable touchscreen.\n"); return -ENXIO; } return 0; } static void migor_ts_close(struct input_dev *dev) { struct migor_ts_priv *priv = input_get_drvdata(dev); struct i2c_client *client = priv->client; disable_irq(priv->irq); /* disable controller */ i2c_master_send(client, migor_ts_dis_seq, sizeof(migor_ts_dis_seq)); enable_irq(priv->irq); } static int migor_ts_probe(struct i2c_client *client) { struct migor_ts_priv *priv; struct input_dev *input; int error; priv = kzalloc(sizeof(*priv), GFP_KERNEL); input = input_allocate_device(); if (!priv || !input) { dev_err(&client->dev, "failed to allocate memory\n"); error = -ENOMEM; goto err_free_mem; } priv->client = client; priv->input = input; priv->irq = client->irq; input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); __set_bit(BTN_TOUCH, input->keybit); input_set_abs_params(input, ABS_X, 95, 955, 0, 0); input_set_abs_params(input, ABS_Y, 85, 935, 0, 0); input->name = client->name; input->id.bustype = BUS_I2C; input->dev.parent = &client->dev; input->open = migor_ts_open; input->close = migor_ts_close; input_set_drvdata(input, priv); error = request_threaded_irq(priv->irq, NULL, migor_ts_isr, IRQF_TRIGGER_LOW | IRQF_ONESHOT, client->name, priv); if (error) { dev_err(&client->dev, "Unable to request touchscreen IRQ.\n"); goto err_free_mem; } error = input_register_device(input); if (error) goto err_free_irq; i2c_set_clientdata(client, priv); device_init_wakeup(&client->dev, 1); return 0; err_free_irq: free_irq(priv->irq, priv); err_free_mem: input_free_device(input); kfree(priv); return error; } static void migor_ts_remove(struct i2c_client *client) { struct migor_ts_priv *priv = i2c_get_clientdata(client); free_irq(priv->irq, priv); input_unregister_device(priv->input); kfree(priv); dev_set_drvdata(&client->dev, NULL); } static int migor_ts_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct migor_ts_priv *priv = i2c_get_clientdata(client); if (device_may_wakeup(&client->dev)) enable_irq_wake(priv->irq); return 0; } static int migor_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct migor_ts_priv *priv = i2c_get_clientdata(client); if (device_may_wakeup(&client->dev)) disable_irq_wake(priv->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(migor_ts_pm, migor_ts_suspend, migor_ts_resume); static const struct i2c_device_id migor_ts_id[] = { { "migor_ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, migor_ts_id); static struct i2c_driver migor_ts_driver = { .driver = { .name = "migor_ts", .pm = pm_sleep_ptr(&migor_ts_pm), }, .probe = migor_ts_probe, .remove = migor_ts_remove, .id_table = migor_ts_id, }; module_i2c_driver(migor_ts_driver); MODULE_DESCRIPTION("MigoR Touchscreen driver"); MODULE_AUTHOR("Magnus Damm <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/migor_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * cyttsp_i2c_common.c * Cypress TrueTouch(TM) Standard Product (TTSP) I2C touchscreen driver. * For use with Cypress Txx3xx and Txx4xx parts. * Supported parts include: * CY8CTST341 * CY8CTMA340 * TMA4XX * TMA1036 * * 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 <linux/device.h> #include <linux/export.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/types.h> #include "cyttsp4_core.h" int cyttsp_i2c_read_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, void *values) { struct i2c_client *client = to_i2c_client(dev); u8 client_addr = client->addr | ((addr >> 8) & 0x1); u8 addr_lo = addr & 0xFF; struct i2c_msg msgs[] = { { .addr = client_addr, .flags = 0, .len = 1, .buf = &addr_lo, }, { .addr = client_addr, .flags = I2C_M_RD, .len = length, .buf = values, }, }; int retval; retval = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (retval < 0) return retval; return retval != ARRAY_SIZE(msgs) ? -EIO : 0; } EXPORT_SYMBOL_GPL(cyttsp_i2c_read_block_data); int cyttsp_i2c_write_block_data(struct device *dev, u8 *xfer_buf, u16 addr, u8 length, const void *values) { struct i2c_client *client = to_i2c_client(dev); u8 client_addr = client->addr | ((addr >> 8) & 0x1); u8 addr_lo = addr & 0xFF; struct i2c_msg msgs[] = { { .addr = client_addr, .flags = 0, .len = length + 1, .buf = xfer_buf, }, }; int retval; xfer_buf[0] = addr_lo; memcpy(&xfer_buf[1], values, length); retval = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (retval < 0) return retval; return retval != ARRAY_SIZE(msgs) ? -EIO : 0; } EXPORT_SYMBOL_GPL(cyttsp_i2c_write_block_data); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Cypress");
linux-master
drivers/input/touchscreen/cyttsp_i2c_common.c
// SPDX-License-Identifier: GPL-2.0-only /* * Penmount serial touchscreen driver * * Copyright (c) 2006 Rick Koch <[email protected]> * Copyright (c) 2011 John Sung <[email protected]> * * Based on ELO driver (drivers/input/touchscreen/elo.c) * Copyright (c) 2004 Vojtech Pavlik */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/serio.h> #define DRIVER_DESC "PenMount serial touchscreen driver" MODULE_AUTHOR("Rick Koch <[email protected]>"); MODULE_AUTHOR("John Sung <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); /* * Definitions & global arrays. */ #define PM_MAX_LENGTH 6 #define PM_MAX_MTSLOT 16 #define PM_3000_MTSLOT 2 #define PM_6250_MTSLOT 12 /* * Multi-touch slot */ struct mt_slot { unsigned short x, y; bool active; /* is the touch valid? */ }; /* * Per-touchscreen data. */ struct pm { struct input_dev *dev; struct serio *serio; int idx; unsigned char data[PM_MAX_LENGTH]; char phys[32]; unsigned char packetsize; unsigned char maxcontacts; struct mt_slot slots[PM_MAX_MTSLOT]; void (*parse_packet)(struct pm *); }; /* * pm_mtevent() sends mt events and also emulates pointer movement */ static void pm_mtevent(struct pm *pm, struct input_dev *input) { int i; for (i = 0; i < pm->maxcontacts; ++i) { input_mt_slot(input, i); input_mt_report_slot_state(input, MT_TOOL_FINGER, pm->slots[i].active); if (pm->slots[i].active) { input_event(input, EV_ABS, ABS_MT_POSITION_X, pm->slots[i].x); input_event(input, EV_ABS, ABS_MT_POSITION_Y, pm->slots[i].y); } } input_mt_report_pointer_emulation(input, true); input_sync(input); } /* * pm_checkpacket() checks if data packet is valid */ static bool pm_checkpacket(unsigned char *packet) { int total = 0; int i; for (i = 0; i < 5; i++) total += packet[i]; return packet[5] == (unsigned char)~(total & 0xff); } static void pm_parse_9000(struct pm *pm) { struct input_dev *dev = pm->dev; if ((pm->data[0] & 0x80) && pm->packetsize == ++pm->idx) { input_report_abs(dev, ABS_X, pm->data[1] * 128 + pm->data[2]); input_report_abs(dev, ABS_Y, pm->data[3] * 128 + pm->data[4]); input_report_key(dev, BTN_TOUCH, !!(pm->data[0] & 0x40)); input_sync(dev); pm->idx = 0; } } static void pm_parse_6000(struct pm *pm) { struct input_dev *dev = pm->dev; if ((pm->data[0] & 0xbf) == 0x30 && pm->packetsize == ++pm->idx) { if (pm_checkpacket(pm->data)) { input_report_abs(dev, ABS_X, pm->data[2] * 256 + pm->data[1]); input_report_abs(dev, ABS_Y, pm->data[4] * 256 + pm->data[3]); input_report_key(dev, BTN_TOUCH, pm->data[0] & 0x40); input_sync(dev); } pm->idx = 0; } } static void pm_parse_3000(struct pm *pm) { struct input_dev *dev = pm->dev; if ((pm->data[0] & 0xce) == 0x40 && pm->packetsize == ++pm->idx) { if (pm_checkpacket(pm->data)) { int slotnum = pm->data[0] & 0x0f; pm->slots[slotnum].active = pm->data[0] & 0x30; pm->slots[slotnum].x = pm->data[2] * 256 + pm->data[1]; pm->slots[slotnum].y = pm->data[4] * 256 + pm->data[3]; pm_mtevent(pm, dev); } pm->idx = 0; } } static void pm_parse_6250(struct pm *pm) { struct input_dev *dev = pm->dev; if ((pm->data[0] & 0xb0) == 0x30 && pm->packetsize == ++pm->idx) { if (pm_checkpacket(pm->data)) { int slotnum = pm->data[0] & 0x0f; pm->slots[slotnum].active = pm->data[0] & 0x40; pm->slots[slotnum].x = pm->data[2] * 256 + pm->data[1]; pm->slots[slotnum].y = pm->data[4] * 256 + pm->data[3]; pm_mtevent(pm, dev); } pm->idx = 0; } } static irqreturn_t pm_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct pm *pm = serio_get_drvdata(serio); pm->data[pm->idx] = data; pm->parse_packet(pm); return IRQ_HANDLED; } /* * pm_disconnect() is the opposite of pm_connect() */ static void pm_disconnect(struct serio *serio) { struct pm *pm = serio_get_drvdata(serio); serio_close(serio); input_unregister_device(pm->dev); kfree(pm); serio_set_drvdata(serio, NULL); } /* * pm_connect() is the routine that is called when someone adds a * new serio device that supports PenMount protocol and registers it as * an input device. */ static int pm_connect(struct serio *serio, struct serio_driver *drv) { struct pm *pm; struct input_dev *input_dev; int max_x, max_y; int err; pm = kzalloc(sizeof(struct pm), GFP_KERNEL); input_dev = input_allocate_device(); if (!pm || !input_dev) { err = -ENOMEM; goto fail1; } pm->serio = serio; pm->dev = input_dev; snprintf(pm->phys, sizeof(pm->phys), "%s/input0", serio->phys); pm->maxcontacts = 1; input_dev->name = "PenMount Serial TouchScreen"; input_dev->phys = pm->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_PENMOUNT; 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); switch (serio->id.id) { default: case 0: pm->packetsize = 5; pm->parse_packet = pm_parse_9000; input_dev->id.product = 0x9000; max_x = max_y = 0x3ff; break; case 1: pm->packetsize = 6; pm->parse_packet = pm_parse_6000; input_dev->id.product = 0x6000; max_x = max_y = 0x3ff; break; case 2: pm->packetsize = 6; pm->parse_packet = pm_parse_3000; input_dev->id.product = 0x3000; max_x = max_y = 0x7ff; pm->maxcontacts = PM_3000_MTSLOT; break; case 3: pm->packetsize = 6; pm->parse_packet = pm_parse_6250; input_dev->id.product = 0x6250; max_x = max_y = 0x3ff; pm->maxcontacts = PM_6250_MTSLOT; break; } input_set_abs_params(pm->dev, ABS_X, 0, max_x, 0, 0); input_set_abs_params(pm->dev, ABS_Y, 0, max_y, 0, 0); if (pm->maxcontacts > 1) { input_mt_init_slots(pm->dev, pm->maxcontacts, 0); input_set_abs_params(pm->dev, ABS_MT_POSITION_X, 0, max_x, 0, 0); input_set_abs_params(pm->dev, ABS_MT_POSITION_Y, 0, max_y, 0, 0); } serio_set_drvdata(serio, pm); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(pm->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(pm); return err; } /* * The serio driver structure. */ static const struct serio_device_id pm_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_PENMOUNT, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, pm_serio_ids); static struct serio_driver pm_drv = { .driver = { .name = "serio-penmount", }, .description = DRIVER_DESC, .id_table = pm_serio_ids, .interrupt = pm_interrupt, .connect = pm_connect, .disconnect = pm_disconnect, }; module_serio_driver(pm_drv);
linux-master
drivers/input/touchscreen/penmount.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Cypress CY8CTMA140 (TMA140) touchscreen * (C) 2020 Linus Walleij <[email protected]> * (C) 2007 Cypress * (C) 2007 Google, Inc. * * Inspired by the tma140_skomer.c driver in the Samsung GT-S7710 code * drop. The GT-S7710 is codenamed "Skomer", the code also indicates * that the same touchscreen was used in a product called "Lucas". * * The code drop for GT-S7710 also contains a firmware downloader and * 15 (!) versions of the firmware drop from Cypress. But here we assume * the firmware got downloaded to the touchscreen flash successfully and * just use it to read the fingers. The shipped vendor driver does the * same. */ #include <asm/unaligned.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/input.h> #include <linux/input/touchscreen.h> #include <linux/input/mt.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/i2c.h> #include <linux/regulator/consumer.h> #include <linux/delay.h> #define CY8CTMA140_NAME "cy8ctma140" #define CY8CTMA140_MAX_FINGERS 4 #define CY8CTMA140_GET_FINGERS 0x00 #define CY8CTMA140_GET_FW_INFO 0x19 /* This message also fits some bytes for touchkeys, if used */ #define CY8CTMA140_PACKET_SIZE 31 #define CY8CTMA140_INVALID_BUFFER_BIT 5 struct cy8ctma140 { struct input_dev *input; struct touchscreen_properties props; struct device *dev; struct i2c_client *client; struct regulator_bulk_data regulators[2]; u8 prev_fingers; u8 prev_f1id; u8 prev_f2id; }; static void cy8ctma140_report(struct cy8ctma140 *ts, u8 *data, int n_fingers) { static const u8 contact_offsets[] = { 0x03, 0x09, 0x10, 0x16 }; u8 *buf; u16 x, y; u8 w; u8 id; int slot; int i; for (i = 0; i < n_fingers; i++) { buf = &data[contact_offsets[i]]; /* * Odd contacts have contact ID in the lower nibble of * the preceding byte, whereas even contacts have it in * the upper nibble of the following byte. */ id = i % 2 ? buf[-1] & 0x0f : buf[5] >> 4; slot = input_mt_get_slot_by_key(ts->input, id); if (slot < 0) continue; x = get_unaligned_be16(buf); y = get_unaligned_be16(buf + 2); w = buf[4]; dev_dbg(ts->dev, "finger %d: ID %02x (%d, %d) w: %d\n", slot, id, x, y, w); input_mt_slot(ts->input, slot); input_mt_report_slot_state(ts->input, MT_TOOL_FINGER, true); touchscreen_report_pos(ts->input, &ts->props, x, y, true); input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, w); } input_mt_sync_frame(ts->input); input_sync(ts->input); } static irqreturn_t cy8ctma140_irq_thread(int irq, void *d) { struct cy8ctma140 *ts = d; u8 cmdbuf[] = { CY8CTMA140_GET_FINGERS }; u8 buf[CY8CTMA140_PACKET_SIZE]; struct i2c_msg msg[] = { { .addr = ts->client->addr, .flags = 0, .len = sizeof(cmdbuf), .buf = cmdbuf, }, { .addr = ts->client->addr, .flags = I2C_M_RD, .len = sizeof(buf), .buf = buf, }, }; u8 n_fingers; int ret; ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) { if (ret < 0) dev_err(ts->dev, "error reading message: %d\n", ret); else dev_err(ts->dev, "wrong number of messages\n"); goto out; } if (buf[1] & BIT(CY8CTMA140_INVALID_BUFFER_BIT)) { dev_dbg(ts->dev, "invalid event\n"); goto out; } n_fingers = buf[2] & 0x0f; if (n_fingers > CY8CTMA140_MAX_FINGERS) { dev_err(ts->dev, "unexpected number of fingers: %d\n", n_fingers); goto out; } cy8ctma140_report(ts, buf, n_fingers); out: return IRQ_HANDLED; } static int cy8ctma140_init(struct cy8ctma140 *ts) { u8 addr[1]; u8 buf[5]; int ret; addr[0] = CY8CTMA140_GET_FW_INFO; ret = i2c_master_send(ts->client, addr, 1); if (ret < 0) { dev_err(ts->dev, "error sending FW info message\n"); return ret; } ret = i2c_master_recv(ts->client, buf, 5); if (ret < 0) { dev_err(ts->dev, "error receiving FW info message\n"); return ret; } if (ret != 5) { dev_err(ts->dev, "got only %d bytes\n", ret); return -EIO; } dev_dbg(ts->dev, "vendor %c%c, HW ID %.2d, FW ver %.4d\n", buf[0], buf[1], buf[3], buf[4]); return 0; } static int cy8ctma140_power_up(struct cy8ctma140 *ts) { int error; error = regulator_bulk_enable(ARRAY_SIZE(ts->regulators), ts->regulators); if (error) { dev_err(ts->dev, "failed to enable regulators\n"); return error; } msleep(250); return 0; } static void cy8ctma140_power_down(struct cy8ctma140 *ts) { regulator_bulk_disable(ARRAY_SIZE(ts->regulators), ts->regulators); } /* Called from the registered devm action */ static void cy8ctma140_power_off_action(void *d) { struct cy8ctma140 *ts = d; cy8ctma140_power_down(ts); } static int cy8ctma140_probe(struct i2c_client *client) { struct cy8ctma140 *ts; struct input_dev *input; struct device *dev = &client->dev; int error; ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; input = devm_input_allocate_device(dev); if (!input) return -ENOMEM; ts->dev = dev; ts->client = client; ts->input = input; input_set_capability(input, EV_ABS, ABS_MT_POSITION_X); input_set_capability(input, EV_ABS, ABS_MT_POSITION_Y); /* One byte for width 0..255 so this is the limit */ input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); /* * This sets up event max/min capabilities and fuzz. * Some DT properties are compulsory so we do not need * to provide defaults for X/Y max or pressure max. * * We just initialize a very simple MT touchscreen here, * some devices use the capability of this touchscreen to * provide touchkeys, and in that case this needs to be * extended to handle touchkey input. * * The firmware takes care of finger tracking and dropping * invalid ranges. */ touchscreen_parse_properties(input, true, &ts->props); input_abs_set_fuzz(input, ABS_MT_POSITION_X, 0); input_abs_set_fuzz(input, ABS_MT_POSITION_Y, 0); error = input_mt_init_slots(input, CY8CTMA140_MAX_FINGERS, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (error) return error; input->name = CY8CTMA140_NAME; input->id.bustype = BUS_I2C; input_set_drvdata(input, ts); /* * VCPIN is the analog voltage supply * VDD is the digital voltage supply * since the voltage range of VDD overlaps that of VCPIN, * many designs to just supply both with a single voltage * source of ~3.3 V. */ ts->regulators[0].supply = "vcpin"; ts->regulators[1].supply = "vdd"; error = devm_regulator_bulk_get(dev, ARRAY_SIZE(ts->regulators), ts->regulators); if (error) return dev_err_probe(dev, error, "Failed to get regulators\n"); error = cy8ctma140_power_up(ts); if (error) return error; error = devm_add_action_or_reset(dev, cy8ctma140_power_off_action, ts); if (error) { dev_err(dev, "failed to install power off handler\n"); return error; } error = devm_request_threaded_irq(dev, client->irq, NULL, cy8ctma140_irq_thread, IRQF_ONESHOT, CY8CTMA140_NAME, ts); if (error) { dev_err(dev, "irq %d busy? error %d\n", client->irq, error); return error; } error = cy8ctma140_init(ts); if (error) return error; error = input_register_device(input); if (error) return error; i2c_set_clientdata(client, ts); return 0; } static int cy8ctma140_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct cy8ctma140 *ts = i2c_get_clientdata(client); if (!device_may_wakeup(&client->dev)) cy8ctma140_power_down(ts); return 0; } static int cy8ctma140_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct cy8ctma140 *ts = i2c_get_clientdata(client); int error; if (!device_may_wakeup(&client->dev)) { error = cy8ctma140_power_up(ts); if (error) return error; } return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(cy8ctma140_pm, cy8ctma140_suspend, cy8ctma140_resume); static const struct i2c_device_id cy8ctma140_idtable[] = { { CY8CTMA140_NAME, 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, cy8ctma140_idtable); static const struct of_device_id cy8ctma140_of_match[] = { { .compatible = "cypress,cy8ctma140", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, cy8ctma140_of_match); static struct i2c_driver cy8ctma140_driver = { .driver = { .name = CY8CTMA140_NAME, .pm = pm_sleep_ptr(&cy8ctma140_pm), .of_match_table = cy8ctma140_of_match, }, .id_table = cy8ctma140_idtable, .probe = cy8ctma140_probe, }; module_i2c_driver(cy8ctma140_driver); MODULE_AUTHOR("Linus Walleij <[email protected]>"); MODULE_DESCRIPTION("CY8CTMA140 TouchScreen Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/cy8ctma140.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2012-2017 Hideep, Inc. */ #include <linux/module.h> #include <linux/of.h> #include <linux/firmware.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/acpi.h> #include <linux/interrupt.h> #include <linux/regmap.h> #include <linux/sysfs.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/regulator/consumer.h> #include <asm/unaligned.h> #define HIDEEP_TS_NAME "HiDeep Touchscreen" #define HIDEEP_I2C_NAME "hideep_ts" #define HIDEEP_MT_MAX 10 #define HIDEEP_KEY_MAX 3 /* count(2) + touch data(100) + key data(6) */ #define HIDEEP_MAX_EVENT 108UL #define HIDEEP_TOUCH_EVENT_INDEX 2 #define HIDEEP_KEY_EVENT_INDEX 102 /* Touch & key event */ #define HIDEEP_EVENT_ADDR 0x240 /* command list */ #define HIDEEP_WORK_MODE 0x081e #define HIDEEP_RESET_CMD 0x9800 /* event bit */ #define HIDEEP_MT_RELEASED BIT(4) #define HIDEEP_KEY_PRESSED BIT(7) #define HIDEEP_KEY_FIRST_PRESSED BIT(8) #define HIDEEP_KEY_PRESSED_MASK (HIDEEP_KEY_PRESSED | \ HIDEEP_KEY_FIRST_PRESSED) #define HIDEEP_KEY_IDX_MASK 0x0f /* For NVM */ #define HIDEEP_YRAM_BASE 0x40000000 #define HIDEEP_PERIPHERAL_BASE 0x50000000 #define HIDEEP_ESI_BASE (HIDEEP_PERIPHERAL_BASE + 0x00000000) #define HIDEEP_FLASH_BASE (HIDEEP_PERIPHERAL_BASE + 0x01000000) #define HIDEEP_SYSCON_BASE (HIDEEP_PERIPHERAL_BASE + 0x02000000) #define HIDEEP_SYSCON_MOD_CON (HIDEEP_SYSCON_BASE + 0x0000) #define HIDEEP_SYSCON_SPC_CON (HIDEEP_SYSCON_BASE + 0x0004) #define HIDEEP_SYSCON_CLK_CON (HIDEEP_SYSCON_BASE + 0x0008) #define HIDEEP_SYSCON_CLK_ENA (HIDEEP_SYSCON_BASE + 0x000C) #define HIDEEP_SYSCON_RST_CON (HIDEEP_SYSCON_BASE + 0x0010) #define HIDEEP_SYSCON_WDT_CON (HIDEEP_SYSCON_BASE + 0x0014) #define HIDEEP_SYSCON_WDT_CNT (HIDEEP_SYSCON_BASE + 0x0018) #define HIDEEP_SYSCON_PWR_CON (HIDEEP_SYSCON_BASE + 0x0020) #define HIDEEP_SYSCON_PGM_ID (HIDEEP_SYSCON_BASE + 0x00F4) #define HIDEEP_FLASH_CON (HIDEEP_FLASH_BASE + 0x0000) #define HIDEEP_FLASH_STA (HIDEEP_FLASH_BASE + 0x0004) #define HIDEEP_FLASH_CFG (HIDEEP_FLASH_BASE + 0x0008) #define HIDEEP_FLASH_TIM (HIDEEP_FLASH_BASE + 0x000C) #define HIDEEP_FLASH_CACHE_CFG (HIDEEP_FLASH_BASE + 0x0010) #define HIDEEP_FLASH_PIO_SIG (HIDEEP_FLASH_BASE + 0x400000) #define HIDEEP_ESI_TX_INVALID (HIDEEP_ESI_BASE + 0x0008) #define HIDEEP_PERASE 0x00040000 #define HIDEEP_WRONLY 0x00100000 #define HIDEEP_NVM_MASK_OFS 0x0000000C #define HIDEEP_NVM_DEFAULT_PAGE 0 #define HIDEEP_NVM_SFR_WPAGE 1 #define HIDEEP_NVM_SFR_RPAGE 2 #define HIDEEP_PIO_SIG 0x00400000 #define HIDEEP_PROT_MODE 0x03400000 #define HIDEEP_NVM_PAGE_SIZE 128 #define HIDEEP_DWZ_INFO 0x000002C0 struct hideep_event { __le16 x; __le16 y; __le16 z; u8 w; u8 flag; u8 type; u8 index; }; struct dwz_info { __be32 code_start; u8 code_crc[12]; __be32 c_code_start; __be16 gen_ver; __be16 c_code_len; __be32 vr_start; __be16 rsv0; __be16 vr_len; __be32 ft_start; __be16 vr_version; __be16 ft_len; __be16 core_ver; __be16 boot_ver; __be16 release_ver; __be16 custom_ver; u8 factory_id; u8 panel_type; u8 model_name[6]; __be16 extra_option; __be16 product_code; __be16 vendor_id; __be16 product_id; }; struct pgm_packet { struct { u8 unused[3]; u8 len; __be32 addr; } header; __be32 payload[HIDEEP_NVM_PAGE_SIZE / sizeof(__be32)]; }; #define HIDEEP_XFER_BUF_SIZE sizeof(struct pgm_packet) struct hideep_ts { struct i2c_client *client; struct input_dev *input_dev; struct regmap *reg; struct touchscreen_properties prop; struct gpio_desc *reset_gpio; struct regulator *vcc_vdd; struct regulator *vcc_vid; struct mutex dev_mutex; u32 tch_count; u32 lpm_count; /* * Data buffer to read packet from the device (contacts and key * states). We align it on double-word boundary to keep word-sized * fields in contact data and double-word-sized fields in program * packet aligned. */ u8 xfer_buf[HIDEEP_XFER_BUF_SIZE] __aligned(4); int key_num; u32 key_codes[HIDEEP_KEY_MAX]; struct dwz_info dwz_info; unsigned int fw_size; u32 nvm_mask; }; static int hideep_pgm_w_mem(struct hideep_ts *ts, u32 addr, const __be32 *data, size_t count) { struct pgm_packet *packet = (void *)ts->xfer_buf; size_t len = count * sizeof(*data); struct i2c_msg msg = { .addr = ts->client->addr, .len = len + sizeof(packet->header.len) + sizeof(packet->header.addr), .buf = &packet->header.len, }; int ret; if (len > HIDEEP_NVM_PAGE_SIZE) return -EINVAL; packet->header.len = 0x80 | (count - 1); packet->header.addr = cpu_to_be32(addr); memcpy(packet->payload, data, len); ret = i2c_transfer(ts->client->adapter, &msg, 1); if (ret != 1) return ret < 0 ? ret : -EIO; return 0; } static int hideep_pgm_r_mem(struct hideep_ts *ts, u32 addr, __be32 *data, size_t count) { struct pgm_packet *packet = (void *)ts->xfer_buf; size_t len = count * sizeof(*data); struct i2c_msg msg[] = { { .addr = ts->client->addr, .len = sizeof(packet->header.len) + sizeof(packet->header.addr), .buf = &packet->header.len, }, { .addr = ts->client->addr, .flags = I2C_M_RD, .len = len, .buf = (u8 *)data, }, }; int ret; if (len > HIDEEP_NVM_PAGE_SIZE) return -EINVAL; packet->header.len = count - 1; packet->header.addr = cpu_to_be32(addr); ret = i2c_transfer(ts->client->adapter, msg, ARRAY_SIZE(msg)); if (ret != ARRAY_SIZE(msg)) return ret < 0 ? ret : -EIO; return 0; } static int hideep_pgm_r_reg(struct hideep_ts *ts, u32 addr, u32 *val) { __be32 data; int error; error = hideep_pgm_r_mem(ts, addr, &data, 1); if (error) { dev_err(&ts->client->dev, "read of register %#08x failed: %d\n", addr, error); return error; } *val = be32_to_cpu(data); return 0; } static int hideep_pgm_w_reg(struct hideep_ts *ts, u32 addr, u32 val) { __be32 data = cpu_to_be32(val); int error; error = hideep_pgm_w_mem(ts, addr, &data, 1); if (error) { dev_err(&ts->client->dev, "write to register %#08x (%#08x) failed: %d\n", addr, val, error); return error; } return 0; } #define SW_RESET_IN_PGM(clk) \ { \ __be32 data = cpu_to_be32(0x01); \ hideep_pgm_w_reg(ts, HIDEEP_SYSCON_WDT_CNT, (clk)); \ hideep_pgm_w_reg(ts, HIDEEP_SYSCON_WDT_CON, 0x03); \ /* \ * The first write may already cause a reset, use a raw \ * write for the second write to avoid error logging. \ */ \ hideep_pgm_w_mem(ts, HIDEEP_SYSCON_WDT_CON, &data, 1); \ } #define SET_FLASH_PIO(ce) \ hideep_pgm_w_reg(ts, HIDEEP_FLASH_CON, \ 0x01 | ((ce) << 1)) #define SET_PIO_SIG(x, y) \ hideep_pgm_w_reg(ts, HIDEEP_FLASH_PIO_SIG + (x), (y)) #define SET_FLASH_HWCONTROL() \ hideep_pgm_w_reg(ts, HIDEEP_FLASH_CON, 0x00) #define NVM_W_SFR(x, y) \ { \ SET_FLASH_PIO(1); \ SET_PIO_SIG(x, y); \ SET_FLASH_PIO(0); \ } static void hideep_pgm_set(struct hideep_ts *ts) { hideep_pgm_w_reg(ts, HIDEEP_SYSCON_WDT_CON, 0x00); hideep_pgm_w_reg(ts, HIDEEP_SYSCON_SPC_CON, 0x00); hideep_pgm_w_reg(ts, HIDEEP_SYSCON_CLK_ENA, 0xFF); hideep_pgm_w_reg(ts, HIDEEP_SYSCON_CLK_CON, 0x01); hideep_pgm_w_reg(ts, HIDEEP_SYSCON_PWR_CON, 0x01); hideep_pgm_w_reg(ts, HIDEEP_FLASH_TIM, 0x03); hideep_pgm_w_reg(ts, HIDEEP_FLASH_CACHE_CFG, 0x00); } static int hideep_pgm_get_pattern(struct hideep_ts *ts, u32 *pattern) { u16 p1 = 0xAF39; u16 p2 = 0xDF9D; int error; error = regmap_bulk_write(ts->reg, p1, &p2, 1); if (error) { dev_err(&ts->client->dev, "%s: regmap_bulk_write() failed with %d\n", __func__, error); return error; } usleep_range(1000, 1100); /* flush invalid Tx load register */ error = hideep_pgm_w_reg(ts, HIDEEP_ESI_TX_INVALID, 0x01); if (error) return error; error = hideep_pgm_r_reg(ts, HIDEEP_SYSCON_PGM_ID, pattern); if (error) return error; return 0; } static int hideep_enter_pgm(struct hideep_ts *ts) { int retry_count = 10; u32 pattern; int error; while (retry_count--) { error = hideep_pgm_get_pattern(ts, &pattern); if (error) { dev_err(&ts->client->dev, "hideep_pgm_get_pattern failed: %d\n", error); } else if (pattern != 0x39AF9DDF) { dev_err(&ts->client->dev, "%s: bad pattern: %#08x\n", __func__, pattern); } else { dev_dbg(&ts->client->dev, "found magic code"); hideep_pgm_set(ts); usleep_range(1000, 1100); return 0; } } dev_err(&ts->client->dev, "failed to enter pgm mode\n"); SW_RESET_IN_PGM(1000); return -EIO; } static int hideep_nvm_unlock(struct hideep_ts *ts) { u32 unmask_code; int error; hideep_pgm_w_reg(ts, HIDEEP_FLASH_CFG, HIDEEP_NVM_SFR_RPAGE); error = hideep_pgm_r_reg(ts, 0x0000000C, &unmask_code); hideep_pgm_w_reg(ts, HIDEEP_FLASH_CFG, HIDEEP_NVM_DEFAULT_PAGE); if (error) return error; /* make it unprotected code */ unmask_code &= ~HIDEEP_PROT_MODE; /* compare unmask code */ if (unmask_code != ts->nvm_mask) dev_warn(&ts->client->dev, "read mask code different %#08x vs %#08x", unmask_code, ts->nvm_mask); hideep_pgm_w_reg(ts, HIDEEP_FLASH_CFG, HIDEEP_NVM_SFR_WPAGE); SET_FLASH_PIO(0); NVM_W_SFR(HIDEEP_NVM_MASK_OFS, ts->nvm_mask); SET_FLASH_HWCONTROL(); hideep_pgm_w_reg(ts, HIDEEP_FLASH_CFG, HIDEEP_NVM_DEFAULT_PAGE); return 0; } static int hideep_check_status(struct hideep_ts *ts) { int time_out = 100; int status; int error; while (time_out--) { error = hideep_pgm_r_reg(ts, HIDEEP_FLASH_STA, &status); if (!error && status) return 0; usleep_range(1000, 1100); } return -ETIMEDOUT; } static int hideep_program_page(struct hideep_ts *ts, u32 addr, const __be32 *ucode, size_t xfer_count) { u32 val; int error; error = hideep_check_status(ts); if (error) return -EBUSY; addr &= ~(HIDEEP_NVM_PAGE_SIZE - 1); SET_FLASH_PIO(0); SET_FLASH_PIO(1); /* erase page */ SET_PIO_SIG(HIDEEP_PERASE | addr, 0xFFFFFFFF); SET_FLASH_PIO(0); error = hideep_check_status(ts); if (error) return -EBUSY; /* write page */ SET_FLASH_PIO(1); val = be32_to_cpu(ucode[0]); SET_PIO_SIG(HIDEEP_WRONLY | addr, val); hideep_pgm_w_mem(ts, HIDEEP_FLASH_PIO_SIG | HIDEEP_WRONLY, ucode, xfer_count); val = be32_to_cpu(ucode[xfer_count - 1]); SET_PIO_SIG(124, val); SET_FLASH_PIO(0); usleep_range(1000, 1100); error = hideep_check_status(ts); if (error) return -EBUSY; SET_FLASH_HWCONTROL(); return 0; } static int hideep_program_nvm(struct hideep_ts *ts, const __be32 *ucode, size_t ucode_len) { struct pgm_packet *packet_r = (void *)ts->xfer_buf; __be32 *current_ucode = packet_r->payload; size_t xfer_len; size_t xfer_count; u32 addr = 0; int error; error = hideep_nvm_unlock(ts); if (error) return error; while (ucode_len > 0) { xfer_len = min_t(size_t, ucode_len, HIDEEP_NVM_PAGE_SIZE); xfer_count = xfer_len / sizeof(*ucode); error = hideep_pgm_r_mem(ts, 0x00000000 + addr, current_ucode, xfer_count); if (error) { dev_err(&ts->client->dev, "%s: failed to read page at offset %#08x: %d\n", __func__, addr, error); return error; } /* See if the page needs updating */ if (memcmp(ucode, current_ucode, xfer_len)) { error = hideep_program_page(ts, addr, ucode, xfer_count); if (error) { dev_err(&ts->client->dev, "%s: iwrite failure @%#08x: %d\n", __func__, addr, error); return error; } usleep_range(1000, 1100); } ucode += xfer_count; addr += xfer_len; ucode_len -= xfer_len; } return 0; } static int hideep_verify_nvm(struct hideep_ts *ts, const __be32 *ucode, size_t ucode_len) { struct pgm_packet *packet_r = (void *)ts->xfer_buf; __be32 *current_ucode = packet_r->payload; size_t xfer_len; size_t xfer_count; u32 addr = 0; int i; int error; while (ucode_len > 0) { xfer_len = min_t(size_t, ucode_len, HIDEEP_NVM_PAGE_SIZE); xfer_count = xfer_len / sizeof(*ucode); error = hideep_pgm_r_mem(ts, 0x00000000 + addr, current_ucode, xfer_count); if (error) { dev_err(&ts->client->dev, "%s: failed to read page at offset %#08x: %d\n", __func__, addr, error); return error; } if (memcmp(ucode, current_ucode, xfer_len)) { const u8 *ucode_bytes = (const u8 *)ucode; const u8 *current_bytes = (const u8 *)current_ucode; for (i = 0; i < xfer_len; i++) if (ucode_bytes[i] != current_bytes[i]) dev_err(&ts->client->dev, "%s: mismatch @%#08x: (%#02x vs %#02x)\n", __func__, addr + i, ucode_bytes[i], current_bytes[i]); return -EIO; } ucode += xfer_count; addr += xfer_len; ucode_len -= xfer_len; } return 0; } static int hideep_load_dwz(struct hideep_ts *ts) { u16 product_code; int error; error = hideep_enter_pgm(ts); if (error) return error; msleep(50); error = hideep_pgm_r_mem(ts, HIDEEP_DWZ_INFO, (void *)&ts->dwz_info, sizeof(ts->dwz_info) / sizeof(__be32)); SW_RESET_IN_PGM(10); msleep(50); if (error) { dev_err(&ts->client->dev, "failed to fetch DWZ data: %d\n", error); return error; } product_code = be16_to_cpu(ts->dwz_info.product_code); switch (product_code & 0xF0) { case 0x40: dev_dbg(&ts->client->dev, "used crimson IC"); ts->fw_size = 1024 * 48; ts->nvm_mask = 0x00310000; break; case 0x60: dev_dbg(&ts->client->dev, "used lime IC"); ts->fw_size = 1024 * 64; ts->nvm_mask = 0x0030027B; break; default: dev_err(&ts->client->dev, "product code is wrong: %#04x", product_code); return -EINVAL; } dev_dbg(&ts->client->dev, "firmware release version: %#04x", be16_to_cpu(ts->dwz_info.release_ver)); return 0; } static int hideep_flash_firmware(struct hideep_ts *ts, const __be32 *ucode, size_t ucode_len) { int retry_cnt = 3; int error; while (retry_cnt--) { error = hideep_program_nvm(ts, ucode, ucode_len); if (!error) { error = hideep_verify_nvm(ts, ucode, ucode_len); if (!error) return 0; } } return error; } static int hideep_update_firmware(struct hideep_ts *ts, const __be32 *ucode, size_t ucode_len) { int error, error2; dev_dbg(&ts->client->dev, "starting firmware update"); /* enter program mode */ error = hideep_enter_pgm(ts); if (error) return error; error = hideep_flash_firmware(ts, ucode, ucode_len); if (error) dev_err(&ts->client->dev, "firmware update failed: %d\n", error); else dev_dbg(&ts->client->dev, "firmware updated successfully\n"); SW_RESET_IN_PGM(1000); error2 = hideep_load_dwz(ts); if (error2) dev_err(&ts->client->dev, "failed to load dwz after firmware update: %d\n", error2); return error ?: error2; } static int hideep_power_on(struct hideep_ts *ts) { int error = 0; error = regulator_enable(ts->vcc_vdd); if (error) dev_err(&ts->client->dev, "failed to enable 'vdd' regulator: %d", error); usleep_range(999, 1000); error = regulator_enable(ts->vcc_vid); if (error) dev_err(&ts->client->dev, "failed to enable 'vcc_vid' regulator: %d", error); msleep(30); if (ts->reset_gpio) { gpiod_set_value_cansleep(ts->reset_gpio, 0); } else { error = regmap_write(ts->reg, HIDEEP_RESET_CMD, 0x01); if (error) dev_err(&ts->client->dev, "failed to send 'reset' command: %d\n", error); } msleep(50); return error; } static void hideep_power_off(void *data) { struct hideep_ts *ts = data; if (ts->reset_gpio) gpiod_set_value(ts->reset_gpio, 1); regulator_disable(ts->vcc_vid); regulator_disable(ts->vcc_vdd); } #define __GET_MT_TOOL_TYPE(type) ((type) == 0x01 ? MT_TOOL_FINGER : MT_TOOL_PEN) static void hideep_report_slot(struct input_dev *input, const struct hideep_event *event) { input_mt_slot(input, event->index & 0x0f); input_mt_report_slot_state(input, __GET_MT_TOOL_TYPE(event->type), !(event->flag & HIDEEP_MT_RELEASED)); if (!(event->flag & HIDEEP_MT_RELEASED)) { input_report_abs(input, ABS_MT_POSITION_X, le16_to_cpup(&event->x)); input_report_abs(input, ABS_MT_POSITION_Y, le16_to_cpup(&event->y)); input_report_abs(input, ABS_MT_PRESSURE, le16_to_cpup(&event->z)); input_report_abs(input, ABS_MT_TOUCH_MAJOR, event->w); } } static void hideep_parse_and_report(struct hideep_ts *ts) { const struct hideep_event *events = (void *)&ts->xfer_buf[HIDEEP_TOUCH_EVENT_INDEX]; const u8 *keys = &ts->xfer_buf[HIDEEP_KEY_EVENT_INDEX]; int touch_count = ts->xfer_buf[0]; int key_count = ts->xfer_buf[1] & 0x0f; int lpm_count = ts->xfer_buf[1] & 0xf0; int i; /* get touch event count */ dev_dbg(&ts->client->dev, "mt = %d, key = %d, lpm = %02x", touch_count, key_count, lpm_count); touch_count = min(touch_count, HIDEEP_MT_MAX); for (i = 0; i < touch_count; i++) hideep_report_slot(ts->input_dev, events + i); key_count = min(key_count, HIDEEP_KEY_MAX); for (i = 0; i < key_count; i++) { u8 key_data = keys[i * 2]; input_report_key(ts->input_dev, ts->key_codes[key_data & HIDEEP_KEY_IDX_MASK], key_data & HIDEEP_KEY_PRESSED_MASK); } input_mt_sync_frame(ts->input_dev); input_sync(ts->input_dev); } static irqreturn_t hideep_irq(int irq, void *handle) { struct hideep_ts *ts = handle; int error; BUILD_BUG_ON(HIDEEP_MAX_EVENT > HIDEEP_XFER_BUF_SIZE); error = regmap_bulk_read(ts->reg, HIDEEP_EVENT_ADDR, ts->xfer_buf, HIDEEP_MAX_EVENT / 2); if (error) { dev_err(&ts->client->dev, "failed to read events: %d\n", error); goto out; } hideep_parse_and_report(ts); out: return IRQ_HANDLED; } static int hideep_get_axis_info(struct hideep_ts *ts) { __le16 val[2]; int error; error = regmap_bulk_read(ts->reg, 0x28, val, ARRAY_SIZE(val)); if (error) return error; ts->prop.max_x = le16_to_cpup(val); ts->prop.max_y = le16_to_cpup(val + 1); dev_dbg(&ts->client->dev, "X: %d, Y: %d", ts->prop.max_x, ts->prop.max_y); return 0; } static int hideep_init_input(struct hideep_ts *ts) { struct device *dev = &ts->client->dev; int i; int error; ts->input_dev = devm_input_allocate_device(dev); if (!ts->input_dev) { dev_err(dev, "failed to allocate input device\n"); return -ENOMEM; } ts->input_dev->name = HIDEEP_TS_NAME; ts->input_dev->id.bustype = BUS_I2C; input_set_drvdata(ts->input_dev, ts); 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_PRESSURE, 0, 65535, 0, 0); input_set_abs_params(ts->input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); input_set_abs_params(ts->input_dev, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); touchscreen_parse_properties(ts->input_dev, true, &ts->prop); if (ts->prop.max_x == 0 || ts->prop.max_y == 0) { error = hideep_get_axis_info(ts); if (error) return error; } error = input_mt_init_slots(ts->input_dev, HIDEEP_MT_MAX, INPUT_MT_DIRECT); if (error) return error; ts->key_num = device_property_count_u32(dev, "linux,keycodes"); if (ts->key_num > HIDEEP_KEY_MAX) { dev_err(dev, "too many keys defined: %d\n", ts->key_num); return -EINVAL; } if (ts->key_num <= 0) { dev_dbg(dev, "missing or malformed 'linux,keycodes' property\n"); } else { error = device_property_read_u32_array(dev, "linux,keycodes", ts->key_codes, ts->key_num); if (error) { dev_dbg(dev, "failed to read keymap: %d", error); return error; } if (ts->key_num) { ts->input_dev->keycode = ts->key_codes; ts->input_dev->keycodesize = sizeof(ts->key_codes[0]); ts->input_dev->keycodemax = ts->key_num; for (i = 0; i < ts->key_num; i++) input_set_capability(ts->input_dev, EV_KEY, ts->key_codes[i]); } } error = input_register_device(ts->input_dev); if (error) { dev_err(dev, "failed to register input device: %d", error); return error; } return 0; } static ssize_t hideep_update_fw(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct hideep_ts *ts = i2c_get_clientdata(client); const struct firmware *fw_entry; char *fw_name; int mode; int error; error = kstrtoint(buf, 0, &mode); if (error) return error; fw_name = kasprintf(GFP_KERNEL, "hideep_ts_%04x.bin", be16_to_cpu(ts->dwz_info.product_id)); if (!fw_name) return -ENOMEM; error = request_firmware(&fw_entry, fw_name, dev); if (error) { dev_err(dev, "failed to request firmware %s: %d", fw_name, error); goto out_free_fw_name; } if (fw_entry->size % sizeof(__be32)) { dev_err(dev, "invalid firmware size %zu\n", fw_entry->size); error = -EINVAL; goto out_release_fw; } if (fw_entry->size > ts->fw_size) { dev_err(dev, "fw size (%zu) is too big (memory size %d)\n", fw_entry->size, ts->fw_size); error = -EFBIG; goto out_release_fw; } mutex_lock(&ts->dev_mutex); disable_irq(client->irq); error = hideep_update_firmware(ts, (const __be32 *)fw_entry->data, fw_entry->size); enable_irq(client->irq); mutex_unlock(&ts->dev_mutex); out_release_fw: release_firmware(fw_entry); out_free_fw_name: kfree(fw_name); return error ?: count; } static ssize_t hideep_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct hideep_ts *ts = i2c_get_clientdata(client); ssize_t len; mutex_lock(&ts->dev_mutex); len = scnprintf(buf, PAGE_SIZE, "%04x\n", be16_to_cpu(ts->dwz_info.release_ver)); mutex_unlock(&ts->dev_mutex); return len; } static ssize_t hideep_product_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct hideep_ts *ts = i2c_get_clientdata(client); ssize_t len; mutex_lock(&ts->dev_mutex); len = scnprintf(buf, PAGE_SIZE, "%04x\n", be16_to_cpu(ts->dwz_info.product_id)); mutex_unlock(&ts->dev_mutex); return len; } static DEVICE_ATTR(version, 0664, hideep_fw_version_show, NULL); static DEVICE_ATTR(product_id, 0664, hideep_product_id_show, NULL); static DEVICE_ATTR(update_fw, 0664, NULL, hideep_update_fw); static struct attribute *hideep_ts_sysfs_entries[] = { &dev_attr_version.attr, &dev_attr_product_id.attr, &dev_attr_update_fw.attr, NULL, }; static const struct attribute_group hideep_ts_attr_group = { .attrs = hideep_ts_sysfs_entries, }; static void hideep_set_work_mode(struct hideep_ts *ts) { /* * Reset touch report format to the native HiDeep 20 protocol if requested. * This is necessary to make touchscreens which come up in I2C-HID mode * work with this driver. * * Note this is a kernel internal device-property set by x86 platform code, * this MUST not be used in devicetree files without first adding it to * the DT bindings. */ if (device_property_read_bool(&ts->client->dev, "hideep,force-native-protocol")) regmap_write(ts->reg, HIDEEP_WORK_MODE, 0x00); } static int hideep_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct hideep_ts *ts = i2c_get_clientdata(client); disable_irq(client->irq); hideep_power_off(ts); return 0; } static int hideep_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct hideep_ts *ts = i2c_get_clientdata(client); int error; error = hideep_power_on(ts); if (error) { dev_err(&client->dev, "power on failed"); return error; } hideep_set_work_mode(ts); enable_irq(client->irq); return 0; } static DEFINE_SIMPLE_DEV_PM_OPS(hideep_pm_ops, hideep_suspend, hideep_resume); static const struct regmap_config hideep_regmap_config = { .reg_bits = 16, .reg_format_endian = REGMAP_ENDIAN_LITTLE, .val_bits = 16, .val_format_endian = REGMAP_ENDIAN_LITTLE, .max_register = 0xffff, }; static int hideep_probe(struct i2c_client *client) { struct hideep_ts *ts; int error; /* check i2c bus */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "check i2c device error"); return -ENODEV; } if (client->irq <= 0) { dev_err(&client->dev, "missing irq: %d\n", client->irq); return -EINVAL; } ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL); if (!ts) return -ENOMEM; ts->client = client; i2c_set_clientdata(client, ts); mutex_init(&ts->dev_mutex); ts->reg = devm_regmap_init_i2c(client, &hideep_regmap_config); if (IS_ERR(ts->reg)) { error = PTR_ERR(ts->reg); dev_err(&client->dev, "failed to initialize regmap: %d\n", error); return error; } ts->vcc_vdd = devm_regulator_get(&client->dev, "vdd"); if (IS_ERR(ts->vcc_vdd)) return PTR_ERR(ts->vcc_vdd); ts->vcc_vid = devm_regulator_get(&client->dev, "vid"); if (IS_ERR(ts->vcc_vid)) return PTR_ERR(ts->vcc_vid); ts->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ts->reset_gpio)) return PTR_ERR(ts->reset_gpio); error = hideep_power_on(ts); if (error) { dev_err(&client->dev, "power on failed: %d\n", error); return error; } error = devm_add_action_or_reset(&client->dev, hideep_power_off, ts); if (error) return error; error = hideep_load_dwz(ts); if (error) { dev_err(&client->dev, "failed to load dwz: %d", error); return error; } hideep_set_work_mode(ts); error = hideep_init_input(ts); if (error) return error; error = devm_request_threaded_irq(&client->dev, client->irq, NULL, hideep_irq, IRQF_ONESHOT, client->name, ts); if (error) { dev_err(&client->dev, "failed to request irq %d: %d\n", client->irq, error); return error; } error = devm_device_add_group(&client->dev, &hideep_ts_attr_group); if (error) { dev_err(&client->dev, "failed to add sysfs attributes: %d\n", error); return error; } return 0; } static const struct i2c_device_id hideep_i2c_id[] = { { HIDEEP_I2C_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, hideep_i2c_id); #ifdef CONFIG_ACPI static const struct acpi_device_id hideep_acpi_id[] = { { "HIDP0001", 0 }, { } }; MODULE_DEVICE_TABLE(acpi, hideep_acpi_id); #endif #ifdef CONFIG_OF static const struct of_device_id hideep_match_table[] = { { .compatible = "hideep,hideep-ts" }, { } }; MODULE_DEVICE_TABLE(of, hideep_match_table); #endif static struct i2c_driver hideep_driver = { .driver = { .name = HIDEEP_I2C_NAME, .of_match_table = of_match_ptr(hideep_match_table), .acpi_match_table = ACPI_PTR(hideep_acpi_id), .pm = pm_sleep_ptr(&hideep_pm_ops), }, .id_table = hideep_i2c_id, .probe = hideep_probe, }; module_i2c_driver(hideep_driver); MODULE_DESCRIPTION("Driver for HiDeep Touchscreen Controller"); MODULE_AUTHOR("[email protected]"); MODULE_LICENSE("GPL v2");
linux-master
drivers/input/touchscreen/hideep.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Hynitron cstxxx Touchscreen * * Copyright (c) 2022 Chris Morgan <[email protected]> * * This code is based on hynitron_core.c authored by Hynitron. * Note that no datasheet was available, so much of these registers * are undocumented. This is essentially a cleaned-up version of the * vendor driver with support removed for hardware I cannot test and * device-specific functions replated with generic functions wherever * possible. */ #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/mod_devicetable.h> #include <linux/module.h> #include <linux/property.h> #include <asm/unaligned.h> /* Per chip data */ struct hynitron_ts_chip_data { unsigned int max_touch_num; u32 ic_chkcode; int (*firmware_info)(struct i2c_client *client); int (*bootloader_enter)(struct i2c_client *client); int (*init_input)(struct i2c_client *client); void (*report_touch)(struct i2c_client *client); }; /* Data generic to all (supported and non-supported) controllers. */ struct hynitron_ts_data { const struct hynitron_ts_chip_data *chip; struct i2c_client *client; struct input_dev *input_dev; struct touchscreen_properties prop; struct gpio_desc *reset_gpio; }; /* * Since I have no datasheet, these values are guessed and/or assumed * based on observation and testing. */ #define CST3XX_FIRMWARE_INFO_START_CMD 0x01d1 #define CST3XX_FIRMWARE_INFO_END_CMD 0x09d1 #define CST3XX_FIRMWARE_CHK_CODE_REG 0xfcd1 #define CST3XX_FIRMWARE_VERSION_REG 0x08d2 #define CST3XX_FIRMWARE_VER_INVALID_VAL 0xa5a5a5a5 #define CST3XX_BOOTLDR_PROG_CMD 0xaa01a0 #define CST3XX_BOOTLDR_PROG_CHK_REG 0x02a0 #define CST3XX_BOOTLDR_CHK_VAL 0xac #define CST3XX_TOUCH_DATA_PART_REG 0x00d0 #define CST3XX_TOUCH_DATA_FULL_REG 0x07d0 #define CST3XX_TOUCH_DATA_CHK_VAL 0xab #define CST3XX_TOUCH_DATA_TOUCH_VAL 0x03 #define CST3XX_TOUCH_DATA_STOP_CMD 0xab00d0 #define CST3XX_TOUCH_COUNT_MASK GENMASK(6, 0) /* * Hard coded reset delay value of 20ms not IC dependent in * vendor driver. */ static void hyn_reset_proc(struct i2c_client *client, int delay) { struct hynitron_ts_data *ts_data = i2c_get_clientdata(client); gpiod_set_value_cansleep(ts_data->reset_gpio, 1); msleep(20); gpiod_set_value_cansleep(ts_data->reset_gpio, 0); if (delay) fsleep(delay * 1000); } static irqreturn_t hyn_interrupt_handler(int irq, void *dev_id) { struct i2c_client *client = dev_id; struct hynitron_ts_data *ts_data = i2c_get_clientdata(client); ts_data->chip->report_touch(client); return IRQ_HANDLED; } /* * The vendor driver would retry twice before failing to read or write * to the i2c device. */ static int cst3xx_i2c_write(struct i2c_client *client, unsigned char *buf, int len) { int ret; int retries = 0; while (retries < 2) { ret = i2c_master_send(client, buf, len); if (ret == len) return 0; if (ret <= 0) retries++; else break; } return ret < 0 ? ret : -EIO; } static int cst3xx_i2c_read_register(struct i2c_client *client, u16 reg, u8 *val, u16 len) { __le16 buf = cpu_to_le16(reg); struct i2c_msg msgs[] = { { .addr = client->addr, .flags = 0, .len = 2, .buf = (u8 *)&buf, }, { .addr = client->addr, .flags = I2C_M_RD, .len = len, .buf = val, } }; int err; int ret; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret == ARRAY_SIZE(msgs)) return 0; err = ret < 0 ? ret : -EIO; dev_err(&client->dev, "Error reading %d bytes from 0x%04x: %d (%d)\n", len, reg, err, ret); return err; } static int cst3xx_firmware_info(struct i2c_client *client) { struct hynitron_ts_data *ts_data = i2c_get_clientdata(client); int err; u32 tmp; unsigned char buf[4]; /* * Tests suggest this command needed to read firmware regs. */ put_unaligned_le16(CST3XX_FIRMWARE_INFO_START_CMD, buf); err = cst3xx_i2c_write(client, buf, 2); if (err) return err; usleep_range(10000, 11000); /* * Read register for check-code to determine if device detected * correctly. */ err = cst3xx_i2c_read_register(client, CST3XX_FIRMWARE_CHK_CODE_REG, buf, 4); if (err) return err; tmp = get_unaligned_le32(buf); if ((tmp & 0xffff0000) != ts_data->chip->ic_chkcode) { dev_err(&client->dev, "%s ic mismatch, chkcode is %u\n", __func__, tmp); return -ENODEV; } usleep_range(10000, 11000); /* Read firmware version and test if firmware missing. */ err = cst3xx_i2c_read_register(client, CST3XX_FIRMWARE_VERSION_REG, buf, 4); if (err) return err; tmp = get_unaligned_le32(buf); if (tmp == CST3XX_FIRMWARE_VER_INVALID_VAL) { dev_err(&client->dev, "Device firmware missing\n"); return -ENODEV; } /* * Tests suggest cmd required to exit reading firmware regs. */ put_unaligned_le16(CST3XX_FIRMWARE_INFO_END_CMD, buf); err = cst3xx_i2c_write(client, buf, 2); if (err) return err; usleep_range(5000, 6000); return 0; } static int cst3xx_bootloader_enter(struct i2c_client *client) { int err; u8 retry; u32 tmp = 0; unsigned char buf[3]; for (retry = 0; retry < 5; retry++) { hyn_reset_proc(client, (7 + retry)); /* set cmd to enter program mode */ put_unaligned_le24(CST3XX_BOOTLDR_PROG_CMD, buf); err = cst3xx_i2c_write(client, buf, 3); if (err) continue; usleep_range(2000, 2500); /* check whether in program mode */ err = cst3xx_i2c_read_register(client, CST3XX_BOOTLDR_PROG_CHK_REG, buf, 1); if (err) continue; tmp = get_unaligned(buf); if (tmp == CST3XX_BOOTLDR_CHK_VAL) break; } if (tmp != CST3XX_BOOTLDR_CHK_VAL) { dev_err(&client->dev, "%s unable to enter bootloader mode\n", __func__); return -ENODEV; } hyn_reset_proc(client, 40); return 0; } static void cst3xx_report_contact(struct hynitron_ts_data *ts_data, u8 id, unsigned int x, unsigned int y, u8 w) { input_mt_slot(ts_data->input_dev, id); input_mt_report_slot_state(ts_data->input_dev, MT_TOOL_FINGER, 1); touchscreen_report_pos(ts_data->input_dev, &ts_data->prop, x, y, true); input_report_abs(ts_data->input_dev, ABS_MT_TOUCH_MAJOR, w); } static int cst3xx_finish_touch_read(struct i2c_client *client) { unsigned char buf[3]; int err; put_unaligned_le24(CST3XX_TOUCH_DATA_STOP_CMD, buf); err = cst3xx_i2c_write(client, buf, 3); if (err) { dev_err(&client->dev, "send read touch info ending failed: %d\n", err); return err; } return 0; } /* * Handle events from IRQ. Note that for cst3xx it appears that IRQ * fires continuously while touched, otherwise once every 1500ms * when not touched (assume touchscreen waking up periodically). * Note buffer is sized for 5 fingers, if more needed buffer must * be increased. The buffer contains 5 bytes for each touch point, * a touch count byte, a check byte, and then a second check byte after * all other touch points. * * For example 1 touch would look like this: * touch1[5]:touch_count[1]:chk_byte[1] * * 3 touches would look like this: * touch1[5]:touch_count[1]:chk_byte[1]:touch2[5]:touch3[5]:chk_byte[1] */ static void cst3xx_touch_report(struct i2c_client *client) { struct hynitron_ts_data *ts_data = i2c_get_clientdata(client); u8 buf[28]; u8 finger_id, sw, w; unsigned int x, y; unsigned int touch_cnt, end_byte; unsigned int idx = 0; unsigned int i; int err; /* Read and validate the first bits of input data. */ err = cst3xx_i2c_read_register(client, CST3XX_TOUCH_DATA_PART_REG, buf, 28); if (err || buf[6] != CST3XX_TOUCH_DATA_CHK_VAL || buf[0] == CST3XX_TOUCH_DATA_CHK_VAL) { dev_err(&client->dev, "cst3xx touch read failure\n"); return; } /* Report to the device we're done reading the touch data. */ err = cst3xx_finish_touch_read(client); if (err) return; touch_cnt = buf[5] & CST3XX_TOUCH_COUNT_MASK; /* * Check the check bit of the last touch slot. The check bit is * always present after touch point 1 for valid data, and then * appears as the last byte after all other touch data. */ if (touch_cnt > 1) { end_byte = touch_cnt * 5 + 2; if (buf[end_byte] != CST3XX_TOUCH_DATA_CHK_VAL) { dev_err(&client->dev, "cst3xx touch read failure\n"); return; } } /* Parse through the buffer to capture touch data. */ for (i = 0; i < touch_cnt; i++) { x = ((buf[idx + 1] << 4) | ((buf[idx + 3] >> 4) & 0x0f)); y = ((buf[idx + 2] << 4) | (buf[idx + 3] & 0x0f)); w = (buf[idx + 4] >> 3); sw = (buf[idx] & 0x0f) >> 1; finger_id = (buf[idx] >> 4) & 0x0f; /* Sanity check we don't have more fingers than we expect */ if (ts_data->chip->max_touch_num < finger_id) { dev_err(&client->dev, "cst3xx touch read failure\n"); break; } /* sw value of 0 means no touch, 0x03 means touch */ if (sw == CST3XX_TOUCH_DATA_TOUCH_VAL) cst3xx_report_contact(ts_data, finger_id, x, y, w); idx += 5; /* Skip the 2 bytes between point 1 and point 2 */ if (i == 0) idx += 2; } input_mt_sync_frame(ts_data->input_dev); input_sync(ts_data->input_dev); } static int cst3xx_input_dev_int(struct i2c_client *client) { struct hynitron_ts_data *ts_data = i2c_get_clientdata(client); int err; ts_data->input_dev = devm_input_allocate_device(&client->dev); if (!ts_data->input_dev) { dev_err(&client->dev, "Failed to allocate input device\n"); return -ENOMEM; } ts_data->input_dev->name = "Hynitron cst3xx Touchscreen"; ts_data->input_dev->phys = "input/ts"; ts_data->input_dev->id.bustype = BUS_I2C; input_set_drvdata(ts_data->input_dev, ts_data); input_set_capability(ts_data->input_dev, EV_ABS, ABS_MT_POSITION_X); input_set_capability(ts_data->input_dev, EV_ABS, ABS_MT_POSITION_Y); input_set_abs_params(ts_data->input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); touchscreen_parse_properties(ts_data->input_dev, true, &ts_data->prop); if (!ts_data->prop.max_x || !ts_data->prop.max_y) { dev_err(&client->dev, "Invalid x/y (%d, %d), using defaults\n", ts_data->prop.max_x, ts_data->prop.max_y); ts_data->prop.max_x = 1152; ts_data->prop.max_y = 1920; input_abs_set_max(ts_data->input_dev, ABS_MT_POSITION_X, ts_data->prop.max_x); input_abs_set_max(ts_data->input_dev, ABS_MT_POSITION_Y, ts_data->prop.max_y); } err = input_mt_init_slots(ts_data->input_dev, ts_data->chip->max_touch_num, INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED); if (err) { dev_err(&client->dev, "Failed to initialize input slots: %d\n", err); return err; } err = input_register_device(ts_data->input_dev); if (err) { dev_err(&client->dev, "Input device registration failed: %d\n", err); return err; } return 0; } static int hyn_probe(struct i2c_client *client) { struct hynitron_ts_data *ts_data; int err; ts_data = devm_kzalloc(&client->dev, sizeof(*ts_data), GFP_KERNEL); if (!ts_data) return -ENOMEM; ts_data->client = client; i2c_set_clientdata(client, ts_data); ts_data->chip = device_get_match_data(&client->dev); if (!ts_data->chip) return -EINVAL; ts_data->reset_gpio = devm_gpiod_get(&client->dev, "reset", GPIOD_OUT_LOW); err = PTR_ERR_OR_ZERO(ts_data->reset_gpio); if (err) { dev_err(&client->dev, "request reset gpio failed: %d\n", err); return err; } hyn_reset_proc(client, 60); err = ts_data->chip->bootloader_enter(client); if (err < 0) return err; err = ts_data->chip->init_input(client); if (err < 0) return err; err = ts_data->chip->firmware_info(client); if (err < 0) return err; err = devm_request_threaded_irq(&client->dev, client->irq, NULL, hyn_interrupt_handler, IRQF_ONESHOT, "Hynitron Touch Int", client); if (err) { dev_err(&client->dev, "failed to request IRQ: %d\n", err); return err; } return 0; } static const struct hynitron_ts_chip_data cst3xx_data = { .max_touch_num = 5, .ic_chkcode = 0xcaca0000, .firmware_info = &cst3xx_firmware_info, .bootloader_enter = &cst3xx_bootloader_enter, .init_input = &cst3xx_input_dev_int, .report_touch = &cst3xx_touch_report, }; static const struct i2c_device_id hyn_tpd_id[] = { { .name = "hynitron_ts", 0 }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(i2c, hyn_tpd_id); static const struct of_device_id hyn_dt_match[] = { { .compatible = "hynitron,cst340", .data = &cst3xx_data }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, hyn_dt_match); static struct i2c_driver hynitron_i2c_driver = { .driver = { .name = "Hynitron-TS", .of_match_table = hyn_dt_match, .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, .id_table = hyn_tpd_id, .probe = hyn_probe, }; module_i2c_driver(hynitron_i2c_driver); MODULE_AUTHOR("Chris Morgan"); MODULE_DESCRIPTION("Hynitron Touchscreen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/hynitron_cstxxx.c
// SPDX-License-Identifier: GPL-2.0 /* * Driver for EETI eGalax Multiple Touch Controller * * Copyright (C) 2011 Freescale Semiconductor, Inc. * * based on max11801_ts.c */ /* EETI eGalax serial touch screen controller is a I2C based multiple * touch screen controller, it supports 5 point multiple touch. */ /* TODO: - auto idle mode support */ #include <linux/err.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/irq.h> #include <linux/gpio/consumer.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/bitops.h> #include <linux/input/mt.h> /* * Mouse Mode: some panel may configure the controller to mouse mode, * which can only report one point at a given time. * This driver will ignore events in this mode. */ #define REPORT_MODE_MOUSE 0x1 /* * Vendor Mode: this mode is used to transfer some vendor specific * messages. * This driver will ignore events in this mode. */ #define REPORT_MODE_VENDOR 0x3 /* Multiple Touch Mode */ #define REPORT_MODE_MTTOUCH 0x4 #define MAX_SUPPORT_POINTS 5 #define EVENT_VALID_OFFSET 7 #define EVENT_VALID_MASK (0x1 << EVENT_VALID_OFFSET) #define EVENT_ID_OFFSET 2 #define EVENT_ID_MASK (0xf << EVENT_ID_OFFSET) #define EVENT_IN_RANGE (0x1 << 1) #define EVENT_DOWN_UP (0X1 << 0) #define MAX_I2C_DATA_LEN 10 #define EGALAX_MAX_X 32760 #define EGALAX_MAX_Y 32760 #define EGALAX_MAX_TRIES 100 struct egalax_ts { struct i2c_client *client; struct input_dev *input_dev; }; static irqreturn_t egalax_ts_interrupt(int irq, void *dev_id) { struct egalax_ts *ts = dev_id; struct input_dev *input_dev = ts->input_dev; struct i2c_client *client = ts->client; u8 buf[MAX_I2C_DATA_LEN]; int id, ret, x, y, z; int tries = 0; bool down, valid; u8 state; do { ret = i2c_master_recv(client, buf, MAX_I2C_DATA_LEN); } while (ret == -EAGAIN && tries++ < EGALAX_MAX_TRIES); if (ret < 0) return IRQ_HANDLED; if (buf[0] != REPORT_MODE_MTTOUCH) { /* ignore mouse events and vendor events */ return IRQ_HANDLED; } state = buf[1]; x = (buf[3] << 8) | buf[2]; y = (buf[5] << 8) | buf[4]; z = (buf[7] << 8) | buf[6]; valid = state & EVENT_VALID_MASK; id = (state & EVENT_ID_MASK) >> EVENT_ID_OFFSET; down = state & EVENT_DOWN_UP; if (!valid || id > MAX_SUPPORT_POINTS) { dev_dbg(&client->dev, "point invalid\n"); return IRQ_HANDLED; } input_mt_slot(input_dev, id); input_mt_report_slot_state(input_dev, MT_TOOL_FINGER, down); dev_dbg(&client->dev, "%s id:%d x:%d y:%d z:%d", down ? "down" : "up", id, x, y, z); if (down) { input_report_abs(input_dev, ABS_MT_POSITION_X, x); input_report_abs(input_dev, ABS_MT_POSITION_Y, y); input_report_abs(input_dev, ABS_MT_PRESSURE, z); } input_mt_report_pointer_emulation(input_dev, true); input_sync(input_dev); return IRQ_HANDLED; } /* wake up controller by an falling edge of interrupt gpio. */ static int egalax_wake_up_device(struct i2c_client *client) { struct gpio_desc *gpio; int ret; /* wake up controller via an falling edge on IRQ gpio. */ gpio = gpiod_get(&client->dev, "wakeup", GPIOD_OUT_HIGH); ret = PTR_ERR_OR_ZERO(gpio); if (ret) { if (ret != -EPROBE_DEFER) dev_err(&client->dev, "failed to request wakeup gpio, cannot wake up controller: %d\n", ret); return ret; } /* release the line */ gpiod_set_value_cansleep(gpio, 0); /* controller should be woken up, return irq. */ gpiod_direction_input(gpio); gpiod_put(gpio); return 0; } static int egalax_firmware_version(struct i2c_client *client) { static const u8 cmd[MAX_I2C_DATA_LEN] = { 0x03, 0x03, 0xa, 0x01, 0x41 }; int ret; ret = i2c_master_send(client, cmd, MAX_I2C_DATA_LEN); if (ret < 0) return ret; return 0; } static int egalax_ts_probe(struct i2c_client *client) { struct egalax_ts *ts; struct input_dev *input_dev; int error; ts = devm_kzalloc(&client->dev, sizeof(struct egalax_ts), GFP_KERNEL); if (!ts) { dev_err(&client->dev, "Failed to allocate memory\n"); return -ENOMEM; } input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) { dev_err(&client->dev, "Failed to allocate memory\n"); return -ENOMEM; } ts->client = client; ts->input_dev = input_dev; /* controller may be in sleep, wake it up. */ error = egalax_wake_up_device(client); if (error) return error; error = egalax_firmware_version(client); if (error < 0) { dev_err(&client->dev, "Failed to read firmware version\n"); return error; } input_dev->name = "EETI eGalax Touch Screen"; input_dev->id.bustype = BUS_I2C; __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, EGALAX_MAX_X, 0, 0); input_set_abs_params(input_dev, ABS_Y, 0, EGALAX_MAX_Y, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, EGALAX_MAX_X, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, EGALAX_MAX_Y, 0, 0); input_mt_init_slots(input_dev, MAX_SUPPORT_POINTS, 0); error = devm_request_threaded_irq(&client->dev, client->irq, NULL, egalax_ts_interrupt, IRQF_ONESHOT, "egalax_ts", ts); if (error < 0) { dev_err(&client->dev, "Failed to register interrupt\n"); return error; } error = input_register_device(ts->input_dev); if (error) return error; return 0; } static const struct i2c_device_id egalax_ts_id[] = { { "egalax_ts", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, egalax_ts_id); static int egalax_ts_suspend(struct device *dev) { static const u8 suspend_cmd[MAX_I2C_DATA_LEN] = { 0x3, 0x6, 0xa, 0x3, 0x36, 0x3f, 0x2, 0, 0, 0 }; struct i2c_client *client = to_i2c_client(dev); int ret; if (device_may_wakeup(dev)) return enable_irq_wake(client->irq); ret = i2c_master_send(client, suspend_cmd, MAX_I2C_DATA_LEN); return ret > 0 ? 0 : ret; } static int egalax_ts_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); if (device_may_wakeup(dev)) return disable_irq_wake(client->irq); return egalax_wake_up_device(client); } static DEFINE_SIMPLE_DEV_PM_OPS(egalax_ts_pm_ops, egalax_ts_suspend, egalax_ts_resume); static const struct of_device_id egalax_ts_dt_ids[] = { { .compatible = "eeti,egalax_ts" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, egalax_ts_dt_ids); static struct i2c_driver egalax_ts_driver = { .driver = { .name = "egalax_ts", .pm = pm_sleep_ptr(&egalax_ts_pm_ops), .of_match_table = egalax_ts_dt_ids, }, .id_table = egalax_ts_id, .probe = egalax_ts_probe, }; module_i2c_driver(egalax_ts_driver); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_DESCRIPTION("Touchscreen driver for EETI eGalax touch controller"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/egalax_ts.c
// SPDX-License-Identifier: GPL-2.0-only /* * Core Source for: * Cypress TrueTouch(TM) Standard Product (TTSP) touchscreen drivers. * 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 <linux/delay.h> #include <linux/input.h> #include <linux/input/mt.h> #include <linux/input/touchscreen.h> #include <linux/gpio.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/property.h> #include <linux/gpio/consumer.h> #include <linux/regulator/consumer.h> #include "cyttsp_core.h" /* Bootloader number of command keys */ #define CY_NUM_BL_KEYS 8 /* helpers */ #define GET_NUM_TOUCHES(x) ((x) & 0x0F) #define IS_LARGE_AREA(x) (((x) & 0x10) >> 4) #define IS_BAD_PKT(x) ((x) & 0x20) #define IS_VALID_APP(x) ((x) & 0x01) #define IS_OPERATIONAL_ERR(x) ((x) & 0x3F) #define GET_HSTMODE(reg) (((reg) & 0x70) >> 4) #define GET_BOOTLOADERMODE(reg) (((reg) & 0x10) >> 4) #define CY_REG_BASE 0x00 #define CY_REG_ACT_DIST 0x1E #define CY_REG_ACT_INTRVL 0x1D #define CY_REG_TCH_TMOUT (CY_REG_ACT_INTRVL + 1) #define CY_REG_LP_INTRVL (CY_REG_TCH_TMOUT + 1) #define CY_MAXZ 255 #define CY_DELAY_DFLT 20 /* ms */ #define CY_DELAY_MAX 500 /* Active distance in pixels for a gesture to be reported */ #define CY_ACT_DIST_DFLT 0xF8 /* pixels */ #define CY_ACT_DIST_MASK 0x0F /* Active Power state scanning/processing refresh interval */ #define CY_ACT_INTRVL_DFLT 0x00 /* ms */ /* Low Power state scanning/processing refresh interval */ #define CY_LP_INTRVL_DFLT 0x0A /* ms */ /* touch timeout for the Active power */ #define CY_TCH_TMOUT_DFLT 0xFF /* ms */ #define CY_HNDSHK_BIT 0x80 /* device mode bits */ #define CY_OPERATE_MODE 0x00 #define CY_SYSINFO_MODE 0x10 /* power mode select bits */ #define CY_SOFT_RESET_MODE 0x01 /* return to Bootloader mode */ #define CY_DEEP_SLEEP_MODE 0x02 #define CY_LOW_POWER_MODE 0x04 /* Slots management */ #define CY_MAX_FINGER 4 #define CY_MAX_ID 16 static const u8 bl_command[] = { 0x00, /* file offset */ 0xFF, /* command */ 0xA5, /* exit bootloader command */ 0, 1, 2, 3, 4, 5, 6, 7 /* default keys */ }; static int ttsp_read_block_data(struct cyttsp *ts, u8 command, u8 length, void *buf) { int error; int tries; for (tries = 0; tries < CY_NUM_RETRY; tries++) { error = ts->bus_ops->read(ts->dev, ts->xfer_buf, command, length, buf); if (!error) return 0; msleep(CY_DELAY_DFLT); } return -EIO; } static int ttsp_write_block_data(struct cyttsp *ts, u8 command, u8 length, void *buf) { int error; int tries; for (tries = 0; tries < CY_NUM_RETRY; tries++) { error = ts->bus_ops->write(ts->dev, ts->xfer_buf, command, length, buf); if (!error) return 0; msleep(CY_DELAY_DFLT); } return -EIO; } static int ttsp_send_command(struct cyttsp *ts, u8 cmd) { return ttsp_write_block_data(ts, CY_REG_BASE, sizeof(cmd), &cmd); } static int cyttsp_handshake(struct cyttsp *ts) { if (ts->use_hndshk) return ttsp_send_command(ts, ts->xy_data.hst_mode ^ CY_HNDSHK_BIT); return 0; } static int cyttsp_load_bl_regs(struct cyttsp *ts) { memset(&ts->bl_data, 0, sizeof(ts->bl_data)); ts->bl_data.bl_status = 0x10; return ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->bl_data), &ts->bl_data); } static int cyttsp_exit_bl_mode(struct cyttsp *ts) { int error; u8 bl_cmd[sizeof(bl_command)]; memcpy(bl_cmd, bl_command, sizeof(bl_command)); if (ts->bl_keys) memcpy(&bl_cmd[sizeof(bl_command) - CY_NUM_BL_KEYS], ts->bl_keys, CY_NUM_BL_KEYS); error = ttsp_write_block_data(ts, CY_REG_BASE, sizeof(bl_cmd), bl_cmd); if (error) return error; /* wait for TTSP Device to complete the operation */ msleep(CY_DELAY_DFLT); error = cyttsp_load_bl_regs(ts); if (error) return error; if (GET_BOOTLOADERMODE(ts->bl_data.bl_status)) return -EIO; return 0; } static int cyttsp_set_operational_mode(struct cyttsp *ts) { int error; error = ttsp_send_command(ts, CY_OPERATE_MODE); if (error) return error; /* wait for TTSP Device to complete switch to Operational mode */ error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->xy_data), &ts->xy_data); if (error) return error; error = cyttsp_handshake(ts); if (error) return error; return ts->xy_data.act_dist == CY_ACT_DIST_DFLT ? -EIO : 0; } static int cyttsp_set_sysinfo_mode(struct cyttsp *ts) { int error; memset(&ts->sysinfo_data, 0, sizeof(ts->sysinfo_data)); /* switch to sysinfo mode */ error = ttsp_send_command(ts, CY_SYSINFO_MODE); if (error) return error; /* read sysinfo registers */ msleep(CY_DELAY_DFLT); error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->sysinfo_data), &ts->sysinfo_data); if (error) return error; error = cyttsp_handshake(ts); if (error) return error; if (!ts->sysinfo_data.tts_verh && !ts->sysinfo_data.tts_verl) return -EIO; return 0; } static int cyttsp_set_sysinfo_regs(struct cyttsp *ts) { int retval = 0; if (ts->act_intrvl != CY_ACT_INTRVL_DFLT || ts->tch_tmout != CY_TCH_TMOUT_DFLT || ts->lp_intrvl != CY_LP_INTRVL_DFLT) { u8 intrvl_ray[] = { ts->act_intrvl, ts->tch_tmout, ts->lp_intrvl }; /* set intrvl registers */ retval = ttsp_write_block_data(ts, CY_REG_ACT_INTRVL, sizeof(intrvl_ray), intrvl_ray); msleep(CY_DELAY_DFLT); } return retval; } static void cyttsp_hard_reset(struct cyttsp *ts) { if (ts->reset_gpio) { /* * According to the CY8CTMA340 datasheet page 21, the external * reset pulse width should be >= 1 ms. The datasheet does not * specify how long we have to wait after reset but a vendor * tree specifies 5 ms here. */ gpiod_set_value_cansleep(ts->reset_gpio, 1); usleep_range(1000, 2000); gpiod_set_value_cansleep(ts->reset_gpio, 0); usleep_range(5000, 6000); } } static int cyttsp_soft_reset(struct cyttsp *ts) { int retval; /* wait for interrupt to set ready completion */ reinit_completion(&ts->bl_ready); ts->state = CY_BL_STATE; enable_irq(ts->irq); retval = ttsp_send_command(ts, CY_SOFT_RESET_MODE); if (retval) { dev_err(ts->dev, "failed to send soft reset\n"); goto out; } if (!wait_for_completion_timeout(&ts->bl_ready, msecs_to_jiffies(CY_DELAY_DFLT * CY_DELAY_MAX))) { dev_err(ts->dev, "timeout waiting for soft reset\n"); retval = -EIO; } out: ts->state = CY_IDLE_STATE; disable_irq(ts->irq); return retval; } static int cyttsp_act_dist_setup(struct cyttsp *ts) { u8 act_dist_setup = ts->act_dist; /* Init gesture; active distance setup */ return ttsp_write_block_data(ts, CY_REG_ACT_DIST, sizeof(act_dist_setup), &act_dist_setup); } static void cyttsp_extract_track_ids(struct cyttsp_xydata *xy_data, int *ids) { ids[0] = xy_data->touch12_id >> 4; ids[1] = xy_data->touch12_id & 0xF; ids[2] = xy_data->touch34_id >> 4; ids[3] = xy_data->touch34_id & 0xF; } static const struct cyttsp_tch *cyttsp_get_tch(struct cyttsp_xydata *xy_data, int idx) { switch (idx) { case 0: return &xy_data->tch1; case 1: return &xy_data->tch2; case 2: return &xy_data->tch3; case 3: return &xy_data->tch4; default: return NULL; } } static void cyttsp_report_tchdata(struct cyttsp *ts) { struct cyttsp_xydata *xy_data = &ts->xy_data; struct input_dev *input = ts->input; int num_tch = GET_NUM_TOUCHES(xy_data->tt_stat); const struct cyttsp_tch *tch; int ids[CY_MAX_ID]; int i; DECLARE_BITMAP(used, CY_MAX_ID); if (IS_LARGE_AREA(xy_data->tt_stat) == 1) { /* terminate all active tracks */ num_tch = 0; dev_dbg(ts->dev, "%s: Large area detected\n", __func__); } else if (num_tch > CY_MAX_FINGER) { /* terminate all active tracks */ num_tch = 0; dev_dbg(ts->dev, "%s: Num touch error detected\n", __func__); } else if (IS_BAD_PKT(xy_data->tt_mode)) { /* terminate all active tracks */ num_tch = 0; dev_dbg(ts->dev, "%s: Invalid buffer detected\n", __func__); } cyttsp_extract_track_ids(xy_data, ids); bitmap_zero(used, CY_MAX_ID); for (i = 0; i < num_tch; i++) { tch = cyttsp_get_tch(xy_data, i); input_mt_slot(input, ids[i]); input_mt_report_slot_state(input, MT_TOOL_FINGER, true); input_report_abs(input, ABS_MT_POSITION_X, be16_to_cpu(tch->x)); input_report_abs(input, ABS_MT_POSITION_Y, be16_to_cpu(tch->y)); input_report_abs(input, ABS_MT_TOUCH_MAJOR, tch->z); __set_bit(ids[i], used); } for (i = 0; i < CY_MAX_ID; i++) { if (test_bit(i, used)) continue; input_mt_slot(input, i); input_mt_report_slot_inactive(input); } input_sync(input); } static irqreturn_t cyttsp_irq(int irq, void *handle) { struct cyttsp *ts = handle; int error; if (unlikely(ts->state == CY_BL_STATE)) { complete(&ts->bl_ready); goto out; } /* Get touch data from CYTTSP device */ error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(struct cyttsp_xydata), &ts->xy_data); if (error) goto out; /* provide flow control handshake */ error = cyttsp_handshake(ts); if (error) goto out; if (unlikely(ts->state == CY_IDLE_STATE)) goto out; if (GET_BOOTLOADERMODE(ts->xy_data.tt_mode)) { /* * TTSP device has reset back to bootloader mode. * Restore to operational mode. */ error = cyttsp_exit_bl_mode(ts); if (error) { dev_err(ts->dev, "Could not return to operational mode, err: %d\n", error); ts->state = CY_IDLE_STATE; } } else { cyttsp_report_tchdata(ts); } out: return IRQ_HANDLED; } static int cyttsp_power_on(struct cyttsp *ts) { int error; error = cyttsp_soft_reset(ts); if (error) return error; error = cyttsp_load_bl_regs(ts); if (error) return error; if (GET_BOOTLOADERMODE(ts->bl_data.bl_status) && IS_VALID_APP(ts->bl_data.bl_status)) { error = cyttsp_exit_bl_mode(ts); if (error) { dev_err(ts->dev, "failed to exit bootloader mode\n"); return error; } } if (GET_HSTMODE(ts->bl_data.bl_file) != CY_OPERATE_MODE || IS_OPERATIONAL_ERR(ts->bl_data.bl_status)) { return -ENODEV; } error = cyttsp_set_sysinfo_mode(ts); if (error) return error; error = cyttsp_set_sysinfo_regs(ts); if (error) return error; error = cyttsp_set_operational_mode(ts); if (error) return error; /* init active distance */ error = cyttsp_act_dist_setup(ts); if (error) return error; ts->state = CY_ACTIVE_STATE; return 0; } static int cyttsp_enable(struct cyttsp *ts) { int error; /* * The device firmware can wake on an I2C or SPI memory slave * address match. So just reading a register is sufficient to * wake up the device. The first read attempt will fail but it * will wake it up making the second read attempt successful. */ error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->xy_data), &ts->xy_data); if (error) return error; if (GET_HSTMODE(ts->xy_data.hst_mode)) return -EIO; enable_irq(ts->irq); return 0; } static int cyttsp_disable(struct cyttsp *ts) { int error; error = ttsp_send_command(ts, CY_LOW_POWER_MODE); if (error) return error; disable_irq(ts->irq); return 0; } static int cyttsp_suspend(struct device *dev) { struct cyttsp *ts = dev_get_drvdata(dev); int retval = 0; mutex_lock(&ts->input->mutex); if (input_device_enabled(ts->input)) { retval = cyttsp_disable(ts); if (retval == 0) ts->suspended = true; } mutex_unlock(&ts->input->mutex); return retval; } static int cyttsp_resume(struct device *dev) { struct cyttsp *ts = dev_get_drvdata(dev); mutex_lock(&ts->input->mutex); if (input_device_enabled(ts->input)) cyttsp_enable(ts); ts->suspended = false; mutex_unlock(&ts->input->mutex); return 0; } EXPORT_GPL_SIMPLE_DEV_PM_OPS(cyttsp_pm_ops, cyttsp_suspend, cyttsp_resume); static int cyttsp_open(struct input_dev *dev) { struct cyttsp *ts = input_get_drvdata(dev); int retval = 0; if (!ts->suspended) retval = cyttsp_enable(ts); return retval; } static void cyttsp_close(struct input_dev *dev) { struct cyttsp *ts = input_get_drvdata(dev); if (!ts->suspended) cyttsp_disable(ts); } static int cyttsp_parse_properties(struct cyttsp *ts) { struct device *dev = ts->dev; u32 dt_value; int ret; ts->bl_keys = devm_kzalloc(dev, CY_NUM_BL_KEYS, GFP_KERNEL); if (!ts->bl_keys) return -ENOMEM; /* Set some default values */ ts->use_hndshk = false; ts->act_dist = CY_ACT_DIST_DFLT; ts->act_intrvl = CY_ACT_INTRVL_DFLT; ts->tch_tmout = CY_TCH_TMOUT_DFLT; ts->lp_intrvl = CY_LP_INTRVL_DFLT; ret = device_property_read_u8_array(dev, "bootloader-key", ts->bl_keys, CY_NUM_BL_KEYS); if (ret) { dev_err(dev, "bootloader-key property could not be retrieved\n"); return ret; } ts->use_hndshk = device_property_present(dev, "use-handshake"); if (!device_property_read_u32(dev, "active-distance", &dt_value)) { if (dt_value > 15) { dev_err(dev, "active-distance (%u) must be [0-15]\n", dt_value); return -EINVAL; } ts->act_dist &= ~CY_ACT_DIST_MASK; ts->act_dist |= dt_value; } if (!device_property_read_u32(dev, "active-interval-ms", &dt_value)) { if (dt_value > 255) { dev_err(dev, "active-interval-ms (%u) must be [0-255]\n", dt_value); return -EINVAL; } ts->act_intrvl = dt_value; } if (!device_property_read_u32(dev, "lowpower-interval-ms", &dt_value)) { if (dt_value > 2550) { dev_err(dev, "lowpower-interval-ms (%u) must be [0-2550]\n", dt_value); return -EINVAL; } /* Register value is expressed in 0.01s / bit */ ts->lp_intrvl = dt_value / 10; } if (!device_property_read_u32(dev, "touch-timeout-ms", &dt_value)) { if (dt_value > 2550) { dev_err(dev, "touch-timeout-ms (%u) must be [0-2550]\n", dt_value); return -EINVAL; } /* Register value is expressed in 0.01s / bit */ ts->tch_tmout = dt_value / 10; } return 0; } static void cyttsp_disable_regulators(void *_ts) { struct cyttsp *ts = _ts; regulator_bulk_disable(ARRAY_SIZE(ts->regulators), ts->regulators); } struct cyttsp *cyttsp_probe(const struct cyttsp_bus_ops *bus_ops, struct device *dev, int irq, size_t xfer_buf_size) { struct cyttsp *ts; struct input_dev *input_dev; int error; ts = devm_kzalloc(dev, sizeof(*ts) + xfer_buf_size, GFP_KERNEL); if (!ts) return ERR_PTR(-ENOMEM); input_dev = devm_input_allocate_device(dev); if (!input_dev) return ERR_PTR(-ENOMEM); ts->dev = dev; ts->input = input_dev; ts->bus_ops = bus_ops; ts->irq = irq; /* * VCPIN is the analog voltage supply * VDD is the digital voltage supply */ ts->regulators[0].supply = "vcpin"; ts->regulators[1].supply = "vdd"; error = devm_regulator_bulk_get(dev, ARRAY_SIZE(ts->regulators), ts->regulators); if (error) { dev_err(dev, "Failed to get regulators: %d\n", error); return ERR_PTR(error); } error = regulator_bulk_enable(ARRAY_SIZE(ts->regulators), ts->regulators); if (error) { dev_err(dev, "Cannot enable regulators: %d\n", error); return ERR_PTR(error); } error = devm_add_action_or_reset(dev, cyttsp_disable_regulators, ts); if (error) { dev_err(dev, "failed to install chip disable handler\n"); return ERR_PTR(error); } 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, "Failed to request reset gpio, error %d\n", error); return ERR_PTR(error); } error = cyttsp_parse_properties(ts); if (error) return ERR_PTR(error); init_completion(&ts->bl_ready); input_dev->name = "Cypress TTSP TouchScreen"; input_dev->id.bustype = bus_ops->bustype; input_dev->dev.parent = ts->dev; input_dev->open = cyttsp_open; input_dev->close = cyttsp_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); /* One byte for width 0..255 so this is the limit */ input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0); touchscreen_parse_properties(input_dev, true, NULL); error = input_mt_init_slots(input_dev, CY_MAX_ID, INPUT_MT_DIRECT); if (error) { dev_err(dev, "Unable to init MT slots.\n"); return ERR_PTR(error); } error = devm_request_threaded_irq(dev, ts->irq, NULL, cyttsp_irq, IRQF_ONESHOT | IRQF_NO_AUTOEN, "cyttsp", ts); if (error) { dev_err(ts->dev, "failed to request IRQ %d, err: %d\n", ts->irq, error); return ERR_PTR(error); } cyttsp_hard_reset(ts); error = cyttsp_power_on(ts); if (error) return ERR_PTR(error); error = input_register_device(input_dev); if (error) { dev_err(ts->dev, "failed to register input device: %d\n", error); return ERR_PTR(error); } return ts; } EXPORT_SYMBOL_GPL(cyttsp_probe); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen driver core"); MODULE_AUTHOR("Cypress");
linux-master
drivers/input/touchscreen/cyttsp_core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * wm9705.c -- Codec driver for Wolfson WM9705 AC97 Codec. * * Copyright 2003, 2004, 2005, 2006, 2007 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 WM9705_VERSION "1.00" #define DEFAULT_PRESSURE 0xb0c0 /* * Module parameters */ /* * 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."); /* * Pen detect comparator threshold. * * 0 to Vmid in 15 steps, 0 = use zero power comparator with Vmid threshold * i.e. 1 = Vmid/15 threshold * 15 = Vmid/1 threshold * * Adjust this value if you are having problems with pen detect not * detecting any down events. */ static int pdd = 8; module_param(pdd, int, 0); MODULE_PARM_DESC(pdd, "Set pen detect comparator threshold"); /* * 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."); /* * 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 WM9705 */ static void wm9705_phy_init(struct wm97xx *wm) { u16 dig1 = 0, dig2 = WM97XX_RPR; /* * mute VIDEO and AUX as they share X and Y touchscreen * inputs on the WM9705 */ wm97xx_reg_write(wm, AC97_AUX, 0x8000); wm97xx_reg_write(wm, AC97_VIDEO, 0x8000); /* touchpanel pressure current*/ if (pil == 2) { dig2 |= WM9705_PIL; dev_dbg(wm->dev, "setting pressure measurement current to 400uA."); } else if (pil) dev_dbg(wm->dev, "setting pressure measurement current to 200uA."); if (!pil) pressure = 0; /* polling mode sample settling delay */ if (delay != 4) { if (delay < 0 || delay > 15) { dev_dbg(wm->dev, "supplied delay out of range."); delay = 4; } } dig1 &= 0xff0f; dig1 |= WM97XX_DELAY(delay); dev_dbg(wm->dev, "setting adc sample delay to %d u Secs.", delay_table[delay]); /* WM9705 pdd */ dig2 |= (pdd & 0x000f); dev_dbg(wm->dev, "setting pdd to Vmid/%d", 1 - (pdd & 0x000f)); /* mask */ dig2 |= ((mask & 0x3) << 4); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, dig1); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2); } static void wm9705_dig_enable(struct wm97xx *wm, int enable) { if (enable) { wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, wm->dig[2] | WM97XX_PRP_DET_DIG); wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER_RD); /* dummy read */ } else wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, wm->dig[2] & ~WM97XX_PRP_DET_DIG); } static void wm9705_aux_prepare(struct wm97xx *wm) { memcpy(wm->dig_save, wm->dig, sizeof(wm->dig)); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, 0); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, WM97XX_PRP_DET_DIG); } static void wm9705_dig_restore(struct wm97xx *wm) { wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, wm->dig_save[1]); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, wm->dig_save[2]); } static inline int is_pden(struct wm97xx *wm) { return wm->dig[2] & WM9705_PDEN; } /* * Read a sample from the WM9705 adc in polling mode. */ static int wm9705_poll_sample(struct wm97xx *wm, int adcsel, int *sample) { 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 */ if (wm->mach_ops && wm->mach_ops->pre_sample) wm->mach_ops->pre_sample(adcsel); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, (adcsel & WM97XX_ADCSEL_MASK) | WM97XX_POLL | WM97XX_DELAY(delay)); /* wait 3 AC97 time slots + delay for conversion */ poll_delay(delay); /* wait for POLL to go low */ while ((wm97xx_reg_read(wm, AC97_WM97XX_DIGITISER1) & WM97XX_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; } /* * Sample the WM9705 touchscreen in polling mode */ static int wm9705_poll_touch(struct wm97xx *wm, struct wm97xx_data *data) { int rc; rc = wm9705_poll_sample(wm, WM97XX_ADCSEL_X | WM97XX_PEN_DOWN, &data->x); if (rc != RC_VALID) return rc; rc = wm9705_poll_sample(wm, WM97XX_ADCSEL_Y | WM97XX_PEN_DOWN, &data->y); if (rc != RC_VALID) return rc; if (pil) { rc = wm9705_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 WM9705 continuous mode, i.e. touch data is streamed across * an AC97 slot */ static int wm9705_acc_enable(struct wm97xx *wm, int enable) { u16 dig1, dig2; int ret = 0; dig1 = wm->dig[1]; dig2 = wm->dig[2]; if (enable) { /* continuous mode */ if (wm->mach_ops->acc_startup && (ret = wm->mach_ops->acc_startup(wm)) < 0) return ret; dig1 &= ~(WM97XX_CM_RATE_MASK | WM97XX_ADCSEL_MASK | WM97XX_DELAY_MASK | WM97XX_SLT_MASK); dig1 |= WM97XX_CTC | WM97XX_COO | WM97XX_SLEN | WM97XX_DELAY(delay) | WM97XX_SLT(wm->acc_slot) | WM97XX_RATE(wm->acc_rate); if (pil) dig1 |= WM97XX_ADCSEL_PRES; dig2 |= WM9705_PDEN; } else { dig1 &= ~(WM97XX_CTC | WM97XX_COO | WM97XX_SLEN); dig2 &= ~WM9705_PDEN; if (wm->mach_ops->acc_shutdown) wm->mach_ops->acc_shutdown(wm); } wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER1, dig1); wm97xx_reg_write(wm, AC97_WM97XX_DIGITISER2, dig2); return ret; } struct wm97xx_codec_drv wm9705_codec = { .id = WM9705_ID2, .name = "wm9705", .poll_sample = wm9705_poll_sample, .poll_touch = wm9705_poll_touch, .acc_enable = wm9705_acc_enable, .phy_init = wm9705_phy_init, .dig_enable = wm9705_dig_enable, .dig_restore = wm9705_dig_restore, .aux_prepare = wm9705_aux_prepare, }; EXPORT_SYMBOL_GPL(wm9705_codec); /* Module information */ MODULE_AUTHOR("Liam Girdwood <[email protected]>"); MODULE_DESCRIPTION("WM9705 Touch Screen Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/input/touchscreen/wm9705.c